/** * admission.ts: atomic, multi-scope admission control before a paid call. * * WHY THIS EXISTS * ---------------- * Almost every AI-calling app needs the same guard: before the paid call, * count one admission against several caps at once (for example a global * daily cap and a per-user daily cap) and refuse the call if ANY of them is * full. The author's apps each hand-rolled it in SQL. The versions that held * up shared four properties, and this module encodes them as a contract: * * 1. Atomic and all-or-nothing. Every scope is checked and incremented in * one step owned by the store. A racy "count, then insert" lets * concurrent requests all pass the count (one app did exactly that, and * its insert was best-effort, so a failed write let calls through * uncounted). * 2. The store owns the clock. The window (UTC day or hour) is resolved by * the store, after it has taken its lock, so midnight contention cannot * borrow yesterday's allowance and app servers with skewed clocks agree. * 3. Fail closed. A store that throws, hangs or answers something * malformed means "do not make the paid call", never "assume allowed". * 4. Never refunded. The admission counts the ATTEMPT. A provider timeout * can still bill, so a failed or uncertain call keeps its slot, and this * module never retries an admission (a retry after a lost reply could * double count, and an "undo" after a lost reply could under count). * * The kit owns the validation and the fail-closed mapping. The atomic * increment lives in YOUR store (Postgres, D1, Redis); README.md has adapter * recipes, which the app owns and tests. `createInMemoryAdmissionStore` is a * single-process reference for unit tests only. */ /** One cap to count against. */ export interface AdmissionScope { /** * What is limited, for example `explain:global` or `explain:user:`. * Must be a non-blank string (not empty, not only whitespace or invisible * characters). Compared exactly: not trimmed, not Unicode-normalized. */ key: string; /** * Maximum admissions in the window, a safe integer >= 0. `0` always limits. * The store may apply a LOWER limit (a policy row in the database, or the * lowest limit seen this window), never a higher one. */ limit: number; } /** The counting window, always in UTC and always resolved by the store's clock. */ export type AdmissionWindow = 'utc-day' | 'utc-hour'; /** What the store receives: a validated, frozen copy of the caller's scopes. */ export interface AdmissionRequest { scopes: readonly AdmissionScope[]; window: AdmissionWindow; } /** What a store must answer. */ export type AdmissionDecision = { status: 'admitted'; windowId: string; } | { status: 'limited'; scopeKey: string; windowId: string; }; /** * Storage contract for {@link admitBeforeCall}. This is the safety boundary; * the kit has no counter of its own. * * `admit` MUST, atomically: resolve the current window from the store's own * clock AFTER taking its lock; if `used < limit` for EVERY scope in that * window, increment every scope by one and answer `admitted`; otherwise change * nothing and answer `limited` with the key of a scope that was full. It must * never decrement or refund. * * `windowId` is the window the store counted in, formatted `YYYY-MM-DD` for * `utc-day` and `YYYY-MM-DDTHH` (24-hour) for `utc-hour`, in UTC. Anything * else is treated as a malformed reply. * * Throw or reject when the outcome is unknown (a lost reply, a database * error). Do not retry inside the store after a write may have committed. */ export interface AdmissionStore { admit(request: AdmissionRequest): Promise; } /** Why an admission could not be confirmed. Every one of these means: do not make the call. */ export type AdmissionUnavailableReason = /** The request (or the store argument) was malformed: a programmer error. `cause` is a TypeError or RangeError naming the problem. */ 'invalid_request' /** The store threw or rejected. `cause` is what it threw. */ | 'store_error' /** The store did not answer within `timeoutMs`. It may still commit the admission later. */ | 'timeout' /** The store answered something that is not a valid decision for this request. */ | 'malformed_reply'; /** Result of {@link admitBeforeCall}. Only `admitted` allows the paid call. */ export type AdmitOutcome = { status: 'admitted'; windowId: string; } | { status: 'limited'; scopeKey: string; windowId: string; } | { status: 'unavailable'; reason: AdmissionUnavailableReason; cause?: unknown; }; /** Input to {@link admitBeforeCall}. */ export interface AdmitBeforeCallRequest { /** One or more scopes, with distinct keys. All must have room for the call to be admitted. */ scopes: readonly AdmissionScope[]; /** Defaults to `'utc-day'`. */ window?: AdmissionWindow; /** * How long to wait for the store, in milliseconds: a safe integer from 1 to * 2,147,483,647. Defaults to {@link DEFAULT_ADMISSION_TIMEOUT_MS}. Give the * store's own transport a shorter timeout than this. */ timeoutMs?: number; } /** Default wait for a store's answer, in milliseconds. */ export declare const DEFAULT_ADMISSION_TIMEOUT_MS = 5000; /** * Count one admission against every scope BEFORE a paid call. Never throws, * never rejects, never retries, never refunds. * * - Reads `request` once and validates that copy. A request that is not a * plain object, no scopes, a scope that is not a plain object, a blank or * non-string key, duplicate keys, a limit that is not a safe integer >= 0, * an unknown window, a bad `timeoutMs`, or a `store` without an `admit` * function returns `unavailable` with reason `invalid_request` and a * TypeError or RangeError in `cause`, without calling the store. (These are * programmer errors; they are returned instead of thrown so that a route * handler cannot turn them into an unguarded paid call.) * - Calls `store.admit` exactly once with a frozen copy of the validated * scopes, so neither the caller nor the store can change what the reply is * checked against. * - A throw or rejection is `store_error`; no answer within `timeoutMs` is * `timeout`. The deadline is measured from just before the store is called * (`performance.now()`), so a store that blocks the event loop and then * answers late is also `timeout`, even if it said `admitted`. That late * admission is discarded, fail closed, and the store may have counted it: * admission is never refunded. * - The reply is read once. It is `malformed_reply` unless it is exactly * `{ status: 'admitted', windowId }` or * `{ status: 'limited', scopeKey, windowId }` where `windowId` is a real * UTC date (`YYYY-MM-DD`) or hour (`YYYY-MM-DDTHH`) matching the requested * window, `scopeKey` is one of the requested keys, and, for `admitted`, * no requested scope has limit 0 (a store that admits past a zero limit is * not enforcing limits). * * Admission is not refunded on failure, by design: the paid call that follows * may fail or time out after the provider already billed it, so the slot stays * spent. Do not "give back" an admission after a failed call, and do not * retry `admitBeforeCall` for the same logical attempt after `timeout` or * `store_error`. * * @example * const outcome = await admitBeforeCall(store, { * scopes: [ * { key: 'explain:global', limit: 2_000 }, * { key: `explain:user:${userId}`, limit: 20 }, * ], * }); * const status = admissionHttpStatus(outcome, { perUserScopePrefixes: ['explain:user:'] }); * if (status !== null) return new Response('Try again later', { status }); * // ...only now make the paid call, with provider retries off. */ export declare function admitBeforeCall(store: AdmissionStore, request: AdmitBeforeCallRequest): Promise; /** Options for {@link admissionHttpStatus}. */ export interface AdmissionHttpStatusOptions { /** * Key prefixes that mark a scope as belonging to one user or client, for * example `['explain:user:', 'explain:ip:']`. A `limited` outcome on such a * scope maps to 429; on any other scope (a global or route cap) to 503. * Each prefix must be a non-blank string. */ perUserScopePrefixes?: readonly string[]; } /** * Map an {@link AdmitOutcome} to an HTTP status: * * | outcome | status | why | * | --- | --- | --- | * | `admitted` with a valid `windowId` | `null` | proceed with the call | * | `admitted` without one, or naming a `scopeKey` | `503` | malformed; fail closed | * | `limited` on a per-user scope | `429` | this caller used their allowance | * | `limited` on any other scope | `503` | shared capacity is exhausted; not the caller's fault | * | `unavailable` | `503` | the cap could not be confirmed, so the call is refused | * | anything else | `503` | not a valid outcome; fail closed | * * A scope is per-user when its key starts with one of * `opts.perUserScopePrefixes`. With no prefixes, every `limited` is 503. * * @throws TypeError or RangeError when `opts` is malformed (not a plain * object, prefixes not an array of non-blank strings). That is static * configuration, so it fails on the first call rather than mapping silently. */ export declare function admissionHttpStatus(outcome: AdmitOutcome, opts?: AdmissionHttpStatusOptions): 429 | 503 | null; /** Options for {@link createInMemoryAdmissionStore}. */ export interface InMemoryAdmissionStoreOptions { /** The store's clock. Defaults to `() => new Date()`. Inject one to test window rollover. */ now?: () => Date; } /** * A reference {@link AdmissionStore} that keeps counts in this process's * memory. **For unit tests only, not for production.** It is atomic within * one JavaScript process (each `admit` checks and increments synchronously, * with no `await` in between), but its counts are not shared across * processes, serverless instances or restarts, so it does NOT hold a cap * across instances. Use a database-backed store (see README.md) for that. * * Behavior, which a production store should match: * - Counts per window: `utc-day` and `utc-hour` keep separate counters. * - The window is resolved from `now()` once per call, inside the atomic step. * - All-or-nothing: if any scope has `used >= limit`, no count changes and the * first full scope (in request order) is reported. * - A scope's limit can only go down within a window: the effective limit is * the lowest limit seen for that key in the current window, recorded even * when the request is limited. * - Counters of past windows are dropped when the window changes, and the * window never moves backwards: if `now()` steps back into an earlier * window, counting continues in the newest window seen, so a spent window * is never reopened. (A database store whose own clock steps back would * count in the earlier window's row; the README recipes do not guard * against that.) * * It validates its input like {@link admitBeforeCall} and throws (rejects) on * malformed input or a `now()` that is not a valid Date. */ export declare function createInMemoryAdmissionStore(options?: InMemoryAdmissionStoreOptions): AdmissionStore;