@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.
@@ -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
  }
@@ -15,11 +15,17 @@
15
15
 
16
16
  import { toOpenApiPath } from '@ultimat3/core';
17
17
  import type { Route } from '@ultimat3/http';
18
- import { mountedPath } from '@ultimat3/http';
18
+ import { mountedPath, TENANTS_SEGMENT } from '@ultimat3/http';
19
19
  import type { ApiMount, ApiOpenApi } from './api-declaration';
20
20
  import type { JsonSchemaObject } from './json-schema';
21
- import { PROBLEM_SCHEMA_NAME, schemaRef } from './naming';
22
21
  import type { OpenApiDocument } from './openapi';
22
+ import { listingOperationId, tenantsOperation, withTenantParameter } from './openapi-mount-tenant';
23
+ import {
24
+ problem,
25
+ RATE_LIMIT_HEADERS,
26
+ RETRY_AFTER_HEADER,
27
+ tooManyDescription,
28
+ } from './openapi-problem';
23
29
 
24
30
  /** `components.securitySchemes` keys. */
25
31
  export const COOKIE_SCHEME = 'cookie';
@@ -33,36 +39,6 @@ const BEARER_SECURITY_SCHEME = {
33
39
  description: 'A token issued by the app, sent as Authorization: Bearer <token>.',
34
40
  };
35
41
 
36
- const RATE_LIMIT_HEADERS: Record<string, unknown> = {
37
- 'RateLimit-Limit': {
38
- description: 'Requests the bucket admits per window.',
39
- schema: { type: 'integer' },
40
- },
41
- 'RateLimit-Remaining': {
42
- description: 'Requests left in the current window.',
43
- schema: { type: 'integer' },
44
- },
45
- 'RateLimit-Reset': {
46
- description: 'Seconds until the bucket is full again.',
47
- schema: { type: 'integer' },
48
- },
49
- };
50
-
51
- const RETRY_AFTER_HEADER: Record<string, unknown> = {
52
- 'Retry-After': {
53
- description: 'Seconds to wait before retrying.',
54
- schema: { type: 'integer', minimum: 1 },
55
- },
56
- };
57
-
58
- function problem(description: string, headers?: Record<string, unknown>): Record<string, unknown> {
59
- return {
60
- description,
61
- ...(headers === undefined ? {} : { headers }),
62
- content: { 'application/problem+json': { schema: { $ref: schemaRef(PROBLEM_SCHEMA_NAME) } } },
63
- };
64
- }
65
-
66
42
  const lower = (method: string): string => method.toLowerCase();
67
43
 
68
44
  /** `method path` → the route that serves it, the path in the document's `{param}` spelling. */
@@ -109,15 +85,6 @@ function declares(operation: Operation, key: 'rateLimit' | 'meter'): boolean {
109
85
  return declared !== undefined && declared !== null;
110
86
  }
111
87
 
112
- /** The codes a 429 can carry here, named so a client knows which refusal it is reading. */
113
- function tooManyDescription(throttled: boolean, metered: boolean): string {
114
- const codes = [
115
- ...(throttled ? ['X_RATE_LIMITED'] : []),
116
- ...(metered ? ['X_METER_EXCEEDED'] : []),
117
- ].join(' or ');
118
- return `${codes} — retry after Retry-After seconds`;
119
- }
120
-
121
88
  /** One operation, with its route's refusals and security added. Never mutates `operation`. */
122
89
  function completeOperation(operation: Operation, route: Route | undefined, refusals: Refusals) {
123
90
  const authenticated = route?.meta.auth === 'required';
@@ -287,15 +254,39 @@ export function mountOpenApi(
287
254
  );
288
255
  const responses = {
289
256
  ...(completed['responses'] as Record<string, unknown>),
290
- '404': problem('X_ROUTE_NOT_FOUND — also the answer for a token without this scope'),
257
+ '404': problem(
258
+ mount.tenant === undefined
259
+ ? 'X_ROUTE_NOT_FOUND — also the answer for a token without this scope'
260
+ : 'X_ROUTE_NOT_FOUND — also the answer for a token without this scope, or a tenant its person is not in',
261
+ ),
291
262
  };
292
263
  const extensions = (completed['x-ultimate'] as Record<string, unknown> | undefined) ?? {};
293
264
  for (const tag of (completed['tags'] as readonly string[] | undefined) ?? []) tags.add(tag);
294
265
  unlocks.set(scope, [...(unlocks.get(scope) ?? []), route.meta.name]);
295
266
  const mounted = toOpenApiPath(mountedPath(mount.prefix, route.path));
267
+ const served = { ...completed, responses, 'x-ultimate': { ...extensions, scope } };
296
268
  mountedItems.set(mounted, {
297
269
  ...mountedItems.get(mounted),
298
- [method]: { ...completed, responses, 'x-ultimate': { ...extensions, scope } },
270
+ [method]: mount.tenant === undefined ? served : withTenantParameter(served, mount.tenant.arg),
271
+ });
272
+ }
273
+ const listing = mount.tenant === undefined ? undefined : `${mount.prefix}${TENANTS_SEGMENT}`;
274
+ if (listing !== undefined) {
275
+ // Joined, never replacing: an app's own POST at that path is served, so it stays documented.
276
+ const taken = new Set(
277
+ [...mountedItems.values()].flatMap((item) =>
278
+ Object.values(item as Record<string, Operation>).map(
279
+ (operation) => operation['operationId'],
280
+ ),
281
+ ),
282
+ );
283
+ mountedItems.set(listing, {
284
+ ...mountedItems.get(listing),
285
+ get: tenantsOperation(
286
+ BEARER_SCHEME,
287
+ mount.rateLimit !== undefined,
288
+ listingOperationId(taken),
289
+ ),
299
290
  });
300
291
  }
301
292
  const paths = Object.fromEntries(mountedItems);
@@ -307,7 +298,7 @@ export function mountOpenApi(
307
298
  paths,
308
299
  components: {
309
300
  schemas,
310
- securitySchemes: { [BEARER_SCHEME]: scopedBearerScheme(unlocks) },
301
+ securitySchemes: { [BEARER_SCHEME]: scopedBearerScheme(unlocks, listing) },
311
302
  },
312
303
  tags: [...tags].sort().map((name) => ({ name })),
313
304
  };
@@ -318,7 +309,10 @@ export function mountOpenApi(
318
309
  * is OAuth's `flows`), so they are in the description for a reader and in `x-ultimate.scopes` —
319
310
  * scope → operation names, both sorted — for a generator; each operation's requirement names one.
320
311
  */
321
- function scopedBearerScheme(unlocks: ReadonlyMap<string, readonly string[]>) {
312
+ function scopedBearerScheme(
313
+ unlocks: ReadonlyMap<string, readonly string[]>,
314
+ listing: string | undefined,
315
+ ) {
322
316
  const scopes = [...unlocks.keys()].sort();
323
317
  const table = scopes.map((scope) => [scope, [...(unlocks.get(scope) ?? [])].sort()] as const);
324
318
  const lines = table.map(([scope, names]) => `- \`${scope}\`: ${names.join(', ')}`);
@@ -326,7 +320,12 @@ function scopedBearerScheme(unlocks: ReadonlyMap<string, readonly string[]>) {
326
320
  ...BEARER_SECURITY_SCHEME,
327
321
  description: [
328
322
  BEARER_SECURITY_SCHEME.description,
329
- 'Each operation lists the one scope a token needs in its security requirement; a token without it is answered 404.',
323
+ 'Each mounted primitive operation lists the one scope a token needs in its security requirement; a token without it is answered 404.',
324
+ ...(listing === undefined
325
+ ? []
326
+ : [
327
+ `Every operation but one names its tenant in the query string; GET ${listing} needs no scope and names no tenant: any valid token lists the tenants it may name.`,
328
+ ]),
330
329
  ...(lines.length === 0 ? [] : ['', 'Scopes:', ...lines]),
331
330
  ].join('\n'),
332
331
  'x-ultimate': { scopes: Object.fromEntries(table) },
@@ -0,0 +1,129 @@
1
+ // A tenant mount's document: every operation takes the tenant as a required query parameter, says
2
+ // the 400 a call without one is answered and the 500 a failed lookup is, and the listing a caller
3
+ // learns its tenants from is a path of its own. Applied by `mountOpenApi` only when the mount
4
+ // declares `tenant`.
5
+
6
+ import { MAX_TENANT_VALUE } from '@ultimat3/http';
7
+ import {
8
+ problem,
9
+ RATE_LIMIT_HEADERS,
10
+ RETRY_AFTER_HEADER,
11
+ tooManyDescription,
12
+ } from './openapi-problem';
13
+
14
+ type Operation = Record<string, unknown>;
15
+ type Responses = Record<string, Record<string, unknown> | undefined>;
16
+
17
+ const TENANT_REQUIRED = 'X_BEARER_TENANT_REQUIRED — the call named no tenant';
18
+ const TENANT_UNRESOLVED = 'X_BEARER_TENANT_UNRESOLVED — the tenant lookup failed';
19
+
20
+ /** The values a call is resolved for: JSON Schema counts code points, as the mount does. */
21
+ const TENANT_VALUE_SCHEMA = { type: 'string', minLength: 1, maxLength: MAX_TENANT_VALUE };
22
+
23
+ /** The listing's operationId, as every document before this one named it: a client looks it up. */
24
+ export const TENANT_LISTING_OPERATION_ID = 'tenantsOfToken';
25
+ /**
26
+ * Its id when a mounted primitive is already named `tenantsOfToken`. Kebab case on purpose: a
27
+ * primitive's id is its export name, a JS identifier, which can never contain a hyphen.
28
+ */
29
+ export const TENANT_LISTING_COLLIDED_ID = 'tenants-of-token';
30
+
31
+ /** The listing's id beside the mounted operations' `taken` ids: its own, unless one carries it. */
32
+ export const listingOperationId = (taken: ReadonlySet<unknown>): string =>
33
+ taken.has(TENANT_LISTING_OPERATION_ID) ? TENANT_LISTING_COLLIDED_ID : TENANT_LISTING_OPERATION_ID;
34
+
35
+ /** `code` added to the operation's own response of that status, which keeps its words. */
36
+ const joined = (responses: Responses, status: string, description: string) => {
37
+ const own = responses[status];
38
+ return own === undefined
39
+ ? problem(description)
40
+ : { ...own, description: `${String(own['description'])}; or ${description}` };
41
+ };
42
+
43
+ /**
44
+ * The operation with `arg` as a required `in: query` parameter, the 400 its absence is answered
45
+ * and the 500 a failed lookup is. A read that already declares a query parameter of that name keeps
46
+ * its own declaration, schema and all — its handler still validates the value — made required.
47
+ */
48
+ export function withTenantParameter(operation: Operation, arg: string): Operation {
49
+ const declared = Array.isArray(operation['parameters'])
50
+ ? (operation['parameters'] as readonly Record<string, unknown>[])
51
+ : [];
52
+ const isTenant = (parameter: Record<string, unknown>) =>
53
+ parameter['in'] === 'query' && parameter['name'] === arg;
54
+ const own = declared.find(isTenant);
55
+ const responses = operation['responses'] as Responses;
56
+ return {
57
+ ...operation,
58
+ parameters: [
59
+ own === undefined
60
+ ? {
61
+ name: arg,
62
+ in: 'query',
63
+ required: true,
64
+ description: 'The tenant this call acts in: a value from the tenants listing.',
65
+ schema: TENANT_VALUE_SCHEMA,
66
+ }
67
+ : { ...own, required: true },
68
+ ...declared.filter((parameter) => !isTenant(parameter)),
69
+ ],
70
+ responses: {
71
+ ...responses,
72
+ // The operation's own 400 (an action's `X_INPUT_INVALID`) keeps its words, and gains these.
73
+ '400': joined(responses, '400', TENANT_REQUIRED),
74
+ '500': joined(responses, '500', TENANT_UNRESOLVED),
75
+ },
76
+ };
77
+ }
78
+
79
+ /**
80
+ * `GET <prefix>/tenants`: the tenants the token's person may name, any valid token, no tenant. Its
81
+ * authenticator spends the mount's per-token allowance like every mounted route, so it documents
82
+ * the same 401 challenge and 429, and with an allowance of its own the `RateLimit-*` every answer
83
+ * carries.
84
+ */
85
+ export function tenantsOperation(
86
+ scheme: string,
87
+ ownAllowance: boolean,
88
+ operationId: string,
89
+ ): Operation {
90
+ return {
91
+ operationId,
92
+ summary: 'The tenants this token may act in',
93
+ security: [{ [scheme]: [] }],
94
+ responses: {
95
+ '200': {
96
+ description: 'Each value is what a call sends as the tenant query parameter.',
97
+ ...(ownAllowance ? { headers: RATE_LIMIT_HEADERS } : {}),
98
+ content: {
99
+ 'application/json': {
100
+ schema: {
101
+ type: 'object',
102
+ required: ['tenants'],
103
+ properties: {
104
+ tenants: {
105
+ type: 'array',
106
+ items: {
107
+ type: 'object',
108
+ required: ['value'],
109
+ properties: { value: TENANT_VALUE_SCHEMA, name: { type: 'string' } },
110
+ },
111
+ },
112
+ },
113
+ },
114
+ },
115
+ },
116
+ },
117
+ '401': problem('X_UNAUTHENTICATED — no credential, or one that did not resolve', {
118
+ 'WWW-Authenticate': { description: 'Bearer', schema: { type: 'string' } },
119
+ }),
120
+ '429': problem(
121
+ tooManyDescription(true, false),
122
+ ownAllowance ? { ...RETRY_AFTER_HEADER, ...RATE_LIMIT_HEADERS } : RETRY_AFTER_HEADER,
123
+ ),
124
+ '500': problem(
125
+ 'X_BEARER_TENANT_LIST_INVALID — the listing named a value no call could send back',
126
+ ),
127
+ },
128
+ };
129
+ }