@friggframework/core 2.0.0--canary.658.e11f3b0.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 +42 -58
- 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 -3
- package/core/Worker.js +2 -1
- 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/workers/integration-defined-workers.js +0 -2
- package/index.js +2 -18
- package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +67 -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 +42 -23
- package/integrations/repositories/integration-repository-interface.js +37 -21
- package/integrations/repositories/integration-repository-mongo.js +69 -30
- package/integrations/repositories/integration-repository-postgres.js +74 -30
- package/integrations/repositories/process-repository-mongo.js +1 -1
- package/integrations/tests/doubles/test-integration-repository.js +2 -15
- 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/remove-entities-from-integration.js +70 -0
- package/integrations/use-cases/update-integration-messages.js +9 -28
- 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/module.js +0 -27
- package/modules/requester/requester.js +9 -211
- 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 +10 -7
- package/prisma-mongodb/schema.prisma +1 -1
- package/prisma-postgresql/schema.prisma +1 -1
- package/queues/queuer-util.js +9 -7
- 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 -33
- package/types/errors/index.d.ts +0 -47
- package/types/integrations/index.d.ts +4 -20
- package/types/module-plugin/index.d.ts +0 -47
- 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/repositories/message-item-shared.js +0 -4
- package/integrations/tests/doubles/prisma-message-row.js +0 -24
- package/integrations/use-cases/record-rate-limit-message.js +0 -110
- 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
|
@@ -354,6 +354,10 @@ const config = {
|
|
|
354
354
|
{
|
|
355
355
|
"fromEnvVar": null,
|
|
356
356
|
"value": "rhel-openssl-3.0.x"
|
|
357
|
+
},
|
|
358
|
+
{
|
|
359
|
+
"fromEnvVar": null,
|
|
360
|
+
"value": "linux-arm64-openssl-3.0.x"
|
|
357
361
|
}
|
|
358
362
|
],
|
|
359
363
|
"previewFeatures": [],
|
|
@@ -380,8 +384,8 @@ const config = {
|
|
|
380
384
|
}
|
|
381
385
|
}
|
|
382
386
|
},
|
|
383
|
-
"inlineSchema": "// Frigg Framework - Prisma Schema (PostgreSQL)\n// PostgreSQL database schema for enterprise integration platform\n// Converted from MongoDB schema for relational database support\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma-postgresql\"\n binaryTargets = [\"native\", \"rhel-openssl-3.0.x\"] // native for local dev, rhel for Lambda deployment\n // Library engine (default since Prisma 3.x): Rust query engine loads as a\n // Node-API addon inside the same process. The binary engine forks a child\n // query-engine subprocess and communicates over a local HTTP/IPC pipe with\n // NO client-side timeout — a zombied child wedges the Node process until\n // Lambda's 900s cap. Switching to library eliminates that entire class of\n // silent hangs. See friggframework/frigg#580 for the investigation.\n engineType = \"library\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\n// ============================================================================\n// USER MODELS\n// ============================================================================\n\n/// User model with discriminator pattern support\n/// Replaces Mongoose discriminators (IndividualUser, OrganizationUser)\nmodel User {\n id Int @id @default(autoincrement())\n type UserType\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // IndividualUser fields (nullable for organizations)\n email String?\n username String?\n hashword String? // Bcrypt hashed password (handled in application layer)\n appUserId String?\n organizationId Int?\n\n // Self-referential relation for organization membership\n organization User? @relation(\"OrgMembers\", fields: [organizationId], references: [id], onDelete: NoAction, onUpdate: NoAction)\n members User[] @relation(\"OrgMembers\")\n\n // OrganizationUser fields (nullable for individuals)\n appOrgId String?\n name String?\n\n // Relations\n tokens Token[]\n credentials Credential[]\n entities Entity[]\n integrations Integration[]\n processes Process[]\n\n @@unique([username, appUserId])\n @@index([type])\n @@index([appUserId])\n @@index([organizationId])\n}\n\nenum UserType {\n INDIVIDUAL\n ORGANIZATION\n}\n\n// ============================================================================\n// AUTHENTICATION MODELS\n// ============================================================================\n\n/// Authentication tokens with expiration\n/// Bcrypt hashed tokens stored (handled in application layer)\nmodel Token {\n id Int @id @default(autoincrement())\n token String // Bcrypt hashed\n created DateTime @default(now())\n expires DateTime?\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([expires])\n}\n\n// ============================================================================\n// CREDENTIAL & ENTITY MODELS\n// ============================================================================\n\n/// OAuth credentials and API tokens\n/// All sensitive data encrypted with KMS at rest\nmodel Credential {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n authIsValid Boolean?\n externalId String?\n\n // Dynamic OAuth fields stored as JSON (encrypted via Prisma middleware)\n // Contains: access_token, refresh_token, domain, expires_in, token_type, etc.\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n entities Entity[]\n\n @@index([userId])\n @@index([externalId])\n}\n\n/// External service entities (API connections)\nmodel Entity {\n id Int @id @default(autoincrement())\n credentialId Int?\n credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull)\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n name String?\n moduleName String?\n externalId String?\n\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations - many-to-many with implicit join tables\n integrations Integration[]\n syncs Sync[]\n\n dataIdentifiers DataIdentifier[]\n associationObjects AssociationObject[]\n\n @@index([userId])\n @@index([externalId])\n @@index([moduleName])\n @@index([credentialId])\n}\n\n// ============================================================================\n// INTEGRATION MODELS\n// ============================================================================\n\n/// Main integration configuration and state\nmodel Integration {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n status IntegrationStatus @default(IN_CREATION)\n\n // Configuration and version\n config Json? // Integration configuration object\n version String?\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n // Message arrays (stored as JSON)\n errors Json @default(\"[]\")\n warnings Json @default(\"[]\")\n info Json @default(\"[]\")\n logs Json @default(\"[]\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n associations Association[]\n syncs Sync[]\n mappings IntegrationMapping[]\n processes Process[]\n\n @@index([userId])\n @@index([status])\n}\n\nenum IntegrationStatus {\n ENABLED\n NEEDS_CONFIG\n PROCESSING\n DISABLED\n ERROR\n IN_CREATION\n IN_DELETION\n}\n\n/// Integration-specific data mappings\n/// All mapping data encrypted with KMS\nmodel IntegrationMapping {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n sourceId String?\n\n // Encrypted mapping data (handled via Prisma middleware)\n mapping Json?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, sourceId])\n @@index([integrationId])\n @@index([sourceId])\n}\n\n// ============================================================================\n// SYNC MODELS\n// ============================================================================\n\n/// Bidirectional data synchronization tracking\nmodel Sync {\n id Int @id @default(autoincrement())\n integrationId Int?\n integration Integration? @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n hash String\n name String\n\n // Data identifiers (extracted to separate model)\n dataIdentifiers DataIdentifier[]\n\n @@index([integrationId])\n @@index([hash])\n @@index([name])\n}\n\n/// Data identifier for sync operations\n/// Replaces nested array structure in Mongoose\nmodel DataIdentifier {\n id Int @id @default(autoincrement())\n syncId Int?\n sync Sync? @relation(fields: [syncId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n\n // Identifier data (can be any structure)\n idData Json\n\n hash String\n\n @@index([syncId])\n @@index([entityId])\n @@index([hash])\n}\n\n// ============================================================================\n// ASSOCIATION MODELS\n// ============================================================================\n\n/// Entity associations with cardinality tracking\nmodel Association {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n name String\n type AssociationType\n primaryObject String\n\n // Associated objects (extracted to separate model)\n objects AssociationObject[]\n\n @@index([integrationId])\n @@index([name])\n}\n\n/// Association object entry\n/// Replaces nested array structure in Mongoose\nmodel AssociationObject {\n id Int @id @default(autoincrement())\n associationId Int\n association Association @relation(fields: [associationId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n objectType String\n objId String\n metadata Json? // Optional metadata\n\n @@index([associationId])\n @@index([entityId])\n}\n\nenum AssociationType {\n ONE_TO_MANY\n ONE_TO_ONE\n MANY_TO_ONE\n}\n\n// ============================================================================\n// PROCESS MODELS\n// ============================================================================\n\n/// Generic Process Model - tracks any long-running operation\n/// Used for: CRM syncs, data migrations, bulk operations, etc.\nmodel Process {\n id Int @id @default(autoincrement())\n\n // Core references\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Process identification\n name String // e.g., \"zoho-crm-contact-sync\", \"pipedrive-lead-sync\"\n type String // e.g., \"CRM_SYNC\", \"DATA_MIGRATION\", \"BULK_OPERATION\"\n\n // State machine\n state String // Current state (integration-defined states)\n\n // Flexible storage\n context Json @default(\"{}\") // Process-specific data (pagination, metadata, etc.)\n results Json @default(\"{}\") // Process results and metrics\n\n // Hierarchy support - self-referential relation\n parentProcessId Int?\n parentProcess Process? @relation(\"ProcessHierarchy\", fields: [parentProcessId], references: [id], onDelete: SetNull)\n childProcesses Process[] @relation(\"ProcessHierarchy\")\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([userId])\n @@index([integrationId])\n @@index([type])\n @@index([state])\n @@index([name])\n @@index([parentProcessId])\n}\n\n// ============================================================================\n// UTILITY MODELS\n// ============================================================================\n\n/// Generic state storage\nmodel State {\n id Int @id @default(autoincrement())\n state Json?\n}\n\n/// AWS API Gateway WebSocket connection tracking\nmodel WebsocketConnection {\n id Int @id @default(autoincrement())\n connectionId String?\n\n @@index([connectionId])\n}\n\n// ============================================================================\n// ADMIN PROCESS MODELS\n// ============================================================================\n\n/// Admin process state machine\nenum AdminScriptExecutionState {\n PENDING\n RUNNING\n COMPLETED\n FAILED\n}\n\n/// Admin process tracking (like Process but without user/integration FK)\n/// Used for: admin scripts, db migrations, system maintenance tasks\nmodel AdminScriptExecution {\n id Int @id @default(autoincrement())\n name String // e.g., \"oauth-token-refresh\", \"db-migration-xyz\"\n type String // e.g., \"ADMIN_SCRIPT\", \"DB_MIGRATION\"\n\n // State machine\n state AdminScriptExecutionState @default(PENDING)\n\n // Flexible storage (mirrors Process model pattern)\n context Json @default(\"{}\") // input, trigger, audit info, script version\n results Json @default(\"{}\") // output, logs, metrics, errors\n\n // Hierarchy support - self-referential relation\n parentExecutionId Int?\n parentExecution AdminScriptExecution? @relation(\"AdminScriptExecutionHierarchy\", fields: [parentExecutionId], references: [id], onDelete: SetNull)\n childExecutions AdminScriptExecution[] @relation(\"AdminScriptExecutionHierarchy\")\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([name, createdAt(sort: Desc)])\n @@index([state])\n @@index([type])\n}\n\n/// Script scheduling configuration for hybrid scheduling (SQS + EventBridge)\nmodel ScriptSchedule {\n id Int @id @default(autoincrement())\n scriptName String @unique\n enabled Boolean @default(false)\n cronExpression String?\n timezone String @default(\"UTC\")\n lastTriggeredAt DateTime?\n nextTriggerAt DateTime?\n\n // External Scheduler (e.g., AWS EventBridge Scheduler)\n externalScheduleId String?\n externalScheduleName String?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([enabled])\n}\n\n/// Durable usage counters, deliberately isolated: no userId and no foreign key\n/// to Integration, so a user-scoped query can never return a usage row and usage\n/// history survives integration deletion.\nmodel UsageCounter {\n id Int @id @default(autoincrement())\n\n integrationId String\n integrationType String\n metric String\n window String // e.g. \"day:2026-07-05\" or \"hour:2026-07-05T14\"\n value BigInt @default(0) // BigInt: a busy day/hour counter can exceed 32-bit\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, integrationType, metric, window])\n // Covers totals() (metric + window prefix/range, no integrationType filter).\n @@index([metric, window])\n // Covers series() (metric + integrationType + window range).\n @@index([metric, integrationType, window])\n}\n",
|
|
384
|
-
"inlineSchemaHash": "
|
|
387
|
+
"inlineSchema": "// Frigg Framework - Prisma Schema (PostgreSQL)\n// PostgreSQL database schema for enterprise integration platform\n// Converted from MongoDB schema for relational database support\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma-postgresql\"\n binaryTargets = [\"native\", \"rhel-openssl-3.0.x\", \"linux-arm64-openssl-3.0.x\"] // native for local dev, rhel for x86_64 Lambda, linux-arm64 for arm64 Lambda\n // Library engine (default since Prisma 3.x): Rust query engine loads as a\n // Node-API addon inside the same process. The binary engine forks a child\n // query-engine subprocess and communicates over a local HTTP/IPC pipe with\n // NO client-side timeout — a zombied child wedges the Node process until\n // Lambda's 900s cap. Switching to library eliminates that entire class of\n // silent hangs. See friggframework/frigg#580 for the investigation.\n engineType = \"library\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\n// ============================================================================\n// USER MODELS\n// ============================================================================\n\n/// User model with discriminator pattern support\n/// Replaces Mongoose discriminators (IndividualUser, OrganizationUser)\nmodel User {\n id Int @id @default(autoincrement())\n type UserType\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // IndividualUser fields (nullable for organizations)\n email String?\n username String?\n hashword String? // Bcrypt hashed password (handled in application layer)\n appUserId String?\n organizationId Int?\n\n // Self-referential relation for organization membership\n organization User? @relation(\"OrgMembers\", fields: [organizationId], references: [id], onDelete: NoAction, onUpdate: NoAction)\n members User[] @relation(\"OrgMembers\")\n\n // OrganizationUser fields (nullable for individuals)\n appOrgId String?\n name String?\n\n // Relations\n tokens Token[]\n credentials Credential[]\n entities Entity[]\n integrations Integration[]\n processes Process[]\n\n @@unique([username, appUserId])\n @@index([type])\n @@index([appUserId])\n @@index([organizationId])\n}\n\nenum UserType {\n INDIVIDUAL\n ORGANIZATION\n}\n\n// ============================================================================\n// AUTHENTICATION MODELS\n// ============================================================================\n\n/// Authentication tokens with expiration\n/// Bcrypt hashed tokens stored (handled in application layer)\nmodel Token {\n id Int @id @default(autoincrement())\n token String // Bcrypt hashed\n created DateTime @default(now())\n expires DateTime?\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([expires])\n}\n\n// ============================================================================\n// CREDENTIAL & ENTITY MODELS\n// ============================================================================\n\n/// OAuth credentials and API tokens\n/// All sensitive data encrypted with KMS at rest\nmodel Credential {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n authIsValid Boolean?\n externalId String?\n\n // Dynamic OAuth fields stored as JSON (encrypted via Prisma middleware)\n // Contains: access_token, refresh_token, domain, expires_in, token_type, etc.\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n entities Entity[]\n\n @@index([userId])\n @@index([externalId])\n}\n\n/// External service entities (API connections)\nmodel Entity {\n id Int @id @default(autoincrement())\n credentialId Int?\n credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull)\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n name String?\n moduleName String?\n externalId String?\n\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations - many-to-many with implicit join tables\n integrations Integration[]\n syncs Sync[]\n\n dataIdentifiers DataIdentifier[]\n associationObjects AssociationObject[]\n\n @@index([userId])\n @@index([externalId])\n @@index([moduleName])\n @@index([credentialId])\n}\n\n// ============================================================================\n// INTEGRATION MODELS\n// ============================================================================\n\n/// Main integration configuration and state\nmodel Integration {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n status IntegrationStatus @default(IN_CREATION)\n\n // Configuration and version\n config Json? // Integration configuration object\n version String?\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n // Message arrays (stored as JSON)\n errors Json @default(\"[]\")\n warnings Json @default(\"[]\")\n info Json @default(\"[]\")\n logs Json @default(\"[]\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n associations Association[]\n syncs Sync[]\n mappings IntegrationMapping[]\n processes Process[]\n\n @@index([userId])\n @@index([status])\n}\n\nenum IntegrationStatus {\n ENABLED\n NEEDS_CONFIG\n PROCESSING\n DISABLED\n ERROR\n IN_CREATION\n IN_DELETION\n}\n\n/// Integration-specific data mappings\n/// All mapping data encrypted with KMS\nmodel IntegrationMapping {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n sourceId String?\n\n // Encrypted mapping data (handled via Prisma middleware)\n mapping Json?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, sourceId])\n @@index([integrationId])\n @@index([sourceId])\n}\n\n// ============================================================================\n// SYNC MODELS\n// ============================================================================\n\n/// Bidirectional data synchronization tracking\nmodel Sync {\n id Int @id @default(autoincrement())\n integrationId Int?\n integration Integration? @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n hash String\n name String\n\n // Data identifiers (extracted to separate model)\n dataIdentifiers DataIdentifier[]\n\n @@index([integrationId])\n @@index([hash])\n @@index([name])\n}\n\n/// Data identifier for sync operations\n/// Replaces nested array structure in Mongoose\nmodel DataIdentifier {\n id Int @id @default(autoincrement())\n syncId Int?\n sync Sync? @relation(fields: [syncId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n\n // Identifier data (can be any structure)\n idData Json\n\n hash String\n\n @@index([syncId])\n @@index([entityId])\n @@index([hash])\n}\n\n// ============================================================================\n// ASSOCIATION MODELS\n// ============================================================================\n\n/// Entity associations with cardinality tracking\nmodel Association {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n name String\n type AssociationType\n primaryObject String\n\n // Associated objects (extracted to separate model)\n objects AssociationObject[]\n\n @@index([integrationId])\n @@index([name])\n}\n\n/// Association object entry\n/// Replaces nested array structure in Mongoose\nmodel AssociationObject {\n id Int @id @default(autoincrement())\n associationId Int\n association Association @relation(fields: [associationId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n objectType String\n objId String\n metadata Json? // Optional metadata\n\n @@index([associationId])\n @@index([entityId])\n}\n\nenum AssociationType {\n ONE_TO_MANY\n ONE_TO_ONE\n MANY_TO_ONE\n}\n\n// ============================================================================\n// PROCESS MODELS\n// ============================================================================\n\n/// Generic Process Model - tracks any long-running operation\n/// Used for: CRM syncs, data migrations, bulk operations, etc.\nmodel Process {\n id Int @id @default(autoincrement())\n\n // Core references\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Process identification\n name String // e.g., \"zoho-crm-contact-sync\", \"pipedrive-lead-sync\"\n type String // e.g., \"CRM_SYNC\", \"DATA_MIGRATION\", \"BULK_OPERATION\"\n\n // State machine\n state String // Current state (integration-defined states)\n\n // Flexible storage\n context Json @default(\"{}\") // Process-specific data (pagination, metadata, etc.)\n results Json @default(\"{}\") // Process results and metrics\n\n // Hierarchy support - self-referential relation\n parentProcessId Int?\n parentProcess Process? @relation(\"ProcessHierarchy\", fields: [parentProcessId], references: [id], onDelete: SetNull)\n childProcesses Process[] @relation(\"ProcessHierarchy\")\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([userId])\n @@index([integrationId])\n @@index([type])\n @@index([state])\n @@index([name])\n @@index([parentProcessId])\n}\n\n// ============================================================================\n// UTILITY MODELS\n// ============================================================================\n\n/// Generic state storage\nmodel State {\n id Int @id @default(autoincrement())\n state Json?\n}\n\n/// AWS API Gateway WebSocket connection tracking\nmodel WebsocketConnection {\n id Int @id @default(autoincrement())\n connectionId String?\n\n @@index([connectionId])\n}\n\n// ============================================================================\n// ADMIN PROCESS MODELS\n// ============================================================================\n\n/// Admin process state machine\nenum AdminScriptExecutionState {\n PENDING\n RUNNING\n COMPLETED\n FAILED\n}\n\n/// Admin process tracking (like Process but without user/integration FK)\n/// Used for: admin scripts, db migrations, system maintenance tasks\nmodel AdminScriptExecution {\n id Int @id @default(autoincrement())\n name String // e.g., \"oauth-token-refresh\", \"db-migration-xyz\"\n type String // e.g., \"ADMIN_SCRIPT\", \"DB_MIGRATION\"\n\n // State machine\n state AdminScriptExecutionState @default(PENDING)\n\n // Flexible storage (mirrors Process model pattern)\n context Json @default(\"{}\") // input, trigger, audit info, script version\n results Json @default(\"{}\") // output, logs, metrics, errors\n\n // Hierarchy support - self-referential relation\n parentExecutionId Int?\n parentExecution AdminScriptExecution? @relation(\"AdminScriptExecutionHierarchy\", fields: [parentExecutionId], references: [id], onDelete: SetNull)\n childExecutions AdminScriptExecution[] @relation(\"AdminScriptExecutionHierarchy\")\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([name, createdAt(sort: Desc)])\n @@index([state])\n @@index([type])\n}\n\n/// Script scheduling configuration for hybrid scheduling (SQS + EventBridge)\nmodel ScriptSchedule {\n id Int @id @default(autoincrement())\n scriptName String @unique\n enabled Boolean @default(false)\n cronExpression String?\n timezone String @default(\"UTC\")\n lastTriggeredAt DateTime?\n nextTriggerAt DateTime?\n\n // External Scheduler (e.g., AWS EventBridge Scheduler)\n externalScheduleId String?\n externalScheduleName String?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([enabled])\n}\n\n/// Durable usage counters, deliberately isolated: no userId and no foreign key\n/// to Integration, so a user-scoped query can never return a usage row and usage\n/// history survives integration deletion.\nmodel UsageCounter {\n id Int @id @default(autoincrement())\n\n integrationId String\n integrationType String\n metric String\n window String // e.g. \"day:2026-07-05\" or \"hour:2026-07-05T14\"\n value BigInt @default(0) // BigInt: a busy day/hour counter can exceed 32-bit\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, integrationType, metric, window])\n // Covers totals() (metric + window prefix/range, no integrationType filter).\n @@index([metric, window])\n // Covers series() (metric + integrationType + window range).\n @@index([metric, integrationType, window])\n}\n",
|
|
388
|
+
"inlineSchemaHash": "db175a805645aca6df6afa87560783c4a684e0579eb550a679bae2f16d43119a",
|
|
385
389
|
"copyEngine": true
|
|
386
390
|
}
|
|
387
391
|
config.dirname = '/'
|
package/handlers/WEBHOOKS.md
CHANGED
|
@@ -483,6 +483,35 @@ async onWebhook({ data }) {
|
|
|
483
483
|
}
|
|
484
484
|
```
|
|
485
485
|
|
|
486
|
+
`getMapping` followed by `upsertMapping` is not atomic. To claim an event so only one
|
|
487
|
+
concurrent worker proceeds, use the insert-only `createMapping`, which throws
|
|
488
|
+
`MappingAlreadyExistsError` (exported from `@friggframework/core`) when the
|
|
489
|
+
`sourceId` is already taken. `deleteMapping(sourceId)` releases the claim and is a
|
|
490
|
+
no-op when nothing exists.
|
|
491
|
+
|
|
492
|
+
```javascript
|
|
493
|
+
const { MappingAlreadyExistsError } = require('@friggframework/core');
|
|
494
|
+
|
|
495
|
+
async onWebhook({ data }) {
|
|
496
|
+
const claimId = `claim:${data.body.id}`;
|
|
497
|
+
try {
|
|
498
|
+
await this.createMapping(claimId, { claimedAt: new Date() });
|
|
499
|
+
} catch (error) {
|
|
500
|
+
if (error instanceof MappingAlreadyExistsError) {
|
|
501
|
+
return { processed: false, duplicate: true };
|
|
502
|
+
}
|
|
503
|
+
throw error;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
try {
|
|
507
|
+
await this.processEvent(data.body);
|
|
508
|
+
} catch (error) {
|
|
509
|
+
await this.deleteMapping(claimId);
|
|
510
|
+
throw error;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
```
|
|
514
|
+
|
|
486
515
|
### 4. Error Handling
|
|
487
516
|
```javascript
|
|
488
517
|
async onWebhook({ data }) {
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
const { findNearestBackendPackageJson } = require('@friggframework/core/utils');
|
|
2
2
|
const path = require('node:path');
|
|
3
3
|
const fs = require('fs-extra');
|
|
4
|
+
const {
|
|
5
|
+
applyAppDefinitionDefaults,
|
|
6
|
+
} = require('@friggframework/schemas/app-definition');
|
|
4
7
|
const { resolveTelemetryConfig } = require('../telemetry/telemetry-config');
|
|
5
8
|
const { registerDeniedKeys } = require('../logs/denied-keys');
|
|
6
9
|
const {
|
|
@@ -33,7 +36,9 @@ function registerCredentialLogKeys(appDefinition, integrations) {
|
|
|
33
36
|
* @function loadAppDefinition
|
|
34
37
|
* @description Searches for the nearest backend package.json, loads the corresponding index.js file,
|
|
35
38
|
* and extracts the application definition containing integrations and user configuration.
|
|
36
|
-
*
|
|
39
|
+
* The defaults declared in the app-definition schema are applied first (ADR-051), so
|
|
40
|
+
* `userConfig` always holds a complete user config, also when the app omits `user`.
|
|
41
|
+
* @returns {{integrations: Array<object>, userConfig: object, adminScripts: Array<object>, reports: Array<object>, admin: object, telemetry: object, logging: object | null}} An object containing the application definition.
|
|
37
42
|
* @throws {Error} Throws error if backend package.json cannot be found.
|
|
38
43
|
* @throws {Error} Throws error if index.js file cannot be found in the backend directory.
|
|
39
44
|
* @example
|
|
@@ -53,7 +58,9 @@ function loadAppDefinition() {
|
|
|
53
58
|
}
|
|
54
59
|
|
|
55
60
|
const backendJsFile = require(backendFilePath);
|
|
56
|
-
|
|
61
|
+
// The one place schema defaults are applied at runtime (ADR-051): a
|
|
62
|
+
// default in app-definition.schema.json is the value core sees.
|
|
63
|
+
const appDefinition = applyAppDefinitionDefaults(backendJsFile.Definition);
|
|
57
64
|
|
|
58
65
|
const {
|
|
59
66
|
integrations = [],
|
|
@@ -9,6 +9,17 @@ const serverlessHttp = require('serverless-http');
|
|
|
9
9
|
|
|
10
10
|
const log = getLogger('frigg.http');
|
|
11
11
|
|
|
12
|
+
const isHttpErrorStatus = (statusCode) =>
|
|
13
|
+
Number.isInteger(statusCode) && statusCode >= 400 && statusCode <= 599;
|
|
14
|
+
|
|
15
|
+
const toBoom = (err) => {
|
|
16
|
+
if (err.isBoom) return err;
|
|
17
|
+
if (err.isClientSafe === true && isHttpErrorStatus(err.statusCode)) {
|
|
18
|
+
return Boom.boomify(err, { statusCode: err.statusCode });
|
|
19
|
+
}
|
|
20
|
+
return Boom.boomify(err);
|
|
21
|
+
};
|
|
22
|
+
|
|
12
23
|
const createApp = (applyMiddleware) => {
|
|
13
24
|
const app = express();
|
|
14
25
|
|
|
@@ -27,7 +38,7 @@ const createApp = (applyMiddleware) => {
|
|
|
27
38
|
|
|
28
39
|
// The express boundary: send the error response and log it one time.
|
|
29
40
|
app.use((err, req, res, next) => {
|
|
30
|
-
const boomError =
|
|
41
|
+
const boomError = toBoom(err);
|
|
31
42
|
const {
|
|
32
43
|
output: { statusCode = 500 },
|
|
33
44
|
} = boomError;
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
const { createHandler } = require('@friggframework/core');
|
|
2
2
|
const { loadAppDefinition } = require('../app-definition-loader');
|
|
3
3
|
const { createQueueWorker } = require('../backend-utils');
|
|
4
|
-
const { MAX_IN_PROCESS_WAIT_MS } = require('../../core/invocation-deadline');
|
|
5
4
|
// TODO(Phase 2): mount extension-declared workers in addition to the per-integration
|
|
6
5
|
// default queue worker. Today, getExtensionWorkers(IntegrationClass) returns the
|
|
7
6
|
// declared workers but they are not yet bound to dedicated SQS sources. Extension-
|
|
@@ -20,7 +19,6 @@ integrationClasses.forEach((IntegrationClass) => {
|
|
|
20
19
|
queueWorker: createHandler({
|
|
21
20
|
eventName: `Queue Worker for ${IntegrationClass.Definition.name}`,
|
|
22
21
|
isUserFacingResponse: false,
|
|
23
|
-
maxInProcessWaitMs: MAX_IN_PROCESS_WAIT_MS.queueWorker,
|
|
24
22
|
method: async (event, context) => {
|
|
25
23
|
const worker = new defaultQueueWorker();
|
|
26
24
|
return await worker.run(event, context);
|
package/index.js
CHANGED
|
@@ -12,8 +12,6 @@ const {
|
|
|
12
12
|
loadInstalledModules,
|
|
13
13
|
createHandler,
|
|
14
14
|
runInvocationScope,
|
|
15
|
-
runWithInvocationDeadline,
|
|
16
|
-
remainingInvocationMs,
|
|
17
15
|
} = require('./core/index');
|
|
18
16
|
const {
|
|
19
17
|
prisma,
|
|
@@ -57,9 +55,9 @@ const {
|
|
|
57
55
|
BaseError,
|
|
58
56
|
FetchError,
|
|
59
57
|
HaltError,
|
|
60
|
-
RateLimitError,
|
|
61
58
|
RequiredPropertyError,
|
|
62
59
|
ParameterTypeError,
|
|
60
|
+
MappingAlreadyExistsError,
|
|
63
61
|
} = require('./errors/index');
|
|
64
62
|
const {
|
|
65
63
|
IntegrationBase,
|
|
@@ -103,12 +101,6 @@ const {
|
|
|
103
101
|
ModuleConstants,
|
|
104
102
|
ModuleFactory,
|
|
105
103
|
} = require('./modules/index');
|
|
106
|
-
const {
|
|
107
|
-
classifyRateLimit,
|
|
108
|
-
parseRetryAfter,
|
|
109
|
-
parseResetHeaders,
|
|
110
|
-
parseIetfRateLimit,
|
|
111
|
-
} = require('./modules/requester/rate-limit');
|
|
112
104
|
const application = require('./application');
|
|
113
105
|
const utils = require('./utils');
|
|
114
106
|
|
|
@@ -129,8 +121,6 @@ module.exports = {
|
|
|
129
121
|
loadInstalledModules,
|
|
130
122
|
createHandler,
|
|
131
123
|
runInvocationScope,
|
|
132
|
-
runWithInvocationDeadline,
|
|
133
|
-
remainingInvocationMs,
|
|
134
124
|
|
|
135
125
|
// database
|
|
136
126
|
prisma,
|
|
@@ -153,15 +143,9 @@ module.exports = {
|
|
|
153
143
|
BaseError,
|
|
154
144
|
FetchError,
|
|
155
145
|
HaltError,
|
|
156
|
-
RateLimitError,
|
|
157
146
|
RequiredPropertyError,
|
|
158
147
|
ParameterTypeError,
|
|
159
|
-
|
|
160
|
-
// rate limit
|
|
161
|
-
classifyRateLimit,
|
|
162
|
-
parseRetryAfter,
|
|
163
|
-
parseResetHeaders,
|
|
164
|
-
parseIetfRateLimit,
|
|
148
|
+
MappingAlreadyExistsError,
|
|
165
149
|
|
|
166
150
|
// integrations
|
|
167
151
|
IntegrationBase,
|
|
@@ -11,19 +11,65 @@
|
|
|
11
11
|
* This adapter implements SchedulerServiceInterface for AWS EventBridge Scheduler.
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
|
-
const {
|
|
15
|
-
SchedulerClient,
|
|
16
|
-
CreateScheduleCommand,
|
|
17
|
-
DeleteScheduleCommand,
|
|
18
|
-
GetScheduleCommand,
|
|
19
|
-
ResourceNotFoundException,
|
|
20
|
-
} = require('@aws-sdk/client-scheduler');
|
|
21
|
-
|
|
22
14
|
const { SchedulerServiceInterface } = require('./scheduler-service-interface');
|
|
23
15
|
|
|
16
|
+
const SCHEDULER_SDK = '@aws-sdk/client-scheduler';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Lazily load the AWS EventBridge Scheduler SDK.
|
|
20
|
+
*
|
|
21
|
+
* Requiring `@aws-sdk/client-scheduler` at module top level would put the AWS
|
|
22
|
+
* SDK on the load path of every consumer of `@friggframework/core`, including
|
|
23
|
+
* those using the mock scheduler or no scheduler at all. Loading it here, on
|
|
24
|
+
* construction of the EventBridge adapter, keeps it out of the module-load
|
|
25
|
+
* path. The adapter calls it exactly once, in its constructor, and keeps the
|
|
26
|
+
* classes its methods need on the instance.
|
|
27
|
+
*
|
|
28
|
+
* Only a MODULE_NOT_FOUND for the scheduler SDK itself is rewritten into an
|
|
29
|
+
* actionable message; any other failure (including a missing transitive
|
|
30
|
+
* dependency) is rethrown unchanged so the real cause is not masked.
|
|
31
|
+
*
|
|
32
|
+
* @returns {object} The relevant exports from `@aws-sdk/client-scheduler`.
|
|
33
|
+
*/
|
|
34
|
+
function loadSchedulerSdk() {
|
|
35
|
+
try {
|
|
36
|
+
// Keep the literal specifier so bundlers (esbuild) can resolve it.
|
|
37
|
+
return require('@aws-sdk/client-scheduler');
|
|
38
|
+
} catch (error) {
|
|
39
|
+
const isSchedulerSdkMissing =
|
|
40
|
+
error &&
|
|
41
|
+
error.code === 'MODULE_NOT_FOUND' &&
|
|
42
|
+
typeof error.message === 'string' &&
|
|
43
|
+
error.message.includes(SCHEDULER_SDK);
|
|
44
|
+
if (isSchedulerSdkMissing) {
|
|
45
|
+
throw new Error(
|
|
46
|
+
`The EventBridge scheduler requires the "${SCHEDULER_SDK}" package, ` +
|
|
47
|
+
`which is not installed. Install it (\`npm install ${SCHEDULER_SDK}\`) ` +
|
|
48
|
+
'to use the EventBridge scheduler provider, or use the mock scheduler provider ' +
|
|
49
|
+
'(SCHEDULER_PROVIDER=mock) for local development.',
|
|
50
|
+
{ cause: error }
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
24
57
|
class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
|
|
25
58
|
constructor({ region } = {}) {
|
|
26
59
|
super();
|
|
60
|
+
const {
|
|
61
|
+
SchedulerClient,
|
|
62
|
+
CreateScheduleCommand,
|
|
63
|
+
DeleteScheduleCommand,
|
|
64
|
+
GetScheduleCommand,
|
|
65
|
+
ResourceNotFoundException,
|
|
66
|
+
} = loadSchedulerSdk();
|
|
67
|
+
this.sdk = {
|
|
68
|
+
CreateScheduleCommand,
|
|
69
|
+
DeleteScheduleCommand,
|
|
70
|
+
GetScheduleCommand,
|
|
71
|
+
ResourceNotFoundException,
|
|
72
|
+
};
|
|
27
73
|
this.client = new SchedulerClient({
|
|
28
74
|
region: region || process.env.AWS_REGION || 'us-east-1',
|
|
29
75
|
});
|
|
@@ -42,7 +88,12 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
|
|
|
42
88
|
* @param {Object} params.payload - Message payload
|
|
43
89
|
* @returns {Promise<{scheduledJobId: string, scheduledAt: string}>}
|
|
44
90
|
*/
|
|
45
|
-
async scheduleOneTime({
|
|
91
|
+
async scheduleOneTime({
|
|
92
|
+
scheduleName,
|
|
93
|
+
scheduleAt,
|
|
94
|
+
queueResourceId,
|
|
95
|
+
payload,
|
|
96
|
+
}) {
|
|
46
97
|
if (!scheduleName) {
|
|
47
98
|
throw new Error('scheduleName is required');
|
|
48
99
|
}
|
|
@@ -59,8 +110,11 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
|
|
|
59
110
|
}
|
|
60
111
|
|
|
61
112
|
// Format date to AWS schedule expression (at(yyyy-mm-ddThh:mm:ss))
|
|
62
|
-
const scheduleExpression = `at(${scheduleAt
|
|
113
|
+
const scheduleExpression = `at(${scheduleAt
|
|
114
|
+
.toISOString()
|
|
115
|
+
.replace(/\.\d{3}Z$/, '')})`;
|
|
63
116
|
|
|
117
|
+
const { CreateScheduleCommand } = this.sdk;
|
|
64
118
|
const command = new CreateScheduleCommand({
|
|
65
119
|
Name: scheduleName,
|
|
66
120
|
GroupName: this.scheduleGroupName,
|
|
@@ -107,6 +161,7 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
|
|
|
107
161
|
throw new Error('scheduleName is required');
|
|
108
162
|
}
|
|
109
163
|
|
|
164
|
+
const { DeleteScheduleCommand, ResourceNotFoundException } = this.sdk;
|
|
110
165
|
const command = new DeleteScheduleCommand({
|
|
111
166
|
Name: scheduleName,
|
|
112
167
|
GroupName: this.scheduleGroupName,
|
|
@@ -141,6 +196,7 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
|
|
|
141
196
|
throw new Error('scheduleName is required');
|
|
142
197
|
}
|
|
143
198
|
|
|
199
|
+
const { GetScheduleCommand, ResourceNotFoundException } = this.sdk;
|
|
144
200
|
const command = new GetScheduleCommand({
|
|
145
201
|
Name: scheduleName,
|
|
146
202
|
GroupName: this.scheduleGroupName,
|
|
@@ -153,9 +209,7 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
|
|
|
153
209
|
// Format: at(yyyy-mm-ddThh:mm:ss)
|
|
154
210
|
let scheduledAt = null;
|
|
155
211
|
if (response.ScheduleExpression) {
|
|
156
|
-
const match = response.ScheduleExpression.match(
|
|
157
|
-
/^at\((.+)\)$/
|
|
158
|
-
);
|
|
212
|
+
const match = response.ScheduleExpression.match(/^at\((.+)\)$/);
|
|
159
213
|
if (match) {
|
|
160
214
|
scheduledAt = new Date(match[1] + 'Z').toISOString();
|
|
161
215
|
}
|
|
@@ -17,9 +17,6 @@ const {
|
|
|
17
17
|
const {
|
|
18
18
|
UpdateIntegrationConfig,
|
|
19
19
|
} = require('./use-cases/update-integration-config');
|
|
20
|
-
const {
|
|
21
|
-
RecordRateLimitMessage,
|
|
22
|
-
} = require('./use-cases/record-rate-limit-message');
|
|
23
20
|
const { validateExtensionBinding } = require('./extension');
|
|
24
21
|
const { getTelemetry } = require('../telemetry/telemetry-runtime');
|
|
25
22
|
const { instrumentHandler } = require('../telemetry/instrument-handler');
|
|
@@ -62,9 +59,6 @@ class IntegrationBase {
|
|
|
62
59
|
updateIntegrationConfig = new UpdateIntegrationConfig({
|
|
63
60
|
integrationRepository: this.integrationRepository,
|
|
64
61
|
});
|
|
65
|
-
recordRateLimitMessage = new RecordRateLimitMessage({
|
|
66
|
-
integrationRepository: this.integrationRepository,
|
|
67
|
-
});
|
|
68
62
|
|
|
69
63
|
// this.telemetry.count('records.synced', n, { entity: 'contact' })
|
|
70
64
|
telemetry = bindTelemetryContext(getTelemetry(), () =>
|
|
@@ -463,6 +457,35 @@ class IntegrationBase {
|
|
|
463
457
|
);
|
|
464
458
|
}
|
|
465
459
|
|
|
460
|
+
/**
|
|
461
|
+
* Insert-only mapping write; usable as an atomic claim/lock row.
|
|
462
|
+
* @throws {MappingAlreadyExistsError} If a mapping for sourceId exists
|
|
463
|
+
*/
|
|
464
|
+
async createMapping(sourceId, mapping) {
|
|
465
|
+
if (!sourceId) {
|
|
466
|
+
throw new Error(`sourceId must be set`);
|
|
467
|
+
}
|
|
468
|
+
return await this.integrationMappingRepository.createMapping(
|
|
469
|
+
this.id,
|
|
470
|
+
sourceId,
|
|
471
|
+
mapping
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* Deletes the mapping for sourceId. A missing mapping is not an error
|
|
477
|
+
* (resolves with deletedCount 0).
|
|
478
|
+
*/
|
|
479
|
+
async deleteMapping(sourceId) {
|
|
480
|
+
if (!sourceId) {
|
|
481
|
+
throw new Error(`sourceId must be set`);
|
|
482
|
+
}
|
|
483
|
+
return await this.integrationMappingRepository.deleteMapping(
|
|
484
|
+
this.id,
|
|
485
|
+
sourceId
|
|
486
|
+
);
|
|
487
|
+
}
|
|
488
|
+
|
|
466
489
|
/**
|
|
467
490
|
* CHILDREN CAN OVERRIDE THESE CONFIGURATION METHODS
|
|
468
491
|
*/
|
|
@@ -534,17 +557,30 @@ class IntegrationBase {
|
|
|
534
557
|
}
|
|
535
558
|
}
|
|
536
559
|
}
|
|
537
|
-
const dynamicUserActions = await this.
|
|
538
|
-
const filteredDynamicActions =
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
560
|
+
const dynamicUserActions = await this._loadDynamicUserActionEvents();
|
|
561
|
+
const filteredDynamicActions = Object.fromEntries(
|
|
562
|
+
Object.entries(dynamicUserActions).filter(
|
|
563
|
+
([_, event]) =>
|
|
564
|
+
event.type === constantsToBeMigrated.types.USER_ACTION &&
|
|
565
|
+
(!actionType || event.userActionType === actionType)
|
|
566
|
+
)
|
|
567
|
+
);
|
|
545
568
|
return { ...userActions, ...filteredDynamicActions };
|
|
546
569
|
}
|
|
547
570
|
|
|
571
|
+
async _loadDynamicUserActionEvents() {
|
|
572
|
+
const dynamicUserActions = await this.loadDynamicUserActions();
|
|
573
|
+
return Object.fromEntries(
|
|
574
|
+
Object.entries(dynamicUserActions).map(([key, event]) => [
|
|
575
|
+
key,
|
|
576
|
+
{
|
|
577
|
+
...event,
|
|
578
|
+
type: event.type ?? constantsToBeMigrated.types.USER_ACTION,
|
|
579
|
+
},
|
|
580
|
+
])
|
|
581
|
+
);
|
|
582
|
+
}
|
|
583
|
+
|
|
548
584
|
async getActionOptions(actionId, data) {
|
|
549
585
|
const options = {
|
|
550
586
|
jsonSchema: {},
|
|
@@ -824,7 +860,8 @@ class IntegrationBase {
|
|
|
824
860
|
|
|
825
861
|
async initialize() {
|
|
826
862
|
try {
|
|
827
|
-
const additionalUserActions =
|
|
863
|
+
const additionalUserActions =
|
|
864
|
+
await this._loadDynamicUserActionEvents();
|
|
828
865
|
this.events = { ...this.events, ...additionalUserActions };
|
|
829
866
|
} catch (e) {
|
|
830
867
|
this.addError(e);
|
|
@@ -914,16 +951,6 @@ class IntegrationBase {
|
|
|
914
951
|
});
|
|
915
952
|
await this.persistStatus('ENABLED');
|
|
916
953
|
}
|
|
917
|
-
|
|
918
|
-
if (delegateString === 'RATE_LIMITED') {
|
|
919
|
-
this.logger.warn('Module reported a rate limit', {
|
|
920
|
-
eventName: `${this.logger.name}.rate_limited`,
|
|
921
|
-
moduleName: object?.moduleName,
|
|
922
|
-
reason: object?.reason,
|
|
923
|
-
retryAt: object?.retryAt,
|
|
924
|
-
});
|
|
925
|
-
await this.recordRateLimitMessage.execute(this.id, object);
|
|
926
|
-
}
|
|
927
954
|
}
|
|
928
955
|
|
|
929
956
|
/**
|
|
@@ -42,6 +42,9 @@ const {
|
|
|
42
42
|
} = require('../modules/use-cases/get-entity-options-by-type');
|
|
43
43
|
const { TestModuleAuth } = require('../modules/use-cases/test-module-auth');
|
|
44
44
|
const { GetModule } = require('../modules/use-cases/get-module');
|
|
45
|
+
const {
|
|
46
|
+
CreateEntityFromCredential,
|
|
47
|
+
} = require('../modules/use-cases/create-entity-from-credential');
|
|
45
48
|
const {
|
|
46
49
|
GetEntityOptionsById,
|
|
47
50
|
} = require('../modules/use-cases/get-entity-options-by-id');
|
|
@@ -198,6 +201,13 @@ function createIntegrationRouter() {
|
|
|
198
201
|
getModulesDefinitionFromIntegrationClasses(integrationClasses),
|
|
199
202
|
});
|
|
200
203
|
|
|
204
|
+
const createEntityFromCredential = new CreateEntityFromCredential({
|
|
205
|
+
processAuthorizationCallback,
|
|
206
|
+
credentialRepository,
|
|
207
|
+
moduleDefinitions:
|
|
208
|
+
getModulesDefinitionFromIntegrationClasses(integrationClasses),
|
|
209
|
+
});
|
|
210
|
+
|
|
201
211
|
const router = express();
|
|
202
212
|
|
|
203
213
|
setIntegrationRoutes(router, authenticateUser, {
|
|
@@ -218,6 +228,7 @@ function createIntegrationRouter() {
|
|
|
218
228
|
getEntityOptionsById,
|
|
219
229
|
refreshEntityOptions,
|
|
220
230
|
processAuthorizationCallback,
|
|
231
|
+
createEntityFromCredential,
|
|
221
232
|
});
|
|
222
233
|
return router;
|
|
223
234
|
}
|
|
@@ -246,6 +257,15 @@ function checkRequiredParams(params, requiredKeys) {
|
|
|
246
257
|
return returnDict;
|
|
247
258
|
}
|
|
248
259
|
|
|
260
|
+
function assertUserAction(integration, actionId) {
|
|
261
|
+
if (
|
|
262
|
+
!Object.hasOwn(integration.events, actionId) ||
|
|
263
|
+
integration.events[actionId].type !== 'USER_ACTION'
|
|
264
|
+
) {
|
|
265
|
+
throw Boom.notFound(`User action ${actionId} does not exist`);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
249
269
|
/**
|
|
250
270
|
* Sets up integration-related routes on the provided Express router
|
|
251
271
|
* @param {express.Router} router - Express router instance to add routes to
|
|
@@ -382,6 +402,7 @@ function setIntegrationRoutes(router, authenticateUser, useCases) {
|
|
|
382
402
|
params.integrationId,
|
|
383
403
|
user.getId()
|
|
384
404
|
);
|
|
405
|
+
assertUserAction(integration, params.actionId);
|
|
385
406
|
|
|
386
407
|
res.json(
|
|
387
408
|
await integration.send('GET_USER_ACTION_OPTIONS', {
|
|
@@ -407,6 +428,7 @@ function setIntegrationRoutes(router, authenticateUser, useCases) {
|
|
|
407
428
|
params.integrationId,
|
|
408
429
|
user.getId()
|
|
409
430
|
);
|
|
431
|
+
assertUserAction(integration, params.actionId);
|
|
410
432
|
|
|
411
433
|
res.json(
|
|
412
434
|
await integration.send('REFRESH_USER_ACTION_OPTIONS', {
|
|
@@ -428,6 +450,7 @@ function setIntegrationRoutes(router, authenticateUser, useCases) {
|
|
|
428
450
|
params.integrationId,
|
|
429
451
|
user.getId()
|
|
430
452
|
);
|
|
453
|
+
assertUserAction(integration, params.actionId);
|
|
431
454
|
res.json(await integration.send(params.actionId, req.body));
|
|
432
455
|
})
|
|
433
456
|
);
|
|
@@ -502,6 +525,7 @@ function setEntityRoutes(router, authenticateUser, useCases) {
|
|
|
502
525
|
getEntityOptionsById,
|
|
503
526
|
refreshEntityOptions,
|
|
504
527
|
processAuthorizationCallback,
|
|
528
|
+
createEntityFromCredential,
|
|
505
529
|
} = useCases;
|
|
506
530
|
|
|
507
531
|
router.route('/api/authorize').get(
|
|
@@ -566,35 +590,19 @@ function setEntityRoutes(router, authenticateUser, useCases) {
|
|
|
566
590
|
router.route('/api/entity').post(
|
|
567
591
|
catchAsyncError(async (req, res) => {
|
|
568
592
|
const user = await authenticateUser.execute(req);
|
|
569
|
-
const userId = user.getId();
|
|
570
593
|
const params = checkRequiredParams(req.body, [
|
|
571
594
|
'entityType',
|
|
572
595
|
'data',
|
|
573
596
|
]);
|
|
574
597
|
checkRequiredParams(req.body.data, ['credential_id']);
|
|
575
598
|
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
599
|
+
res.json(
|
|
600
|
+
await createEntityFromCredential.execute({
|
|
601
|
+
user,
|
|
602
|
+
entityType: params.entityType,
|
|
603
|
+
credentialId: params.data.credential_id,
|
|
604
|
+
})
|
|
580
605
|
);
|
|
581
|
-
|
|
582
|
-
if (!credential) {
|
|
583
|
-
throw Boom.badRequest('Invalid credential ID');
|
|
584
|
-
}
|
|
585
|
-
|
|
586
|
-
const module = await getModuleInstanceFromType.execute(
|
|
587
|
-
userId,
|
|
588
|
-
params.entityType
|
|
589
|
-
);
|
|
590
|
-
const entityDetails = await module.getEntityDetails(
|
|
591
|
-
module.api,
|
|
592
|
-
null,
|
|
593
|
-
null,
|
|
594
|
-
userId
|
|
595
|
-
);
|
|
596
|
-
|
|
597
|
-
res.json(await module.findOrCreateEntity(entityDetails));
|
|
598
606
|
})
|
|
599
607
|
);
|
|
600
608
|
|