@friggframework/core 2.0.0--canary.744.e18e27f.0 → 2.0.0--canary.743.d13a976.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.
@@ -0,0 +1,785 @@
1
+ const { createHash } = require('node:crypto');
2
+ const { BUILT_IN_PARSERS, headerValue } = require('./parsers');
3
+ const {
4
+ RateLimitStateRepositoryMemory,
5
+ } = require('./state/rate-limit-state-repository-memory');
6
+ const { SLOTS_FULL } = require('./state/rate-limit-state-repository-interface');
7
+
8
+ // ADR-049 section 6: pacing. 2a is the in-process part (token buckets from
9
+ // `windows`, a block from the headers). 2b is the shared part: the block and
10
+ // the retry slots of one scope key, in Entity.data of the calling entity, for
11
+ // parallel workers.
12
+
13
+ const PACING_ENV = 'FRIGG_RATE_LIMIT_PACING';
14
+ const SHARED_CACHE_MS_ENV = 'FRIGG_RATE_LIMIT_SHARED_CACHE_MS';
15
+ const SHARED_TIMEOUT_MS_ENV = 'FRIGG_RATE_LIMIT_SHARED_TIMEOUT_MS';
16
+ const MAX_SLOT_HORIZON_MS_ENV = 'FRIGG_RATE_LIMIT_MAX_SLOT_HORIZON_MS';
17
+ const MAX_PACING_WAIT_MS_ENV = 'FRIGG_RATE_LIMIT_MAX_PACING_WAIT_MS';
18
+ const MAX_BLOCK_MS_ENV = 'FRIGG_RATE_LIMIT_MAX_BLOCK_MS';
19
+ const JITTER_MAX_MS_ENV = 'FRIGG_QUEUE_DEFERRAL_JITTER_MAX_MS';
20
+ const DEFAULT_SHARED_CACHE_MS = 1_000;
21
+ const DEFAULT_SHARED_TIMEOUT_MS = 1_000;
22
+ const DEFAULT_MAX_PACING_WAIT_MS = 5_000;
23
+ // The furthest ahead a call slot is booked, whatever the caller's budget (an
24
+ // HTTP handler or a script can wait much longer than a queue worker).
25
+ const DEFAULT_MAX_SLOT_HORIZON_MS = 5_000;
26
+ // Call slots are used for windows up to this long. A longer window (100 per
27
+ // minute, a daily quota) would space calls seconds apart; it keeps the
28
+ // in-process bucket and the 429 path, unless `sharedCalls: true`.
29
+ const MAX_CALL_WINDOW_MS = 60_000;
30
+ // While the shared store fails, each process runs at limit / this (or
31
+ // limit / maxConcurrency), not at the full rate: a database stall hits every
32
+ // worker at once.
33
+ const DEFAULT_DEGRADED_SHARE = 10;
34
+ // A block stops every call on a key. A longer limit (a daily quota) is left to
35
+ // the next call: its 429 defers that one message with the provider's time.
36
+ const DEFAULT_MAX_BLOCK_MS = 15 * 60 * 1000;
37
+ const DEFAULT_JITTER_MAX_MS = 5 * 60 * 1000;
38
+ const SHARED_FAILURE_PAUSE_MS = 5_000;
39
+ // A block that moves by less than this is not written again to the store.
40
+ const MIN_SHARED_BLOCK_STEP_MS = 250;
41
+ // The SQS delay range: a paced retry that can come back inside it stays in it.
42
+ const MAX_PACED_RETRY_MS = 900 * 1000;
43
+ // The most that one caller waits past the end of a block, at random.
44
+ const MAX_RELEASE_JITTER_MS = 1_000;
45
+ // A retry without a known rate spreads over at least this time.
46
+ const MIN_RETRY_SPREAD_MS = 1_000;
47
+ const HEADER_PARSERS = ['ietf', 'resetHeaders'];
48
+ const MAX_SCOPES = 10_000;
49
+ const FAILURE_METRIC = 'frigg.rate_limit.shared_state_failures';
50
+
51
+ const toNonNegativeInteger = (value) => {
52
+ if (value === undefined || value === null || value === '') return undefined;
53
+ const number = Number(value);
54
+ return Number.isInteger(number) && number >= 0 ? number : undefined;
55
+ };
56
+
57
+ const readMs = (env, name, fallback) =>
58
+ toNonNegativeInteger(env[name]) ?? fallback;
59
+
60
+ function pacingEnabled(env = process.env) {
61
+ const value = String(env[PACING_ENV] ?? '').toLowerCase();
62
+ return !['off', 'false', '0', 'disabled'].includes(value);
63
+ }
64
+
65
+ const maxPacingWaitMs = (env = process.env) =>
66
+ readMs(env, MAX_PACING_WAIT_MS_ENV, DEFAULT_MAX_PACING_WAIT_MS);
67
+ const sharedCacheMs = (env = process.env) =>
68
+ readMs(env, SHARED_CACHE_MS_ENV, DEFAULT_SHARED_CACHE_MS);
69
+ const sharedTimeoutMs = (env = process.env) =>
70
+ readMs(env, SHARED_TIMEOUT_MS_ENV, DEFAULT_SHARED_TIMEOUT_MS);
71
+ const maxBlockMs = (env = process.env) =>
72
+ readMs(env, MAX_BLOCK_MS_ENV, DEFAULT_MAX_BLOCK_MS);
73
+ const jitterMaxMs = (env = process.env) =>
74
+ readMs(env, JITTER_MAX_MS_ENV, DEFAULT_JITTER_MAX_MS);
75
+ const maxSlotHorizonMs = (env = process.env) =>
76
+ readMs(env, MAX_SLOT_HORIZON_MS_ENV, DEFAULT_MAX_SLOT_HORIZON_MS);
77
+
78
+ /**
79
+ * A stable, short, one-way id for a scope value that must not be stored or
80
+ * logged, such as an API key. For a module whose provider counts per key:
81
+ * `scope: (api) => hashRateLimitScope(api.api_key)`.
82
+ */
83
+ function hashRateLimitScope(value) {
84
+ if (value === undefined || value === null || value === '') return undefined;
85
+ return createHash('sha256')
86
+ .update(String(value))
87
+ .digest('hex')
88
+ .slice(0, 32);
89
+ }
90
+
91
+ /** The windows of a policy that a token bucket can enforce. */
92
+ function bucketWindows(policy) {
93
+ if (!Array.isArray(policy?.windows)) return [];
94
+ return policy.windows.filter(
95
+ (window) =>
96
+ window &&
97
+ Number.isFinite(window.limit) &&
98
+ window.limit > 0 &&
99
+ Number.isFinite(window.perMs) &&
100
+ window.perMs > 0
101
+ );
102
+ }
103
+
104
+ /**
105
+ * The provider's burst quota from an IETF `RateLimit-Policy` header, as the
106
+ * time one request uses: `w` seconds over `q` requests. With several policies
107
+ * the shortest window wins: retry slots follow the burst rate, and a longer
108
+ * quota shows up as `remaining: 0` and a block. Example:
109
+ * `"per-second"; q=10; w=1` gives 100 ms.
110
+ */
111
+ function intervalFromPolicyHeader(headers) {
112
+ const raw = headerValue(headers, 'ratelimit-policy');
113
+ if (raw === undefined) return undefined;
114
+ let best;
115
+ for (const item of raw.split(',')) {
116
+ const q = Number(/(?:^|;)\s*q\s*=\s*(\d+(?:\.\d+)?)/.exec(item)?.[1]);
117
+ const w = Number(/(?:^|;)\s*w\s*=\s*(\d+(?:\.\d+)?)/.exec(item)?.[1]);
118
+ if (q > 0 && w > 0 && (best === undefined || w < best.w)) {
119
+ best = { q, w };
120
+ }
121
+ }
122
+ return best ? (best.w * 1000) / best.q : undefined;
123
+ }
124
+
125
+ function shortestWindow(policy) {
126
+ const windows = bucketWindows(policy);
127
+ if (windows.length === 0) return undefined;
128
+ return windows.reduce((a, b) => (b.perMs < a.perMs ? b : a));
129
+ }
130
+
131
+ /** The interval of the window with the shortest period. */
132
+ function intervalFromWindows(policy) {
133
+ const shortest = shortestWindow(policy);
134
+ return shortest ? shortest.perMs / shortest.limit : undefined;
135
+ }
136
+
137
+ /** `burst` of a window: calls allowed at once (GCRA), 1 to `limit`. */
138
+ function windowBurst(window) {
139
+ const burst = window?.burst;
140
+ if (!Number.isInteger(burst) || burst < 1) return 1;
141
+ return Math.min(burst, window.limit);
142
+ }
143
+
144
+ class TokenBucket {
145
+ constructor({ limit, perMs, ratePerMs }, now) {
146
+ this.capacity = limit;
147
+ this.ratePerMs = ratePerMs ?? limit / perMs;
148
+ this.tokens = limit;
149
+ this.updatedAt = now;
150
+ }
151
+
152
+ _refill(now) {
153
+ if (now <= this.updatedAt) return;
154
+ this.tokens = Math.min(
155
+ this.capacity,
156
+ this.tokens + (now - this.updatedAt) * this.ratePerMs
157
+ );
158
+ this.updatedAt = now;
159
+ }
160
+
161
+ waitMs(now) {
162
+ this._refill(now);
163
+ return this.tokens >= 1
164
+ ? 0
165
+ : Math.ceil((1 - this.tokens) / this.ratePerMs);
166
+ }
167
+
168
+ // The token can be one in the future: the caller sleeps until it exists.
169
+ take() {
170
+ this.tokens -= 1;
171
+ }
172
+ }
173
+
174
+ class StoreTimeoutError extends Error {
175
+ constructor(operation, ms) {
176
+ super(`rate-limit store ${operation} took more than ${ms} ms`);
177
+ this.name = 'StoreTimeoutError';
178
+ }
179
+ }
180
+
181
+ function withTimeout(promise, ms, operation) {
182
+ if (!(ms > 0)) return promise;
183
+ let timer;
184
+ const timeout = new Promise((_, reject) => {
185
+ timer = setTimeout(
186
+ () => reject(new StoreTimeoutError(operation, ms)),
187
+ ms
188
+ );
189
+ timer.unref?.();
190
+ });
191
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
192
+ }
193
+
194
+ function defaultLogger() {
195
+ return require('../../../logs').getLogger('frigg.rate_limit');
196
+ }
197
+
198
+ function defaultTelemetry() {
199
+ return require('../../../telemetry/telemetry-runtime').getTelemetry();
200
+ }
201
+
202
+ class RateLimitPacer {
203
+ /**
204
+ * @param {Object} [options]
205
+ * @param {Object} [options.localStore] in-process state (default: memory)
206
+ * @param {Object|Function} [options.sharedStore] the shared store, or a
207
+ * factory that makes it on first use. Default: Entity.data in the app database.
208
+ * @param {Function} [options.now]
209
+ * @param {Function} [options.random]
210
+ * @param {Object} [options.logger] default: the `frigg.rate_limit` logger
211
+ * @param {Object} [options.telemetry] default: the process telemetry
212
+ * @param {Object} [options.env]
213
+ */
214
+ constructor({
215
+ localStore = new RateLimitStateRepositoryMemory(),
216
+ sharedStore,
217
+ now = Date.now,
218
+ random = Math.random,
219
+ logger,
220
+ telemetry,
221
+ env = process.env,
222
+ } = {}) {
223
+ this.localStore = localStore;
224
+ this._sharedStoreOption = sharedStore;
225
+ this._sharedStore = undefined;
226
+ this.now = now;
227
+ this.random = random;
228
+ this._logger = logger;
229
+ this._telemetry = telemetry;
230
+ this.env = env;
231
+ this.scopes = new Map();
232
+ this._sharedPausedUntil = 0;
233
+ }
234
+
235
+ get logger() {
236
+ this._logger ??= defaultLogger();
237
+ return this._logger;
238
+ }
239
+
240
+ _scope(scopeKey) {
241
+ let scope = this.scopes.get(scopeKey);
242
+ if (!scope) {
243
+ if (this.scopes.size >= MAX_SCOPES) this._evictOne();
244
+ scope = {
245
+ buckets: new Map(),
246
+ degradedBuckets: new Map(),
247
+ learnedIntervalMs: undefined,
248
+ localBlockedUntil: 0,
249
+ sharedBlockedUntil: 0,
250
+ sharedCheckedAt: -Infinity,
251
+ sharedRead: null,
252
+ sharedWrittenUntil: 0,
253
+ };
254
+ this.scopes.set(scopeKey, scope);
255
+ }
256
+ return scope;
257
+ }
258
+
259
+ // Drop the oldest key that is not blocked now, else the oldest key.
260
+ _evictOne() {
261
+ const now = this.now();
262
+ for (const [key, scope] of this.scopes) {
263
+ if (
264
+ scope.localBlockedUntil <= now &&
265
+ scope.sharedBlockedUntil <= now
266
+ ) {
267
+ this.scopes.delete(key);
268
+ return;
269
+ }
270
+ }
271
+ this.scopes.delete(this.scopes.keys().next().value);
272
+ }
273
+
274
+ _buckets(scope, policy, now) {
275
+ for (const window of bucketWindows(policy)) {
276
+ const id = `${window.name ?? ''}:${window.limit}/${window.perMs}`;
277
+ if (!scope.buckets.has(id)) {
278
+ scope.buckets.set(id, new TokenBucket(window, now));
279
+ }
280
+ }
281
+ return [...scope.buckets.values()];
282
+ }
283
+
284
+ // Shared state lives on the Entity row, so it needs an entity id.
285
+ _shared(policy, entityId) {
286
+ if (policy?.shared !== true) return null;
287
+ if (entityId === undefined || entityId === null) return null;
288
+ if (this.now() < this._sharedPausedUntil) return null;
289
+ if (this._sharedStore !== undefined) return this._sharedStore;
290
+ try {
291
+ const option = this._sharedStoreOption;
292
+ if (typeof option === 'function') {
293
+ this._sharedStore = option();
294
+ } else if (option) {
295
+ this._sharedStore = option;
296
+ } else {
297
+ const {
298
+ createRateLimitStateRepository,
299
+ } = require('./state/rate-limit-state-repository-factory');
300
+ this._sharedStore = createRateLimitStateRepository();
301
+ }
302
+ } catch (error) {
303
+ // Try again after the pause: a cold start can fail on its first
304
+ // database connection.
305
+ this._sharedStore = undefined;
306
+ this._sharedPausedUntil = this.now() + SHARED_FAILURE_PAUSE_MS;
307
+ this._reportFailure('create', error);
308
+ return null;
309
+ }
310
+ return this._sharedStore;
311
+ }
312
+
313
+ // Every store call is bounded: a slow database must not hold the API call.
314
+ _storeCall(operation, call) {
315
+ return withTimeout(
316
+ Promise.resolve().then(call),
317
+ sharedTimeoutMs(this.env),
318
+ operation
319
+ ).catch((error) => {
320
+ this._sharedPausedUntil = this.now() + SHARED_FAILURE_PAUSE_MS;
321
+ this._reportFailure(operation, error);
322
+ return undefined;
323
+ });
324
+ }
325
+
326
+ _reportFailure(operation, error) {
327
+ try {
328
+ this.logger?.warn?.(
329
+ 'Shared rate-limit state failed; pacing goes on in process',
330
+ {
331
+ eventName: 'frigg.rate_limit.shared_state_failed',
332
+ operation,
333
+ pausedMs: SHARED_FAILURE_PAUSE_MS,
334
+ error,
335
+ }
336
+ );
337
+ } catch {
338
+ // Logging must never stop a request.
339
+ }
340
+ try {
341
+ (this._telemetry ?? defaultTelemetry())?.count?.(
342
+ FAILURE_METRIC,
343
+ 1,
344
+ {
345
+ operation,
346
+ }
347
+ );
348
+ } catch {
349
+ // Telemetry must never stop a request.
350
+ }
351
+ }
352
+
353
+ _warn(message, error) {
354
+ try {
355
+ this.logger?.warn?.(message, {
356
+ eventName: 'frigg.rate_limit.headers_failed',
357
+ error,
358
+ });
359
+ } catch {
360
+ // Logging must never stop a request.
361
+ }
362
+ }
363
+
364
+ async _sharedBlockedUntil(location, scope, policy, now) {
365
+ const store = this._shared(policy, location.entityId);
366
+ // A paused store still honours the last block it gave.
367
+ if (!store) return scope.sharedBlockedUntil;
368
+ if (now - scope.sharedCheckedAt < sharedCacheMs(this.env)) {
369
+ return scope.sharedBlockedUntil;
370
+ }
371
+ // One read at a time for each key in this process.
372
+ scope.sharedRead ??= this._storeCall('read', () => store.read(location))
373
+ .then((row) => {
374
+ if (row !== undefined) {
375
+ scope.sharedBlockedUntil = Math.max(
376
+ 0,
377
+ row?.blockedUntil?.getTime?.() ?? 0
378
+ );
379
+ }
380
+ })
381
+ .finally(() => {
382
+ scope.sharedCheckedAt = this.now();
383
+ scope.sharedRead = null;
384
+ });
385
+ await scope.sharedRead;
386
+ return scope.sharedBlockedUntil;
387
+ }
388
+
389
+ /**
390
+ * Ask to make one call on the key.
391
+ *
392
+ * When the wait fits `budgetMs`, the call is granted: the caller sleeps
393
+ * `waitMs` and calls. Otherwise nothing is taken and the caller defers.
394
+ *
395
+ * @returns {Promise<{ granted: boolean, waitMs: number, reason?: string }>}
396
+ */
397
+ async acquire({ scopeKey, entityId, policy, budgetMs = 0 }) {
398
+ const admission = this._callAdmission(scopeKey, policy, entityId);
399
+ if (admission) {
400
+ return this._acquireCallSlot({
401
+ scopeKey,
402
+ entityId,
403
+ policy,
404
+ budgetMs,
405
+ admission,
406
+ });
407
+ }
408
+ return this._acquireLocal({ scopeKey, entityId, policy, budgetMs });
409
+ }
410
+
411
+ /**
412
+ * Shared call admission (ADR-049 section 6, amended 2026-12): with
413
+ * `shared: true` and a short window, every call takes the next call slot
414
+ * of the key in the shared store, so all workers together stay at the
415
+ * rate. The slot interval is `perMs / limit` of the shortest window, and
416
+ * `burst` (default 1) calls may go at once (GCRA tolerance).
417
+ */
418
+ _callAdmission(scopeKey, policy, entityId) {
419
+ if (policy?.shared !== true || policy.sharedCalls === false) {
420
+ return null;
421
+ }
422
+ if (entityId === undefined || entityId === null) return null;
423
+ const window = shortestWindow(policy);
424
+ let intervalMs;
425
+ let toleranceMs = 0;
426
+ if (window) {
427
+ if (
428
+ window.perMs > MAX_CALL_WINDOW_MS &&
429
+ policy.sharedCalls !== true
430
+ ) {
431
+ return null;
432
+ }
433
+ intervalMs = window.perMs / window.limit;
434
+ toleranceMs = (windowBurst(window) - 1) * intervalMs;
435
+ } else {
436
+ intervalMs = this.scopes.get(scopeKey)?.learnedIntervalMs;
437
+ }
438
+ if (!(intervalMs > 0)) return null;
439
+ // A slot further apart than the horizon would defer every call.
440
+ if (intervalMs > maxSlotHorizonMs(this.env)) return null;
441
+ return { intervalMs, toleranceMs };
442
+ }
443
+
444
+ // The in-process gates: the local block and the local token buckets.
445
+ _localGate(scope, policy, now) {
446
+ const blockWaitMs = Math.max(0, scope.localBlockedUntil - now);
447
+ const buckets = this._buckets(scope, policy, now);
448
+ const bucketWaitMs = Math.max(0, ...buckets.map((b) => b.waitMs(now)));
449
+ return {
450
+ buckets,
451
+ blockWaitMs,
452
+ waitMs: Math.max(blockWaitMs, bucketWaitMs),
453
+ reason: blockWaitMs >= bucketWaitMs ? 'blocked' : 'window',
454
+ };
455
+ }
456
+
457
+ async _acquireCallSlot({
458
+ scopeKey,
459
+ entityId,
460
+ policy,
461
+ budgetMs,
462
+ admission,
463
+ }) {
464
+ const scope = this._scope(scopeKey);
465
+ const now = this.now();
466
+ const local = this._localGate(scope, policy, now);
467
+ if (local.waitMs > budgetMs) {
468
+ return {
469
+ granted: false,
470
+ waitMs: local.waitMs,
471
+ reason: local.reason,
472
+ };
473
+ }
474
+
475
+ const paused = now < this._sharedPausedUntil;
476
+ const store = paused ? null : this._shared(policy, entityId);
477
+ if (!store) {
478
+ // No store at all (not configured, or `data` encrypted): pacing
479
+ // stays in process, as before. A failing store: degraded rate.
480
+ return paused || this._sharedStore === undefined
481
+ ? this._acquireDegraded(scope, policy, now, budgetMs, local)
482
+ : this._acquireLocal({ scopeKey, entityId, policy, budgetMs });
483
+ }
484
+
485
+ const horizonMs = Math.min(budgetMs, maxSlotHorizonMs(this.env));
486
+ const result = await this._storeCall('reserveCallSlot', () =>
487
+ store.reserveCallSlot(
488
+ { entityId, scopeKey },
489
+ { nowMs: now, horizonMs, ...admission }
490
+ )
491
+ );
492
+ if (result === undefined) {
493
+ return this._acquireDegraded(
494
+ scope,
495
+ policy,
496
+ this.now(),
497
+ budgetMs,
498
+ local
499
+ );
500
+ }
501
+ if (result === null) {
502
+ // The store keeps no call slots for this entity (encrypted Entity
503
+ // fields, or no entity row): pacing stays in process.
504
+ return this._acquireLocal({ scopeKey, entityId, policy, budgetMs });
505
+ }
506
+ const after = this.now();
507
+ if (result.full) {
508
+ return {
509
+ granted: false,
510
+ waitMs: Math.max(local.waitMs, result.nextAtMs - after, 0),
511
+ reason: 'window',
512
+ shared: true,
513
+ };
514
+ }
515
+ for (const bucket of local.buckets) bucket.take();
516
+ const slotWaitMs = Math.max(0, result.slotMs - after);
517
+ const waitMs = Math.max(local.waitMs, slotWaitMs);
518
+ return {
519
+ granted: true,
520
+ waitMs,
521
+ ...(waitMs > 0 && {
522
+ reason: slotWaitMs >= local.waitMs ? 'slot' : local.reason,
523
+ }),
524
+ shared: true,
525
+ };
526
+ }
527
+
528
+ // The shared store fails: this process runs at a share of the rate, so
529
+ // a database stall that hits every worker does not open the key.
530
+ _acquireDegraded(scope, policy, now, budgetMs, local) {
531
+ const share = policy?.maxConcurrency ?? DEFAULT_DEGRADED_SHARE;
532
+ const buckets = bucketWindows(policy).map((window) => {
533
+ const id = `${window.name ?? ''}:${window.limit}/${window.perMs}`;
534
+ if (!scope.degradedBuckets.has(id)) {
535
+ scope.degradedBuckets.set(
536
+ id,
537
+ new TokenBucket(
538
+ {
539
+ limit: Math.max(
540
+ 1,
541
+ Math.floor(window.limit / share)
542
+ ),
543
+ perMs: window.perMs,
544
+ ratePerMs: window.limit / share / window.perMs,
545
+ },
546
+ now
547
+ )
548
+ );
549
+ }
550
+ return scope.degradedBuckets.get(id);
551
+ });
552
+ const degradedWaitMs = Math.max(
553
+ 0,
554
+ ...buckets.map((b) => b.waitMs(now))
555
+ );
556
+ const waitMs = Math.max(local.waitMs, degradedWaitMs);
557
+ if (waitMs > budgetMs) {
558
+ return { granted: false, waitMs, reason: 'window', degraded: true };
559
+ }
560
+ for (const bucket of [...local.buckets, ...buckets]) bucket.take();
561
+ return {
562
+ granted: true,
563
+ waitMs,
564
+ ...(waitMs > 0 && { reason: 'window' }),
565
+ degraded: true,
566
+ };
567
+ }
568
+
569
+ async _acquireLocal({ scopeKey, entityId, policy, budgetMs }) {
570
+ const scope = this._scope(scopeKey);
571
+ const sharedUntil = await this._sharedBlockedUntil(
572
+ { entityId, scopeKey },
573
+ scope,
574
+ policy,
575
+ this.now()
576
+ );
577
+ // The shared read can take time: measure after it.
578
+ const now = this.now();
579
+ const blockWaitMs = Math.max(
580
+ 0,
581
+ scope.localBlockedUntil - now,
582
+ sharedUntil - now
583
+ );
584
+ const buckets = this._buckets(scope, policy, now);
585
+ const bucketWaitMs = Math.max(0, ...buckets.map((b) => b.waitMs(now)));
586
+ const waitMs = Math.max(blockWaitMs, bucketWaitMs);
587
+ const reason = blockWaitMs >= bucketWaitMs ? 'blocked' : 'window';
588
+
589
+ if (waitMs > budgetMs) return { granted: false, waitMs, reason };
590
+ for (const bucket of buckets) bucket.take();
591
+ if (waitMs === 0) return { granted: true, waitMs: 0 };
592
+ // Callers that wait for the end of a block do not all call at that
593
+ // moment: each one adds a random part of the block (up to 1 s),
594
+ // inside the budget, so the calls of many processes spread out.
595
+ const jitterMs =
596
+ reason === 'blocked'
597
+ ? Math.floor(
598
+ this.random() *
599
+ Math.min(blockWaitMs, MAX_RELEASE_JITTER_MS)
600
+ )
601
+ : 0;
602
+ return {
603
+ granted: true,
604
+ waitMs: Math.max(waitMs, Math.min(waitMs + jitterMs, budgetMs)),
605
+ reason,
606
+ };
607
+ }
608
+
609
+ /**
610
+ * Read the rate-limit headers of any response, a 2xx too. A `remaining`
611
+ * of 0 blocks the key until the reset. A 2xx with calls remaining ends a
612
+ * block that this process holds. A `RateLimit-Policy` quota sets the
613
+ * spacing of retry slots when the module declares no window.
614
+ */
615
+ async observe({ scopeKey, entityId, policy, headers, status }) {
616
+ try {
617
+ const now = this.now();
618
+ const scope = this._scope(scopeKey);
619
+ const interval = intervalFromPolicyHeader(headers);
620
+ if (interval !== undefined) scope.learnedIntervalMs = interval;
621
+
622
+ const parsers = (policy?.parsers ?? HEADER_PARSERS).filter((name) =>
623
+ HEADER_PARSERS.includes(name)
624
+ );
625
+ for (const name of parsers) {
626
+ const hint = BUILT_IN_PARSERS[name](headers, {
627
+ now,
628
+ resetDeltaUnit: policy?.resetDeltaUnit,
629
+ });
630
+ if (!hint || !Number.isFinite(hint.remaining)) continue;
631
+ if (hint.remaining <= 0 && hint.waitMs > 0) {
632
+ await this.block({
633
+ scopeKey,
634
+ entityId,
635
+ policy,
636
+ until: new Date(now + hint.waitMs),
637
+ });
638
+ } else if (
639
+ hint.remaining > 0 &&
640
+ status >= 200 &&
641
+ status < 300
642
+ ) {
643
+ this._unblockLocal(scope);
644
+ }
645
+ return;
646
+ }
647
+ } catch (error) {
648
+ this._warn('Rate-limit headers not read', error);
649
+ }
650
+ }
651
+
652
+ // The provider just accepted a call and says calls remain. A shared block
653
+ // in the store stays (it only moves later) and is capped by the maximum.
654
+ _unblockLocal(scope) {
655
+ scope.localBlockedUntil = 0;
656
+ scope.sharedBlockedUntil = 0;
657
+ }
658
+
659
+ /**
660
+ * No call on the key before `until`, in this process and, if shared, in
661
+ * all. A block is never longer than FRIGG_RATE_LIMIT_MAX_BLOCK_MS.
662
+ */
663
+ async block({ scopeKey, entityId, policy, until }) {
664
+ const requested = until?.getTime?.();
665
+ if (!Number.isFinite(requested)) return;
666
+ const at = Math.min(requested, this.now() + maxBlockMs(this.env));
667
+ const scope = this._scope(scopeKey);
668
+ scope.localBlockedUntil = Math.max(scope.localBlockedUntil, at);
669
+
670
+ const store = this._shared(policy, entityId);
671
+ if (
672
+ !store ||
673
+ at - scope.sharedWrittenUntil < MIN_SHARED_BLOCK_STEP_MS
674
+ ) {
675
+ return;
676
+ }
677
+ scope.sharedWrittenUntil = at;
678
+ scope.sharedBlockedUntil = Math.max(scope.sharedBlockedUntil, at);
679
+ await this._storeCall('block', () =>
680
+ store.block({ entityId, scopeKey }, new Date(at))
681
+ );
682
+ }
683
+
684
+ /** The end of the block this process holds on the key (epoch ms). */
685
+ localBlockedUntil(scopeKey) {
686
+ return this.scopes.get(scopeKey)?.localBlockedUntil ?? 0;
687
+ }
688
+
689
+ /** The time one request uses, from `windows` or a learned header quota. */
690
+ intervalMs({ scopeKey, policy }) {
691
+ return (
692
+ intervalFromWindows(policy) ??
693
+ this.scopes.get(scopeKey)?.learnedIntervalMs
694
+ );
695
+ }
696
+
697
+ /**
698
+ * The time a deferred message comes back. With a known rate, each message
699
+ * takes the next slot of the key (shared when the policy is shared) and a
700
+ * random point inside it, so a backlog drains at the provider's rate.
701
+ * Without one, a random point in [notBefore, notBefore + spread], where
702
+ * spread is max(waitMs, 1 s), but never more than
703
+ * FRIGG_QUEUE_DEFERRAL_JITTER_MAX_MS.
704
+ *
705
+ * Slots exist only inside the SQS delay range (900 s from now):
706
+ * - A retry that cannot come back inside it (a long quota wait) takes no
707
+ * slot, so it never moves the sequence past the range. It comes back at
708
+ * a random point after notBefore, like a retry without a known rate.
709
+ * - When every slot up to the end of the range is taken, the message
710
+ * takes no slot and comes back at a random point in the rest of the
711
+ * range. The sequence moves back inside the range as time passes.
712
+ * So a burst backlog stays in the delay tier, never spends receives, and
713
+ * never writes a user message. Slots go in arrival order and are never
714
+ * given back, so under a long overload a message that is paced again
715
+ * waits behind newer ones; the deferral caps bound that wait.
716
+ *
717
+ * @returns {Promise<Date>}
718
+ */
719
+ async reserveRetry({ scopeKey, entityId, policy, notBefore, waitMs = 0 }) {
720
+ const nb = notBefore.getTime();
721
+ const delayEnd = this.now() + MAX_PACED_RETRY_MS;
722
+ const intervalMs = scopeKey
723
+ ? this.intervalMs({ scopeKey, policy })
724
+ : undefined;
725
+ if (!intervalMs || nb > delayEnd) {
726
+ let spread = Math.min(
727
+ Math.max(waitMs, MIN_RETRY_SPREAD_MS),
728
+ jitterMaxMs(this.env)
729
+ );
730
+ if (nb <= delayEnd) spread = Math.min(spread, delayEnd - nb);
731
+ return new Date(nb + Math.floor(this.random() * spread));
732
+ }
733
+
734
+ const options = { notBefore, intervalMs, notAfter: new Date(delayEnd) };
735
+ let slot;
736
+ const store = this._shared(policy, entityId);
737
+ if (store) {
738
+ slot = await this._storeCall('reserveSlot', () =>
739
+ store.reserveSlot({ entityId, scopeKey }, options)
740
+ );
741
+ }
742
+ slot ??= await this.localStore.reserveSlot({ scopeKey }, options);
743
+ if (slot === SLOTS_FULL) {
744
+ return new Date(nb + Math.floor(this.random() * (delayEnd - nb)));
745
+ }
746
+ const at = slot.getTime() + Math.floor(this.random() * intervalMs);
747
+ return new Date(Math.min(at, delayEnd));
748
+ }
749
+ }
750
+
751
+ const PACER_KEY = Symbol.for('@friggframework/core.rate-limit-pacer');
752
+
753
+ /** The pacer of this process. Every requester shares it. */
754
+ function getRateLimitPacer() {
755
+ globalThis[PACER_KEY] ??= new RateLimitPacer();
756
+ return globalThis[PACER_KEY];
757
+ }
758
+
759
+ /** Replace the pacer of this process, for example with a custom store. */
760
+ function setRateLimitPacer(pacer) {
761
+ globalThis[PACER_KEY] = pacer ?? undefined;
762
+ }
763
+
764
+ module.exports = {
765
+ DEFAULT_MAX_BLOCK_MS,
766
+ DEFAULT_MAX_PACING_WAIT_MS,
767
+ DEFAULT_MAX_SLOT_HORIZON_MS,
768
+ DEFAULT_SHARED_CACHE_MS,
769
+ DEFAULT_SHARED_TIMEOUT_MS,
770
+ MAX_BLOCK_MS_ENV,
771
+ MAX_PACING_WAIT_MS_ENV,
772
+ MAX_SLOT_HORIZON_MS_ENV,
773
+ PACING_ENV,
774
+ RateLimitPacer,
775
+ SHARED_CACHE_MS_ENV,
776
+ SHARED_TIMEOUT_MS_ENV,
777
+ TokenBucket,
778
+ bucketWindows,
779
+ getRateLimitPacer,
780
+ hashRateLimitScope,
781
+ intervalFromPolicyHeader,
782
+ maxPacingWaitMs,
783
+ pacingEnabled,
784
+ setRateLimitPacer,
785
+ };