@friggframework/core 2.0.0-next.128 → 2.0.0-next.129

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 (43) hide show
  1. package/CLAUDE.md +166 -7
  2. package/core/CLAUDE.md +57 -1
  3. package/core/Worker.js +420 -9
  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 +18 -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 +4 -0
  32. package/modules/requester/rate-limit/parsers.js +249 -0
  33. package/modules/requester/rate-limit/policy.js +321 -0
  34. package/modules/requester/requester.js +187 -9
  35. package/package.json +7 -6
  36. package/queues/queue-deferral.js +80 -0
  37. package/queues/queue-delivery.js +1 -0
  38. package/queues/queuer-util.js +1 -1
  39. package/types/core/consumer.fixture.ts +12 -0
  40. package/types/core/index.d.ts +84 -0
  41. package/types/errors/index.d.ts +47 -0
  42. package/types/integrations/index.d.ts +25 -4
  43. package/types/module-plugin/index.d.ts +45 -0
@@ -1,13 +1,24 @@
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');
11
22
 
12
23
  const DEFAULT_REQUEST_TIMEOUT_MS = 60_000;
13
24
 
@@ -22,6 +33,10 @@ function sanitizedCause(err) {
22
33
  }
23
34
  const MAX_AUTH_RETRIES = 3;
24
35
 
36
+ // Hinted waits are bounded by time, but a provider that always answers with a
37
+ // short Retry-After would still keep the request in a long loop.
38
+ const MAX_HINTED_RETRIES = 10;
39
+
25
40
  // This context marks the async call chain that holds the refresh slot, and
26
41
  // names the requester that holds it. Token requests re-enter _rawRequest
27
42
  // through this._post. A 401 from inside that chain must fail fast: if it
@@ -34,6 +49,8 @@ class Requester extends Delegate {
34
49
  constructor(params) {
35
50
  super(params);
36
51
  this.backOff = get(params, 'backOff', [1, 3, 10, 30, 60, 180]);
52
+ this._rateLimitPolicy = readRateLimitPolicy(this.constructor);
53
+ this._random = params?.random ?? Math.random;
37
54
  this.isRefreshable = false;
38
55
  this.refreshCount = 0;
39
56
  this.authGraceRetryCount = 0;
@@ -211,9 +228,16 @@ class Requester extends Delegate {
211
228
  * @param {Object} options - Fetch options, as built by `_request`.
212
229
  * @param {number} attempt - 0-based count of retries already made for
213
230
  * this call. Indexes `this.backOff` for the next delay and is passed
214
- * back in on each recursive retry.
231
+ * back in on each recursive retry. A hinted retry leaves it unchanged.
232
+ * @param {{ waitedMs: number, retries: number }} hinted - The time slept
233
+ * and the retries made for rate-limit hints, for the whole call.
215
234
  */
216
- async _rawRequest(url, options, attempt = 0) {
235
+ async _rawRequest(
236
+ url,
237
+ options,
238
+ attempt = 0,
239
+ hinted = { waitedMs: 0, retries: 0 }
240
+ ) {
217
241
  let encodedUrl = encodeURI(url);
218
242
  if (options.query) {
219
243
  let queryBuild = '?';
@@ -279,7 +303,7 @@ class Requester extends Delegate {
279
303
  clearRequestTimer();
280
304
  const delay = this.backOff[attempt] * 1000;
281
305
  await new Promise((resolve) => setTimeout(resolve, delay));
282
- return this._rawRequest(url, options, attempt + 1);
306
+ return this._rawRequest(url, options, attempt + 1, hinted);
283
307
  }
284
308
  const fetchError = await FetchError.create({
285
309
  resource: encodedUrl,
@@ -298,15 +322,41 @@ class Requester extends Delegate {
298
322
 
299
323
  const { status } = response;
300
324
 
325
+ const throttle = await this._detectThrottle(
326
+ response,
327
+ status,
328
+ attempt
329
+ );
330
+ const hintedDelayMs = await this._hintedRetryDelayMs({
331
+ throttle,
332
+ status,
333
+ attempt,
334
+ hinted,
335
+ encodedUrl,
336
+ options,
337
+ response,
338
+ timeoutMs,
339
+ });
340
+ if (hintedDelayMs !== null) {
341
+ clearRequestTimer();
342
+ await new Promise((resolve) =>
343
+ setTimeout(resolve, hintedDelayMs)
344
+ );
345
+ return this._rawRequest(url, options, attempt, {
346
+ waitedMs: hinted.waitedMs + hintedDelayMs,
347
+ retries: hinted.retries + 1,
348
+ });
349
+ }
350
+
301
351
  // If the status is retriable and there are back off requests left, retry the request
302
352
  if (
303
- (status === 429 || status >= 500) &&
353
+ (throttle?.throttled || status >= 500) &&
304
354
  attempt < this.backOff.length
305
355
  ) {
306
356
  clearRequestTimer();
307
357
  const delay = this.backOff[attempt] * 1000;
308
358
  await new Promise((resolve) => setTimeout(resolve, delay));
309
- return this._rawRequest(url, options, attempt + 1);
359
+ return this._rawRequest(url, options, attempt + 1, hinted);
310
360
  }
311
361
 
312
362
  if (status === 401) {
@@ -327,7 +377,7 @@ class Requester extends Delegate {
327
377
  // This request did not try the current token. Retry with
328
378
  // it. Do not spend one more provider-side rotation.
329
379
  clearRequestTimer();
330
- return this._rawRequest(url, options, attempt + 1);
380
+ return this._rawRequest(url, options, attempt + 1, hinted);
331
381
  }
332
382
 
333
383
  if (!this.isRefreshable) {
@@ -344,7 +394,12 @@ class Requester extends Delegate {
344
394
  await new Promise((resolve) =>
345
395
  setTimeout(resolve, delay)
346
396
  );
347
- return this._rawRequest(url, options, attempt + 1);
397
+ return this._rawRequest(
398
+ url,
399
+ options,
400
+ attempt + 1,
401
+ hinted
402
+ );
348
403
  }
349
404
 
350
405
  throw await this._invalidateAuth(
@@ -377,7 +432,7 @@ class Requester extends Delegate {
377
432
  const refreshSucceeded = await this._refreshAuthOnce();
378
433
  if (refreshSucceeded) {
379
434
  clearRequestTimer();
380
- return this._rawRequest(url, options, attempt + 1);
435
+ return this._rawRequest(url, options, attempt + 1, hinted);
381
436
  }
382
437
 
383
438
  throw await this._invalidateAuth(encodedUrl, options, response);
@@ -392,6 +447,7 @@ class Requester extends Delegate {
392
447
  resource: encodedUrl,
393
448
  init: options,
394
449
  response,
450
+ responseBody: throttle?.responseBody,
395
451
  });
396
452
  throw this._maybeFlagTimeoutDuringBodyRead(
397
453
  fetchError,
@@ -421,6 +477,128 @@ class Requester extends Delegate {
421
477
  }
422
478
  }
423
479
 
480
+ async _hintedRetryDelayMs({
481
+ throttle,
482
+ status,
483
+ attempt,
484
+ hinted,
485
+ encodedUrl,
486
+ options,
487
+ response,
488
+ timeoutMs,
489
+ }) {
490
+ if (!throttle?.throttled || throttle.hint.source === 'backoff') {
491
+ return null;
492
+ }
493
+ const { hint } = throttle;
494
+ const untimed = hint.waitMs === undefined;
495
+ const mayWait =
496
+ this.backOff.length > 0 && hinted.retries < MAX_HINTED_RETRIES;
497
+ const budgetMs = mayWait
498
+ ? inProcessBudgetMs({
499
+ maxInProcessWaitMs: invocationMaxInProcessWaitMs(),
500
+ requestTimeoutMs: this.requestTimeoutMs,
501
+ remainingMs: remainingInvocationMs(),
502
+ waitedMs: hinted.waitedMs,
503
+ })
504
+ : 0;
505
+ const { waitMs, fits } = untimed
506
+ ? { waitMs: undefined, fits: false }
507
+ : computeWaitMs({
508
+ hint,
509
+ policy: this._rateLimitPolicy,
510
+ budgetMs,
511
+ random: this._random,
512
+ });
513
+ if (fits) {
514
+ this._logRateLimited({
515
+ status,
516
+ hint,
517
+ waitMs,
518
+ attempt,
519
+ waitedMs: hinted.waitedMs,
520
+ });
521
+ return waitMs;
522
+ }
523
+
524
+ this._logRequestFailed(encodedUrl, options, status);
525
+ const rateLimitError = await RateLimitError.create({
526
+ resource: encodedUrl,
527
+ init: options,
528
+ response,
529
+ responseBody: throttle.responseBody,
530
+ hint,
531
+ waitMs,
532
+ module: this._telemetryModuleLabel(),
533
+ scopeKey: computeScopeKey(this._rateLimitPolicy, this),
534
+ });
535
+ throw this._maybeFlagTimeoutDuringBodyRead(rateLimitError, timeoutMs);
536
+ }
537
+
538
+ async _detectThrottle(response, status, attempt) {
539
+ const policy = this._rateLimitPolicy;
540
+ const canClassify =
541
+ typeof policy?.classify === 'function' &&
542
+ status >= 400 &&
543
+ status !== 401;
544
+ if (status !== 429 && !canClassify) return null;
545
+
546
+ let responseBody;
547
+ let body;
548
+ if (canClassify) {
549
+ ({ text: responseBody, json: body } =
550
+ await this._readBodyForClassify(response));
551
+ }
552
+
553
+ const hint = resolveRateLimitHint(
554
+ policy,
555
+ { status, headers: response.headers, body },
556
+ {
557
+ attempt,
558
+ backOff: this.backOff,
559
+ now: Date.now(),
560
+ onClassifyError: (error) =>
561
+ this._logClassifyFailed(status, error),
562
+ }
563
+ );
564
+ return { throttled: Boolean(hint), hint, responseBody };
565
+ }
566
+
567
+ async _readBodyForClassify(response) {
568
+ if (response.bodyUsed || typeof response.text !== 'function') {
569
+ return {};
570
+ }
571
+ const text = await response.text();
572
+ try {
573
+ return { text, json: JSON.parse(text) };
574
+ } catch {
575
+ return { text };
576
+ }
577
+ }
578
+
579
+ _logRateLimited({ status, hint, waitMs, attempt, waitedMs }) {
580
+ const logger = this.logger;
581
+ logger.trace('Rate limited', {
582
+ eventName: `${logger.name}.rate_limited`,
583
+ statusCode: status,
584
+ waitMs,
585
+ retryAt: new Date(Date.now() + waitMs).toISOString(),
586
+ reason: hint.reason,
587
+ hintSource: hint.source,
588
+ attempt,
589
+ waitedMs,
590
+ });
591
+ }
592
+
593
+ _logClassifyFailed(status, error) {
594
+ const logger = this.logger;
595
+ logger.warn('Rate limit classifier failed', {
596
+ eventName: `${logger.name}.rate_limit_classify_failed`,
597
+ statusCode: status,
598
+ error,
599
+ });
600
+ }
601
+
424
602
  _logRequestFailed(encodedUrl, options, status) {
425
603
  const logger = this.logger;
426
604
  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-next.128",
4
+ "version": "2.0.0-next.129",
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-next.128",
14
+ "@friggframework/schemas": "2.0.0-next.129",
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-next.128",
53
- "@friggframework/prettier-config": "2.0.0-next.128",
54
- "@friggframework/test": "2.0.0-next.128",
52
+ "@friggframework/eslint-config": "2.0.0-next.129",
53
+ "@friggframework/prettier-config": "2.0.0-next.129",
54
+ "@friggframework/test": "2.0.0-next.129",
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": "c116a4803d205e5b54a59d56d8b163ab43d66205"
96
+ "gitHead": "4326b2498dcb1627e43fceada462b384b722da52"
96
97
  }
@@ -0,0 +1,80 @@
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
+
18
+ const readDeferralLimits = (env = process.env) => ({
19
+ maxDeferrals: toPositiveInteger(env[MAX_DEFERRALS_ENV]) ?? MAX_DEFERRALS,
20
+ maxDeferredMs:
21
+ toPositiveInteger(env[MAX_DEFERRED_MS_ENV]) ?? MAX_DEFERRED_MS,
22
+ probeMs:
23
+ toPositiveInteger(env[RATE_LIMIT_PROBE_MS_ENV]) ?? RATE_LIMIT_PROBE_MS,
24
+ });
25
+
26
+ const readDeferral = (body) => {
27
+ const frigg = body?._frigg;
28
+ const deferrals =
29
+ Number.isInteger(frigg?.deferrals) && frigg.deferrals > 0
30
+ ? frigg.deferrals
31
+ : 0;
32
+ const firstDeferredAt =
33
+ typeof frigg?.firstDeferredAt === 'string' &&
34
+ !Number.isNaN(Date.parse(frigg.firstDeferredAt))
35
+ ? frigg.firstDeferredAt
36
+ : undefined;
37
+ const deferralId =
38
+ typeof frigg?.deferralId === 'string' && frigg.deferralId !== ''
39
+ ? frigg.deferralId
40
+ : undefined;
41
+ return { deferrals, firstDeferredAt, deferralId };
42
+ };
43
+
44
+ const nextDeferral = (body, now = Date.now(), messageId) => {
45
+ const current = readDeferral(body);
46
+ return {
47
+ deferrals: current.deferrals + 1,
48
+ firstDeferredAt: current.firstDeferredAt ?? new Date(now).toISOString(),
49
+ deferralId: current.deferralId ?? messageId,
50
+ };
51
+ };
52
+
53
+ const withDeferral = (body, deferral) => ({
54
+ ...body,
55
+ _frigg: { ...body._frigg, ...deferral },
56
+ });
57
+
58
+ const deferredMs = ({ firstDeferredAt, retryAt }) =>
59
+ retryAt.getTime() - Date.parse(firstDeferredAt);
60
+
61
+ const isDeferralCapped = (deferral, { maxDeferrals, maxDeferredMs }) =>
62
+ deferral.deferrals > maxDeferrals || deferredMs(deferral) > maxDeferredMs;
63
+
64
+ module.exports = {
65
+ MAX_DEFERRALS,
66
+ MAX_DEFERRALS_ENV,
67
+ MAX_DEFERRED_MS,
68
+ MAX_DEFERRED_MS_ENV,
69
+ MAX_DEFERRED_VISIBILITY_SECONDS,
70
+ MAX_DELAY_SECONDS,
71
+ MAX_VISIBILITY_TIMEOUT_SECONDS,
72
+ RATE_LIMIT_PROBE_MS,
73
+ RATE_LIMIT_PROBE_MS_ENV,
74
+ deferredMs,
75
+ isDeferralCapped,
76
+ nextDeferral,
77
+ readDeferral,
78
+ readDeferralLimits,
79
+ withDeferral,
80
+ };
@@ -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
  };
@@ -127,4 +127,4 @@ const QueuerUtil = {
127
127
  },
128
128
  };
129
129
 
130
- module.exports = { QueuerUtil };
130
+ module.exports = { QueuerUtil, awsConfigOptions };
@@ -0,0 +1,12 @@
1
+ /// <reference path="../index.d.ts" />
2
+ import { RateLimitError, parseResetHeaders } from "@friggframework/core";
3
+ import type { RateLimitPolicy } from "@friggframework/module-plugin";
4
+
5
+ const error = new RateLimitError({ waitMs: 1_000 });
6
+ const isRateLimited: true = error.isRateLimited;
7
+ const retryAt: Date | undefined = error.retryAt;
8
+
9
+ const policy: RateLimitPolicy = { resetDeltaUnit: "ms" };
10
+ const hint = parseResetHeaders({}, { now: 0, resetDeltaUnit: "ms" });
11
+
12
+ export { isRateLimited, retryAt, policy, hint };
@@ -1,5 +1,12 @@
1
1
  declare module "@friggframework/core" {
2
2
  import type { SendMessageCommandInput } from "@aws-sdk/client-sqs";
3
+ import type { RateLimitHint } from "@friggframework/errors";
4
+ import type {
5
+ RateLimitPolicy,
6
+ RateLimitSignal,
7
+ } from "@friggframework/module-plugin";
8
+
9
+ export { RateLimitError } from "@friggframework/errors";
3
10
 
4
11
  export class Delegate implements IFriggDelegate {
5
12
  delegate: any;
@@ -42,8 +49,57 @@ declare module "@friggframework/core" {
42
49
  send(params: object & { QueueUrl: any }, delay?: number): Promise<string>;
43
50
 
44
51
  sendAsyncSQSMessage(params: SendSQSMessageParams): Promise<string>;
52
+
53
+ recordRateLimitWait(
54
+ body: object,
55
+ error: Error,
56
+ state: RateLimitWaitState
57
+ ): Promise<void>;
58
+
59
+ clearRateLimitWait(
60
+ body: object,
61
+ options?: { deferralId?: string }
62
+ ): Promise<void>;
63
+
64
+ decideRateLimited(
65
+ event: RateLimitedEvent
66
+ ): Promise<RateLimitedDecision | void>;
67
+
68
+ /** Runs past the delay tier, for an unknown retryAt, or at a cap. */
69
+ recordRateLimitMessage(
70
+ body: object,
71
+ error: Error,
72
+ limit: { retryAt: Date; capped: boolean }
73
+ ): Promise<void>;
45
74
  }
46
75
 
76
+ /** ADR-049 section 3. The input of the RATE_LIMITED event handler. */
77
+ export type RateLimitedEvent = {
78
+ retryAt?: Date;
79
+ waitMs?: number;
80
+ reason?: string;
81
+ module?: string;
82
+ scopeKey?: string;
83
+ message: object;
84
+ delivery: {
85
+ messageId: string;
86
+ receiveCount?: number;
87
+ deferrals: number;
88
+ deferredMs: number;
89
+ };
90
+ };
91
+
92
+ /** `defer` or no value runs the default handler. A throw counts as `retry`. */
93
+ export type RateLimitedDecision = "defer" | "drop" | "retry";
94
+
95
+ export type RateLimitWaitState = {
96
+ status: "WAITING" | "EXHAUSTED";
97
+ mechanism: "delay" | "schedule" | "visibility" | "none";
98
+ deferrals: number;
99
+ deferralId?: string;
100
+ retryAt: Date;
101
+ };
102
+
47
103
  interface IWorker {
48
104
  getQueueURL(params: GetQueueURLParams): Promise<string | undefined>;
49
105
  run(params: { Records: any }, context?: object): Promise<BatchItemFailuresResponse>;
@@ -53,6 +109,34 @@ declare module "@friggframework/core" {
53
109
 
54
110
  export function loadInstalledModules(): any[];
55
111
 
112
+ export function runWithInvocationDeadline<T>(
113
+ limits: { deadlineAt?: number; maxInProcessWaitMs?: number },
114
+ fn: () => T
115
+ ): T;
116
+
117
+ export function remainingInvocationMs(now?: number): number;
118
+
119
+ export function classifyRateLimit(
120
+ policy: RateLimitPolicy | undefined,
121
+ signal: RateLimitSignal,
122
+ options?: { now?: number; onClassifyError?: (error: Error) => void }
123
+ ): RateLimitHint | null;
124
+
125
+ export function parseRetryAfter(
126
+ value: string | null | undefined,
127
+ options?: { now?: number }
128
+ ): RateLimitHint | null;
129
+
130
+ export function parseResetHeaders(
131
+ headers: object | undefined,
132
+ options?: { now?: number; resetDeltaUnit?: "s" | "ms" }
133
+ ): RateLimitHint | null;
134
+
135
+ export function parseIetfRateLimit(
136
+ headers: object | undefined,
137
+ options?: { now?: number }
138
+ ): RateLimitHint | null;
139
+
56
140
  type GetQueueURLParams = {
57
141
  QueueName: string;
58
142
  QueueOwnerAWSAccountId?: string;
@@ -16,10 +16,57 @@ declare module "@friggframework/errors" {
16
16
  readonly body: any;
17
17
  isTimeout?: boolean;
18
18
  timeoutMs?: number;
19
+ isRateLimited?: boolean;
20
+ reason?: RateLimitReason;
19
21
 
20
22
  static create(options?: CreateFetchErrorParams): Promise<FetchError>;
21
23
  }
22
24
 
25
+ export type RateLimitReason =
26
+ | "burst"
27
+ | "daily"
28
+ | "monthly"
29
+ | "concurrency"
30
+ | "unknown";
31
+
32
+ export type RateLimitSource = "header" | "body" | "static" | "backoff";
33
+
34
+ export type RateLimitHint = {
35
+ retryAt: Date;
36
+ waitMs: number;
37
+ reason: RateLimitReason;
38
+ policy?: string;
39
+ remaining?: number;
40
+ source: RateLimitSource;
41
+ };
42
+
43
+ export class RateLimitError extends FetchError {
44
+ constructor(options?: RateLimitErrorConstructor);
45
+
46
+ isRateLimited: true;
47
+ retryAt?: Date;
48
+ waitMs?: number;
49
+ reason: RateLimitReason;
50
+ policy?: string;
51
+ source: RateLimitSource | "unknown";
52
+ module?: string;
53
+ scopeKey?: string;
54
+
55
+ static create(
56
+ options?: CreateRateLimitErrorParams
57
+ ): Promise<RateLimitError>;
58
+ }
59
+
60
+ type RateLimitErrorConstructor = FetchErrorConstructor & {
61
+ hint?: Partial<RateLimitHint>;
62
+ waitMs?: number;
63
+ module?: string;
64
+ scopeKey?: string;
65
+ now?: number;
66
+ };
67
+
68
+ type CreateRateLimitErrorParams = RateLimitErrorConstructor;
69
+
23
70
  type FetchErrorResponse = {
24
71
  headers?: object;
25
72
  status?: number;
@@ -1,6 +1,27 @@
1
1
  declare module "@friggframework/integrations" {
2
2
  import { Delegate, IFriggDelegate } from "@friggframework/core";
3
3
 
4
+ export type IntegrationMessageAction =
5
+ | { type: "RETRY_WHEN_READY" }
6
+ | { type: "LINK"; label: string; url: string };
7
+
8
+ /** A stored integration message. Each type keeps its newest 50 items. */
9
+ export interface IntegrationMessage {
10
+ title: string | null;
11
+ message: string;
12
+ timestamp: number;
13
+ [key: string]: unknown;
14
+ }
15
+
16
+ /** ADR-049 section 5. Stored in `warnings`; `retryAt` is ISO UTC. */
17
+ export interface RateLimitedIntegrationMessage extends IntegrationMessage {
18
+ code: "RATE_LIMITED";
19
+ module: string;
20
+ reason: string;
21
+ retryAt: string;
22
+ actions: IntegrationMessageAction[];
23
+ }
24
+
4
25
  export interface Integration {
5
26
  entities: any[];
6
27
  userId: string;
@@ -8,10 +29,10 @@ declare module "@friggframework/integrations" {
8
29
  config: any;
9
30
  version: string;
10
31
  messages: {
11
- errors: [];
12
- warnings: [];
13
- info: [];
14
- logs: [];
32
+ errors: IntegrationMessage[];
33
+ warnings: IntegrationMessage[];
34
+ info: IntegrationMessage[];
35
+ logs: IntegrationMessage[];
15
36
  };
16
37
  }
17
38