@friggframework/core 2.0.0--canary.686.7f3bc1a.0 → 2.0.0--canary.680.6bacd26.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.
Files changed (156) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/CLAUDE.md +0 -28
  3. package/README.md +0 -105
  4. package/application/commands/integration-commands.js +2 -2
  5. package/application/commands/scheduler-commands.js +7 -11
  6. package/application/commands/user-commands.js +5 -17
  7. package/core/Worker.js +7 -31
  8. package/core/create-handler.js +0 -9
  9. package/credential/use-cases/credential-operations-for-user.js +25 -110
  10. package/credential/use-cases/reauthorize-credential-for-user.js +8 -15
  11. package/database/config.js +24 -48
  12. package/database/documentdb-utils.js +1 -6
  13. package/database/encryption/README.md +2 -0
  14. package/database/encryption/encryption-config.js +31 -10
  15. package/database/encryption/encryption-schema-registry.js +47 -99
  16. package/database/encryption/field-encryption-service.js +69 -5
  17. package/database/encryption/test-support/fake-ciphertext.js +15 -0
  18. package/database/prisma.js +2 -4
  19. package/generated/prisma-mongodb/edge.js +4 -27
  20. package/generated/prisma-mongodb/index-browser.js +1 -24
  21. package/generated/prisma-mongodb/index.d.ts +48 -3228
  22. package/generated/prisma-mongodb/index.js +4 -27
  23. package/generated/prisma-mongodb/package.json +1 -1
  24. package/generated/prisma-mongodb/schema.prisma +0 -65
  25. package/generated/prisma-mongodb/wasm.js +4 -27
  26. package/generated/prisma-postgresql/edge.js +4 -27
  27. package/generated/prisma-postgresql/index-browser.js +1 -24
  28. package/generated/prisma-postgresql/index.d.ts +51 -3503
  29. package/generated/prisma-postgresql/index.js +4 -27
  30. package/generated/prisma-postgresql/package.json +1 -1
  31. package/generated/prisma-postgresql/schema.prisma +0 -61
  32. package/generated/prisma-postgresql/wasm.js +4 -27
  33. package/handlers/app-definition-loader.js +12 -103
  34. package/handlers/routers/auth.js +12 -40
  35. package/handlers/routers/health.js +2 -4
  36. package/handlers/routers/integration-defined-routers.js +92 -144
  37. package/handlers/routers/integration-webhook-routers.js +64 -102
  38. package/index.js +1 -63
  39. package/infrastructure/scheduler/index.js +6 -19
  40. package/infrastructure/scheduler/scheduler-service-factory.js +7 -55
  41. package/integrations/index.js +0 -5
  42. package/integrations/integration-router.js +73 -115
  43. package/integrations/repositories/integration-repository-documentdb.js +3 -35
  44. package/integrations/repositories/integration-repository-interface.js +1 -17
  45. package/integrations/repositories/integration-repository-mongo.js +76 -59
  46. package/integrations/repositories/integration-repository-postgres.js +76 -62
  47. package/integrations/tests/doubles/test-integration-repository.js +1 -12
  48. package/integrations/use-cases/create-integration.js +20 -55
  49. package/integrations/use-cases/get-integrations-for-user.js +40 -80
  50. package/integrations/use-cases/index.js +1 -7
  51. package/integrations/use-cases/integration-operations-for-user.js +24 -55
  52. package/integrations/utils/map-integration-dto.js +1 -44
  53. package/management-api/management-api-config.js +2 -71
  54. package/management-api/meta-router.js +2 -21
  55. package/management-api/openapi/components.js +0 -40
  56. package/management-api/openapi/v2-operations.js +4 -16
  57. package/management-api/route-registry.js +6 -123
  58. package/management-api/v2/dependencies.js +15 -40
  59. package/management-api/v2/dto.js +0 -20
  60. package/management-api/v2/handlers/authorization.js +0 -1
  61. package/management-api/v2/handlers/credentials.js +2 -6
  62. package/management-api/v2/handlers/entities.js +7 -10
  63. package/management-api/v2/handlers/integrations.js +3 -6
  64. package/management-api/v2/request.js +1 -32
  65. package/modules/index.js +0 -8
  66. package/modules/module-factory.js +0 -12
  67. package/modules/module.js +2 -53
  68. package/modules/repositories/module-repository-documentdb.js +6 -51
  69. package/modules/repositories/module-repository-interface.js +2 -19
  70. package/modules/repositories/module-repository-mongo.js +74 -67
  71. package/modules/repositories/module-repository-postgres.js +74 -66
  72. package/modules/repositories/module-repository.js +1 -2
  73. package/modules/use-cases/entity-operations-for-user.js +13 -50
  74. package/modules/use-cases/entity-types.js +7 -31
  75. package/modules/use-cases/execute-entity-proxy-request.js +3 -50
  76. package/modules/use-cases/get-authorization-requirements.js +2 -2
  77. package/modules/use-cases/get-entities-for-user.js +13 -26
  78. package/modules/use-cases/get-entity-module-for-user.js +7 -34
  79. package/modules/use-cases/get-entity-options-by-id.js +4 -10
  80. package/modules/use-cases/get-entity-options-by-type.js +1 -1
  81. package/modules/use-cases/get-module-instance-from-type.js +1 -1
  82. package/modules/use-cases/get-module.js +4 -10
  83. package/modules/use-cases/multi-step-authorization.js +13 -40
  84. package/modules/use-cases/process-authorization-callback.js +19 -53
  85. package/modules/use-cases/refresh-entity-options.js +4 -10
  86. package/modules/use-cases/test-module-auth.js +4 -10
  87. package/package.json +5 -6
  88. package/prisma-mongodb/schema.prisma +0 -65
  89. package/prisma-postgresql/schema.prisma +0 -61
  90. package/queues/index.js +0 -25
  91. package/types/index.d.ts +0 -1
  92. package/types/modules/index.d.ts +0 -139
  93. package/user/repositories/user-repository-documentdb.js +2 -27
  94. package/user/repositories/user-repository-interface.js +0 -18
  95. package/user/repositories/user-repository-mongo.js +0 -24
  96. package/user/repositories/user-repository-postgres.js +0 -18
  97. package/user/use-cases/authenticate-user.js +1 -7
  98. package/user/use-cases/get-user-from-adopter-jwt.js +124 -95
  99. package/user/use-cases/get-user-from-x-frigg-headers.js +80 -83
  100. package/user/user.js +1 -64
  101. package/database/organization-where.js +0 -18
  102. package/database/unique-violation.js +0 -25
  103. package/extensions/bootstrap-runner.js +0 -43
  104. package/extensions/extension-loader.js +0 -187
  105. package/extensions/index.js +0 -41
  106. package/extensions/initialize-app.js +0 -123
  107. package/extensions/route-mounter.js +0 -103
  108. package/extensions/schema-composer.js +0 -188
  109. package/infrastructure/scheduler/netlify-scheduler-adapter.js +0 -216
  110. package/infrastructure/scheduler/scheduled-job-repository.js +0 -118
  111. package/integrations/repositories/integration-not-found.js +0 -14
  112. package/integrations/schedule-config.js +0 -80
  113. package/integrations/use-cases/dispatch-ongoing-syncs.js +0 -100
  114. package/integrations/use-cases/resolve-integration-ownership.js +0 -177
  115. package/modules/entity-scope.js +0 -15
  116. package/modules/repositories/entity-not-found.js +0 -18
  117. package/modules/scope-config.js +0 -192
  118. package/modules/scope-policy.js +0 -112
  119. package/modules/scope-resolution.js +0 -288
  120. package/modules/scope-visibility.js +0 -247
  121. package/modules/tests/doubles/ownership-matching.js +0 -18
  122. package/modules/use-cases/authorize-entity-for-user.js +0 -61
  123. package/modules/use-cases/create-entity-from-credential.js +0 -113
  124. package/modules/use-cases/manage-access.js +0 -21
  125. package/prisma-postgresql/migrations/20261015000000_add_organization_membership/migration.sql +0 -26
  126. package/prisma-postgresql/migrations/20261016000000_add_entity_integration_organization/migration.sql +0 -25
  127. package/prisma-postgresql/migrations/20261017000000_add_scheduled_job/migration.sql +0 -28
  128. package/providers/index.js +0 -23
  129. package/providers/resolve-provider.js +0 -93
  130. package/providers/runtime-detection.js +0 -124
  131. package/queues/providers/index.js +0 -11
  132. package/queues/providers/netlify-background-provider.js +0 -150
  133. package/queues/providers/qstash-queue-provider.js +0 -219
  134. package/queues/providers/sqs-queue-provider.js +0 -70
  135. package/queues/queue-client-interface.js +0 -55
  136. package/queues/queue-message-auth.js +0 -193
  137. package/queues/queue-provider-factory.js +0 -101
  138. package/queues/queue-provider.js +0 -65
  139. package/queues/sqs-queue-client.js +0 -81
  140. package/types/user/index.d.ts +0 -134
  141. package/user/adopter-jwt-config.js +0 -177
  142. package/user/adopter-jwt-errors.js +0 -59
  143. package/user/adopter-token-verifier.js +0 -122
  144. package/user/app-user-helpers.js +0 -97
  145. package/user/create-user-authentication.js +0 -64
  146. package/user/membership.js +0 -51
  147. package/user/repositories/organization-membership-record.js +0 -19
  148. package/user/repositories/organization-membership-repository-documentdb.js +0 -106
  149. package/user/repositories/organization-membership-repository-factory.js +0 -42
  150. package/user/repositories/organization-membership-repository-interface.js +0 -57
  151. package/user/repositories/organization-membership-repository-mongo.js +0 -13
  152. package/user/repositories/organization-membership-repository-postgres.js +0 -29
  153. package/user/repositories/organization-membership-repository-prisma.js +0 -81
  154. package/user/tests/doubles/adopter-jwt-fixtures.js +0 -220
  155. package/user/use-cases/ensure-organization-membership.js +0 -92
  156. package/user/use-cases/find-individual-users-by-organization.js +0 -54
@@ -1,188 +0,0 @@
1
- /**
2
- * Schema Composer
3
- *
4
- * Merges extension .prisma schema fragments with a base Prisma schema.
5
- * Extensions can add new models/enums that get composed into the final schema
6
- * used for `prisma generate` and migrations.
7
- *
8
- * Two approaches are supported:
9
- * 1. Build-time merge: Concatenate model definitions from extension files
10
- * into the base schema and write a merged output file.
11
- * 2. Multi-file schema (Prisma 5.15+): Return a list of schema paths for
12
- * Prisma's native `prismaSchemaFolder` feature.
13
- *
14
- * @example
15
- * const { composeSchemas } = require('@friggframework/core/extensions/schema-composer');
16
- *
17
- * // Build-time merge — writes a merged schema file
18
- * await composeSchemas({
19
- * baseSchemaPath: '/path/to/prisma-postgresql/schema.prisma',
20
- * extensionSchemaPaths: ['/path/to/extensions/db-credentials/schema.prisma'],
21
- * outputPath: '/path/to/prisma-postgresql/schema.composed.prisma',
22
- * });
23
- */
24
-
25
- const fs = require('fs');
26
- const path = require('path');
27
-
28
- /**
29
- * Extracts model/enum blocks from a .prisma file, stripping out
30
- * generator and datasource blocks (which should only appear in the base schema).
31
- *
32
- * @param {string} schemaContent - Raw .prisma file content
33
- * @returns {string} Only model/enum/type definitions
34
- */
35
- function extractModelBlocks(schemaContent) {
36
- const lines = schemaContent.split('\n');
37
- const result = [];
38
- let depth = 0;
39
- let inBlock = false;
40
- let blockType = null;
41
-
42
- for (const line of lines) {
43
- const trimmed = line.trim();
44
-
45
- // Detect block start
46
- if (depth === 0 && !inBlock) {
47
- const blockMatch = trimmed.match(
48
- /^(model|enum|type)\s+\w+\s*\{/
49
- );
50
- if (blockMatch) {
51
- inBlock = true;
52
- blockType = blockMatch[1];
53
- result.push(line);
54
- depth += (line.match(/\{/g) || []).length;
55
- depth -= (line.match(/\}/g) || []).length;
56
- continue;
57
- }
58
-
59
- // Skip generator/datasource blocks
60
- const skipMatch = trimmed.match(
61
- /^(generator|datasource)\s+\w+\s*\{/
62
- );
63
- if (skipMatch) {
64
- inBlock = true;
65
- blockType = 'skip';
66
- depth += (line.match(/\{/g) || []).length;
67
- depth -= (line.match(/\}/g) || []).length;
68
- continue;
69
- }
70
-
71
- // Keep standalone comments between blocks
72
- if (trimmed.startsWith('//') || trimmed === '') {
73
- // Only keep if we've already accumulated some model blocks
74
- if (result.length > 0) {
75
- result.push(line);
76
- }
77
- continue;
78
- }
79
- } else if (inBlock) {
80
- depth += (line.match(/\{/g) || []).length;
81
- depth -= (line.match(/\}/g) || []).length;
82
-
83
- if (blockType !== 'skip') {
84
- result.push(line);
85
- }
86
-
87
- if (depth <= 0) {
88
- inBlock = false;
89
- blockType = null;
90
- depth = 0;
91
- if (result.length > 0) {
92
- result.push(''); // blank line between blocks
93
- }
94
- }
95
- }
96
- }
97
-
98
- return result.join('\n').trim();
99
- }
100
-
101
- /**
102
- * Composes a merged Prisma schema from a base schema + extension fragments.
103
- *
104
- * @param {Object} options
105
- * @param {string} options.baseSchemaPath - Absolute path to the core .prisma file
106
- * @param {string[]} options.extensionSchemaPaths - Absolute paths to extension .prisma files
107
- * @param {string} [options.outputPath] - Where to write the merged schema.
108
- * Defaults to `<baseDir>/schema.composed.prisma`
109
- * @returns {string} The merged schema content
110
- */
111
- function composeSchemas({ baseSchemaPath, extensionSchemaPaths, outputPath }) {
112
- if (!baseSchemaPath) {
113
- throw new Error('baseSchemaPath is required');
114
- }
115
-
116
- if (
117
- !extensionSchemaPaths ||
118
- !Array.isArray(extensionSchemaPaths) ||
119
- extensionSchemaPaths.length === 0
120
- ) {
121
- // No extensions — just return base schema as-is
122
- const baseContent = fs.readFileSync(baseSchemaPath, 'utf-8');
123
- return baseContent;
124
- }
125
-
126
- const baseContent = fs.readFileSync(baseSchemaPath, 'utf-8');
127
-
128
- // Collect model blocks from each extension
129
- const extensionBlocks = [];
130
- for (const extPath of extensionSchemaPaths) {
131
- if (!fs.existsSync(extPath)) {
132
- throw new Error(
133
- `Extension schema not found: ${extPath}`
134
- );
135
- }
136
- const extContent = fs.readFileSync(extPath, 'utf-8');
137
- const models = extractModelBlocks(extContent);
138
- if (models) {
139
- extensionBlocks.push(
140
- `// --- Extension schema from: ${path.basename(path.dirname(extPath))}/${path.basename(extPath)} ---`,
141
- models
142
- );
143
- }
144
- }
145
-
146
- if (extensionBlocks.length === 0) {
147
- return baseContent;
148
- }
149
-
150
- // Append extension models to the base schema
151
- const merged = [
152
- baseContent.trimEnd(),
153
- '',
154
- '// =========================================================================',
155
- '// Extension Models (auto-composed — do not edit manually)',
156
- '// =========================================================================',
157
- '',
158
- ...extensionBlocks,
159
- '',
160
- ].join('\n');
161
-
162
- // Write the merged schema if outputPath is specified
163
- const resolvedOutput =
164
- outputPath ||
165
- path.join(path.dirname(baseSchemaPath), 'schema.composed.prisma');
166
-
167
- fs.writeFileSync(resolvedOutput, merged, 'utf-8');
168
-
169
- return merged;
170
- }
171
-
172
- /**
173
- * Returns schema paths suitable for Prisma's native multi-file schema support
174
- * (prismaSchemaFolder feature, Prisma 5.15+).
175
- *
176
- * @param {string} baseSchemaPath - Path to the core schema
177
- * @param {string[]} extensionSchemaPaths - Paths to extension schemas
178
- * @returns {string[]} All schema file paths
179
- */
180
- function getSchemaFilePaths(baseSchemaPath, extensionSchemaPaths) {
181
- return [baseSchemaPath, ...(extensionSchemaPaths || [])];
182
- }
183
-
184
- module.exports = {
185
- composeSchemas,
186
- extractModelBlocks,
187
- getSchemaFilePaths,
188
- };
@@ -1,216 +0,0 @@
1
- /**
2
- * Netlify Scheduler Adapter
3
- *
4
- * Implements SchedulerServiceInterface for Netlify deployments.
5
- *
6
- * Netlify Scheduled Functions use cron syntax but are defined statically in
7
- * netlify.toml or via the @netlify/functions schedule() helper. They cannot
8
- * be created dynamically at runtime like EventBridge Scheduler.
9
- *
10
- * Strategy for one-time scheduled jobs on Netlify:
11
- * 1. Store the schedule in the database (same as mock adapter pattern)
12
- * 2. A Netlify Scheduled Function runs on a cron interval (e.g., every 5 min)
13
- * 3. The cron function queries for due schedules and dispatches them
14
- * to a background function for execution
15
- *
16
- * This is a "poll-and-dispatch" pattern vs EventBridge's "push" pattern.
17
- * Trade-off: slightly less precise timing (up to cron interval delay),
18
- * but works on any platform without cloud-specific scheduling APIs.
19
- *
20
- * For integrations that need the queue provider to dispatch jobs:
21
- * - queueResourceId maps to the background function URL path
22
- * - Payload is stored and forwarded when the cron fires
23
- */
24
-
25
- const { SchedulerServiceInterface } = require('./scheduler-service-interface');
26
-
27
- // The one queue worker every Netlify deployment has (provider-netlify's
28
- // worker-background function); it dispatches by integrationName.
29
- const DEFAULT_WORKER_PATH = '/.netlify/functions/worker-background';
30
- const DEFAULT_LEASE_MS = 5 * 60 * 1000;
31
-
32
- class NetlifySchedulerAdapter extends SchedulerServiceInterface {
33
- /**
34
- * @param {Object} options
35
- * @param {Object} options.repository - Repository for persisting schedules
36
- * Must implement: save(schedule), delete(scheduleName),
37
- * findByName(scheduleName), findDue(now)
38
- * @param {Object} [options.queueProvider] - Queue provider for dispatching due jobs
39
- * @param {number} [options.leaseMs] - how long a claimed (PROCESSING) job
40
- * is held before another tick may take it again (default 5 minutes,
41
- * well past a Netlify scheduled function's 60-second limit)
42
- */
43
- constructor(options = {}) {
44
- super();
45
- this.repository = options.repository;
46
- this.queueProvider = options.queueProvider;
47
- this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS;
48
-
49
- if (!this.repository) {
50
- console.warn(
51
- '[NetlifyScheduler] No repository provided. ' +
52
- 'Schedules will be stored in memory (lost on function restart). ' +
53
- 'Provide a database-backed repository for production use.'
54
- );
55
- this._inMemorySchedules = new Map();
56
- }
57
- }
58
-
59
- /**
60
- * Where a due job is sent. Netlify has no per-integration queues, so an
61
- * SQS-style queue URL (often unset here) maps to the worker function;
62
- * a function path is kept as given.
63
- *
64
- * @param {string} [queueUrl]
65
- * @returns {string} a path NetlifyBackgroundProvider.send() accepts
66
- */
67
- toQueueResourceId(queueUrl) {
68
- return typeof queueUrl === 'string' && queueUrl.startsWith('/')
69
- ? queueUrl
70
- : DEFAULT_WORKER_PATH;
71
- }
72
-
73
- async scheduleOneTime({
74
- scheduleName,
75
- scheduleAt,
76
- queueResourceId,
77
- payload,
78
- }) {
79
- if (!scheduleName) throw new Error('scheduleName is required');
80
- if (!scheduleAt || !(scheduleAt instanceof Date))
81
- throw new Error('scheduleAt must be a valid Date object');
82
- if (!queueResourceId) throw new Error('queueResourceId is required');
83
-
84
- const scheduleData = {
85
- scheduleName,
86
- scheduledAt: scheduleAt.toISOString(),
87
- queueResourceId,
88
- payload,
89
- createdAt: new Date().toISOString(),
90
- state: 'PENDING',
91
- };
92
-
93
- if (this.repository) {
94
- await this.repository.save(scheduleData);
95
- } else {
96
- this._inMemorySchedules.set(scheduleName, scheduleData);
97
- }
98
-
99
- console.log(
100
- `[NetlifyScheduler] Scheduled: ${scheduleName} for ${scheduleAt.toISOString()}`
101
- );
102
-
103
- return {
104
- scheduledJobId: `netlify-schedule-${scheduleName}`,
105
- scheduledAt: scheduleAt.toISOString(),
106
- };
107
- }
108
-
109
- async deleteSchedule(scheduleName) {
110
- if (!scheduleName) throw new Error('scheduleName is required');
111
-
112
- if (this.repository) {
113
- await this.repository.delete(scheduleName);
114
- } else {
115
- this._inMemorySchedules.delete(scheduleName);
116
- }
117
-
118
- console.log(`[NetlifyScheduler] Deleted schedule: ${scheduleName}`);
119
- }
120
-
121
- async getScheduleStatus(scheduleName) {
122
- if (!scheduleName) throw new Error('scheduleName is required');
123
-
124
- let schedule;
125
- if (this.repository) {
126
- schedule = await this.repository.findByName(scheduleName);
127
- } else {
128
- schedule = this._inMemorySchedules.get(scheduleName);
129
- }
130
-
131
- if (!schedule) {
132
- return { exists: false };
133
- }
134
-
135
- return {
136
- exists: true,
137
- scheduledAt: schedule.scheduledAt,
138
- state: schedule.state,
139
- };
140
- }
141
-
142
- /**
143
- * Process due schedules. Called by the Netlify cron function.
144
- *
145
- * Finds all schedules where scheduledAt <= now, dispatches them
146
- * to the queue provider, and marks them as completed.
147
- *
148
- * @returns {Promise<{ processed: number, errors: number }>}
149
- */
150
- async processDueSchedules() {
151
- if (!this.repository) {
152
- console.warn(
153
- '[NetlifyScheduler] Cannot process due schedules without a repository'
154
- );
155
- return { processed: 0, errors: 0, skipped: 0 };
156
- }
157
-
158
- const now = new Date();
159
- const lease = { leaseMs: this.leaseMs };
160
- const dueSchedules = await this.repository.findDue(now, lease);
161
-
162
- let processed = 0;
163
- let errors = 0;
164
- let skipped = 0;
165
-
166
- for (const schedule of dueSchedules) {
167
- try {
168
- // Claim before dispatch. Two overlapping ticks can both see
169
- // the row in findDue; only the one whose conditional update
170
- // wins sends it. A repository without claim() (a custom one)
171
- // keeps the old unconditional PROCESSING write.
172
- const claimed =
173
- typeof this.repository.claim === 'function'
174
- ? await this.repository.claim(schedule.scheduleName, now, lease)
175
- : (await this.repository.save({ ...schedule, state: 'PROCESSING' }), true);
176
- if (!claimed) {
177
- skipped++;
178
- continue;
179
- }
180
-
181
- if (this.queueProvider) {
182
- await this.queueProvider.send(
183
- schedule.payload,
184
- schedule.queueResourceId
185
- );
186
- } else {
187
- console.log(
188
- `[NetlifyScheduler] No queue provider — logging payload for: ${schedule.scheduleName}`,
189
- JSON.stringify(schedule.payload)
190
- );
191
- }
192
-
193
- await this.repository.delete(schedule.scheduleName);
194
- processed++;
195
- } catch (error) {
196
- console.error(
197
- `[NetlifyScheduler] Error processing schedule ${schedule.scheduleName}:`,
198
- error
199
- );
200
- // Mark as FAILED so it won't be re-dispatched automatically.
201
- // Operators can inspect FAILED schedules and retry manually.
202
- await this.repository
203
- .save({ ...schedule, state: 'FAILED' })
204
- .catch(() => {});
205
- errors++;
206
- }
207
- }
208
-
209
- console.log(
210
- `[NetlifyScheduler] Processed ${processed} due schedules, ${errors} errors, ${skipped} claimed elsewhere`
211
- );
212
- return { processed, errors, skipped };
213
- }
214
- }
215
-
216
- module.exports = { NetlifySchedulerAdapter, DEFAULT_WORKER_PATH, DEFAULT_LEASE_MS };
@@ -1,118 +0,0 @@
1
- /**
2
- * Scheduled Job Repository
3
- *
4
- * Prisma-based implementation of the repository interface required by
5
- * NetlifySchedulerAdapter. Persists one-time scheduled jobs to the
6
- * ScheduledJob model so they survive function restarts.
7
- *
8
- * Repository interface:
9
- * save(scheduleData) — Upsert a scheduled job
10
- * delete(scheduleName) — Remove a scheduled job
11
- * findByName(scheduleName) — Find a single scheduled job
12
- * findDue(now, { leaseMs }) — Find due jobs: PENDING, or PROCESSING with an
13
- * expired lease (a dispatcher that died after
14
- * claiming), where scheduledAt <= now
15
- * claim(scheduleName, now, { leaseMs })
16
- * — Atomically move one due job to PROCESSING;
17
- * true only for the one caller that won it
18
- *
19
- * The lease clock is the row's updatedAt: a claim writes it, so a PROCESSING
20
- * row whose updatedAt is older than now - leaseMs is claimable again.
21
- */
22
-
23
- const DEFAULT_LEASE_MS = 5 * 60 * 1000;
24
-
25
- // Rows a dispatcher may take: never claimed, or claimed by one that has not
26
- // finished within the lease.
27
- function claimableWhere(now, leaseMs = DEFAULT_LEASE_MS) {
28
- return {
29
- OR: [
30
- { state: 'PENDING' },
31
- {
32
- state: 'PROCESSING',
33
- updatedAt: { lt: new Date(now.getTime() - leaseMs) },
34
- },
35
- ],
36
- };
37
- }
38
-
39
- class ScheduledJobRepository {
40
- /**
41
- * @param {Object} options
42
- * @param {import('@prisma/client').PrismaClient} options.prismaClient
43
- */
44
- constructor({ prismaClient }) {
45
- if (!prismaClient) {
46
- throw new Error(
47
- 'ScheduledJobRepository requires a prismaClient instance'
48
- );
49
- }
50
- this.prisma = prismaClient;
51
- }
52
-
53
- async save(scheduleData) {
54
- return this.prisma.scheduledJob.upsert({
55
- where: { scheduleName: scheduleData.scheduleName },
56
- update: {
57
- scheduledAt: new Date(scheduleData.scheduledAt),
58
- queueResourceId: scheduleData.queueResourceId,
59
- payload: scheduleData.payload ?? undefined,
60
- state: scheduleData.state || 'PENDING',
61
- },
62
- create: {
63
- scheduleName: scheduleData.scheduleName,
64
- scheduledAt: new Date(scheduleData.scheduledAt),
65
- queueResourceId: scheduleData.queueResourceId,
66
- payload: scheduleData.payload ?? undefined,
67
- state: scheduleData.state || 'PENDING',
68
- },
69
- });
70
- }
71
-
72
- async delete(scheduleName) {
73
- try {
74
- await this.prisma.scheduledJob.delete({
75
- where: { scheduleName },
76
- });
77
- } catch (error) {
78
- // P2025 = record not found — safe to ignore on delete
79
- if (error.code !== 'P2025') {
80
- throw error;
81
- }
82
- }
83
- }
84
-
85
- async findByName(scheduleName) {
86
- return this.prisma.scheduledJob.findUnique({
87
- where: { scheduleName },
88
- });
89
- }
90
-
91
- async findDue(now, { leaseMs = DEFAULT_LEASE_MS } = {}) {
92
- return this.prisma.scheduledJob.findMany({
93
- where: {
94
- scheduledAt: { lte: now },
95
- ...claimableWhere(now, leaseMs),
96
- },
97
- orderBy: { scheduledAt: 'asc' },
98
- });
99
- }
100
-
101
- /**
102
- * Conditional update: only a row that is still claimable moves to
103
- * PROCESSING, so of two overlapping ticks exactly one gets count === 1.
104
- * (PostgreSQL re-checks the WHERE on the row it locked; MongoDB updates
105
- * each document atomically.)
106
- *
107
- * @returns {Promise<boolean>} true when this caller claimed the job
108
- */
109
- async claim(scheduleName, now, { leaseMs = DEFAULT_LEASE_MS } = {}) {
110
- const { count } = await this.prisma.scheduledJob.updateMany({
111
- where: { scheduleName, ...claimableWhere(now, leaseMs) },
112
- data: { state: 'PROCESSING', updatedAt: now },
113
- });
114
- return count === 1;
115
- }
116
- }
117
-
118
- module.exports = { ScheduledJobRepository, DEFAULT_LEASE_MS };
@@ -1,14 +0,0 @@
1
- /**
2
- * The error `findIntegrationById` throws for an id with no row, and the one
3
- * predicate that recognises it. The adapters build the error here and the
4
- * use cases match it here, so the message is written once and a missing
5
- * integration can be told from any other failure without widening a regex.
6
- */
7
- const MESSAGE = /^Integration with id .+ not found$/;
8
-
9
- const integrationNotFoundError = (id) =>
10
- new Error(`Integration with id ${id} not found`);
11
-
12
- const isIntegrationNotFound = (error) => MESSAGE.test(error?.message || '');
13
-
14
- module.exports = { integrationNotFoundError, isIntegrationNotFound };
@@ -1,80 +0,0 @@
1
- /**
2
- * An integration's schedule configuration (`static Definition.schedule`),
3
- * read by hosts that tick ONGOING_SYNC from a cron (provider-netlify's
4
- * scheduled-sync function).
5
- *
6
- * schedule: {
7
- * // 'class' (default): one ONGOING_SYNC per integration class per tick,
8
- * // with no integration id: the worker runs it on an unhydrated
9
- * // instance, so the handler finds its own installations.
10
- * // 'installation': one ONGOING_SYNC per ENABLED integration record of
11
- * // the class, carrying `data.integrationId`, so the worker hydrates
12
- * // that installation before the handler runs.
13
- * scope: 'installation',
14
- * // Optional, 'installation' only: (integration, { now }) => boolean |
15
- * // Promise<boolean>. Return false to skip that installation this tick.
16
- * // Without it every installation is dispatched on every tick.
17
- * isDue: (integration, { now }) => true,
18
- * }
19
- *
20
- * Validated at load (loadAppDefinition) so a mistyped scope stops the app
21
- * rather than silently falling back to 'class'.
22
- */
23
-
24
- const SCHEDULE_SCOPES = Object.freeze({
25
- CLASS: 'class',
26
- INSTALLATION: 'installation',
27
- });
28
-
29
- const DEFAULT_SCHEDULE_SCOPE = SCHEDULE_SCOPES.CLASS;
30
-
31
- class ScheduleConfigError extends Error {
32
- constructor(message) {
33
- super(message);
34
- this.name = 'ScheduleConfigError';
35
- this.code = 'SCHEDULE_CONFIG_INVALID';
36
- }
37
- }
38
-
39
- /**
40
- * @param {Object} [definition] - an integration's static Definition
41
- * @returns {{ scope: 'class'|'installation', isDue: Function|null }}
42
- * @throws {ScheduleConfigError} when `schedule` is malformed
43
- */
44
- function resolveScheduleConfig(definition) {
45
- const name = definition?.name || 'integration';
46
- const schedule = definition?.schedule;
47
- if (schedule === undefined || schedule === null) {
48
- return { scope: DEFAULT_SCHEDULE_SCOPE, isDue: null };
49
- }
50
- if (typeof schedule !== 'object' || Array.isArray(schedule)) {
51
- throw new ScheduleConfigError(`${name}: Definition.schedule must be an object`);
52
- }
53
-
54
- const scopes = Object.values(SCHEDULE_SCOPES);
55
- const scope = schedule.scope === undefined ? DEFAULT_SCHEDULE_SCOPE : schedule.scope;
56
- if (!scopes.includes(scope)) {
57
- throw new ScheduleConfigError(
58
- `${name}: Definition.schedule.scope must be one of ${scopes.map((s) => `'${s}'`).join(', ')} (got ${JSON.stringify(schedule.scope)})`
59
- );
60
- }
61
-
62
- const isDue = schedule.isDue === undefined ? null : schedule.isDue;
63
- if (isDue !== null && typeof isDue !== 'function') {
64
- throw new ScheduleConfigError(`${name}: Definition.schedule.isDue must be a function`);
65
- }
66
- if (isDue && scope !== SCHEDULE_SCOPES.INSTALLATION) {
67
- throw new ScheduleConfigError(
68
- `${name}: Definition.schedule.isDue applies to scope 'installation' only`
69
- );
70
- }
71
-
72
- return { scope, isDue };
73
- }
74
-
75
- module.exports = {
76
- SCHEDULE_SCOPES,
77
- DEFAULT_SCHEDULE_SCOPE,
78
- ScheduleConfigError,
79
- resolveScheduleConfig,
80
- };