@open-mercato/scheduler 0.6.7-develop.6862.1.c11a64ce0a → 0.6.7

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 (67) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/scheduler/__integration__/TC-SCHED-007.spec.js +1 -4
  3. package/dist/modules/scheduler/__integration__/TC-SCHED-007.spec.js.map +2 -2
  4. package/dist/modules/scheduler/api/jobs/[id]/executions/route.js +2 -4
  5. package/dist/modules/scheduler/api/jobs/[id]/executions/route.js.map +2 -2
  6. package/dist/modules/scheduler/api/queue-jobs/[jobId]/route.js +2 -4
  7. package/dist/modules/scheduler/api/queue-jobs/[jobId]/route.js.map +2 -2
  8. package/dist/modules/scheduler/api/targets/route.js +4 -5
  9. package/dist/modules/scheduler/api/targets/route.js.map +2 -2
  10. package/dist/modules/scheduler/commands/jobs.js +14 -33
  11. package/dist/modules/scheduler/commands/jobs.js.map +2 -2
  12. package/dist/modules/scheduler/data/validators.js +1 -27
  13. package/dist/modules/scheduler/data/validators.js.map +2 -2
  14. package/dist/modules/scheduler/i18n/de.json +0 -2
  15. package/dist/modules/scheduler/i18n/en.json +0 -2
  16. package/dist/modules/scheduler/i18n/es.json +0 -2
  17. package/dist/modules/scheduler/i18n/pl.json +0 -2
  18. package/dist/modules/scheduler/lib/intervalParser.js +3 -8
  19. package/dist/modules/scheduler/lib/intervalParser.js.map +2 -2
  20. package/dist/modules/scheduler/lib/localLockStrategy.js +45 -23
  21. package/dist/modules/scheduler/lib/localLockStrategy.js.map +2 -2
  22. package/dist/modules/scheduler/lib/nextRunCalculator.js +1 -8
  23. package/dist/modules/scheduler/lib/nextRunCalculator.js.map +2 -2
  24. package/dist/modules/scheduler/services/bullmqSchedulerService.js +43 -92
  25. package/dist/modules/scheduler/services/bullmqSchedulerService.js.map +2 -2
  26. package/dist/modules/scheduler/services/localSchedulerService.js +3 -9
  27. package/dist/modules/scheduler/services/localSchedulerService.js.map +2 -2
  28. package/dist/modules/scheduler/services/schedulerService.js +11 -23
  29. package/dist/modules/scheduler/services/schedulerService.js.map +2 -2
  30. package/dist/modules/scheduler/workers/execute-schedule.worker.js +0 -9
  31. package/dist/modules/scheduler/workers/execute-schedule.worker.js.map +2 -2
  32. package/package.json +9 -10
  33. package/src/modules/scheduler/__integration__/TC-SCHED-007.spec.ts +4 -6
  34. package/src/modules/scheduler/api/jobs/[id]/executions/route.ts +2 -4
  35. package/src/modules/scheduler/api/queue-jobs/[jobId]/route.ts +2 -4
  36. package/src/modules/scheduler/api/targets/route.ts +7 -7
  37. package/src/modules/scheduler/commands/jobs.ts +15 -40
  38. package/src/modules/scheduler/data/__tests__/validators.test.ts +9 -69
  39. package/src/modules/scheduler/data/validators.ts +1 -30
  40. package/src/modules/scheduler/i18n/de.json +0 -2
  41. package/src/modules/scheduler/i18n/en.json +0 -2
  42. package/src/modules/scheduler/i18n/es.json +0 -2
  43. package/src/modules/scheduler/i18n/pl.json +0 -2
  44. package/src/modules/scheduler/lib/__tests__/intervalParser.test.ts +9 -27
  45. package/src/modules/scheduler/lib/__tests__/localLockStrategy.test.ts +106 -0
  46. package/src/modules/scheduler/lib/__tests__/nextRunCalculator.test.ts +7 -18
  47. package/src/modules/scheduler/lib/intervalParser.ts +3 -8
  48. package/src/modules/scheduler/lib/localLockStrategy.ts +60 -26
  49. package/src/modules/scheduler/lib/nextRunCalculator.ts +1 -14
  50. package/src/modules/scheduler/services/__tests__/bullmqSchedulerService.test.ts +149 -246
  51. package/src/modules/scheduler/services/__tests__/localSchedulerService.test.ts +11 -97
  52. package/src/modules/scheduler/services/__tests__/schedulerService.test.ts +0 -101
  53. package/src/modules/scheduler/services/bullmqSchedulerService.ts +49 -135
  54. package/src/modules/scheduler/services/localSchedulerService.ts +11 -14
  55. package/src/modules/scheduler/services/schedulerService.ts +12 -27
  56. package/src/modules/scheduler/workers/__tests__/execute-schedule.worker.test.ts +0 -12
  57. package/src/modules/scheduler/workers/execute-schedule.worker.ts +0 -15
  58. package/dist/modules/scheduler/i18n/ko.json +0 -157
  59. package/dist/modules/scheduler/lib/activeScheduleLimits.js +0 -44
  60. package/dist/modules/scheduler/lib/activeScheduleLimits.js.map +0 -7
  61. package/dist/modules/scheduler/lib/scheduler-safe-commands.js +0 -73
  62. package/dist/modules/scheduler/lib/scheduler-safe-commands.js.map +0 -7
  63. package/src/modules/scheduler/api/targets/__tests__/route.test.ts +0 -76
  64. package/src/modules/scheduler/commands/__tests__/jobs.active-limit.test.ts +0 -184
  65. package/src/modules/scheduler/i18n/ko.json +0 -157
  66. package/src/modules/scheduler/lib/activeScheduleLimits.ts +0 -48
  67. package/src/modules/scheduler/lib/scheduler-safe-commands.ts +0 -98
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/scheduler/services/bullmqSchedulerService.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { recalculateNextRun } from '../lib/nextRunCalculator'\nimport { parseCronExpression } from '../lib/cronParser'\nimport { resolveScheduleIntervalMs } from '../lib/intervalParser'\nimport { getRedisUrlOrThrow, parseRedisUrl } from '@open-mercato/shared/lib/redis/connection'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'bullmq' })\n\ninterface BullJobScheduler {\n key: string\n name: string\n id?: string | null\n}\n\ninterface BullRepeatableJob {\n key: string\n name: string\n id?: string | null\n}\n\ninterface BullRepeatOptions {\n tz?: string\n pattern?: string\n every?: number\n}\n\ninterface BullQueue {\n add(name: string, data: unknown, opts?: Record<string, unknown>): Promise<unknown>\n getRepeatableJobs?(): Promise<BullRepeatableJob[]>\n removeRepeatableByKey?(key: string): Promise<boolean>\n upsertJobScheduler?(\n id: string,\n repeatOptions: BullRepeatOptions,\n jobTemplate: { name: string; data: unknown; opts: Record<string, unknown> },\n ): Promise<unknown>\n getJobSchedulers?(): Promise<BullJobScheduler[]>\n removeJobScheduler?(id: string): Promise<boolean>\n close(): Promise<void>\n}\n\ntype BullJobSchedulerQueue = BullQueue & Required<Pick<\n BullQueue,\n 'upsertJobScheduler' | 'getJobSchedulers' | 'removeJobScheduler'\n>>\n\n/**\n * Production scheduler using BullMQ Job Schedulers.\n * \n * Requires Redis. Set QUEUE_STRATEGY=async to use this service.\n * \n * This service syncs database schedules with BullMQ's Job Scheduler mechanism.\n * When a schedule is created/updated/deleted in the database, this service\n * adds/updates/removes the corresponding BullMQ Job Scheduler.\n * \n * BullMQ handles:\n * - Exact timing based on cron expressions or intervals\n * - Distributed locking across multiple instances\n * - Automatic retries if worker fails\n * \n * The worker loads fresh schedule config from DB on each execution,\n * so updates to schedules take effect immediately.\n */\nexport class BullMQSchedulerService {\n private queue: BullQueue | null = null\n \n constructor(\n private em: () => EntityManager,\n ) {}\n\n /**\n * Lazy-load and return the BullMQ queue instance\n */\n private async getQueue(): Promise<BullQueue> {\n if (!this.queue) {\n try {\n const { Queue } = await import('bullmq')\n this.queue = new Queue('scheduler-execution', {\n connection: parseRedisUrl(getRedisUrlOrThrow('QUEUE')),\n })\n } catch {\n throw new Error('BullMQ is required for async scheduler. Install it with: npm install bullmq')\n }\n }\n return this.queue\n }\n\n private getScheduleJobName(scheduleId: string): string {\n return `schedule-${scheduleId}`\n }\n\n private getScheduleIdFromJobScheduler(job: BullJobScheduler): string | null {\n const candidate = [job.key, job.id, job.name]\n .find((value) => value?.startsWith('schedule-'))\n\n return candidate ? candidate.slice('schedule-'.length) : null\n }\n\n private isJobSchedulerForSchedule(job: BullJobScheduler, scheduleId: string): boolean {\n return this.getScheduleIdFromJobScheduler(job) === scheduleId\n }\n\n private isCanonicalJobScheduler(job: BullJobScheduler, scheduleId: string): boolean {\n return job.key === this.getScheduleJobName(scheduleId)\n }\n\n private supportsJobSchedulers(queue: BullQueue): queue is BullJobSchedulerQueue {\n return typeof queue.upsertJobScheduler === 'function'\n && typeof queue.getJobSchedulers === 'function'\n && typeof queue.removeJobScheduler === 'function'\n }\n\n private isRepeatableJobForSchedule(job: BullRepeatableJob, scheduleId: string): boolean {\n const jobName = this.getScheduleJobName(scheduleId)\n return job.id === jobName || job.name === jobName\n }\n\n private async removeLegacyRepeatableJobs(queue: BullQueue, scheduleId: string): Promise<number> {\n const repeatableJobs = await queue.getRepeatableJobs?.()\n if (!repeatableJobs || typeof queue.removeRepeatableByKey !== 'function') {\n return 0\n }\n\n let removed = 0\n for (const job of repeatableJobs) {\n if (!this.isRepeatableJobForSchedule(job, scheduleId)) continue\n await queue.removeRepeatableByKey(job.key)\n removed += 1\n }\n return removed\n }\n\n /**\n * Register a schedule with BullMQ Job Schedulers\n * @param schedule - The schedule to register\n * @param options - Optional configuration\n * @param options.skipNextRunUpdate - If true, skip updating nextRunAt (used when called from hooks)\n */\n async register(schedule: ScheduledJob, options: { skipNextRunUpdate?: boolean } = {}): Promise<void> {\n if (!schedule.isEnabled) {\n logger.debug('Skipping disabled schedule', { scheduleId: schedule.id })\n return\n }\n\n try {\n // Calculate and update next run time (unless skipped)\n if (!options.skipNextRunUpdate) {\n const nextRun = recalculateNextRun(\n schedule.scheduleType,\n schedule.scheduleValue,\n schedule.timezone\n )\n \n if (nextRun) {\n schedule.nextRunAt = nextRun\n // Flush will be handled by the caller\n }\n }\n\n // Build BullMQ repeat options based on schedule type\n const repeatOpts = this.buildRepeatOptions(schedule)\n\n // Upsert the BullMQ Job Scheduler\n // IMPORTANT: Wrap in QueuedJob format to match queue strategy expectations\n // BullMQ will store this in job.data, and the async strategy worker expects\n // job.data to be a QueuedJob with id, payload, and createdAt\n const queue = await this.getQueue()\n const jobName = this.getScheduleJobName(schedule.id)\n \n // Job Scheduler instances use a stable ID in the data\n // that will be used for each repeat instance\n // CRITICAL: Include scope information (tenantId, organizationId, scopeType)\n // for proper multi-tenant isolation and auditing\n const jobData = {\n id: jobName,\n payload: { \n scheduleId: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scopeType: schedule.scopeType,\n },\n createdAt: new Date().toISOString(),\n }\n \n logger.debug('Upserting job scheduler', {\n jobName,\n scheduleId: schedule.id,\n scopeType: schedule.scopeType,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n repeatOpts,\n })\n \n const jobOptions = {\n removeOnComplete: {\n age: 86400 * 30,\n count: 1000,\n },\n removeOnFail: {\n age: 86400 * 90,\n count: 5000,\n },\n }\n\n if (this.supportsJobSchedulers(queue)) {\n const existingJobSchedulers = await queue.getJobSchedulers()\n await queue.upsertJobScheduler(\n jobName,\n repeatOpts,\n {\n name: jobName,\n data: jobData,\n opts: jobOptions,\n },\n )\n for (const jobScheduler of existingJobSchedulers) {\n if (\n this.isJobSchedulerForSchedule(jobScheduler, schedule.id)\n && !this.isCanonicalJobScheduler(jobScheduler, schedule.id)\n ) {\n await queue.removeJobScheduler(jobScheduler.key)\n }\n }\n } else {\n await this.removeLegacyRepeatableJobs(queue, schedule.id)\n await queue.add(jobName, jobData, { repeat: repeatOpts, ...jobOptions })\n }\n\n logger.debug('Registered schedule', {\n scheduleId: schedule.id,\n scheduleName: schedule.name,\n type: schedule.scheduleType,\n pattern: schedule.scheduleValue,\n timezone: schedule.timezone,\n })\n } catch (error: unknown) {\n logger.error('Failed to register schedule', { scheduleId: schedule.id, err: error })\n throw error\n }\n }\n\n /**\n * Unregister a schedule from BullMQ Job Schedulers\n */\n async unregister(scheduleId: string): Promise<void> {\n try {\n const queue = await this.getQueue()\n if (this.supportsJobSchedulers(queue)) {\n const jobSchedulers = await queue.getJobSchedulers()\n const matchingJobSchedulers = jobSchedulers.filter((job) => (\n this.isJobSchedulerForSchedule(job, scheduleId)\n ))\n if (matchingJobSchedulers.length > 0) {\n for (const jobScheduler of matchingJobSchedulers) {\n await queue.removeJobScheduler(jobScheduler.key)\n }\n logger.debug('Unregistered schedule', { scheduleId })\n } else {\n logger.debug('No job scheduler found for schedule', { scheduleId })\n }\n return\n }\n\n const removed = await this.removeLegacyRepeatableJobs(queue, scheduleId)\n if (removed > 0) {\n logger.debug('Unregistered schedule', { scheduleId })\n } else {\n logger.debug('No repeatable job found for schedule', { scheduleId })\n }\n } catch (error: unknown) {\n logger.error('Failed to unregister schedule', { scheduleId, err: error })\n throw error\n }\n }\n\n /**\n * Sync all enabled schedules with BullMQ\n * Useful for initialization or repair\n */\n async syncAll(): Promise<void> {\n const em = this.em().fork()\n const queue = await this.getQueue()\n \n logger.debug('Starting full sync')\n\n const bullmqScheduleIds = new Set<string>()\n const bullmqScheduleCounts = new Map<string, number>()\n const canonicalJobSchedulerIds = new Set<string>()\n if (this.supportsJobSchedulers(queue)) {\n const jobSchedulers = await queue.getJobSchedulers()\n for (const job of jobSchedulers) {\n const scheduleId = this.getScheduleIdFromJobScheduler(job)\n if (!scheduleId) continue\n bullmqScheduleIds.add(scheduleId)\n bullmqScheduleCounts.set(scheduleId, (bullmqScheduleCounts.get(scheduleId) ?? 0) + 1)\n if (this.isCanonicalJobScheduler(job, scheduleId)) {\n canonicalJobSchedulerIds.add(scheduleId)\n }\n }\n } else {\n const repeatableJobs = await queue.getRepeatableJobs?.() ?? []\n for (const job of repeatableJobs) {\n const candidate = job.id?.startsWith('schedule-')\n ? job.id\n : job.name?.startsWith('schedule-')\n ? job.name\n : null\n if (!candidate) continue\n const scheduleId = candidate.slice('schedule-'.length)\n bullmqScheduleIds.add(scheduleId)\n bullmqScheduleCounts.set(scheduleId, (bullmqScheduleCounts.get(scheduleId) ?? 0) + 1)\n }\n }\n\n // Get enabled schedules from database in batches to avoid unbounded loads\n const BATCH_SIZE = 500\n const dbSchedules: ScheduledJob[] = []\n let offset = 0\n let batch: ScheduledJob[]\n do {\n batch = await em.find(ScheduledJob, {\n isEnabled: true,\n deletedAt: null,\n }, { limit: BATCH_SIZE, offset })\n dbSchedules.push(...batch)\n offset += BATCH_SIZE\n } while (batch.length === BATCH_SIZE)\n\n const dbScheduleIds = new Set(dbSchedules.map(s => s.id))\n\n // Register schedules that exist in DB but not in BullMQ\n for (const schedule of dbSchedules) {\n if (!bullmqScheduleIds.has(schedule.id)) {\n logger.debug('Registering missing schedule', { scheduleId: schedule.id, scheduleName: schedule.name })\n await this.register(schedule)\n } else if (\n (bullmqScheduleCounts.get(schedule.id) ?? 0) > 1\n || !canonicalJobSchedulerIds.has(schedule.id)\n ) {\n logger.info('Migrating legacy or duplicate job scheduler', { scheduleId: schedule.id })\n await this.register(schedule)\n }\n }\n\n // Remove BullMQ jobs that don't exist in DB or are disabled\n for (const scheduleId of bullmqScheduleIds) {\n if (!dbScheduleIds.has(scheduleId)) {\n logger.info('Removing orphaned schedule', { scheduleId })\n await this.unregister(String(scheduleId))\n }\n }\n\n logger.debug('Sync complete', { activeSchedules: dbSchedules.length })\n }\n\n /**\n * Build BullMQ repeat options from schedule configuration\n */\n private buildRepeatOptions(schedule: ScheduledJob): BullRepeatOptions {\n const opts: BullRepeatOptions = {\n tz: schedule.timezone || 'UTC',\n }\n\n if (schedule.scheduleType === 'cron') {\n // Validate cron expression\n const parsedCron = parseCronExpression(schedule.scheduleValue, schedule.timezone || 'UTC')\n if (!parsedCron.isValid) {\n throw new Error(parsedCron.error || 'Invalid cron expression')\n }\n opts.pattern = schedule.scheduleValue\n } else if (schedule.scheduleType === 'interval') {\n // Parse interval (e.g., \"15m\", \"2h\", \"1d\")\n const intervalMs = resolveScheduleIntervalMs(schedule.scheduleValue)\n opts.every = intervalMs\n } else {\n throw new Error(`Unsupported schedule type: ${schedule.scheduleType}`)\n }\n\n return opts\n }\n\n /**\n * Get list of all scheduled jobs from BullMQ\n */\n async getRepeatableJobs(): Promise<unknown[]> {\n try {\n const queue = await this.getQueue()\n if (this.supportsJobSchedulers(queue)) {\n return await queue.getJobSchedulers()\n }\n return await queue.getRepeatableJobs?.() ?? []\n } catch (error) {\n logger.error('Failed to get job schedulers', { err: error })\n return []\n }\n }\n\n /**\n * Close the cached BullMQ queue connection.\n * Must be called during graceful shutdown to prevent Redis connection leaks.\n */\n async destroy(): Promise<void> {\n if (this.queue) {\n try {\n await this.queue.close()\n this.queue = null\n logger.debug('Queue connection closed')\n } catch (error) {\n logger.error('Error closing queue', { err: error })\n }\n }\n }\n}\n"],
5
- "mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AACpC,SAAS,iCAAiC;AAC1C,SAAS,oBAAoB,qBAAqB;AAClD,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,SAAS,CAAC;AAwD/D,MAAM,uBAAuB;AAAA,EAGlC,YACU,IACR;AADQ;AAHV,SAAQ,QAA0B;AAAA,EAI/B;AAAA;AAAA;AAAA;AAAA,EAKH,MAAc,WAA+B;AAC3C,QAAI,CAAC,KAAK,OAAO;AACf,UAAI;AACF,cAAM,EAAE,MAAM,IAAI,MAAM,OAAO,QAAQ;AACvC,aAAK,QAAQ,IAAI,MAAM,uBAAuB;AAAA,UAC5C,YAAY,cAAc,mBAAmB,OAAO,CAAC;AAAA,QACvD,CAAC;AAAA,MACH,QAAQ;AACN,cAAM,IAAI,MAAM,6EAA6E;AAAA,MAC/F;AAAA,IACF;AACA,WAAO,KAAK;AAAA,EACd;AAAA,EAEQ,mBAAmB,YAA4B;AACrD,WAAO,YAAY,UAAU;AAAA,EAC/B;AAAA,EAEQ,8BAA8B,KAAsC;AAC1E,UAAM,YAAY,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,IAAI,EACzC,KAAK,CAAC,UAAU,OAAO,WAAW,WAAW,CAAC;AAEjD,WAAO,YAAY,UAAU,MAAM,YAAY,MAAM,IAAI;AAAA,EAC3D;AAAA,EAEQ,0BAA0B,KAAuB,YAA6B;AACpF,WAAO,KAAK,8BAA8B,GAAG,MAAM;AAAA,EACrD;AAAA,EAEQ,wBAAwB,KAAuB,YAA6B;AAClF,WAAO,IAAI,QAAQ,KAAK,mBAAmB,UAAU;AAAA,EACvD;AAAA,EAEQ,sBAAsB,OAAkD;AAC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AO;AACd,UAAI;AACF,cAAM,KAAK,MAAM,MAAM;AACvB,aAAK,QAAQ;AACb,eAAO,MAAM,yBAAyB;AAAA,MACxC,SAAS,OAAO;AACd,eAAO,MAAM,uBAAuB,EAAE,KAAK,MAAM,CAAC;AAAA,MACpD;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { recalculateNextRun } from '../lib/nextRunCalculator'\nimport { parseCronExpression } from '../lib/cronParser'\nimport { parseInterval } from '../lib/intervalParser'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'bullmq' })\n\ninterface BullRepeatableJob {\n key: string\n name: string\n id?: string | null\n}\n\ninterface BullRepeatOptions {\n tz?: string\n pattern?: string\n every?: number\n}\n\ninterface BullQueue {\n add(name: string, data: unknown, opts?: unknown): Promise<unknown>\n getRepeatableJobs?(): Promise<BullRepeatableJob[]>\n removeRepeatableByKey?(key: string): Promise<boolean>\n close(): Promise<void>\n}\n\n/**\n * Production scheduler using BullMQ repeatable jobs.\n * \n * Requires Redis. Set QUEUE_STRATEGY=async to use this service.\n * \n * This service syncs database schedules with BullMQ's repeat mechanism.\n * When a schedule is created/updated/deleted in the database, this service\n * adds/updates/removes the corresponding BullMQ repeatable job.\n * \n * BullMQ handles:\n * - Exact timing based on cron expressions or intervals\n * - Distributed locking across multiple instances\n * - Automatic retries if worker fails\n * \n * The worker loads fresh schedule config from DB on each execution,\n * so updates to schedules take effect immediately.\n */\nexport class BullMQSchedulerService {\n private queue: BullQueue | null = null\n \n constructor(\n private em: () => EntityManager,\n ) {}\n\n /**\n * Lazy-load and return the BullMQ queue instance\n */\n private async getQueue(): Promise<BullQueue> {\n if (!this.queue) {\n try {\n const { Queue } = await import('bullmq')\n this.queue = new Queue('scheduler-execution', { connection: { url: getRedisUrlOrThrow('QUEUE') } })\n } catch {\n throw new Error('BullMQ is required for async scheduler. Install it with: npm install bullmq')\n }\n }\n return this.queue\n }\n\n private getScheduleJobName(scheduleId: string): string {\n return `schedule-${scheduleId}`\n }\n\n private getScheduleIdFromRepeatableJob(job: BullRepeatableJob): string | null {\n const candidate = job.id?.startsWith('schedule-')\n ? job.id\n : job.name?.startsWith('schedule-')\n ? job.name\n : null\n\n return candidate ? candidate.slice('schedule-'.length) : null\n }\n\n private isRepeatableJobForSchedule(job: BullRepeatableJob, scheduleId: string): boolean {\n const jobName = this.getScheduleJobName(scheduleId)\n return job.id === jobName || job.name === jobName\n }\n\n private async removeRepeatableJobsForSchedule(queue: BullQueue, scheduleId: string): Promise<number> {\n const repeatableJobs = await queue.getRepeatableJobs?.()\n if (!repeatableJobs || typeof queue.removeRepeatableByKey !== 'function') {\n return 0\n }\n\n let removed = 0\n for (const job of repeatableJobs) {\n if (!this.isRepeatableJobForSchedule(job, scheduleId)) continue\n await queue.removeRepeatableByKey(job.key)\n removed += 1\n }\n\n return removed\n }\n\n /**\n * Register a schedule with BullMQ repeatable jobs\n * @param schedule - The schedule to register\n * @param options - Optional configuration\n * @param options.skipNextRunUpdate - If true, skip updating nextRunAt (used when called from hooks)\n */\n async register(schedule: ScheduledJob, options: { skipNextRunUpdate?: boolean } = {}): Promise<void> {\n if (!schedule.isEnabled) {\n logger.debug('Skipping disabled schedule', { scheduleId: schedule.id })\n return\n }\n\n try {\n // Calculate and update next run time (unless skipped)\n if (!options.skipNextRunUpdate) {\n const nextRun = recalculateNextRun(\n schedule.scheduleType,\n schedule.scheduleValue,\n schedule.timezone\n )\n \n if (nextRun) {\n schedule.nextRunAt = nextRun\n // Flush will be handled by the caller\n }\n }\n\n // Build BullMQ repeat options based on schedule type\n const repeatOpts = this.buildRepeatOptions(schedule)\n\n // Add repeatable job to BullMQ\n // IMPORTANT: Wrap in QueuedJob format to match queue strategy expectations\n // BullMQ will store this in job.data, and the async strategy worker expects\n // job.data to be a QueuedJob with id, payload, and createdAt\n const queue = await this.getQueue()\n const jobName = this.getScheduleJobName(schedule.id)\n await this.removeRepeatableJobsForSchedule(queue, schedule.id)\n \n // For repeatable jobs, we need to provide a stable ID in the data\n // that will be used for each repeat instance\n // CRITICAL: Include scope information (tenantId, organizationId, scopeType)\n // for proper multi-tenant isolation and auditing\n const jobData = {\n id: jobName,\n payload: { \n scheduleId: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scopeType: schedule.scopeType,\n },\n createdAt: new Date().toISOString(),\n }\n \n logger.debug('Adding repeatable job', {\n jobName,\n scheduleId: schedule.id,\n scopeType: schedule.scopeType,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n repeatOpts,\n })\n \n await queue.add(\n jobName, // Job name - used as part of repeatable job key\n jobData, // Job data in QueuedJob format\n {\n repeat: repeatOpts,\n // Don't set jobId for repeatable jobs - BullMQ generates unique IDs for each instance\n removeOnComplete: {\n age: 86400 * 30, // Keep completed jobs for 30 days (execution history)\n count: 1000, // Keep last 1000 completed jobs\n },\n removeOnFail: {\n age: 86400 * 90, // Keep failed jobs for 90 days (debugging/audit)\n count: 5000, // Keep last 5000 failed jobs\n },\n }\n )\n\n logger.debug('Registered schedule', {\n scheduleId: schedule.id,\n scheduleName: schedule.name,\n type: schedule.scheduleType,\n pattern: schedule.scheduleValue,\n timezone: schedule.timezone,\n })\n } catch (error: unknown) {\n logger.error('Failed to register schedule', { scheduleId: schedule.id, err: error })\n throw error\n }\n }\n\n /**\n * Unregister a schedule from BullMQ repeatable jobs\n */\n async unregister(scheduleId: string): Promise<void> {\n try {\n const queue = await this.getQueue()\n\n const removed = await this.removeRepeatableJobsForSchedule(queue, scheduleId)\n if (removed > 0) {\n logger.debug('Unregistered schedule', { scheduleId })\n } else {\n logger.debug('No repeatable job found for schedule', { scheduleId })\n }\n } catch (error: unknown) {\n logger.error('Failed to unregister schedule', { scheduleId, err: error })\n throw error\n }\n }\n\n /**\n * Sync all enabled schedules with BullMQ\n * Useful for initialization or repair\n */\n async syncAll(): Promise<void> {\n const em = this.em().fork()\n const queue = await this.getQueue()\n \n logger.debug('Starting full sync')\n\n // Get all BullMQ repeatable jobs\n const repeatableJobs = await queue.getRepeatableJobs?.() || []\n const bullmqScheduleIds = new Set<string>()\n const bullmqScheduleCounts = new Map<string, number>()\n for (const job of repeatableJobs) {\n const scheduleId = this.getScheduleIdFromRepeatableJob(job)\n if (!scheduleId) continue\n bullmqScheduleIds.add(scheduleId)\n bullmqScheduleCounts.set(scheduleId, (bullmqScheduleCounts.get(scheduleId) ?? 0) + 1)\n }\n\n // Get enabled schedules from database in batches to avoid unbounded loads\n const BATCH_SIZE = 500\n const dbSchedules: ScheduledJob[] = []\n let offset = 0\n let batch: ScheduledJob[]\n do {\n batch = await em.find(ScheduledJob, {\n isEnabled: true,\n deletedAt: null,\n }, { limit: BATCH_SIZE, offset })\n dbSchedules.push(...batch)\n offset += BATCH_SIZE\n } while (batch.length === BATCH_SIZE)\n\n const dbScheduleIds = new Set(dbSchedules.map(s => s.id))\n\n // Register schedules that exist in DB but not in BullMQ\n for (const schedule of dbSchedules) {\n if (!bullmqScheduleIds.has(schedule.id)) {\n logger.debug('Registering missing schedule', { scheduleId: schedule.id, scheduleName: schedule.name })\n await this.register(schedule)\n } else if ((bullmqScheduleCounts.get(schedule.id) ?? 0) > 1) {\n logger.info('Repairing duplicate repeatable jobs', { scheduleId: schedule.id })\n await this.register(schedule)\n }\n }\n\n // Remove BullMQ jobs that don't exist in DB or are disabled\n for (const scheduleId of bullmqScheduleIds) {\n if (!dbScheduleIds.has(scheduleId)) {\n logger.info('Removing orphaned schedule', { scheduleId })\n await this.unregister(String(scheduleId))\n }\n }\n\n logger.debug('Sync complete', { activeSchedules: dbSchedules.length })\n }\n\n /**\n * Build BullMQ repeat options from schedule configuration\n */\n private buildRepeatOptions(schedule: ScheduledJob): BullRepeatOptions {\n const opts: BullRepeatOptions = {\n tz: schedule.timezone || 'UTC',\n }\n\n if (schedule.scheduleType === 'cron') {\n // Validate cron expression\n const parsedCron = parseCronExpression(schedule.scheduleValue, schedule.timezone || 'UTC')\n if (!parsedCron.isValid) {\n throw new Error(parsedCron.error || 'Invalid cron expression')\n }\n opts.pattern = schedule.scheduleValue\n } else if (schedule.scheduleType === 'interval') {\n // Parse interval (e.g., \"15m\", \"2h\", \"1d\")\n const intervalMs = parseInterval(schedule.scheduleValue)\n opts.every = intervalMs\n } else {\n throw new Error(`Unsupported schedule type: ${schedule.scheduleType}`)\n }\n\n return opts\n }\n\n /**\n * Get list of all repeatable jobs from BullMQ\n */\n async getRepeatableJobs(): Promise<unknown[]> {\n try {\n const queue = await this.getQueue()\n return await queue.getRepeatableJobs?.() || []\n } catch (error) {\n logger.error('Failed to get repeatable jobs', { err: error })\n return []\n }\n }\n\n /**\n * Close the cached BullMQ queue connection.\n * Must be called during graceful shutdown to prevent Redis connection leaks.\n */\n async destroy(): Promise<void> {\n if (this.queue) {\n try {\n await this.queue.close()\n this.queue = null\n logger.debug('Queue connection closed')\n } catch (error) {\n logger.error('Error closing queue', { err: error })\n }\n }\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AACpC,SAAS,qBAAqB;AAC9B,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,SAAS,CAAC;AAsC/D,MAAM,uBAAuB;AAAA,EAGlC,YACU,IACR;AADQ;AAHV,SAAQ,QAA0B;AAAA,EAI/B;AAAA;AAAA;AAAA;AAAA,EAKH,MAAc,WAA+B;AAC3C,QAAI,CAAC,KAAK,OAAO;AACf,UAAI;AACF,cAAM,EAAE,MAAM,IAAI,MAAM,OAAO,QAAQ;AACvC,aAAK,QAAQ,IAAI,MAAM,uBAAuB,EAAE,YAAY,EAAE,KAAK,mBAAmB,OAAO,EAAE,EAAE,CAAC;AAAA,MACpG,QAAQ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AA;AAAA,EAMA,MAAM,UAAyB;AAC7B,QAAI,KAAK,OAAO;AACd,UAAI;AACF,cAAM,KAAK,MAAM,MAAM;AACvB,aAAK,QAAQ;AACb,eAAO,MAAM,yBAAyB;AAAA,MACxC,SAAS,OAAO;AACd,eAAO,MAAM,uBAAuB,EAAE,KAAK,MAAM,CAAC;AAAA,MACpD;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -4,7 +4,6 @@ import { LocalLockStrategy } from "../lib/localLockStrategy.js";
4
4
  import { recalculateNextRun } from "../lib/nextRunCalculator.js";
5
5
  import { emitSchedulerEvent } from "../events.js";
6
6
  import { getGlobalEventBus } from "@open-mercato/shared/modules/events";
7
- import { assertSchedulerSafeCommandAuthorized } from "../lib/scheduler-safe-commands.js";
8
7
  import { buildScheduledCommandContext } from "../lib/commandContext.js";
9
8
  import { buildQueueTargetPayload, buildSchedulerIdempotencyKey } from "../lib/queueTargetPayload.js";
10
9
  import { createLogger } from "@open-mercato/shared/lib/logger";
@@ -28,6 +27,9 @@ class LocalSchedulerService {
28
27
  }
29
28
  this.isRunning = true;
30
29
  logger.info("Starting polling engine", { pollIntervalMs: this.config.pollIntervalMs });
30
+ logger.warn(
31
+ "Local scheduler strategy provides no cross-process protection: duplicate prevention is in-process only, so a second process polling the same database will execute the same due schedule. Run exactly one process with QUEUE_STRATEGY=local, or use the async strategy for distributed locking."
32
+ );
31
33
  await this.poll();
32
34
  this.pollTimer = setInterval(() => {
33
35
  this.poll().catch((error) => {
@@ -185,14 +187,6 @@ class LocalSchedulerService {
185
187
  throw new Error("Target command is required for command target type");
186
188
  }
187
189
  const commandBus = new CommandBus();
188
- const actorUserId = typeof schedule.createdByUserId === "string" ? schedule.createdByUserId.trim() : "";
189
- await assertSchedulerSafeCommandAuthorized({
190
- commandId: schedule.targetCommand,
191
- actorUserId,
192
- tenantId: schedule.tenantId,
193
- organizationId: schedule.organizationId,
194
- rbacService: this.rbacService
195
- });
196
190
  const commandInput = {
197
191
  ...schedule.targetPayload || {},
198
192
  tenantId: schedule.tenantId,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/scheduler/services/localSchedulerService.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport type { Queue } from '@open-mercato/queue'\nimport { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { ScheduledJob } from '../data/entities.js'\nimport { LocalLockStrategy } from '../lib/localLockStrategy'\nimport { recalculateNextRun } from '../lib/nextRunCalculator'\nimport { emitSchedulerEvent } from '../events.js'\nimport { getGlobalEventBus } from '@open-mercato/shared/modules/events'\nimport { assertSchedulerSafeCommandAuthorized } from '../lib/scheduler-safe-commands.js'\nimport { buildScheduledCommandContext } from '../lib/commandContext.js'\nimport { buildQueueTargetPayload, buildSchedulerIdempotencyKey } from '../lib/queueTargetPayload.js'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'local' })\n\nexport interface RbacServiceLike {\n tenantHasFeature(tenantId: string | null | undefined, feature: string, opts?: { organizationId?: string | null }): Promise<boolean>\n userHasAllFeatures(userId: string, required: readonly string[], scope: { tenantId: string | null; organizationId: string | null }): Promise<boolean>\n}\n\nexport interface LocalSchedulerConfig {\n pollIntervalMs: number\n}\n\n/**\n * Local scheduler service for development\n * \n * This service polls the database for due schedules and executes them locally\n * without requiring Redis. Perfect for local development.\n * \n * Features:\n * - PostgreSQL polling (configurable interval, default 30s)\n * - PostgreSQL advisory locks for duplicate prevention\n * - Supports both queue and command targets\n * - Emits the same events as async strategy\n * - Updates nextRunAt after execution\n * \n * Limitations:\n * - Polling delay (up to configured interval)\n * - Single instance only (no distributed locking across instances)\n * - Higher database load than async strategy\n * \n * Set QUEUE_STRATEGY=local to use this service.\n */\nexport class LocalSchedulerService {\n private isRunning = false\n private pollTimer?: NodeJS.Timeout\n private lockStrategy: LocalLockStrategy\n\n constructor(\n private em: () => EntityManager,\n private queueFactory: (name: string) => Queue,\n private rbacService: RbacServiceLike,\n private config: LocalSchedulerConfig = { pollIntervalMs: 30000 },\n ) {\n this.lockStrategy = new LocalLockStrategy(em)\n }\n\n /**\n * Start the local scheduler polling engine\n */\n async start(): Promise<void> {\n if (this.isRunning) {\n logger.warn('Polling engine already running')\n return\n }\n\n this.isRunning = true\n logger.info('Starting polling engine', { pollIntervalMs: this.config.pollIntervalMs })\n\n // Run initial poll immediately\n await this.poll()\n\n // Schedule recurring polls\n this.pollTimer = setInterval(() => {\n this.poll().catch((error) => {\n logger.error('Poll error', { err: error })\n })\n }, this.config.pollIntervalMs)\n\n logger.info('Polling engine started')\n }\n\n /**\n * Stop the local scheduler\n */\n async stop(): Promise<void> {\n logger.info('Stopping polling engine')\n this.isRunning = false\n \n if (this.pollTimer) {\n clearInterval(this.pollTimer)\n this.pollTimer = undefined\n }\n\n logger.info('Polling engine stopped')\n }\n\n /**\n * Poll for due schedules and execute them\n */\n private async poll(): Promise<void> {\n if (!this.isRunning) {\n return\n }\n\n const em = this.em().fork()\n\n try {\n // Find enabled schedules that are due (limited to avoid spikes after outages)\n const dueSchedules = await em.find(ScheduledJob, {\n isEnabled: true,\n deletedAt: null,\n nextRunAt: { $lte: new Date() },\n }, {\n limit: 100,\n orderBy: { nextRunAt: 'ASC' },\n })\n\n if (dueSchedules.length === 0) {\n logger.debug('No due schedules')\n return\n }\n\n logger.info('Found due schedules', { count: dueSchedules.length })\n\n // Execute each schedule\n for (const schedule of dueSchedules) {\n await this.executeSchedule(schedule)\n }\n } catch (error: unknown) {\n logger.error('Poll failed', { err: error })\n }\n }\n\n /**\n * Execute a single schedule\n */\n private async executeSchedule(schedule: ScheduledJob): Promise<void> {\n const lockKey = `schedule:${schedule.id}`\n const scheduleLogger = logger.child({ scheduleId: schedule.id, scheduleName: schedule.name })\n\n const { acquired } = await this.lockStrategy.runWithLock(lockKey, async () => {\n scheduleLogger.info('Executing schedule')\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 scopeType: schedule.scopeType,\n triggerType: 'scheduled',\n startedAt: new Date(),\n })\n\n try {\n // Check feature flag if required\n if (schedule.requireFeature) {\n const hasFeature = await this.checkFeature(schedule)\n \n if (!hasFeature) {\n scheduleLogger.info('Schedule skipped: missing required feature', { requireFeature: schedule.requireFeature })\n \n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n reason: `Missing required feature: ${schedule.requireFeature}`,\n skippedAt: new Date(),\n })\n\n // Still update next run time\n await this.updateNextRun(schedule)\n return\n }\n }\n\n // Execute based on target type\n if (schedule.targetType === 'queue') {\n await this.executeQueueTarget(schedule)\n } else if (schedule.targetType === 'command') {\n await this.executeCommandTarget(schedule)\n } else {\n throw new Error(`Unknown target type: ${schedule.targetType}`)\n }\n\n // Update last run and next run times\n const em = this.em().fork()\n const freshSchedule = await em.findOne(ScheduledJob, { id: schedule.id })\n \n if (freshSchedule) {\n freshSchedule.lastRunAt = new Date()\n \n // Calculate next run time\n const nextRun = recalculateNextRun(\n freshSchedule.scheduleType,\n freshSchedule.scheduleValue,\n freshSchedule.timezone\n )\n \n if (nextRun) {\n freshSchedule.nextRunAt = nextRun\n }\n \n await em.flush()\n }\n\n scheduleLogger.info('Schedule completed')\n\n // Emit completed event\n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n completedAt: new Date(),\n })\n } catch (error: unknown) {\n scheduleLogger.error('Schedule failed', { err: error })\n\n // Emit failed event\n await emitSchedulerEvent('scheduler.job.failed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n error: error instanceof Error ? error.message : String(error),\n failedAt: new Date(),\n })\n\n // Still update next run time even on failure\n await this.updateNextRun(schedule)\n }\n })\n\n if (!acquired) {\n scheduleLogger.debug('Schedule already locked, skipping')\n return\n }\n }\n\n /**\n * Execute a queue-based target\n */\n private async executeQueueTarget(schedule: ScheduledJob): Promise<void> {\n if (!schedule.targetQueue) {\n throw new Error('Target queue is required for queue target type')\n }\n\n const queue = this.queueFactory(schedule.targetQueue)\n\n // Deliver the same flat contract as the asynchronous execute-schedule\n // worker: targetPayload fields on the root, scheduler-owned scope and\n // idempotency fields applied last. Local mode runs each firing exactly\n // once, so the firing timestamp is a valid logical execution key.\n await queue.enqueue(buildQueueTargetPayload({\n targetPayload: schedule.targetPayload,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n idempotencyKey: buildSchedulerIdempotencyKey(schedule.id, Date.now()),\n }))\n\n logger.info('Enqueued job to target queue', { scheduleId: schedule.id, targetQueue: schedule.targetQueue })\n }\n\n /**\n * Execute a command-based target\n */\n private async executeCommandTarget(schedule: ScheduledJob): Promise<void> {\n if (!schedule.targetCommand) {\n throw new Error('Target command is required for command target type')\n }\n\n const commandBus = new CommandBus()\n const actorUserId = typeof schedule.createdByUserId === 'string' ? schedule.createdByUserId.trim() : ''\n await assertSchedulerSafeCommandAuthorized({\n commandId: schedule.targetCommand,\n actorUserId,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n rbacService: this.rbacService,\n })\n \n const commandInput = {\n ...((schedule.targetPayload as Record<string, unknown>) || {}),\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n }\n \n // Build the schedule-scoped command context after the allowlist/RBAC gate.\n const commandCtx = buildScheduledCommandContext(\n schedule,\n {\n resolve: (name: string) => {\n // Simple resolver that forwards to our dependencies\n if (name === 'em') return this.em()\n if (name === 'eventBus') return getGlobalEventBus()\n if (name === 'rbacService') return this.rbacService\n throw new Error(`Service not available in scheduler context: ${name}`)\n },\n } as AppContainer,\n )\n\n await commandBus.execute(schedule.targetCommand, {\n input: commandInput,\n ctx: commandCtx,\n })\n\n logger.info('Executed command', { scheduleId: schedule.id, targetCommand: schedule.targetCommand })\n }\n\n /**\n * Check if user/tenant has required feature\n */\n private async checkFeature(schedule: ScheduledJob): Promise<boolean> {\n if (!schedule.requireFeature) {\n return true\n }\n\n try {\n // For system-scoped schedules, no RBAC check needed\n if (schedule.scopeType === 'system') {\n return true\n }\n\n // For tenant/org scoped schedules, check if ANY admin user has the feature\n // This is a simplified check - in reality, scheduled jobs run without a user context\n // so we're just checking if the feature is enabled for the tenant\n const hasFeature = await this.rbacService.tenantHasFeature(\n schedule.tenantId,\n schedule.requireFeature,\n {\n organizationId: schedule.organizationId,\n }\n )\n\n return hasFeature\n } catch (error: unknown) {\n logger.error('Feature check failed', { scheduleId: schedule.id, err: error })\n return false\n }\n }\n\n /**\n * Update next run time for a schedule\n */\n private async updateNextRun(schedule: ScheduledJob): Promise<void> {\n const em = this.em().fork()\n const freshSchedule = await em.findOne(ScheduledJob, { id: schedule.id })\n \n if (freshSchedule) {\n const nextRun = recalculateNextRun(\n freshSchedule.scheduleType,\n freshSchedule.scheduleValue,\n freshSchedule.timezone\n )\n \n if (nextRun) {\n freshSchedule.nextRunAt = nextRun\n await em.flush()\n }\n }\n }\n}\n"],
5
- "mappings": "AAEA,SAAS,kBAAkB;AAE3B,SAAS,oBAAoB;AAC7B,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AACnC,SAAS,0BAA0B;AACnC,SAAS,yBAAyB;AAClC,SAAS,4CAA4C;AACrD,SAAS,oCAAoC;AAC7C,SAAS,yBAAyB,oCAAoC;AACtE,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,QAAQ,CAAC;AA+B9D,MAAM,sBAAsB;AAAA,EAKjC,YACU,IACA,cACA,aACA,SAA+B,EAAE,gBAAgB,IAAM,GAC/D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WAAO,KAAK,oBAAoB,EAAE,YAAY,SAAS,IAAI,eAAe,SAAS,cAAc,CAAC;AAAA,EACpG;AAAA;AAAA;AAAA;AAAA,EAKA,MAAc,aAAa,UAA0C;AACnE,QAAI,CAAC,SAAS,gBAAgB;AAC5B,aAAO;AAAA,IACT;AAEA,QAAI;AAEF,UAAI,SAAS,cAAc,UAAU;AACnC,eAAO;AAAA,MACT;AAKA,YAAM,aAAa,MAAM,KAAK,YAAY;AAAA,QACxC,SAAS;AAAA,QACT,SAAS;AAAA,QACT;AAAA,UACE,gBAAgB,SAAS;AAAA,QAC3B;AAAA,MACF;AAEA,aAAO;AAAA,IACT,SAAS,OAAgB;AACvB,aAAO,MAAM,wBAAwB,EAAE,YAAY,SAAS,IAAI,KAAK,MAAM,CAAC;AAC5E,aAAO;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAc,cAAc,UAAuC;AACjE,UAAM,KAAK,KAAK,GAAG,EAAE,KAAK;AAC1B,UAAM,gBAAgB,MAAM,GAAG,QAAQ,cAAc,EAAE,IAAI,SAAS,GAAG,CAAC;AAExE,QAAI,eAAe;AACjB,YAAM,UAAU;AAAA,QACd,cAAc;AAAA,QACd,cAAc;AAAA,QACd,cAAc;AAAA,MAChB;AAEA,UAAI,SAAS;AACX,sBAAc,YAAY;AAC1B,cAAM,GAAG,MAAM;AAAA,MACjB;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport type { Queue } from '@open-mercato/queue'\nimport { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { ScheduledJob } from '../data/entities.js'\nimport { LocalLockStrategy } from '../lib/localLockStrategy'\nimport { recalculateNextRun } from '../lib/nextRunCalculator'\nimport { emitSchedulerEvent } from '../events.js'\nimport { getGlobalEventBus } from '@open-mercato/shared/modules/events'\nimport { buildScheduledCommandContext } from '../lib/commandContext.js'\nimport { buildQueueTargetPayload, buildSchedulerIdempotencyKey } from '../lib/queueTargetPayload.js'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'local' })\n\nexport interface RbacServiceLike {\n tenantHasFeature(tenantId: string | null | undefined, feature: string, opts?: { organizationId?: string | null }): Promise<boolean>\n}\n\nexport interface LocalSchedulerConfig {\n pollIntervalMs: number\n}\n\n/**\n * Local scheduler service for development\n * \n * This service polls the database for due schedules and executes them locally\n * without requiring Redis. Perfect for local development.\n * \n * Features:\n * - PostgreSQL polling (configurable interval, default 30s)\n * - In-process duplicate prevention across overlapping poll ticks\n * - Supports both queue and command targets\n * - Emits the same events as async strategy\n * - Updates nextRunAt after execution\n *\n * Limitations:\n * - Polling delay (up to configured interval)\n * - Single instance only (no distributed locking across instances). Duplicate\n * prevention is in-process only: the advisory lock serialises the claim, not\n * the execution, and nextRunAt is advanced only after the target has run, so\n * two processes polling the same database will both execute a due schedule.\n * Run exactly one process with QUEUE_STRATEGY=local, or use the async\n * strategy, which locks across instances.\n * - Higher database load than async strategy\n * \n * Set QUEUE_STRATEGY=local to use this service.\n */\nexport class LocalSchedulerService {\n private isRunning = false\n private pollTimer?: NodeJS.Timeout\n private lockStrategy: LocalLockStrategy\n\n constructor(\n private em: () => EntityManager,\n private queueFactory: (name: string) => Queue,\n private rbacService: RbacServiceLike,\n private config: LocalSchedulerConfig = { pollIntervalMs: 30000 },\n ) {\n this.lockStrategy = new LocalLockStrategy(em)\n }\n\n /**\n * Start the local scheduler polling engine\n */\n async start(): Promise<void> {\n if (this.isRunning) {\n logger.warn('Polling engine already running')\n return\n }\n\n this.isRunning = true\n logger.info('Starting polling engine', { pollIntervalMs: this.config.pollIntervalMs })\n logger.warn(\n 'Local scheduler strategy provides no cross-process protection: duplicate prevention is in-process only, so a second process polling the same database will execute the same due schedule. Run exactly one process with QUEUE_STRATEGY=local, or use the async strategy for distributed locking.',\n )\n\n // Run initial poll immediately\n await this.poll()\n\n // Schedule recurring polls\n this.pollTimer = setInterval(() => {\n this.poll().catch((error) => {\n logger.error('Poll error', { err: error })\n })\n }, this.config.pollIntervalMs)\n\n logger.info('Polling engine started')\n }\n\n /**\n * Stop the local scheduler\n */\n async stop(): Promise<void> {\n logger.info('Stopping polling engine')\n this.isRunning = false\n \n if (this.pollTimer) {\n clearInterval(this.pollTimer)\n this.pollTimer = undefined\n }\n\n logger.info('Polling engine stopped')\n }\n\n /**\n * Poll for due schedules and execute them\n */\n private async poll(): Promise<void> {\n if (!this.isRunning) {\n return\n }\n\n const em = this.em().fork()\n\n try {\n // Find enabled schedules that are due (limited to avoid spikes after outages)\n const dueSchedules = await em.find(ScheduledJob, {\n isEnabled: true,\n deletedAt: null,\n nextRunAt: { $lte: new Date() },\n }, {\n limit: 100,\n orderBy: { nextRunAt: 'ASC' },\n })\n\n if (dueSchedules.length === 0) {\n logger.debug('No due schedules')\n return\n }\n\n logger.info('Found due schedules', { count: dueSchedules.length })\n\n // Execute each schedule\n for (const schedule of dueSchedules) {\n await this.executeSchedule(schedule)\n }\n } catch (error: unknown) {\n logger.error('Poll failed', { err: error })\n }\n }\n\n /**\n * Execute a single schedule\n */\n private async executeSchedule(schedule: ScheduledJob): Promise<void> {\n const lockKey = `schedule:${schedule.id}`\n const scheduleLogger = logger.child({ scheduleId: schedule.id, scheduleName: schedule.name })\n\n const { acquired } = await this.lockStrategy.runWithLock(lockKey, async () => {\n scheduleLogger.info('Executing schedule')\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 scopeType: schedule.scopeType,\n triggerType: 'scheduled',\n startedAt: new Date(),\n })\n\n try {\n // Check feature flag if required\n if (schedule.requireFeature) {\n const hasFeature = await this.checkFeature(schedule)\n \n if (!hasFeature) {\n scheduleLogger.info('Schedule skipped: missing required feature', { requireFeature: schedule.requireFeature })\n \n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n reason: `Missing required feature: ${schedule.requireFeature}`,\n skippedAt: new Date(),\n })\n\n // Still update next run time\n await this.updateNextRun(schedule)\n return\n }\n }\n\n // Execute based on target type\n if (schedule.targetType === 'queue') {\n await this.executeQueueTarget(schedule)\n } else if (schedule.targetType === 'command') {\n await this.executeCommandTarget(schedule)\n } else {\n throw new Error(`Unknown target type: ${schedule.targetType}`)\n }\n\n // Update last run and next run times\n const em = this.em().fork()\n const freshSchedule = await em.findOne(ScheduledJob, { id: schedule.id })\n \n if (freshSchedule) {\n freshSchedule.lastRunAt = new Date()\n \n // Calculate next run time\n const nextRun = recalculateNextRun(\n freshSchedule.scheduleType,\n freshSchedule.scheduleValue,\n freshSchedule.timezone\n )\n \n if (nextRun) {\n freshSchedule.nextRunAt = nextRun\n }\n \n await em.flush()\n }\n\n scheduleLogger.info('Schedule completed')\n\n // Emit completed event\n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n completedAt: new Date(),\n })\n } catch (error: unknown) {\n scheduleLogger.error('Schedule failed', { err: error })\n\n // Emit failed event\n await emitSchedulerEvent('scheduler.job.failed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n error: error instanceof Error ? error.message : String(error),\n failedAt: new Date(),\n })\n\n // Still update next run time even on failure\n await this.updateNextRun(schedule)\n }\n })\n\n if (!acquired) {\n scheduleLogger.debug('Schedule already locked, skipping')\n return\n }\n }\n\n /**\n * Execute a queue-based target\n */\n private async executeQueueTarget(schedule: ScheduledJob): Promise<void> {\n if (!schedule.targetQueue) {\n throw new Error('Target queue is required for queue target type')\n }\n\n const queue = this.queueFactory(schedule.targetQueue)\n\n // Deliver the same flat contract as the asynchronous execute-schedule\n // worker: targetPayload fields on the root, scheduler-owned scope and\n // idempotency fields applied last. Local mode runs each firing exactly\n // once, so the firing timestamp is a valid logical execution key.\n await queue.enqueue(buildQueueTargetPayload({\n targetPayload: schedule.targetPayload,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n idempotencyKey: buildSchedulerIdempotencyKey(schedule.id, Date.now()),\n }))\n\n logger.info('Enqueued job to target queue', { scheduleId: schedule.id, targetQueue: schedule.targetQueue })\n }\n\n /**\n * Execute a command-based target\n */\n private async executeCommandTarget(schedule: ScheduledJob): Promise<void> {\n if (!schedule.targetCommand) {\n throw new Error('Target command is required for command target type')\n }\n\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(\n schedule,\n {\n resolve: (name: string) => {\n // Simple resolver that forwards to our dependencies\n if (name === 'em') return this.em()\n if (name === 'eventBus') return getGlobalEventBus()\n if (name === 'rbacService') return this.rbacService\n throw new Error(`Service not available in scheduler context: ${name}`)\n },\n } as AppContainer,\n )\n\n await commandBus.execute(schedule.targetCommand, {\n input: commandInput,\n ctx: commandCtx,\n })\n\n logger.info('Executed command', { scheduleId: schedule.id, targetCommand: schedule.targetCommand })\n }\n\n /**\n * Check if user/tenant has required feature\n */\n private async checkFeature(schedule: ScheduledJob): Promise<boolean> {\n if (!schedule.requireFeature) {\n return true\n }\n\n try {\n // For system-scoped schedules, no RBAC check needed\n if (schedule.scopeType === 'system') {\n return true\n }\n\n // For tenant/org scoped schedules, check if ANY admin user has the feature\n // This is a simplified check - in reality, scheduled jobs run without a user context\n // so we're just checking if the feature is enabled for the tenant\n const hasFeature = await this.rbacService.tenantHasFeature(\n schedule.tenantId,\n schedule.requireFeature,\n {\n organizationId: schedule.organizationId,\n }\n )\n\n return hasFeature\n } catch (error: unknown) {\n logger.error('Feature check failed', { scheduleId: schedule.id, err: error })\n return false\n }\n }\n\n /**\n * Update next run time for a schedule\n */\n private async updateNextRun(schedule: ScheduledJob): Promise<void> {\n const em = this.em().fork()\n const freshSchedule = await em.findOne(ScheduledJob, { id: schedule.id })\n \n if (freshSchedule) {\n const nextRun = recalculateNextRun(\n freshSchedule.scheduleType,\n freshSchedule.scheduleValue,\n freshSchedule.timezone\n )\n \n if (nextRun) {\n freshSchedule.nextRunAt = nextRun\n await em.flush()\n }\n }\n }\n}\n"],
5
+ "mappings": "AAEA,SAAS,kBAAkB;AAE3B,SAAS,oBAAoB;AAC7B,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AACnC,SAAS,0BAA0B;AACnC,SAAS,yBAAyB;AAClC,SAAS,oCAAoC;AAC7C,SAAS,yBAAyB,oCAAoC;AACtE,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,QAAQ,CAAC;AAmC9D,MAAM,sBAAsB;AAAA,EAKjC,YACU,IACA,cACA,aACA,SAA+B,EAAE,gBAAgB,IAAM,GAC/D;AAJQ;AACA;AACA;AACA;AARV,SAAQ,YAAY;AAUlB,SAAK,eAAe,IAAI,kBAAkB,EAAE;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,QAAuB;AAC3B,QAAI,KAAK,WAAW;AAClB,aAAO,KAAK,gCAAgC;AAC5C;AAAA,IACF;AAEA,SAAK,YAAY;AACjB,WAAO,KAAK,2BAA2B,EAAE,gBAAgB,KAAK,OAAO,eAAe,CAAC;AACrF,WAAO;AAAA,MACL;AAAA,IACF;AAGA,UAAM,KAAK,KAAK;AAGhB,SAAK,YAAY,YAAY,MAAM;AACjC,WAAK,KAAK,EAAE,MAAM,CAAC,UAAU;AAC3B,eAAO,MAAM,cAAc,EAAE,KAAK,MAAM,CAAC;AAAA,MAC3C,CAAC;AAAA,IACH,GAAG,KAAK,OAAO,cAAc;AAE7B,WAAO,KAAK,wBAAwB;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cAAc;AAAA,QACd,cAAc;AAAA,QACd,cAAc;AAAA,MAChB;AAEA,UAAI,SAAS;AACX,sBAAc,YAAY;AAC1B,cAAM,GAAG,MAAM;AAAA,MACjB;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,6 +1,5 @@
1
1
  import { ScheduledJob } from "../data/entities.js";
2
- import { calculateNextRunForWrite } from "../lib/nextRunCalculator.js";
3
- import { enforceTenantActiveScheduleLimit } from "../lib/activeScheduleLimits.js";
2
+ import { calculateNextRun } from "../lib/nextRunCalculator.js";
4
3
  import { createLogger } from "@open-mercato/shared/lib/logger";
5
4
  const logger = createLogger("scheduler");
6
5
  class SchedulerService {
@@ -15,7 +14,7 @@ class SchedulerService {
15
14
  const em = this.em().fork();
16
15
  this.validateScope(registration);
17
16
  this.validateTarget(registration);
18
- const nextRunAt = calculateNextRunForWrite(
17
+ const nextRunAt = calculateNextRun(
19
18
  registration.scheduleType,
20
19
  registration.scheduleValue,
21
20
  registration.timezone || "UTC"
@@ -24,12 +23,6 @@ class SchedulerService {
24
23
  throw new Error(`Failed to calculate next run time for schedule: ${registration.id}`);
25
24
  }
26
25
  let schedule = await em.findOne(ScheduledJob, { id: registration.id });
27
- const nextTenantId = registration.tenantId || null;
28
- const nextIsEnabled = registration.isEnabled !== void 0 ? registration.isEnabled : schedule?.isEnabled ?? true;
29
- const tenantChanged = schedule ? (schedule.tenantId || null) !== nextTenantId : false;
30
- if (nextIsEnabled && (schedule?.isEnabled !== true || tenantChanged)) {
31
- await enforceTenantActiveScheduleLimit(em, nextTenantId);
32
- }
33
26
  if (schedule) {
34
27
  schedule.name = registration.name;
35
28
  schedule.description = registration.description || null;
@@ -121,18 +114,6 @@ class SchedulerService {
121
114
  if (!schedule) {
122
115
  throw new Error(`Schedule not found: ${scheduleId}`);
123
116
  }
124
- if (changes.isEnabled === true && schedule.isEnabled !== true) {
125
- await enforceTenantActiveScheduleLimit(em, schedule.tenantId);
126
- }
127
- const scheduleChanged = changes.scheduleType !== void 0 || changes.scheduleValue !== void 0 || changes.timezone !== void 0;
128
- const nextRunAt = scheduleChanged ? calculateNextRunForWrite(
129
- changes.scheduleType ?? schedule.scheduleType,
130
- changes.scheduleValue ?? schedule.scheduleValue,
131
- changes.timezone ?? schedule.timezone
132
- ) : null;
133
- if (scheduleChanged && !nextRunAt) {
134
- throw new Error(`Failed to calculate next run time for schedule: ${scheduleId}`);
135
- }
136
117
  if (changes.name !== void 0) schedule.name = changes.name;
137
118
  if (changes.description !== void 0) schedule.description = changes.description || null;
138
119
  if (changes.scheduleType !== void 0) schedule.scheduleType = changes.scheduleType;
@@ -156,8 +137,15 @@ class SchedulerService {
156
137
  if (changes.targetQueue !== void 0) schedule.targetQueue = changes.targetQueue || null;
157
138
  if (changes.targetCommand !== void 0) schedule.targetCommand = changes.targetCommand || null;
158
139
  }
159
- if (nextRunAt) {
160
- schedule.nextRunAt = nextRunAt;
140
+ if (changes.scheduleType !== void 0 || changes.scheduleValue !== void 0 || changes.timezone !== void 0) {
141
+ const nextRunAt = calculateNextRun(
142
+ schedule.scheduleType,
143
+ schedule.scheduleValue,
144
+ schedule.timezone
145
+ );
146
+ if (nextRunAt) {
147
+ schedule.nextRunAt = nextRunAt;
148
+ }
161
149
  }
162
150
  schedule.updatedAt = /* @__PURE__ */ new Date();
163
151
  await em.flush();
@@ -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 { calculateNextRunForWrite } from '../lib/nextRunCalculator.js'\nimport { enforceTenantActiveScheduleLimit } from '../lib/activeScheduleLimits.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 = calculateNextRunForWrite(\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 const nextTenantId = registration.tenantId || null\n const nextIsEnabled = registration.isEnabled !== undefined ? registration.isEnabled : (schedule?.isEnabled ?? true)\n const tenantChanged = schedule ? (schedule.tenantId || null) !== nextTenantId : false\n if (nextIsEnabled && (schedule?.isEnabled !== true || tenantChanged)) {\n await enforceTenantActiveScheduleLimit(em, nextTenantId)\n }\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 if (changes.isEnabled === true && schedule.isEnabled !== true) {\n await enforceTenantActiveScheduleLimit(em, schedule.tenantId)\n }\n\n const scheduleChanged = changes.scheduleType !== undefined || changes.scheduleValue !== undefined || changes.timezone !== undefined\n const nextRunAt = scheduleChanged\n ? calculateNextRunForWrite(\n changes.scheduleType ?? schedule.scheduleType,\n changes.scheduleValue ?? schedule.scheduleValue,\n changes.timezone ?? schedule.timezone,\n )\n : null\n if (scheduleChanged && !nextRunAt) {\n throw new Error(`Failed to calculate next run time for schedule: ${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 if (nextRunAt) {\n schedule.nextRunAt = nextRunAt\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;AAC7B,SAAS,gCAAgC;AACzC,SAAS,wCAAwC;AAEjD,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAsBhC,MAAM,iBAAiB;AAAA,EAC5B,YACU,IACA,eACR;AAFQ;AACA;AAAA,EACP;AAAA;A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,WAAW,KAAK,GAAG,EAAE,MAAM,CAAC;AAAA,EACrF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,OAAO,YAAmC;AAC9C,UAAM,KAAK,OAAO,YAAY,EAAE,WAAW,KAAK,CAAC;AAAA,EACnD;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,QAAQ,YAAmC;AAC/C,UAAM,KAAK,OAAO,YAAY,EAAE,WAAW,MAAM,CAAC;AAAA,EACpD;AAAA,EAEQ,cAAc,cAA0C;AAC9D,UAAM,EAAE,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;",
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;AAC7B,SAAS,wBAAwB;AAEjC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAsBhC,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,SAAK,cAAc,YAAY;AAG/B,SAAK,eAAe,YAAY;AAGhC,UAAM,YAAY;AAAA,MAChB,aAAa;AAAA,MACb,aAAa;AAAA,MACb,aAAa,YAAY;AAAA,IAC3B;AAEA,QAAI,CAAC,WAAW;AACd,YAAM,IAAI,MAAM,mDAAmD,aAAa,EAAE,EAAE;AAAA,IACtF;AAGA,QAAI,WAAW,MAAM,GAAG,QAAQ,cAAc,EAAE,IAAI,aAAa,GAAG,CAAC;AAErE,QAAI,UAAU;AAEZ,eAAS,OAA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AI,CAAC,eAAe;AAClB,cAAM,IAAI,MAAM,wCAAwC;AAAA,MAC1D;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -3,7 +3,6 @@ import { getRedisUrlOrThrow } from "@open-mercato/shared/lib/redis/connection";
3
3
  import { ScheduledJob } from "../data/entities.js";
4
4
  import { CommandBus } from "@open-mercato/shared/lib/commands";
5
5
  import { emitSchedulerEvent } from "../events.js";
6
- import { assertSchedulerSafeCommandAuthorized } from "../lib/scheduler-safe-commands.js";
7
6
  import { buildScheduledCommandContext } from "../lib/commandContext.js";
8
7
  import { buildQueueTargetPayload, buildSchedulerIdempotencyKey } from "../lib/queueTargetPayload.js";
9
8
  import { createLogger } from "@open-mercato/shared/lib/logger";
@@ -125,14 +124,6 @@ async function executeScheduleWorker(job, ctx) {
125
124
  });
126
125
  } else if (schedule.targetType === "command" && schedule.targetCommand) {
127
126
  const commandBus = new CommandBus();
128
- const actorUserId = typeof schedule.createdByUserId === "string" ? schedule.createdByUserId.trim() : "";
129
- await assertSchedulerSafeCommandAuthorized({
130
- commandId: schedule.targetCommand,
131
- actorUserId,
132
- tenantId: schedule.tenantId,
133
- organizationId: schedule.organizationId,
134
- rbacService
135
- });
136
127
  const commandInput = {
137
128
  ...schedule.targetPayload || {},
138
129
  tenantId: schedule.tenantId,
@@ -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 { assertSchedulerSafeCommandAuthorized } from '../lib/scheduler-safe-commands.js'\nimport { buildScheduledCommandContext } from '../lib/commandContext.js'\nimport { buildQueueTargetPayload, buildSchedulerIdempotencyKey } from '../lib/queueTargetPayload.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 userHasAllFeatures(\n userId: string,\n required: readonly string[],\n scope: { tenantId: string | null; 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 // The execute-schedule job id is stable across BullMQ retries, so if\n // this worker crashes between enqueue and DB flush the retried attempt\n // reuses the same idempotency key and downstream workers can dedupe.\n const idempotencyKey = buildSchedulerIdempotencyKey(schedule.id, ctx.jobId ?? Date.now())\n\n targetJobId = await targetQueue.enqueue(buildQueueTargetPayload({\n targetPayload: schedule.targetPayload,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n idempotencyKey,\n }))\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 const actorUserId = typeof schedule.createdByUserId === 'string' ? schedule.createdByUserId.trim() : ''\n await assertSchedulerSafeCommandAuthorized({\n commandId: schedule.targetCommand,\n actorUserId,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n rbacService,\n })\n \n const commandInput = {\n ...((schedule.targetPayload as Record<string, unknown>) || {}),\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n }\n \n // Build the schedule-scoped command context after the allowlist/RBAC gate.\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,4CAA4C;AACrD,SAAS,oCAAoC;AAC7C,SAAS,yBAAyB,oCAAoC;AACtE,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;AA4CA,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,QAAM,KAAK,IAAI,QAAuB,IAAI;AAC1C,QAAM,cAAc,IAAI,QAAyB,aAAa;AAG9D,QAAM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;AAClC,UAAM,cAAc,OAAO,SAAS,oBAAoB,WAAW,SAAS,gBAAgB,KAAK,IAAI;AACrG,UAAM,qCAAqC;AAAA,MACzC,WAAW,SAAS;AAAA,MACpB;AAAA,MACA,UAAU,SAAS;AAAA,MACnB,gBAAgB,SAAS;AAAA,MACzB;AAAA,IACF,CAAC;AAED,UAAM,eAAe;AAAA,MACnB,GAAK,SAAS,iBAA6C,CAAC;AAAA,MAC5D,UAAU,SAAS;AAAA,MACnB,gBAAgB,SAAS;AAAA,IAC3B;AAGA,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;",
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 { buildQueueTargetPayload, buildSchedulerIdempotencyKey } from '../lib/queueTargetPayload.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 // The execute-schedule job id is stable across BullMQ retries, so if\n // this worker crashes between enqueue and DB flush the retried attempt\n // reuses the same idempotency key and downstream workers can dedupe.\n const idempotencyKey = buildSchedulerIdempotencyKey(schedule.id, ctx.jobId ?? Date.now())\n\n targetJobId = await targetQueue.enqueue(buildQueueTargetPayload({\n targetPayload: schedule.targetPayload,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n idempotencyKey,\n }))\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', {\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ACnB,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.7-develop.6862.1.c11a64ce0a",
3
+ "version": "0.6.7",
4
4
  "license": "MIT",
5
5
  "description": "Database-managed scheduled jobs with admin UI",
6
6
  "type": "module",
@@ -59,14 +59,14 @@
59
59
  "./*/*/*/*/*/*.json": "./src/*/*/*/*/*/*.json"
60
60
  },
61
61
  "dependencies": {
62
- "@open-mercato/events": "0.6.7-develop.6862.1.c11a64ce0a",
63
- "@open-mercato/queue": "0.6.7-develop.6862.1.c11a64ce0a",
62
+ "@open-mercato/events": "0.6.7",
63
+ "@open-mercato/queue": "0.6.7",
64
64
  "cron-parser": "^5.6.2"
65
65
  },
66
66
  "peerDependencies": {
67
67
  "@mikro-orm/core": "^7.0.14",
68
- "@open-mercato/shared": "0.6.7-develop.6862.1.c11a64ce0a",
69
- "bullmq": "^5.0.0 || ^6.0.0",
68
+ "@open-mercato/shared": "0.6.7",
69
+ "bullmq": "^5.0.0",
70
70
  "ioredis": "^5.0.0",
71
71
  "zod": ">=3.23.0"
72
72
  },
@@ -79,11 +79,11 @@
79
79
  }
80
80
  },
81
81
  "devDependencies": {
82
- "@open-mercato/shared": "0.6.7-develop.6862.1.c11a64ce0a",
82
+ "@open-mercato/shared": "0.6.7",
83
83
  "@types/jest": "^30.0.0",
84
- "@types/node": "^26.1.2",
84
+ "@types/node": "^26.0.1",
85
85
  "jest": "^30.4.2",
86
- "ts-jest": "^29.4.12",
86
+ "ts-jest": "^29.4.11",
87
87
  "typescript": "7.0.2"
88
88
  },
89
89
  "publishConfig": {
@@ -93,6 +93,5 @@
93
93
  "type": "git",
94
94
  "url": "https://github.com/open-mercato/open-mercato",
95
95
  "directory": "packages/scheduler"
96
- },
97
- "stableVersion": "0.6.6"
96
+ }
98
97
  }
@@ -9,18 +9,16 @@ type ValidationError = { error?: string; details?: Array<{ path?: Array<string |
9
9
  * TC-SCHED-007: POST /api/scheduler/jobs rejects invalid cron and interval
10
10
  * `scheduleValue`s with 400 and an error scoped to the `scheduleValue` path.
11
11
  *
12
- * Interval format is `<number><unit>` with unit in s|m|h|d and a minimum floor
13
- * of one minute. All cases are rejected at validation, so no records are
14
- * created and no teardown is required.
12
+ * Interval format is `<number><unit>` with unit in s|m|h|d, so the inputs below
13
+ * are genuinely malformed (the issue's "99h"/"0m" drafts are actually valid).
14
+ * All cases are rejected at validation, so no records are created and no
15
+ * teardown is required.
15
16
  */
16
17
  const invalidCases = [
17
18
  { label: 'cron: not a cron expression', scheduleType: 'cron' as const, scheduleValue: 'not-a-cron' },
18
19
  { label: 'cron: too few fields', scheduleType: 'cron' as const, scheduleValue: '* * *' },
19
20
  { label: 'interval: unsupported unit', scheduleType: 'interval' as const, scheduleValue: '15x' },
20
21
  { label: 'interval: missing unit', scheduleType: 'interval' as const, scheduleValue: '99' },
21
- { label: 'interval: zero seconds', scheduleType: 'interval' as const, scheduleValue: '0s' },
22
- { label: 'interval: one second', scheduleType: 'interval' as const, scheduleValue: '1s' },
23
- { label: 'interval: below one minute', scheduleType: 'interval' as const, scheduleValue: '59s' },
24
22
  ]
25
23
 
26
24
  test.describe('TC-SCHED-007: POST /api/scheduler/jobs validates schedule value format', () => {
@@ -5,7 +5,7 @@ import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
5
5
  import type { EntityManager } from '@mikro-orm/core'
6
6
  import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'
7
7
  import { ScheduledJob } from '../../../../data/entities.js'
8
- import { getRedisUrlOrThrow, parseRedisUrl } from '@open-mercato/shared/lib/redis/connection'
8
+ import { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'
9
9
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
10
10
  import { createLogger } from '@open-mercato/shared/lib/logger'
11
11
 
@@ -79,9 +79,7 @@ export async function GET(
79
79
 
80
80
  // Fetch jobs from BullMQ scheduler-execution queue
81
81
  const { Queue } = await import('bullmq')
82
- const queue = new Queue('scheduler-execution', {
83
- connection: parseRedisUrl(getRedisUrlOrThrow('QUEUE')),
84
- })
82
+ const queue = new Queue('scheduler-execution', { connection: { url: getRedisUrlOrThrow('QUEUE') } })
85
83
 
86
84
  try {
87
85
  // Validate query params with Zod schema
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from 'next/server'
2
2
  import { z } from 'zod'
3
3
  import { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'
4
4
  import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'
5
- import { getRedisUrlOrThrow, parseRedisUrl } from '@open-mercato/shared/lib/redis/connection'
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
8
  import { createLogger } from '@open-mercato/shared/lib/logger'
@@ -72,9 +72,7 @@ export async function GET(
72
72
 
73
73
  // Fetch job from BullMQ
74
74
  const { Queue } = await import('bullmq')
75
- const queue = new Queue(queueName, {
76
- connection: parseRedisUrl(getRedisUrlOrThrow('QUEUE')),
77
- })
75
+ const queue = new Queue(queueName, { connection: { url: getRedisUrlOrThrow('QUEUE') } })
78
76
 
79
77
  const job = await queue.getJob(jobId)
80
78