@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
@@ -1,13 +1,29 @@
1
1
  const fetch = require('node-fetch');
2
2
  const { AsyncLocalStorage } = require('async_hooks');
3
3
  const { Delegate } = require('../../core');
4
- const { FetchError } = require('../../errors');
4
+ const {
5
+ invocationMaxInProcessWaitMs,
6
+ remainingInvocationMs,
7
+ } = require('../../core/invocation-deadline');
8
+ const { FetchError, RateLimitError } = require('../../errors');
5
9
  const { get } = require('../../assertions');
6
10
  const { getTelemetry } = require('../../telemetry/telemetry-runtime');
7
11
  const { getLogger } = require('../../logs');
8
12
  const { redactUrl } = require('../../logs/redact');
9
13
  const { toSanitizedSurrogate } = require('../../logs/serialize');
10
14
  const { getLoggerScope } = require('../../logs/context');
15
+ const {
16
+ computeScopeKey,
17
+ computeWaitMs,
18
+ inProcessBudgetMs,
19
+ readRateLimitPolicy,
20
+ resolveRateLimitHint,
21
+ } = require('./rate-limit');
22
+ const {
23
+ getRateLimitPacer,
24
+ maxPacingWaitMs,
25
+ pacingEnabled,
26
+ } = require('./rate-limit/pacer');
11
27
 
12
28
  const DEFAULT_REQUEST_TIMEOUT_MS = 60_000;
13
29
 
@@ -22,6 +38,12 @@ function sanitizedCause(err) {
22
38
  }
23
39
  const MAX_AUTH_RETRIES = 3;
24
40
 
41
+ // Hinted waits are bounded by time, but a provider that always answers with a
42
+ // short Retry-After would still keep the request in a long loop.
43
+ const MAX_HINTED_RETRIES = 10;
44
+ // A provider hint shorter than this still blocks the key this long.
45
+ const MIN_SCOPE_BLOCK_MS = 1_000;
46
+
25
47
  // This context marks the async call chain that holds the refresh slot, and
26
48
  // names the requester that holds it. Token requests re-enter _rawRequest
27
49
  // through this._post. A 401 from inside that chain must fail fast: if it
@@ -34,6 +56,8 @@ class Requester extends Delegate {
34
56
  constructor(params) {
35
57
  super(params);
36
58
  this.backOff = get(params, 'backOff', [1, 3, 10, 30, 60, 180]);
59
+ this._rateLimitPolicy = readRateLimitPolicy(this.constructor);
60
+ this._random = params?.random ?? Math.random;
37
61
  this.isRefreshable = false;
38
62
  this.refreshCount = 0;
39
63
  this.authGraceRetryCount = 0;
@@ -191,8 +215,18 @@ class Requester extends Delegate {
191
215
  return result;
192
216
  } catch (err) {
193
217
  const code = err?.status ?? err?.statusCode;
194
- const status = code ? String(code) : 'error';
195
- if (span && typeof span.setAttribute === 'function' && code) {
218
+ // A paced call was never sent: it is not a provider 429.
219
+ const status = err?.preempted
220
+ ? 'paced'
221
+ : code
222
+ ? String(code)
223
+ : 'error';
224
+ if (
225
+ span &&
226
+ typeof span.setAttribute === 'function' &&
227
+ code &&
228
+ !err?.preempted
229
+ ) {
196
230
  span.setAttribute('http.response.status_code', code);
197
231
  }
198
232
  telemetry.count(
@@ -211,9 +245,16 @@ class Requester extends Delegate {
211
245
  * @param {Object} options - Fetch options, as built by `_request`.
212
246
  * @param {number} attempt - 0-based count of retries already made for
213
247
  * this call. Indexes `this.backOff` for the next delay and is passed
214
- * back in on each recursive retry.
248
+ * back in on each recursive retry. A hinted retry leaves it unchanged.
249
+ * @param {{ waitedMs: number, retries: number }} hinted - The time slept
250
+ * and the retries made for rate-limit hints, for the whole call.
215
251
  */
216
- async _rawRequest(url, options, attempt = 0) {
252
+ async _rawRequest(
253
+ url,
254
+ options,
255
+ attempt = 0,
256
+ hinted = { waitedMs: 0, retries: 0 }
257
+ ) {
217
258
  let encodedUrl = encodeURI(url);
218
259
  if (options.query) {
219
260
  let queryBuild = '?';
@@ -225,6 +266,8 @@ class Requester extends Delegate {
225
266
  encodedUrl += queryBuild.slice(0, -1);
226
267
  }
227
268
 
269
+ await this._paceRequest(encodedUrl, options, hinted);
270
+
228
271
  options.headers = await this.addAuthHeaders(options.headers);
229
272
 
230
273
  // A 401 that arrives after a concurrent refresh is stale. It is not
@@ -279,7 +322,7 @@ class Requester extends Delegate {
279
322
  clearRequestTimer();
280
323
  const delay = this.backOff[attempt] * 1000;
281
324
  await new Promise((resolve) => setTimeout(resolve, delay));
282
- return this._rawRequest(url, options, attempt + 1);
325
+ return this._rawRequest(url, options, attempt + 1, hinted);
283
326
  }
284
327
  const fetchError = await FetchError.create({
285
328
  resource: encodedUrl,
@@ -298,15 +341,46 @@ class Requester extends Delegate {
298
341
 
299
342
  const { status } = response;
300
343
 
344
+ await this._observeRateLimit(response);
345
+
346
+ const throttle = await this._detectThrottle(
347
+ response,
348
+ status,
349
+ attempt
350
+ );
351
+ const hintedDelayMs = await this._hintedRetryDelayMs({
352
+ throttle,
353
+ status,
354
+ attempt,
355
+ hinted,
356
+ encodedUrl,
357
+ options,
358
+ response,
359
+ timeoutMs,
360
+ });
361
+ if (hintedDelayMs !== null) {
362
+ clearRequestTimer();
363
+ await new Promise((resolve) =>
364
+ setTimeout(resolve, hintedDelayMs)
365
+ );
366
+ return this._rawRequest(url, options, attempt, {
367
+ waitedMs: hinted.waitedMs + hintedDelayMs,
368
+ retries: hinted.retries + 1,
369
+ });
370
+ }
371
+
301
372
  // If the status is retriable and there are back off requests left, retry the request
302
373
  if (
303
- (status === 429 || status >= 500) &&
374
+ (throttle?.throttled || status >= 500) &&
304
375
  attempt < this.backOff.length
305
376
  ) {
306
377
  clearRequestTimer();
307
378
  const delay = this.backOff[attempt] * 1000;
379
+ if (throttle?.throttled) {
380
+ await this._blockScope(Date.now() + delay);
381
+ }
308
382
  await new Promise((resolve) => setTimeout(resolve, delay));
309
- return this._rawRequest(url, options, attempt + 1);
383
+ return this._rawRequest(url, options, attempt + 1, hinted);
310
384
  }
311
385
 
312
386
  if (status === 401) {
@@ -327,7 +401,7 @@ class Requester extends Delegate {
327
401
  // This request did not try the current token. Retry with
328
402
  // it. Do not spend one more provider-side rotation.
329
403
  clearRequestTimer();
330
- return this._rawRequest(url, options, attempt + 1);
404
+ return this._rawRequest(url, options, attempt + 1, hinted);
331
405
  }
332
406
 
333
407
  if (!this.isRefreshable) {
@@ -344,7 +418,12 @@ class Requester extends Delegate {
344
418
  await new Promise((resolve) =>
345
419
  setTimeout(resolve, delay)
346
420
  );
347
- return this._rawRequest(url, options, attempt + 1);
421
+ return this._rawRequest(
422
+ url,
423
+ options,
424
+ attempt + 1,
425
+ hinted
426
+ );
348
427
  }
349
428
 
350
429
  throw await this._invalidateAuth(
@@ -377,7 +456,7 @@ class Requester extends Delegate {
377
456
  const refreshSucceeded = await this._refreshAuthOnce();
378
457
  if (refreshSucceeded) {
379
458
  clearRequestTimer();
380
- return this._rawRequest(url, options, attempt + 1);
459
+ return this._rawRequest(url, options, attempt + 1, hinted);
381
460
  }
382
461
 
383
462
  throw await this._invalidateAuth(encodedUrl, options, response);
@@ -392,6 +471,7 @@ class Requester extends Delegate {
392
471
  resource: encodedUrl,
393
472
  init: options,
394
473
  response,
474
+ responseBody: throttle?.responseBody,
395
475
  });
396
476
  throw this._maybeFlagTimeoutDuringBodyRead(
397
477
  fetchError,
@@ -421,6 +501,272 @@ class Requester extends Delegate {
421
501
  }
422
502
  }
423
503
 
504
+ async _hintedRetryDelayMs({
505
+ throttle,
506
+ status,
507
+ attempt,
508
+ hinted,
509
+ encodedUrl,
510
+ options,
511
+ response,
512
+ timeoutMs,
513
+ }) {
514
+ if (!throttle?.throttled || throttle.hint.source === 'backoff') {
515
+ return null;
516
+ }
517
+ const { hint } = throttle;
518
+ const untimed = hint.waitMs === undefined;
519
+ const mayWait =
520
+ this.backOff.length > 0 && hinted.retries < MAX_HINTED_RETRIES;
521
+ const budgetMs = mayWait
522
+ ? inProcessBudgetMs({
523
+ maxInProcessWaitMs: invocationMaxInProcessWaitMs(),
524
+ requestTimeoutMs: this.requestTimeoutMs,
525
+ remainingMs: remainingInvocationMs(),
526
+ waitedMs: hinted.waitedMs,
527
+ })
528
+ : 0;
529
+ const { waitMs, fits } = untimed
530
+ ? { waitMs: undefined, fits: false }
531
+ : computeWaitMs({
532
+ hint,
533
+ policy: this._rateLimitPolicy,
534
+ budgetMs,
535
+ random: this._random,
536
+ });
537
+ // Block the key for the provider's time only. minRetryAfterMs and
538
+ // the jitter delay this message, not every other call on the key.
539
+ if (!untimed) {
540
+ await this._blockScope(
541
+ Date.now() + Math.max(hint.waitMs, MIN_SCOPE_BLOCK_MS)
542
+ );
543
+ }
544
+ if (fits) {
545
+ this._logRateLimited({
546
+ status,
547
+ hint,
548
+ waitMs,
549
+ attempt,
550
+ waitedMs: hinted.waitedMs,
551
+ });
552
+ return waitMs;
553
+ }
554
+
555
+ this._logRequestFailed(encodedUrl, options, status);
556
+ const retryWaitMs = untimed
557
+ ? undefined
558
+ : await this._spreadRetryWaitMs(waitMs);
559
+ const rateLimitError = await RateLimitError.create({
560
+ resource: encodedUrl,
561
+ init: options,
562
+ response,
563
+ responseBody: throttle.responseBody,
564
+ hint,
565
+ waitMs: retryWaitMs,
566
+ module: this._telemetryModuleLabel(),
567
+ scopeKey: computeScopeKey(this._rateLimitPolicy, this),
568
+ });
569
+ if (retryWaitMs !== undefined && this._pacingScopeKey()) {
570
+ rateLimitError.paced = true;
571
+ }
572
+ throw this._maybeFlagTimeoutDuringBodyRead(rateLimitError, timeoutMs);
573
+ }
574
+
575
+ // ADR-049 section 6: pacing. Every requester in the process shares one
576
+ // pacer, so a new requester for each queue message still sees the block.
577
+ _pacingScopeKey() {
578
+ const policy = this._rateLimitPolicy;
579
+ if (!policy || policy.pacing === false || !pacingEnabled()) {
580
+ return undefined;
581
+ }
582
+ return computeScopeKey(policy, this);
583
+ }
584
+
585
+ // Shared state (`shared: true`) lives on the Entity row of the module.
586
+ _pacingEntityId() {
587
+ return this.delegate?.entity?.id ?? undefined;
588
+ }
589
+
590
+ async _paceRequest(encodedUrl, options, hinted) {
591
+ // A token request inside a refresh must not wait for the key, or
592
+ // defer: the refresh would fail and the credential would be lost.
593
+ if (this._isInsideRefreshFlow()) return;
594
+ const scopeKey = this._pacingScopeKey();
595
+ if (!scopeKey) return;
596
+
597
+ const policy = this._rateLimitPolicy;
598
+ const pacer = getRateLimitPacer();
599
+ // A short pacing sleep costs less than a deferral, so it may pass the
600
+ // caller's hinted-wait budget (0 in a queue worker), up to a cap.
601
+ const budgetMs = inProcessBudgetMs({
602
+ maxInProcessWaitMs: Math.max(
603
+ invocationMaxInProcessWaitMs(),
604
+ maxPacingWaitMs()
605
+ ),
606
+ requestTimeoutMs: this.requestTimeoutMs,
607
+ remainingMs: remainingInvocationMs(),
608
+ waitedMs: hinted.waitedMs,
609
+ });
610
+ const entityId = this._pacingEntityId();
611
+ const gate = await pacer.acquire({
612
+ scopeKey,
613
+ entityId,
614
+ policy,
615
+ budgetMs,
616
+ });
617
+ if (gate.granted) {
618
+ if (gate.waitMs > 0) {
619
+ this._logPaced(gate, scopeKey);
620
+ hinted.waitedMs += gate.waitMs;
621
+ await new Promise((resolve) =>
622
+ setTimeout(resolve, gate.waitMs)
623
+ );
624
+ }
625
+ return;
626
+ }
627
+
628
+ const now = Date.now();
629
+ const retryAt = await pacer.reserveRetry({
630
+ scopeKey,
631
+ entityId,
632
+ policy,
633
+ notBefore: new Date(now + gate.waitMs),
634
+ waitMs: gate.waitMs,
635
+ });
636
+ const error = new RateLimitError({
637
+ resource: encodedUrl,
638
+ init: options,
639
+ hint: { reason: 'burst', source: 'pacer' },
640
+ waitMs: Math.max(0, retryAt.getTime() - now),
641
+ module: this._telemetryModuleLabel(),
642
+ scopeKey,
643
+ now,
644
+ });
645
+ error.statusCode = 429;
646
+ error.preempted = true;
647
+ error.paced = true;
648
+ error.message = `${error.message} paced: not sent`;
649
+ this._logPaced(gate, scopeKey, error);
650
+ throw error;
651
+ }
652
+
653
+ async _observeRateLimit(response) {
654
+ // A token endpoint can count on its own limit: its headers must not
655
+ // block the API key.
656
+ if (this._isInsideRefreshFlow()) return;
657
+ const scopeKey = this._pacingScopeKey();
658
+ if (!scopeKey || !response?.headers) return;
659
+ await getRateLimitPacer().observe({
660
+ scopeKey,
661
+ entityId: this._pacingEntityId(),
662
+ policy: this._rateLimitPolicy,
663
+ headers: response.headers,
664
+ status: response.status,
665
+ });
666
+ }
667
+
668
+ async _blockScope(untilMs) {
669
+ if (this._isInsideRefreshFlow()) return;
670
+ const scopeKey = this._pacingScopeKey();
671
+ if (!scopeKey || !Number.isFinite(untilMs)) return;
672
+ await getRateLimitPacer().block({
673
+ scopeKey,
674
+ entityId: this._pacingEntityId(),
675
+ policy: this._rateLimitPolicy,
676
+ until: new Date(untilMs),
677
+ });
678
+ }
679
+
680
+ // The wait of a thrown RateLimitError, spread across the scope's backlog.
681
+ async _spreadRetryWaitMs(waitMs) {
682
+ const scopeKey = this._pacingScopeKey();
683
+ if (!scopeKey) return waitMs;
684
+ const now = Date.now();
685
+ const retryAt = await getRateLimitPacer().reserveRetry({
686
+ scopeKey,
687
+ entityId: this._pacingEntityId(),
688
+ policy: this._rateLimitPolicy,
689
+ notBefore: new Date(now + waitMs),
690
+ waitMs,
691
+ });
692
+ return Math.max(waitMs, retryAt.getTime() - now);
693
+ }
694
+
695
+ _logPaced(gate, scopeKey, error) {
696
+ const logger = this.logger;
697
+ logger.trace(error ? 'Request deferred by pacer' : 'Request paced', {
698
+ eventName: `${logger.name}.${error ? 'rate_limit_deferred' : 'rate_limit_paced'}`,
699
+ waitMs: gate.waitMs,
700
+ reason: gate.reason,
701
+ scopeKey,
702
+ ...(error && { retryAt: error.retryAt?.toISOString() }),
703
+ });
704
+ }
705
+
706
+ async _detectThrottle(response, status, attempt) {
707
+ const policy = this._rateLimitPolicy;
708
+ const canClassify =
709
+ typeof policy?.classify === 'function' &&
710
+ status >= 400 &&
711
+ status !== 401;
712
+ if (status !== 429 && !canClassify) return null;
713
+
714
+ let responseBody;
715
+ let body;
716
+ if (canClassify) {
717
+ ({ text: responseBody, json: body } =
718
+ await this._readBodyForClassify(response));
719
+ }
720
+
721
+ const hint = resolveRateLimitHint(
722
+ policy,
723
+ { status, headers: response.headers, body },
724
+ {
725
+ attempt,
726
+ backOff: this.backOff,
727
+ now: Date.now(),
728
+ onClassifyError: (error) =>
729
+ this._logClassifyFailed(status, error),
730
+ }
731
+ );
732
+ return { throttled: Boolean(hint), hint, responseBody };
733
+ }
734
+
735
+ async _readBodyForClassify(response) {
736
+ if (response.bodyUsed || typeof response.text !== 'function') {
737
+ return {};
738
+ }
739
+ const text = await response.text();
740
+ try {
741
+ return { text, json: JSON.parse(text) };
742
+ } catch {
743
+ return { text };
744
+ }
745
+ }
746
+
747
+ _logRateLimited({ status, hint, waitMs, attempt, waitedMs }) {
748
+ const logger = this.logger;
749
+ logger.trace('Rate limited', {
750
+ eventName: `${logger.name}.rate_limited`,
751
+ statusCode: status,
752
+ waitMs,
753
+ retryAt: new Date(Date.now() + waitMs).toISOString(),
754
+ reason: hint.reason,
755
+ hintSource: hint.source,
756
+ attempt,
757
+ waitedMs,
758
+ });
759
+ }
760
+
761
+ _logClassifyFailed(status, error) {
762
+ const logger = this.logger;
763
+ logger.warn('Rate limit classifier failed', {
764
+ eventName: `${logger.name}.rate_limit_classify_failed`,
765
+ statusCode: status,
766
+ error,
767
+ });
768
+ }
769
+
424
770
  _logRequestFailed(encodedUrl, options, status) {
425
771
  const logger = this.logger;
426
772
  if (!logger.isLevelEnabled('DEBUG')) return;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@friggframework/core",
3
3
  "prettier": "@friggframework/prettier-config",
4
- "version": "2.0.0--canary.737.83b4e17.0",
4
+ "version": "2.0.0--canary.743.57dc4bf.0",
5
5
  "dependencies": {
6
6
  "@aws-sdk/client-apigatewaymanagementapi": "^3.588.0",
7
7
  "@aws-sdk/client-kms": "^3.588.0",
@@ -11,7 +11,7 @@
11
11
  "@aws-sdk/client-sqs": "^3.588.0",
12
12
  "@aws-sdk/client-ssm": "^3.588.0",
13
13
  "@aws-sdk/s3-request-presigner": "^3.588.0",
14
- "@friggframework/schemas": "2.0.0--canary.737.83b4e17.0",
14
+ "@friggframework/schemas": "2.0.0--canary.743.57dc4bf.0",
15
15
  "@hapi/boom": "^10.0.1",
16
16
  "@opentelemetry/api": "^1.9.1",
17
17
  "@opentelemetry/context-async-hooks": "^2.9.0",
@@ -49,12 +49,13 @@
49
49
  }
50
50
  },
51
51
  "devDependencies": {
52
- "@friggframework/eslint-config": "2.0.0--canary.737.83b4e17.0",
53
- "@friggframework/prettier-config": "2.0.0--canary.737.83b4e17.0",
54
- "@friggframework/test": "2.0.0--canary.737.83b4e17.0",
52
+ "@friggframework/eslint-config": "2.0.0--canary.743.57dc4bf.0",
53
+ "@friggframework/prettier-config": "2.0.0--canary.743.57dc4bf.0",
54
+ "@friggframework/test": "2.0.0--canary.743.57dc4bf.0",
55
55
  "@prisma/client": "^6.19.3",
56
56
  "@types/lodash": "4.17.15",
57
57
  "@typescript-eslint/eslint-plugin": "^8.0.0",
58
+ "aws-sdk-client-mock": "^4.1.0",
58
59
  "chai": "^4.3.6",
59
60
  "eslint": "^8.22.0",
60
61
  "eslint-plugin-import": "^2.29.1",
@@ -92,5 +93,5 @@
92
93
  "publishConfig": {
93
94
  "access": "public"
94
95
  },
95
- "gitHead": "83b4e17ac7ec4481bd8143508a2a532e399fcce8"
96
+ "gitHead": "57dc4bfa7d4bd3dbf00a286355c7e4c041acd0fe"
96
97
  }
@@ -0,0 +1,155 @@
1
+ const { toPositiveInteger } = require('./queue-delivery');
2
+
3
+ const MAX_DEFERRALS = 30;
4
+ const MAX_DEFERRED_MS = 26 * 60 * 60 * 1000;
5
+ const RATE_LIMIT_PROBE_MS = 60 * 60 * 1000;
6
+ const MAX_DELAY_SECONDS = 900;
7
+ const MAX_VISIBILITY_TIMEOUT_SECONDS = 43_200;
8
+ const MAX_LAMBDA_RUN_SECONDS = 900;
9
+ const MAX_BATCHING_WINDOW_SECONDS = 300;
10
+ const MAX_DEFERRED_VISIBILITY_SECONDS =
11
+ MAX_VISIBILITY_TIMEOUT_SECONDS -
12
+ MAX_LAMBDA_RUN_SECONDS -
13
+ MAX_BATCHING_WINDOW_SECONDS;
14
+ const MAX_DEFERRALS_ENV = 'FRIGG_QUEUE_MAX_DEFERRALS';
15
+ const MAX_DEFERRED_MS_ENV = 'FRIGG_QUEUE_MAX_DEFERRED_MS';
16
+ const RATE_LIMIT_PROBE_MS_ENV = 'FRIGG_QUEUE_RATE_LIMIT_PROBE_MS';
17
+ // Full jitter on a deferral that the requester did not already spread: the
18
+ // retry lands at a random point in [retryAt, retryAt + min(wait, max)]. One
19
+ // shared retryAt for a whole backlog made every message come back in the same
20
+ // second (a thundering herd).
21
+ const DEFERRAL_JITTER_MAX_MS = 5 * 60 * 1000;
22
+ const DEFERRAL_JITTER_MAX_MS_ENV = 'FRIGG_QUEUE_DEFERRAL_JITTER_MAX_MS';
23
+ // A pacer deferral (no call sent) does not use the deferral count, up to this
24
+ // number. Past it, each one counts: a key that never gets free must not hold
25
+ // a message for the full time cap with no end.
26
+ const MAX_PACED_DEFERRALS = 100;
27
+ const MAX_PACED_DEFERRALS_ENV = 'FRIGG_QUEUE_MAX_PACED_DEFERRALS';
28
+
29
+ const readDeferralLimits = (env = process.env) => ({
30
+ maxDeferrals: toPositiveInteger(env[MAX_DEFERRALS_ENV]) ?? MAX_DEFERRALS,
31
+ maxDeferredMs:
32
+ toPositiveInteger(env[MAX_DEFERRED_MS_ENV]) ?? MAX_DEFERRED_MS,
33
+ probeMs:
34
+ toPositiveInteger(env[RATE_LIMIT_PROBE_MS_ENV]) ?? RATE_LIMIT_PROBE_MS,
35
+ jitterMaxMs: readJitterMaxMs(env),
36
+ maxPacedDeferrals:
37
+ toPositiveInteger(env[MAX_PACED_DEFERRALS_ENV]) ?? MAX_PACED_DEFERRALS,
38
+ });
39
+
40
+ function readJitterMaxMs(env) {
41
+ const raw = env[DEFERRAL_JITTER_MAX_MS_ENV];
42
+ if (raw === '0') return 0;
43
+ return toPositiveInteger(raw) ?? DEFERRAL_JITTER_MAX_MS;
44
+ }
45
+
46
+ /**
47
+ * @param {Date} retryAt the earliest time the provider allows
48
+ * @param {number} waitMs the wait until retryAt
49
+ * @param {Object} limits
50
+ * @param {number} limits.jitterMaxMs
51
+ * @param {number} [limits.now] when retryAt is in the SQS delay range from
52
+ * `now`, the result stays in it: the jitter must not move a short wait to
53
+ * the scheduler or to the visibility timeout.
54
+ * @returns {Date} retryAt plus a random part of min(waitMs, jitterMaxMs)
55
+ */
56
+ const jitteredRetryAt = (
57
+ retryAt,
58
+ waitMs,
59
+ { jitterMaxMs, now },
60
+ random = Math.random
61
+ ) => {
62
+ let spread = Math.min(Math.max(0, waitMs), jitterMaxMs);
63
+ if (Number.isFinite(now)) {
64
+ const delayEnd = now + MAX_DELAY_SECONDS * 1000;
65
+ if (retryAt.getTime() <= delayEnd) {
66
+ spread = Math.min(spread, delayEnd - retryAt.getTime());
67
+ }
68
+ }
69
+ return new Date(retryAt.getTime() + Math.floor(random() * spread));
70
+ };
71
+
72
+ const readDeferral = (body) => {
73
+ const frigg = body?._frigg;
74
+ const deferrals =
75
+ Number.isInteger(frigg?.deferrals) && frigg.deferrals > 0
76
+ ? frigg.deferrals
77
+ : 0;
78
+ const firstDeferredAt =
79
+ typeof frigg?.firstDeferredAt === 'string' &&
80
+ !Number.isNaN(Date.parse(frigg.firstDeferredAt))
81
+ ? frigg.firstDeferredAt
82
+ : undefined;
83
+ const pacedDeferrals =
84
+ Number.isInteger(frigg?.pacedDeferrals) && frigg.pacedDeferrals > 0
85
+ ? frigg.pacedDeferrals
86
+ : undefined;
87
+ const deferralId =
88
+ typeof frigg?.deferralId === 'string' && frigg.deferralId !== ''
89
+ ? frigg.deferralId
90
+ : undefined;
91
+ return {
92
+ deferrals,
93
+ firstDeferredAt,
94
+ deferralId,
95
+ ...(pacedDeferrals && { pacedDeferrals }),
96
+ };
97
+ };
98
+
99
+ /**
100
+ * A deferral by the pacer (`preempted`: no call was sent) does not count
101
+ * against maxDeferrals. The key was known to be busy, so the message did not
102
+ * fail. The time cap still applies to it. After `maxPacedDeferrals` of them,
103
+ * a pacer deferral counts as a normal one.
104
+ */
105
+ const nextDeferral = (
106
+ body,
107
+ now = Date.now(),
108
+ messageId,
109
+ { preempted = false, maxPacedDeferrals = MAX_PACED_DEFERRALS } = {}
110
+ ) => {
111
+ const current = readDeferral(body);
112
+ const pacedBefore = current.pacedDeferrals ?? 0;
113
+ const free = preempted && pacedBefore < maxPacedDeferrals;
114
+ const paced = pacedBefore + (free ? 1 : 0);
115
+ return {
116
+ deferrals: current.deferrals + (free ? 0 : 1),
117
+ ...(paced > 0 && { pacedDeferrals: paced }),
118
+ firstDeferredAt: current.firstDeferredAt ?? new Date(now).toISOString(),
119
+ deferralId: current.deferralId ?? messageId,
120
+ };
121
+ };
122
+
123
+ const withDeferral = (body, deferral) => ({
124
+ ...body,
125
+ _frigg: { ...body._frigg, ...deferral },
126
+ });
127
+
128
+ const deferredMs = ({ firstDeferredAt, retryAt }) =>
129
+ retryAt.getTime() - Date.parse(firstDeferredAt);
130
+
131
+ const isDeferralCapped = (deferral, { maxDeferrals, maxDeferredMs }) =>
132
+ deferral.deferrals > maxDeferrals || deferredMs(deferral) > maxDeferredMs;
133
+
134
+ module.exports = {
135
+ DEFERRAL_JITTER_MAX_MS,
136
+ DEFERRAL_JITTER_MAX_MS_ENV,
137
+ MAX_DEFERRALS,
138
+ MAX_DEFERRALS_ENV,
139
+ MAX_PACED_DEFERRALS,
140
+ MAX_PACED_DEFERRALS_ENV,
141
+ MAX_DEFERRED_MS,
142
+ MAX_DEFERRED_MS_ENV,
143
+ MAX_DEFERRED_VISIBILITY_SECONDS,
144
+ MAX_DELAY_SECONDS,
145
+ MAX_VISIBILITY_TIMEOUT_SECONDS,
146
+ RATE_LIMIT_PROBE_MS,
147
+ RATE_LIMIT_PROBE_MS_ENV,
148
+ deferredMs,
149
+ isDeferralCapped,
150
+ jitteredRetryAt,
151
+ nextDeferral,
152
+ readDeferral,
153
+ readDeferralLimits,
154
+ withDeferral,
155
+ };
@@ -38,4 +38,5 @@ module.exports = {
38
38
  INTEGRATION_QUEUE_MAX_RECEIVE_COUNT,
39
39
  QUEUE_MAX_RECEIVE_COUNT_ENV,
40
40
  readQueueDelivery,
41
+ toPositiveInteger,
41
42
  };