@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 +1 -1
- package/README.md +11 -2
- package/package.json +9 -9
- package/src/api-declaration.ts +7 -1
- package/src/error-titles.ts +2 -2
- package/src/errors-meter.ts +65 -9
- package/src/http.ts +5 -3
- package/src/index.ts +6 -3
- package/src/invoke.ts +2 -2
- package/src/meter-draw.ts +120 -0
- package/src/meter-fifo.ts +79 -0
- package/src/meter-gate.ts +7 -3
- package/src/meter-memory.ts +136 -18
- package/src/meter-period.ts +19 -0
- package/src/meter-postgres.ts +224 -6
- package/src/meter-store.ts +27 -2
- package/src/meter.ts +18 -6
- package/src/openapi-complete.ts +45 -46
- package/src/openapi-mount-tenant.ts +129 -0
- package/src/openapi-problem.ts +48 -0
package/src/openapi-complete.ts
CHANGED
|
@@ -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(
|
|
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]:
|
|
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(
|
|
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
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// The refusal responses every projected document states the same way: one `application/problem+json`
|
|
2
|
+
// envelope, and the rate-limit headers a 429 or a limited 200 carries. One copy, so the cookie
|
|
3
|
+
// document, a bearer mount's and its tenant listing can never drift apart.
|
|
4
|
+
|
|
5
|
+
import { PROBLEM_SCHEMA_NAME, schemaRef } from './naming';
|
|
6
|
+
|
|
7
|
+
export const RATE_LIMIT_HEADERS: Record<string, unknown> = {
|
|
8
|
+
'RateLimit-Limit': {
|
|
9
|
+
description: 'Requests the bucket admits per window.',
|
|
10
|
+
schema: { type: 'integer' },
|
|
11
|
+
},
|
|
12
|
+
'RateLimit-Remaining': {
|
|
13
|
+
description: 'Requests left in the current window.',
|
|
14
|
+
schema: { type: 'integer' },
|
|
15
|
+
},
|
|
16
|
+
'RateLimit-Reset': {
|
|
17
|
+
description: 'Seconds until the bucket is full again.',
|
|
18
|
+
schema: { type: 'integer' },
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export const RETRY_AFTER_HEADER: Record<string, unknown> = {
|
|
23
|
+
'Retry-After': {
|
|
24
|
+
description: 'Seconds to wait before retrying.',
|
|
25
|
+
schema: { type: 'integer', minimum: 1 },
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/** A refusal response: its description, any headers, and the shared Problem schema. */
|
|
30
|
+
export function problem(
|
|
31
|
+
description: string,
|
|
32
|
+
headers?: Record<string, unknown>,
|
|
33
|
+
): Record<string, unknown> {
|
|
34
|
+
return {
|
|
35
|
+
description,
|
|
36
|
+
...(headers === undefined ? {} : { headers }),
|
|
37
|
+
content: { 'application/problem+json': { schema: { $ref: schemaRef(PROBLEM_SCHEMA_NAME) } } },
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The codes a 429 can carry here, named so a client knows which refusal it is reading. */
|
|
42
|
+
export function tooManyDescription(throttled: boolean, metered: boolean): string {
|
|
43
|
+
const codes = [
|
|
44
|
+
...(throttled ? ['X_RATE_LIMITED'] : []),
|
|
45
|
+
...(metered ? ['X_METER_EXCEEDED'] : []),
|
|
46
|
+
].join(' or ');
|
|
47
|
+
return `${codes} — retry after Retry-After seconds`;
|
|
48
|
+
}
|