/** * internal/idempotency/idempotency — dedupe-by-key + last-result cache as pure state + ops. * * Same shape as `../../work-queue`'s `ops.ts` and `../../resilience/rate-limit`: * a state type plus pure transition functions. Host-agnostic by construction — * no `Date.now()`, no timers, no I/O. The caller injects the clock (`nowMs`) * and wires the result into its own reducer / interpret. This keeps the store * inside TEA's invariant 2 (transitions are pure: same inputs → same outputs, * no `Date.now`) so a consumer can fold it through `update` and exercise it * with `replay` / the pbt fold without a fake clock. * * Every op returns a NEW store value and never mutates its input (invariant 1 — * state is a value, not a place). `seen` / `recall` are read-shaped predicates; * `remember` / `evictExpired` return a new store. * * The use case: a webhook receiver, a retried queue message, or a repeated user * action arrives carrying an idempotency key. `seen(store, key, now)` answers * "did I already process this?"; `recall(store, key, now)` returns the cached * result so the duplicate request gets the SAME response the original produced * rather than re-running the side effect. `remember(store, key, value, now)` * records the key + its result after the first run. * * Two eviction policies keep the store bounded, both injected at `initStore`: * * - **`ttlMs`** — an entry expires `ttlMs` after the `atMs` it was remembered * at. `seen` / `recall` treat an expired entry as absent; `evictExpired` * (and every `remember`) physically drops it. Without a TTL, entries live * until evicted by capacity. The cutoff is half-open: an entry exactly * `ttlMs` old is expired (`age >= ttlMs` drops it), matching `rate-limit`'s * window edge — a key remembered at `t` no longer counts at `t + ttlMs`. * - **`capacity`** — at most `capacity` entries are retained. When a * `remember` would push the count past `capacity` (after expiry eviction), * the OLDEST entries by insertion `order` are dropped until the count fits. * Without a capacity, the store grows unbounded (TTL alone bounds it). * * `order` is the insertion-order index that capacity eviction reads — the keys * oldest-first. It is the store's own LRU-by-insertion ledger, kept in lockstep * with `entries` so `entries` never needs to be sorted to find the oldest. * * **Overwrite semantics** (decided + pinned by tests): re-`remember`ing an * existing key is an UPDATE, not a no-op. It (1) overwrites `value`, (2) * refreshes `atMs` to the new `nowMs` — so the TTL clock restarts and a * frequently-seen key never expires — and (3) moves the key to the NEWEST * position in `order` — so capacity eviction treats a re-remembered key as * fresh, not as a stale candidate for eviction. This makes `remember` behave * like "touch": a key actively being re-seen is kept alive on both the TTL and * capacity axes. * * Internal since #47 — not published on any subpath; reached from inside the * package as `internal/idempotency/idempotency`. Same one-shape-per-package rule * as `work-queue`, `rate-limit`, and `do`. */ /** * A cached entry: the result `value` the original request produced and the * clock reading `atMs` it was remembered at. `atMs` is the TTL anchor — expiry * is measured from here, and a re-`remember` refreshes it. Both fields are * plain data so the whole store is trivially JSON-serializable into a * consumer's `Store`. */ interface IdempotencyEntry { readonly value: V; readonly atMs: number; } /** * The dedupe store: a map of `key → entry`, an insertion-`order` ledger * (oldest-first) that capacity eviction reads, and the two optional bounds. * * `entries` and `order` are kept in lockstep — every key in `order` has an * entry and vice versa. `capacity` / `ttlMs` are carried on the store (not * passed per-op) so a single value fully describes the policy; a consumer * persists the store and rehydrates the same bounds without re-deriving them. */ interface IdempotencyStore { readonly entries: Readonly>>; readonly order: readonly string[]; readonly capacity?: number; readonly ttlMs?: number; } /** * Create an empty store. `capacity` and `ttlMs` are both optional — omit both * for an unbounded cache, supply either or both to bound by count, age, or * both. Stored on the returned value so every later op reads the policy off * the store rather than from a re-passed argument. */ declare function initStore(opts?: { capacity?: number; ttlMs?: number; }): IdempotencyStore; /** * True iff `key` is present AND not expired at `nowMs`. This is the dedupe * predicate: a webhook / retried message / repeated action whose key returns * `true` has already been processed and should be short-circuited (paired with * `recall` to return the original result). PURE — reads only, never mutates. */ declare function seen(store: IdempotencyStore, key: string, nowMs: number): boolean; /** * The cached `value` for `key` if present and unexpired at `nowMs`, else * `undefined`. Use after `seen` returns `true` to replay the original result to * a duplicate request. An expired entry reads as absent (returns `undefined`) * even though it is physically still in `entries` until the next `remember` / * `evictExpired` drops it. PURE — reads only, never mutates. */ declare function recall(store: IdempotencyStore, key: string, nowMs: number): V | undefined; /** * Drop every entry expired at `nowMs` (older than `ttlMs`). Returns a NEW store * with the survivors; `order` is rebuilt to drop the same keys, preserving the * relative insertion order of the survivors. A no-TTL store returns an * equivalent store (nothing ages out). PURE — the input store is never mutated. */ declare function evictExpired(store: IdempotencyStore, nowMs: number): IdempotencyStore; /** * Record `key → value` at `nowMs`, then enforce both bounds. PURE — returns a * new store; the input is untouched. * * Order of operations (each step matters): * 1. **Expiry eviction** — drop everything older than `ttlMs` first, so an * expired key never occupies a capacity slot the new entry could take, and * a stale entry under the same `key` is cleared before the overwrite. * 2. **Insert / overwrite** — write the new entry. If `key` already exists, * this is an UPDATE: `value` is overwritten, `atMs` is refreshed to * `nowMs` (restarting the TTL clock), and the key is moved to the NEWEST * position in `order` (removed from wherever it sat, appended at the end). * See the module-level "Overwrite semantics" note. * 3. **Capacity eviction** — if the entry count now exceeds `capacity`, drop * the OLDEST keys by `order` until the count fits. Because step 2 moves a * re-remembered key to the newest position, an actively re-seen key is * never the eviction victim. */ declare function remember(store: IdempotencyStore, key: string, value: V, nowMs: number): IdempotencyStore; export { type IdempotencyStore as I, type IdempotencyEntry as a, remember as b, evictExpired as e, initStore as i, recall as r, seen as s };