@friggframework/core 2.0.0--canary.658.e11f3b0.0 → 2.0.0--canary.743.c55fe7b.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 +204 -54
- package/application/commands/README.md +17 -11
- package/application/commands/entity-commands.js +18 -60
- package/application/commands/integration-commands.js +63 -0
- package/core/CLAUDE.md +55 -1
- package/core/Worker.js +439 -9
- package/core/create-handler.js +17 -0
- package/core/invocation-deadline.js +1 -1
- package/core/rate-limited-response.js +27 -0
- package/database/documentdb-encryption-service.js +2 -33
- package/database/documentdb-utils.js +4 -1
- package/database/encryption/README.md +3 -3
- package/database/encryption/ciphertext-format.js +24 -0
- package/database/encryption/encryption-schema-registry.js +109 -29
- package/database/encryption/field-encryption-service.js +55 -16
- package/database/encryption/prisma-encryption-extension.js +6 -9
- package/database/prisma.js +10 -1
- package/encrypt/Cryptor.js +90 -38
- package/errors/fetch-error.js +12 -1
- package/errors/index.js +4 -0
- package/errors/mapping-already-exists-error.js +14 -0
- package/generated/prisma-mongodb/edge.js +17 -4
- package/generated/prisma-mongodb/index-browser.js +10 -1
- package/generated/prisma-mongodb/index.d.ts +1394 -118
- package/generated/prisma-mongodb/index.js +21 -4
- package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
- package/generated/prisma-mongodb/package.json +1 -1
- package/generated/prisma-mongodb/schema.prisma +16 -1
- package/generated/prisma-mongodb/wasm.js +17 -4
- package/generated/prisma-postgresql/edge.js +17 -4
- package/generated/prisma-postgresql/index-browser.js +10 -1
- package/generated/prisma-postgresql/index.d.ts +1438 -100
- package/generated/prisma-postgresql/index.js +21 -4
- package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
- package/generated/prisma-postgresql/package.json +1 -1
- package/generated/prisma-postgresql/schema.prisma +14 -1
- package/generated/prisma-postgresql/wasm.js +17 -4
- package/handlers/WEBHOOKS.md +29 -0
- package/handlers/app-definition-loader.js +9 -2
- package/handlers/app-handler-helpers.js +27 -1
- package/handlers/backend-utils.js +75 -1
- package/index.js +10 -0
- package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +69 -13
- package/integrations/integration-base.js +52 -25
- package/integrations/integration-router.js +30 -22
- package/integrations/repositories/integration-mapping-repository-documentdb.js +50 -0
- package/integrations/repositories/integration-mapping-repository-interface.js +15 -0
- package/integrations/repositories/integration-mapping-repository-mongo.js +29 -0
- package/integrations/repositories/integration-mapping-repository-postgres.js +30 -0
- package/integrations/repositories/integration-mapping-repository.js +29 -0
- package/integrations/repositories/integration-repository-documentdb.js +69 -1
- package/integrations/repositories/integration-repository-interface.js +59 -0
- package/integrations/repositories/integration-repository-mongo.js +113 -2
- package/integrations/repositories/integration-repository-postgres.js +118 -1
- package/integrations/repositories/message-item-shared.js +14 -1
- package/integrations/repositories/process-repository-mongo.js +1 -1
- package/integrations/tests/doubles/test-integration-repository.js +17 -0
- package/integrations/use-cases/add-entities-to-integration.js +92 -0
- package/integrations/use-cases/clear-rate-limit-wait.js +28 -0
- package/integrations/use-cases/create-integration.js +57 -19
- package/integrations/use-cases/delete-integration-for-user.js +8 -11
- package/integrations/use-cases/get-integration-instance.js +12 -12
- package/integrations/use-cases/index.js +7 -1
- package/integrations/use-cases/record-rate-limit-message.js +66 -72
- package/integrations/use-cases/record-rate-limit-wait.js +36 -0
- package/integrations/use-cases/remove-entities-from-integration.js +70 -0
- package/integrations/use-cases/update-integration.js +12 -12
- package/integrations/utils/assert-entity-ids-input.js +42 -0
- package/jest-setup.js +13 -2
- package/jest-teardown.js +5 -2
- package/jest.config.js +4 -0
- package/jest.db.config.js +23 -0
- package/modules/module.js +0 -27
- package/modules/requester/oauth-2.js +8 -0
- package/modules/requester/rate-limit/index.js +3 -1
- package/modules/requester/rate-limit/pacer.js +541 -0
- package/modules/requester/rate-limit/parsers.js +9 -5
- package/modules/requester/rate-limit/policy.js +29 -7
- package/modules/requester/rate-limit/state/rate-limit-state-repository-factory.js +35 -0
- package/modules/requester/rate-limit/state/rate-limit-state-repository-interface.js +48 -0
- package/modules/requester/rate-limit/state/rate-limit-state-repository-memory.js +57 -0
- package/modules/requester/rate-limit/state/rate-limit-state-repository-mongo.js +160 -0
- package/modules/requester/rate-limit/state/rate-limit-state-repository-postgres.js +59 -0
- package/modules/requester/requester.js +156 -27
- package/modules/use-cases/create-entity-from-credential.js +105 -0
- package/modules/use-cases/get-entity-options-by-id.js +7 -5
- package/modules/use-cases/get-module.js +29 -8
- package/modules/use-cases/process-authorization-callback.js +78 -27
- package/modules/use-cases/refresh-entity-options.js +7 -5
- package/modules/use-cases/test-module-auth.js +7 -5
- package/modules/utils/find-module-definition.js +23 -0
- package/modules/utils/map-module-dto.js +5 -3
- package/modules/utils/to-credential-id.js +14 -0
- package/package.json +11 -7
- package/prisma-mongodb/schema.prisma +16 -1
- package/prisma-postgresql/migrations/20261202000000_create_rate_limit_scope/migration.sql +14 -0
- package/prisma-postgresql/schema.prisma +14 -1
- package/queues/queue-deferral.js +155 -0
- package/queues/queue-delivery.js +1 -0
- package/queues/queuer-util.js +7 -6
- package/telemetry/otel-telemetry.js +76 -3
- package/telemetry/telemetry-config.js +16 -5
- package/telemetry/telemetry-runtime.js +14 -1
- package/token/repositories/token-repository-documentdb.js +13 -1
- package/token/repositories/token-repository-mongo.js +13 -1
- package/token/repositories/token-repository-postgres.js +13 -1
- package/types/core/consumer.fixture.ts +12 -0
- package/types/core/index.d.ts +52 -1
- package/types/integrations/index.d.ts +11 -6
- package/types/module-plugin/index.d.ts +11 -6
- package/user/tests/doubles/test-user-repository.js +1 -1
- package/user/use-cases/authenticate-user.js +23 -7
- package/user/use-cases/get-user-from-bearer-token.js +7 -2
package/CLAUDE.md
CHANGED
|
@@ -206,11 +206,51 @@ packages/core/
|
|
|
206
206
|
- `delete-integration-for-user.js` - Remove integration
|
|
207
207
|
- `get-integration-instance.js` - Load integration with modules
|
|
208
208
|
- `load-integration-context.js` - Full integration context loading
|
|
209
|
+
- `add-entities-to-integration.js` / `remove-entities-from-integration.js` - Attach or detach entities on an existing integration
|
|
209
210
|
|
|
210
211
|
**Repositories**:
|
|
211
212
|
- `integration-repository-factory.js` - Creates database-specific repositories
|
|
212
213
|
- `integration-repository-mongo.js` - MongoDB implementation
|
|
213
214
|
- `integration-repository-postgres.js` - PostgreSQL implementation
|
|
215
|
+
- `addEntitiesToIntegration(integrationId, entityIds)` /
|
|
216
|
+
`removeEntitiesFromIntegration(integrationId, entityIds)` change the entity
|
|
217
|
+
set of an existing integration (all three adapters; `null` for an unknown
|
|
218
|
+
integration). Reach them through the `addEntitiesToIntegration` /
|
|
219
|
+
`removeEntitiesFromIntegration` commands. The add use case
|
|
220
|
+
(`add-entities-to-integration.js`) rejects unknown entities
|
|
221
|
+
(`ENTITIES_NOT_FOUND`, 404), entities of another user
|
|
222
|
+
(`ENTITY_USER_MISMATCH`, 403) and entities of a module the integration does
|
|
223
|
+
not already hold (`ENTITY_MODULE_MISMATCH`, 400). The remove use case
|
|
224
|
+
(`remove-entities-from-integration.js`) refuses to leave a module with no
|
|
225
|
+
entity (`LAST_ENTITY_OF_MODULE`, 409). Re-adding an attached entity or
|
|
226
|
+
removing a detached one changes nothing; a detached entity is not deleted.
|
|
227
|
+
`integration-repository-entities-parity.db.test.js` runs every adapter against
|
|
228
|
+
real databases when `INTEGRATION_ENTITIES_PARITY_MONGO_URL` /
|
|
229
|
+
`INTEGRATION_ENTITIES_PARITY_POSTGRES_URL` are set. The DocumentDB adapter
|
|
230
|
+
writes only `Integration.entityIds` (as its `createIntegration` does), not
|
|
231
|
+
`Entity.integrationIds`.
|
|
232
|
+
**One credential, many accounts**: when one credential covers several
|
|
233
|
+
provider accounts, give each account its own entity (externalId = account
|
|
234
|
+
id) and attach them all to one integration; webhooks then route with
|
|
235
|
+
`findIntegrationByEntityExternalId`. Traps:
|
|
236
|
+
(1) `IntegrationBase` keys modules by module name, so `this.<moduleKey>`
|
|
237
|
+
holds only one entity's module, and on the queue/webhook path
|
|
238
|
+
(`get-integration-instance.js`) `this.entities` holds entity **ids**, not
|
|
239
|
+
records. For per-account work (a webhook for one account, teardown of every
|
|
240
|
+
account in `onDelete`), load
|
|
241
|
+
`this.commands.loadIntegrationContextById(this.id)` and use
|
|
242
|
+
`context.modules`: one module per entity, each with its record on
|
|
243
|
+
`module.entity` (pick by `module.entity.externalId`).
|
|
244
|
+
(2) `findIntegrationByEntityExternalId` counts every entity with that
|
|
245
|
+
externalId, attached or not, across users: reuse an existing entity
|
|
246
|
+
(`findEntity`) when an account comes back, or delete it when it is revoked,
|
|
247
|
+
never create a second one.
|
|
248
|
+
(3) `createIntegration` reuses an existing integration of the same user
|
|
249
|
+
and type whose entities include all requested ones (an exact match wins),
|
|
250
|
+
so a reconnect that sends the original entities finds the integration that
|
|
251
|
+
now holds more.
|
|
252
|
+
(4) Every module's delegate is the integration: an auth failure on any
|
|
253
|
+
account marks the shared credential invalid and the integration ERROR.
|
|
214
254
|
- `integration-mapping-repository-*.js` - Mapping data persistence.
|
|
215
255
|
`queryMappings(integrationId, { where, orderBy, skip, take, omit })`
|
|
216
256
|
returns `{ mappings, total }`: one filtered, ordered page of an
|
|
@@ -226,7 +266,7 @@ packages/core/
|
|
|
226
266
|
mapping keys to leave out of the rows; never write such rows back. Path
|
|
227
267
|
segments must match `^[A-Za-z_][A-Za-z0-9_]*$`. The PostgreSQL, MongoDB and
|
|
228
268
|
DocumentDB adapters give the same pages and totals;
|
|
229
|
-
`integration-mapping-repository-query-parity.test.js` checks that against
|
|
269
|
+
`integration-mapping-repository-query-parity.db.test.js` checks that against
|
|
230
270
|
real databases when `QUERY_MAPPINGS_PARITY_MONGO_URL` /
|
|
231
271
|
`QUERY_MAPPINGS_PARITY_POSTGRES_URL` are set. Two orderings still differ:
|
|
232
272
|
strings compare by the database collation on PostgreSQL and by code point
|
|
@@ -261,6 +301,14 @@ packages/core/
|
|
|
261
301
|
per integration and 0.5–0.7 s at 10⁵ (the DocumentDB pipeline, run on
|
|
262
302
|
MongoDB, 0.6–0.8 s). On every adapter a deep offset or an empty page past
|
|
263
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.
|
|
264
312
|
- `process-repository-*.js` - Process (long-running job) persistence.
|
|
265
313
|
Implements `applyProcessUpdate(processId, ops)` — a race-safe alternative
|
|
266
314
|
to `update(id, patch)` that routes increments, sets, and bounded-array
|
|
@@ -372,7 +420,7 @@ class MyIntegration extends IntegrationBase {
|
|
|
372
420
|
**Rate limits** (ADR-049): an API module declares `static rateLimit` on its
|
|
373
421
|
`Requester` subclass. A hinted wait (from `classify()`, the header parsers or
|
|
374
422
|
the static policy) sleeps within a budget that the caller owns (10 s in an HTTP
|
|
375
|
-
handler,
|
|
423
|
+
handler, 0 in a queue worker, 300 s outside an invocation, at most 10
|
|
376
424
|
hinted retries), or throws `RateLimitError`
|
|
377
425
|
(`isRateLimited`, `retryAt`) when it does not fit. A 429 with no hint keeps the
|
|
378
426
|
fixed `backOff` ladder. A non-429 limit that `classify` names without a time
|
|
@@ -486,20 +534,22 @@ handlers (`{ req, res, next }`) and `this.on` events do not.
|
|
|
486
534
|
|
|
487
535
|
`isLastAttempt` is `false` when either count is unknown: a local or non-SQS
|
|
488
536
|
invocation, or a queue whose redrive policy the stack does not own
|
|
489
|
-
(`ownership.queue: 'external'`). The value
|
|
490
|
-
|
|
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.
|
|
491
541
|
|
|
492
|
-
Use it to end a run or count lost work on the final try: when
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
message
|
|
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.
|
|
496
546
|
|
|
497
547
|
```javascript
|
|
498
548
|
async processBatch({ data, delivery }) {
|
|
499
549
|
try {
|
|
500
550
|
await this.syncPage(data);
|
|
501
551
|
} catch (error) {
|
|
502
|
-
if (delivery?.isLastAttempt)
|
|
552
|
+
if (delivery?.isLastAttempt) return this.failRun(data.processId, error);
|
|
503
553
|
throw error;
|
|
504
554
|
}
|
|
505
555
|
}
|
|
@@ -510,6 +560,141 @@ The single source of the max receive count is
|
|
|
510
560
|
devtools integration builder uses it for the queue's `RedrivePolicy` and sets
|
|
511
561
|
it as `FRIGG_QUEUE_MAX_RECEIVE_COUNT` on the queue worker function.
|
|
512
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
|
+
|
|
513
698
|
### 8. Error Handling (`/errors`)
|
|
514
699
|
|
|
515
700
|
**Purpose**: Standardized error types with proper HTTP semantics.
|
|
@@ -532,51 +717,6 @@ if (!userId) {
|
|
|
532
717
|
}
|
|
533
718
|
```
|
|
534
719
|
|
|
535
|
-
**Rate-limit message** (ADR-049): when a wait is longer than the in-process cap
|
|
536
|
-
of the caller (`maxInProcessWaitMs`: 10 s HTTP, 60 s queue worker, 5 min outside
|
|
537
|
-
an invocation), the Requester tells its delegate
|
|
538
|
-
(`RATE_LIMITED`, with the `RateLimitError`) and then throws. A shorter wait
|
|
539
|
-
that throws sends no notification. The notification takes the path of
|
|
540
|
-
`CREDENTIAL_INVALIDATED`: Requester, `Module`, `IntegrationBase`.
|
|
541
|
-
|
|
542
|
-
- The `Module` sends `{ moduleName, reason, retryAt, policy, statusCode, links }`.
|
|
543
|
-
`links` is `static rateLimit.userHints[reason].links`, or `[]`. The message,
|
|
544
|
-
url, body and headers of the error are never sent: the message reaches end
|
|
545
|
-
users.
|
|
546
|
-
- `IntegrationBase` writes one `WARN` (`integration.<name>.rate_limited`), and
|
|
547
|
-
`RecordRateLimitMessage` appends one item to the stored `warnings`. It
|
|
548
|
-
changes no status. A rate limit is not an `ERROR`, and an `ERROR` status
|
|
549
|
-
makes the queue worker drop every webhook.
|
|
550
|
-
- A report for the same module whose reset time is within 60 s of a stored one
|
|
551
|
-
is skipped. The check reads the stored `warnings` with
|
|
552
|
-
`findIntegrationMessages`, not `this.messages`, which is per instance and
|
|
553
|
-
empty on Postgres. It is a read then a write, so workers that report at the
|
|
554
|
-
same instant can still store a few copies.
|
|
555
|
-
- Every hop is best effort. A failure is logged, and the caller still gets the
|
|
556
|
-
`RateLimitError`.
|
|
557
|
-
|
|
558
|
-
```javascript
|
|
559
|
-
{
|
|
560
|
-
title: 'Rate limit reached',
|
|
561
|
-
message: 'The hubspot API rate limit was reached and resets at 2026-09-28 14:31 UTC.',
|
|
562
|
-
timestamp: 1790000000000,
|
|
563
|
-
code: 'RATE_LIMITED',
|
|
564
|
-
module: 'hubspot',
|
|
565
|
-
reason: 'daily',
|
|
566
|
-
retryAt: '2026-09-28T14:30:15.000Z',
|
|
567
|
-
actions: [
|
|
568
|
-
{ type: 'RETRY_WHEN_READY' },
|
|
569
|
-
{ type: 'LINK', label: 'API usage limits', url: 'https://example.com/limits' },
|
|
570
|
-
],
|
|
571
|
-
}
|
|
572
|
-
```
|
|
573
|
-
|
|
574
|
-
The text is fixed. It holds the module name and the reset time in UTC, rounded
|
|
575
|
-
up to the minute, and nothing from the request.
|
|
576
|
-
|
|
577
|
-
Integration messages (the item form, `findIntegrationMessages`, the newest 50
|
|
578
|
-
per type): see "Integration Messages" in `docs/guides/INTEGRATION-PATTERNS.md`.
|
|
579
|
-
|
|
580
720
|
### 9. Logging System (`/logs`)
|
|
581
721
|
|
|
582
722
|
**Purpose**: One redacted JSON record per line to stdout (ADR-048). See `docs/guides/LOGGING.md`.
|
|
@@ -806,6 +946,16 @@ Use test doubles from `@friggframework/test` package for consistent mocking.
|
|
|
806
946
|
- `SECRET_ARN` - AWS Secrets Manager ARN for auto-injection
|
|
807
947
|
- `FRIGG_LOG_LEVEL` - Minimum log level (`TRACE` … `FATAL`, default `INFO`; `DEBUG` on local runs)
|
|
808
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)
|
|
952
|
+
- `FRIGG_QUEUE_DEFERRAL_JITTER_MAX_MS` - Most random spread in ms added to a rate-limit deferral (default 5 min; `0` turns it off). A wait in the 900 s SQS delay range stays in it
|
|
953
|
+
- `FRIGG_QUEUE_MAX_PACED_DEFERRALS` - Pacer deferrals (no call sent) of one message that do not count against `FRIGG_QUEUE_MAX_DEFERRALS` (default 100)
|
|
954
|
+
- `FRIGG_RATE_LIMIT_PACING` - `off` turns off pacing before a call (ADR-049 section 6) in all modules
|
|
955
|
+
- `FRIGG_RATE_LIMIT_MAX_PACING_WAIT_MS` - Longest pacing sleep in ms before the call defers instead (default 2 s)
|
|
956
|
+
- `FRIGG_RATE_LIMIT_MAX_BLOCK_MS` - Longest block of a scope key in ms (default 15 min)
|
|
957
|
+
- `FRIGG_RATE_LIMIT_SHARED_CACHE_MS` - How long in ms a worker keeps the shared block it read (default 1 s)
|
|
958
|
+
- `FRIGG_RATE_LIMIT_SHARED_TIMEOUT_MS` - Longest wait in ms for the shared rate-limit store before pacing goes on in process (default 250 ms)
|
|
809
959
|
|
|
810
960
|
## Version Information
|
|
811
961
|
|
|
@@ -67,9 +67,10 @@ class MyIntegration extends IntegrationBase {
|
|
|
67
67
|
async hydrateFromExternalUser(externalUserId) {
|
|
68
68
|
// Find integration context by external entity ID
|
|
69
69
|
const result =
|
|
70
|
-
await this.commands.findIntegrationContextByExternalEntityId(
|
|
71
|
-
externalUserId
|
|
72
|
-
|
|
70
|
+
await this.commands.findIntegrationContextByExternalEntityId({
|
|
71
|
+
externalId: externalUserId,
|
|
72
|
+
type: 'my-integration', // integration config.type to match
|
|
73
|
+
});
|
|
73
74
|
|
|
74
75
|
if (result.error) {
|
|
75
76
|
return { error: result.error };
|
|
@@ -231,9 +232,10 @@ Manage integration records and load full integration contexts.
|
|
|
231
232
|
```javascript
|
|
232
233
|
// Find integration context by external entity ID
|
|
233
234
|
// Returns { context, error } where context includes record + hydrated modules
|
|
234
|
-
const result = await commands.findIntegrationContextByExternalEntityId(
|
|
235
|
-
'external-user-or-workspace-id'
|
|
236
|
-
|
|
235
|
+
const result = await commands.findIntegrationContextByExternalEntityId({
|
|
236
|
+
externalId: 'external-user-or-workspace-id',
|
|
237
|
+
type: 'my-integration', // integration config.type to match
|
|
238
|
+
});
|
|
237
239
|
|
|
238
240
|
if (!result.error) {
|
|
239
241
|
integration.setIntegrationRecord(result.context);
|
|
@@ -299,7 +301,10 @@ try {
|
|
|
299
301
|
For integration context operations, errors are returned in the result:
|
|
300
302
|
|
|
301
303
|
```javascript
|
|
302
|
-
const result = await commands.findIntegrationContextByExternalEntityId(
|
|
304
|
+
const result = await commands.findIntegrationContextByExternalEntityId({
|
|
305
|
+
externalId: userId,
|
|
306
|
+
type: 'my-integration',
|
|
307
|
+
});
|
|
303
308
|
|
|
304
309
|
if (result.error) {
|
|
305
310
|
return { error: result.error };
|
|
@@ -349,9 +354,10 @@ const result =
|
|
|
349
354
|
const { createFriggCommands } = require('@friggframework/core');
|
|
350
355
|
|
|
351
356
|
this.commands = createFriggCommands({ integrationClass: MyIntegration });
|
|
352
|
-
const result = await this.commands.findIntegrationContextByExternalEntityId(
|
|
353
|
-
userId
|
|
354
|
-
|
|
357
|
+
const result = await this.commands.findIntegrationContextByExternalEntityId({
|
|
358
|
+
externalId: userId,
|
|
359
|
+
type: 'my-integration',
|
|
360
|
+
});
|
|
355
361
|
```
|
|
356
362
|
|
|
357
363
|
## Best Practices
|
|
@@ -433,7 +439,7 @@ if (!user) {
|
|
|
433
439
|
| | `findEntitiesByIds(ids)` | Find multiple by IDs |
|
|
434
440
|
| | `updateEntity(id, updates)` | Update entity properties |
|
|
435
441
|
| | `deleteEntity(id)` | Delete entity |
|
|
436
|
-
| **Integration** | `findIntegrationContextByExternalEntityId(externalId)`
|
|
442
|
+
| **Integration** | `findIntegrationContextByExternalEntityId({ externalId, type })` | Load integration + modules by external ID |
|
|
437
443
|
| | `loadIntegrationContextById(integrationId)` | Load integration + modules by ID |
|
|
438
444
|
|
|
439
445
|
## Support
|
|
@@ -1,12 +1,24 @@
|
|
|
1
1
|
const {
|
|
2
2
|
createModuleRepository,
|
|
3
3
|
} = require('../../modules/repositories/module-repository-factory');
|
|
4
|
+
const { toCredentialId } = require('../../modules/utils/to-credential-id');
|
|
4
5
|
|
|
5
6
|
const ERROR_CODE_MAP = {
|
|
6
7
|
ENTITY_NOT_FOUND: 404,
|
|
7
8
|
INVALID_ENTITY_DATA: 400,
|
|
8
9
|
};
|
|
9
10
|
|
|
11
|
+
function toEntityDto(entity) {
|
|
12
|
+
return {
|
|
13
|
+
id: entity.id,
|
|
14
|
+
userId: entity.userId,
|
|
15
|
+
externalId: entity.externalId,
|
|
16
|
+
name: entity.name,
|
|
17
|
+
moduleName: entity.moduleName,
|
|
18
|
+
credentialId: toCredentialId(entity.credential),
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
10
22
|
function mapErrorToResponse(error) {
|
|
11
23
|
const status = ERROR_CODE_MAP[error?.code] || 500;
|
|
12
24
|
return {
|
|
@@ -66,16 +78,7 @@ function createEntityCommands() {
|
|
|
66
78
|
|
|
67
79
|
const entity = await moduleRepo.createEntity(entityData);
|
|
68
80
|
|
|
69
|
-
return
|
|
70
|
-
id: entity.id,
|
|
71
|
-
userId: entity.userId,
|
|
72
|
-
externalId: entity.externalId,
|
|
73
|
-
name: entity.name,
|
|
74
|
-
moduleName: entity.moduleName,
|
|
75
|
-
credentialId: entity.credential?._id
|
|
76
|
-
? entity.credential._id.toString()
|
|
77
|
-
: entity.credential,
|
|
78
|
-
};
|
|
81
|
+
return toEntityDto(entity);
|
|
79
82
|
} catch (error) {
|
|
80
83
|
return mapErrorToResponse(error);
|
|
81
84
|
}
|
|
@@ -109,16 +112,7 @@ function createEntityCommands() {
|
|
|
109
112
|
return null;
|
|
110
113
|
}
|
|
111
114
|
|
|
112
|
-
return
|
|
113
|
-
id: entity.id,
|
|
114
|
-
userId: entity.userId,
|
|
115
|
-
externalId: entity.externalId,
|
|
116
|
-
name: entity.name,
|
|
117
|
-
moduleName: entity.moduleName,
|
|
118
|
-
credentialId: entity.credential?._id
|
|
119
|
-
? entity.credential._id.toString()
|
|
120
|
-
: entity.credential,
|
|
121
|
-
};
|
|
115
|
+
return toEntityDto(entity);
|
|
122
116
|
} catch (error) {
|
|
123
117
|
return mapErrorToResponse(error);
|
|
124
118
|
}
|
|
@@ -139,16 +133,7 @@ function createEntityCommands() {
|
|
|
139
133
|
|
|
140
134
|
const entities = await moduleRepo.findEntitiesByUserId(userId);
|
|
141
135
|
|
|
142
|
-
return entities.map((entity) => (
|
|
143
|
-
id: entity.id,
|
|
144
|
-
userId: entity.userId,
|
|
145
|
-
externalId: entity.externalId,
|
|
146
|
-
name: entity.name,
|
|
147
|
-
moduleName: entity.moduleName,
|
|
148
|
-
credentialId: entity.credential?._id
|
|
149
|
-
? entity.credential._id.toString()
|
|
150
|
-
: entity.credential,
|
|
151
|
-
}));
|
|
136
|
+
return entities.map((entity) => toEntityDto(entity));
|
|
152
137
|
} catch (error) {
|
|
153
138
|
if (error.code) {
|
|
154
139
|
return mapErrorToResponse(error);
|
|
@@ -180,16 +165,7 @@ function createEntityCommands() {
|
|
|
180
165
|
moduleName
|
|
181
166
|
);
|
|
182
167
|
|
|
183
|
-
return entities.map((entity) => (
|
|
184
|
-
id: entity.id,
|
|
185
|
-
userId: entity.userId,
|
|
186
|
-
externalId: entity.externalId,
|
|
187
|
-
name: entity.name,
|
|
188
|
-
moduleName: entity.moduleName,
|
|
189
|
-
credentialId: entity.credential?._id
|
|
190
|
-
? entity.credential._id.toString()
|
|
191
|
-
: entity.credential,
|
|
192
|
-
}));
|
|
168
|
+
return entities.map((entity) => toEntityDto(entity));
|
|
193
169
|
} catch (error) {
|
|
194
170
|
if (error.code) {
|
|
195
171
|
return mapErrorToResponse(error);
|
|
@@ -213,16 +189,7 @@ function createEntityCommands() {
|
|
|
213
189
|
|
|
214
190
|
const entity = await moduleRepo.findEntityById(entityId);
|
|
215
191
|
|
|
216
|
-
return
|
|
217
|
-
id: entity.id,
|
|
218
|
-
userId: entity.userId,
|
|
219
|
-
externalId: entity.externalId,
|
|
220
|
-
name: entity.name,
|
|
221
|
-
moduleName: entity.moduleName,
|
|
222
|
-
credentialId: entity.credential?._id
|
|
223
|
-
? entity.credential._id.toString()
|
|
224
|
-
: entity.credential,
|
|
225
|
-
};
|
|
192
|
+
return toEntityDto(entity);
|
|
226
193
|
} catch (error) {
|
|
227
194
|
return mapErrorToResponse(error);
|
|
228
195
|
}
|
|
@@ -250,16 +217,7 @@ function createEntityCommands() {
|
|
|
250
217
|
throw error;
|
|
251
218
|
}
|
|
252
219
|
|
|
253
|
-
return
|
|
254
|
-
id: entity.id,
|
|
255
|
-
userId: entity.userId,
|
|
256
|
-
externalId: entity.externalId,
|
|
257
|
-
name: entity.name,
|
|
258
|
-
moduleName: entity.moduleName,
|
|
259
|
-
credentialId: entity.credential?._id
|
|
260
|
-
? entity.credential._id.toString()
|
|
261
|
-
: entity.credential,
|
|
262
|
-
};
|
|
220
|
+
return toEntityDto(entity);
|
|
263
221
|
} catch (error) {
|
|
264
222
|
return mapErrorToResponse(error);
|
|
265
223
|
}
|
|
@@ -29,6 +29,12 @@ const {
|
|
|
29
29
|
const {
|
|
30
30
|
PatchIntegrationConfig,
|
|
31
31
|
} = require('../../integrations/use-cases/patch-integration-config');
|
|
32
|
+
const {
|
|
33
|
+
AddEntitiesToIntegration,
|
|
34
|
+
} = require('../../integrations/use-cases/add-entities-to-integration');
|
|
35
|
+
const {
|
|
36
|
+
RemoveEntitiesFromIntegration,
|
|
37
|
+
} = require('../../integrations/use-cases/remove-entities-from-integration');
|
|
32
38
|
const {
|
|
33
39
|
getModulesDefinitionFromIntegrationClasses,
|
|
34
40
|
} = require('../../integrations/utils/map-integration-dto');
|
|
@@ -40,6 +46,11 @@ const ERROR_CODE_MAP = {
|
|
|
40
46
|
EXTERNAL_ID_REQUIRED: 400,
|
|
41
47
|
TYPE_REQUIRED: 400,
|
|
42
48
|
INTEGRATION_RECORD_NOT_FOUND: 404,
|
|
49
|
+
INVALID_INTEGRATION_DATA: 400,
|
|
50
|
+
ENTITIES_NOT_FOUND: 404,
|
|
51
|
+
ENTITY_USER_MISMATCH: 403,
|
|
52
|
+
ENTITY_MODULE_MISMATCH: 400,
|
|
53
|
+
LAST_ENTITY_OF_MODULE: 409,
|
|
43
54
|
};
|
|
44
55
|
|
|
45
56
|
function mapErrorToResponse(error) {
|
|
@@ -163,6 +174,17 @@ function createIntegrationCommands({ integrationClass } = {}) {
|
|
|
163
174
|
integrationRepository,
|
|
164
175
|
});
|
|
165
176
|
|
|
177
|
+
const addEntitiesToIntegrationUseCase = new AddEntitiesToIntegration({
|
|
178
|
+
integrationRepository,
|
|
179
|
+
moduleRepository,
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
const removeEntitiesFromIntegrationUseCase =
|
|
183
|
+
new RemoveEntitiesFromIntegration({
|
|
184
|
+
integrationRepository,
|
|
185
|
+
moduleRepository,
|
|
186
|
+
});
|
|
187
|
+
|
|
166
188
|
return {
|
|
167
189
|
findIntegrationById,
|
|
168
190
|
listIntegrations,
|
|
@@ -307,6 +329,47 @@ function createIntegrationCommands({ integrationClass } = {}) {
|
|
|
307
329
|
}
|
|
308
330
|
},
|
|
309
331
|
|
|
332
|
+
/**
|
|
333
|
+
* Attach entities to an existing integration. Every entity must
|
|
334
|
+
* exist, belong to the integration's user, and be of a module the
|
|
335
|
+
* integration already holds; entities that are already attached are
|
|
336
|
+
* left as they are.
|
|
337
|
+
* @param {Object} params
|
|
338
|
+
* @param {string} params.integrationId - Integration ID
|
|
339
|
+
* @param {Array<string>} params.entityIds - Entity IDs to attach
|
|
340
|
+
* @returns {Promise<Object>} Updated integration
|
|
341
|
+
*/
|
|
342
|
+
async addEntitiesToIntegration({ integrationId, entityIds }) {
|
|
343
|
+
try {
|
|
344
|
+
return await addEntitiesToIntegrationUseCase.execute(
|
|
345
|
+
integrationId,
|
|
346
|
+
entityIds
|
|
347
|
+
);
|
|
348
|
+
} catch (error) {
|
|
349
|
+
return mapErrorToResponse(error);
|
|
350
|
+
}
|
|
351
|
+
},
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Detach entities from an integration. Entities that are not
|
|
355
|
+
* attached are ignored; detached entities are not deleted. Each
|
|
356
|
+
* module must keep at least one entity.
|
|
357
|
+
* @param {Object} params
|
|
358
|
+
* @param {string} params.integrationId - Integration ID
|
|
359
|
+
* @param {Array<string>} params.entityIds - Entity IDs to detach
|
|
360
|
+
* @returns {Promise<Object>} Updated integration
|
|
361
|
+
*/
|
|
362
|
+
async removeEntitiesFromIntegration({ integrationId, entityIds }) {
|
|
363
|
+
try {
|
|
364
|
+
return await removeEntitiesFromIntegrationUseCase.execute(
|
|
365
|
+
integrationId,
|
|
366
|
+
entityIds
|
|
367
|
+
);
|
|
368
|
+
} catch (error) {
|
|
369
|
+
return mapErrorToResponse(error);
|
|
370
|
+
}
|
|
371
|
+
},
|
|
372
|
+
|
|
310
373
|
/**
|
|
311
374
|
* Delete an integration by ID
|
|
312
375
|
* @param {string} integrationId - Integration ID to delete
|