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