@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
|
@@ -354,10 +354,6 @@ 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"
|
|
361
357
|
}
|
|
362
358
|
],
|
|
363
359
|
"previewFeatures": [],
|
|
@@ -384,8 +380,8 @@ const config = {
|
|
|
384
380
|
}
|
|
385
381
|
}
|
|
386
382
|
},
|
|
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": "
|
|
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": "479850322beddd1dd3603ea62e13dd64fd3fb9c7b99da74bb7f40fe6450e65ae",
|
|
389
385
|
"copyEngine": true
|
|
390
386
|
}
|
|
391
387
|
config.dirname = '/'
|
package/handlers/WEBHOOKS.md
CHANGED
|
@@ -483,35 +483,6 @@ 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
|
-
|
|
515
486
|
### 4. Error Handling
|
|
516
487
|
```javascript
|
|
517
488
|
async onWebhook({ data }) {
|
|
@@ -1,9 +1,6 @@
|
|
|
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');
|
|
7
4
|
const { resolveTelemetryConfig } = require('../telemetry/telemetry-config');
|
|
8
5
|
const { registerDeniedKeys } = require('../logs/denied-keys');
|
|
9
6
|
const {
|
|
@@ -36,9 +33,7 @@ function registerCredentialLogKeys(appDefinition, integrations) {
|
|
|
36
33
|
* @function loadAppDefinition
|
|
37
34
|
* @description Searches for the nearest backend package.json, loads the corresponding index.js file,
|
|
38
35
|
* and extracts the application definition containing integrations and user configuration.
|
|
39
|
-
*
|
|
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.
|
|
36
|
+
* @returns {{integrations: Array<object>, userConfig: object | null, adminScripts: Array<object>, reports: Array<object>, admin: object, telemetry: object, logging: object | null}} An object containing the application definition.
|
|
42
37
|
* @throws {Error} Throws error if backend package.json cannot be found.
|
|
43
38
|
* @throws {Error} Throws error if index.js file cannot be found in the backend directory.
|
|
44
39
|
* @example
|
|
@@ -58,9 +53,7 @@ function loadAppDefinition() {
|
|
|
58
53
|
}
|
|
59
54
|
|
|
60
55
|
const backendJsFile = require(backendFilePath);
|
|
61
|
-
|
|
62
|
-
// default in app-definition.schema.json is the value core sees.
|
|
63
|
-
const appDefinition = applyAppDefinitionDefaults(backendJsFile.Definition);
|
|
56
|
+
const appDefinition = backendJsFile.Definition;
|
|
64
57
|
|
|
65
58
|
const {
|
|
66
59
|
integrations = [],
|
|
@@ -9,17 +9,6 @@ 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
|
-
|
|
23
12
|
const createApp = (applyMiddleware) => {
|
|
24
13
|
const app = express();
|
|
25
14
|
|
|
@@ -38,7 +27,7 @@ const createApp = (applyMiddleware) => {
|
|
|
38
27
|
|
|
39
28
|
// The express boundary: send the error response and log it one time.
|
|
40
29
|
app.use((err, req, res, next) => {
|
|
41
|
-
const boomError =
|
|
30
|
+
const boomError = err.isBoom ? err : Boom.boomify(err);
|
|
42
31
|
const {
|
|
43
32
|
output: { statusCode = 500 },
|
|
44
33
|
} = boomError;
|
|
@@ -21,6 +21,12 @@ const {
|
|
|
21
21
|
getModulesDefinitionFromIntegrationClasses,
|
|
22
22
|
} = require('../integrations/utils/map-integration-dto');
|
|
23
23
|
const { processNotFound } = require('../integrations/use-cases/process-errors');
|
|
24
|
+
const {
|
|
25
|
+
RecordRateLimitWait,
|
|
26
|
+
} = require('../integrations/use-cases/record-rate-limit-wait');
|
|
27
|
+
const {
|
|
28
|
+
ClearRateLimitWait,
|
|
29
|
+
} = require('../integrations/use-cases/clear-rate-limit-wait');
|
|
24
30
|
|
|
25
31
|
const loadRouterFromObject = (IntegrationClass, routerObject) => {
|
|
26
32
|
const router = Router();
|
|
@@ -165,6 +171,28 @@ const createQueueWorker = (integrationClass) => {
|
|
|
165
171
|
const integrationName = integrationClass.Definition.name;
|
|
166
172
|
|
|
167
173
|
class QueueWorker extends Worker {
|
|
174
|
+
async recordRateLimitWait(body, error, state) {
|
|
175
|
+
const processId = body.data?.processId;
|
|
176
|
+
if (!processId) return;
|
|
177
|
+
const recordRateLimitWait = new RecordRateLimitWait({
|
|
178
|
+
processRepository: createProcessRepository(),
|
|
179
|
+
});
|
|
180
|
+
await recordRateLimitWait.execute(processId, {
|
|
181
|
+
...state,
|
|
182
|
+
reason: error.reason,
|
|
183
|
+
module: error.module,
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async clearRateLimitWait(body, { deferralId } = {}) {
|
|
188
|
+
const processId = body?.data?.processId;
|
|
189
|
+
if (!processId) return;
|
|
190
|
+
const clearRateLimitWait = new ClearRateLimitWait({
|
|
191
|
+
processRepository: createProcessRepository(),
|
|
192
|
+
});
|
|
193
|
+
await clearRateLimitWait.execute(processId, { deferralId });
|
|
194
|
+
}
|
|
195
|
+
|
|
168
196
|
async _run(params, context, delivery) {
|
|
169
197
|
const logCtx = {
|
|
170
198
|
integration: integrationName,
|
|
@@ -285,7 +313,8 @@ const createQueueWorker = (integrationClass) => {
|
|
|
285
313
|
status >= 400 &&
|
|
286
314
|
status < 500 &&
|
|
287
315
|
status !== 408 &&
|
|
288
|
-
status !== 429
|
|
316
|
+
status !== 429 &&
|
|
317
|
+
!error.isRateLimited
|
|
289
318
|
) {
|
|
290
319
|
error.isHaltError = true;
|
|
291
320
|
console.warn(
|
|
@@ -1,6 +1,7 @@
|
|
|
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');
|
|
4
5
|
// TODO(Phase 2): mount extension-declared workers in addition to the per-integration
|
|
5
6
|
// default queue worker. Today, getExtensionWorkers(IntegrationClass) returns the
|
|
6
7
|
// declared workers but they are not yet bound to dedicated SQS sources. Extension-
|
|
@@ -19,6 +20,7 @@ integrationClasses.forEach((IntegrationClass) => {
|
|
|
19
20
|
queueWorker: createHandler({
|
|
20
21
|
eventName: `Queue Worker for ${IntegrationClass.Definition.name}`,
|
|
21
22
|
isUserFacingResponse: false,
|
|
23
|
+
maxInProcessWaitMs: MAX_IN_PROCESS_WAIT_MS.queueWorker,
|
|
22
24
|
method: async (event, context) => {
|
|
23
25
|
const worker = new defaultQueueWorker();
|
|
24
26
|
return await worker.run(event, context);
|
package/index.js
CHANGED
|
@@ -12,6 +12,8 @@ const {
|
|
|
12
12
|
loadInstalledModules,
|
|
13
13
|
createHandler,
|
|
14
14
|
runInvocationScope,
|
|
15
|
+
runWithInvocationDeadline,
|
|
16
|
+
remainingInvocationMs,
|
|
15
17
|
} = require('./core/index');
|
|
16
18
|
const {
|
|
17
19
|
prisma,
|
|
@@ -55,9 +57,9 @@ const {
|
|
|
55
57
|
BaseError,
|
|
56
58
|
FetchError,
|
|
57
59
|
HaltError,
|
|
60
|
+
RateLimitError,
|
|
58
61
|
RequiredPropertyError,
|
|
59
62
|
ParameterTypeError,
|
|
60
|
-
MappingAlreadyExistsError,
|
|
61
63
|
} = require('./errors/index');
|
|
62
64
|
const {
|
|
63
65
|
IntegrationBase,
|
|
@@ -101,6 +103,12 @@ const {
|
|
|
101
103
|
ModuleConstants,
|
|
102
104
|
ModuleFactory,
|
|
103
105
|
} = require('./modules/index');
|
|
106
|
+
const {
|
|
107
|
+
classifyRateLimit,
|
|
108
|
+
parseRetryAfter,
|
|
109
|
+
parseResetHeaders,
|
|
110
|
+
parseIetfRateLimit,
|
|
111
|
+
} = require('./modules/requester/rate-limit');
|
|
104
112
|
const application = require('./application');
|
|
105
113
|
const utils = require('./utils');
|
|
106
114
|
|
|
@@ -121,6 +129,8 @@ module.exports = {
|
|
|
121
129
|
loadInstalledModules,
|
|
122
130
|
createHandler,
|
|
123
131
|
runInvocationScope,
|
|
132
|
+
runWithInvocationDeadline,
|
|
133
|
+
remainingInvocationMs,
|
|
124
134
|
|
|
125
135
|
// database
|
|
126
136
|
prisma,
|
|
@@ -143,9 +153,15 @@ module.exports = {
|
|
|
143
153
|
BaseError,
|
|
144
154
|
FetchError,
|
|
145
155
|
HaltError,
|
|
156
|
+
RateLimitError,
|
|
146
157
|
RequiredPropertyError,
|
|
147
158
|
ParameterTypeError,
|
|
148
|
-
|
|
159
|
+
|
|
160
|
+
// rate limit
|
|
161
|
+
classifyRateLimit,
|
|
162
|
+
parseRetryAfter,
|
|
163
|
+
parseResetHeaders,
|
|
164
|
+
parseIetfRateLimit,
|
|
149
165
|
|
|
150
166
|
// integrations
|
|
151
167
|
IntegrationBase,
|
|
@@ -11,67 +11,23 @@
|
|
|
11
11
|
* This adapter implements SchedulerServiceInterface for AWS EventBridge Scheduler.
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
|
-
const {
|
|
15
|
-
|
|
16
|
-
|
|
14
|
+
const {
|
|
15
|
+
SchedulerClient,
|
|
16
|
+
CreateScheduleCommand,
|
|
17
|
+
DeleteScheduleCommand,
|
|
18
|
+
GetScheduleCommand,
|
|
19
|
+
ResourceNotFoundException,
|
|
20
|
+
} = require('@aws-sdk/client-scheduler');
|
|
17
21
|
|
|
18
|
-
|
|
19
|
-
|
|
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
|
-
}
|
|
22
|
+
const { SchedulerServiceInterface } = require('./scheduler-service-interface');
|
|
23
|
+
const { awsConfigOptions } = require('../../queues/queuer-util');
|
|
56
24
|
|
|
57
25
|
class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
|
|
58
26
|
constructor({ region } = {}) {
|
|
59
27
|
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
|
-
};
|
|
73
28
|
this.client = new SchedulerClient({
|
|
74
29
|
region: region || process.env.AWS_REGION || 'us-east-1',
|
|
30
|
+
...awsConfigOptions(),
|
|
75
31
|
});
|
|
76
32
|
this.scheduleGroupName =
|
|
77
33
|
process.env.SCHEDULE_GROUP_NAME || 'frigg-integration-schedules';
|
|
@@ -88,12 +44,7 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
|
|
|
88
44
|
* @param {Object} params.payload - Message payload
|
|
89
45
|
* @returns {Promise<{scheduledJobId: string, scheduledAt: string}>}
|
|
90
46
|
*/
|
|
91
|
-
async scheduleOneTime({
|
|
92
|
-
scheduleName,
|
|
93
|
-
scheduleAt,
|
|
94
|
-
queueResourceId,
|
|
95
|
-
payload,
|
|
96
|
-
}) {
|
|
47
|
+
async scheduleOneTime({ scheduleName, scheduleAt, queueResourceId, payload }) {
|
|
97
48
|
if (!scheduleName) {
|
|
98
49
|
throw new Error('scheduleName is required');
|
|
99
50
|
}
|
|
@@ -110,11 +61,8 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
|
|
|
110
61
|
}
|
|
111
62
|
|
|
112
63
|
// Format date to AWS schedule expression (at(yyyy-mm-ddThh:mm:ss))
|
|
113
|
-
const scheduleExpression = `at(${scheduleAt
|
|
114
|
-
.toISOString()
|
|
115
|
-
.replace(/\.\d{3}Z$/, '')})`;
|
|
64
|
+
const scheduleExpression = `at(${scheduleAt.toISOString().replace(/\.\d{3}Z$/, '')})`;
|
|
116
65
|
|
|
117
|
-
const { CreateScheduleCommand } = this.sdk;
|
|
118
66
|
const command = new CreateScheduleCommand({
|
|
119
67
|
Name: scheduleName,
|
|
120
68
|
GroupName: this.scheduleGroupName,
|
|
@@ -161,7 +109,6 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
|
|
|
161
109
|
throw new Error('scheduleName is required');
|
|
162
110
|
}
|
|
163
111
|
|
|
164
|
-
const { DeleteScheduleCommand, ResourceNotFoundException } = this.sdk;
|
|
165
112
|
const command = new DeleteScheduleCommand({
|
|
166
113
|
Name: scheduleName,
|
|
167
114
|
GroupName: this.scheduleGroupName,
|
|
@@ -196,7 +143,6 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
|
|
|
196
143
|
throw new Error('scheduleName is required');
|
|
197
144
|
}
|
|
198
145
|
|
|
199
|
-
const { GetScheduleCommand, ResourceNotFoundException } = this.sdk;
|
|
200
146
|
const command = new GetScheduleCommand({
|
|
201
147
|
Name: scheduleName,
|
|
202
148
|
GroupName: this.scheduleGroupName,
|
|
@@ -209,7 +155,9 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
|
|
|
209
155
|
// Format: at(yyyy-mm-ddThh:mm:ss)
|
|
210
156
|
let scheduledAt = null;
|
|
211
157
|
if (response.ScheduleExpression) {
|
|
212
|
-
const match = response.ScheduleExpression.match(
|
|
158
|
+
const match = response.ScheduleExpression.match(
|
|
159
|
+
/^at\((.+)\)$/
|
|
160
|
+
);
|
|
213
161
|
if (match) {
|
|
214
162
|
scheduledAt = new Date(match[1] + 'Z').toISOString();
|
|
215
163
|
}
|
|
@@ -457,35 +457,6 @@ class IntegrationBase {
|
|
|
457
457
|
);
|
|
458
458
|
}
|
|
459
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
|
-
|
|
489
460
|
/**
|
|
490
461
|
* CHILDREN CAN OVERRIDE THESE CONFIGURATION METHODS
|
|
491
462
|
*/
|
|
@@ -557,28 +528,15 @@ class IntegrationBase {
|
|
|
557
528
|
}
|
|
558
529
|
}
|
|
559
530
|
}
|
|
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
|
-
);
|
|
568
|
-
return { ...userActions, ...filteredDynamicActions };
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
async _loadDynamicUserActionEvents() {
|
|
572
531
|
const dynamicUserActions = await this.loadDynamicUserActions();
|
|
573
|
-
|
|
574
|
-
Object.
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
);
|
|
532
|
+
const filteredDynamicActions = actionType
|
|
533
|
+
? Object.fromEntries(
|
|
534
|
+
Object.entries(dynamicUserActions).filter(
|
|
535
|
+
([_, event]) => event.userActionType === actionType
|
|
536
|
+
)
|
|
537
|
+
)
|
|
538
|
+
: dynamicUserActions;
|
|
539
|
+
return { ...userActions, ...filteredDynamicActions };
|
|
582
540
|
}
|
|
583
541
|
|
|
584
542
|
async getActionOptions(actionId, data) {
|
|
@@ -860,8 +818,7 @@ class IntegrationBase {
|
|
|
860
818
|
|
|
861
819
|
async initialize() {
|
|
862
820
|
try {
|
|
863
|
-
const additionalUserActions =
|
|
864
|
-
await this._loadDynamicUserActionEvents();
|
|
821
|
+
const additionalUserActions = await this.loadDynamicUserActions();
|
|
865
822
|
this.events = { ...this.events, ...additionalUserActions };
|
|
866
823
|
} catch (e) {
|
|
867
824
|
this.addError(e);
|
|
@@ -42,9 +42,6 @@ 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');
|
|
48
45
|
const {
|
|
49
46
|
GetEntityOptionsById,
|
|
50
47
|
} = require('../modules/use-cases/get-entity-options-by-id');
|
|
@@ -201,13 +198,6 @@ function createIntegrationRouter() {
|
|
|
201
198
|
getModulesDefinitionFromIntegrationClasses(integrationClasses),
|
|
202
199
|
});
|
|
203
200
|
|
|
204
|
-
const createEntityFromCredential = new CreateEntityFromCredential({
|
|
205
|
-
processAuthorizationCallback,
|
|
206
|
-
credentialRepository,
|
|
207
|
-
moduleDefinitions:
|
|
208
|
-
getModulesDefinitionFromIntegrationClasses(integrationClasses),
|
|
209
|
-
});
|
|
210
|
-
|
|
211
201
|
const router = express();
|
|
212
202
|
|
|
213
203
|
setIntegrationRoutes(router, authenticateUser, {
|
|
@@ -228,7 +218,6 @@ function createIntegrationRouter() {
|
|
|
228
218
|
getEntityOptionsById,
|
|
229
219
|
refreshEntityOptions,
|
|
230
220
|
processAuthorizationCallback,
|
|
231
|
-
createEntityFromCredential,
|
|
232
221
|
});
|
|
233
222
|
return router;
|
|
234
223
|
}
|
|
@@ -257,15 +246,6 @@ function checkRequiredParams(params, requiredKeys) {
|
|
|
257
246
|
return returnDict;
|
|
258
247
|
}
|
|
259
248
|
|
|
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
|
-
|
|
269
249
|
/**
|
|
270
250
|
* Sets up integration-related routes on the provided Express router
|
|
271
251
|
* @param {express.Router} router - Express router instance to add routes to
|
|
@@ -402,7 +382,6 @@ function setIntegrationRoutes(router, authenticateUser, useCases) {
|
|
|
402
382
|
params.integrationId,
|
|
403
383
|
user.getId()
|
|
404
384
|
);
|
|
405
|
-
assertUserAction(integration, params.actionId);
|
|
406
385
|
|
|
407
386
|
res.json(
|
|
408
387
|
await integration.send('GET_USER_ACTION_OPTIONS', {
|
|
@@ -428,7 +407,6 @@ function setIntegrationRoutes(router, authenticateUser, useCases) {
|
|
|
428
407
|
params.integrationId,
|
|
429
408
|
user.getId()
|
|
430
409
|
);
|
|
431
|
-
assertUserAction(integration, params.actionId);
|
|
432
410
|
|
|
433
411
|
res.json(
|
|
434
412
|
await integration.send('REFRESH_USER_ACTION_OPTIONS', {
|
|
@@ -450,7 +428,6 @@ function setIntegrationRoutes(router, authenticateUser, useCases) {
|
|
|
450
428
|
params.integrationId,
|
|
451
429
|
user.getId()
|
|
452
430
|
);
|
|
453
|
-
assertUserAction(integration, params.actionId);
|
|
454
431
|
res.json(await integration.send(params.actionId, req.body));
|
|
455
432
|
})
|
|
456
433
|
);
|
|
@@ -525,7 +502,6 @@ function setEntityRoutes(router, authenticateUser, useCases) {
|
|
|
525
502
|
getEntityOptionsById,
|
|
526
503
|
refreshEntityOptions,
|
|
527
504
|
processAuthorizationCallback,
|
|
528
|
-
createEntityFromCredential,
|
|
529
505
|
} = useCases;
|
|
530
506
|
|
|
531
507
|
router.route('/api/authorize').get(
|
|
@@ -590,19 +566,35 @@ function setEntityRoutes(router, authenticateUser, useCases) {
|
|
|
590
566
|
router.route('/api/entity').post(
|
|
591
567
|
catchAsyncError(async (req, res) => {
|
|
592
568
|
const user = await authenticateUser.execute(req);
|
|
569
|
+
const userId = user.getId();
|
|
593
570
|
const params = checkRequiredParams(req.body, [
|
|
594
571
|
'entityType',
|
|
595
572
|
'data',
|
|
596
573
|
]);
|
|
597
574
|
checkRequiredParams(req.body.data, ['credential_id']);
|
|
598
575
|
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
credentialId: params.data.credential_id,
|
|
604
|
-
})
|
|
576
|
+
// May want to pass along the user ID as well so credential ID's can't be fished???
|
|
577
|
+
const credential = await getCredentialForUser.execute(
|
|
578
|
+
params.data.credential_id,
|
|
579
|
+
userId
|
|
605
580
|
);
|
|
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));
|
|
606
598
|
})
|
|
607
599
|
);
|
|
608
600
|
|