WindowedCallBudget
The supplied CallBudget: an integer ledger of epoch-aligned fixed rate windows with lane floors, first-come-first-served waits, pauses from server signals and a hard window that survives a restart through a BudgetStore. Built with the factory WindowedCallBudget(windows) { }; Stable Core, usable without any opt-in.
Windows and the guard. Each RateWindow's fixed periods start at multiples of its period since the Unix epoch (UTC); a call is charged to the period the wall clock is in, and, within Builder.boundaryGuard of a boundary, to the adjacent period too, so a provider whose clock differs from this one by up to the guard never sees a period over its limit.
Lanes and the floor. Builder.laneShares converts a lane's share into reserved units per window (ceil(share * limit), at least 1): a held-back floor the other lanes can never use, never lent. A lane may use the whole window itself; a call whose cost exceeds limit - (the other lanes' reserves) can never fit and is refused with CostExceedsLimit. The default reserves 20 % for Lane.Interactive; a window of limit 1 wants laneShares = emptyMap(), or every other lane is refused there.
First come first served and the fail-fast cap. A call that fits now is granted at once when its lane has no waiter; one that would wait is planned at the earliest slot that fits, never before the lane's last waiter, and waits in its own coroutine (the budget owns no scope, thread or timer). A wait longer than maxWait is refused at once with BudgetExhausted carrying the wait the call would have had; a lane with Builder.maxQueued waiters refuses with QueueFull.
Refunds and re-plans. A cancelled wait is refunded and the waiters behind it are planned again, each from the ledger as it then stands; release() refunds a grant and re-plans everyone. A waiter whose new wait exceeds its cap fails at once.
Signals and the pause. complete(signals) with a window reading raises the local count to what the server counted (never lowers it); a throttled signal pauses every lane until the longest of Retry-After, every exhausted reading's resetIn, or, with no timing hint, the next boundary of the exhausted windows plus the guard, each capped by Builder.maxPause. A later hint never shortens a pause.
Hard windows and persistence. A hard window refuses until its boundary once full (raising BudgetEvent.HardStop once per period) and is saved write-ahead to the Builder.store in blocks of Builder.persistAhead grants, under the budget's lock and before the grant; a restart restores the stored count at the first acquire, utilisation() or flush() (a stale period is dropped, the current one merged additively, a stamp further ahead than Builder.maxRestoreSkew has its stamp and pause ignored but its counts kept). A store that returns a failure or throws an Exception is logged and ignored: grants continue from the in-process count and the next attempt waits Builder.storeRetryInterval; no save is made before a restore has succeeded. Grants made while the store is failing are unsaved: a crash then loses them, and the restart under-counts the window by up to as many. While saves succeed, a crash never under-counts the grants made, save for a grant made after three saves that each outlasted their period, which proceeds unsaved; it over-counts by at most persistAhead - 1 plus any units written ahead and then given back (a release(), or a call cancelled or closed after its save), which stay in the stored count until flush(). A count a server reading or a backward clock step raised is saved with the next grant or flush(), not when it is raised. An Error the store throws is not a store failure: it propagates to the caller of the member that made the store call (possibly as a stack-trace-recovery copy whose cause is the original), raises no BudgetEvent.StoreFailed and grants nothing; the lock is released. Call flush before close for the exact final write; close() itself writes nothing. A snapshot store is last-writer-wins and does not count one provider across several processes.
Time. The Builder.wallClock decides where in the provider's calendar now is (indices, boundaries, the guard, the snapshot's stamp); the Builder.timeSource measures every wait and duration. A backward step of the wall clock across a boundary copies the counts of the periods it left into the current one (never under-counting a window that guards a bill); a forward jump is trusted, and a waiter whose period the jump left behind is re-planned from the new reading. The known limit: a clock set forward by mistake and left uncorrected can under-count a hard window.
Closing. close is non-suspending, idempotent, thread-safe and never throws; every waiting call and every later acquire returns Result.failure(HttpFailure.Closed("budget")) as a value. After it, flush, utilisation and the permits' complete and release keep working.
Thread safety. Every member may be called from any thread and coroutine; all state is under one coroutine Mutex, which is held across a store call for at most Builder.storeTimeout (a blocking store cannot be interrupted: see BudgetStore). Events are delivered to the Builder.observer after the lock is released, on the thread of the call that produced them, so an observer may call back into the budget.
Logging (com.spartanlabs.webtools.http.WindowedCallBudget): INFO on creation (settings numbers only), on close() and on a restore; WARN on a pause, a hard stop and a store failure (the cause's class name only); DEBUG per refusal and per reconciliation; nothing per grant. Never a header value, a body, a credential, a URL or a store exception's message: the budget receives RateSignals, never a response.
The builder's properties and defaults: laneShares (Interactive 0.2), boundaryGuard (1 s), maxPause (24 h), maxQueued (1,000 per lane), persistAhead (10), maxRestoreSkew (5 min), storeTimeout (2 s), storeRetryInterval (30 s), timeSource (TimeSource.Monotonic), wallClock (WallClock.System), store (InMemoryBudgetStore), observer (BudgetObserver.None). The caller closes the budget; the budget never closes its store or observer.
Types
Collects the properties of a WindowedCallBudget. Not thread-safe; use it only inside the factory's lambda. Stable Core.