@friggframework/core 2.0.0--canary.531.eb2e0bb.0 → 2.0.0--canary.517.f738cdd.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 (42) hide show
  1. package/admin-scripts/index.js +52 -0
  2. package/admin-scripts/repositories/admin-process-repository-documentdb.js +21 -0
  3. package/admin-scripts/repositories/admin-process-repository-factory.js +51 -0
  4. package/admin-scripts/repositories/admin-process-repository-interface.js +150 -0
  5. package/admin-scripts/repositories/admin-process-repository-mongo.js +213 -0
  6. package/admin-scripts/repositories/admin-process-repository-postgres.js +251 -0
  7. package/admin-scripts/repositories/script-schedule-repository-documentdb.js +21 -0
  8. package/admin-scripts/repositories/script-schedule-repository-factory.js +51 -0
  9. package/admin-scripts/repositories/script-schedule-repository-interface.js +108 -0
  10. package/admin-scripts/repositories/script-schedule-repository-mongo.js +179 -0
  11. package/admin-scripts/repositories/script-schedule-repository-postgres.js +210 -0
  12. package/application/commands/admin-script-commands.js +344 -0
  13. package/application/index.js +0 -4
  14. package/database/use-cases/check-database-state-use-case.js +2 -2
  15. package/database/use-cases/trigger-database-migration-use-case.js +1 -1
  16. package/generated/prisma-mongodb/edge.js +47 -4
  17. package/generated/prisma-mongodb/index-browser.js +37 -1
  18. package/generated/prisma-mongodb/index.d.ts +2775 -52
  19. package/generated/prisma-mongodb/index.js +47 -4
  20. package/generated/prisma-mongodb/package.json +1 -1
  21. package/generated/prisma-mongodb/schema.prisma +69 -0
  22. package/generated/prisma-mongodb/wasm.js +47 -4
  23. package/generated/prisma-postgresql/edge.js +46 -4
  24. package/generated/prisma-postgresql/index-browser.js +36 -1
  25. package/generated/prisma-postgresql/index.d.ts +3414 -83
  26. package/generated/prisma-postgresql/index.js +46 -4
  27. package/generated/prisma-postgresql/package.json +1 -1
  28. package/generated/prisma-postgresql/schema.prisma +68 -0
  29. package/generated/prisma-postgresql/wasm.js +46 -4
  30. package/handlers/middleware/admin-auth.js +53 -0
  31. package/handlers/routers/db-migration.handler.js +1 -1
  32. package/handlers/routers/db-migration.js +18 -33
  33. package/index.js +0 -1
  34. package/package.json +5 -5
  35. package/prisma-mongodb/schema.prisma +69 -0
  36. package/prisma-postgresql/schema.prisma +68 -0
  37. package/application/commands/scheduler-commands.js +0 -263
  38. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +0 -185
  39. package/infrastructure/scheduler/index.js +0 -34
  40. package/infrastructure/scheduler/mock-scheduler-adapter.js +0 -143
  41. package/infrastructure/scheduler/scheduler-service-factory.js +0 -73
  42. package/infrastructure/scheduler/scheduler-service-interface.js +0 -47
@@ -1,263 +0,0 @@
1
- /**
2
- * Scheduler Commands
3
- *
4
- * Application Layer - Command pattern for scheduling operations.
5
- *
6
- * Follows hexagonal architecture:
7
- * - Receives SchedulerServiceInterface via dependency injection
8
- * - Contains business logic (validation, logging, error mapping)
9
- * - Protocol-agnostic (doesn't know about HTTP/Lambda)
10
- *
11
- * @example
12
- * const schedulerCommands = createSchedulerCommands({ integrationName: 'zoho' });
13
- * await schedulerCommands.scheduleJob({
14
- * jobId: 'zoho-notif-renewal-abc123',
15
- * scheduledAt: new Date(Date.now() + 6 * 24 * 60 * 60 * 1000), // 6 days
16
- * event: 'REFRESH_WEBHOOK',
17
- * payload: { integrationId: 'abc123' },
18
- * queueUrl: process.env.ZOHO_QUEUE_URL,
19
- * });
20
- */
21
-
22
- const { createSchedulerService } = require('../../infrastructure/scheduler');
23
-
24
- /**
25
- * Derive SQS ARN from SQS URL
26
- *
27
- * SQS URL format: https://sqs.{region}.amazonaws.com/{account-id}/{queue-name}
28
- * SQS ARN format: arn:aws:sqs:{region}:{account-id}:{queue-name}
29
- *
30
- * @param {string} queueUrl - SQS queue URL
31
- * @returns {string} SQS queue ARN
32
- */
33
- function deriveArnFromQueueUrl(queueUrl) {
34
- try {
35
- const url = new URL(queueUrl);
36
- const region = url.hostname.split('.')[1];
37
- const pathParts = url.pathname.split('/').filter(Boolean);
38
- const accountId = pathParts[0];
39
- const queueName = pathParts[1];
40
- return `arn:aws:sqs:${region}:${accountId}:${queueName}`;
41
- } catch (error) {
42
- throw new Error(`Invalid SQS queue URL: ${queueUrl}`);
43
- }
44
- }
45
-
46
- const ERROR_CODE_MAP = {
47
- SCHEDULER_NOT_CONFIGURED: 503,
48
- INVALID_JOB_DATA: 400,
49
- SCHEDULE_NOT_FOUND: 404,
50
- };
51
-
52
- function mapErrorToResponse(error) {
53
- const status = ERROR_CODE_MAP[error?.code] || 500;
54
- return {
55
- error: status,
56
- reason: error?.message,
57
- code: error?.code,
58
- };
59
- }
60
-
61
- /**
62
- * Create scheduler commands for an integration
63
- *
64
- * @param {Object} params
65
- * @param {string} params.integrationName - Name of the integration (used for logging)
66
- * @param {SchedulerServiceInterface} [params.schedulerService] - Optional injected scheduler service
67
- * @returns {Object} Scheduler commands object
68
- */
69
- function createSchedulerCommands({ integrationName, schedulerService }) {
70
- if (!integrationName) {
71
- throw new Error('integrationName is required');
72
- }
73
-
74
- // Support both dependency injection and lazy creation
75
- // DI is preferred for testability, lazy creation for convenience
76
- let _schedulerService = schedulerService || null;
77
-
78
- function getSchedulerService() {
79
- if (!_schedulerService) {
80
- try {
81
- _schedulerService = createSchedulerService();
82
- } catch (error) {
83
- console.warn(
84
- `[${integrationName}] Scheduler service not available: ${error.message}`
85
- );
86
- return null;
87
- }
88
- }
89
- return _schedulerService;
90
- }
91
-
92
- return {
93
- /**
94
- * Schedule a one-time job to be executed at a specific time
95
- *
96
- * @param {Object} params
97
- * @param {string} params.jobId - Unique identifier for the job
98
- * @param {Date} params.scheduledAt - When to execute the job
99
- * @param {string} params.event - Event name to trigger
100
- * @param {Object} params.payload - Additional payload data
101
- * @param {string} params.queueUrl - Target SQS queue URL (ARN is derived internally)
102
- * @returns {Promise<{jobArn: string, scheduledAt: string} | {error: number, reason: string}>}
103
- */
104
- async scheduleJob({ jobId, scheduledAt, event, payload, queueUrl }) {
105
- try {
106
- if (!jobId) {
107
- const error = new Error('jobId is required');
108
- error.code = 'INVALID_JOB_DATA';
109
- throw error;
110
- }
111
-
112
- if (!scheduledAt || !(scheduledAt instanceof Date)) {
113
- const error = new Error('scheduledAt must be a valid Date');
114
- error.code = 'INVALID_JOB_DATA';
115
- throw error;
116
- }
117
-
118
- if (!event) {
119
- const error = new Error('event is required');
120
- error.code = 'INVALID_JOB_DATA';
121
- throw error;
122
- }
123
-
124
- if (!queueUrl) {
125
- const error = new Error('queueUrl is required');
126
- error.code = 'INVALID_JOB_DATA';
127
- throw error;
128
- }
129
-
130
- // Derive ARN from URL (business logic - transformation)
131
- const queueArn = deriveArnFromQueueUrl(queueUrl);
132
-
133
- // Get scheduler service (via DI or factory)
134
- const service = getSchedulerService();
135
- if (!service) {
136
- console.warn(
137
- `[${integrationName}] Scheduler not configured, skipping job schedule`
138
- );
139
- return {
140
- jobId,
141
- jobArn: null,
142
- scheduledAt: null,
143
- warning: 'Scheduler not configured',
144
- };
145
- }
146
-
147
- // Build the SQS message payload (business logic - assembly)
148
- const sqsPayload = {
149
- eventType: event,
150
- integrationName,
151
- data: payload || {},
152
- scheduledAt: scheduledAt.toISOString(),
153
- createdAt: new Date().toISOString(),
154
- };
155
-
156
- // Delegate to service (Port interface)
157
- const result = await service.scheduleOneTime({
158
- scheduleName: jobId,
159
- scheduleAt: scheduledAt,
160
- queueResourceId: queueArn,
161
- payload: sqsPayload,
162
- });
163
-
164
- console.log(
165
- `[${integrationName}] Scheduled job ${jobId} for ${result.scheduledAt}`
166
- );
167
-
168
- return {
169
- jobId,
170
- jobArn: result.scheduledJobId,
171
- scheduledAt: result.scheduledAt,
172
- };
173
- } catch (error) {
174
- console.error(
175
- `[${integrationName}] Failed to schedule job ${jobId}:`,
176
- error.message
177
- );
178
- return mapErrorToResponse(error);
179
- }
180
- },
181
-
182
- /**
183
- * Delete a scheduled job
184
- *
185
- * @param {string} jobId - Job ID to delete
186
- * @returns {Promise<{success: boolean, jobId: string} | {error: number, reason: string}>}
187
- */
188
- async deleteJob(jobId) {
189
- try {
190
- if (!jobId) {
191
- const error = new Error('jobId is required');
192
- error.code = 'INVALID_JOB_DATA';
193
- throw error;
194
- }
195
-
196
- const service = getSchedulerService();
197
- if (!service) {
198
- console.warn(
199
- `[${integrationName}] Scheduler not configured, skipping job deletion`
200
- );
201
- return {
202
- success: true,
203
- jobId,
204
- warning: 'Scheduler not configured',
205
- };
206
- }
207
-
208
- await service.deleteSchedule(jobId);
209
-
210
- console.log(`[${integrationName}] Deleted scheduled job ${jobId}`);
211
-
212
- return {
213
- success: true,
214
- jobId,
215
- };
216
- } catch (error) {
217
- console.error(
218
- `[${integrationName}] Failed to delete job ${jobId}:`,
219
- error.message
220
- );
221
- return mapErrorToResponse(error);
222
- }
223
- },
224
-
225
- /**
226
- * Get the status of a scheduled job
227
- *
228
- * @param {string} jobId - Job ID to check
229
- * @returns {Promise<{exists: boolean, scheduledAt?: string, state?: string} | {error: number, reason: string}>}
230
- */
231
- async getJobStatus(jobId) {
232
- try {
233
- if (!jobId) {
234
- const error = new Error('jobId is required');
235
- error.code = 'INVALID_JOB_DATA';
236
- throw error;
237
- }
238
-
239
- const service = getSchedulerService();
240
- if (!service) {
241
- return {
242
- exists: false,
243
- warning: 'Scheduler not configured',
244
- };
245
- }
246
-
247
- const status = await service.getScheduleStatus(jobId);
248
-
249
- return status;
250
- } catch (error) {
251
- console.error(
252
- `[${integrationName}] Failed to get job status ${jobId}:`,
253
- error.message
254
- );
255
- return mapErrorToResponse(error);
256
- }
257
- },
258
- };
259
- }
260
-
261
- module.exports = {
262
- createSchedulerCommands,
263
- };
@@ -1,185 +0,0 @@
1
- /**
2
- * EventBridge Scheduler Adapter
3
- *
4
- * Infrastructure Layer - Hexagonal Architecture
5
- *
6
- * Responsible for:
7
- * - Creating one-time EventBridge Scheduler schedules
8
- * - Deleting schedules when no longer needed
9
- * - Checking schedule status
10
- *
11
- * This adapter implements SchedulerServiceInterface for AWS EventBridge Scheduler.
12
- */
13
-
14
- const {
15
- SchedulerClient,
16
- CreateScheduleCommand,
17
- DeleteScheduleCommand,
18
- GetScheduleCommand,
19
- ResourceNotFoundException,
20
- } = require('@aws-sdk/client-scheduler');
21
-
22
- const { SchedulerServiceInterface } = require('./scheduler-service-interface');
23
-
24
- const SCHEDULE_GROUP_NAME = 'frigg-integration-schedules';
25
-
26
- class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
27
- constructor({ region } = {}) {
28
- super();
29
- this.client = new SchedulerClient({
30
- region: region || process.env.AWS_REGION || 'us-east-1',
31
- });
32
- this.scheduleGroupName = SCHEDULE_GROUP_NAME;
33
- this.roleArn = process.env.SCHEDULER_ROLE_ARN;
34
- }
35
-
36
- /**
37
- * Create a one-time schedule that sends a message to SQS
38
- *
39
- * @param {Object} params
40
- * @param {string} params.scheduleName - Unique name for the schedule
41
- * @param {Date} params.scheduleAt - When to trigger the schedule
42
- * @param {string} params.queueResourceId - Queue resource identifier (ARN) to send message to
43
- * @param {Object} params.payload - Message payload
44
- * @returns {Promise<{scheduledJobId: string, scheduledAt: string}>}
45
- */
46
- async scheduleOneTime({ scheduleName, scheduleAt, queueResourceId, payload }) {
47
- if (!scheduleName) {
48
- throw new Error('scheduleName is required');
49
- }
50
- if (!scheduleAt || !(scheduleAt instanceof Date)) {
51
- throw new Error('scheduleAt must be a valid Date object');
52
- }
53
- if (!queueResourceId) {
54
- throw new Error('queueResourceId is required');
55
- }
56
- if (!this.roleArn) {
57
- throw new Error(
58
- 'SCHEDULER_ROLE_ARN environment variable is not set'
59
- );
60
- }
61
-
62
- // Format date to AWS schedule expression (at(yyyy-mm-ddThh:mm:ss))
63
- const scheduleExpression = `at(${scheduleAt.toISOString().replace(/\.\d{3}Z$/, '')})`;
64
-
65
- const command = new CreateScheduleCommand({
66
- Name: scheduleName,
67
- GroupName: this.scheduleGroupName,
68
- ScheduleExpression: scheduleExpression,
69
- ScheduleExpressionTimezone: 'UTC',
70
- FlexibleTimeWindow: {
71
- Mode: 'OFF',
72
- },
73
- Target: {
74
- Arn: queueResourceId,
75
- RoleArn: this.roleArn,
76
- Input: JSON.stringify(payload),
77
- },
78
- ActionAfterCompletion: 'DELETE', // Auto-cleanup after execution
79
- });
80
-
81
- try {
82
- const response = await this.client.send(command);
83
- console.log(
84
- `[Scheduler] Created schedule ${scheduleName} for ${scheduleAt.toISOString()}`
85
- );
86
-
87
- return {
88
- scheduledJobId: response.ScheduleArn,
89
- scheduledAt: scheduleAt.toISOString(),
90
- };
91
- } catch (error) {
92
- console.error(
93
- `[Scheduler] Failed to create schedule ${scheduleName}:`,
94
- error.message
95
- );
96
- throw error;
97
- }
98
- }
99
-
100
- /**
101
- * Delete a schedule
102
- *
103
- * @param {string} scheduleName - Name of the schedule to delete
104
- * @returns {Promise<void>}
105
- */
106
- async deleteSchedule(scheduleName) {
107
- if (!scheduleName) {
108
- throw new Error('scheduleName is required');
109
- }
110
-
111
- const command = new DeleteScheduleCommand({
112
- Name: scheduleName,
113
- GroupName: this.scheduleGroupName,
114
- });
115
-
116
- try {
117
- await this.client.send(command);
118
- console.log(`[Scheduler] Deleted schedule ${scheduleName}`);
119
- } catch (error) {
120
- if (error instanceof ResourceNotFoundException) {
121
- console.log(
122
- `[Scheduler] Schedule ${scheduleName} not found (already deleted or executed)`
123
- );
124
- return; // Graceful handling - schedule doesn't exist
125
- }
126
- console.error(
127
- `[Scheduler] Failed to delete schedule ${scheduleName}:`,
128
- error.message
129
- );
130
- throw error;
131
- }
132
- }
133
-
134
- /**
135
- * Get schedule status
136
- *
137
- * @param {string} scheduleName - Name of the schedule
138
- * @returns {Promise<{exists: boolean, scheduledAt?: string, state?: string}>}
139
- */
140
- async getScheduleStatus(scheduleName) {
141
- if (!scheduleName) {
142
- throw new Error('scheduleName is required');
143
- }
144
-
145
- const command = new GetScheduleCommand({
146
- Name: scheduleName,
147
- GroupName: this.scheduleGroupName,
148
- });
149
-
150
- try {
151
- const response = await this.client.send(command);
152
-
153
- // Parse the schedule expression to get the scheduled time
154
- // Format: at(yyyy-mm-ddThh:mm:ss)
155
- let scheduledAt = null;
156
- if (response.ScheduleExpression) {
157
- const match = response.ScheduleExpression.match(
158
- /^at\((.+)\)$/
159
- );
160
- if (match) {
161
- scheduledAt = new Date(match[1] + 'Z').toISOString();
162
- }
163
- }
164
-
165
- return {
166
- exists: true,
167
- scheduledAt,
168
- state: response.State,
169
- };
170
- } catch (error) {
171
- if (error instanceof ResourceNotFoundException) {
172
- return {
173
- exists: false,
174
- };
175
- }
176
- console.error(
177
- `[Scheduler] Failed to get schedule ${scheduleName}:`,
178
- error.message
179
- );
180
- throw error;
181
- }
182
- }
183
- }
184
-
185
- module.exports = { EventBridgeSchedulerAdapter, SCHEDULE_GROUP_NAME };
@@ -1,34 +0,0 @@
1
- /**
2
- * Scheduler Infrastructure
3
- *
4
- * Provides scheduling capabilities for one-time jobs.
5
- * Follows hexagonal architecture with interface + adapters pattern.
6
- *
7
- * Providers:
8
- * - eventbridge: AWS EventBridge Scheduler (production)
9
- * - mock: In-memory mock scheduler (local development)
10
- */
11
-
12
- const { SchedulerServiceInterface } = require('./scheduler-service-interface');
13
- const { EventBridgeSchedulerAdapter, SCHEDULE_GROUP_NAME } = require('./eventbridge-scheduler-adapter');
14
- const { MockSchedulerAdapter } = require('./mock-scheduler-adapter');
15
- const {
16
- createSchedulerService,
17
- SCHEDULER_PROVIDERS,
18
- determineProvider,
19
- } = require('./scheduler-service-factory');
20
-
21
- module.exports = {
22
- // Interface (Port)
23
- SchedulerServiceInterface,
24
-
25
- // Adapters
26
- EventBridgeSchedulerAdapter,
27
- MockSchedulerAdapter,
28
- SCHEDULE_GROUP_NAME,
29
-
30
- // Factory
31
- createSchedulerService,
32
- SCHEDULER_PROVIDERS,
33
- determineProvider,
34
- };
@@ -1,143 +0,0 @@
1
- /**
2
- * Mock Scheduler Adapter for Local Development
3
- *
4
- * Stores schedules in memory and logs instead of creating real EventBridge schedules.
5
- * Used when SCHEDULER_PROVIDER=mock or in local/dev/test environments.
6
- *
7
- * This adapter implements SchedulerServiceInterface for local development and testing.
8
- */
9
-
10
- const { SchedulerServiceInterface } = require('./scheduler-service-interface');
11
-
12
- class MockSchedulerAdapter extends SchedulerServiceInterface {
13
- constructor(options = {}) {
14
- super();
15
- this.verbose = options.verbose || false;
16
- this.schedules = new Map();
17
- }
18
-
19
- /**
20
- * Schedule a one-time job to be executed at a specific time
21
- *
22
- * @param {Object} params
23
- * @param {string} params.scheduleName - Unique name for the schedule
24
- * @param {Date} params.scheduleAt - When to trigger the schedule
25
- * @param {string} params.queueResourceId - Queue resource identifier to send message to
26
- * @param {Object} params.payload - JSON payload to send
27
- * @returns {Promise<{scheduledJobId: string, scheduledAt: string}>}
28
- */
29
- async scheduleOneTime({ scheduleName, scheduleAt, queueResourceId, payload }) {
30
- if (!scheduleName) {
31
- throw new Error('scheduleName is required');
32
- }
33
- if (!scheduleAt || !(scheduleAt instanceof Date)) {
34
- throw new Error('scheduleAt must be a valid Date object');
35
- }
36
- if (!queueResourceId) {
37
- throw new Error('queueResourceId is required');
38
- }
39
-
40
- const scheduleData = {
41
- scheduleName,
42
- scheduledAt: scheduleAt.toISOString(),
43
- queueResourceId,
44
- payload,
45
- createdAt: new Date().toISOString(),
46
- state: 'ENABLED',
47
- };
48
-
49
- this.schedules.set(scheduleName, scheduleData);
50
-
51
- console.log(`[MockScheduler] Created schedule: ${scheduleName}`);
52
- console.log(`[MockScheduler] Scheduled for: ${scheduleAt.toISOString()}`);
53
- console.log(`[MockScheduler] Target: ${queueResourceId}`);
54
- if (this.verbose) {
55
- console.log(`[MockScheduler] Payload:`, JSON.stringify(payload, null, 2));
56
- }
57
-
58
- return {
59
- scheduledJobId: `mock-job-${scheduleName}`,
60
- scheduledAt: scheduleAt.toISOString(),
61
- };
62
- }
63
-
64
- /**
65
- * Delete a scheduled job
66
- *
67
- * @param {string} scheduleName - Name of the schedule to delete
68
- * @returns {Promise<void>}
69
- */
70
- async deleteSchedule(scheduleName) {
71
- if (!scheduleName) {
72
- throw new Error('scheduleName is required');
73
- }
74
-
75
- const existed = this.schedules.has(scheduleName);
76
- this.schedules.delete(scheduleName);
77
-
78
- console.log(`[MockScheduler] Deleted schedule: ${scheduleName} (existed: ${existed})`);
79
- }
80
-
81
- /**
82
- * Get the status of a scheduled job
83
- *
84
- * @param {string} scheduleName - Name of the schedule
85
- * @returns {Promise<{exists: boolean, scheduledAt?: string, state?: string}>}
86
- */
87
- async getScheduleStatus(scheduleName) {
88
- if (!scheduleName) {
89
- throw new Error('scheduleName is required');
90
- }
91
-
92
- const schedule = this.schedules.get(scheduleName);
93
-
94
- if (!schedule) {
95
- return { exists: false };
96
- }
97
-
98
- return {
99
- exists: true,
100
- scheduledAt: schedule.scheduledAt,
101
- state: schedule.state,
102
- };
103
- }
104
-
105
- /**
106
- * Get all scheduled jobs (helper for testing)
107
- *
108
- * @returns {Object} Map of all schedules as plain object
109
- */
110
- _getSchedules() {
111
- return Object.fromEntries(this.schedules);
112
- }
113
-
114
- /**
115
- * Clear all schedules (helper for testing)
116
- */
117
- _clearSchedules() {
118
- const count = this.schedules.size;
119
- this.schedules.clear();
120
- console.log(`[MockScheduler] Cleared ${count} schedules`);
121
- }
122
-
123
- /**
124
- * Simulate triggering a schedule (helper for testing)
125
- *
126
- * @param {string} scheduleName - Name of the schedule to trigger
127
- * @returns {Object|null} The payload that would be sent, or null if not found
128
- */
129
- _simulateTrigger(scheduleName) {
130
- const schedule = this.schedules.get(scheduleName);
131
- if (!schedule) {
132
- console.log(`[MockScheduler] Cannot trigger - schedule not found: ${scheduleName}`);
133
- return null;
134
- }
135
-
136
- console.log(`[MockScheduler] Simulating trigger for: ${scheduleName}`);
137
- console.log(`[MockScheduler] Payload:`, JSON.stringify(schedule.payload, null, 2));
138
-
139
- return schedule.payload;
140
- }
141
- }
142
-
143
- module.exports = { MockSchedulerAdapter };
@@ -1,73 +0,0 @@
1
- /**
2
- * Scheduler Service Factory
3
- *
4
- * Creates scheduler service instances based on configuration.
5
- * Returns implementations of SchedulerServiceInterface.
6
- *
7
- * Environment Detection:
8
- * - SCHEDULER_PROVIDER=eventbridge -> Use AWS EventBridge Scheduler
9
- * - SCHEDULER_PROVIDER=mock -> Use in-memory mock scheduler
10
- * - Default in dev/test/local stages -> Mock scheduler
11
- * - Default in other stages -> EventBridge scheduler
12
- */
13
-
14
- const { EventBridgeSchedulerAdapter } = require('./eventbridge-scheduler-adapter');
15
- const { MockSchedulerAdapter } = require('./mock-scheduler-adapter');
16
-
17
- const SCHEDULER_PROVIDERS = {
18
- EVENTBRIDGE: 'eventbridge',
19
- MOCK: 'mock',
20
- };
21
-
22
- const LOCAL_STAGES = ['dev', 'test', 'local'];
23
-
24
- /**
25
- * Determine the scheduler provider based on environment
26
- *
27
- * @returns {string} Provider name
28
- */
29
- function determineProvider() {
30
- const explicitProvider = process.env.SCHEDULER_PROVIDER;
31
- if (explicitProvider) {
32
- return explicitProvider;
33
- }
34
-
35
- const stage = process.env.STAGE || 'dev';
36
- if (LOCAL_STAGES.includes(stage)) {
37
- return SCHEDULER_PROVIDERS.MOCK;
38
- }
39
-
40
- return SCHEDULER_PROVIDERS.EVENTBRIDGE;
41
- }
42
-
43
- /**
44
- * Create a scheduler service instance
45
- *
46
- * @param {Object} options
47
- * @param {string} options.provider - Scheduler provider ('eventbridge' or 'mock')
48
- * @param {string} options.region - AWS region (for EventBridge)
49
- * @param {boolean} options.verbose - Verbose logging (for Mock)
50
- * @returns {SchedulerServiceInterface} Implementation of scheduler interface
51
- */
52
- function createSchedulerService(options = {}) {
53
- const provider = options.provider || determineProvider();
54
-
55
- switch (provider) {
56
- case SCHEDULER_PROVIDERS.EVENTBRIDGE:
57
- return new EventBridgeSchedulerAdapter({
58
- region: options.region,
59
- });
60
- case SCHEDULER_PROVIDERS.MOCK:
61
- return new MockSchedulerAdapter({
62
- verbose: options.verbose,
63
- });
64
- default:
65
- throw new Error(`Unknown scheduler provider: ${provider}`);
66
- }
67
- }
68
-
69
- module.exports = {
70
- createSchedulerService,
71
- SCHEDULER_PROVIDERS,
72
- determineProvider,
73
- };