@friggframework/core 2.0.0--canary.731.ffe61d3.0 → 2.0.0--canary.657.18fb0ee.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 +93 -48
- package/application/commands/README.md +11 -17
- package/application/commands/entity-commands.js +60 -18
- package/application/commands/integration-commands.js +0 -63
- package/core/CLAUDE.md +30 -1
- package/core/Worker.js +310 -9
- package/core/create-handler.js +3 -0
- package/core/index.js +6 -0
- package/core/invocation-deadline.js +91 -0
- package/core/invocation-scope.js +30 -24
- package/database/documentdb-encryption-service.js +33 -2
- package/database/documentdb-utils.js +1 -4
- package/database/encryption/README.md +3 -3
- package/database/encryption/encryption-schema-registry.js +29 -109
- package/database/encryption/field-encryption-service.js +16 -55
- package/database/encryption/prisma-encryption-extension.js +9 -6
- package/database/prisma.js +1 -10
- package/encrypt/Cryptor.js +38 -90
- package/errors/fetch-error.js +11 -18
- package/errors/index.js +2 -4
- package/errors/rate-limit-error.js +45 -0
- package/generated/prisma-mongodb/edge.js +2 -6
- package/generated/prisma-mongodb/index.js +2 -10
- package/generated/prisma-mongodb/package.json +1 -1
- package/generated/prisma-mongodb/schema.prisma +1 -1
- package/generated/prisma-mongodb/wasm.js +2 -6
- package/generated/prisma-postgresql/edge.js +2 -6
- package/generated/prisma-postgresql/index.js +2 -10
- package/generated/prisma-postgresql/package.json +1 -1
- package/generated/prisma-postgresql/schema.prisma +1 -1
- package/generated/prisma-postgresql/wasm.js +2 -6
- package/handlers/WEBHOOKS.md +0 -29
- package/handlers/app-definition-loader.js +2 -9
- package/handlers/app-handler-helpers.js +1 -12
- package/handlers/backend-utils.js +30 -1
- package/handlers/workers/integration-defined-workers.js +2 -0
- package/index.js +18 -2
- package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +15 -67
- package/integrations/integration-base.js +9 -52
- package/integrations/integration-router.js +22 -30
- package/integrations/repositories/integration-mapping-repository-documentdb.js +0 -50
- package/integrations/repositories/integration-mapping-repository-interface.js +0 -15
- package/integrations/repositories/integration-mapping-repository-mongo.js +0 -29
- package/integrations/repositories/integration-mapping-repository-postgres.js +0 -30
- package/integrations/repositories/integration-mapping-repository.js +0 -29
- package/integrations/repositories/integration-repository-documentdb.js +0 -32
- package/integrations/repositories/integration-repository-interface.js +0 -30
- package/integrations/repositories/integration-repository-mongo.js +1 -53
- package/integrations/repositories/integration-repository-postgres.js +0 -58
- package/integrations/repositories/process-repository-mongo.js +1 -1
- package/integrations/use-cases/clear-rate-limit-wait.js +28 -0
- package/integrations/use-cases/create-integration.js +19 -57
- package/integrations/use-cases/delete-integration-for-user.js +11 -8
- package/integrations/use-cases/get-integration-instance.js +12 -12
- package/integrations/use-cases/index.js +5 -1
- package/integrations/use-cases/record-rate-limit-wait.js +36 -0
- package/integrations/use-cases/update-integration.js +12 -12
- package/jest-setup.js +2 -13
- package/jest-teardown.js +2 -5
- package/jest.config.js +0 -4
- package/logs/serialize.js +15 -0
- package/modules/requester/oauth-2.js +7 -0
- package/modules/requester/rate-limit/index.js +4 -0
- package/modules/requester/rate-limit/parsers.js +245 -0
- package/modules/requester/rate-limit/policy.js +304 -0
- package/modules/requester/requester.js +187 -9
- package/modules/use-cases/get-entity-options-by-id.js +5 -7
- package/modules/use-cases/get-module.js +8 -29
- package/modules/use-cases/process-authorization-callback.js +27 -78
- package/modules/use-cases/refresh-entity-options.js +5 -7
- package/modules/use-cases/test-module-auth.js +5 -7
- package/modules/utils/map-module-dto.js +3 -5
- package/package.json +8 -9
- package/prisma-mongodb/schema.prisma +1 -1
- package/prisma-postgresql/schema.prisma +1 -1
- package/queues/queue-deferral.js +74 -0
- package/queues/queue-delivery.js +1 -0
- package/queues/queuer-util.js +6 -7
- package/telemetry/otel-telemetry.js +3 -76
- package/telemetry/telemetry-config.js +5 -16
- package/telemetry/telemetry-runtime.js +1 -14
- package/token/repositories/token-repository-documentdb.js +1 -13
- package/token/repositories/token-repository-mongo.js +1 -13
- package/token/repositories/token-repository-postgres.js +1 -13
- package/types/core/index.d.ts +52 -0
- package/types/errors/index.d.ts +47 -0
- package/types/module-plugin/index.d.ts +43 -0
- package/user/tests/doubles/test-user-repository.js +1 -1
- package/user/use-cases/authenticate-user.js +7 -23
- package/user/use-cases/get-user-from-bearer-token.js +2 -7
- package/database/encryption/ciphertext-format.js +0 -24
- package/errors/mapping-already-exists-error.js +0 -14
- package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
- package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
- package/integrations/use-cases/add-entities-to-integration.js +0 -92
- package/integrations/use-cases/remove-entities-from-integration.js +0 -70
- package/integrations/utils/assert-entity-ids-input.js +0 -42
- package/jest.db.config.js +0 -23
- package/modules/use-cases/create-entity-from-credential.js +0 -105
- package/modules/utils/find-module-definition.js +0 -23
- package/modules/utils/to-credential-id.js +0 -14
package/CLAUDE.md
CHANGED
|
@@ -206,51 +206,11 @@ 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
|
|
210
209
|
|
|
211
210
|
**Repositories**:
|
|
212
211
|
- `integration-repository-factory.js` - Creates database-specific repositories
|
|
213
212
|
- `integration-repository-mongo.js` - MongoDB implementation
|
|
214
213
|
- `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.
|
|
254
214
|
- `integration-mapping-repository-*.js` - Mapping data persistence.
|
|
255
215
|
`queryMappings(integrationId, { where, orderBy, skip, take, omit })`
|
|
256
216
|
returns `{ mappings, total }`: one filtered, ordered page of an
|
|
@@ -266,7 +226,7 @@ packages/core/
|
|
|
266
226
|
mapping keys to leave out of the rows; never write such rows back. Path
|
|
267
227
|
segments must match `^[A-Za-z_][A-Za-z0-9_]*$`. The PostgreSQL, MongoDB and
|
|
268
228
|
DocumentDB adapters give the same pages and totals;
|
|
269
|
-
`integration-mapping-repository-query-parity.
|
|
229
|
+
`integration-mapping-repository-query-parity.test.js` checks that against
|
|
270
230
|
real databases when `QUERY_MAPPINGS_PARITY_MONGO_URL` /
|
|
271
231
|
`QUERY_MAPPINGS_PARITY_POSTGRES_URL` are set. Two orderings still differ:
|
|
272
232
|
strings compare by the database collation on PostgreSQL and by code point
|
|
@@ -409,6 +369,16 @@ class MyIntegration extends IntegrationBase {
|
|
|
409
369
|
- `ApiKeyRequester` - API key authentication
|
|
410
370
|
- `BasicAuthRequester` - Basic authentication
|
|
411
371
|
|
|
372
|
+
**Rate limits** (ADR-049): an API module declares `static rateLimit` on its
|
|
373
|
+
`Requester` subclass. A hinted wait (from `classify()`, the header parsers or
|
|
374
|
+
the static policy) sleeps within a budget that the caller owns (10 s in an HTTP
|
|
375
|
+
handler, 60 s in a queue worker, 300 s outside an invocation, at most 10
|
|
376
|
+
hinted retries), or throws `RateLimitError`
|
|
377
|
+
(`isRateLimited`, `retryAt`) when it does not fit. A 429 with no hint keeps the
|
|
378
|
+
fixed `backOff` ladder. A non-429 limit that `classify` names without a time
|
|
379
|
+
throws `RateLimitError` at once, with `retryAt` unknown. See
|
|
380
|
+
[Rate Limits](../../docs/reference/api-module-definition-and-functions.md#rate-limits-static-ratelimit).
|
|
381
|
+
|
|
412
382
|
**Module Factory**:
|
|
413
383
|
- `ModuleFactory` - Creates and configures API module instances
|
|
414
384
|
- Handles credential injection
|
|
@@ -516,20 +486,22 @@ handlers (`{ req, res, next }`) and `this.on` events do not.
|
|
|
516
486
|
|
|
517
487
|
`isLastAttempt` is `false` when either count is unknown: a local or non-SQS
|
|
518
488
|
invocation, or a queue whose redrive policy the stack does not own
|
|
519
|
-
(`ownership.queue: 'external'`). The value
|
|
520
|
-
|
|
489
|
+
(`ownership.queue: 'external'`). The value does not change what core does: a
|
|
490
|
+
retryable error returns the message to SQS, a rate-limited error puts it back
|
|
491
|
+
to run at `retryAt` (see **Rate-limit deferral** below), and a halt error (4xx
|
|
492
|
+
except 408, 429 and errors with `isRateLimited`) discards it.
|
|
521
493
|
|
|
522
|
-
Use it to end a run or count lost work on the final try: when
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
message
|
|
494
|
+
Use it to end a run or count lost work on the final try. Check it first: when
|
|
495
|
+
it is `true`, mark the run failed or count the message's records as failed, and
|
|
496
|
+
return. Otherwise rethrow. Do not end the run and then rethrow: core can still
|
|
497
|
+
send a `RateLimitError` again, so the message would run again on an ended run.
|
|
526
498
|
|
|
527
499
|
```javascript
|
|
528
500
|
async processBatch({ data, delivery }) {
|
|
529
501
|
try {
|
|
530
502
|
await this.syncPage(data);
|
|
531
503
|
} catch (error) {
|
|
532
|
-
if (delivery?.isLastAttempt)
|
|
504
|
+
if (delivery?.isLastAttempt) return this.failRun(data.processId, error);
|
|
533
505
|
throw error;
|
|
534
506
|
}
|
|
535
507
|
}
|
|
@@ -540,6 +512,76 @@ The single source of the max receive count is
|
|
|
540
512
|
devtools integration builder uses it for the queue's `RedrivePolicy` and sets
|
|
541
513
|
it as `FRIGG_QUEUE_MAX_RECEIVE_COUNT` on the queue worker function.
|
|
542
514
|
|
|
515
|
+
**Rate-limit deferral** (ADR-049): when a queue handler throws an error with
|
|
516
|
+
`isRateLimited` and a `retryAt` (a `RateLimitError` from the Requester, or one a
|
|
517
|
+
module throws), `Worker.run` does not give the message back to SQS for a 30
|
|
518
|
+
minute redelivery. It puts the message back so it runs at `retryAt`:
|
|
519
|
+
|
|
520
|
+
| Wait | What the worker does | Record |
|
|
521
|
+
|---|---|---|
|
|
522
|
+
| Up to 900 s | Sends the same body again with `DelaySeconds`, then acknowledges the old message | handled |
|
|
523
|
+
| 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 |
|
|
524
|
+
| 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 |
|
|
525
|
+
|
|
526
|
+
- The new message starts at receive count 1. A deferred body carries
|
|
527
|
+
`_frigg: { deferrals, firstDeferredAt, deferralId }`; `_frigg` is reserved and
|
|
528
|
+
the handler never sees it. `deferralId` is the SQS message id of the first
|
|
529
|
+
message that was put back, and every later deferral of that work keeps it.
|
|
530
|
+
- The visibility tier sets a timeout of at most 12 h less 20 minutes
|
|
531
|
+
(42,000 s). SQS counts its 12 h maximum from the receive, and an extension
|
|
532
|
+
does not reset it. The margin covers the longest Lambda run (900 s) plus the
|
|
533
|
+
longest batching window (300 s).
|
|
534
|
+
- Two caps bound it: `FRIGG_QUEUE_MAX_DEFERRALS` (default 30) and
|
|
535
|
+
`FRIGG_QUEUE_MAX_DEFERRED_MS` (default 26 h, from the first deferral to the
|
|
536
|
+
retry time). The defaults cover one full day of hourly waits, for a module
|
|
537
|
+
that probes a daily limit every hour. Past a cap, with no `retryAt`, with no
|
|
538
|
+
event source ARN or on a FIFO queue, the record fails like any retryable
|
|
539
|
+
error and `delivery` applies.
|
|
540
|
+
- The mock scheduler is never used for a deferral: a schedule kept in memory
|
|
541
|
+
would be lost with the acknowledged message.
|
|
542
|
+
- With a `processId` in the message, the worker writes
|
|
543
|
+
`Process.context.rateLimit = { status: 'WAITING' | 'EXHAUSTED', mechanism,
|
|
544
|
+
retryAt, reason, module, deferrals, deferralId, updatedAt }`. `EXHAUSTED` means
|
|
545
|
+
a cap ended the deferrals, or a visibility change came on the last delivery.
|
|
546
|
+
The value is one per process, so it holds the latest known wait: a new wait
|
|
547
|
+
replaces it only when its `retryAt` is later, and a `WAITING` value never hides
|
|
548
|
+
an `EXHAUSTED` one. After a deferred or redelivered message ran, the worker
|
|
549
|
+
sets a `WAITING` value to `null` at once when that message set it (same
|
|
550
|
+
`deferralId`, or the message's own id for a visibility change), and for any
|
|
551
|
+
other message only when its `retryAt` is past or within 5 s. So a job that
|
|
552
|
+
resumes before its `retryAt` clears its own wait, and cannot clear the wait of
|
|
553
|
+
another message.
|
|
554
|
+
- Delivery stays at least once. The new message is sent before the old one is
|
|
555
|
+
acknowledged, so a crash between the two can run the work twice.
|
|
556
|
+
- Handlers check `delivery.isLastAttempt` first, then rethrow. The delay and
|
|
557
|
+
schedule tiers send a new message, so they never reach the last attempt. The
|
|
558
|
+
visibility tier and a cap use a receive: on the last one the worker writes an
|
|
559
|
+
ERROR (`frigg.worker.record_lost_rate_limited`), and the handler has this one
|
|
560
|
+
chance to end the run.
|
|
561
|
+
|
|
562
|
+
```javascript
|
|
563
|
+
async processBatch({ data, delivery }) {
|
|
564
|
+
try {
|
|
565
|
+
await this.syncPage(data);
|
|
566
|
+
} catch (error) {
|
|
567
|
+
if (delivery?.isLastAttempt) return this.failRun(data.processId, error);
|
|
568
|
+
throw error; // a RateLimitError too: core puts the message back at retryAt
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
```
|
|
572
|
+
|
|
573
|
+
Records: a rate-limited SQS record gets one log record, by its outcome.
|
|
574
|
+
|
|
575
|
+
| Outcome | Log record |
|
|
576
|
+
|---|---|
|
|
577
|
+
| Acknowledged | WARN `frigg.worker.record_deferred` (`mechanism` `delay` or `schedule`) |
|
|
578
|
+
| Not acknowledged, not the last attempt | One WARN: `record_deferral_capped`, `record_visibility_extended`, or `record_failed` with `deferral.skipped` |
|
|
579
|
+
| Not acknowledged, last attempt | One ERROR, `record_lost_rate_limited`, with the details, and no WARN |
|
|
580
|
+
|
|
581
|
+
A failing run state hook adds `rate_limit_state_failed`. A queue in a stack
|
|
582
|
+
that does not own it (`ownership.queue: 'external'`) needs its own
|
|
583
|
+
`sqs:ChangeMessageVisibility` and scheduler access.
|
|
584
|
+
|
|
543
585
|
### 8. Error Handling (`/errors`)
|
|
544
586
|
|
|
545
587
|
**Purpose**: Standardized error types with proper HTTP semantics.
|
|
@@ -547,6 +589,7 @@ it as `FRIGG_QUEUE_MAX_RECEIVE_COUNT` on the queue worker function.
|
|
|
547
589
|
**Error Types**:
|
|
548
590
|
- `BaseError` - Base error class
|
|
549
591
|
- `FetchError` - HTTP request failures
|
|
592
|
+
- `RateLimitError` - A `FetchError` for a limit the provider or the module's policy says when to retry (`retryAt`)
|
|
550
593
|
- `HaltError` - Stop processing without retry
|
|
551
594
|
- `RequiredPropertyError` - Missing required parameters
|
|
552
595
|
- `ParameterTypeError` - Invalid parameter type
|
|
@@ -790,6 +833,8 @@ Use test doubles from `@friggframework/test` package for consistent mocking.
|
|
|
790
833
|
- `SECRET_ARN` - AWS Secrets Manager ARN for auto-injection
|
|
791
834
|
- `FRIGG_LOG_LEVEL` - Minimum log level (`TRACE` … `FATAL`, default `INFO`; `DEBUG` on local runs)
|
|
792
835
|
- `FRIGG_QUEUE_MAX_RECEIVE_COUNT` - Set by devtools on integration queue workers whose queue the stack owns; feeds `delivery.maxReceiveCount`
|
|
836
|
+
- `FRIGG_QUEUE_MAX_DEFERRALS` - Most rate-limit deferrals of one message (default 30)
|
|
837
|
+
- `FRIGG_QUEUE_MAX_DEFERRED_MS` - Most time in ms from a message's first rate-limit deferral to its retry time (default 26 h)
|
|
793
838
|
|
|
794
839
|
## Version Information
|
|
795
840
|
|
|
@@ -67,10 +67,9 @@ 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
|
-
|
|
72
|
-
|
|
73
|
-
});
|
|
70
|
+
await this.commands.findIntegrationContextByExternalEntityId(
|
|
71
|
+
externalUserId
|
|
72
|
+
);
|
|
74
73
|
|
|
75
74
|
if (result.error) {
|
|
76
75
|
return { error: result.error };
|
|
@@ -232,10 +231,9 @@ Manage integration records and load full integration contexts.
|
|
|
232
231
|
```javascript
|
|
233
232
|
// Find integration context by external entity ID
|
|
234
233
|
// Returns { context, error } where context includes record + hydrated modules
|
|
235
|
-
const result = await commands.findIntegrationContextByExternalEntityId(
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
});
|
|
234
|
+
const result = await commands.findIntegrationContextByExternalEntityId(
|
|
235
|
+
'external-user-or-workspace-id'
|
|
236
|
+
);
|
|
239
237
|
|
|
240
238
|
if (!result.error) {
|
|
241
239
|
integration.setIntegrationRecord(result.context);
|
|
@@ -301,10 +299,7 @@ try {
|
|
|
301
299
|
For integration context operations, errors are returned in the result:
|
|
302
300
|
|
|
303
301
|
```javascript
|
|
304
|
-
const result = await commands.findIntegrationContextByExternalEntityId(
|
|
305
|
-
externalId: userId,
|
|
306
|
-
type: 'my-integration',
|
|
307
|
-
});
|
|
302
|
+
const result = await commands.findIntegrationContextByExternalEntityId(userId);
|
|
308
303
|
|
|
309
304
|
if (result.error) {
|
|
310
305
|
return { error: result.error };
|
|
@@ -354,10 +349,9 @@ const result =
|
|
|
354
349
|
const { createFriggCommands } = require('@friggframework/core');
|
|
355
350
|
|
|
356
351
|
this.commands = createFriggCommands({ integrationClass: MyIntegration });
|
|
357
|
-
const result = await this.commands.findIntegrationContextByExternalEntityId(
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
});
|
|
352
|
+
const result = await this.commands.findIntegrationContextByExternalEntityId(
|
|
353
|
+
userId
|
|
354
|
+
);
|
|
361
355
|
```
|
|
362
356
|
|
|
363
357
|
## Best Practices
|
|
@@ -439,7 +433,7 @@ if (!user) {
|
|
|
439
433
|
| | `findEntitiesByIds(ids)` | Find multiple by IDs |
|
|
440
434
|
| | `updateEntity(id, updates)` | Update entity properties |
|
|
441
435
|
| | `deleteEntity(id)` | Delete entity |
|
|
442
|
-
| **Integration** | `findIntegrationContextByExternalEntityId(
|
|
436
|
+
| **Integration** | `findIntegrationContextByExternalEntityId(externalId)` | Load integration + modules by external ID |
|
|
443
437
|
| | `loadIntegrationContextById(integrationId)` | Load integration + modules by ID |
|
|
444
438
|
|
|
445
439
|
## Support
|
|
@@ -1,24 +1,12 @@
|
|
|
1
1
|
const {
|
|
2
2
|
createModuleRepository,
|
|
3
3
|
} = require('../../modules/repositories/module-repository-factory');
|
|
4
|
-
const { toCredentialId } = require('../../modules/utils/to-credential-id');
|
|
5
4
|
|
|
6
5
|
const ERROR_CODE_MAP = {
|
|
7
6
|
ENTITY_NOT_FOUND: 404,
|
|
8
7
|
INVALID_ENTITY_DATA: 400,
|
|
9
8
|
};
|
|
10
9
|
|
|
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
|
-
|
|
22
10
|
function mapErrorToResponse(error) {
|
|
23
11
|
const status = ERROR_CODE_MAP[error?.code] || 500;
|
|
24
12
|
return {
|
|
@@ -78,7 +66,16 @@ function createEntityCommands() {
|
|
|
78
66
|
|
|
79
67
|
const entity = await moduleRepo.createEntity(entityData);
|
|
80
68
|
|
|
81
|
-
return
|
|
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
|
+
};
|
|
82
79
|
} catch (error) {
|
|
83
80
|
return mapErrorToResponse(error);
|
|
84
81
|
}
|
|
@@ -112,7 +109,16 @@ function createEntityCommands() {
|
|
|
112
109
|
return null;
|
|
113
110
|
}
|
|
114
111
|
|
|
115
|
-
return
|
|
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
|
+
};
|
|
116
122
|
} catch (error) {
|
|
117
123
|
return mapErrorToResponse(error);
|
|
118
124
|
}
|
|
@@ -133,7 +139,16 @@ function createEntityCommands() {
|
|
|
133
139
|
|
|
134
140
|
const entities = await moduleRepo.findEntitiesByUserId(userId);
|
|
135
141
|
|
|
136
|
-
return entities.map((entity) =>
|
|
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
|
+
}));
|
|
137
152
|
} catch (error) {
|
|
138
153
|
if (error.code) {
|
|
139
154
|
return mapErrorToResponse(error);
|
|
@@ -165,7 +180,16 @@ function createEntityCommands() {
|
|
|
165
180
|
moduleName
|
|
166
181
|
);
|
|
167
182
|
|
|
168
|
-
return entities.map((entity) =>
|
|
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
|
+
}));
|
|
169
193
|
} catch (error) {
|
|
170
194
|
if (error.code) {
|
|
171
195
|
return mapErrorToResponse(error);
|
|
@@ -189,7 +213,16 @@ function createEntityCommands() {
|
|
|
189
213
|
|
|
190
214
|
const entity = await moduleRepo.findEntityById(entityId);
|
|
191
215
|
|
|
192
|
-
return
|
|
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
|
+
};
|
|
193
226
|
} catch (error) {
|
|
194
227
|
return mapErrorToResponse(error);
|
|
195
228
|
}
|
|
@@ -217,7 +250,16 @@ function createEntityCommands() {
|
|
|
217
250
|
throw error;
|
|
218
251
|
}
|
|
219
252
|
|
|
220
|
-
return
|
|
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
|
+
};
|
|
221
263
|
} catch (error) {
|
|
222
264
|
return mapErrorToResponse(error);
|
|
223
265
|
}
|
|
@@ -29,12 +29,6 @@ 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');
|
|
38
32
|
const {
|
|
39
33
|
getModulesDefinitionFromIntegrationClasses,
|
|
40
34
|
} = require('../../integrations/utils/map-integration-dto');
|
|
@@ -46,11 +40,6 @@ const ERROR_CODE_MAP = {
|
|
|
46
40
|
EXTERNAL_ID_REQUIRED: 400,
|
|
47
41
|
TYPE_REQUIRED: 400,
|
|
48
42
|
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,
|
|
54
43
|
};
|
|
55
44
|
|
|
56
45
|
function mapErrorToResponse(error) {
|
|
@@ -174,17 +163,6 @@ function createIntegrationCommands({ integrationClass } = {}) {
|
|
|
174
163
|
integrationRepository,
|
|
175
164
|
});
|
|
176
165
|
|
|
177
|
-
const addEntitiesToIntegrationUseCase = new AddEntitiesToIntegration({
|
|
178
|
-
integrationRepository,
|
|
179
|
-
moduleRepository,
|
|
180
|
-
});
|
|
181
|
-
|
|
182
|
-
const removeEntitiesFromIntegrationUseCase =
|
|
183
|
-
new RemoveEntitiesFromIntegration({
|
|
184
|
-
integrationRepository,
|
|
185
|
-
moduleRepository,
|
|
186
|
-
});
|
|
187
|
-
|
|
188
166
|
return {
|
|
189
167
|
findIntegrationById,
|
|
190
168
|
listIntegrations,
|
|
@@ -329,47 +307,6 @@ function createIntegrationCommands({ integrationClass } = {}) {
|
|
|
329
307
|
}
|
|
330
308
|
},
|
|
331
309
|
|
|
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
|
-
|
|
373
310
|
/**
|
|
374
311
|
* Delete an integration by ID
|
|
375
312
|
* @param {string} integrationId - Integration ID to delete
|
package/core/CLAUDE.md
CHANGED
|
@@ -79,6 +79,33 @@ 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_retry_at`), no `eventSourceARN` or a FIFO queue
|
|
91
|
+
(`no_event_source`), a failed send (`send_failed`), or a failed visibility
|
|
92
|
+
change (`visibility_failed`). The record fails as any error does.
|
|
93
|
+
|
|
94
|
+
Each outcome writes one log record. `acked` writes WARN `record_deferred`.
|
|
95
|
+
`failed` and `skipped` write one WARN (`record_visibility_extended`,
|
|
96
|
+
`record_deferral_capped`, or `record_failed` with `deferral: { skipped }`). On
|
|
97
|
+
the last attempt they write one ERROR, `record_lost_rate_limited`, with the
|
|
98
|
+
details, and no WARN.
|
|
99
|
+
|
|
100
|
+
Subclasses override two no-op hooks to keep run state: `recordRateLimitWait(body,
|
|
101
|
+
error, state)` runs after the message was put back, and `clearRateLimitWait(body,
|
|
102
|
+
{ deferralId })` runs after a deferred or redelivered message succeeded.
|
|
103
|
+
`state.deferralId` and `deferralId` name the message that was first put back
|
|
104
|
+
(`_frigg.deferralId`, or the message's own id). A failing hook logs
|
|
105
|
+
`frigg.worker.rate_limit_state_failed` and never changes the outcome. The queue
|
|
106
|
+
worker of an integration (`createQueueWorker`) writes `Process.context.rateLimit`
|
|
107
|
+
in them. See `packages/core/CLAUDE.md` section 7.
|
|
108
|
+
|
|
82
109
|
### Delegate Pattern System (`Delegate.js:3-27`)
|
|
83
110
|
|
|
84
111
|
**Purpose**: Observer/delegation pattern for decoupled component communication
|
|
@@ -130,7 +157,7 @@ class MyIntegration extends Delegate {
|
|
|
130
157
|
### Lambda Handler Lifecycle
|
|
131
158
|
1. **Pre-Execution Setup**:
|
|
132
159
|
```javascript
|
|
133
|
-
runInvocationScope({ requestId, handlerName, method, route, invocation }, …); // Logger scope
|
|
160
|
+
runInvocationScope({ requestId, handlerName, method, route, invocation }, …); // Logger scope + invocation deadline (remainingInvocationMs()) + in-process wait budget (createHandler `maxInProcessWaitMs`: 10 s HTTP, 60 s queue worker)
|
|
134
161
|
log.info('Handler invoked', { eventName: 'frigg.handler.invoked' });
|
|
135
162
|
await secretsToEnv(); // Secrets Manager injection
|
|
136
163
|
await parametersToEnv(); // SSM Parameter Store fetch (only when SSM_PARAMETER_PREFIX + FRIGG_SSM_OFFLOADED_KEYS are set)
|
|
@@ -226,6 +253,8 @@ const handler = createHandler({
|
|
|
226
253
|
- Logs error but returns success
|
|
227
254
|
- Prevents infinite retries for known issues
|
|
228
255
|
- Used for graceful degradation scenarios
|
|
256
|
+
- The queue worker sets it on a 4xx except 408, 429 and errors with
|
|
257
|
+
`isRateLimited` (a provider limit signalled with 403 clears with time)
|
|
229
258
|
|
|
230
259
|
### Logging Strategy
|
|
231
260
|
```javascript
|