@open-mercato/scheduler 0.6.6-develop.6465.1.019f0fb26f → 0.6.6-develop.6471.1.9ab5bdd79a

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 (40) hide show
  1. package/dist/modules/scheduler/api/jobs/[id]/executions/route.js +3 -1
  2. package/dist/modules/scheduler/api/jobs/[id]/executions/route.js.map +2 -2
  3. package/dist/modules/scheduler/api/queue-jobs/[jobId]/route.js +3 -1
  4. package/dist/modules/scheduler/api/queue-jobs/[jobId]/route.js.map +2 -2
  5. package/dist/modules/scheduler/api/trigger/route.js +4 -2
  6. package/dist/modules/scheduler/api/trigger/route.js.map +2 -2
  7. package/dist/modules/scheduler/cli.js +55 -50
  8. package/dist/modules/scheduler/cli.js.map +2 -2
  9. package/dist/modules/scheduler/commands/test-echo.js +3 -2
  10. package/dist/modules/scheduler/commands/test-echo.js.map +2 -2
  11. package/dist/modules/scheduler/di.js +4 -2
  12. package/dist/modules/scheduler/di.js.map +2 -2
  13. package/dist/modules/scheduler/lib/localLockStrategy.js +3 -1
  14. package/dist/modules/scheduler/lib/localLockStrategy.js.map +2 -2
  15. package/dist/modules/scheduler/lib/scheduledJobSubscriber.js +8 -6
  16. package/dist/modules/scheduler/lib/scheduledJobSubscriber.js.map +2 -2
  17. package/dist/modules/scheduler/services/bullmqSchedulerService.js +20 -17
  18. package/dist/modules/scheduler/services/bullmqSchedulerService.js.map +2 -2
  19. package/dist/modules/scheduler/services/localSchedulerService.js +21 -19
  20. package/dist/modules/scheduler/services/localSchedulerService.js.map +2 -2
  21. package/dist/modules/scheduler/services/schedulerService.js +5 -3
  22. package/dist/modules/scheduler/services/schedulerService.js.map +2 -2
  23. package/dist/modules/scheduler/workers/execute-schedule.worker.js +16 -15
  24. package/dist/modules/scheduler/workers/execute-schedule.worker.js.map +2 -2
  25. package/package.json +5 -5
  26. package/src/modules/scheduler/api/jobs/[id]/executions/route.ts +4 -1
  27. package/src/modules/scheduler/api/queue-jobs/[jobId]/route.ts +4 -1
  28. package/src/modules/scheduler/api/trigger/route.ts +5 -2
  29. package/src/modules/scheduler/cli.ts +55 -48
  30. package/src/modules/scheduler/commands/test-echo.ts +4 -2
  31. package/src/modules/scheduler/di.ts +6 -3
  32. package/src/modules/scheduler/lib/localLockStrategy.ts +4 -1
  33. package/src/modules/scheduler/lib/scheduledJobSubscriber.ts +9 -6
  34. package/src/modules/scheduler/services/__tests__/bullmqSchedulerService.test.ts +49 -74
  35. package/src/modules/scheduler/services/__tests__/localSchedulerService.test.ts +29 -67
  36. package/src/modules/scheduler/services/__tests__/schedulerService.test.ts +24 -9
  37. package/src/modules/scheduler/services/bullmqSchedulerService.ts +20 -16
  38. package/src/modules/scheduler/services/localSchedulerService.ts +22 -19
  39. package/src/modules/scheduler/services/schedulerService.ts +6 -3
  40. package/src/modules/scheduler/workers/execute-schedule.worker.ts +16 -14
@@ -1,5 +1,7 @@
1
1
  import { ScheduledJob } from "../data/entities.js";
2
2
  import { calculateNextRun } from "../lib/nextRunCalculator.js";
3
+ import { createLogger } from "@open-mercato/shared/lib/logger";
4
+ const logger = createLogger("scheduler");
3
5
  class SchedulerService {
4
6
  constructor(em, bullmqService) {
5
7
  this.em = em;
@@ -74,7 +76,7 @@ class SchedulerService {
74
76
  await this.bullmqService.unregister(schedule.id);
75
77
  }
76
78
  } catch (error) {
77
- console.error(`[scheduler] Failed to sync with BullMQ:`, error);
79
+ logger.error("Failed to sync with BullMQ", { scheduleId: schedule.id, err: error });
78
80
  }
79
81
  }
80
82
  }
@@ -90,7 +92,7 @@ class SchedulerService {
90
92
  try {
91
93
  await this.bullmqService.unregister(scheduleId);
92
94
  } catch (error) {
93
- console.error(`[scheduler] Failed to unregister from BullMQ:`, error);
95
+ logger.error("Failed to unregister from BullMQ", { scheduleId, err: error });
94
96
  }
95
97
  }
96
98
  }
@@ -155,7 +157,7 @@ class SchedulerService {
155
157
  await this.bullmqService.unregister(scheduleId);
156
158
  }
157
159
  } catch (error) {
158
- console.error(`[scheduler] Failed to sync update with BullMQ:`, error);
160
+ logger.error("Failed to sync update with BullMQ", { scheduleId, err: error });
159
161
  }
160
162
  }
161
163
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/scheduler/services/schedulerService.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { calculateNextRun } from '../lib/nextRunCalculator.js'\nimport type { BullMQSchedulerService } from './bullmqSchedulerService.js'\n\nexport interface ScheduleRegistration {\n id: string\n name: string\n scopeType: 'system' | 'organization' | 'tenant'\n organizationId?: string\n tenantId?: string\n scheduleType: 'cron' | 'interval'\n scheduleValue: string\n timezone?: string\n targetType: 'queue' | 'command'\n targetQueue?: string\n targetCommand?: string\n targetPayload?: unknown\n requireFeature?: string\n sourceType?: 'user' | 'module'\n sourceModule?: string\n isEnabled?: boolean\n description?: string\n}\n\nexport class SchedulerService {\n constructor(\n private em: () => EntityManager,\n private bullmqService?: BullMQSchedulerService,\n ) {}\n\n /**\n * Register a new schedule (upsert)\n */\n async register(registration: ScheduleRegistration): Promise<void> {\n const em = this.em().fork()\n \n // Validate scope consistency\n this.validateScope(registration)\n \n // Validate target consistency\n this.validateTarget(registration)\n \n // Calculate next run time\n const nextRunAt = calculateNextRun(\n registration.scheduleType,\n registration.scheduleValue,\n registration.timezone || 'UTC'\n )\n \n if (!nextRunAt) {\n throw new Error(`Failed to calculate next run time for schedule: ${registration.id}`)\n }\n \n // Check if schedule already exists\n let schedule = await em.findOne(ScheduledJob, { id: registration.id })\n \n if (schedule) {\n // Update existing\n schedule.name = registration.name\n schedule.description = registration.description || null\n schedule.scopeType = registration.scopeType\n schedule.organizationId = registration.organizationId || null\n schedule.tenantId = registration.tenantId || null\n schedule.scheduleType = registration.scheduleType\n schedule.scheduleValue = registration.scheduleValue\n schedule.timezone = registration.timezone || 'UTC'\n schedule.targetType = registration.targetType\n schedule.targetQueue = registration.targetQueue || null\n schedule.targetCommand = registration.targetCommand || null\n schedule.targetPayload = registration.targetPayload as Record<string, unknown> || null\n schedule.requireFeature = registration.requireFeature || null\n schedule.sourceType = registration.sourceType || 'user'\n schedule.sourceModule = registration.sourceModule || null\n schedule.isEnabled = registration.isEnabled !== undefined ? registration.isEnabled : schedule.isEnabled\n schedule.nextRunAt = nextRunAt\n schedule.updatedAt = new Date()\n } else {\n // Create new\n schedule = em.create(ScheduledJob, {\n id: registration.id,\n name: registration.name,\n description: registration.description || null,\n scopeType: registration.scopeType,\n organizationId: registration.organizationId || null,\n tenantId: registration.tenantId || null,\n scheduleType: registration.scheduleType,\n scheduleValue: registration.scheduleValue,\n timezone: registration.timezone || 'UTC',\n targetType: registration.targetType,\n targetQueue: registration.targetQueue || null,\n targetCommand: registration.targetCommand || null,\n targetPayload: registration.targetPayload as Record<string, unknown> || null,\n requireFeature: registration.requireFeature || null,\n sourceType: registration.sourceType || 'module',\n sourceModule: registration.sourceModule || null,\n isEnabled: registration.isEnabled !== undefined ? registration.isEnabled : true,\n nextRunAt,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(schedule)\n }\n \n await em.flush()\n\n // Sync with BullMQ if available\n if (this.bullmqService && schedule) {\n try {\n if (schedule.isEnabled) {\n await this.bullmqService.register(schedule)\n } else {\n await this.bullmqService.unregister(schedule.id)\n }\n } catch (error: unknown) {\n console.error(`[scheduler] Failed to sync with BullMQ:`, error)\n // Don't throw - DB is source of truth, BullMQ sync is best-effort\n }\n }\n }\n\n /**\n * Unregister a schedule\n */\n async unregister(scheduleId: string): Promise<void> {\n const em = this.em().fork()\n const schedule = await em.findOne(ScheduledJob, { id: scheduleId })\n \n if (schedule) {\n await em.remove(schedule).flush()\n \n // Unregister from BullMQ if available\n if (this.bullmqService) {\n try {\n await this.bullmqService.unregister(scheduleId)\n } catch (error: unknown) {\n console.error(`[scheduler] Failed to unregister from BullMQ:`, error)\n }\n }\n }\n }\n\n /**\n * Check if a schedule exists\n */\n async exists(scheduleId: string): Promise<boolean> {\n const em = this.em()\n const count = await em.count(ScheduledJob, { id: scheduleId })\n return count > 0\n }\n\n /**\n * Update an existing schedule\n */\n async update(\n scheduleId: string,\n changes: Partial<Omit<ScheduleRegistration, 'id'>>\n ): Promise<void> {\n const em = this.em().fork()\n const schedule = await em.findOne(ScheduledJob, { id: scheduleId })\n \n if (!schedule) {\n throw new Error(`Schedule not found: ${scheduleId}`)\n }\n \n // Apply changes\n if (changes.name !== undefined) schedule.name = changes.name\n if (changes.description !== undefined) schedule.description = changes.description || null\n if (changes.scheduleType !== undefined) schedule.scheduleType = changes.scheduleType\n if (changes.scheduleValue !== undefined) schedule.scheduleValue = changes.scheduleValue\n if (changes.timezone !== undefined) schedule.timezone = changes.timezone\n if (changes.targetPayload !== undefined) {\n schedule.targetPayload = changes.targetPayload as Record<string, unknown> || null\n }\n if (changes.requireFeature !== undefined) schedule.requireFeature = changes.requireFeature || null\n if (changes.isEnabled !== undefined) schedule.isEnabled = changes.isEnabled\n \n // Handle target type changes - clear stale values when switching between queue and command\n if (changes.targetType !== undefined) {\n schedule.targetType = changes.targetType\n \n if (changes.targetType === 'queue') {\n // Switching to queue: set new queue and clear command\n if (changes.targetQueue !== undefined) schedule.targetQueue = changes.targetQueue || null\n schedule.targetCommand = null\n } else if (changes.targetType === 'command') {\n // Switching to command: set new command and clear queue\n if (changes.targetCommand !== undefined) schedule.targetCommand = changes.targetCommand || null\n schedule.targetQueue = null\n }\n } else {\n // targetType not changing, but allow updating individual target fields\n if (changes.targetQueue !== undefined) schedule.targetQueue = changes.targetQueue || null\n if (changes.targetCommand !== undefined) schedule.targetCommand = changes.targetCommand || null\n }\n \n // Recalculate next run if schedule changed\n if (changes.scheduleType !== undefined || changes.scheduleValue !== undefined || changes.timezone !== undefined) {\n const nextRunAt = calculateNextRun(\n schedule.scheduleType,\n schedule.scheduleValue,\n schedule.timezone\n )\n if (nextRunAt) {\n schedule.nextRunAt = nextRunAt\n }\n }\n \n schedule.updatedAt = new Date()\n await em.flush()\n\n // Sync with BullMQ if available\n if (this.bullmqService) {\n try {\n if (schedule.isEnabled) {\n await this.bullmqService.register(schedule)\n } else {\n await this.bullmqService.unregister(scheduleId)\n }\n } catch (error: unknown) {\n console.error(`[scheduler] Failed to sync update with BullMQ:`, error)\n }\n }\n }\n\n /**\n * Find schedules by module\n */\n async findByModule(moduleId: string, limit = 100): Promise<ScheduledJob[]> {\n const em = this.em()\n return em.find(ScheduledJob, { sourceModule: moduleId, deletedAt: null }, { limit })\n }\n\n /**\n * Enable a schedule\n */\n async enable(scheduleId: string): Promise<void> {\n await this.update(scheduleId, { isEnabled: true })\n }\n\n /**\n * Disable a schedule\n */\n async disable(scheduleId: string): Promise<void> {\n await this.update(scheduleId, { isEnabled: false })\n }\n\n private validateScope(registration: ScheduleRegistration): void {\n const { scopeType, organizationId, tenantId } = registration\n \n if (scopeType === 'system') {\n if (organizationId || tenantId) {\n throw new Error('System-scoped schedules cannot have organizationId or tenantId')\n }\n } else if (scopeType === 'organization') {\n if (!organizationId || !tenantId) {\n throw new Error('Organization-scoped schedules must have both organizationId and tenantId')\n }\n } else if (scopeType === 'tenant') {\n if (organizationId || !tenantId) {\n throw new Error('Tenant-scoped schedules must have tenantId and no organizationId')\n }\n }\n }\n\n private validateTarget(registration: ScheduleRegistration): void {\n const { targetType, targetQueue, targetCommand } = registration\n \n if (targetType === 'queue') {\n if (!targetQueue) {\n throw new Error('Queue target must have targetQueue')\n }\n } else if (targetType === 'command') {\n if (!targetCommand) {\n throw new Error('Command target must have targetCommand')\n }\n }\n }\n}\n"],
5
- "mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AAuB1B,MAAM,iBAAiB;AAAA,EAC5B,YACU,IACA,eACR;AAFQ;AACA;AAAA,EACP;AAAA;AAAA;AAAA;AAAA,EAKH,MAAM,SAAS,cAAmD;AAChE,UAAM,KAAK,KAAK,GAAG,EAAE,KAAK;AAG1B,SAA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EAAkE;AAAA,MACpF;AAAA,IACF;AAAA,EACF;AAAA,EAEQ,eAAe,cAA0C;AAC/D,UAAM,EAAE,YAAY,aAAa,cAAc,IAAI;AAEnD,QAAI,eAAe,SAAS;AAC1B,UAAI,CAAC,aAAa;AAChB,cAAM,IAAI,MAAM,oCAAoC;AAAA,MACtD;AAAA,IACF,WAAW,eAAe,WAAW;AACnC,UAAI,CAAC,eAAe;AAClB,cAAM,IAAI,MAAM,wCAAwC;AAAA,MAC1D;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { calculateNextRun } from '../lib/nextRunCalculator.js'\nimport type { BullMQSchedulerService } from './bullmqSchedulerService.js'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler')\n\nexport interface ScheduleRegistration {\n id: string\n name: string\n scopeType: 'system' | 'organization' | 'tenant'\n organizationId?: string\n tenantId?: string\n scheduleType: 'cron' | 'interval'\n scheduleValue: string\n timezone?: string\n targetType: 'queue' | 'command'\n targetQueue?: string\n targetCommand?: string\n targetPayload?: unknown\n requireFeature?: string\n sourceType?: 'user' | 'module'\n sourceModule?: string\n isEnabled?: boolean\n description?: string\n}\n\nexport class SchedulerService {\n constructor(\n private em: () => EntityManager,\n private bullmqService?: BullMQSchedulerService,\n ) {}\n\n /**\n * Register a new schedule (upsert)\n */\n async register(registration: ScheduleRegistration): Promise<void> {\n const em = this.em().fork()\n \n // Validate scope consistency\n this.validateScope(registration)\n \n // Validate target consistency\n this.validateTarget(registration)\n \n // Calculate next run time\n const nextRunAt = calculateNextRun(\n registration.scheduleType,\n registration.scheduleValue,\n registration.timezone || 'UTC'\n )\n \n if (!nextRunAt) {\n throw new Error(`Failed to calculate next run time for schedule: ${registration.id}`)\n }\n \n // Check if schedule already exists\n let schedule = await em.findOne(ScheduledJob, { id: registration.id })\n \n if (schedule) {\n // Update existing\n schedule.name = registration.name\n schedule.description = registration.description || null\n schedule.scopeType = registration.scopeType\n schedule.organizationId = registration.organizationId || null\n schedule.tenantId = registration.tenantId || null\n schedule.scheduleType = registration.scheduleType\n schedule.scheduleValue = registration.scheduleValue\n schedule.timezone = registration.timezone || 'UTC'\n schedule.targetType = registration.targetType\n schedule.targetQueue = registration.targetQueue || null\n schedule.targetCommand = registration.targetCommand || null\n schedule.targetPayload = registration.targetPayload as Record<string, unknown> || null\n schedule.requireFeature = registration.requireFeature || null\n schedule.sourceType = registration.sourceType || 'user'\n schedule.sourceModule = registration.sourceModule || null\n schedule.isEnabled = registration.isEnabled !== undefined ? registration.isEnabled : schedule.isEnabled\n schedule.nextRunAt = nextRunAt\n schedule.updatedAt = new Date()\n } else {\n // Create new\n schedule = em.create(ScheduledJob, {\n id: registration.id,\n name: registration.name,\n description: registration.description || null,\n scopeType: registration.scopeType,\n organizationId: registration.organizationId || null,\n tenantId: registration.tenantId || null,\n scheduleType: registration.scheduleType,\n scheduleValue: registration.scheduleValue,\n timezone: registration.timezone || 'UTC',\n targetType: registration.targetType,\n targetQueue: registration.targetQueue || null,\n targetCommand: registration.targetCommand || null,\n targetPayload: registration.targetPayload as Record<string, unknown> || null,\n requireFeature: registration.requireFeature || null,\n sourceType: registration.sourceType || 'module',\n sourceModule: registration.sourceModule || null,\n isEnabled: registration.isEnabled !== undefined ? registration.isEnabled : true,\n nextRunAt,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(schedule)\n }\n \n await em.flush()\n\n // Sync with BullMQ if available\n if (this.bullmqService && schedule) {\n try {\n if (schedule.isEnabled) {\n await this.bullmqService.register(schedule)\n } else {\n await this.bullmqService.unregister(schedule.id)\n }\n } catch (error: unknown) {\n logger.error('Failed to sync with BullMQ', { scheduleId: schedule.id, err: error })\n // Don't throw - DB is source of truth, BullMQ sync is best-effort\n }\n }\n }\n\n /**\n * Unregister a schedule\n */\n async unregister(scheduleId: string): Promise<void> {\n const em = this.em().fork()\n const schedule = await em.findOne(ScheduledJob, { id: scheduleId })\n \n if (schedule) {\n await em.remove(schedule).flush()\n \n // Unregister from BullMQ if available\n if (this.bullmqService) {\n try {\n await this.bullmqService.unregister(scheduleId)\n } catch (error: unknown) {\n logger.error('Failed to unregister from BullMQ', { scheduleId, err: error })\n }\n }\n }\n }\n\n /**\n * Check if a schedule exists\n */\n async exists(scheduleId: string): Promise<boolean> {\n const em = this.em()\n const count = await em.count(ScheduledJob, { id: scheduleId })\n return count > 0\n }\n\n /**\n * Update an existing schedule\n */\n async update(\n scheduleId: string,\n changes: Partial<Omit<ScheduleRegistration, 'id'>>\n ): Promise<void> {\n const em = this.em().fork()\n const schedule = await em.findOne(ScheduledJob, { id: scheduleId })\n \n if (!schedule) {\n throw new Error(`Schedule not found: ${scheduleId}`)\n }\n \n // Apply changes\n if (changes.name !== undefined) schedule.name = changes.name\n if (changes.description !== undefined) schedule.description = changes.description || null\n if (changes.scheduleType !== undefined) schedule.scheduleType = changes.scheduleType\n if (changes.scheduleValue !== undefined) schedule.scheduleValue = changes.scheduleValue\n if (changes.timezone !== undefined) schedule.timezone = changes.timezone\n if (changes.targetPayload !== undefined) {\n schedule.targetPayload = changes.targetPayload as Record<string, unknown> || null\n }\n if (changes.requireFeature !== undefined) schedule.requireFeature = changes.requireFeature || null\n if (changes.isEnabled !== undefined) schedule.isEnabled = changes.isEnabled\n \n // Handle target type changes - clear stale values when switching between queue and command\n if (changes.targetType !== undefined) {\n schedule.targetType = changes.targetType\n \n if (changes.targetType === 'queue') {\n // Switching to queue: set new queue and clear command\n if (changes.targetQueue !== undefined) schedule.targetQueue = changes.targetQueue || null\n schedule.targetCommand = null\n } else if (changes.targetType === 'command') {\n // Switching to command: set new command and clear queue\n if (changes.targetCommand !== undefined) schedule.targetCommand = changes.targetCommand || null\n schedule.targetQueue = null\n }\n } else {\n // targetType not changing, but allow updating individual target fields\n if (changes.targetQueue !== undefined) schedule.targetQueue = changes.targetQueue || null\n if (changes.targetCommand !== undefined) schedule.targetCommand = changes.targetCommand || null\n }\n \n // Recalculate next run if schedule changed\n if (changes.scheduleType !== undefined || changes.scheduleValue !== undefined || changes.timezone !== undefined) {\n const nextRunAt = calculateNextRun(\n schedule.scheduleType,\n schedule.scheduleValue,\n schedule.timezone\n )\n if (nextRunAt) {\n schedule.nextRunAt = nextRunAt\n }\n }\n \n schedule.updatedAt = new Date()\n await em.flush()\n\n // Sync with BullMQ if available\n if (this.bullmqService) {\n try {\n if (schedule.isEnabled) {\n await this.bullmqService.register(schedule)\n } else {\n await this.bullmqService.unregister(scheduleId)\n }\n } catch (error: unknown) {\n logger.error('Failed to sync update with BullMQ', { scheduleId, err: error })\n }\n }\n }\n\n /**\n * Find schedules by module\n */\n async findByModule(moduleId: string, limit = 100): Promise<ScheduledJob[]> {\n const em = this.em()\n return em.find(ScheduledJob, { sourceModule: moduleId, deletedAt: null }, { limit })\n }\n\n /**\n * Enable a schedule\n */\n async enable(scheduleId: string): Promise<void> {\n await this.update(scheduleId, { isEnabled: true })\n }\n\n /**\n * Disable a schedule\n */\n async disable(scheduleId: string): Promise<void> {\n await this.update(scheduleId, { isEnabled: false })\n }\n\n private validateScope(registration: ScheduleRegistration): void {\n const { scopeType, organizationId, tenantId } = registration\n \n if (scopeType === 'system') {\n if (organizationId || tenantId) {\n throw new Error('System-scoped schedules cannot have organizationId or tenantId')\n }\n } else if (scopeType === 'organization') {\n if (!organizationId || !tenantId) {\n throw new Error('Organization-scoped schedules must have both organizationId and tenantId')\n }\n } else if (scopeType === 'tenant') {\n if (organizationId || !tenantId) {\n throw new Error('Tenant-scoped schedules must have tenantId and no organizationId')\n }\n }\n }\n\n private validateTarget(registration: ScheduleRegistration): void {\n const { targetType, targetQueue, targetCommand } = registration\n \n if (targetType === 'queue') {\n if (!targetQueue) {\n throw new Error('Queue target must have targetQueue')\n }\n } else if (targetType === 'command') {\n if (!targetCommand) {\n throw new Error('Command target must have targetCommand')\n }\n }\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,oBAAoB;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E,WAAW,gBAAgB,SAAS,IAAI;AAEhD,QAAI,cAAc,UAAU;AAC1B,UAAI,kBAAkB,UAAU;AAC9B,cAAM,IAAI,MAAM,gEAAgE;AAAA,MAClF;AAAA,IACF,WAAW,cAAc,gBAAgB;AACvC,UAAI,CAAC,kBAAkB,CAAC,UAAU;AAChC,cAAM,IAAI,MAAM,0EAA0E;AAAA,MAC5F;AAAA,IACF,WAAW,cAAc,UAAU;AACjC,UAAI,kBAAkB,CAAC,UAAU;AAC/B,cAAM,IAAI,MAAM,kEAAkE;AAAA,MACpF;AAAA,IACF;AAAA,EACF;AAAA,EAEQ,eAAe,cAA0C;AAC/D,UAAM,EAAE,YAAY,aAAa,cAAc,IAAI;AAEnD,QAAI,eAAe,SAAS;AAC1B,UAAI,CAAC,aAAa;AAChB,cAAM,IAAI,MAAM,oCAAoC;AAAA,MACtD;AAAA,IACF,WAAW,eAAe,WAAW;AACnC,UAAI,CAAC,eAAe;AAClB,cAAM,IAAI,MAAM,wCAAwC;AAAA,MAC1D;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -4,22 +4,21 @@ import { ScheduledJob } from "../data/entities.js";
4
4
  import { CommandBus } from "@open-mercato/shared/lib/commands";
5
5
  import { emitSchedulerEvent } from "../events.js";
6
6
  import { buildScheduledCommandContext } from "../lib/commandContext.js";
7
+ import { createLogger } from "@open-mercato/shared/lib/logger";
8
+ const logger = createLogger("scheduler").child({ component: "worker" });
7
9
  const metadata = {
8
10
  queue: "scheduler-execution",
9
11
  concurrency: 5
10
12
  // Process up to 5 schedules concurrently
11
13
  };
12
14
  async function executeScheduleWorker(job, ctx) {
13
- console.debug("[scheduler:execute] Processing job:", {
15
+ logger.debug("Processing job", {
14
16
  jobId: ctx.jobId,
15
17
  attemptNumber: ctx.attemptNumber
16
18
  });
17
19
  const payload = job.payload || job.data;
18
20
  if (!payload || !payload.scheduleId) {
19
- console.error("[scheduler:execute] Invalid job payload:", {
20
- jobId: ctx.jobId,
21
- payload: job.payload
22
- });
21
+ logger.error("Invalid job payload: scheduleId missing", { jobId: ctx.jobId });
23
22
  throw new Error("scheduleId is required in job payload");
24
23
  }
25
24
  const { scheduleId } = payload;
@@ -30,32 +29,35 @@ async function executeScheduleWorker(job, ctx) {
30
29
  deletedAt: null
31
30
  });
32
31
  if (!schedule) {
33
- console.log(`[scheduler:worker] Schedule not found or deleted: ${scheduleId}`);
32
+ logger.info("Schedule not found or deleted", { scheduleId });
34
33
  return;
35
34
  }
36
35
  if (payload.scopeType !== schedule.scopeType) {
37
- console.error(`[scheduler:worker] Scope type mismatch for schedule ${scheduleId}:`, {
36
+ logger.error("Scope type mismatch for schedule", {
37
+ scheduleId,
38
38
  payloadScope: payload.scopeType,
39
39
  dbScope: schedule.scopeType
40
40
  });
41
41
  throw new Error("Schedule scope type mismatch - potential security issue");
42
42
  }
43
43
  if (payload.tenantId !== schedule.tenantId) {
44
- console.error(`[scheduler:worker] Tenant ID mismatch for schedule ${scheduleId}:`, {
44
+ logger.error("Tenant ID mismatch for schedule", {
45
+ scheduleId,
45
46
  payloadTenant: payload.tenantId,
46
47
  dbTenant: schedule.tenantId
47
48
  });
48
49
  throw new Error("Schedule tenant ID mismatch - potential security issue");
49
50
  }
50
51
  if (payload.organizationId !== schedule.organizationId) {
51
- console.error(`[scheduler:worker] Organization ID mismatch for schedule ${scheduleId}:`, {
52
+ logger.error("Organization ID mismatch for schedule", {
53
+ scheduleId,
52
54
  payloadOrg: payload.organizationId,
53
55
  dbOrg: schedule.organizationId
54
56
  });
55
57
  throw new Error("Schedule organization ID mismatch - potential security issue");
56
58
  }
57
59
  if (!schedule.isEnabled) {
58
- console.debug(`[scheduler:worker] Schedule is disabled: ${scheduleId}`);
60
+ logger.debug("Schedule is disabled", { scheduleId });
59
61
  await emitSchedulerEvent("scheduler.job.skipped", {
60
62
  id: schedule.id,
61
63
  tenantId: schedule.tenantId,
@@ -84,7 +86,7 @@ async function executeScheduleWorker(job, ctx) {
84
86
  organizationId: schedule.organizationId,
85
87
  reason: `Feature not enabled: ${schedule.requireFeature}`
86
88
  });
87
- console.debug(`[scheduler:worker] Schedule skipped - feature not enabled: ${schedule.requireFeature}`);
89
+ logger.debug("Schedule skipped: feature not enabled", { scheduleId, requireFeature: schedule.requireFeature });
88
90
  return;
89
91
  }
90
92
  }
@@ -116,7 +118,7 @@ async function executeScheduleWorker(job, ctx) {
116
118
  queueJobId: targetJobId,
117
119
  queueName: schedule.targetQueue
118
120
  });
119
- console.debug(`[scheduler:worker] Successfully enqueued job`, {
121
+ logger.debug("Successfully enqueued job", {
120
122
  scheduleId: schedule.id,
121
123
  targetQueue: schedule.targetQueue,
122
124
  queueJobId: targetJobId
@@ -142,10 +144,9 @@ async function executeScheduleWorker(job, ctx) {
142
144
  commandId: schedule.targetCommand,
143
145
  commandResult: commandResult.result
144
146
  });
145
- console.debug(`[scheduler:worker] Successfully executed command`, {
147
+ logger.debug("Successfully executed command", {
146
148
  scheduleId: schedule.id,
147
- commandId: schedule.targetCommand,
148
- result: commandResult.result
149
+ commandId: schedule.targetCommand
149
150
  });
150
151
  } else {
151
152
  throw new Error("Invalid target configuration");
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/scheduler/workers/execute-schedule.worker.ts"],
4
- "sourcesContent": ["import type { QueuedJob, JobContext, WorkerMeta } from '@open-mercato/queue'\nimport { createQueue } from '@open-mercato/queue'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { emitSchedulerEvent } from '../events.js'\nimport { buildScheduledCommandContext } from '../lib/commandContext.js'\n\n// Worker metadata for auto-discovery\nexport const metadata: WorkerMeta = {\n queue: 'scheduler-execution',\n concurrency: 5, // Process up to 5 schedules concurrently\n}\n\nexport type ExecuteSchedulePayload = {\n scheduleId: string\n tenantId?: string | null\n organizationId?: string | null\n scopeType: 'system' | 'organization' | 'tenant'\n triggerType?: 'scheduled' | 'manual'\n triggeredByUserId?: string | null\n}\n\ntype HandlerContext = { resolve: <T = unknown>(name: string) => T }\ntype RbacServiceLike = {\n tenantHasFeature(\n tenantId: string | null | undefined,\n feature: string,\n opts?: { organizationId?: string | null },\n ): Promise<boolean>\n}\n\n/**\n * Worker that executes scheduled jobs.\n * \n * This worker is triggered by BullMQ repeatable jobs at the scheduled times.\n * It loads the fresh schedule configuration from the database, validates\n * conditions, and enqueues the target job or executes the command.\n * \n * BullMQ handles:\n * - Timing (exact cron/interval execution)\n * - Distributed locking (prevents duplicate execution)\n * - Retries (if worker fails)\n * - Execution history (via job state, logs, timestamps)\n * \n * This worker handles:\n * - Loading fresh schedule config\n * - Checking feature flags and conditions\n * - Enqueuing target job or executing command\n * - Updating last run time\n */\nexport default async function executeScheduleWorker(\n job: QueuedJob<ExecuteSchedulePayload>,\n ctx: JobContext & HandlerContext,\n): Promise<void> {\n console.debug('[scheduler:execute] Processing job:', {\n jobId: ctx.jobId,\n attemptNumber: ctx.attemptNumber,\n })\n \n // Defensive: handle both data and payload for BullMQ compatibility\n const payload = (job.payload || (job as unknown as { data?: ExecuteSchedulePayload }).data) as ExecuteSchedulePayload | undefined\n \n if (!payload || !payload.scheduleId) {\n console.error('[scheduler:execute] Invalid job payload:', {\n jobId: ctx.jobId,\n payload: job.payload,\n })\n throw new Error('scheduleId is required in job payload')\n }\n\n const { scheduleId } = payload\n\n const em = ctx.resolve<EntityManager>('em')\n const rbacService = ctx.resolve<RbacServiceLike>('rbacService')\n\n // Load fresh schedule from database\n const schedule = await em.findOne(ScheduledJob, { \n id: scheduleId,\n deletedAt: null,\n })\n\n if (!schedule) {\n console.log(`[scheduler:worker] Schedule not found or deleted: ${scheduleId}`)\n return\n }\n\n // CRITICAL: Verify scope integrity - ensure payload scope matches database\n // This prevents scope tampering and ensures proper multi-tenant isolation\n if (payload.scopeType !== schedule.scopeType) {\n console.error(`[scheduler:worker] Scope type mismatch for schedule ${scheduleId}:`, {\n payloadScope: payload.scopeType,\n dbScope: schedule.scopeType,\n })\n throw new Error('Schedule scope type mismatch - potential security issue')\n }\n\n if (payload.tenantId !== schedule.tenantId) {\n console.error(`[scheduler:worker] Tenant ID mismatch for schedule ${scheduleId}:`, {\n payloadTenant: payload.tenantId,\n dbTenant: schedule.tenantId,\n })\n throw new Error('Schedule tenant ID mismatch - potential security issue')\n }\n\n if (payload.organizationId !== schedule.organizationId) {\n console.error(`[scheduler:worker] Organization ID mismatch for schedule ${scheduleId}:`, {\n payloadOrg: payload.organizationId,\n dbOrg: schedule.organizationId,\n })\n throw new Error('Schedule organization ID mismatch - potential security issue')\n }\n\n // Check if schedule is still enabled\n if (!schedule.isEnabled) {\n console.debug(`[scheduler:worker] Schedule is disabled: ${scheduleId}`)\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: 'Schedule is disabled',\n })\n return\n }\n\n // Emit started event\n await emitSchedulerEvent('scheduler.job.started', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n attemptNumber: ctx.attemptNumber || 1,\n })\n\n // Check feature flag if required\n if (schedule.requireFeature) {\n const hasFeature = await rbacService.tenantHasFeature(\n schedule.tenantId,\n schedule.requireFeature,\n { organizationId: schedule.organizationId },\n )\n \n if (!hasFeature) {\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Feature not enabled: ${schedule.requireFeature}`,\n })\n\n console.debug(`[scheduler:worker] Schedule skipped - feature not enabled: ${schedule.requireFeature}`)\n return\n }\n }\n\n // Enqueue target job or execute command\n if (schedule.targetType === 'queue' && schedule.targetQueue) {\n // Determine queue strategy from environment\n const queueStrategy = (process.env.QUEUE_STRATEGY || 'local') as 'local' | 'async'\n const targetQueue = createQueue(schedule.targetQueue, queueStrategy, {\n connection: { url: getRedisUrlOrThrow('QUEUE') },\n })\n \n let targetJobId: string | undefined\n try {\n // Generate a deterministic idempotency key so that if BullMQ retries\n // this worker after a crash between enqueue and DB flush, downstream\n // workers can deduplicate using this key.\n const executionTimestamp = Date.now()\n const idempotencyKey = `scheduler-${schedule.id}-${executionTimestamp}`\n\n const queuePayload = {\n ...((schedule.targetPayload as Record<string, unknown>) || {}),\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n _idempotencyKey: idempotencyKey,\n }\n\n targetJobId = await targetQueue.enqueue(queuePayload)\n } finally {\n // Always close the queue instance to free Redis connections\n await targetQueue.close()\n }\n \n // Update schedule's last run time\n schedule.lastRunAt = new Date()\n await em.flush()\n\n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n queueJobId: targetJobId,\n queueName: schedule.targetQueue,\n })\n\n console.debug(`[scheduler:worker] Successfully enqueued job`, {\n scheduleId: schedule.id,\n targetQueue: schedule.targetQueue,\n queueJobId: targetJobId,\n })\n\n } else if (schedule.targetType === 'command' && schedule.targetCommand) {\n const commandBus = new CommandBus()\n \n const commandInput = {\n ...((schedule.targetPayload as Record<string, unknown>) || {}),\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n }\n \n const commandCtx = buildScheduledCommandContext(schedule, ctx as unknown as AppContainer)\n \n const commandResult = await commandBus.execute(schedule.targetCommand, {\n input: commandInput,\n ctx: commandCtx,\n })\n \n // Update schedule's last run time\n schedule.lastRunAt = new Date()\n await em.flush()\n \n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n commandId: schedule.targetCommand,\n commandResult: commandResult.result,\n })\n \n console.debug(`[scheduler:worker] Successfully executed command`, {\n scheduleId: schedule.id,\n commandId: schedule.targetCommand,\n result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AAQ,MAAM,oDAAoD;AAAA,MAChE,YAAY,SAAS;AAAA,MACrB,WAAW,SAAS;AAAA,MACpB,QAAQ,cAAc;AAAA,IACxB,CAAC;AAAA,EAEH,OAAO;AACL,UAAM,IAAI,MAAM,8BAA8B;AAAA,EAChD;AACF;",
4
+ "sourcesContent": ["import type { QueuedJob, JobContext, WorkerMeta } from '@open-mercato/queue'\nimport { createQueue } from '@open-mercato/queue'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { emitSchedulerEvent } from '../events.js'\nimport { buildScheduledCommandContext } from '../lib/commandContext.js'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'worker' })\n\n// Worker metadata for auto-discovery\nexport const metadata: WorkerMeta = {\n queue: 'scheduler-execution',\n concurrency: 5, // Process up to 5 schedules concurrently\n}\n\nexport type ExecuteSchedulePayload = {\n scheduleId: string\n tenantId?: string | null\n organizationId?: string | null\n scopeType: 'system' | 'organization' | 'tenant'\n triggerType?: 'scheduled' | 'manual'\n triggeredByUserId?: string | null\n}\n\ntype HandlerContext = { resolve: <T = unknown>(name: string) => T }\ntype RbacServiceLike = {\n tenantHasFeature(\n tenantId: string | null | undefined,\n feature: string,\n opts?: { organizationId?: string | null },\n ): Promise<boolean>\n}\n\n/**\n * Worker that executes scheduled jobs.\n * \n * This worker is triggered by BullMQ repeatable jobs at the scheduled times.\n * It loads the fresh schedule configuration from the database, validates\n * conditions, and enqueues the target job or executes the command.\n * \n * BullMQ handles:\n * - Timing (exact cron/interval execution)\n * - Distributed locking (prevents duplicate execution)\n * - Retries (if worker fails)\n * - Execution history (via job state, logs, timestamps)\n * \n * This worker handles:\n * - Loading fresh schedule config\n * - Checking feature flags and conditions\n * - Enqueuing target job or executing command\n * - Updating last run time\n */\nexport default async function executeScheduleWorker(\n job: QueuedJob<ExecuteSchedulePayload>,\n ctx: JobContext & HandlerContext,\n): Promise<void> {\n logger.debug('Processing job', {\n jobId: ctx.jobId,\n attemptNumber: ctx.attemptNumber,\n })\n \n // Defensive: handle both data and payload for BullMQ compatibility\n const payload = (job.payload || (job as unknown as { data?: ExecuteSchedulePayload }).data) as ExecuteSchedulePayload | undefined\n \n if (!payload || !payload.scheduleId) {\n logger.error('Invalid job payload: scheduleId missing', { jobId: ctx.jobId })\n throw new Error('scheduleId is required in job payload')\n }\n\n const { scheduleId } = payload\n\n const em = ctx.resolve<EntityManager>('em')\n const rbacService = ctx.resolve<RbacServiceLike>('rbacService')\n\n // Load fresh schedule from database\n const schedule = await em.findOne(ScheduledJob, { \n id: scheduleId,\n deletedAt: null,\n })\n\n if (!schedule) {\n logger.info('Schedule not found or deleted', { scheduleId })\n return\n }\n\n // CRITICAL: Verify scope integrity - ensure payload scope matches database\n // This prevents scope tampering and ensures proper multi-tenant isolation\n if (payload.scopeType !== schedule.scopeType) {\n logger.error('Scope type mismatch for schedule', {\n scheduleId,\n payloadScope: payload.scopeType,\n dbScope: schedule.scopeType,\n })\n throw new Error('Schedule scope type mismatch - potential security issue')\n }\n\n if (payload.tenantId !== schedule.tenantId) {\n logger.error('Tenant ID mismatch for schedule', {\n scheduleId,\n payloadTenant: payload.tenantId,\n dbTenant: schedule.tenantId,\n })\n throw new Error('Schedule tenant ID mismatch - potential security issue')\n }\n\n if (payload.organizationId !== schedule.organizationId) {\n logger.error('Organization ID mismatch for schedule', {\n scheduleId,\n payloadOrg: payload.organizationId,\n dbOrg: schedule.organizationId,\n })\n throw new Error('Schedule organization ID mismatch - potential security issue')\n }\n\n // Check if schedule is still enabled\n if (!schedule.isEnabled) {\n logger.debug('Schedule is disabled', { scheduleId })\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: 'Schedule is disabled',\n })\n return\n }\n\n // Emit started event\n await emitSchedulerEvent('scheduler.job.started', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n attemptNumber: ctx.attemptNumber || 1,\n })\n\n // Check feature flag if required\n if (schedule.requireFeature) {\n const hasFeature = await rbacService.tenantHasFeature(\n schedule.tenantId,\n schedule.requireFeature,\n { organizationId: schedule.organizationId },\n )\n \n if (!hasFeature) {\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Feature not enabled: ${schedule.requireFeature}`,\n })\n\n logger.debug('Schedule skipped: feature not enabled', { scheduleId, requireFeature: schedule.requireFeature })\n return\n }\n }\n\n // Enqueue target job or execute command\n if (schedule.targetType === 'queue' && schedule.targetQueue) {\n // Determine queue strategy from environment\n const queueStrategy = (process.env.QUEUE_STRATEGY || 'local') as 'local' | 'async'\n const targetQueue = createQueue(schedule.targetQueue, queueStrategy, {\n connection: { url: getRedisUrlOrThrow('QUEUE') },\n })\n \n let targetJobId: string | undefined\n try {\n // Generate a deterministic idempotency key so that if BullMQ retries\n // this worker after a crash between enqueue and DB flush, downstream\n // workers can deduplicate using this key.\n const executionTimestamp = Date.now()\n const idempotencyKey = `scheduler-${schedule.id}-${executionTimestamp}`\n\n const queuePayload = {\n ...((schedule.targetPayload as Record<string, unknown>) || {}),\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n _idempotencyKey: idempotencyKey,\n }\n\n targetJobId = await targetQueue.enqueue(queuePayload)\n } finally {\n // Always close the queue instance to free Redis connections\n await targetQueue.close()\n }\n \n // Update schedule's last run time\n schedule.lastRunAt = new Date()\n await em.flush()\n\n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n queueJobId: targetJobId,\n queueName: schedule.targetQueue,\n })\n\n logger.debug('Successfully enqueued job', {\n scheduleId: schedule.id,\n targetQueue: schedule.targetQueue,\n queueJobId: targetJobId,\n })\n\n } else if (schedule.targetType === 'command' && schedule.targetCommand) {\n const commandBus = new CommandBus()\n \n const commandInput = {\n ...((schedule.targetPayload as Record<string, unknown>) || {}),\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n }\n \n const commandCtx = buildScheduledCommandContext(schedule, ctx as unknown as AppContainer)\n \n const commandResult = await commandBus.execute(schedule.targetCommand, {\n input: commandInput,\n ctx: commandCtx,\n })\n \n // Update schedule's last run time\n schedule.lastRunAt = new Date()\n await em.flush()\n \n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n commandId: schedule.targetCommand,\n commandResult: commandResult.result,\n })\n \n logger.debug('Successfully executed command', {\n scheduleId: schedule.id,\n commandId: schedule.targetCommand,\n })\n\n } else {\n throw new Error('Invalid target configuration')\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,mBAAmB;AAC5B,SAAS,0BAA0B;AAEnC,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAE3B,SAAS,0BAA0B;AACnC,SAAS,oCAAoC;AAC7C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,SAAS,CAAC;AAG/D,MAAM,WAAuB;AAAA,EAClC,OAAO;AAAA,EACP,aAAa;AAAA;AACf;AAuCA,eAAO,sBACL,KACA,KACe;AACf,SAAO,MAAM,kBAAkB;AAAA,IAC7B,OAAO,IAAI;AAAA,IACX,eAAe,IAAI;AAAA,EACrB,CAAC;AAGD,QAAM,UAAW,IAAI,WAAY,IAAqD;AAEtF,MAAI,CAAC,WAAW,CAAC,QAAQ,YAAY;AACnC,WAAO,MAAM,2CAA2C,EAAE,OAAO,IAAI,MAAM,CAAC;AAC5E,UAAM,IAAI,MAAM,uCAAuC;AAAA,EACzD;AAEA,QAAM,EAAE,WAAW,IAAI;AAEvB,Q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AAa,SAAS;AAAA,MACtB,YAAY;AAAA,IACd,CAAC;AAAA,EAEH,WAAW,SAAS,eAAe,aAAa,SAAS,eAAe;AACtE,UAAM,aAAa,IAAI,WAAW;AAElC,UAAM,eAAe;AAAA,MACnB,GAAK,SAAS,iBAA6C,CAAC;AAAA,MAC5D,UAAU,SAAS;AAAA,MACnB,gBAAgB,SAAS;AAAA,IAC3B;AAEA,UAAM,aAAa,6BAA6B,UAAU,GAA8B;AAExF,UAAM,gBAAgB,MAAM,WAAW,QAAQ,SAAS,eAAe;AAAA,MACrE,OAAO;AAAA,MACP,KAAK;AAAA,IACP,CAAC;AAGD,aAAS,YAAY,oBAAI,KAAK;AAC9B,UAAM,GAAG,MAAM;AAEf,UAAM,mBAAmB,2BAA2B;AAAA,MAClD,IAAI,SAAS;AAAA,MACb,UAAU,SAAS;AAAA,MACnB,gBAAgB,SAAS;AAAA,MACzB,WAAW,SAAS;AAAA,MACpB,eAAe,cAAc;AAAA,IAC/B,CAAC;AAED,WAAO,MAAM,iCAAiC;AAAA,MAC5C,YAAY,SAAS;AAAA,MACrB,WAAW,SAAS;AAAA,IACtB,CAAC;AAAA,EAEH,OAAO;AACL,UAAM,IAAI,MAAM,8BAA8B;AAAA,EAChD;AACF;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/scheduler",
3
- "version": "0.6.6-develop.6465.1.019f0fb26f",
3
+ "version": "0.6.6-develop.6471.1.9ab5bdd79a",
4
4
  "license": "MIT",
5
5
  "description": "Database-managed scheduled jobs with admin UI",
6
6
  "type": "module",
@@ -59,13 +59,13 @@
59
59
  "./*/*/*/*/*/*.json": "./src/*/*/*/*/*/*.json"
60
60
  },
61
61
  "dependencies": {
62
- "@open-mercato/events": "0.6.6-develop.6465.1.019f0fb26f",
63
- "@open-mercato/queue": "0.6.6-develop.6465.1.019f0fb26f",
62
+ "@open-mercato/events": "0.6.6-develop.6471.1.9ab5bdd79a",
63
+ "@open-mercato/queue": "0.6.6-develop.6471.1.9ab5bdd79a",
64
64
  "cron-parser": "^5.6.1"
65
65
  },
66
66
  "peerDependencies": {
67
67
  "@mikro-orm/core": "^7.0.14",
68
- "@open-mercato/shared": "0.6.6-develop.6465.1.019f0fb26f",
68
+ "@open-mercato/shared": "0.6.6-develop.6471.1.9ab5bdd79a",
69
69
  "bullmq": "^5.0.0",
70
70
  "ioredis": "^5.0.0",
71
71
  "zod": ">=3.23.0"
@@ -79,7 +79,7 @@
79
79
  }
80
80
  },
81
81
  "devDependencies": {
82
- "@open-mercato/shared": "0.6.6-develop.6465.1.019f0fb26f",
82
+ "@open-mercato/shared": "0.6.6-develop.6471.1.9ab5bdd79a",
83
83
  "@types/jest": "^30.0.0",
84
84
  "@types/node": "^26.0.1",
85
85
  "jest": "^30.4.2",
@@ -7,6 +7,9 @@ import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'
7
7
  import { ScheduledJob } from '../../../../data/entities.js'
8
8
  import { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'
9
9
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
10
+ import { createLogger } from '@open-mercato/shared/lib/logger'
11
+
12
+ const logger = createLogger('scheduler').child({ component: 'executions' })
10
13
 
11
14
 
12
15
  export const metadata = {
@@ -143,7 +146,7 @@ export async function GET(
143
146
  }
144
147
 
145
148
  } catch (error: unknown) {
146
- console.error('[scheduler:executions] Error fetching execution history:', error)
149
+ logger.error('Error fetching execution history', { err: error })
147
150
  return NextResponse.json(
148
151
  { error: error instanceof Error ? error.message : translate('scheduler.error.fetch_executions_failed', 'Failed to fetch execution history') },
149
152
  { status: 500 }
@@ -5,6 +5,9 @@ import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'
5
5
  import { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'
6
6
  import { getModules } from '@open-mercato/shared/lib/modules/registry'
7
7
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
8
+ import { createLogger } from '@open-mercato/shared/lib/logger'
9
+
10
+ const logger = createLogger('scheduler').child({ component: 'queue-jobs' })
8
11
 
9
12
 
10
13
  export const metadata = {
@@ -130,7 +133,7 @@ export async function GET(
130
133
  logs: logs.logs || [],
131
134
  })
132
135
  } catch (error: unknown) {
133
- console.error('[scheduler:queue-jobs] Error fetching job:', error)
136
+ logger.error('Error fetching job', { err: error })
134
137
  return NextResponse.json(
135
138
  { error: error instanceof Error ? error.message : translate('scheduler.error.fetch_job_failed', 'Failed to fetch job details') },
136
139
  { status: 500 }
@@ -10,6 +10,9 @@ import { ScheduledJob } from '../../data/entities.js'
10
10
  import { scheduleTriggerSchema } from '../../data/validators.js'
11
11
  import type { ExecuteSchedulePayload } from '../../workers/execute-schedule.worker.js'
12
12
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
13
+ import { createLogger } from '@open-mercato/shared/lib/logger'
14
+
15
+ const logger = createLogger('scheduler').child({ component: 'trigger' })
13
16
 
14
17
  export const metadata = {
15
18
  requireAuth: true,
@@ -94,7 +97,7 @@ export async function POST(req: NextRequest) {
94
97
  const jobId = await executionQueue.enqueue(payload)
95
98
  await executionQueue.close()
96
99
 
97
- console.log('[scheduler:trigger] Manually triggered schedule:', {
100
+ logger.info('Manually triggered schedule', {
98
101
  scheduleId: schedule.id,
99
102
  scheduleName: schedule.name,
100
103
  jobId,
@@ -108,7 +111,7 @@ export async function POST(req: NextRequest) {
108
111
  })
109
112
 
110
113
  } catch (error) {
111
- console.error('[scheduler:trigger] Error:', error)
114
+ logger.error('Manual trigger failed', { err: error })
112
115
  return NextResponse.json(
113
116
  { error: error instanceof Error ? error.message : translate('scheduler.error.trigger_failed', 'Failed to trigger schedule') },
114
117
  { status: 400 }
@@ -4,6 +4,14 @@ import type { EntityManager } from '@mikro-orm/core'
4
4
  import { ScheduledJob } from './data/entities.js'
5
5
  import { parseBooleanToken } from '@open-mercato/shared/lib/boolean'
6
6
 
7
+ const writeLine = (text = '') => {
8
+ process.stdout.write(`${text}\n`)
9
+ }
10
+
11
+ const writeErrorLine = (text: string) => {
12
+ process.stderr.write(`${text}\n`)
13
+ }
14
+
7
15
  function parseArgs(rest: string[]): Record<string, string> {
8
16
  const args: Record<string, string> = {}
9
17
  for (let i = 0; i < rest.length; i += 2) {
@@ -46,13 +54,13 @@ const listCommand: ModuleCli = {
46
54
  })
47
55
 
48
56
  if (jobs.length === 0) {
49
- console.log('No scheduled jobs found.')
57
+ writeLine('No scheduled jobs found.')
50
58
  return
51
59
  }
52
60
 
53
- console.log(`\nFound ${jobs.length} scheduled job(s):\n`)
54
- console.log('ID'.padEnd(38) + 'Name'.padEnd(35) + 'Type'.padEnd(12) + 'Schedule'.padEnd(20) + 'Status'.padEnd(10) + 'Next Run')
55
- console.log('-'.repeat(140))
61
+ writeLine(`\nFound ${jobs.length} scheduled job(s):\n`)
62
+ writeLine('ID'.padEnd(38) + 'Name'.padEnd(35) + 'Type'.padEnd(12) + 'Schedule'.padEnd(20) + 'Status'.padEnd(10) + 'Next Run')
63
+ writeLine('-'.repeat(140))
56
64
 
57
65
  for (const job of jobs) {
58
66
  const id = String(job.id).padEnd(38)
@@ -61,10 +69,10 @@ const listCommand: ModuleCli = {
61
69
  const schedule = (job.scheduleValue || '').substring(0, 18).padEnd(20)
62
70
  const status = (job.isEnabled ? 'āœ“ Enabled' : 'āœ— Disabled').padEnd(10)
63
71
  const nextRun = job.nextRunAt ? new Date(job.nextRunAt).toISOString() : 'N/A'
64
- console.log(`${id}${name}${type}${schedule}${status}${nextRun}`)
72
+ writeLine(`${id}${name}${type}${schedule}${status}${nextRun}`)
65
73
  }
66
74
 
67
- console.log('')
75
+ writeLine('')
68
76
  },
69
77
  }
70
78
 
@@ -84,20 +92,20 @@ const statusCommand: ModuleCli = {
84
92
 
85
93
  const queueStrategy = process.env.QUEUE_STRATEGY || 'local'
86
94
 
87
- console.log('\nšŸ“Š Scheduler Status\n')
88
- console.log('Strategy:', queueStrategy === 'async' ? 'BullMQ (async)' : 'Local (polling)')
95
+ writeLine('\nšŸ“Š Scheduler Status\n')
96
+ writeLine(`Strategy: ${queueStrategy === 'async' ? 'BullMQ (async)' : 'Local (polling)'}`)
89
97
 
90
98
  if (queueStrategy === 'local') {
91
99
  const pollInterval = parseInt(process.env.SCHEDULER_POLL_INTERVAL_MS || '30000', 10)
92
- console.log('Poll Interval:', `${Math.round(pollInterval / 1000)}s`)
100
+ writeLine(`Poll Interval: ${Math.round(pollInterval / 1000)}s`)
93
101
  }
94
102
 
95
- console.log('')
96
- console.log('Schedules:')
97
- console.log(` Total: ${totalCount}`)
98
- console.log(` Enabled: ${enabledCount}`)
99
- console.log(` Due Now: ${dueCount}`)
100
- console.log('')
103
+ writeLine('')
104
+ writeLine('Schedules:')
105
+ writeLine(` Total: ${totalCount}`)
106
+ writeLine(` Enabled: ${enabledCount}`)
107
+ writeLine(` Due Now: ${dueCount}`)
108
+ writeLine('')
101
109
  },
102
110
  }
103
111
 
@@ -106,7 +114,7 @@ const runCommand: ModuleCli = {
106
114
  async run(rest) {
107
115
  const scheduleId = rest[0]
108
116
  if (!scheduleId) {
109
- console.error('Usage: mercato scheduler run <schedule-id>')
117
+ writeErrorLine('Usage: mercato scheduler run <schedule-id>')
110
118
  return
111
119
  }
112
120
 
@@ -116,28 +124,27 @@ const runCommand: ModuleCli = {
116
124
 
117
125
  const job = await em.findOne(ScheduledJob, { id: scheduleId, deletedAt: null })
118
126
  if (!job) {
119
- console.error(`Schedule not found: ${scheduleId}`)
127
+ writeErrorLine(`Schedule not found: ${scheduleId}`)
120
128
  return
121
129
  }
122
130
 
123
- console.log(`\nšŸš€ Manually triggering schedule: ${job.name}\n`)
124
- console.log(` ID: ${job.id}`)
125
- console.log(` Type: ${job.scheduleType}`)
126
- console.log(` Schedule: ${job.scheduleValue}`)
127
- console.log(` Target: ${job.targetType === 'queue' ? job.targetQueue : job.targetCommand}`)
128
- console.log('')
131
+ writeLine(`\nšŸš€ Manually triggering schedule: ${job.name}\n`)
132
+ writeLine(` ID: ${job.id}`)
133
+ writeLine(` Type: ${job.scheduleType}`)
134
+ writeLine(` Schedule: ${job.scheduleValue}`)
135
+ writeLine(` Target: ${job.targetType === 'queue' ? job.targetQueue : job.targetCommand}`)
136
+ writeLine('')
129
137
 
130
138
  try {
131
139
  // Manually enqueue the job (triggering the scheduler-execution worker)
132
140
  const schedulerQueue = queueService.getQueue('scheduler-execution')
133
141
  await schedulerQueue.add('execute-schedule', { scheduleId: job.id })
134
142
 
135
- console.log('āœ“ Job successfully triggered via scheduler-execution queue')
136
- console.log(' The worker will pick it up and enqueue to:',
137
- job.targetType === 'queue' ? job.targetQueue : job.targetCommand)
138
- console.log('āœ“ Manual trigger completed\n')
143
+ writeLine('āœ“ Job successfully triggered via scheduler-execution queue')
144
+ writeLine(` The worker will pick it up and enqueue to: ${job.targetType === 'queue' ? job.targetQueue : job.targetCommand}`)
145
+ writeLine('āœ“ Manual trigger completed\n')
139
146
  } catch (error: unknown) {
140
- console.error('āœ— Failed to trigger job:', error instanceof Error ? error.message : String(error))
147
+ writeErrorLine(`āœ— Failed to trigger job: ${error instanceof Error ? error.message : String(error)}`)
141
148
  process.exit(1)
142
149
  }
143
150
  },
@@ -149,7 +156,7 @@ const startCommand: ModuleCli = {
149
156
  const { resolve } = await createRequestContainer()
150
157
  const queueStrategy = process.env.QUEUE_STRATEGY || 'local'
151
158
 
152
- console.log(`šŸš€ Starting scheduler (strategy: ${queueStrategy})...\n`)
159
+ writeLine(`šŸš€ Starting scheduler (strategy: ${queueStrategy})...\n`)
153
160
 
154
161
  if (queueStrategy === 'async') {
155
162
  // BullMQ strategy: Sync schedules with BullMQ repeatable jobs
@@ -157,22 +164,22 @@ const startCommand: ModuleCli = {
157
164
  const bullmqService = resolve('bullmqSchedulerService') as { syncAll(): Promise<void> } | undefined
158
165
 
159
166
  if (!bullmqService) {
160
- console.error('āŒ BullMQSchedulerService not available.')
161
- console.error(' Set QUEUE_STRATEGY=async and configure REDIS_URL.')
167
+ writeErrorLine('āŒ BullMQSchedulerService not available.')
168
+ writeErrorLine(' Set QUEUE_STRATEGY=async and configure REDIS_URL.')
162
169
  process.exit(1)
163
170
  }
164
171
 
165
172
  // Sync all enabled schedules with BullMQ
166
173
  await bullmqService.syncAll()
167
174
 
168
- console.log('āœ“ Scheduler sync completed')
169
- console.log('')
170
- console.log('BullMQ is managing all schedules.')
171
- console.log('Start workers to process jobs:')
172
- console.log(' yarn mercato worker:start')
173
- console.log('')
175
+ writeLine('āœ“ Scheduler sync completed')
176
+ writeLine('')
177
+ writeLine('BullMQ is managing all schedules.')
178
+ writeLine('Start workers to process jobs:')
179
+ writeLine(' yarn mercato worker:start')
180
+ writeLine('')
174
181
  } catch (error: unknown) {
175
- console.error('āŒ Failed to sync schedules:', error instanceof Error ? error.message : String(error))
182
+ writeErrorLine(`āŒ Failed to sync schedules: ${error instanceof Error ? error.message : String(error)}`)
176
183
  process.exit(1)
177
184
  }
178
185
  } else {
@@ -181,8 +188,8 @@ const startCommand: ModuleCli = {
181
188
  const localService = resolve('localSchedulerService') as { start(): Promise<void>; stop(): Promise<void> } | undefined
182
189
 
183
190
  if (!localService) {
184
- console.error('āŒ LocalSchedulerService not available.')
185
- console.error(' This should not happen in local mode.')
191
+ writeErrorLine('āŒ LocalSchedulerService not available.')
192
+ writeErrorLine(' This should not happen in local mode.')
186
193
  process.exit(1)
187
194
  }
188
195
 
@@ -191,17 +198,17 @@ const startCommand: ModuleCli = {
191
198
  // Start the local polling engine
192
199
  await localService.start()
193
200
 
194
- console.log('āœ“ Local scheduler started (polling every', Math.round(pollInterval / 1000), 'seconds)')
195
- console.log('Press Ctrl+C to stop.')
196
- console.log('')
197
- console.log('šŸ’” Tip: For production, use QUEUE_STRATEGY=async with Redis.')
198
- console.log('')
201
+ writeLine(`āœ“ Local scheduler started (polling every ${Math.round(pollInterval / 1000)} seconds)`)
202
+ writeLine('Press Ctrl+C to stop.')
203
+ writeLine('')
204
+ writeLine('šŸ’” Tip: For production, use QUEUE_STRATEGY=async with Redis.')
205
+ writeLine('')
199
206
 
200
207
  // Keep the process alive and handle graceful shutdown
201
208
  const gracefulShutdown = async () => {
202
- console.log('\nšŸ“› Shutting down...')
209
+ writeLine('\nšŸ“› Shutting down...')
203
210
  await localService.stop()
204
- console.log('āœ“ Stopped')
211
+ writeLine('āœ“ Stopped')
205
212
  process.exit(0)
206
213
  }
207
214
 
@@ -211,7 +218,7 @@ const startCommand: ModuleCli = {
211
218
  // Keep process alive
212
219
  await new Promise(() => {}) // Never resolves
213
220
  } catch (error: unknown) {
214
- console.error('āŒ Failed to start local scheduler:', error instanceof Error ? error.message : String(error))
221
+ writeErrorLine(`āŒ Failed to start local scheduler: ${error instanceof Error ? error.message : String(error)}`)
215
222
  process.exit(1)
216
223
  }
217
224
  }
@@ -1,5 +1,8 @@
1
1
  import { registerCommand } from '@open-mercato/shared/lib/commands'
2
2
  import type { CommandHandler } from '@open-mercato/shared/lib/commands'
3
+ import { createLogger } from '@open-mercato/shared/lib/logger'
4
+
5
+ const logger = createLogger('scheduler').child({ component: 'test-echo' })
3
6
 
4
7
  /**
5
8
  * A simple test command that prints its arguments and returns them.
@@ -16,8 +19,7 @@ const testEchoCommand: CommandHandler<Record<string, unknown>, { echoed: Record<
16
19
  async execute(input) {
17
20
  const timestamp = new Date().toISOString()
18
21
 
19
- console.log(`[scheduler:test-echo] Received args at ${timestamp}:`)
20
- console.log(JSON.stringify(input, null, 2))
22
+ logger.info('Echo command received', { timestamp, input })
21
23
 
22
24
  return { echoed: input, timestamp }
23
25
  },