@friggframework/core 2.0.0--canary.737.83b4e17.0 → 2.0.0--canary.743.57dc4bf.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.
Files changed (50) hide show
  1. package/CLAUDE.md +173 -7
  2. package/core/CLAUDE.md +57 -1
  3. package/core/Worker.js +440 -11
  4. package/core/create-handler.js +20 -0
  5. package/core/index.js +6 -0
  6. package/core/invocation-deadline.js +91 -0
  7. package/core/invocation-scope.js +30 -24
  8. package/core/rate-limited-response.js +27 -0
  9. package/errors/fetch-error.js +10 -6
  10. package/errors/index.js +2 -0
  11. package/errors/rate-limit-error.js +46 -0
  12. package/handlers/app-handler-helpers.js +15 -0
  13. package/handlers/backend-utils.js +75 -1
  14. package/handlers/workers/integration-defined-workers.js +2 -0
  15. package/index.js +26 -0
  16. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +2 -0
  17. package/integrations/repositories/integration-repository-documentdb.js +59 -10
  18. package/integrations/repositories/integration-repository-interface.js +50 -7
  19. package/integrations/repositories/integration-repository-mongo.js +88 -16
  20. package/integrations/repositories/integration-repository-postgres.js +89 -16
  21. package/integrations/repositories/message-item-shared.js +17 -0
  22. package/integrations/tests/doubles/prisma-message-row.js +24 -0
  23. package/integrations/tests/doubles/test-integration-repository.js +32 -2
  24. package/integrations/use-cases/clear-rate-limit-wait.js +28 -0
  25. package/integrations/use-cases/index.js +7 -1
  26. package/integrations/use-cases/record-rate-limit-message.js +104 -0
  27. package/integrations/use-cases/record-rate-limit-wait.js +36 -0
  28. package/integrations/use-cases/update-integration-messages.js +28 -9
  29. package/logs/serialize.js +15 -0
  30. package/modules/requester/oauth-2.js +8 -0
  31. package/modules/requester/rate-limit/index.js +6 -0
  32. package/modules/requester/rate-limit/pacer.js +551 -0
  33. package/modules/requester/rate-limit/parsers.js +249 -0
  34. package/modules/requester/rate-limit/policy.js +326 -0
  35. package/modules/requester/rate-limit/state/rate-limit-state-repository-factory.js +35 -0
  36. package/modules/requester/rate-limit/state/rate-limit-state-repository-interface.js +69 -0
  37. package/modules/requester/rate-limit/state/rate-limit-state-repository-memory.js +62 -0
  38. package/modules/requester/rate-limit/state/rate-limit-state-repository-mongo.js +148 -0
  39. package/modules/requester/rate-limit/state/rate-limit-state-repository-postgres.js +93 -0
  40. package/modules/requester/requester.js +357 -11
  41. package/package.json +7 -6
  42. package/queues/queue-deferral.js +155 -0
  43. package/queues/queue-delivery.js +1 -0
  44. package/queues/queuer-util.js +3 -4
  45. package/types/core/consumer.fixture.ts +12 -0
  46. package/types/core/index.d.ts +84 -0
  47. package/types/errors/index.d.ts +47 -0
  48. package/types/integrations/index.d.ts +25 -4
  49. package/types/module-plugin/index.d.ts +53 -0
  50. package/queues/sqs-message-body.js +0 -17
@@ -0,0 +1,6 @@
1
+ const parsers = require('./parsers');
2
+ const policy = require('./policy');
3
+ const pacer = require('./pacer');
4
+ const state = require('./state/rate-limit-state-repository-factory');
5
+
6
+ module.exports = { ...parsers, ...policy, ...pacer, ...state };
@@ -0,0 +1,551 @@
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
+
7
+ // ADR-049 section 6: pacing. 2a is the in-process part (token buckets from
8
+ // `windows`, a block from the headers). 2b is the shared part: the block and
9
+ // the retry slots of one scope key, in Entity.data of the calling entity, for
10
+ // parallel workers.
11
+
12
+ const PACING_ENV = 'FRIGG_RATE_LIMIT_PACING';
13
+ const SHARED_CACHE_MS_ENV = 'FRIGG_RATE_LIMIT_SHARED_CACHE_MS';
14
+ const SHARED_TIMEOUT_MS_ENV = 'FRIGG_RATE_LIMIT_SHARED_TIMEOUT_MS';
15
+ const MAX_PACING_WAIT_MS_ENV = 'FRIGG_RATE_LIMIT_MAX_PACING_WAIT_MS';
16
+ const MAX_BLOCK_MS_ENV = 'FRIGG_RATE_LIMIT_MAX_BLOCK_MS';
17
+ const JITTER_MAX_MS_ENV = 'FRIGG_QUEUE_DEFERRAL_JITTER_MAX_MS';
18
+ const DEFAULT_SHARED_CACHE_MS = 1_000;
19
+ const DEFAULT_SHARED_TIMEOUT_MS = 250;
20
+ const DEFAULT_MAX_PACING_WAIT_MS = 2_000;
21
+ // A block stops every call on a key. A longer limit (a daily quota) is left to
22
+ // the next call: its 429 defers that one message with the provider's time.
23
+ const DEFAULT_MAX_BLOCK_MS = 15 * 60 * 1000;
24
+ const DEFAULT_JITTER_MAX_MS = 5 * 60 * 1000;
25
+ const SHARED_FAILURE_PAUSE_MS = 30_000;
26
+ // A block that moves by less than this is not written again to the store.
27
+ const MIN_SHARED_BLOCK_STEP_MS = 250;
28
+ // A retry without a known rate spreads over at least this time.
29
+ const MIN_RETRY_SPREAD_MS = 1_000;
30
+ const HEADER_PARSERS = ['ietf', 'resetHeaders'];
31
+ const MAX_SCOPES = 10_000;
32
+ const FAILURE_METRIC = 'frigg.rate_limit.shared_state_failures';
33
+
34
+ const toNonNegativeInteger = (value) => {
35
+ if (value === undefined || value === null || value === '') return undefined;
36
+ const number = Number(value);
37
+ return Number.isInteger(number) && number >= 0 ? number : undefined;
38
+ };
39
+
40
+ const readMs = (env, name, fallback) =>
41
+ toNonNegativeInteger(env[name]) ?? fallback;
42
+
43
+ function pacingEnabled(env = process.env) {
44
+ const value = String(env[PACING_ENV] ?? '').toLowerCase();
45
+ return !['off', 'false', '0', 'disabled'].includes(value);
46
+ }
47
+
48
+ const maxPacingWaitMs = (env = process.env) =>
49
+ readMs(env, MAX_PACING_WAIT_MS_ENV, DEFAULT_MAX_PACING_WAIT_MS);
50
+ const sharedCacheMs = (env = process.env) =>
51
+ readMs(env, SHARED_CACHE_MS_ENV, DEFAULT_SHARED_CACHE_MS);
52
+ const sharedTimeoutMs = (env = process.env) =>
53
+ readMs(env, SHARED_TIMEOUT_MS_ENV, DEFAULT_SHARED_TIMEOUT_MS);
54
+ const maxBlockMs = (env = process.env) =>
55
+ readMs(env, MAX_BLOCK_MS_ENV, DEFAULT_MAX_BLOCK_MS);
56
+ const jitterMaxMs = (env = process.env) =>
57
+ readMs(env, JITTER_MAX_MS_ENV, DEFAULT_JITTER_MAX_MS);
58
+
59
+ /**
60
+ * A stable, short, one-way id for a scope value that must not be stored or
61
+ * logged, such as an API key. For a module whose provider counts per key:
62
+ * `scope: (api) => hashRateLimitScope(api.api_key)`.
63
+ */
64
+ function hashRateLimitScope(value) {
65
+ if (value === undefined || value === null || value === '') return undefined;
66
+ return createHash('sha256')
67
+ .update(String(value))
68
+ .digest('hex')
69
+ .slice(0, 32);
70
+ }
71
+
72
+ /** The windows of a policy that a token bucket can enforce. */
73
+ function bucketWindows(policy) {
74
+ if (!Array.isArray(policy?.windows)) return [];
75
+ return policy.windows.filter(
76
+ (window) =>
77
+ window &&
78
+ Number.isFinite(window.limit) &&
79
+ window.limit > 0 &&
80
+ Number.isFinite(window.perMs) &&
81
+ window.perMs > 0
82
+ );
83
+ }
84
+
85
+ /**
86
+ * The provider's burst quota from an IETF `RateLimit-Policy` header, as the
87
+ * time one request uses: `w` seconds over `q` requests. With several policies
88
+ * the shortest window wins: retry slots follow the burst rate, and a longer
89
+ * quota shows up as `remaining: 0` and a block. Example:
90
+ * `"per-second"; q=10; w=1` gives 100 ms.
91
+ */
92
+ function intervalFromPolicyHeader(headers) {
93
+ const raw = headerValue(headers, 'ratelimit-policy');
94
+ if (raw === undefined) return undefined;
95
+ let best;
96
+ for (const item of raw.split(',')) {
97
+ const q = Number(/(?:^|;)\s*q\s*=\s*(\d+(?:\.\d+)?)/.exec(item)?.[1]);
98
+ const w = Number(/(?:^|;)\s*w\s*=\s*(\d+(?:\.\d+)?)/.exec(item)?.[1]);
99
+ if (q > 0 && w > 0 && (best === undefined || w < best.w)) {
100
+ best = { q, w };
101
+ }
102
+ }
103
+ return best ? (best.w * 1000) / best.q : undefined;
104
+ }
105
+
106
+ /** The interval of the window with the shortest period. */
107
+ function intervalFromWindows(policy) {
108
+ const windows = bucketWindows(policy);
109
+ if (windows.length === 0) return undefined;
110
+ const shortest = windows.reduce((a, b) => (b.perMs < a.perMs ? b : a));
111
+ return shortest.perMs / shortest.limit;
112
+ }
113
+
114
+ class TokenBucket {
115
+ constructor({ limit, perMs }, now) {
116
+ this.capacity = limit;
117
+ this.ratePerMs = limit / perMs;
118
+ this.tokens = limit;
119
+ this.updatedAt = now;
120
+ }
121
+
122
+ _refill(now) {
123
+ if (now <= this.updatedAt) return;
124
+ this.tokens = Math.min(
125
+ this.capacity,
126
+ this.tokens + (now - this.updatedAt) * this.ratePerMs
127
+ );
128
+ this.updatedAt = now;
129
+ }
130
+
131
+ waitMs(now) {
132
+ this._refill(now);
133
+ return this.tokens >= 1
134
+ ? 0
135
+ : Math.ceil((1 - this.tokens) / this.ratePerMs);
136
+ }
137
+
138
+ // The token can be one in the future: the caller sleeps until it exists.
139
+ take() {
140
+ this.tokens -= 1;
141
+ }
142
+ }
143
+
144
+ class StoreTimeoutError extends Error {
145
+ constructor(operation, ms) {
146
+ super(`rate-limit store ${operation} took more than ${ms} ms`);
147
+ this.name = 'StoreTimeoutError';
148
+ }
149
+ }
150
+
151
+ function withTimeout(promise, ms, operation) {
152
+ if (!(ms > 0)) return promise;
153
+ let timer;
154
+ const timeout = new Promise((_, reject) => {
155
+ timer = setTimeout(
156
+ () => reject(new StoreTimeoutError(operation, ms)),
157
+ ms
158
+ );
159
+ timer.unref?.();
160
+ });
161
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
162
+ }
163
+
164
+ function defaultLogger() {
165
+ return require('../../../logs').getLogger('frigg.rate_limit');
166
+ }
167
+
168
+ function defaultTelemetry() {
169
+ return require('../../../telemetry/telemetry-runtime').getTelemetry();
170
+ }
171
+
172
+ class RateLimitPacer {
173
+ /**
174
+ * @param {Object} [options]
175
+ * @param {Object} [options.localStore] in-process state (default: memory)
176
+ * @param {Object|Function} [options.sharedStore] the shared store, or a
177
+ * factory that makes it on first use. Default: Entity.data in the app database.
178
+ * @param {Function} [options.now]
179
+ * @param {Function} [options.random]
180
+ * @param {Object} [options.logger] default: the `frigg.rate_limit` logger
181
+ * @param {Object} [options.telemetry] default: the process telemetry
182
+ * @param {Object} [options.env]
183
+ */
184
+ constructor({
185
+ localStore = new RateLimitStateRepositoryMemory(),
186
+ sharedStore,
187
+ now = Date.now,
188
+ random = Math.random,
189
+ logger,
190
+ telemetry,
191
+ env = process.env,
192
+ } = {}) {
193
+ this.localStore = localStore;
194
+ this._sharedStoreOption = sharedStore;
195
+ this._sharedStore = undefined;
196
+ this.now = now;
197
+ this.random = random;
198
+ this._logger = logger;
199
+ this._telemetry = telemetry;
200
+ this.env = env;
201
+ this.scopes = new Map();
202
+ this._sharedPausedUntil = 0;
203
+ }
204
+
205
+ get logger() {
206
+ this._logger ??= defaultLogger();
207
+ return this._logger;
208
+ }
209
+
210
+ _scope(scopeKey) {
211
+ let scope = this.scopes.get(scopeKey);
212
+ if (!scope) {
213
+ if (this.scopes.size >= MAX_SCOPES) this._evictOne();
214
+ scope = {
215
+ buckets: new Map(),
216
+ learnedIntervalMs: undefined,
217
+ localBlockedUntil: 0,
218
+ sharedBlockedUntil: 0,
219
+ sharedCheckedAt: -Infinity,
220
+ sharedRead: null,
221
+ sharedWrittenUntil: 0,
222
+ };
223
+ this.scopes.set(scopeKey, scope);
224
+ }
225
+ return scope;
226
+ }
227
+
228
+ // Drop the oldest key that is not blocked now, else the oldest key.
229
+ _evictOne() {
230
+ const now = this.now();
231
+ for (const [key, scope] of this.scopes) {
232
+ if (
233
+ scope.localBlockedUntil <= now &&
234
+ scope.sharedBlockedUntil <= now
235
+ ) {
236
+ this.scopes.delete(key);
237
+ return;
238
+ }
239
+ }
240
+ this.scopes.delete(this.scopes.keys().next().value);
241
+ }
242
+
243
+ _buckets(scope, policy, now) {
244
+ for (const window of bucketWindows(policy)) {
245
+ const id = `${window.name ?? ''}:${window.limit}/${window.perMs}`;
246
+ if (!scope.buckets.has(id)) {
247
+ scope.buckets.set(id, new TokenBucket(window, now));
248
+ }
249
+ }
250
+ return [...scope.buckets.values()];
251
+ }
252
+
253
+ // Shared state lives on the Entity row, so it needs an entity id.
254
+ _shared(policy, entityId) {
255
+ if (policy?.shared !== true) return null;
256
+ if (entityId === undefined || entityId === null) return null;
257
+ if (this.now() < this._sharedPausedUntil) return null;
258
+ if (this._sharedStore !== undefined) return this._sharedStore;
259
+ try {
260
+ const option = this._sharedStoreOption;
261
+ if (typeof option === 'function') {
262
+ this._sharedStore = option();
263
+ } else if (option) {
264
+ this._sharedStore = option;
265
+ } else {
266
+ const {
267
+ createRateLimitStateRepository,
268
+ } = require('./state/rate-limit-state-repository-factory');
269
+ this._sharedStore = createRateLimitStateRepository();
270
+ }
271
+ } catch (error) {
272
+ this._sharedStore = null;
273
+ this._reportFailure('create', error);
274
+ }
275
+ return this._sharedStore;
276
+ }
277
+
278
+ // Every store call is bounded: a slow database must not hold the API call.
279
+ _storeCall(operation, call) {
280
+ return withTimeout(
281
+ Promise.resolve().then(call),
282
+ sharedTimeoutMs(this.env),
283
+ operation
284
+ ).catch((error) => {
285
+ this._sharedPausedUntil = this.now() + SHARED_FAILURE_PAUSE_MS;
286
+ this._reportFailure(operation, error);
287
+ return undefined;
288
+ });
289
+ }
290
+
291
+ _reportFailure(operation, error) {
292
+ try {
293
+ this.logger?.warn?.(
294
+ 'Shared rate-limit state failed; pacing goes on in process',
295
+ {
296
+ eventName: 'frigg.rate_limit.shared_state_failed',
297
+ operation,
298
+ pausedMs: SHARED_FAILURE_PAUSE_MS,
299
+ error,
300
+ }
301
+ );
302
+ } catch {
303
+ // Logging must never stop a request.
304
+ }
305
+ try {
306
+ (this._telemetry ?? defaultTelemetry())?.count?.(
307
+ FAILURE_METRIC,
308
+ 1,
309
+ {
310
+ operation,
311
+ }
312
+ );
313
+ } catch {
314
+ // Telemetry must never stop a request.
315
+ }
316
+ }
317
+
318
+ _warn(message, error) {
319
+ try {
320
+ this.logger?.warn?.(message, {
321
+ eventName: 'frigg.rate_limit.headers_failed',
322
+ error,
323
+ });
324
+ } catch {
325
+ // Logging must never stop a request.
326
+ }
327
+ }
328
+
329
+ async _sharedBlockedUntil(location, scope, policy, now) {
330
+ const store = this._shared(policy, location.entityId);
331
+ // A paused store still honours the last block it gave.
332
+ if (!store) return scope.sharedBlockedUntil;
333
+ if (now - scope.sharedCheckedAt < sharedCacheMs(this.env)) {
334
+ return scope.sharedBlockedUntil;
335
+ }
336
+ // One read at a time for each key in this process.
337
+ scope.sharedRead ??= this._storeCall('read', () => store.read(location))
338
+ .then((row) => {
339
+ if (row !== undefined) {
340
+ scope.sharedBlockedUntil = Math.max(
341
+ 0,
342
+ row?.blockedUntil?.getTime?.() ?? 0
343
+ );
344
+ }
345
+ })
346
+ .finally(() => {
347
+ scope.sharedCheckedAt = this.now();
348
+ scope.sharedRead = null;
349
+ });
350
+ await scope.sharedRead;
351
+ return scope.sharedBlockedUntil;
352
+ }
353
+
354
+ /**
355
+ * Ask to make one call on the key.
356
+ *
357
+ * When the wait fits `budgetMs`, the call is granted: the caller sleeps
358
+ * `waitMs` and calls. Otherwise nothing is taken and the caller defers.
359
+ *
360
+ * @returns {Promise<{ granted: boolean, waitMs: number, reason?: string }>}
361
+ */
362
+ async acquire({ scopeKey, entityId, policy, budgetMs = 0 }) {
363
+ const scope = this._scope(scopeKey);
364
+ const sharedUntil = await this._sharedBlockedUntil(
365
+ { entityId, scopeKey },
366
+ scope,
367
+ policy,
368
+ this.now()
369
+ );
370
+ // The shared read can take time: measure after it.
371
+ const now = this.now();
372
+ const blockWaitMs = Math.max(
373
+ 0,
374
+ scope.localBlockedUntil - now,
375
+ sharedUntil - now
376
+ );
377
+ const buckets = this._buckets(scope, policy, now);
378
+ const bucketWaitMs = Math.max(0, ...buckets.map((b) => b.waitMs(now)));
379
+ const waitMs = Math.max(blockWaitMs, bucketWaitMs);
380
+ const reason = blockWaitMs >= bucketWaitMs ? 'blocked' : 'window';
381
+
382
+ if (waitMs > budgetMs) return { granted: false, waitMs, reason };
383
+ for (const bucket of buckets) bucket.take();
384
+ return waitMs > 0
385
+ ? { granted: true, waitMs, reason }
386
+ : { granted: true, waitMs: 0 };
387
+ }
388
+
389
+ /**
390
+ * Read the rate-limit headers of any response, a 2xx too. A `remaining`
391
+ * of 0 blocks the key until the reset. A 2xx with calls remaining ends a
392
+ * block that this process holds. A `RateLimit-Policy` quota sets the
393
+ * spacing of retry slots when the module declares no window.
394
+ */
395
+ async observe({ scopeKey, entityId, policy, headers, status }) {
396
+ try {
397
+ const now = this.now();
398
+ const scope = this._scope(scopeKey);
399
+ const interval = intervalFromPolicyHeader(headers);
400
+ if (interval !== undefined) scope.learnedIntervalMs = interval;
401
+
402
+ const parsers = (policy?.parsers ?? HEADER_PARSERS).filter((name) =>
403
+ HEADER_PARSERS.includes(name)
404
+ );
405
+ for (const name of parsers) {
406
+ const hint = BUILT_IN_PARSERS[name](headers, {
407
+ now,
408
+ resetDeltaUnit: policy?.resetDeltaUnit,
409
+ });
410
+ if (!hint || !Number.isFinite(hint.remaining)) continue;
411
+ if (hint.remaining <= 0 && hint.waitMs > 0) {
412
+ await this.block({
413
+ scopeKey,
414
+ entityId,
415
+ policy,
416
+ until: new Date(now + hint.waitMs),
417
+ });
418
+ } else if (
419
+ hint.remaining > 0 &&
420
+ status >= 200 &&
421
+ status < 300
422
+ ) {
423
+ this._unblockLocal(scope);
424
+ }
425
+ return;
426
+ }
427
+ } catch (error) {
428
+ this._warn('Rate-limit headers not read', error);
429
+ }
430
+ }
431
+
432
+ // The provider just accepted a call and says calls remain. A shared block
433
+ // in the store stays (it only moves later) and is capped by the maximum.
434
+ _unblockLocal(scope) {
435
+ scope.localBlockedUntil = 0;
436
+ scope.sharedBlockedUntil = 0;
437
+ }
438
+
439
+ /**
440
+ * No call on the key before `until`, in this process and, if shared, in
441
+ * all. A block is never longer than FRIGG_RATE_LIMIT_MAX_BLOCK_MS.
442
+ */
443
+ async block({ scopeKey, entityId, policy, until }) {
444
+ const requested = until?.getTime?.();
445
+ if (!Number.isFinite(requested)) return;
446
+ const at = Math.min(requested, this.now() + maxBlockMs(this.env));
447
+ const scope = this._scope(scopeKey);
448
+ scope.localBlockedUntil = Math.max(scope.localBlockedUntil, at);
449
+
450
+ const store = this._shared(policy, entityId);
451
+ if (
452
+ !store ||
453
+ at - scope.sharedWrittenUntil < MIN_SHARED_BLOCK_STEP_MS
454
+ ) {
455
+ return;
456
+ }
457
+ scope.sharedWrittenUntil = at;
458
+ scope.sharedBlockedUntil = Math.max(scope.sharedBlockedUntil, at);
459
+ await this._storeCall('block', () =>
460
+ store.block({ entityId, scopeKey }, new Date(at))
461
+ );
462
+ }
463
+
464
+ /** The time one request uses, from `windows` or a learned header quota. */
465
+ intervalMs({ scopeKey, policy }) {
466
+ return (
467
+ intervalFromWindows(policy) ??
468
+ this.scopes.get(scopeKey)?.learnedIntervalMs
469
+ );
470
+ }
471
+
472
+ /**
473
+ * The time a deferred message comes back. With a known rate, each message
474
+ * takes the next slot of the key (shared when the policy is shared) and a
475
+ * random point inside it, so a backlog drains at the provider's rate.
476
+ * Without one, a random point in [notBefore, notBefore + spread], where
477
+ * spread is max(waitMs, 1 s), but never more than
478
+ * FRIGG_QUEUE_DEFERRAL_JITTER_MAX_MS.
479
+ *
480
+ * @returns {Promise<Date>}
481
+ */
482
+ async reserveRetry({ scopeKey, entityId, policy, notBefore, waitMs = 0 }) {
483
+ const intervalMs = scopeKey
484
+ ? this.intervalMs({ scopeKey, policy })
485
+ : undefined;
486
+ if (!intervalMs) {
487
+ const spread = Math.min(
488
+ Math.max(waitMs, MIN_RETRY_SPREAD_MS),
489
+ jitterMaxMs(this.env)
490
+ );
491
+ return new Date(
492
+ notBefore.getTime() + Math.floor(this.random() * spread)
493
+ );
494
+ }
495
+
496
+ let slot;
497
+ const store = this._shared(policy, entityId);
498
+ if (store) {
499
+ slot = await this._storeCall('reserveSlot', () =>
500
+ store.reserveSlot(
501
+ { entityId, scopeKey },
502
+ { notBefore, intervalMs }
503
+ )
504
+ );
505
+ }
506
+ slot ??= await this.localStore.reserveSlot(
507
+ { scopeKey },
508
+ {
509
+ notBefore,
510
+ intervalMs,
511
+ }
512
+ );
513
+ return new Date(
514
+ slot.getTime() + Math.floor(this.random() * intervalMs)
515
+ );
516
+ }
517
+ }
518
+
519
+ const PACER_KEY = Symbol.for('@friggframework/core.rate-limit-pacer');
520
+
521
+ /** The pacer of this process. Every requester shares it. */
522
+ function getRateLimitPacer() {
523
+ globalThis[PACER_KEY] ??= new RateLimitPacer();
524
+ return globalThis[PACER_KEY];
525
+ }
526
+
527
+ /** Replace the pacer of this process, for example with a custom store. */
528
+ function setRateLimitPacer(pacer) {
529
+ globalThis[PACER_KEY] = pacer ?? undefined;
530
+ }
531
+
532
+ module.exports = {
533
+ DEFAULT_MAX_BLOCK_MS,
534
+ DEFAULT_MAX_PACING_WAIT_MS,
535
+ DEFAULT_SHARED_CACHE_MS,
536
+ DEFAULT_SHARED_TIMEOUT_MS,
537
+ MAX_BLOCK_MS_ENV,
538
+ MAX_PACING_WAIT_MS_ENV,
539
+ PACING_ENV,
540
+ RateLimitPacer,
541
+ SHARED_CACHE_MS_ENV,
542
+ SHARED_TIMEOUT_MS_ENV,
543
+ TokenBucket,
544
+ bucketWindows,
545
+ getRateLimitPacer,
546
+ hashRateLimitScope,
547
+ intervalFromPolicyHeader,
548
+ maxPacingWaitMs,
549
+ pacingEnabled,
550
+ setRateLimitPacer,
551
+ };