@ultimat3/action 31.49.0 → 31.51.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/CLAUDE.md CHANGED
@@ -60,7 +60,7 @@ Owns the `action` + `mutator` primitives and five projections. Tier 3. The MCP t
60
60
  | `cache-gate.ts` | the post-COMMIT bust — **the only** file that calls `invalidateTags` |
61
61
  | `tx-scope.ts` | the open transaction — **the only** file that imports `@ultimat3/db` (`tx-scope.test.ts`): `openCommitScope` (the bust), `liveTransaction` (the settle), `completeTransaction`, and `inRolledBackScope`, the exercise's always-rolled-back scope and the memory transaction it opens always |
62
62
  | `rate-limit-gate.ts` | **the one place** a declared `rateLimit:` is spent (a `limit` resolved per call from `ctx`, through `toBucket`) |
63
- | `meter*.ts`, `errors-meter.ts` | `meter:` — declaration (`meter.ts`), UTC window, store seam + memory + Postgres (`x_meter`), and `meter-gate.ts`, **the one place** it is drawn |
63
+ | `meter*.ts`, `errors-meter.ts` | `meter:` (`meter.ts`), UTC window, store seam, memory, Postgres; `meter-gate.ts` draws a `meter:`, `meter-draw.ts` is `drawMeter` |
64
64
  | `request-deadline.ts` | `requestDeadlineMs` — the app's `requestTimeoutMs`, resolved by http's own `defineHttpConfig` |
65
65
  | `audit.ts` | the audit seam's TYPES, re-exported from `@ultimat3/core` (shared with `query`); the slot (`installAuditSink`, `@ultimat3/core/adapter`) is core's alone |
66
66
  | `audit-memory.ts` | the process default: a bounded ring that DROPS, counting the drops |
package/README.md CHANGED
@@ -661,6 +661,15 @@ stored key says so (`day@UTC`). An idempotent replay draws nothing. `limit` may
661
661
  installed by the CLI boot (one row per counter, rolled over in place, no purge). Full table:
662
662
  [Actions → Usage meters](https://github.com/developerz-ai/ultimate/wiki/Actions#usage-meters-meter).
663
663
 
664
+ An amount measured after the work — tokens, bytes, rows — is `drawMeter(ctx, { meter, period,
665
+ amount, limit, key })`: added whole or not at all (`X_METER_EXCEEDED`), on the counter a `meter:`
666
+ of the same name and period uses. A `key` counts once while it is remembered: for the period it
667
+ counted in and the next, by one store — across replicas and restarts on the Postgres store the
668
+ boot installs; within one process on `memoryMeterStore()`, where either bound ends it early
669
+ (`maxDrawKeys`, or `maxKeys` evicting the counter with its keys). `limit` judges
670
+ new charges only: a remembered key replays even after its limit drops below its amount. Answers
671
+ `{ used, limit, replayed, resetsAt }`: [Actions → Programmatic draws](https://github.com/developerz-ai/ultimate/wiki/Actions#programmatic-draws-drawmeter).
672
+
664
673
  ## `idempotent:` — and where its records live
665
674
 
666
675
  `idempotent: true` + an `Idempotency-Key` header replays the first **outcome**
@@ -1180,8 +1189,8 @@ around it; `undefined` restores the declared handler. `@ultimat3/testing`'s `stu
1180
1189
  | `X_ACTION_PATH_DUPLICATE` | two actions derive one HTTP path (`archiveOrder` / `archiveOrders`) | rename one export |
1181
1190
  | `X_ACTION_POLICY_MISSING` | registration without `policy:` | add `policy: can('…')` |
1182
1191
  | `X_RATE_LIMIT_INVALID` | `rateLimit:` with a non-positive or non-finite half — `windowMs: 0` refills infinitely. Owned by `@ultimat3/http`, which owns the conversion | make both positive, or delete the block |
1183
- | `X_METER_EXCEEDED` | a `meter:`'s allowance for the current UTC period is spent; `meta.resetsAt` and `Retry-After` say when it resets | wait, or raise what `meter.limit` resolves to for the tenant |
1184
- | `X_METER_INVALID` | a `meter:` with a bad name, period or `warnAt`, half a `warnAt`/`onWarn` pair, or a limit resolving to anything but a whole number ≥ 0 | fix the declaration the cause names |
1192
+ | `X_METER_EXCEEDED` | a `meter:`'s allowance for the current UTC period is spent, or a `drawMeter` amount would pass it; `meta.resetsAt` and `Retry-After` say when it resets | wait, or raise what `meter.limit` resolves to for the tenant. A `drawMeter` amount larger than the whole limit fits no period, carries no `Retry-After` and is `terminal` for a job: raise the limit, or, above 0, split the work into draws within it |
1193
+ | `X_METER_INVALID` | a `meter:` with a bad name, period or `warnAt`, half a `warnAt`/`onWarn` pair, or a limit resolving to anything but a whole number ≥ 0; a `drawMeter` with a bad amount (a positive safe integer) or key (1–255 chars, no NUL or lone surrogate), or an installed store that does not declare `keyedDraws: true` | fix the declaration the cause names |
1185
1194
  | `X_ACTION_DEPRECATION_INVALID` | `deprecated:` with a `since`/`sunset` that is not a date | use an ISO-8601 instant |
1186
1195
  | `X_INPUT_INVALID` | input failed the Standard Schema. Carries the rejections **twice**: the flattened line in `cause`, and the structured list in `meta.issues` — one value rendered two ways, `As of 2026-08-24` | `x actions show <name> --json` |
1187
1196
  | `X_IDEMPOTENCY_CONFLICT` | key reused with a new payload / still in flight | new key, or retry later |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/action",
3
- "version": "31.49.0",
3
+ "version": "31.51.0",
4
4
  "description": "The action primitive: one declaration projected to route, OpenAPI, client, MCP tool, job handle, tests",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -48,13 +48,13 @@
48
48
  "test": "bun test"
49
49
  },
50
50
  "dependencies": {
51
- "@ultimat3/cache": "31.49.0",
52
- "@ultimat3/core": "31.49.0",
53
- "@ultimat3/db": "31.49.0",
54
- "@ultimat3/entity": "31.49.0",
55
- "@ultimat3/http": "31.49.0",
56
- "@ultimat3/policy": "31.49.0",
57
- "@ultimat3/schema": "31.49.0",
58
- "@ultimat3/storage": "31.49.0"
51
+ "@ultimat3/cache": "31.51.0",
52
+ "@ultimat3/core": "31.51.0",
53
+ "@ultimat3/db": "31.51.0",
54
+ "@ultimat3/entity": "31.51.0",
55
+ "@ultimat3/http": "31.51.0",
56
+ "@ultimat3/policy": "31.51.0",
57
+ "@ultimat3/schema": "31.51.0",
58
+ "@ultimat3/storage": "31.51.0"
59
59
  }
60
60
  }
@@ -9,7 +9,7 @@
9
9
  */
10
10
 
11
11
  import type { ActionPathStyle } from '@ultimat3/core';
12
- import type { BearerMountRateLimit, BearerResolver } from '@ultimat3/http';
12
+ import type { BearerMountRateLimit, BearerMountTenant, BearerResolver } from '@ultimat3/http';
13
13
  import { OpenApiConfigInvalidError } from './errors-http';
14
14
 
15
15
  /** A second door onto a cut of the API, authenticated by `Authorization: Bearer` alone. */
@@ -32,6 +32,12 @@ export interface ApiMount {
32
32
  * `x verify` refuses it stale, exactly as it does `openapi.json`.
33
33
  */
34
34
  readonly openapi?: string;
35
+ /**
36
+ * One token across tenants: the token resolves to a person, every call names its tenant as
37
+ * `?<arg>=<value>`, and `resolve`'s actor is the caller — the shape `defineAppMcp({ tenant })`
38
+ * takes, so one declaration serves both doors. Adds `GET <prefix>/tenants`.
39
+ */
40
+ readonly tenant?: BearerMountTenant;
35
41
  }
36
42
 
37
43
  export interface ApiHttp {
@@ -50,8 +50,8 @@ export const ACTION_ERROR_TITLES: Readonly<Record<string, string>> = {
50
50
  X_CONTRACT_EXERCISE_UNREACHED: 'no generated run reached the handler',
51
51
  X_CONTRACT_EXERCISE_UNDECLARED: '.contract() on a non-public action names no exercise',
52
52
  X_ACTION_STREAM_INVALID: 'a streaming action broke its stream contract',
53
- X_METER_EXCEEDED: "an action's usage meter is spent for this period",
54
- X_METER_INVALID: "an action's meter cannot be counted against",
53
+ X_METER_EXCEEDED: 'a usage meter is spent for this period',
54
+ X_METER_INVALID: 'a usage meter cannot be counted against',
55
55
  X_REPLAY_PRINCIPAL_MISMATCH:
56
56
  'a queued offline write was replayed under a session that did not queue it',
57
57
  };
@@ -15,33 +15,89 @@ export interface MeterExceededInput {
15
15
  readonly nowMs: number;
16
16
  }
17
17
 
18
+ /**
19
+ * A `drawMeter` call's refusal: no action to name, the call site is the fix. `amount` is set only
20
+ * when the draw alone is larger than the whole limit, which no reset makes room for.
21
+ */
22
+ export type MeterDrawRefusal = Omit<MeterExceededInput, 'action'> & { readonly amount?: number };
23
+
18
24
  /**
19
25
  * `meta.retryAfterSeconds` is the framework's one spelling of a stated delay: `@ultimat3/http`
20
- * renders it onto `Retry-After`, and a job's retry waits the same number.
26
+ * renders it onto `Retry-After`, and a job's retry waits the same number. A draw larger than the
27
+ * whole limit states none and is `terminal`: no reset admits it, so a job dead-letters it at once
28
+ * instead of waiting out a period to be refused again.
21
29
  */
22
30
  export class MeterExceededError extends UltimateError {
23
- constructor(input: MeterExceededInput) {
31
+ constructor(input: MeterExceededInput | MeterDrawRefusal) {
24
32
  const resetsAt = new Date(input.resetsAtMs).toISOString();
25
33
  const retryAfterSeconds = Math.max(1, Math.ceil((input.resetsAtMs - input.nowMs) / 1000));
34
+ const meterArg = renderFixShellArg(input.meter, '<meter>');
35
+ const oversizedBy = 'action' in input ? undefined : input.amount;
36
+ const oversized = oversizedBy !== undefined;
37
+ // At a limit of 0 no draw is small enough: splitting is advice only above it.
38
+ const split = input.limit > 0 ? `, or split the work into draws of at most ${input.limit}` : '';
26
39
  super({
27
40
  code: 'X_METER_EXCEEDED',
28
- cause: `the "${input.meter}" meter on action "${input.action}" allows ${input.limit} calls per ${input.period} (UTC), and this caller's allowance for the period is spent; it resets at ${resetsAt}`,
29
- fix: `x actions show ${renderFixShellArg(input.action, '<action>')} --json # names the meter and its period; raise what meter.limit resolves to for this tenant in the action file, or retry after meta.resetsAt`,
41
+ ...(oversized
42
+ ? {
43
+ cause: `the "${input.meter}" meter allows ${input.limit} units per ${input.period} (UTC), and this draw of ${oversizedBy} is larger than the whole allowance: nothing was counted, and no reset makes room for it`,
44
+ fix: `grep -rn "drawMeter(" apps/ # the call drawing "${meterArg}": raise what its limit resolves to for this tenant${split}`,
45
+ }
46
+ : !('action' in input)
47
+ ? {
48
+ cause: `the "${input.meter}" meter allows ${input.limit} units per ${input.period} (UTC), and this draw would pass this caller's allowance for the period; nothing was counted, and it resets at ${resetsAt}`,
49
+ fix: `grep -rn "drawMeter(" apps/ # the call drawing "${meterArg}": raise what its limit resolves to for this tenant, or retry after meta.resetsAt`,
50
+ }
51
+ : {
52
+ cause: `the "${input.meter}" meter on action "${input.action}" allows ${input.limit} calls per ${input.period} (UTC), and this caller's allowance for the period is spent; it resets at ${resetsAt}`,
53
+ fix: `x actions show ${renderFixShellArg(input.action, '<action>')} --json # names the meter and its period; raise what meter.limit resolves to for this tenant in the action file, or retry after meta.resetsAt`,
54
+ }),
30
55
  callerFix: `retry after ${resetsAt} (the Retry-After header): the "${input.meter}" allowance resets then, and a larger one is the application's to grant`,
31
- meta: { meter: input.meter, limit: input.limit, resetsAt, retryAfterSeconds },
56
+ ...(oversized
57
+ ? {
58
+ callerFix: `this request needs more of "${input.meter}" than one ${input.period} allows; the application has to grant a larger allowance`,
59
+ retry: 'terminal' as const,
60
+ }
61
+ : {}),
62
+ meta: {
63
+ meter: input.meter,
64
+ limit: input.limit,
65
+ resetsAt,
66
+ ...(oversized ? {} : { retryAfterSeconds }),
67
+ },
32
68
  });
33
69
  }
34
70
  }
35
71
 
36
- export type MeterField = 'name' | 'period' | 'limit' | 'warnAt';
72
+ export type MeterField = 'name' | 'period' | 'limit' | 'warnAt' | 'amount' | 'key' | 'store';
73
+
74
+ /** Where the meter was written: an action's `meter:` block, or a `drawMeter` call. */
75
+ export type MeterSite = 'action' | 'draw';
37
76
 
38
77
  /** A meter declared — or a limit resolved — that no counter could enforce. */
39
78
  export class MeterInvalidError extends UltimateError {
40
- constructor(meter: string, field: MeterField, expected: string, value?: unknown) {
79
+ constructor(
80
+ meter: string,
81
+ field: MeterField,
82
+ expected: string,
83
+ value?: unknown,
84
+ site: MeterSite = 'action',
85
+ ) {
86
+ const meterArg = renderFixShellArg(meter, '<meter>');
41
87
  super({
42
88
  code: 'X_METER_INVALID',
43
- cause: `meter "${meter}" declares ${field}${value === undefined ? '' : ` = ${renderCauseValue(value)}`}, which is not ${expected}`,
44
- fix: `meter: { name: 'calls', period: 'day', limit: ({ ctx }) => 500, warnAt: 0.8, onWarn: quotaWarning } # edit the action declaring "${renderFixShellArg(meter, '<meter>')}" — ${field} must be ${expected}`,
89
+ ...(field === 'store'
90
+ ? {
91
+ cause: `meter "${meter}" is drawn on an installed meter store that is not ${expected}: a store written before keyed draws counts one call per draw and never replays, so nothing was counted`,
92
+ fix: `meterStore: { ...store, keyedDraws: true }, // apps/<app>/runtime.ts: keep the store's own scope, add amount and drawKey to its draw(), and pass meterStoreConformance from @ultimat3/testing`,
93
+ }
94
+ : {
95
+ cause: `meter "${meter}" declares ${field}${value === undefined ? '' : ` = ${renderCauseValue(value)}`}, which is not ${expected}`,
96
+ fix:
97
+ site === 'draw'
98
+ ? `drawMeter(ctx, { meter: 'tokens', period: 'day', amount: 1200, limit: ({ ctx }) => 100_000, key: run.id }); // edit the drawMeter call drawing "${meterArg}": ${field} must be ${expected}`
99
+ : `meter: { name: 'calls', period: 'day', limit: ({ ctx }) => 500, warnAt: 0.8, onWarn: quotaWarning }, // edit the action declaring "${meterArg}": ${field} must be ${expected}`,
100
+ }),
45
101
  meta: { meter, field },
46
102
  });
47
103
  }
package/src/http.ts CHANGED
@@ -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
  },
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,7 +47,7 @@ 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
53
  import {
@@ -386,7 +386,7 @@ async function perform(
386
386
  // it is drawn only for a reservation this call CREATED (`beforeRun`), so a replay — of a success
387
387
  // or of a settled failure — draws nothing, and a refusal releases the key for a retry next period.
388
388
  const metered = (): Promise<void> =>
389
- def.meter === undefined ? Promise.resolve() : drawMeter(name, def.meter, ctx);
389
+ def.meter === undefined ? Promise.resolve() : drawActionMeter(name, def.meter, ctx);
390
390
  // The peek can be stale: a record that lapsed after it leaves this call a FRESH reservation, and
391
391
  // the handler must not run on a rule it skipped. `beforeRun` runs only for a created reservation,
392
392
  // and a refusal there releases it. Spend first, in the order a first call takes them.
@@ -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,