@friggframework/core 2.0.0--canary.657.f16d20b.0 → 2.0.0--canary.737.83b4e17.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 +48 -93
- 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 +1 -33
- package/core/Worker.js +11 -317
- package/core/create-handler.js +0 -3
- package/core/index.js +0 -6
- package/core/invocation-scope.js +24 -30
- 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 +18 -11
- package/errors/index.js +4 -2
- package/errors/mapping-already-exists-error.js +14 -0
- package/generated/prisma-mongodb/edge.js +6 -2
- package/generated/prisma-mongodb/index.js +10 -2
- 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 +1 -1
- package/generated/prisma-mongodb/wasm.js +6 -2
- package/generated/prisma-postgresql/edge.js +6 -2
- package/generated/prisma-postgresql/index.js +10 -2
- 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 +1 -1
- package/generated/prisma-postgresql/wasm.js +6 -2
- package/handlers/WEBHOOKS.md +29 -0
- package/handlers/app-definition-loader.js +9 -2
- package/handlers/app-handler-helpers.js +12 -1
- package/handlers/backend-utils.js +1 -30
- package/handlers/workers/integration-defined-workers.js +0 -2
- package/index.js +2 -18
- package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +67 -15
- package/integrations/integration-base.js +52 -9
- 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 +32 -0
- package/integrations/repositories/integration-repository-interface.js +30 -0
- package/integrations/repositories/integration-repository-mongo.js +53 -1
- package/integrations/repositories/integration-repository-postgres.js +58 -0
- package/integrations/repositories/process-repository-mongo.js +1 -1
- package/integrations/use-cases/add-entities-to-integration.js +92 -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 +1 -5
- 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/logs/serialize.js +0 -15
- package/modules/requester/oauth-2.js +0 -7
- package/modules/requester/requester.js +9 -187
- 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 +9 -8
- package/prisma-mongodb/schema.prisma +1 -1
- package/prisma-postgresql/schema.prisma +1 -1
- package/queues/queue-delivery.js +0 -1
- package/queues/queuer-util.js +10 -8
- package/queues/sqs-message-body.js +17 -0
- 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/index.d.ts +0 -52
- package/types/errors/index.d.ts +0 -47
- package/types/module-plugin/index.d.ts +0 -43
- 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/core/invocation-deadline.js +0 -91
- package/errors/rate-limit-error.js +0 -46
- package/integrations/use-cases/clear-rate-limit-wait.js +0 -28
- package/integrations/use-cases/record-rate-limit-wait.js +0 -36
- package/modules/requester/rate-limit/index.js +0 -4
- package/modules/requester/rate-limit/parsers.js +0 -245
- package/modules/requester/rate-limit/policy.js +0 -304
- package/queues/queue-deferral.js +0 -74
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
|
|
@@ -369,16 +409,6 @@ class MyIntegration extends IntegrationBase {
|
|
|
369
409
|
- `ApiKeyRequester` - API key authentication
|
|
370
410
|
- `BasicAuthRequester` - Basic authentication
|
|
371
411
|
|
|
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
|
-
|
|
382
412
|
**Module Factory**:
|
|
383
413
|
- `ModuleFactory` - Creates and configures API module instances
|
|
384
414
|
- Handles credential injection
|
|
@@ -486,22 +516,20 @@ handlers (`{ req, res, next }`) and `this.on` events do not.
|
|
|
486
516
|
|
|
487
517
|
`isLastAttempt` is `false` when either count is unknown: a local or non-SQS
|
|
488
518
|
invocation, or a queue whose redrive policy the stack does not own
|
|
489
|
-
(`ownership.queue: 'external'`). The value
|
|
490
|
-
retryable
|
|
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.
|
|
519
|
+
(`ownership.queue: 'external'`). The value is information only: core still
|
|
520
|
+
rethrows retryable errors and discards halt errors (4xx except 408/429).
|
|
493
521
|
|
|
494
|
-
Use it to end a run or count lost work on the final try
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
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.
|
|
498
526
|
|
|
499
527
|
```javascript
|
|
500
528
|
async processBatch({ data, delivery }) {
|
|
501
529
|
try {
|
|
502
530
|
await this.syncPage(data);
|
|
503
531
|
} catch (error) {
|
|
504
|
-
if (delivery?.isLastAttempt)
|
|
532
|
+
if (delivery?.isLastAttempt) await this.failRun(data.processId, error);
|
|
505
533
|
throw error;
|
|
506
534
|
}
|
|
507
535
|
}
|
|
@@ -512,76 +540,6 @@ The single source of the max receive count is
|
|
|
512
540
|
devtools integration builder uses it for the queue's `RedrivePolicy` and sets
|
|
513
541
|
it as `FRIGG_QUEUE_MAX_RECEIVE_COUNT` on the queue worker function.
|
|
514
542
|
|
|
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
|
-
|
|
585
543
|
### 8. Error Handling (`/errors`)
|
|
586
544
|
|
|
587
545
|
**Purpose**: Standardized error types with proper HTTP semantics.
|
|
@@ -589,7 +547,6 @@ that does not own it (`ownership.queue: 'external'`) needs its own
|
|
|
589
547
|
**Error Types**:
|
|
590
548
|
- `BaseError` - Base error class
|
|
591
549
|
- `FetchError` - HTTP request failures
|
|
592
|
-
- `RateLimitError` - A `FetchError` for a limit the provider or the module's policy says when to retry (`retryAt`)
|
|
593
550
|
- `HaltError` - Stop processing without retry
|
|
594
551
|
- `RequiredPropertyError` - Missing required parameters
|
|
595
552
|
- `ParameterTypeError` - Invalid parameter type
|
|
@@ -833,8 +790,6 @@ Use test doubles from `@friggframework/test` package for consistent mocking.
|
|
|
833
790
|
- `SECRET_ARN` - AWS Secrets Manager ARN for auto-injection
|
|
834
791
|
- `FRIGG_LOG_LEVEL` - Minimum log level (`TRACE` … `FATAL`, default `INFO`; `DEBUG` on local runs)
|
|
835
792
|
- `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)
|
|
838
793
|
|
|
839
794
|
## Version Information
|
|
840
795
|
|
|
@@ -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
|
package/core/CLAUDE.md
CHANGED
|
@@ -79,36 +79,6 @@ await worker.send({
|
|
|
79
79
|
}, delaySeconds);
|
|
80
80
|
```
|
|
81
81
|
|
|
82
|
-
**Rate-limit deferral** (ADR-049): `run()` handles an error with `isRateLimited`
|
|
83
|
-
and a `retryAt` through `defer(record, body, error, delivery)`, which returns
|
|
84
|
-
`{ outcome }`:
|
|
85
|
-
- `acked`: the message was sent again with `DelaySeconds` (wait up to 900 s) or
|
|
86
|
-
scheduled with the one-time scheduler (longer wait). The record is handled.
|
|
87
|
-
- `failed`: the visibility timeout was extended to `retryAt`, or a cap
|
|
88
|
-
(`FRIGG_QUEUE_MAX_DEFERRALS`, `FRIGG_QUEUE_MAX_DEFERRED_MS`) ended the
|
|
89
|
-
deferrals. The record is reported failed.
|
|
90
|
-
- `skipped`: no `retryAt` (`no_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.
|
|
101
|
-
`recordRateLimitWait(body, error, state)` runs before a delayed message is sent,
|
|
102
|
-
because with a short delay the new message can run first; a failed send clears
|
|
103
|
-
the wait again. For a schedule or a visibility change it runs after the change.
|
|
104
|
-
`clearRateLimitWait(body, { deferralId })` runs after a deferred or redelivered
|
|
105
|
-
message succeeded.
|
|
106
|
-
`state.deferralId` and `deferralId` name the message that was first put back
|
|
107
|
-
(`_frigg.deferralId`, or the message's own id). A failing hook logs
|
|
108
|
-
`frigg.worker.rate_limit_state_failed` and never changes the outcome. The queue
|
|
109
|
-
worker of an integration (`createQueueWorker`) writes `Process.context.rateLimit`
|
|
110
|
-
in them. See `packages/core/CLAUDE.md` section 7.
|
|
111
|
-
|
|
112
82
|
### Delegate Pattern System (`Delegate.js:3-27`)
|
|
113
83
|
|
|
114
84
|
**Purpose**: Observer/delegation pattern for decoupled component communication
|
|
@@ -160,7 +130,7 @@ class MyIntegration extends Delegate {
|
|
|
160
130
|
### Lambda Handler Lifecycle
|
|
161
131
|
1. **Pre-Execution Setup**:
|
|
162
132
|
```javascript
|
|
163
|
-
runInvocationScope({ requestId, handlerName, method, route, invocation }, …); // Logger scope
|
|
133
|
+
runInvocationScope({ requestId, handlerName, method, route, invocation }, …); // Logger scope for the invocation
|
|
164
134
|
log.info('Handler invoked', { eventName: 'frigg.handler.invoked' });
|
|
165
135
|
await secretsToEnv(); // Secrets Manager injection
|
|
166
136
|
await parametersToEnv(); // SSM Parameter Store fetch (only when SSM_PARAMETER_PREFIX + FRIGG_SSM_OFFLOADED_KEYS are set)
|
|
@@ -256,8 +226,6 @@ const handler = createHandler({
|
|
|
256
226
|
- Logs error but returns success
|
|
257
227
|
- Prevents infinite retries for known issues
|
|
258
228
|
- Used for graceful degradation scenarios
|
|
259
|
-
- The queue worker sets it on a 4xx except 408, 429 and errors with
|
|
260
|
-
`isRateLimited` (a provider limit signalled with 403 clears with time)
|
|
261
229
|
|
|
262
230
|
### Logging Strategy
|
|
263
231
|
```javascript
|