@friggframework/core 2.0.0--canary.657.8f335eb.0 → 2.0.0--canary.656.7302a64.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.
package/CLAUDE.md CHANGED
@@ -546,58 +546,6 @@ The single source of the max receive count is
546
546
  devtools integration builder uses it for the queue's `RedrivePolicy` and sets
547
547
  it as `FRIGG_QUEUE_MAX_RECEIVE_COUNT` on the queue worker function.
548
548
 
549
- **Rate-limit deferral** (ADR-049): when a queue handler throws an error with
550
- `isRateLimited` and a `retryAt` (a `RateLimitError` from the Requester, or one a
551
- module throws), `Worker.run` does not give the message back to SQS for a 30
552
- minute redelivery that spends one of its three receives. It puts the message
553
- back so it runs at `retryAt`:
554
-
555
- | Wait | What the worker does | Record |
556
- |---|---|---|
557
- | Up to 900 s | Sends the same body again with `DelaySeconds`, then acknowledges the old message | handled |
558
- | Over 900 s, and `SCHEDULER_ROLE_ARN` is set | Creates a one-time EventBridge schedule at `retryAt` that sends the body to the queue, then acknowledges | handled |
559
- | Over 900 s, no scheduler | Extends the message's visibility timeout to `retryAt` (12 h at most). This uses one receive | reported failed |
560
-
561
- - The new message starts at receive count 1. A deferred body carries
562
- `_frigg: { deferrals, firstDeferredAt }`; `_frigg` is reserved and the handler
563
- never sees it.
564
- - Two caps bound it: `FRIGG_QUEUE_MAX_DEFERRALS` (default 10) and
565
- `FRIGG_QUEUE_MAX_DEFERRED_MS` (default 24 h, from the first deferral to the
566
- retry time). Past a cap, with no `retryAt`, with no event source ARN or on a
567
- FIFO queue, the record fails like any retryable error and `delivery`
568
- applies.
569
- - The mock scheduler is never used for a deferral: a schedule kept in memory
570
- would be lost with the acknowledged message.
571
- - With a `processId` in the message, the worker writes
572
- `Process.context.rateLimit = { status: 'WAITING' | 'EXHAUSTED', mechanism,
573
- retryAt, reason, module, deferrals, updatedAt }`, and `null` after the message
574
- ran. `EXHAUSTED` means a cap ended the deferrals, or a visibility change came
575
- on the last delivery.
576
- - Delivery stays at least once. The new message is sent before the old one is
577
- acknowledged, so a crash between the two can run the work twice.
578
- - Handlers check `delivery.isLastAttempt` first, then rethrow. The delay and
579
- schedule tiers send a new message, so they never reach the last attempt. The
580
- visibility tier and a cap use a receive: on the last one the worker writes an
581
- ERROR (`frigg.worker.record_lost_rate_limited`), and the handler has this one
582
- chance to end the run.
583
-
584
- ```javascript
585
- async processBatch({ data, delivery }) {
586
- try {
587
- await this.syncPage(data);
588
- } catch (error) {
589
- if (delivery?.isLastAttempt) return this.failRun(data.processId, error);
590
- throw error; // a RateLimitError too: core puts the message back at retryAt
591
- }
592
- }
593
- ```
594
-
595
- Records: `frigg.worker.record_deferred` (`mechanism` `delay` or `schedule`),
596
- `record_visibility_extended`, `record_deferral_capped`,
597
- `record_lost_rate_limited` and `rate_limit_state_failed`. A queue in a stack
598
- that does not own it (`ownership.queue: 'external'`) needs its own
599
- `sqs:ChangeMessageVisibility` and scheduler access.
600
-
601
549
  ### 8. Error Handling (`/errors`)
602
550
 
603
551
  **Purpose**: Standardized error types with proper HTTP semantics.
package/core/CLAUDE.md CHANGED
@@ -79,25 +79,6 @@ await worker.send({
79
79
  }, delaySeconds);
80
80
  ```
81
81
 
82
- **Rate-limit deferral** (ADR-049): `run()` handles an error with `isRateLimited`
83
- and a `retryAt` through `defer(record, body, error, delivery)`, which returns
84
- `{ outcome }`:
85
- - `acked`: the message was sent again with `DelaySeconds` (wait up to 900 s) or
86
- scheduled with the one-time scheduler (longer wait). The record is handled.
87
- - `failed`: the visibility timeout was extended to `retryAt`, or a cap
88
- (`FRIGG_QUEUE_MAX_DEFERRALS`, `FRIGG_QUEUE_MAX_DEFERRED_MS`) ended the
89
- deferrals. The record is reported failed.
90
- - `skipped`: no `retryAt`, no `eventSourceARN`, a FIFO queue, or a failed send.
91
- The record fails as any error does, and `record_failed` carries
92
- `deferral: { skipped }`.
93
-
94
- Subclasses override two no-op hooks to keep run state: `recordRateLimitWait(body,
95
- error, state)` runs after the message was put back, and `clearRateLimitWait(body)`
96
- runs after a deferred or redelivered message succeeded. A failing hook logs
97
- `frigg.worker.rate_limit_state_failed` and never changes the outcome. The queue
98
- worker of an integration (`createQueueWorker`) writes `Process.context.rateLimit`
99
- in them. See `packages/core/CLAUDE.md` section 7.
100
-
101
82
  ### Delegate Pattern System (`Delegate.js:3-27`)
102
83
 
103
84
  **Purpose**: Observer/delegation pattern for decoupled component communication
package/core/Worker.js CHANGED
@@ -1,39 +1,14 @@
1
- const { randomUUID } = require('node:crypto');
2
- const {
3
- SQSClient,
4
- GetQueueUrlCommand,
5
- SendMessageCommand,
6
- ChangeMessageVisibilityCommand,
7
- } = require('@aws-sdk/client-sqs');
1
+ const { SQSClient, GetQueueUrlCommand, SendMessageCommand } = require('@aws-sdk/client-sqs');
8
2
  const _ = require('lodash');
9
3
  const { RequiredPropertyError } = require('../errors');
10
4
  const { get } = require('../assertions');
11
5
  const { readQueueDelivery } = require('../queues/queue-delivery');
12
- const { awsConfigOptions } = require('../queues/queuer-util');
13
- const {
14
- MAX_DELAY_SECONDS,
15
- MAX_VISIBILITY_TIMEOUT_SECONDS,
16
- isDeferralCapped,
17
- nextDeferral,
18
- readDeferral,
19
- readDeferralLimits,
20
- withDeferral,
21
- } = require('../queues/queue-deferral');
22
6
  const { runMessageScope } = require('./invocation-scope');
23
- const { getLogger, serializeError } = require('../logs');
7
+ const { getLogger } = require('../logs');
24
8
 
25
- const sqs = new SQSClient({
26
- region: process.env.AWS_REGION,
27
- ...awsConfigOptions(),
28
- });
9
+ const sqs = new SQSClient({ region: process.env.AWS_REGION });
29
10
  const log = getLogger('frigg.worker');
30
11
 
31
- const validDate = (value) =>
32
- value instanceof Date && !Number.isNaN(value.getTime()) ? value : null;
33
- const queueNameOf = (arn) =>
34
- typeof arn === 'string' && arn ? arn.split(':').pop() : undefined;
35
- const causeOf = (error) => serializeError(error).message;
36
-
37
12
  class Worker {
38
13
  async getQueueURL(params) {
39
14
  // Passing params in because there will be multiple QueueNames
@@ -58,31 +33,12 @@ class Worker {
58
33
  // messageId, receiveCount and the event come from the scope.
59
34
  log.debug('Record started', { eventName: 'frigg.worker.record_started' });
60
35
 
61
- const delivery = readQueueDelivery(record);
62
- let runParams;
63
36
  try {
64
- runParams = JSON.parse(record.body);
37
+ const runParams = JSON.parse(record.body);
65
38
  this._validateParams(runParams);
66
- await this._run(runParams, context, delivery);
67
- await this._clearDeferredState(runParams, delivery);
39
+ await this._run(runParams, context, readQueueDelivery(record));
68
40
  log.debug('Record succeeded', { eventName: 'frigg.worker.record_succeeded' });
69
41
  } catch (error) {
70
- let deferral;
71
- if (error.isRateLimited && runParams) {
72
- deferral = await this.defer(
73
- record,
74
- runParams,
75
- error,
76
- delivery
77
- );
78
- if (deferral.outcome === 'acked') return;
79
- if (deferral.outcome === 'failed') {
80
- batchItemFailures.push({
81
- itemIdentifier: record.messageId,
82
- });
83
- return;
84
- }
85
- }
86
42
  if (error.isHaltError) {
87
43
  // HaltError means "discard this message, don't retry".
88
44
  // Treat as success so SQS deletes it from the queue.
@@ -99,14 +55,6 @@ class Worker {
99
55
  log.warn('Record failed, returned for retry', {
100
56
  eventName: 'frigg.worker.record_failed',
101
57
  error,
102
- ...(deferral && {
103
- deferral: {
104
- skipped: deferral.skipped,
105
- ...(deferral.cause && {
106
- cause: causeOf(deferral.cause),
107
- }),
108
- },
109
- }),
110
58
  });
111
59
  batchItemFailures.push({ itemIdentifier: record.messageId });
112
60
  }
@@ -127,240 +75,6 @@ class Worker {
127
75
  // parameters
128
76
  }
129
77
 
130
- /**
131
- * Puts a rate-limited message back so it runs at `error.retryAt`, without
132
- * spending a receive. The message is sent again with a delay of up to 900 s,
133
- * or scheduled with the one-time scheduler, or has its visibility timeout
134
- * extended. The new message goes out before the old one is acknowledged, so
135
- * delivery stays at least once.
136
- *
137
- * @returns {Promise<{outcome: 'acked'|'failed'|'skipped', skipped?: string, cause?: Error}>}
138
- * `acked`: the message is handled. `failed`: report the record failed and
139
- * let SQS redeliver it. `skipped`: nothing was done; fail the record as
140
- * any other error.
141
- */
142
- async defer(record, body, error, delivery) {
143
- const retryAt = validDate(error.retryAt);
144
- if (!retryAt) return { outcome: 'skipped', skipped: 'no_retry_at' };
145
- const queueName = queueNameOf(record.eventSourceARN);
146
- if (!queueName || queueName.endsWith('.fifo')) {
147
- return { outcome: 'skipped', skipped: 'no_event_source' };
148
- }
149
-
150
- const now = Date.now();
151
- const waitMs = Math.max(0, retryAt.getTime() - now);
152
- const deferral = nextDeferral(body, now);
153
- const details = {
154
- waitMs,
155
- retryAt: retryAt.toISOString(),
156
- deferrals: deferral.deferrals,
157
- firstDeferredAt: deferral.firstDeferredAt,
158
- reason: error.reason,
159
- module: error.module,
160
- statusCode: error.statusCode,
161
- };
162
- const state = (status, mechanism) => ({
163
- status,
164
- mechanism,
165
- deferrals: deferral.deferrals,
166
- retryAt,
167
- });
168
-
169
- const limits = readDeferralLimits();
170
- if (isDeferralCapped({ ...deferral, retryAt }, limits)) {
171
- log.warn('Rate-limit deferral capped', {
172
- eventName: 'frigg.worker.record_deferral_capped',
173
- ...details,
174
- maxDeferrals: limits.maxDeferrals,
175
- maxDeferredMs: limits.maxDeferredMs,
176
- deferredMs:
177
- retryAt.getTime() - Date.parse(deferral.firstDeferredAt),
178
- error,
179
- });
180
- await this._recordWait(body, error, state('EXHAUSTED', 'none'));
181
- this._logIfLost(delivery, error, details);
182
- return { outcome: 'failed' };
183
- }
184
-
185
- const next = withDeferral(body, deferral);
186
-
187
- if (waitMs <= MAX_DELAY_SECONDS * 1000) {
188
- const delaySeconds = Math.ceil(waitMs / 1000);
189
- try {
190
- const queueUrl = await this._queueUrl(queueName);
191
- await this.send({ ...next, QueueUrl: queueUrl }, delaySeconds);
192
- } catch (cause) {
193
- return { outcome: 'skipped', skipped: 'send_failed', cause };
194
- }
195
- await this._recordWait(body, error, state('WAITING', 'delay'));
196
- log.warn('Record deferred', {
197
- eventName: 'frigg.worker.record_deferred',
198
- mechanism: 'delay',
199
- delaySeconds,
200
- ...details,
201
- error,
202
- });
203
- return { outcome: 'acked' };
204
- }
205
-
206
- let scheduleError;
207
- const scheduler = this.getSchedulerService();
208
- if (scheduler) {
209
- const scheduleName = `frigg-defer-${
210
- record.messageId || randomUUID()
211
- }`;
212
- try {
213
- await scheduler.scheduleOneTime({
214
- scheduleName,
215
- scheduleAt: retryAt,
216
- queueResourceId: record.eventSourceARN,
217
- payload: next,
218
- });
219
- } catch (cause) {
220
- if (cause?.name !== 'ConflictException') scheduleError = cause;
221
- }
222
- if (!scheduleError) {
223
- await this._recordWait(
224
- body,
225
- error,
226
- state('WAITING', 'schedule')
227
- );
228
- log.warn('Record deferred', {
229
- eventName: 'frigg.worker.record_deferred',
230
- mechanism: 'schedule',
231
- scheduleName,
232
- ...details,
233
- error,
234
- });
235
- return { outcome: 'acked' };
236
- }
237
- }
238
-
239
- const visibilityTimeout = Math.min(
240
- Math.ceil(waitMs / 1000),
241
- MAX_VISIBILITY_TIMEOUT_SECONDS
242
- );
243
- try {
244
- const queueUrl = await this._queueUrl(queueName);
245
- await sqs.send(
246
- new ChangeMessageVisibilityCommand({
247
- QueueUrl: queueUrl,
248
- ReceiptHandle: record.receiptHandle,
249
- VisibilityTimeout: visibilityTimeout,
250
- })
251
- );
252
- } catch (cause) {
253
- return { outcome: 'skipped', skipped: 'visibility_failed', cause };
254
- }
255
- await this._recordWait(
256
- body,
257
- error,
258
- state(
259
- delivery.isLastAttempt ? 'EXHAUSTED' : 'WAITING',
260
- 'visibility'
261
- )
262
- );
263
- log.warn('Record visibility extended', {
264
- eventName: 'frigg.worker.record_visibility_extended',
265
- mechanism: 'visibility',
266
- visibilityTimeout,
267
- ...details,
268
- ...(scheduleError && { scheduleError: causeOf(scheduleError) }),
269
- error,
270
- });
271
- this._logIfLost(delivery, error, details);
272
- return { outcome: 'failed' };
273
- }
274
-
275
- /**
276
- * The one-time scheduler, or null when the stack has none. The mock
277
- * scheduler is never used: a schedule kept in memory would be lost with
278
- * the message.
279
- */
280
- getSchedulerService() {
281
- if (this._schedulerService !== undefined) return this._schedulerService;
282
- this._schedulerService = null;
283
- if (
284
- process.env.SCHEDULER_ROLE_ARN &&
285
- process.env.SCHEDULER_PROVIDER !== 'mock'
286
- ) {
287
- const {
288
- createSchedulerService,
289
- SCHEDULER_PROVIDERS,
290
- } = require('../infrastructure/scheduler/scheduler-service-factory');
291
- this._schedulerService = createSchedulerService({
292
- provider: SCHEDULER_PROVIDERS.EVENTBRIDGE,
293
- });
294
- }
295
- return this._schedulerService;
296
- }
297
-
298
- /**
299
- * Hook: the message was put back for a rate limit. Runs after it was sent.
300
- * @param {Object} body The parsed message body.
301
- * @param {Error} error The RateLimitError.
302
- * @param {{status: 'WAITING'|'EXHAUSTED', mechanism: string, deferrals: number, retryAt: Date}} state
303
- */
304
- async recordRateLimitWait() {}
305
-
306
- /**
307
- * Hook: a message that was put back for a rate limit ran without error.
308
- * @param {Object} body The parsed message body.
309
- */
310
- async clearRateLimitWait() {}
311
-
312
- _queueUrl(queueName) {
313
- this._queueUrls ??= new Map();
314
- if (!this._queueUrls.has(queueName)) {
315
- const lookup = this.getQueueURL({ QueueName: queueName }).catch(
316
- (error) => {
317
- this._queueUrls.delete(queueName);
318
- throw error;
319
- }
320
- );
321
- this._queueUrls.set(queueName, lookup);
322
- }
323
- return this._queueUrls.get(queueName);
324
- }
325
-
326
- async _recordWait(body, error, state) {
327
- await this._runStateHook('record', () =>
328
- this.recordRateLimitWait(body, error, state)
329
- );
330
- }
331
-
332
- async _clearDeferredState(body, delivery) {
333
- if (readDeferral(body).deferrals === 0 && !(delivery.receiveCount > 1))
334
- return;
335
- await this._runStateHook('clear', () => this.clearRateLimitWait(body));
336
- }
337
-
338
- async _runStateHook(operation, hook) {
339
- try {
340
- await hook();
341
- } catch (error) {
342
- log.warn('Rate-limit run state not written', {
343
- eventName: 'frigg.worker.rate_limit_state_failed',
344
- operation,
345
- error,
346
- });
347
- }
348
- }
349
-
350
- _logIfLost(delivery, error, details) {
351
- if (!delivery.isLastAttempt) return;
352
- log.error(
353
- 'Rate-limited record lost: the message goes to the dead-letter queue next',
354
- {
355
- eventName: 'frigg.worker.record_lost_rate_limited',
356
- retryAt: details.retryAt,
357
- reason: error.reason,
358
- module: error.module,
359
- error,
360
- }
361
- );
362
- }
363
-
364
78
  // returns the message id
365
79
  async send(params, delay = 0) {
366
80
  this._validateParams(params);
@@ -165,32 +165,6 @@ const createQueueWorker = (integrationClass) => {
165
165
  const integrationName = integrationClass.Definition.name;
166
166
 
167
167
  class QueueWorker extends Worker {
168
- async recordRateLimitWait(body, error, state) {
169
- const processId = body.data?.processId;
170
- if (!processId) return;
171
- await createProcessRepository().applyProcessUpdate(processId, {
172
- set: {
173
- 'context.rateLimit': {
174
- status: state.status,
175
- mechanism: state.mechanism,
176
- retryAt: state.retryAt.toISOString(),
177
- reason: error.reason,
178
- module: error.module,
179
- deferrals: state.deferrals,
180
- updatedAt: new Date().toISOString(),
181
- },
182
- },
183
- });
184
- }
185
-
186
- async clearRateLimitWait(body) {
187
- const processId = body?.data?.processId;
188
- if (!processId) return;
189
- await createProcessRepository().applyProcessUpdate(processId, {
190
- set: { 'context.rateLimit': null },
191
- });
192
- }
193
-
194
168
  async _run(params, context, delivery) {
195
169
  const logCtx = {
196
170
  integration: integrationName,
@@ -398,12 +398,6 @@ class OAuth2Requester extends Requester {
398
398
  );
399
399
  transportError.statusCode = status;
400
400
  transportError.isTokenRefreshTransportFailure = true;
401
- if (error?.isRateLimited) {
402
- transportError.isRateLimited = true;
403
- transportError.retryAt = error.retryAt;
404
- transportError.waitMs = error.waitMs;
405
- transportError.reason = error.reason;
406
- }
407
401
  return transportError;
408
402
  }
409
403
 
package/package.json CHANGED
@@ -1,13 +1,12 @@
1
1
  {
2
2
  "name": "@friggframework/core",
3
3
  "prettier": "@friggframework/prettier-config",
4
- "version": "2.0.0--canary.657.8f335eb.0",
4
+ "version": "2.0.0--canary.656.7302a64.0",
5
5
  "dependencies": {
6
6
  "@aws-sdk/client-apigatewaymanagementapi": "^3.588.0",
7
7
  "@aws-sdk/client-kms": "^3.588.0",
8
8
  "@aws-sdk/client-lambda": "^3.714.0",
9
9
  "@aws-sdk/client-s3": "^3.588.0",
10
- "@aws-sdk/client-scheduler": "^3.588.0",
11
10
  "@aws-sdk/client-sqs": "^3.588.0",
12
11
  "@aws-sdk/client-ssm": "^3.588.0",
13
12
  "@aws-sdk/s3-request-presigner": "^3.588.0",
@@ -48,9 +47,9 @@
48
47
  }
49
48
  },
50
49
  "devDependencies": {
51
- "@friggframework/eslint-config": "2.0.0--canary.657.8f335eb.0",
52
- "@friggframework/prettier-config": "2.0.0--canary.657.8f335eb.0",
53
- "@friggframework/test": "2.0.0--canary.657.8f335eb.0",
50
+ "@friggframework/eslint-config": "2.0.0--canary.656.7302a64.0",
51
+ "@friggframework/prettier-config": "2.0.0--canary.656.7302a64.0",
52
+ "@friggframework/test": "2.0.0--canary.656.7302a64.0",
54
53
  "@prisma/client": "^6.19.3",
55
54
  "@types/lodash": "4.17.15",
56
55
  "@typescript-eslint/eslint-plugin": "^8.0.0",
@@ -90,5 +89,5 @@
90
89
  "publishConfig": {
91
90
  "access": "public"
92
91
  },
93
- "gitHead": "8f335eb16f678038ad9448d9603c734ad663b3dc"
92
+ "gitHead": "7302a64c61c7eb20e0b42a972c0406f75b1f347b"
94
93
  }
@@ -126,4 +126,4 @@ const QueuerUtil = {
126
126
  },
127
127
  };
128
128
 
129
- module.exports = { QueuerUtil, awsConfigOptions };
129
+ module.exports = { QueuerUtil };
@@ -47,28 +47,8 @@ declare module "@friggframework/core" {
47
47
  send(params: object & { QueueUrl: any }, delay?: number): Promise<string>;
48
48
 
49
49
  sendAsyncSQSMessage(params: SendSQSMessageParams): Promise<string>;
50
-
51
- /**
52
- * Hook: a message was put back for a rate limit. Runs after the message
53
- * was sent. A failure is logged and never changes the outcome.
54
- */
55
- recordRateLimitWait(
56
- body: object,
57
- error: Error,
58
- state: RateLimitWaitState
59
- ): Promise<void>;
60
-
61
- /** Hook: a message that was put back for a rate limit ran without error. */
62
- clearRateLimitWait(body: object): Promise<void>;
63
50
  }
64
51
 
65
- export type RateLimitWaitState = {
66
- status: "WAITING" | "EXHAUSTED";
67
- mechanism: "delay" | "schedule" | "visibility" | "none";
68
- deferrals: number;
69
- retryAt: Date;
70
- };
71
-
72
52
  interface IWorker {
73
53
  getQueueURL(params: GetQueueURLParams): Promise<string | undefined>;
74
54
  run(params: { Records: any }, context?: object): Promise<BatchItemFailuresResponse>;
@@ -1,79 +0,0 @@
1
- const MAX_DEFERRALS = 10;
2
- const MAX_DEFERRED_MS = 24 * 60 * 60 * 1000;
3
- const MAX_DELAY_SECONDS = 900;
4
- const MAX_VISIBILITY_TIMEOUT_SECONDS = 43_200;
5
- const MAX_DEFERRALS_ENV = 'FRIGG_QUEUE_MAX_DEFERRALS';
6
- const MAX_DEFERRED_MS_ENV = 'FRIGG_QUEUE_MAX_DEFERRED_MS';
7
-
8
- const toPositiveInteger = (value) => {
9
- const number = Number(value);
10
- return Number.isInteger(number) && number > 0 ? number : undefined;
11
- };
12
-
13
- /**
14
- * @typedef {Object} DeferralLimits
15
- * @property {number} maxDeferrals Times one message may be put back for a rate limit.
16
- * @property {number} maxDeferredMs Longest total time from the first deferral to the last retry time.
17
- */
18
-
19
- /**
20
- * @param {Object} [env=process.env]
21
- * @returns {DeferralLimits}
22
- */
23
- const readDeferralLimits = (env = process.env) => ({
24
- maxDeferrals: toPositiveInteger(env[MAX_DEFERRALS_ENV]) ?? MAX_DEFERRALS,
25
- maxDeferredMs:
26
- toPositiveInteger(env[MAX_DEFERRED_MS_ENV]) ?? MAX_DEFERRED_MS,
27
- });
28
-
29
- /**
30
- * The deferral counters a message body carries in `_frigg`.
31
- * @returns {{deferrals: number, firstDeferredAt: string|undefined}}
32
- */
33
- const readDeferral = (body) => {
34
- const frigg = body?._frigg;
35
- const deferrals =
36
- Number.isInteger(frigg?.deferrals) && frigg.deferrals > 0
37
- ? frigg.deferrals
38
- : 0;
39
- const firstDeferredAt =
40
- typeof frigg?.firstDeferredAt === 'string' &&
41
- !Number.isNaN(Date.parse(frigg.firstDeferredAt))
42
- ? frigg.firstDeferredAt
43
- : undefined;
44
- return { deferrals, firstDeferredAt };
45
- };
46
-
47
- const nextDeferral = (body, now = Date.now()) => {
48
- const current = readDeferral(body);
49
- return {
50
- deferrals: current.deferrals + 1,
51
- firstDeferredAt: current.firstDeferredAt ?? new Date(now).toISOString(),
52
- };
53
- };
54
-
55
- const withDeferral = (body, deferral) => ({
56
- ...body,
57
- _frigg: { ...body._frigg, ...deferral },
58
- });
59
-
60
- const isDeferralCapped = (
61
- { deferrals, firstDeferredAt, retryAt },
62
- { maxDeferrals, maxDeferredMs }
63
- ) =>
64
- deferrals > maxDeferrals ||
65
- retryAt.getTime() - Date.parse(firstDeferredAt) > maxDeferredMs;
66
-
67
- module.exports = {
68
- MAX_DEFERRALS,
69
- MAX_DEFERRALS_ENV,
70
- MAX_DEFERRED_MS,
71
- MAX_DEFERRED_MS_ENV,
72
- MAX_DELAY_SECONDS,
73
- MAX_VISIBILITY_TIMEOUT_SECONDS,
74
- isDeferralCapped,
75
- nextDeferral,
76
- readDeferral,
77
- readDeferralLimits,
78
- withDeferral,
79
- };