@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
package/CLAUDE.md CHANGED
@@ -301,6 +301,14 @@ packages/core/
301
301
  per integration and 0.5–0.7 s at 10⁵ (the DocumentDB pipeline, run on
302
302
  MongoDB, 0.6–0.8 s). On every adapter a deep offset or an empty page past
303
303
  the end costs about the same as the first page.
304
+ - Integration messages: `updateIntegrationMessages(integrationId, type, item,
305
+ { keepLast })` appends one item and keeps the newest `keepLast` (the use case
306
+ passes 50). `findIntegrationMessages(integrationId, type)` reads the stored
307
+ items of a type. `appendRateLimitMessage` is the atomic write of the
308
+ `RATE_LIMITED` warning (section 7). `integration-repository-messages-parity.db.test.js`
309
+ runs every adapter against real databases when
310
+ `INTEGRATION_MESSAGES_PARITY_MONGO_URL` / `INTEGRATION_MESSAGES_PARITY_POSTGRES_URL`
311
+ are set.
304
312
  - `process-repository-*.js` - Process (long-running job) persistence.
305
313
  Implements `applyProcessUpdate(processId, ops)` — a race-safe alternative
306
314
  to `update(id, patch)` that routes increments, sets, and bounded-array
@@ -409,6 +417,16 @@ class MyIntegration extends IntegrationBase {
409
417
  - `ApiKeyRequester` - API key authentication
410
418
  - `BasicAuthRequester` - Basic authentication
411
419
 
420
+ **Rate limits** (ADR-049): an API module declares `static rateLimit` on its
421
+ `Requester` subclass. A hinted wait (from `classify()`, the header parsers or
422
+ the static policy) sleeps within a budget that the caller owns (10 s in an HTTP
423
+ handler, 0 in a queue worker, 300 s outside an invocation, at most 10
424
+ hinted retries), or throws `RateLimitError`
425
+ (`isRateLimited`, `retryAt`) when it does not fit. A 429 with no hint keeps the
426
+ fixed `backOff` ladder. A non-429 limit that `classify` names without a time
427
+ throws `RateLimitError` at once, with `retryAt` unknown. See
428
+ [Rate Limits](../../docs/reference/api-module-definition-and-functions.md#rate-limits-static-ratelimit).
429
+
412
430
  **Module Factory**:
413
431
  - `ModuleFactory` - Creates and configures API module instances
414
432
  - Handles credential injection
@@ -516,20 +534,22 @@ handlers (`{ req, res, next }`) and `this.on` events do not.
516
534
 
517
535
  `isLastAttempt` is `false` when either count is unknown: a local or non-SQS
518
536
  invocation, or a queue whose redrive policy the stack does not own
519
- (`ownership.queue: 'external'`). The value is information only: core still
520
- rethrows retryable errors and discards halt errors (4xx except 408/429).
537
+ (`ownership.queue: 'external'`). The value does not change what core does: a
538
+ retryable error returns the message to SQS, a rate-limited error puts it back
539
+ to run at `retryAt` (see **Rate-limit deferral** below), and a halt error (4xx
540
+ except 408, 429 and errors with `isRateLimited`) discards it.
521
541
 
522
- Use it to end a run or count lost work on the final try: when a retryable
523
- error (429, 5xx, network) is about to be rethrown and `isLastAttempt` is
524
- `true`, the message goes to the DLQ next, so mark the run failed or count the
525
- message's records as failed before rethrowing.
542
+ Use it to end a run or count lost work on the final try. Check it first: when
543
+ it is `true`, mark the run failed or count the message's records as failed, and
544
+ return. Otherwise rethrow. Do not end the run and then rethrow: core can still
545
+ send a `RateLimitError` again, so the message would run again on an ended run.
526
546
 
527
547
  ```javascript
528
548
  async processBatch({ data, delivery }) {
529
549
  try {
530
550
  await this.syncPage(data);
531
551
  } catch (error) {
532
- if (delivery?.isLastAttempt) await this.failRun(data.processId, error);
552
+ if (delivery?.isLastAttempt) return this.failRun(data.processId, error);
533
553
  throw error;
534
554
  }
535
555
  }
@@ -540,6 +560,141 @@ The single source of the max receive count is
540
560
  devtools integration builder uses it for the queue's `RedrivePolicy` and sets
541
561
  it as `FRIGG_QUEUE_MAX_RECEIVE_COUNT` on the queue worker function.
542
562
 
563
+ **Rate-limit deferral** (ADR-049): when a queue handler throws an error with
564
+ `isRateLimited` (a `RateLimitError` from the Requester, or one a module throws),
565
+ `Worker.run` builds a `RATE_LIMITED` event:
566
+
567
+ ```javascript
568
+ {
569
+ retryAt, waitMs, reason, module, scopeKey, // from the error; retryAt can be undefined
570
+ message, // the body of the queue message
571
+ delivery: { messageId, receiveCount, deferrals, deferredMs },
572
+ }
573
+ ```
574
+
575
+ When the integration defines a `RATE_LIMITED` event handler, the queue worker
576
+ calls it with `{ data: event, context, delivery }`, on the instance that ran the
577
+ job. The return value decides:
578
+
579
+ | Value | What the worker does |
580
+ |---|---|
581
+ | `'defer'`, or no value | The default handler runs (below) |
582
+ | `'drop'` | Acknowledges the record. SQS deletes the message. The wait that the message set is cleared, as after a success |
583
+ | `'retry'` | Reports the record failed, as for any retryable error |
584
+
585
+ A handler that throws counts as `'retry'`. With no `RATE_LIMITED` handler, the
586
+ default handler runs. The same event is meant to become the input of the
587
+ ADR-047 orchestrator later.
588
+
589
+ The default handler does not give the message back to SQS for a 30 minute
590
+ redelivery. It puts the message back so it runs at `retryAt`:
591
+
592
+ | Wait | What the worker does | Record |
593
+ |---|---|---|
594
+ | Up to 900 s | Sends the same body again with `DelaySeconds`, then acknowledges the old message | handled |
595
+ | 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 |
596
+ | Over 900 s, no scheduler | Extends the message's visibility timeout to `retryAt` (12 h less 20 minutes at most). This uses one receive | reported failed |
597
+
598
+ - An unknown `retryAt` (a non-429 limit that `classify` names without a time)
599
+ uses now plus the probe interval, `FRIGG_QUEUE_RATE_LIMIT_PROBE_MS` (default
600
+ 1 h). The worker does not wait for the visibility timeout of the queue. The
601
+ log record then has `probe: true`.
602
+
603
+ - The new message starts at receive count 1. A deferred body carries
604
+ `_frigg: { deferrals, firstDeferredAt, deferralId }`; `_frigg` is reserved and
605
+ the job handler never sees it. The `message` of the `RATE_LIMITED` event is
606
+ the whole body, `_frigg` included. `deferralId` is the SQS message id of the first
607
+ message that was put back, and every later deferral of that work keeps it.
608
+ - The visibility tier sets a timeout of at most 12 h less 20 minutes
609
+ (42,000 s). SQS counts its 12 h maximum from the receive, and an extension
610
+ does not reset it. The margin covers the longest Lambda run (900 s) plus the
611
+ longest batching window (300 s).
612
+ - Two caps bound it: `FRIGG_QUEUE_MAX_DEFERRALS` (default 30) and
613
+ `FRIGG_QUEUE_MAX_DEFERRED_MS` (default 26 h, from the first deferral to the
614
+ retry time). The defaults cover one full day of hourly waits, for a module
615
+ that probes a daily limit every hour. Past a cap, with no event source ARN
616
+ or on a FIFO queue, the record fails like any retryable error and `delivery`
617
+ applies.
618
+ - The mock scheduler is never used for a deferral: a schedule kept in memory
619
+ would be lost with the acknowledged message.
620
+ - With a `processId` in the message, the worker writes
621
+ `Process.context.rateLimit = { status: 'WAITING' | 'EXHAUSTED', mechanism,
622
+ retryAt, reason, module, deferrals, deferralId, updatedAt }`. `EXHAUSTED` means
623
+ a cap ended the deferrals, or a visibility change came on the last delivery.
624
+ The value is one per process, so it holds the latest known wait: a new wait
625
+ replaces it only when its `retryAt` is later, and a `WAITING` value never hides
626
+ an `EXHAUSTED` one. After a deferred or redelivered message ran, the worker
627
+ sets a `WAITING` value to `null` at once when that message set it (same
628
+ `deferralId`, or the message's own id for a visibility change), and for any
629
+ other message only when its `retryAt` is past or within 5 s. So a job that
630
+ resumes before its `retryAt` clears its own wait, and cannot clear the wait of
631
+ another message.
632
+ - Delivery stays at least once. The new message is sent before the old one is
633
+ acknowledged, so a crash between the two can run the work twice.
634
+ - Handlers check `delivery.isLastAttempt` first, then rethrow. The delay and
635
+ schedule tiers send a new message, so they never reach the last attempt. The
636
+ visibility tier and a cap use a receive: on the last one the worker writes an
637
+ ERROR (`frigg.worker.record_lost_rate_limited`), and the handler has this one
638
+ chance to end the run.
639
+
640
+ ```javascript
641
+ async processBatch({ data, delivery }) {
642
+ try {
643
+ await this.syncPage(data);
644
+ } catch (error) {
645
+ if (delivery?.isLastAttempt) return this.failRun(data.processId, error);
646
+ throw error; // a RateLimitError too: core puts the message back at retryAt
647
+ }
648
+ }
649
+ ```
650
+
651
+ Records: a rate-limited SQS record gets one log record, by its outcome.
652
+
653
+ | Outcome | Log record |
654
+ |---|---|
655
+ | Acknowledged | WARN `frigg.worker.record_deferred` (`mechanism` `delay` or `schedule`) |
656
+ | Dropped by the `RATE_LIMITED` handler | WARN `frigg.worker.record_dropped` |
657
+ | Not acknowledged, not the last attempt | One WARN: `record_deferral_capped`, `record_visibility_extended`, or `record_failed` with `deferral.skipped` (`handler_retry` and `handler_failed` for the `RATE_LIMITED` handler) |
658
+ | Not acknowledged, last attempt | One ERROR, `record_lost_rate_limited`, with the details, and no WARN |
659
+
660
+ **The `RATE_LIMITED` message** (ADR-049 section 5): the default handler writes
661
+ one client-safe warning on the integration in three cases: the wait is over
662
+ 900 s, `retryAt` is unknown (the message then has the probe time), or a cap
663
+ ended the deferrals. A shorter wait writes nothing, because the run continues
664
+ within 15 minutes. The `RATE_LIMITED` handler's `'drop'` and `'retry'` write
665
+ nothing, because the default handler does not run.
666
+
667
+ ```javascript
668
+ {
669
+ title: 'Rate limit reached',
670
+ message, // userHints[reason].message, else a default text
671
+ timestamp,
672
+ code: 'RATE_LIMITED',
673
+ module, reason,
674
+ retryAt, // ISO UTC; the UI shows local time
675
+ actions: [
676
+ { type: 'RETRY_WHEN_READY' },
677
+ { type: 'LINK', label, url }, // from userHints[reason].links
678
+ ],
679
+ }
680
+ ```
681
+
682
+ `userHints` come from the `static rateLimit` of the module that the event
683
+ names (`Definition.modules[*].definition.moduleName`). The `QueueWorker` writes
684
+ the warning through `RecordRateLimitMessage` and the repository method
685
+ `appendRateLimitMessage`. That method is one atomic write on every adapter: it
686
+ appends only when no stored warning has the same `code` and `module` and a
687
+ `retryAt` within 60 s, and it keeps the newest 50 warnings. So twenty workers
688
+ that meet one limit write one warning. A rate limit does not change the status
689
+ of the integration.
690
+
691
+ A failing run state hook adds `rate_limit_state_failed`. A failing message hook
692
+ adds `rate_limit_message_failed`. Neither changes the outcome. For a queue that
693
+ the stack does not own (`ownership.queue: 'external'`), devtools grants the
694
+ functions `sqs:SendMessage`, `sqs:GetQueueUrl`, `sqs:GetQueueAttributes` and
695
+ `sqs:ChangeMessageVisibility` on the queue's ARN, and the scheduler role
696
+ `sqs:SendMessage` on it.
697
+
543
698
  ### 8. Error Handling (`/errors`)
544
699
 
545
700
  **Purpose**: Standardized error types with proper HTTP semantics.
@@ -547,6 +702,7 @@ it as `FRIGG_QUEUE_MAX_RECEIVE_COUNT` on the queue worker function.
547
702
  **Error Types**:
548
703
  - `BaseError` - Base error class
549
704
  - `FetchError` - HTTP request failures
705
+ - `RateLimitError` - A `FetchError` for a limit the provider or the module's policy says when to retry (`retryAt`)
550
706
  - `HaltError` - Stop processing without retry
551
707
  - `RequiredPropertyError` - Missing required parameters
552
708
  - `ParameterTypeError` - Invalid parameter type
@@ -790,6 +946,9 @@ Use test doubles from `@friggframework/test` package for consistent mocking.
790
946
  - `SECRET_ARN` - AWS Secrets Manager ARN for auto-injection
791
947
  - `FRIGG_LOG_LEVEL` - Minimum log level (`TRACE` … `FATAL`, default `INFO`; `DEBUG` on local runs)
792
948
  - `FRIGG_QUEUE_MAX_RECEIVE_COUNT` - Set by devtools on integration queue workers whose queue the stack owns; feeds `delivery.maxReceiveCount`
949
+ - `FRIGG_QUEUE_MAX_DEFERRALS` - Most rate-limit deferrals of one message (default 30)
950
+ - `FRIGG_QUEUE_MAX_DEFERRED_MS` - Most time in ms from a message's first rate-limit deferral to its retry time (default 26 h)
951
+ - `FRIGG_QUEUE_RATE_LIMIT_PROBE_MS` - Time in ms until the retry of a rate-limited message whose `retryAt` is unknown (default 1 h)
793
952
 
794
953
  ## Version Information
795
954
 
package/core/CLAUDE.md CHANGED
@@ -36,6 +36,10 @@ const handler = createHandler({
36
36
 
37
37
  **Error Handling Patterns**:
38
38
  - **User-Facing**: Returns 500 with generic "Internal Error Occurred" message
39
+ - **Rate Limited (user-facing)**: An error with `isRateLimited` returns 429,
40
+ `Retry-After` in seconds from `retryAt` (none when `retryAt` is unknown) and
41
+ `{ error: 'Too Many Requests', retryAt }`. The express boundary in
42
+ `handlers/app-handler-helpers.js` does the same (`rate-limited-response.js`)
39
43
  - **Server-to-Server**: Re-throws errors for AWS to handle
40
44
  - **Halt Errors**: `error.isHaltError = true` logs but returns success (no retry)
41
45
 
@@ -79,6 +83,55 @@ await worker.send({
79
83
  }, delaySeconds);
80
84
  ```
81
85
 
86
+ **Rate-limit deferral** (ADR-049): for an error with `isRateLimited`, `run()`
87
+ builds the `RATE_LIMITED` event (`{ retryAt, waitMs, reason, module, scopeKey,
88
+ message, delivery: { messageId, receiveCount, deferrals, deferredMs } }`) and
89
+ gives it to the hook `decideRateLimited(event)`. The hook returns `'defer'`,
90
+ `'drop'` or `'retry'`. The `Worker` default returns no value. A throw counts as
91
+ `'retry'`. `'drop'` acknowledges the record, writes WARN `record_dropped`, and
92
+ clears the wait that the message set, as after a success.
93
+ `'retry'` fails the record with `deferral.skipped` `handler_retry` (or
94
+ `handler_failed` for a throw). The queue worker of an integration
95
+ (`createQueueWorker`) calls the integration's `RATE_LIMITED` event handler
96
+ there, on the instance that ran the job.
97
+
98
+ For `'defer'` or no value, the default handler
99
+ `defer(record, body, error, delivery)` runs. It returns `{ outcome }`. An
100
+ unknown `retryAt` becomes now plus `FRIGG_QUEUE_RATE_LIMIT_PROBE_MS` (default
101
+ 1 h):
102
+ - `acked`: the message was sent again with `DelaySeconds` (wait up to 900 s) or
103
+ scheduled with the one-time scheduler (longer wait). The record is handled.
104
+ - `failed`: the visibility timeout was extended to `retryAt`, or a cap
105
+ (`FRIGG_QUEUE_MAX_DEFERRALS`, `FRIGG_QUEUE_MAX_DEFERRED_MS`) ended the
106
+ deferrals. The record is reported failed.
107
+ - `skipped`: no `eventSourceARN` or a FIFO queue (`no_event_source`), a failed send (`send_failed`), or a failed visibility
108
+ change (`visibility_failed`). The record fails as any error does.
109
+
110
+ Each outcome writes one log record. `acked` writes WARN `record_deferred`.
111
+ `failed` and `skipped` write one WARN (`record_visibility_extended`,
112
+ `record_deferral_capped`, or `record_failed` with `deferral: { skipped }`). On
113
+ the last attempt they write one ERROR, `record_lost_rate_limited`, with the
114
+ details, and no WARN.
115
+
116
+ Subclasses override two no-op hooks to keep run state.
117
+ `recordRateLimitWait(body, error, state)` runs before a delayed message is sent,
118
+ because with a short delay the new message can run first; a failed send clears
119
+ the wait again. For a schedule or a visibility change it runs after the change.
120
+ `clearRateLimitWait(body, { deferralId })` runs after a deferred or redelivered
121
+ message succeeded.
122
+ `state.deferralId` and `deferralId` name the message that was first put back
123
+ (`_frigg.deferralId`, or the message's own id). A failing hook logs
124
+ `frigg.worker.rate_limit_state_failed` and never changes the outcome. The queue
125
+ worker of an integration (`createQueueWorker`) writes `Process.context.rateLimit`
126
+ in them.
127
+
128
+ A third no-op hook, `recordRateLimitMessage(body, error, { retryAt, capped })`,
129
+ runs after a deferral or a cap when the wait is over 900 s, `retryAt` is
130
+ unknown, or a cap ended the deferrals. It does not run for a `skipped`
131
+ outcome. A failing hook logs `frigg.worker.rate_limit_message_failed` and never
132
+ changes the outcome. The queue worker of an integration writes the
133
+ `RATE_LIMITED` warning in it. See `packages/core/CLAUDE.md` section 7.
134
+
82
135
  ### Delegate Pattern System (`Delegate.js:3-27`)
83
136
 
84
137
  **Purpose**: Observer/delegation pattern for decoupled component communication
@@ -130,7 +183,7 @@ class MyIntegration extends Delegate {
130
183
  ### Lambda Handler Lifecycle
131
184
  1. **Pre-Execution Setup**:
132
185
  ```javascript
133
- runInvocationScope({ requestId, handlerName, method, route, invocation }, …); // Logger scope for the invocation
186
+ runInvocationScope({ requestId, handlerName, method, route, invocation }, …); // Logger scope + invocation deadline (remainingInvocationMs()) + in-process wait budget (createHandler `maxInProcessWaitMs`: 10 s HTTP, 0 queue worker)
134
187
  log.info('Handler invoked', { eventName: 'frigg.handler.invoked' });
135
188
  await secretsToEnv(); // Secrets Manager injection
136
189
  await parametersToEnv(); // SSM Parameter Store fetch (only when SSM_PARAMETER_PREFIX + FRIGG_SSM_OFFLOADED_KEYS are set)
@@ -152,6 +205,7 @@ class MyIntegration extends Delegate {
152
205
  4. **Error Handling & Cleanup**:
153
206
  ```javascript
154
207
  // One record at the boundary: WARN frigg.handler.rejected (client-safe),
208
+ // WARN frigg.handler.rate_limited (user-facing, isRateLimited: 429),
155
209
  // ERROR frigg.handler.failed, or ERROR frigg.handler.halted (halt, no retry).
156
210
  // Sanitized error response for user-facing endpoints; server-to-server
157
211
  // errors are rethrown as a sanitized surrogate (toSanitizedSurrogate).
@@ -226,6 +280,8 @@ const handler = createHandler({
226
280
  - Logs error but returns success
227
281
  - Prevents infinite retries for known issues
228
282
  - Used for graceful degradation scenarios
283
+ - The queue worker sets it on a 4xx except 408, 429 and errors with
284
+ `isRateLimited` (a provider limit signalled with 403 clears with time)
229
285
 
230
286
  ### Logging Strategy
231
287
  ```javascript