@ultimat3/action 31.48.0 → 31.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/http.ts CHANGED
@@ -22,7 +22,7 @@ import {
22
22
  writeDigest,
23
23
  } from '@ultimat3/core';
24
24
  import type { Route, RouteMeta, UltimateRequest } from '@ultimat3/http';
25
- import { jsonResponse, publishRateLimit, redirect, takeRedirect } from '@ultimat3/http';
25
+ import { publishRateLimit, redirect, takeRedirect } from '@ultimat3/http';
26
26
  import { admitsAnonymous, policyCapability, policyPermissions } from '@ultimat3/policy';
27
27
  import type { ActionRateLimit, AnyAction } from './action';
28
28
  import { withChunkSink } from './action-stream';
@@ -43,7 +43,7 @@ import {
43
43
  import { answerNatively, isNativeFormPost } from './native-answer';
44
44
  import { withDeclaredErrors } from './openapi-errors';
45
45
  import { assertActionRateLimit, fixedRateLimit } from './rate-limit-gate';
46
- import { carriesRecords, recordResponse } from './record-wire';
46
+ import { carriesRecords, plainResponse, recordResponse } from './record-wire';
47
47
  import { assertReplayPrincipal, REPLAY_REFUSAL } from './replay-scope';
48
48
 
49
49
  /** The digest a request's idempotency key names its write by; none for a missing or blank one. */
@@ -68,11 +68,13 @@ export function toRoute(target: AnyAction): Route {
68
68
  // A `:param` pin's values come from the router's DECODED params and join the body before
69
69
  // `invoke` parses it: one input for the schema, the policy, the row loader and the handler. A
70
70
  // body naming the same key differently is refused (`X_HTTP_PATH_INPUT_CONFLICT`), never overridden.
71
+ // A form's fields are text: coerced toward the input as a query route's are (`bodyCoerced`).
72
+ const body = (req: UltimateRequest): Promise<unknown> => req.bodyCoerced(target.input);
71
73
  const readInput =
72
74
  templateParams(path).length === 0
73
- ? (req: UltimateRequest) => req.bodyRaw()
75
+ ? body
74
76
  : async (req: UltimateRequest) =>
75
- mergePathParams({ owner, template: path, params: req.params, raw: await req.bodyRaw() });
77
+ mergePathParams({ owner, template: path, params: req.params, raw: await body(req) });
76
78
  return projectRoute(target, path, readInput, methodOfHttp(http));
77
79
  }
78
80
 
@@ -88,7 +90,7 @@ export function toPostBinding(target: AnyAction, path: string): Route {
88
90
  target,
89
91
  path,
90
92
  async (req) => {
91
- const body = await req.bodyRaw();
93
+ const body = await req.bodyCoerced(target.input);
92
94
  const fields = typeof body === 'object' && body !== null && !Array.isArray(body) ? body : {};
93
95
  return { ...fields, ...req.queryRaw() };
94
96
  },
@@ -174,7 +176,7 @@ function projectRoute(
174
176
  ? redirect(to.location, to.status)
175
177
  : enveloped
176
178
  ? recordResponse(target.output, result)
177
- : jsonResponse(result);
179
+ : plainResponse(result);
178
180
  if (key !== null) response.headers.set(REPLAYED_HEADER, replayed ? '1' : '0');
179
181
  return response;
180
182
  };
@@ -13,7 +13,7 @@ import type {
13
13
  IdempotencyStore,
14
14
  } from './idempotency';
15
15
  import { requestDeadlineMs } from './request-deadline';
16
- import { liveTransaction } from './tx-scope';
16
+ import { settleScope } from './tx-scope';
17
17
 
18
18
  /**
19
19
  * How long a key is remembered. A day is the window every payment API this shape exists to serve
@@ -118,7 +118,7 @@ export class MemoryIdempotencyStore implements IdempotencyStore {
118
118
  createdAt: nowMs,
119
119
  };
120
120
  this.#records.set(key, record);
121
- this.#flights.set(record, { bound: liveTransaction() !== undefined, settling: false });
121
+ this.#flights.set(record, { bound: settleScope() !== undefined, settling: false });
122
122
  this.#maintain(nowMs);
123
123
  return Promise.resolve({ record, created: true });
124
124
  }
@@ -158,15 +158,15 @@ export class MemoryIdempotencyStore implements IdempotencyStore {
158
158
  value,
159
159
  ...(redacted ? { redacted: true } : {}),
160
160
  });
161
- const tx = liveTransaction();
161
+ const tx = settleScope();
162
162
  if (tx === undefined) {
163
163
  if (existing !== undefined) this.#records.set(key, settled(existing));
164
164
  else fenced(key, reservationId, 'settle');
165
165
  return Promise.resolve();
166
166
  }
167
- // Inside a transaction the record is settled BY the commit, as the Postgres store's is: a
168
- // rollback leaves it in flight rather than replaying a success for rows nobody stored. And a
169
- // settle that lost its reservation is thrown, because nothing has committed yet and the throw
167
+ // Inside a transaction — SQL or memory — the record is settled BY the commit, as the Postgres
168
+ // store's is: a rollback leaves it in flight rather than replaying a success for rows nobody
169
+ // stored. And a settle that lost its reservation is thrown, because nothing has committed yet and the throw
170
170
  // is what rolls this attempt back beside the retry that replaced it.
171
171
  if (existing === undefined) {
172
172
  return Promise.reject(new IdempotencyReservationLostError(key));
package/src/index.ts CHANGED
@@ -113,7 +113,7 @@ export {
113
113
  RpcFailedError,
114
114
  } from './errors';
115
115
  export { ActionDeprecationSuccessorInvalidError } from './errors-http';
116
- export type { MeterExceededInput } from './errors-meter';
116
+ export type { MeterDrawRefusal, MeterExceededInput } from './errors-meter';
117
117
  export { MeterExceededError } from './errors-meter';
118
118
  export { ActionStreamInvalidError } from './errors-stream';
119
119
  export type {
@@ -178,7 +178,8 @@ export type { JsonSchemaObject } from './json-schema';
178
178
  export { jsonSchemaOf } from './json-schema';
179
179
  /**
180
180
  * The meter seam: `meter: { name, period, limit, warnAt, onWarn }` on an action, drawn inside
181
- * `invoke` on every surface. The draw itself (`meter-gate.ts`) stays unexported — one caller.
181
+ * `invoke` on every surface (`meter-gate.ts`, unexported — its one caller). `drawMeter(ctx, …)`
182
+ * counts work measured after the fact — an amount, idempotent by key — on the same counters.
182
183
  * `MeterWarning` is the schema an app's warning `job()` declares as its input.
183
184
  */
184
185
  export type {
@@ -191,10 +192,12 @@ export type {
191
192
  ResolvedLimit,
192
193
  } from './meter';
193
194
  export { MeterWarning } from './meter';
195
+ export type { MeterDrawInput, MeterDrawOutcome } from './meter-draw';
196
+ export { drawMeter } from './meter-draw';
194
197
  export type { MemoryMeterStoreOptions } from './meter-memory';
195
198
  export { memoryMeterStore } from './meter-memory';
196
199
  export type { PostgresMeterStoreOptions } from './meter-postgres';
197
- export { postgresMeterStore, SQL_METER_TABLE } from './meter-postgres';
200
+ export { postgresMeterStore, SQL_METER_KEY_TABLE, SQL_METER_TABLE } from './meter-postgres';
198
201
  export type { MeterDraw, MeterDrawResult, MeterKey, MeterStore } from './meter-store';
199
202
  export { getMeterStore } from './meter-store';
200
203
  export type {
package/src/invoke.ts CHANGED
@@ -47,10 +47,15 @@ import type { HandlerOverride } from './handler-override';
47
47
  import { handlerOverrideOf, setHandlerOverride } from './handler-override';
48
48
  import { getIdempotencyStore, withIdempotency } from './idempotency';
49
49
  import { idempotencyKeyFor } from './idempotency-key';
50
- import { drawMeter } from './meter-gate';
50
+ import { drawActionMeter } from './meter-gate';
51
51
  import { guardAction, guardActionBeforeInput } from './policy-gate';
52
52
  import { spendActionLimit, withCallerAddress, withJobFrame } from './rate-limit-gate';
53
- import { parseActionInput, parsedOrNothing, validateOutput } from './validate';
53
+ import {
54
+ parseActionInput,
55
+ parsedOrNothing,
56
+ validateOutput,
57
+ validateReplayedOutput,
58
+ } from './validate';
54
59
 
55
60
  /**
56
61
  * Private on purpose. `@ultimat3/action` exports no way to read this back, which
@@ -381,7 +386,7 @@ async function perform(
381
386
  // it is drawn only for a reservation this call CREATED (`beforeRun`), so a replay — of a success
382
387
  // or of a settled failure — draws nothing, and a refusal releases the key for a retry next period.
383
388
  const metered = (): Promise<void> =>
384
- def.meter === undefined ? Promise.resolve() : drawMeter(name, def.meter, ctx);
389
+ def.meter === undefined ? Promise.resolve() : drawActionMeter(name, def.meter, ctx);
385
390
  // The peek can be stale: a record that lapsed after it leaves this call a FRESH reservation, and
386
391
  // the handler must not run on a rule it skipped. `beforeRun` runs only for a created reservation,
387
392
  // and a refusal there releases it. Spend first, in the order a first call takes them.
@@ -403,8 +408,11 @@ async function perform(
403
408
  trace.replayed = outcome.replayed;
404
409
  // A replay is parsed like a first call. The memory store hands back the live value and the
405
410
  // postgres store `JSON.parse(JSON.stringify(v))` — a `Date` on the first call and a `string`
406
- // on every retry served from Postgres — so the output schema is the one answer to its shape.
407
- return outcome.replayed ? validateOutput(def.output, outcome.value, name) : outcome.value;
411
+ // on every retry served from Postgres — so the output schema is the one answer to its shape,
412
+ // and a stored `null` it refuses is the `undefined` JSON could not keep.
413
+ return outcome.replayed
414
+ ? validateReplayedOutput(def.output, outcome.value, name)
415
+ : outcome.value;
408
416
  } finally {
409
417
  // Only for a handler that actually started, and only through the gate. A replay ran no handler
410
418
  // and changed nothing the first call had not already busted — re-busting per retry re-purges
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The programmatic draw: `drawMeter(ctx, { meter, period, amount, limit, key })` counts work
3
+ * measured after the fact — tokens, bytes, rows — on the counters a declared `meter:` uses, for the
4
+ * same caller. One conditional add of `amount` in the installed store, idempotent under `key`.
5
+ */
6
+
7
+ import type { Ctx } from '@ultimat3/core';
8
+ import { t, validate } from '@ultimat3/schema';
9
+ import { MeterExceededError, MeterInvalidError } from './errors-meter';
10
+ import { MAX_IDEMPOTENCY_KEY_LENGTH } from './idempotency-key';
11
+ import type { MeterPeriod, ResolvedLimit } from './meter';
12
+ import { assertMeterCounter, isMeterLimit } from './meter';
13
+ import { meterSubject, resolveMeterLimit } from './meter-gate';
14
+ import { meterPeriodKey, meterWindow } from './meter-period';
15
+ import { getMeterStore } from './meter-store';
16
+
17
+ export interface MeterDrawInput {
18
+ /** The counter's name: a `meter:` with this name and period counts on the same one. */
19
+ readonly meter: string;
20
+ readonly period: MeterPeriod;
21
+ /** Units this draw adds: a positive safe integer (1 to `Number.MAX_SAFE_INTEGER`). */
22
+ readonly amount: number;
23
+ /** Units allowed per period, or resolved per call from `{ ctx }` — the tenant's plan. */
24
+ readonly limit: ResolvedLimit;
25
+ /**
26
+ * The unit of work's own id, 1–255 chars with no NUL or lone surrogate. A second draw under it —
27
+ * a retry, on any replica sharing one store — adds nothing while the key is remembered: the
28
+ * period it counted in and the next one. `memoryMeterStore()` remembers per process, and either
29
+ * of its bounds ends that early — `maxDrawKeys`, or `maxKeys` evicting the counter with its keys;
30
+ * the Postgres store the boot installs remembers across replicas and restarts.
31
+ */
32
+ readonly key: string;
33
+ }
34
+
35
+ export interface MeterDrawOutcome {
36
+ /** The period's count after this draw, or after the draw `key` repeats. */
37
+ readonly used: number;
38
+ /** What `limit` resolved to for this call. */
39
+ readonly limit: number;
40
+ /** `true` when `key` had already counted, and this draw added nothing. */
41
+ readonly replayed: boolean;
42
+ /** When the period resets, ISO 8601 UTC. */
43
+ readonly resetsAt: string;
44
+ }
45
+
46
+ const isAmount = (value: unknown): value is number => isMeterLimit(value) && value >= 1;
47
+
48
+ /**
49
+ * Storable as written: `t.string`'s own rule refuses a NUL and a lone surrogate, which Postgres
50
+ * `text` refuses or rewrites — the shared store would then fail, or alias two keys the memory store
51
+ * keeps apart.
52
+ */
53
+ const isDrawKey = (value: unknown): value is string =>
54
+ typeof value === 'string' &&
55
+ value.length > 0 &&
56
+ value.length <= MAX_IDEMPOTENCY_KEY_LENGTH &&
57
+ validate(t.string, value).issues === undefined;
58
+
59
+ /**
60
+ * Count `amount` against `meter` for this caller (`ctx`'s org, else actor), or throw
61
+ * `X_METER_EXCEEDED` having counted nothing. The draw is the caller's whether or not its
62
+ * transaction commits: the store writes outside it, and `key` is what makes a retry safe.
63
+ */
64
+ export async function drawMeter(ctx: Ctx, input: MeterDrawInput): Promise<MeterDrawOutcome> {
65
+ // Read once, before anything awaits: a limit resolver holding the input cannot change what was
66
+ // validated after the fact.
67
+ const { meter, period, amount, key, limit: declared } = input;
68
+ const name: unknown = meter;
69
+ assertMeterCounter(name, period, 'draw');
70
+ if (!isAmount(amount)) {
71
+ throw new MeterInvalidError(name, 'amount', 'a positive safe integer', amount, 'draw');
72
+ }
73
+ if (!isDrawKey(key)) {
74
+ const expected = `a non-empty string of at most ${MAX_IDEMPOTENCY_KEY_LENGTH} chars, with no NUL or lone surrogate`;
75
+ throw new MeterInvalidError(name, 'key', expected, key, 'draw');
76
+ }
77
+ const store = getMeterStore();
78
+ if (store.keyedDraws !== true) {
79
+ throw new MeterInvalidError(
80
+ name,
81
+ 'store',
82
+ 'a MeterStore declaring keyedDraws: true — one that adds amount and remembers drawKey',
83
+ undefined,
84
+ 'draw',
85
+ );
86
+ }
87
+ const limit = await resolveMeterLimit(name, declared, ctx, 'draw');
88
+ const nowMs = ctx.now().getTime();
89
+ const window = meterWindow(period, nowMs);
90
+ const drawn = await store.draw({
91
+ subject: meterSubject(ctx),
92
+ meter: name,
93
+ period: meterPeriodKey(period),
94
+ periodStartMs: window.startMs,
95
+ limit,
96
+ amount,
97
+ drawKey: key,
98
+ });
99
+ // A lagging replica's draw lands on a counter already in the next period: its reset is that one's.
100
+ const resetsAtMs =
101
+ drawn.periodStartMs === undefined || drawn.periodStartMs <= window.startMs
102
+ ? window.endMs
103
+ : meterWindow(period, drawn.periodStartMs).endMs;
104
+ if (!drawn.allowed) {
105
+ throw new MeterExceededError({
106
+ meter: name,
107
+ period,
108
+ limit,
109
+ resetsAtMs,
110
+ nowMs,
111
+ ...(amount > limit ? { amount } : {}),
112
+ });
113
+ }
114
+ return {
115
+ used: drawn.used,
116
+ limit,
117
+ replayed: drawn.replayed === true,
118
+ resetsAt: new Date(resetsAtMs).toISOString(),
119
+ };
120
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * The memory meter store's eviction order, two shapes: `Fifo`, a key order taken from the head only
3
+ * (O(1) push, amortized O(1) shift), and `Chain`, a counter order any entry leaves in O(1). Not a
4
+ * `Set`: its iterator restarts at the table's first slot and walks every deleted one until the
5
+ * table rehashes, so taking the head after each delete grew per draw.
6
+ */
7
+
8
+ export class Fifo<T> {
9
+ private items: T[] = [];
10
+ private head = 0;
11
+
12
+ get size(): number {
13
+ return this.items.length - this.head;
14
+ }
15
+
16
+ push(item: T): void {
17
+ this.items.push(item);
18
+ }
19
+
20
+ peek(): T | undefined {
21
+ return this.head < this.items.length ? this.items[this.head] : undefined;
22
+ }
23
+
24
+ shift(): T | undefined {
25
+ if (this.head >= this.items.length) return undefined;
26
+ const item = this.items[this.head];
27
+ this.head += 1;
28
+ // Compacted once the consumed half outweighs the rest: each item is copied O(1) times.
29
+ if (this.head * 2 >= this.items.length) {
30
+ this.items = this.items.slice(this.head);
31
+ this.head = 0;
32
+ }
33
+ return item;
34
+ }
35
+ }
36
+
37
+ /** One entry of a `Chain`, held by its owner so it can leave in O(1). */
38
+ export interface ChainLink<T> {
39
+ readonly value: T;
40
+ prev: ChainLink<T> | undefined;
41
+ next: ChainLink<T> | undefined;
42
+ }
43
+
44
+ /**
45
+ * An insertion-ordered list whose entries leave from anywhere in O(1): the owner keeps the link
46
+ * `push` answers and hands it to `unlink`. Nothing retired waits in it for the head to reach it.
47
+ */
48
+ export class Chain<T> {
49
+ private head: ChainLink<T> | undefined;
50
+ private tail: ChainLink<T> | undefined;
51
+ private count = 0;
52
+
53
+ get size(): number {
54
+ return this.count;
55
+ }
56
+
57
+ first(): T | undefined {
58
+ return this.head?.value;
59
+ }
60
+
61
+ push(value: T): ChainLink<T> {
62
+ const link: ChainLink<T> = { value, prev: this.tail, next: undefined };
63
+ if (this.tail === undefined) this.head = link;
64
+ else this.tail.next = link;
65
+ this.tail = link;
66
+ this.count += 1;
67
+ return link;
68
+ }
69
+
70
+ unlink(link: ChainLink<T>): void {
71
+ if (link.prev === undefined) this.head = link.next;
72
+ else link.prev.next = link.next;
73
+ if (link.next === undefined) this.tail = link.prev;
74
+ else link.next.prev = link.prev;
75
+ link.prev = undefined;
76
+ link.next = undefined;
77
+ this.count -= 1;
78
+ }
79
+ }
package/src/meter-gate.ts CHANGED
@@ -6,6 +6,7 @@
6
6
 
7
7
  import type { Ctx } from '@ultimat3/core';
8
8
  import { isAnonymous, logger } from '@ultimat3/core';
9
+ import type { MeterSite } from './errors-meter';
9
10
  import { MeterExceededError, MeterInvalidError } from './errors-meter';
10
11
  import type { ActionMeter, MeterWarning, ResolvedLimit } from './meter';
11
12
  import { isMeterLimit } from './meter';
@@ -32,16 +33,19 @@ export async function resolveMeterLimit(
32
33
  meter: string,
33
34
  limit: ResolvedLimit,
34
35
  ctx: Ctx,
36
+ site: MeterSite = 'action',
35
37
  ): Promise<number> {
36
38
  const resolved: unknown = typeof limit === 'function' ? await limit({ ctx }) : limit;
37
39
  if (!isMeterLimit(resolved)) {
38
- throw new MeterInvalidError(meter, 'limit', 'a whole number of calls, 0 or more', resolved);
40
+ const expected =
41
+ site === 'draw' ? 'a whole number, 0 or more' : 'a whole number of calls, 0 or more';
42
+ throw new MeterInvalidError(meter, 'limit', expected, resolved, site);
39
43
  }
40
44
  return resolved;
41
45
  }
42
46
 
43
- /** Draw one call from `meter` for this caller, or throw `X_METER_EXCEEDED`. */
44
- export async function drawMeter(
47
+ /** Draw one call from an action's `meter:` for this caller, or throw `X_METER_EXCEEDED`. */
48
+ export async function drawActionMeter(
45
49
  action: string,
46
50
  meter: ActionMeter,
47
51
  ctx: Ctx,
@@ -5,16 +5,20 @@
5
5
  */
6
6
 
7
7
  import { finiteCount } from '@ultimat3/core';
8
- import type { MeterPeriod } from './meter';
9
- import { METER_PERIODS } from './meter';
10
- import { meterWindow } from './meter-period';
8
+ import type { ChainLink } from './meter-fifo';
9
+ import { Chain, Fifo } from './meter-fifo';
10
+ import { meterWindow, periodOfKey, previousPeriodStart } from './meter-period';
11
11
  import type { MeterDraw, MeterDrawResult, MeterKey, MeterStore } from './meter-store';
12
12
 
13
13
  /** One entry per tenant × meter × period declaration — the bound, not a cache size. */
14
14
  export const DEFAULT_MAX_METER_KEYS = 20_000;
15
15
 
16
+ /** Draw keys remembered across every counter — the bound on keyed draws, not a cache size. */
17
+ export const DEFAULT_MAX_METER_DRAW_KEYS = 200_000;
18
+
16
19
  export interface MemoryMeterStoreOptions {
17
20
  readonly maxKeys?: number;
21
+ readonly maxDrawKeys?: number;
18
22
  }
19
23
 
20
24
  interface Counter {
@@ -23,21 +27,38 @@ interface Counter {
23
27
  periodEndMs: number;
24
28
  used: number;
25
29
  warned: boolean;
30
+ /** Draw keys that counted in THIS counter's period. */
31
+ keys: Set<string>;
32
+ /** `keys` oldest first: a key leaves `keys` only from this head, or with the whole set. */
33
+ order: Fifo<string>;
34
+ /** Draw keys of the period just before, kept only when the counter rolled over from it. */
35
+ previous: Set<string>;
36
+ /** Its place in the store's `holdingKeys` / `holdingPrevious`, while its set is nonempty. */
37
+ keysLink: ChainLink<Counter> | undefined;
38
+ previousLink: ChainLink<Counter> | undefined;
26
39
  }
27
40
 
28
- const PERIODS: ReadonlySet<string> = new Set<string>(METER_PERIODS);
29
-
30
41
  /** `day@UTC` → the end of the period starting at `startMs`; the zone is UTC, the only one. */
31
42
  function periodEnd(period: string, startMs: number): number {
32
- const name = period.split('@')[0] ?? '';
33
- return PERIODS.has(name)
34
- ? meterWindow(name as MeterPeriod, startMs).endMs
35
- : Number.POSITIVE_INFINITY;
43
+ const name = periodOfKey(period);
44
+ return name === undefined ? Number.POSITIVE_INFINITY : meterWindow(name, startMs).endMs;
36
45
  }
37
46
 
38
47
  /** A JSON tuple, never a joined string: no subject or meter can forge another's key. */
39
48
  const keyOf = (key: MeterKey): string => JSON.stringify([key.subject, key.meter, key.period]);
40
49
 
50
+ /**
51
+ * Whether `drawKey` already counted on `counter`, judged from the period `effectiveMs` the draw
52
+ * lands in: a key counted in that period or the one before it repeats, an older one does not.
53
+ */
54
+ function counted(counter: Counter, period: string, drawKey: string, effectiveMs: number): boolean {
55
+ const keptSince = previousPeriodStart(period, effectiveMs);
56
+ if (counter.keys.has(drawKey)) return counter.periodStartMs >= keptSince;
57
+ return (
58
+ counter.previous.has(drawKey) && previousPeriodStart(period, counter.periodStartMs) >= keptSince
59
+ );
60
+ }
61
+
41
62
  export function memoryMeterStore(options: MemoryMeterStoreOptions = {}): MeterStore {
42
63
  const maxKeys = finiteCount(
43
64
  'memoryMeterStore',
@@ -45,7 +66,35 @@ export function memoryMeterStore(options: MemoryMeterStoreOptions = {}): MeterSt
45
66
  options.maxKeys ?? DEFAULT_MAX_METER_KEYS,
46
67
  1,
47
68
  );
69
+ const maxDrawKeys = finiteCount(
70
+ 'memoryMeterStore',
71
+ 'maxDrawKeys',
72
+ options.maxDrawKeys ?? DEFAULT_MAX_METER_DRAW_KEYS,
73
+ 1,
74
+ );
48
75
  const counters = new Map<string, Counter>();
76
+ /** Every counter's `keys` and `previous` together: kept exact so the bound costs no scan. */
77
+ let drawKeys = 0;
78
+ /**
79
+ * The counters holding a nonempty `previous` / `keys`, in the order each became nonempty, so a
80
+ * saturated draw finds another counter's keys without a scan. A counter leaves the moment its set
81
+ * empties or it retires (evicted, or replaced by its next period): a retired counter kept here
82
+ * would hold its keys past both bounds.
83
+ */
84
+ const holdingPrevious = new Chain<Counter>();
85
+ const holdingKeys = new Chain<Counter>();
86
+ const dropPrevious = (counter: Counter): void => {
87
+ if (counter.previousLink !== undefined) holdingPrevious.unlink(counter.previousLink);
88
+ counter.previousLink = undefined;
89
+ };
90
+ const dropKeys = (counter: Counter): void => {
91
+ if (counter.keysLink !== undefined) holdingKeys.unlink(counter.keysLink);
92
+ counter.keysLink = undefined;
93
+ };
94
+ const retire = (counter: Counter): void => {
95
+ dropPrevious(counter);
96
+ dropKeys(counter);
97
+ };
49
98
 
50
99
  /** The latest period start any draw named: a moment known to have passed, with no clock read. */
51
100
  let passedMs = Number.NEGATIVE_INFINITY;
@@ -72,11 +121,48 @@ export function memoryMeterStore(options: MemoryMeterStoreOptions = {}): MeterSt
72
121
  victimStart = counter.periodStartMs;
73
122
  }
74
123
  }
75
- if (victim !== undefined) counters.delete(victim);
124
+ const gone = victim === undefined ? undefined : counters.get(victim);
125
+ if (victim === undefined || gone === undefined) return;
126
+ drawKeys -= gone.keys.size + gone.previous.size;
127
+ retire(gone);
128
+ counters.delete(victim);
129
+ };
130
+
131
+ /**
132
+ * Past the draw-key bound, a period-before set goes first — this counter's, else any — then the
133
+ * oldest key of this counter, else of any. Forgetting a key lets its retry count again: a weaker
134
+ * guarantee in one process, as forgetting a counter is, never a refusal of a draw within limit.
135
+ * A durable, shared memory of keys is the Postgres store's.
136
+ */
137
+ const forgetKey = (counter: Counter): void => {
138
+ if (drawKeys < maxDrawKeys) return;
139
+ const withPrevious = counter.previous.size > 0 ? counter : holdingPrevious.first();
140
+ if (withPrevious !== undefined) {
141
+ drawKeys -= withPrevious.previous.size;
142
+ withPrevious.previous = new Set();
143
+ dropPrevious(withPrevious);
144
+ return;
145
+ }
146
+ const holder = counter.keys.size > 0 ? counter : holdingKeys.first();
147
+ const oldest = holder?.order.shift();
148
+ if (holder === undefined || oldest === undefined) return;
149
+ holder.keys.delete(oldest);
150
+ drawKeys -= 1;
151
+ if (holder.keys.size === 0) dropKeys(holder);
152
+ };
153
+
154
+ const remember = (counter: Counter, drawKey: string | undefined): void => {
155
+ if (drawKey === undefined || counter.keys.has(drawKey)) return;
156
+ forgetKey(counter);
157
+ counter.keys.add(drawKey);
158
+ counter.order.push(drawKey);
159
+ counter.keysLink ??= holdingKeys.push(counter);
160
+ drawKeys += 1;
76
161
  };
77
162
 
78
163
  return {
79
164
  scope: 'process',
165
+ keyedDraws: true,
80
166
 
81
167
  async draw(request: MeterDraw): Promise<MeterDrawResult> {
82
168
  if (Number.isFinite(request.periodStartMs))
@@ -89,24 +175,56 @@ export function memoryMeterStore(options: MemoryMeterStoreOptions = {}): MeterSt
89
175
  existing === undefined || request.periodStartMs > existing.periodStartMs
90
176
  ? undefined
91
177
  : existing;
92
- const used = (current?.used ?? 0) + 1;
93
- if (used > request.limit) {
94
- return { allowed: false, used: current?.used ?? 0, warned: current?.warned ?? false };
178
+ // The counter's period after this draw, answered to a keyed draw (`drawMeter` reads its reset
179
+ // off it); a `meter:` gate's call always draws its own period, so it is left off there.
180
+ const at =
181
+ request.drawKey === undefined
182
+ ? {}
183
+ : { periodStartMs: current?.periodStartMs ?? request.periodStartMs };
184
+ const spent = current?.used ?? 0;
185
+ const warned = current?.warned ?? false;
186
+ const drawKey = request.drawKey;
187
+ if (
188
+ drawKey !== undefined &&
189
+ existing !== undefined &&
190
+ counted(existing, request.period, drawKey, current?.periodStartMs ?? request.periodStartMs)
191
+ ) {
192
+ return { allowed: true, used: spent, warned, replayed: true, ...at };
95
193
  }
194
+ const used = spent + (request.amount ?? 1);
195
+ if (used > request.limit) return { allowed: false, used: spent, warned, ...at };
96
196
  if (current === undefined) {
97
197
  if (existing === undefined) evict();
98
- counters.set(id, {
198
+ // A rollover keeps the keys of the period just before, whole: a retry just after the reset
199
+ // must still find the draw it repeats. Older ones are dropped as one set, never scanned.
200
+ const adjacent =
201
+ existing !== undefined &&
202
+ existing.periodStartMs === previousPeriodStart(request.period, request.periodStartMs);
203
+ if (existing !== undefined) {
204
+ drawKeys -= existing.previous.size + (adjacent ? 0 : existing.keys.size);
205
+ retire(existing);
206
+ }
207
+ const counter: Counter = {
99
208
  periodStartMs: request.periodStartMs,
100
209
  periodEndMs: periodEnd(request.period, request.periodStartMs),
101
210
  used,
102
211
  warned: false,
103
- });
104
- return { allowed: true, used, warned: false };
212
+ keys: new Set(),
213
+ order: new Fifo(),
214
+ previous: adjacent ? existing.keys : new Set(),
215
+ keysLink: undefined,
216
+ previousLink: undefined,
217
+ };
218
+ counters.set(id, counter);
219
+ if (counter.previous.size > 0) counter.previousLink = holdingPrevious.push(counter);
220
+ remember(counter, drawKey);
221
+ return { allowed: true, used, warned: false, ...at };
105
222
  }
106
223
  current.used = used;
107
- return { allowed: true, used, warned: current.warned };
224
+ // Stamped with the counter's period, not the request's: a lagging draw counted in this one.
225
+ remember(current, drawKey);
226
+ return { allowed: true, used, warned: current.warned, ...at };
108
227
  },
109
-
110
228
  async claimWarning(key, periodStartMs): Promise<boolean> {
111
229
  const counter = counters.get(keyOf(key));
112
230
  if (counter === undefined || counter.periodStartMs !== periodStartMs || counter.warned) {
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  import type { MeterPeriod } from './meter';
9
+ import { METER_PERIODS } from './meter';
9
10
 
10
11
  export interface MeterWindow {
11
12
  readonly startMs: number;
@@ -32,3 +33,21 @@ export function meterWindow(period: MeterPeriod, nowMs: number): MeterWindow {
32
33
 
33
34
  /** The period half of the stored key — the zone spelled out so it can never be assumed. */
34
35
  export const meterPeriodKey = (period: MeterPeriod): string => `${period}@UTC`;
36
+
37
+ const PERIODS: ReadonlySet<string> = new Set<string>(METER_PERIODS);
38
+
39
+ /** `day@UTC` → `day`; `undefined` for a stored key no shipped period spells. */
40
+ export function periodOfKey(key: string): MeterPeriod | undefined {
41
+ const name = key.split('@')[0] ?? '';
42
+ return PERIODS.has(name) ? (name as MeterPeriod) : undefined;
43
+ }
44
+
45
+ /**
46
+ * The start of the period before the one starting at `startMs`: how far back a draw key is
47
+ * remembered, so a retry landing just after a reset still counts once. A key no shipped period
48
+ * spells remembers its own period only.
49
+ */
50
+ export function previousPeriodStart(periodKey: string, startMs: number): number {
51
+ const period = periodOfKey(periodKey);
52
+ return period === undefined ? startMs : meterWindow(period, startMs - 1).startMs;
53
+ }