@procedures/client 0.15.0 → 0.15.1
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/CHANGELOG.md +60 -0
- package/dist/.tsbuildinfo +1 -1
- package/dist/adapters/http/server/handler.d.ts.map +1 -1
- package/dist/adapters/http/server/handler.js +5 -3
- package/dist/adapters/http/server/handler.js.map +1 -1
- package/dist/browser.d.ts +2 -1
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/client/errors/registry.d.ts.map +1 -1
- package/dist/client/errors/registry.js +12 -0
- package/dist/client/errors/registry.js.map +1 -1
- package/dist/client/middleware/rate-limit.d.ts +17 -0
- package/dist/client/middleware/rate-limit.d.ts.map +1 -1
- package/dist/client/middleware/rate-limit.js +94 -39
- package/dist/client/middleware/rate-limit.js.map +1 -1
- package/dist/events/index.d.ts +1 -0
- package/dist/events/index.d.ts.map +1 -1
- package/dist/events/index.js.map +1 -1
- package/dist/events/publisher.d.ts +46 -1
- package/dist/events/publisher.d.ts.map +1 -1
- package/dist/events/publisher.js +95 -5
- package/dist/events/publisher.js.map +1 -1
- package/dist/events/recheck.d.ts +84 -0
- package/dist/events/recheck.d.ts.map +1 -0
- package/dist/events/recheck.js +135 -0
- package/dist/events/recheck.js.map +1 -0
- package/dist/protocol.d.ts +1 -1
- package/dist/protocol.d.ts.map +1 -1
- package/dist/protocol.js +1 -0
- package/dist/protocol.js.map +1 -1
- package/dist/server/host-policy.d.ts +17 -0
- package/dist/server/host-policy.d.ts.map +1 -1
- package/dist/server/host-policy.js +7 -0
- package/dist/server/host-policy.js.map +1 -1
- package/dist/server/limits.d.ts +122 -0
- package/dist/server/limits.d.ts.map +1 -0
- package/dist/server/limits.js +153 -0
- package/dist/server/limits.js.map +1 -0
- package/dist/server/procedure-server.d.ts +31 -1
- package/dist/server/procedure-server.d.ts.map +1 -1
- package/dist/server/procedure-server.js +38 -2
- package/dist/server/procedure-server.js.map +1 -1
- package/dist/server/request-auth.d.ts +5 -1
- package/dist/server/request-auth.d.ts.map +1 -1
- package/dist/server/request-auth.js +19 -2
- package/dist/server/request-auth.js.map +1 -1
- package/package.json +3 -3
- package/src/adapters/http/server/handler.ts +5 -3
- package/src/browser.ts +4 -0
- package/src/client/errors/registry.ts +13 -0
- package/src/client/middleware/rate-limit.ts +116 -41
- package/src/events/index.ts +1 -0
- package/src/events/publisher.ts +116 -6
- package/src/events/recheck.ts +182 -0
- package/src/protocol.ts +3 -1
- package/src/server/host-policy.ts +22 -0
- package/src/server/limits.ts +254 -0
- package/src/server/procedure-server.ts +55 -3
- package/src/server/request-auth.ts +19 -2
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The limits of the calls of a server (CLI-40): one admission step for each face.
|
|
3
|
+
*
|
|
4
|
+
* A limit is data: a key over the call, the calls that it covers, a limit policy, a store and a
|
|
5
|
+
* bound on its keys. Each limit is a keyed limiter of `@mark1russell7/service/limiter` (SYS-28) on
|
|
6
|
+
* the clock of the server. The server takes one unit of each limit that covers a call, after the
|
|
7
|
+
* authentication and before the run. Thus the key can read the principal of the call. It takes the
|
|
8
|
+
* units in the sequence of the limits, and the first refusal stops the call. A limit before the
|
|
9
|
+
* refusal keeps its unit: the server does not give it back.
|
|
10
|
+
*
|
|
11
|
+
* A refusal is `RATE_LIMITED` (retryable), with the wait in the metadata key `retry-after` (in
|
|
12
|
+
* milliseconds) and the cause in `reason` (`limit`, `cap` or `store`). The HTTP face answers 429
|
|
13
|
+
* with `Retry-After` in whole seconds. The WebSocket face and the MCP face give the same code and
|
|
14
|
+
* the same wait. The work did not start, so a retry after the wait is safe.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { valueIn } from "@mark1russell7/quantity";
|
|
18
|
+
import {
|
|
19
|
+
keyedLimiter,
|
|
20
|
+
memoryStore,
|
|
21
|
+
retryAfterSeconds,
|
|
22
|
+
type KeyedLimiter,
|
|
23
|
+
type LimitPolicy,
|
|
24
|
+
type LimiterEviction,
|
|
25
|
+
type LimiterStore,
|
|
26
|
+
type LimiterStoreSpec,
|
|
27
|
+
type Refused,
|
|
28
|
+
} from "@mark1russell7/service/limiter";
|
|
29
|
+
import type { Clock } from "../clock.js";
|
|
30
|
+
import { effectsOf, isReadOnly } from "../procedures/capability.js";
|
|
31
|
+
import { pathToKey, type Effects, type ProcedurePath } from "../procedures/types.js";
|
|
32
|
+
import { exposePatterns } from "./host-policy.js";
|
|
33
|
+
import type { Principal, ServerRequest, ServerResponse } from "./types.js";
|
|
34
|
+
|
|
35
|
+
/** The facts of a call that a limit reads. The server gives them after the authentication of the call. */
|
|
36
|
+
export interface LimitedCall {
|
|
37
|
+
/** The path of the procedure of the call. */
|
|
38
|
+
readonly path: ProcedurePath;
|
|
39
|
+
/** The route of the call: the key of its procedure, for example `collections.notes.set`. */
|
|
40
|
+
readonly route: string;
|
|
41
|
+
/** The effects that the procedure declares, or undefined when it declares none. */
|
|
42
|
+
readonly effects: Effects | undefined;
|
|
43
|
+
/** True when the procedure can change data: its effects do not say `writes: []`. A procedure without effects can change data. */
|
|
44
|
+
readonly writes: boolean;
|
|
45
|
+
/** The principal of the call: from the request hook, the token check or the authenticate function. Undefined for a call without one. */
|
|
46
|
+
readonly principal: Principal | undefined;
|
|
47
|
+
/** The request. Its payload and its metadata come from the caller, thus a key from them is a claim of the caller. */
|
|
48
|
+
readonly request: ServerRequest<unknown>;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* A part of the key of a limit, as data:
|
|
53
|
+
* - `principal`: the id of the principal of the call.
|
|
54
|
+
* - `route`: the key of the procedure of the call.
|
|
55
|
+
* - `{ claim }`: a claim of the principal, for example `{ claim: "tenant" }`. A string or a number.
|
|
56
|
+
*/
|
|
57
|
+
export type CallLimitKeyPart = "principal" | "route" | { readonly claim: string };
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The key of a limit: one part, a list of parts, or a function of the call. A call whose key has
|
|
61
|
+
* no value (a part without a value, or a function that gives undefined) is outside the limit.
|
|
62
|
+
*/
|
|
63
|
+
export type CallLimitKey = CallLimitKeyPart | readonly CallLimitKeyPart[] | ((call: LimitedCall) => string | undefined);
|
|
64
|
+
|
|
65
|
+
/** The calls that a limit covers, as data. Each given field must agree. Without a field, the limit covers each call. */
|
|
66
|
+
export interface CallLimitCovers {
|
|
67
|
+
/** True: only the calls of a procedure that can change data. False: only the calls of a procedure that changes nothing. */
|
|
68
|
+
readonly writes?: boolean | undefined;
|
|
69
|
+
/** Only the calls of these procedures: an exact key (`notes.set`), a prefix (`collections.*`) or `*`. */
|
|
70
|
+
readonly routes?: readonly string[] | undefined;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* A limit of the calls of a server (CLI-40): a keyed limiter of `@mark1russell7/service/limiter`
|
|
75
|
+
* with a key over the call. The policy, the store and the bound on the keys have no defaults, as
|
|
76
|
+
* in the spec of a keyed limiter (`LimiterSpec`).
|
|
77
|
+
*/
|
|
78
|
+
export interface CallLimit {
|
|
79
|
+
/** The name of the limiter. It is unique in the service: `svc.limiter()` declares the limiter with this name. */
|
|
80
|
+
readonly name: string;
|
|
81
|
+
/** The key of each call: who or what the limit counts. */
|
|
82
|
+
readonly key: CallLimitKey;
|
|
83
|
+
/**
|
|
84
|
+
* The text of the key in the declaration of the service (`LimiterSpec.key`), for example
|
|
85
|
+
* `tenant`. The default names the parts of the key, or `call` for a function.
|
|
86
|
+
*/
|
|
87
|
+
readonly keyName?: string | undefined;
|
|
88
|
+
/** The calls that the limit covers: the fields of `CallLimitCovers`, or a function of the call. Without it, each call. */
|
|
89
|
+
readonly covers?: CallLimitCovers | ((call: LimitedCall) => boolean) | undefined;
|
|
90
|
+
/** The policy: a token bucket or a sliding window. */
|
|
91
|
+
readonly policy: LimitPolicy;
|
|
92
|
+
/**
|
|
93
|
+
* The store of the counts. `{ kind: "local" }`: the memory of this replica. `{ kind: "shared",
|
|
94
|
+
* dependency, onStoreFailure }`: the store of `limitStores` with the name of the dependency.
|
|
95
|
+
*/
|
|
96
|
+
readonly store: LimiterStoreSpec;
|
|
97
|
+
/** The bound on the keys that the store holds. */
|
|
98
|
+
readonly evict: LimiterEviction;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The refusal of a call by one limit. */
|
|
102
|
+
export interface CallLimitRefusal {
|
|
103
|
+
/** The name of the limit that refused the call. */
|
|
104
|
+
readonly limit: string;
|
|
105
|
+
readonly refused: Refused;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The limits of one server, as runtime: one keyed limiter for each limit. */
|
|
109
|
+
export interface CallLimiter {
|
|
110
|
+
/** The keyed limiters, in the sequence of the limits. A host declares each one with `svc.limiter(name, spec)`. */
|
|
111
|
+
readonly limiters: readonly KeyedLimiter[];
|
|
112
|
+
/**
|
|
113
|
+
* This method takes one unit of each limit that covers the call, in the sequence of the limits.
|
|
114
|
+
* It gives the first refusal, or undefined. A limit before the refusal keeps its unit.
|
|
115
|
+
*/
|
|
116
|
+
admit(call: LimitedCall): Promise<CallLimitRefusal | undefined>;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** The options of `callLimiter()`. */
|
|
120
|
+
export interface CallLimiterOptions {
|
|
121
|
+
/** The clock of the local store: give the clock of the server. */
|
|
122
|
+
readonly clock: Clock;
|
|
123
|
+
/** The stores that the replicas share, by the name of their dependency. */
|
|
124
|
+
readonly stores?: Readonly<Record<string, LimiterStore>> | undefined;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The metadata key of the wait of a refusal, in milliseconds (the same key as `retry-after` of wire v1). */
|
|
128
|
+
const RETRY_AFTER = "retry-after";
|
|
129
|
+
|
|
130
|
+
/** This function tells if a key is a list of parts. */
|
|
131
|
+
function isPartList(key: CallLimitKey): key is readonly CallLimitKeyPart[] {
|
|
132
|
+
return Array.isArray(key);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** The value of one part of a key, or undefined. */
|
|
136
|
+
function partValue(part: CallLimitKeyPart, call: LimitedCall): string | undefined {
|
|
137
|
+
if (part === "principal") return call.principal?.id;
|
|
138
|
+
if (part === "route") return call.route;
|
|
139
|
+
const value = call.principal?.claims?.[part.claim];
|
|
140
|
+
return typeof value === "string" ? value : typeof value === "number" && Number.isFinite(value) ? String(value) : undefined;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The text of one part of a key, for the declaration of the service. */
|
|
144
|
+
function partName(part: CallLimitKeyPart): string {
|
|
145
|
+
return typeof part === "string" ? part : part.claim;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** This function gives the function of the key of a limit. A list of parts gives the JSON of the values. */
|
|
149
|
+
function keyFunction(key: CallLimitKey): (call: LimitedCall) => string | undefined {
|
|
150
|
+
if (typeof key === "function") return key;
|
|
151
|
+
const parts = isPartList(key) ? key : [key];
|
|
152
|
+
if (parts.length === 0) throw new Error("A key of a limit needs one part or more");
|
|
153
|
+
return (call) => {
|
|
154
|
+
const values: string[] = [];
|
|
155
|
+
for (const part of parts) {
|
|
156
|
+
const value = partValue(part, call);
|
|
157
|
+
if (value === undefined) return undefined;
|
|
158
|
+
values.push(value);
|
|
159
|
+
}
|
|
160
|
+
return values.length === 1 ? values[0] : JSON.stringify(values);
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** The text of the key of a limit, for the declaration of the service. */
|
|
165
|
+
function keyNameOf(limit: CallLimit): string {
|
|
166
|
+
if (limit.keyName !== undefined) return limit.keyName;
|
|
167
|
+
if (typeof limit.key === "function") return "call";
|
|
168
|
+
return (isPartList(limit.key) ? limit.key : [limit.key]).map(partName).join("+");
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** This function gives the function that tells if a limit covers a call. */
|
|
172
|
+
function coversFunction(covers: CallLimit["covers"]): (call: LimitedCall) => boolean {
|
|
173
|
+
if (covers === undefined) return () => true;
|
|
174
|
+
if (typeof covers === "function") return covers;
|
|
175
|
+
const { writes, routes } = covers;
|
|
176
|
+
const routeRule = routes === undefined ? undefined : exposePatterns(routes);
|
|
177
|
+
return (call) => (writes === undefined || call.writes === writes) && (routeRule === undefined || routeRule(call.path));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** This function gives the store of a limit: the local store, or the shared store of its dependency. */
|
|
181
|
+
function storeOf(limit: CallLimit, local: LimiterStore, stores: Readonly<Record<string, LimiterStore>>): LimiterStore {
|
|
182
|
+
const spec = limit.store as LimiterStoreSpec | undefined;
|
|
183
|
+
if (spec === undefined || spec.kind !== "shared") return local;
|
|
184
|
+
const store = Object.prototype.hasOwnProperty.call(stores, spec.dependency) ? stores[spec.dependency] : undefined;
|
|
185
|
+
if (store === undefined) {
|
|
186
|
+
throw new Error(`The limit ${limit.name} keeps its counts in the shared store ${spec.dependency}, and limitStores has no store with that name`);
|
|
187
|
+
}
|
|
188
|
+
return store;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* This function makes the runtime of the limits of a server: one keyed limiter for each limit. The
|
|
193
|
+
* local limits share one memory store on the clock of the options. It refuses two limits with one
|
|
194
|
+
* name, a limit with a problem in its spec, and a shared store that `stores` does not have.
|
|
195
|
+
*/
|
|
196
|
+
export function callLimiter(limits: readonly CallLimit[], options: CallLimiterOptions): CallLimiter {
|
|
197
|
+
const local = memoryStore(options.clock);
|
|
198
|
+
const stores = options.stores ?? {};
|
|
199
|
+
const names = new Set<string>();
|
|
200
|
+
const entries = limits.map((limit) => {
|
|
201
|
+
if (names.has(limit.name)) throw new Error(`Two limits have the name ${limit.name}: the name of a limit is unique`);
|
|
202
|
+
names.add(limit.name);
|
|
203
|
+
const keyOf = keyFunction(limit.key);
|
|
204
|
+
const covers = coversFunction(limit.covers);
|
|
205
|
+
const limiter = keyedLimiter(limit.name, { key: keyNameOf(limit), policy: limit.policy, store: limit.store, evict: limit.evict }, storeOf(limit, local, stores));
|
|
206
|
+
return { limiter, keyOf, covers };
|
|
207
|
+
});
|
|
208
|
+
return {
|
|
209
|
+
limiters: entries.map((entry) => entry.limiter),
|
|
210
|
+
async admit(call) {
|
|
211
|
+
for (const { limiter, keyOf, covers } of entries) {
|
|
212
|
+
if (!covers(call)) continue;
|
|
213
|
+
const key = keyOf(call);
|
|
214
|
+
if (key === undefined) continue;
|
|
215
|
+
const decision = await limiter.take(key);
|
|
216
|
+
if (!decision.allowed) return { limit: limiter.name, refused: decision };
|
|
217
|
+
}
|
|
218
|
+
return undefined;
|
|
219
|
+
},
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** This function gives the facts of a call for the limits: its procedure, its effects, its principal and its request. */
|
|
224
|
+
export function limitedCall(procedure: { readonly path: ProcedurePath; readonly metadata?: unknown }, request: ServerRequest<unknown>): LimitedCall {
|
|
225
|
+
const effects = effectsOf(procedure);
|
|
226
|
+
return {
|
|
227
|
+
path: procedure.path,
|
|
228
|
+
route: pathToKey(procedure.path),
|
|
229
|
+
effects,
|
|
230
|
+
writes: !isReadOnly(effects),
|
|
231
|
+
principal: request.principal,
|
|
232
|
+
request,
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* This function gives the response of a refused call: `RATE_LIMITED`, retryable, with the wait in
|
|
238
|
+
* `retry-after` (milliseconds) and the cause in `reason`. The failure of a store stays on the server.
|
|
239
|
+
*/
|
|
240
|
+
export function rateLimitedResponse(id: string, refusal: CallLimitRefusal): ServerResponse<unknown> {
|
|
241
|
+
const { limit, refused } = refusal;
|
|
242
|
+
const waitMs = valueIn(refused.retryAfter, "ms");
|
|
243
|
+
const seconds = retryAfterSeconds(refused.retryAfter);
|
|
244
|
+
return {
|
|
245
|
+
id,
|
|
246
|
+
status: {
|
|
247
|
+
type: "error",
|
|
248
|
+
code: "RATE_LIMITED",
|
|
249
|
+
message: `The limit ${limit} of the host refuses the call (${refused.cause}): retry after ${seconds} s`,
|
|
250
|
+
retryable: true,
|
|
251
|
+
},
|
|
252
|
+
metadata: { [RETRY_AFTER]: waitMs, reason: refused.cause },
|
|
253
|
+
};
|
|
254
|
+
}
|
|
@@ -33,6 +33,8 @@ import { getGlobalEventBus } from "../events/bus.js";
|
|
|
33
33
|
import type { CollectionProceduresOptions } from "../procedures/collection/procedures.js";
|
|
34
34
|
import type { NarrowingNote } from "../procedures/narrowing.js";
|
|
35
35
|
import type { ServerDebugReport } from "./types.js";
|
|
36
|
+
import type { KeyedLimiter, LimiterStore } from "@mark1russell7/service/limiter";
|
|
37
|
+
import { callLimiter, limitedCall, rateLimitedResponse, type CallLimit, type CallLimiter } from "./limits.js";
|
|
36
38
|
|
|
37
39
|
// =============================================================================
|
|
38
40
|
// Types
|
|
@@ -169,7 +171,8 @@ export interface ProcedureServerOptions extends ServerOptions {
|
|
|
169
171
|
* The remote events of the server (`documentation/EVENTS.md`): a bus and its topic rule, or an
|
|
170
172
|
* `EventPublisher`. The server pins the procedure `events.subscribe`, outside its registry, so a
|
|
171
173
|
* peer can subscribe to the topics. The procedures of the server get this bus as `ctx.bus`.
|
|
172
|
-
* `stop()` ends each subscription first, with `UNAVAILABLE`.
|
|
174
|
+
* `stop()` ends each subscription first, with `UNAVAILABLE`. A publisher that the server makes
|
|
175
|
+
* from the options gets the clock of the server, unless the options give a clock (CLI-44).
|
|
173
176
|
*/
|
|
174
177
|
events?: EventPublisherOptions | EventPublisher | undefined;
|
|
175
178
|
|
|
@@ -181,6 +184,21 @@ export interface ProcedureServerOptions extends ServerOptions {
|
|
|
181
184
|
* @default false
|
|
182
185
|
*/
|
|
183
186
|
debug?: boolean | ((report: ServerDebugReport) => void) | undefined;
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* The limits of the calls (CLI-40). Each limit is a keyed limiter of
|
|
190
|
+
* `@mark1russell7/service/limiter` on the clock of the server. The server takes one unit of each
|
|
191
|
+
* limit that covers a call, after the authentication and before the run, for each face. A
|
|
192
|
+
* refusal is `RATE_LIMITED` with the wait in `retry-after`: HTTP 429 with `Retry-After`. Without
|
|
193
|
+
* this option, the server limits nothing.
|
|
194
|
+
*
|
|
195
|
+
* The server takes the units in the sequence of the limits, and the first refusal stops the call.
|
|
196
|
+
* A limit before the refusal keeps its unit: the server does not give it back.
|
|
197
|
+
*/
|
|
198
|
+
limits?: readonly CallLimit[] | undefined;
|
|
199
|
+
|
|
200
|
+
/** The stores that the replicas share, by the name of their dependency, for each limit with a shared store. */
|
|
201
|
+
limitStores?: Readonly<Record<string, LimiterStore>> | undefined;
|
|
184
202
|
}
|
|
185
203
|
|
|
186
204
|
/** The options of `registerProcedure()`, `registerProcedures()` and `registerModule()` (CLI-47). */
|
|
@@ -439,6 +457,8 @@ export class ProcedureServer extends Server implements RepositoryProvider, StopP
|
|
|
439
457
|
readonly ambientCredentials: AmbientCredentials | undefined;
|
|
440
458
|
/** The receiver of the debug reports, or undefined when the option `debug` is off. */
|
|
441
459
|
private readonly debugReport: ((report: ServerDebugReport) => void) | undefined;
|
|
460
|
+
/** The limits of the calls (CLI-40), or undefined without the option `limits`. */
|
|
461
|
+
private readonly callLimits: CallLimiter | undefined;
|
|
442
462
|
|
|
443
463
|
constructor(options: ProcedureServerOptions = {}) {
|
|
444
464
|
super(options);
|
|
@@ -466,9 +486,13 @@ export class ProcedureServer extends Server implements RepositoryProvider, StopP
|
|
|
466
486
|
: options.debug === true
|
|
467
487
|
? (report) => console.debug(`[ProcedureServer] ${report.topic} of ${report.requestId}: ${report.message}`)
|
|
468
488
|
: undefined;
|
|
489
|
+
// The limits of the calls: one keyed limiter for each limit, on the clock of the server (CLI-40)
|
|
490
|
+
this.callLimits = options.limits && options.limits.length > 0 ? callLimiter(options.limits, { clock: this.clock, stores: options.limitStores }) : undefined;
|
|
469
491
|
// The remote events: the server pins events.subscribe, as a host pins host.health (EVENTS.md).
|
|
470
|
-
// The topic rule is its expose rule, so the pin is always on (CLI-47).
|
|
471
|
-
|
|
492
|
+
// The topic rule is its expose rule, so the pin is always on (CLI-47). The publisher that the
|
|
493
|
+
// server makes gets the clock of the server for its re-checks (CLI-44).
|
|
494
|
+
const events = options.events;
|
|
495
|
+
this.publisher = events instanceof EventPublisher ? events : events ? new EventPublisher({ ...events, clock: events.clock ?? this.clock }) : undefined;
|
|
472
496
|
if (this.publisher) this.registerProcedure(this.publisher.procedure, { alwaysOn: true });
|
|
473
497
|
|
|
474
498
|
// Configure collections
|
|
@@ -798,6 +822,9 @@ export class ProcedureServer extends Server implements RepositoryProvider, StopP
|
|
|
798
822
|
}
|
|
799
823
|
const refusal = await this.admit(request);
|
|
800
824
|
if (refusal) return refusal;
|
|
825
|
+
// The limits come after the authentication, so a key can read the principal (CLI-40)
|
|
826
|
+
const limited = await this.limit(procedure, request);
|
|
827
|
+
if (limited) return limited;
|
|
801
828
|
this.calls++;
|
|
802
829
|
let response: ServerResponse<unknown> | undefined;
|
|
803
830
|
try {
|
|
@@ -873,6 +900,22 @@ export class ProcedureServer extends Server implements RepositoryProvider, StopP
|
|
|
873
900
|
return undefined;
|
|
874
901
|
}
|
|
875
902
|
|
|
903
|
+
/**
|
|
904
|
+
* The limits of a call (CLI-40): one unit of each limit that covers it. The function gives a
|
|
905
|
+
* `RATE_LIMITED` response, or undefined when the call passes. A key or a cover function that
|
|
906
|
+
* throws gives `INTERNAL_ERROR`, so a defect of a limit does not let a call in.
|
|
907
|
+
*/
|
|
908
|
+
private async limit(procedure: AnyProcedure, request: ServerRequest<unknown>): Promise<ServerResponse<unknown> | undefined> {
|
|
909
|
+
if (!this.callLimits) return undefined;
|
|
910
|
+
try {
|
|
911
|
+
const refused = await this.callLimits.admit(limitedCall(procedure, request));
|
|
912
|
+
return refused ? rateLimitedResponse(request.id, refused) : undefined;
|
|
913
|
+
} catch (error) {
|
|
914
|
+
const message = `The limits of the server cannot admit the call: ${error instanceof Error ? error.message : String(error)}`;
|
|
915
|
+
return errorResponse(request.id, Object.assign(new Error(message), { code: "INTERNAL_ERROR" }));
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
|
|
876
919
|
/** One call in flight ended: `drain()` can end when it was the last one. */
|
|
877
920
|
private callEnded(): void {
|
|
878
921
|
this.calls--;
|
|
@@ -1111,6 +1154,15 @@ export class ProcedureServer extends Server implements RepositoryProvider, StopP
|
|
|
1111
1154
|
return this.resolveProcedure(method);
|
|
1112
1155
|
}
|
|
1113
1156
|
|
|
1157
|
+
/**
|
|
1158
|
+
* This method gives the keyed limiters of the option `limits`, in its sequence (CLI-40). A host
|
|
1159
|
+
* declares each one on its service with `svc.limiter(limiter.name, limiter.spec)`, so
|
|
1160
|
+
* `describe()` and `lint()` see it.
|
|
1161
|
+
*/
|
|
1162
|
+
limiters(): readonly KeyedLimiter[] {
|
|
1163
|
+
return this.callLimits?.limiters ?? [];
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1114
1166
|
/**
|
|
1115
1167
|
* This function publishes an event on the bus of the server: the bus of the option `events`, or
|
|
1116
1168
|
* the global bus. Each subscription of the topic gets it (`documentation/EVENTS.md`).
|
|
@@ -40,9 +40,26 @@ export function withoutSecretHeaders(headers: Record<string, unknown>, secret?:
|
|
|
40
40
|
return out;
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
-
/** The
|
|
43
|
+
/** The start of the header that `bearerOf` read before CLI-60: the scheme `Bearer` and one space. */
|
|
44
|
+
const BEARER_PREFIX = "Bearer ";
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The other forms of a bearer credential (RFC 7235 and RFC 6750, CLI-60). Such a form has the
|
|
48
|
+
* scheme `Bearer` in any case, one or more spaces (`1*SP`) and the token. Spaces or tabs can come
|
|
49
|
+
* after the token. The token has no whitespace (`token68`). A tab is not `1*SP`.
|
|
50
|
+
*/
|
|
51
|
+
const BEARER_CREDENTIAL = /^bearer +(\S+)[ \t]*$/i;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The token of an `Authorization: Bearer <token>` header, or undefined. A header that starts
|
|
55
|
+
* with `Bearer ` gives the rest of the header, as before CLI-60. A header with the scheme in
|
|
56
|
+
* another case, for example `bearer`, gives the token after one or more spaces.
|
|
57
|
+
*/
|
|
44
58
|
export function bearerOf(header: unknown): string | undefined {
|
|
45
|
-
|
|
59
|
+
if (typeof header !== "string") return undefined;
|
|
60
|
+
// The old form keeps its old result, so each header that passed before gives the same token
|
|
61
|
+
if (header.startsWith(BEARER_PREFIX)) return header.slice(BEARER_PREFIX.length);
|
|
62
|
+
return BEARER_CREDENTIAL.exec(header)?.[1];
|
|
46
63
|
}
|
|
47
64
|
|
|
48
65
|
/**
|