@ultimat3/action 31.49.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.
@@ -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
+ }
@@ -5,6 +5,8 @@
5
5
  */
6
6
 
7
7
  import type { PgExecutor } from '@ultimat3/core';
8
+ import { InternalError } from '@ultimat3/core';
9
+ import { periodOfKey, previousPeriodStart } from './meter-period';
8
10
  import type { MeterDraw, MeterDrawResult, MeterKey, MeterStore } from './meter-store';
9
11
 
10
12
  /**
@@ -29,7 +31,40 @@ create table if not exists x_meter (
29
31
  `;
30
32
 
31
33
  /**
32
- * `$1` subject, `$2` meter, `$3` period key, `$4` the period start, `$5` the limit.
34
+ * The keys of the keyed draws that COUNTED (`drawMeter`'s `key`): one row per counted draw, this
35
+ * period's and the last's. A keyed draw that counts deletes its counter's older ones, so an active
36
+ * counter holds about two periods of draws; a counter that stops receiving keyed draws keeps its
37
+ * last rows until its next one. Size it as draws per period × 2 for the active counters, plus the
38
+ * idle counters' last two periods. Applied by the boot beside `SQL_METER_TABLE`.
39
+ *
40
+ * `x_meter_key_counted` answers whether a key counted, on a snapshot of its own: Postgres hands a
41
+ * `volatile` function a FRESH snapshot for each query it runs, so called after the counter's lock
42
+ * is taken it sees the key of a draw that held that lock first and committed after the calling
43
+ * statement began, which that statement's own snapshot predates. A body with `from` is never
44
+ * inlined, so the call stays a call; and it holds no semicolon, as the boot splits on them.
45
+ */
46
+ export const SQL_METER_KEY_TABLE = `
47
+ create table if not exists x_meter_key (
48
+ subject text not null,
49
+ meter text not null,
50
+ period text not null,
51
+ draw_key text not null,
52
+ period_start timestamptz not null,
53
+ primary key (subject, meter, period, draw_key)
54
+ );
55
+
56
+ create index if not exists x_meter_key_period_start_idx
57
+ on x_meter_key (subject, meter, period, period_start);
58
+
59
+ create or replace function x_meter_key_counted(text, text, text, text, timestamptz)
60
+ returns boolean language sql volatile
61
+ as $$ select count(*) > 0 from x_meter_key
62
+ where subject = $1 and meter = $2 and period = $3 and draw_key = $4
63
+ and period_start >= $5 $$;
64
+ `;
65
+
66
+ /**
67
+ * `$1` subject, `$2` meter, `$3` period key, `$4` the period start, `$5` the limit, `$6` the amount.
33
68
  *
34
69
  * Atomic and conditional in ONE statement: the `insert … select … where` admits a first draw only
35
70
  * within the limit, and `do update … where` re-checks against the row AFTER its lock is taken — a
@@ -41,18 +76,114 @@ create table if not exists x_meter (
41
76
  */
42
77
  const SQL_METER_DRAW = `
43
78
  insert into x_meter (subject, meter, period, period_start, used, warned)
44
- select $1, $2, $3, $4::timestamptz, 1, false
45
- where 1 <= $5::bigint
79
+ select $1, $2, $3, $4::timestamptz, $6::bigint, false
80
+ where $6::bigint <= $5::bigint
46
81
  on conflict (subject, meter, period) do update set
47
- used = case when excluded.period_start > x_meter.period_start then 1 else x_meter.used + 1 end,
82
+ used = case when excluded.period_start > x_meter.period_start then $6::bigint
83
+ else x_meter.used + $6::bigint end,
48
84
  warned = case when excluded.period_start > x_meter.period_start then false else x_meter.warned end,
49
85
  period_start = greatest(x_meter.period_start, excluded.period_start),
50
86
  updated_at = now()
51
- where (case when excluded.period_start > x_meter.period_start then 0 else x_meter.used end) + 1
52
- <= $5::bigint
87
+ where (case when excluded.period_start > x_meter.period_start then 0 else x_meter.used end)
88
+ + $6::bigint <= $5::bigint
53
89
  returning used, warned
54
90
  `;
55
91
 
92
+ /**
93
+ * A KEYED draw: `$1`–`$6` as above, `$7` the draw key, `$8` the start of the period before the
94
+ * request's, `$9` the period's length as an interval (`1 day`; null for a period key this store
95
+ * cannot read, which remembers its own period only). The period before the COUNTER's is taken in
96
+ * UTC, so a session zone cannot move a calendar boundary.
97
+ *
98
+ * The counter row is locked FIRST (`for update`, which hands back its latest committed version),
99
+ * so every draw on one counter — every replica's — runs one at a time from here. Under that lock
100
+ * the key is claimed only within the limit, and the count moves only when the claim landed: a key
101
+ * that already counted (this period or the last) conflicts, and nothing is added. The row must
102
+ * exist: `SQL_METER_OPEN_KEYED` when no row comes back.
103
+ *
104
+ * A draw past the limit still asks whether its key counted (`seen`), through `x_meter_key_counted`
105
+ * and never a plain read: a draw that held the lock first and counted this very key committed after
106
+ * this statement's snapshot, so a `select` here cannot see its row. Called from `spent`, after the
107
+ * lock, the function reads on a fresh snapshot — so replay or refusal is decided under the same
108
+ * lock as the count it answers, writing nothing.
109
+ *
110
+ * Every period here is the COUNTER's after the draw — `greatest` of its own and the request's — so
111
+ * a lagging replica's draw is stamped with, and judged by, the period it is really counted in. Only
112
+ * a draw that counted deletes the counter's keys older than the period before that one: a refused
113
+ * draw of a later period moves no counter, and must forget nothing the counter still remembers.
114
+ */
115
+ const SQL_METER_DRAW_KEYED = `
116
+ with counter as (
117
+ select used, warned, period_start,
118
+ greatest(period_start, $4::timestamptz) as effective,
119
+ case when period_start <= $4::timestamptz then $8::timestamptz
120
+ when $9::interval is null then period_start
121
+ else ((period_start at time zone 'UTC') - $9::interval) at time zone 'UTC'
122
+ end as kept_since
123
+ from x_meter
124
+ where subject = $1 and meter = $2 and period = $3
125
+ for update
126
+ ),
127
+ spent as (
128
+ select case when $4::timestamptz > period_start then 0 else used end as used,
129
+ case when $4::timestamptz > period_start then false else warned end as warned,
130
+ effective, kept_since,
131
+ case when (case when $4::timestamptz > period_start then 0 else used end) + $6::bigint
132
+ > $5::bigint
133
+ then x_meter_key_counted($1, $2, $3, $7, kept_since) end as seen
134
+ from counter
135
+ ),
136
+ claim as (
137
+ insert into x_meter_key (subject, meter, period, draw_key, period_start)
138
+ select $1, $2, $3, $7, effective from spent where used + $6::bigint <= $5::bigint
139
+ on conflict (subject, meter, period, draw_key) do update set period_start = excluded.period_start
140
+ where x_meter_key.period_start < (select kept_since from spent)
141
+ returning draw_key
142
+ ),
143
+ counted as (
144
+ update x_meter set
145
+ used = case when $4::timestamptz > period_start then $6::bigint else used + $6::bigint end,
146
+ warned = case when $4::timestamptz > period_start then false else warned end,
147
+ period_start = greatest(period_start, $4::timestamptz),
148
+ updated_at = now()
149
+ where subject = $1 and meter = $2 and period = $3 and exists (select 1 from claim)
150
+ returning used, warned
151
+ ),
152
+ purged as (
153
+ delete from x_meter_key
154
+ where subject = $1 and meter = $2 and period = $3
155
+ and period_start < (select kept_since from spent)
156
+ and draw_key <> $7 and exists (select 1 from claim)
157
+ )
158
+ select spent.used, spent.warned, spent.used + $6::bigint <= $5::bigint as within,
159
+ (extract(epoch from spent.effective) * 1000)::bigint as effective_ms,
160
+ counted.used as counted_used, counted.warned as counted_warned,
161
+ spent.seen
162
+ from spent left join counted on true
163
+ `;
164
+
165
+ /**
166
+ * A keyed draw's FIRST counter: the row is inserted already charged, its key beside it, in one
167
+ * statement — a zero row inserted first opened the request's period for a lagging draw to spend
168
+ * before this draw charged it. `$1`–`$4` the counter and its period, `$5` the amount, `$6` the
169
+ * draw key; the caller has checked the amount fits the limit. No row back: a racing draw created
170
+ * the counter first, and the keyed draw above runs against it.
171
+ */
172
+ const SQL_METER_OPEN_KEYED = `
173
+ with opened as (
174
+ insert into x_meter (subject, meter, period, period_start, used, warned)
175
+ values ($1, $2, $3, $4::timestamptz, $5::bigint, false)
176
+ on conflict (subject, meter, period) do nothing
177
+ returning used, warned
178
+ ),
179
+ claimed as (
180
+ insert into x_meter_key (subject, meter, period, draw_key, period_start)
181
+ select $1, $2, $3, $6, $4::timestamptz from opened
182
+ on conflict (subject, meter, period, draw_key) do update set period_start = excluded.period_start
183
+ )
184
+ select used, warned from opened
185
+ `;
186
+
56
187
  /** What a refused draw is told it had used — read only on a refusal, never before a draw. */
57
188
  const SQL_METER_READ = `
58
189
  select used, warned from x_meter
@@ -71,6 +202,18 @@ update x_meter set warned = false
71
202
  where subject = $1 and meter = $2 and period = $3 and period_start = $4::timestamptz
72
203
  `;
73
204
 
205
+ interface KeyedRow {
206
+ readonly used: number | string;
207
+ readonly warned: boolean | string;
208
+ readonly within: boolean | string;
209
+ /** Epoch ms, never a timestamp: a text-mode client renders those in the session's `DateStyle`. */
210
+ readonly effective_ms: number | string;
211
+ readonly counted_used: number | string | null;
212
+ readonly counted_warned: boolean | string | null;
213
+ /** Past the limit only: whether the key had counted, read under the lock. */
214
+ readonly seen: boolean | string | null;
215
+ }
216
+
74
217
  interface CounterRow {
75
218
  /** `bigint`, which a client hands back as a string. */
76
219
  readonly used: number | string;
@@ -83,6 +226,11 @@ export interface PostgresMeterStoreOptions {
83
226
  }
84
227
 
85
228
  const isTrue = (value: boolean | string): boolean => value === true || value === 't';
229
+ /** A period's length as a Postgres interval; null for a period key no shipped period spells. */
230
+ const periodInterval = (periodKey: string): string | null => {
231
+ const period = periodOfKey(periodKey);
232
+ return period === undefined ? null : `1 ${period}`;
233
+ };
86
234
  const iso = (ms: number): string => new Date(ms).toISOString();
87
235
  const keyParams = (key: MeterKey, periodStartMs: number): readonly unknown[] => [
88
236
  key.subject,
@@ -98,13 +246,83 @@ const keyParams = (key: MeterKey, periodStartMs: number): readonly unknown[] =>
98
246
  */
99
247
  export function postgresMeterStore(options: PostgresMeterStoreOptions): MeterStore {
100
248
  const exec = options.executor;
249
+
250
+ /** The locked keyed draw, opening the counter charged when there is none yet. */
251
+ const lockedDraw = async (
252
+ request: MeterDraw,
253
+ drawKey: string,
254
+ params: readonly unknown[],
255
+ ): Promise<KeyedRow | MeterDrawResult> => {
256
+ const row = (await exec.query<KeyedRow>(SQL_METER_DRAW_KEYED, params))[0];
257
+ if (row !== undefined) return row;
258
+ const amount = request.amount ?? 1;
259
+ // No counter yet. A draw that cannot fit even an empty one is refused here, with no row: a
260
+ // zero counter for it would open its period, and a lagging draw would then spend that one.
261
+ if (amount > request.limit) {
262
+ return { allowed: false, used: 0, warned: false, periodStartMs: request.periodStartMs };
263
+ }
264
+ const opened = (
265
+ await exec.query<CounterRow>(SQL_METER_OPEN_KEYED, [
266
+ ...keyParams(request, request.periodStartMs),
267
+ amount,
268
+ drawKey,
269
+ ])
270
+ )[0];
271
+ if (opened !== undefined) {
272
+ return {
273
+ allowed: true,
274
+ used: Number(opened.used),
275
+ warned: isTrue(opened.warned),
276
+ periodStartMs: request.periodStartMs,
277
+ };
278
+ }
279
+ const raced = (await exec.query<KeyedRow>(SQL_METER_DRAW_KEYED, params))[0];
280
+ if (raced === undefined) {
281
+ throw new InternalError({
282
+ cause: `x_meter lost the counter row for meter "${request.meter}" right after it was inserted; something outside the meter store deletes x_meter rows`,
283
+ fix: 'grep -rnE "(delete from|truncate) x_meter" . # the boot owns x_meter: remove the statement that deletes its rows',
284
+ });
285
+ }
286
+ return raced;
287
+ };
288
+
289
+ const drawKeyed = async (request: MeterDraw, drawKey: string): Promise<MeterDrawResult> => {
290
+ const row = await lockedDraw(request, drawKey, [
291
+ ...keyParams(request, request.periodStartMs),
292
+ request.limit,
293
+ request.amount ?? 1,
294
+ drawKey,
295
+ iso(previousPeriodStart(request.period, request.periodStartMs)),
296
+ periodInterval(request.period),
297
+ ]);
298
+ if (!('effective_ms' in row)) return row;
299
+ const periodStartMs = Number(row.effective_ms);
300
+ if (row.counted_used !== null) {
301
+ return {
302
+ allowed: true,
303
+ used: Number(row.counted_used),
304
+ warned: row.counted_warned !== null && isTrue(row.counted_warned),
305
+ periodStartMs,
306
+ };
307
+ }
308
+ const at = { used: Number(row.used), warned: isTrue(row.warned), periodStartMs };
309
+ // Within the limit yet not counted: the claim met this key, already counted. Past it: `seen`.
310
+ if (isTrue(row.within) || (row.seen !== null && isTrue(row.seen))) {
311
+ return { allowed: true, ...at, replayed: true };
312
+ }
313
+ return { allowed: false, ...at };
314
+ };
315
+
101
316
  return {
102
317
  scope: 'shared',
318
+ keyedDraws: true,
103
319
 
104
320
  async draw(request: MeterDraw): Promise<MeterDrawResult> {
321
+ if (request.drawKey !== undefined) return drawKeyed(request, request.drawKey);
105
322
  const rows = await exec.query<CounterRow>(SQL_METER_DRAW, [
106
323
  ...keyParams(request, request.periodStartMs),
107
324
  request.limit,
325
+ request.amount ?? 1,
108
326
  ]);
109
327
  const row = rows[0];
110
328
  if (row !== undefined) {
@@ -21,6 +21,15 @@ export interface MeterDraw extends MeterKey {
21
21
  readonly periodStartMs: number;
22
22
  /** The allowance for THIS call, resolved by the caller: a plan change applies at once. */
23
23
  readonly limit: number;
24
+ /** Units this draw adds, a positive safe integer; absent is `1`: a `meter:` counts calls. */
25
+ readonly amount?: number;
26
+ /**
27
+ * The draw's idempotency key (`drawMeter`'s `key`). A second draw under it, in the period it
28
+ * counted in or the next, adds nothing and answers `replayed: true`; a refused draw leaves no
29
+ * key behind, so its retry is judged afresh. "The period it counted in" is the counter's: a
30
+ * lagging draw added to a counter already in the next period counted in that one.
31
+ */
32
+ readonly drawKey?: string;
24
33
  }
25
34
 
26
35
  export interface MeterDrawResult {
@@ -30,14 +39,30 @@ export interface MeterDrawResult {
30
39
  readonly used: number;
31
40
  /** Whether this period's warning was already claimed. */
32
41
  readonly warned: boolean;
42
+ /** `true` when `drawKey` had already counted: `allowed`, and nothing was added. */
43
+ readonly replayed?: boolean;
44
+ /**
45
+ * The effective period for the returned count and reset: the later of the request's period and
46
+ * the stored counter's. A replay or a refusal need not advance the stored counter. Required on a
47
+ * keyed draw whose effective period is later than the request's (a lagging replica drawing on a
48
+ * counter already in the next period); absent, callers use the request's `periodStartMs`.
49
+ */
50
+ readonly periodStartMs?: number;
33
51
  }
34
52
 
35
53
  export interface MeterStore {
36
54
  /** Declared, never inferred: a driver knows where its counters live. */
37
55
  readonly scope: 'process' | 'shared';
38
56
  /**
39
- * Count one call, atomically, only while the count stays within `limit`: never a read followed
40
- * by a write, so N parallel draws at the edge admit exactly the remainder.
57
+ * `true` when `draw` adds `amount` and remembers `drawKey`, as `drawMeter` needs. A store written
58
+ * before either field existed counts one call per draw and never replays, so `drawMeter` refuses
59
+ * a store that does not declare it (`X_METER_INVALID`) rather than undercount in silence.
60
+ */
61
+ readonly keyedDraws?: boolean;
62
+ /**
63
+ * Count `amount` (one call when absent), atomically, only while the count stays within `limit`:
64
+ * never a read followed by a write, so N parallel draws at the edge admit exactly the remainder.
65
+ * Under a `drawKey`, N parallel draws with that key — on any replica — add it once.
41
66
  */
42
67
  draw(request: MeterDraw): Promise<MeterDrawResult>;
43
68
  /** Claim this period's warning. `true` for exactly one caller per period. */
package/src/meter.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  import type { Ctx } from '@ultimat3/core';
8
8
  import { renderCauseValue } from '@ultimat3/core';
9
9
  import { type Infer, t } from '@ultimat3/schema';
10
+ import type { MeterSite } from './errors-meter';
10
11
  import { MeterInvalidError } from './errors-meter';
11
12
 
12
13
  /** The periods a meter resets on. Boundaries are UTC (`meter-period.ts`), and the key says so. */
@@ -86,16 +87,27 @@ const isMeterPeriod = (value: unknown): value is MeterPeriod =>
86
87
  export const isMeterLimit = (value: unknown): value is number =>
87
88
  typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
88
89
 
89
- /** At `action()`: a meter that could not be counted is refused where it is written. */
90
- export function assertMeterDeclaration(meter: ActionMeter): void {
91
- const name: unknown = meter.name;
90
+ /** The counter's name and period, checked where either is written: `action()` or `drawMeter`. */
91
+ export function assertMeterCounter(
92
+ name: unknown,
93
+ period: unknown,
94
+ site: MeterSite,
95
+ ): asserts name is string {
92
96
  if (typeof name !== 'string' || name.length > METER_NAME_MAX || !METER_NAME.test(name)) {
93
97
  const shown = typeof name === 'string' ? name : renderCauseValue(name);
94
- throw new MeterInvalidError(shown, 'name', 'a camelCase identifier of at most 64 chars');
98
+ const expected = 'a camelCase identifier of at most 64 chars';
99
+ throw new MeterInvalidError(shown, 'name', expected, undefined, site);
95
100
  }
96
- if (!isMeterPeriod(meter.period)) {
97
- throw new MeterInvalidError(name, 'period', `one of ${METER_PERIODS.join(' | ')}`);
101
+ if (!isMeterPeriod(period)) {
102
+ const expected = `one of ${METER_PERIODS.join(' | ')}`;
103
+ throw new MeterInvalidError(name, 'period', expected, undefined, site);
98
104
  }
105
+ }
106
+
107
+ /** At `action()`: a meter that could not be counted is refused where it is written. */
108
+ export function assertMeterDeclaration(meter: ActionMeter): void {
109
+ const name: unknown = meter.name;
110
+ assertMeterCounter(name, meter.period, 'action');
99
111
  if (typeof meter.limit !== 'function' && !isMeterLimit(meter.limit)) {
100
112
  throw new MeterInvalidError(name, 'limit', 'a whole number of calls, 0 or more');
101
113
  }