@open-mercato/scheduler 0.6.6-develop.6465.1.019f0fb26f → 0.6.6-develop.6472.1.1673e7e66b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/modules/scheduler/api/jobs/[id]/executions/route.js +3 -1
  2. package/dist/modules/scheduler/api/jobs/[id]/executions/route.js.map +2 -2
  3. package/dist/modules/scheduler/api/queue-jobs/[jobId]/route.js +3 -1
  4. package/dist/modules/scheduler/api/queue-jobs/[jobId]/route.js.map +2 -2
  5. package/dist/modules/scheduler/api/trigger/route.js +4 -2
  6. package/dist/modules/scheduler/api/trigger/route.js.map +2 -2
  7. package/dist/modules/scheduler/cli.js +55 -50
  8. package/dist/modules/scheduler/cli.js.map +2 -2
  9. package/dist/modules/scheduler/commands/test-echo.js +3 -2
  10. package/dist/modules/scheduler/commands/test-echo.js.map +2 -2
  11. package/dist/modules/scheduler/di.js +4 -2
  12. package/dist/modules/scheduler/di.js.map +2 -2
  13. package/dist/modules/scheduler/lib/localLockStrategy.js +3 -1
  14. package/dist/modules/scheduler/lib/localLockStrategy.js.map +2 -2
  15. package/dist/modules/scheduler/lib/scheduledJobSubscriber.js +8 -6
  16. package/dist/modules/scheduler/lib/scheduledJobSubscriber.js.map +2 -2
  17. package/dist/modules/scheduler/services/bullmqSchedulerService.js +20 -17
  18. package/dist/modules/scheduler/services/bullmqSchedulerService.js.map +2 -2
  19. package/dist/modules/scheduler/services/localSchedulerService.js +21 -19
  20. package/dist/modules/scheduler/services/localSchedulerService.js.map +2 -2
  21. package/dist/modules/scheduler/services/schedulerService.js +5 -3
  22. package/dist/modules/scheduler/services/schedulerService.js.map +2 -2
  23. package/dist/modules/scheduler/workers/execute-schedule.worker.js +16 -15
  24. package/dist/modules/scheduler/workers/execute-schedule.worker.js.map +2 -2
  25. package/package.json +5 -5
  26. package/src/modules/scheduler/api/jobs/[id]/executions/route.ts +4 -1
  27. package/src/modules/scheduler/api/queue-jobs/[jobId]/route.ts +4 -1
  28. package/src/modules/scheduler/api/trigger/route.ts +5 -2
  29. package/src/modules/scheduler/cli.ts +55 -48
  30. package/src/modules/scheduler/commands/test-echo.ts +4 -2
  31. package/src/modules/scheduler/di.ts +6 -3
  32. package/src/modules/scheduler/lib/localLockStrategy.ts +4 -1
  33. package/src/modules/scheduler/lib/scheduledJobSubscriber.ts +9 -6
  34. package/src/modules/scheduler/services/__tests__/bullmqSchedulerService.test.ts +49 -74
  35. package/src/modules/scheduler/services/__tests__/localSchedulerService.test.ts +29 -67
  36. package/src/modules/scheduler/services/__tests__/schedulerService.test.ts +24 -9
  37. package/src/modules/scheduler/services/bullmqSchedulerService.ts +20 -16
  38. package/src/modules/scheduler/services/localSchedulerService.ts +22 -19
  39. package/src/modules/scheduler/services/schedulerService.ts +6 -3
  40. package/src/modules/scheduler/workers/execute-schedule.worker.ts +16 -14
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/modules/scheduler/di.ts"],
4
- "sourcesContent": ["import { asClass } from 'awilix'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { createQueue } from '@open-mercato/queue'\nimport { SchedulerService } from './services/schedulerService.js'\nimport { BullMQSchedulerService } from './services/bullmqSchedulerService.js'\nimport { LocalSchedulerService } from './services/localSchedulerService.js'\nimport { ScheduledJobSubscriber } from './lib/scheduledJobSubscriber.js'\n\n// Process-level guard: ensures BullMQ sync runs at most once per process lifetime.\nlet schedulerSynced = false\n\n/**\n * Scheduler module DI registration\n * \n * Supports two modes:\n * - async (production): BullMQ-based scheduling with Redis\n * - local (development): Simple polling for local dev without Redis\n * \n * Set QUEUE_STRATEGY=async for production use.\n */\nexport function register(container: AppContainer) {\n const queueStrategy = process.env.QUEUE_STRATEGY || 'local'\n\n if (queueStrategy === 'async') {\n // Register BullMQ scheduler service for production (requires Redis)\n container.register({\n bullmqSchedulerService: asClass(BullMQSchedulerService)\n .singleton()\n .disposer((service) => service.destroy())\n .inject(() => ({\n em: () => container.resolve('em'),\n })),\n })\n // Register MikroORM subscriber for automatic BullMQ sync\n try {\n const em = container.resolve<{ getEventManager?: () => { registerSubscriber(s: ScheduledJobSubscriber): void } }>('em')\n if (em && em.getEventManager) {\n const subscriber = new ScheduledJobSubscriber()\n subscriber.setContainer(container)\n em.getEventManager().registerSubscriber(subscriber)\n }\n } catch (error) {\n // Best-effort registration - don't break if EM not available yet\n console.warn('[scheduler] Could not register subscriber:', error)\n }\n\n // Cold start sync: reconcile DB schedules with BullMQ repeatable jobs.\n // Deferred so it doesn't block DI registration. Runs once per process.\n if (!schedulerSynced) {\n schedulerSynced = true\n setImmediate(() => {\n const service = container.resolve('bullmqSchedulerService') as BullMQSchedulerService\n service.syncAll()\n .then(() => console.log('[scheduler] BullMQ cold start sync complete'))\n .catch((err: Error) => console.error('[scheduler] BullMQ cold start sync failed:', err.message))\n })\n }\n } else {\n // Register local scheduler service for development (no Redis required)\n const queueFactory = (name: string) => createQueue(name, 'local')\n \n container.register({\n localSchedulerService: asClass(LocalSchedulerService)\n .singleton()\n .inject(() => ({\n em: () => container.resolve('em'),\n queueFactory,\n rbacService: container.resolve('rbacService'),\n config: {\n pollIntervalMs: parseInt(process.env.SCHEDULER_POLL_INTERVAL_MS || '30000', 10),\n },\n })),\n })\n }\n\n // Register common API service\n container.register({\n schedulerService: asClass(SchedulerService)\n .singleton()\n .inject(() => ({\n em: () => container.resolve('em'),\n bullmqService: queueStrategy === 'async' \n ? container.resolve('bullmqSchedulerService')\n : undefined,\n })),\n })\n}\n"],
5
- "mappings": "AAAA,SAAS,eAAe;AAExB,SAAS,mBAAmB;AAC5B,SAAS,wBAAwB;AACjC,SAAS,8BAA8B;AACvC,SAAS,6BAA6B;AACtC,SAAS,8BAA8B;AAGvC,IAAI,kBAAkB;AAWf,SAAS,SAAS,WAAyB;AAChD,QAAM,gBAAgB,QAAQ,IAAI,kBAAkB;AAEpD,MAAI,kBAAkB,SAAS;AAE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AChC,eAAe,kBAAkB,UAC7B,UAAU,QAAQ,wBAAwB,IAC1C;AAAA,IACN,EAAE;AAAA,EACN,CAAC;AACH;",
4
+ "sourcesContent": ["import { asClass } from 'awilix'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { createQueue } from '@open-mercato/queue'\nimport { SchedulerService } from './services/schedulerService.js'\nimport { BullMQSchedulerService } from './services/bullmqSchedulerService.js'\nimport { LocalSchedulerService } from './services/localSchedulerService.js'\nimport { ScheduledJobSubscriber } from './lib/scheduledJobSubscriber.js'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler')\n\n// Process-level guard: ensures BullMQ sync runs at most once per process lifetime.\nlet schedulerSynced = false\n\n/**\n * Scheduler module DI registration\n * \n * Supports two modes:\n * - async (production): BullMQ-based scheduling with Redis\n * - local (development): Simple polling for local dev without Redis\n * \n * Set QUEUE_STRATEGY=async for production use.\n */\nexport function register(container: AppContainer) {\n const queueStrategy = process.env.QUEUE_STRATEGY || 'local'\n\n if (queueStrategy === 'async') {\n // Register BullMQ scheduler service for production (requires Redis)\n container.register({\n bullmqSchedulerService: asClass(BullMQSchedulerService)\n .singleton()\n .disposer((service) => service.destroy())\n .inject(() => ({\n em: () => container.resolve('em'),\n })),\n })\n // Register MikroORM subscriber for automatic BullMQ sync\n try {\n const em = container.resolve<{ getEventManager?: () => { registerSubscriber(s: ScheduledJobSubscriber): void } }>('em')\n if (em && em.getEventManager) {\n const subscriber = new ScheduledJobSubscriber()\n subscriber.setContainer(container)\n em.getEventManager().registerSubscriber(subscriber)\n }\n } catch (error) {\n // Best-effort registration - don't break if EM not available yet\n logger.warn('Could not register subscriber', { err: error })\n }\n\n // Cold start sync: reconcile DB schedules with BullMQ repeatable jobs.\n // Deferred so it doesn't block DI registration. Runs once per process.\n if (!schedulerSynced) {\n schedulerSynced = true\n setImmediate(() => {\n const service = container.resolve('bullmqSchedulerService') as BullMQSchedulerService\n service.syncAll()\n .then(() => logger.info('BullMQ cold start sync complete'))\n .catch((err: Error) => logger.error('BullMQ cold start sync failed', { err }))\n })\n }\n } else {\n // Register local scheduler service for development (no Redis required)\n const queueFactory = (name: string) => createQueue(name, 'local')\n \n container.register({\n localSchedulerService: asClass(LocalSchedulerService)\n .singleton()\n .inject(() => ({\n em: () => container.resolve('em'),\n queueFactory,\n rbacService: container.resolve('rbacService'),\n config: {\n pollIntervalMs: parseInt(process.env.SCHEDULER_POLL_INTERVAL_MS || '30000', 10),\n },\n })),\n })\n }\n\n // Register common API service\n container.register({\n schedulerService: asClass(SchedulerService)\n .singleton()\n .inject(() => ({\n em: () => container.resolve('em'),\n bullmqService: queueStrategy === 'async' \n ? container.resolve('bullmqSchedulerService')\n : undefined,\n })),\n })\n}\n"],
5
+ "mappings": "AAAA,SAAS,eAAe;AAExB,SAAS,mBAAmB;AAC5B,SAAS,wBAAwB;AACjC,SAAS,8BAA8B;AACvC,SAAS,6BAA6B;AACtC,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAGvC,IAAI,kBAAkB;AAWf,SAAS,SAAS,WAAyB;AAChD,QAAM,gBAAgB,QAAQ,IAAI,kBAAkB;AAEpD,MAAI,kBAAkB,SAAS;AAE7B,cAAU,SAAS;AAAA,MACjB,wBAAwB,QAAQ,sBAAsB,EACnD,UAAU,EACV,SAAS,CAAC,YAAY,QAAQ,QAAQ,CAAC,EACvC,OAAO,OAAO;AAAA,QACb,IAAI,MAAM,UAAU,QAAQ,IAAI;AAAA,MAClC,EAAE;AAAA,IACN,CAAC;AAED,QAAI;AACF,YAAM,KAAK,UAAU,QAA6F,IAAI;AACtH,UAAI,MAAM,GAAG,iBAAiB;AAC5B,cAAM,aAAa,IAAI,uBAAuB;AAC9C,mBAAW,aAAa,SAAS;AACjC,WAAG,gBAAgB,EAAE,mBAAmB,UAAU;AAAA,MACpD;AAAA,IACF,SAAS,OAAO;AAEd,aAAO,KAAK,iCAAiC,EAAE,KAAK,MAAM,CAAC;AAAA,IAC7D;AAIA,QAAI,CAAC,iBAAiB;AACpB,wBAAkB;AAClB,mBAAa,MAAM;AACjB,cAAM,UAAU,UAAU,QAAQ,wBAAwB;AAC1D,gBAAQ,QAAQ,EACb,KAAK,MAAM,OAAO,KAAK,iCAAiC,CAAC,EACzD,MAAM,CAAC,QAAe,OAAO,MAAM,iCAAiC,EAAE,IAAI,CAAC,CAAC;AAAA,MACjF,CAAC;AAAA,IACH;AAAA,EACF,OAAO;AAEL,UAAM,eAAe,CAAC,SAAiB,YAAY,MAAM,OAAO;AAEhE,cAAU,SAAS;AAAA,MACjB,uBAAuB,QAAQ,qBAAqB,EACjD,UAAU,EACV,OAAO,OAAO;AAAA,QACb,IAAI,MAAM,UAAU,QAAQ,IAAI;AAAA,QAChC;AAAA,QACA,aAAa,UAAU,QAAQ,aAAa;AAAA,QAC5C,QAAQ;AAAA,UACN,gBAAgB,SAAS,QAAQ,IAAI,8BAA8B,SAAS,EAAE;AAAA,QAChF;AAAA,MACF,EAAE;AAAA,IACN,CAAC;AAAA,EACH;AAGA,YAAU,SAAS;AAAA,IACjB,kBAAkB,QAAQ,gBAAgB,EACvC,UAAU,EACV,OAAO,OAAO;AAAA,MACb,IAAI,MAAM,UAAU,QAAQ,IAAI;AAAA,MAChC,eAAe,kBAAkB,UAC7B,UAAU,QAAQ,wBAAwB,IAC1C;AAAA,IACN,EAAE;AAAA,EACN,CAAC;AACH;",
6
6
  "names": []
7
7
  }
@@ -1,3 +1,5 @@
1
+ import { createLogger } from "@open-mercato/shared/lib/logger";
2
+ const logger = createLogger("scheduler").child({ component: "local" });
1
3
  class LocalLockStrategy {
2
4
  constructor(em) {
3
5
  this.em = em;
@@ -29,7 +31,7 @@ class LocalLockStrategy {
29
31
  if (lockAcquired) {
30
32
  throw error;
31
33
  }
32
- console.error("[scheduler:local] Failed to acquire lock:", error);
34
+ logger.error("Failed to acquire lock", { lockKey: key, err: error });
33
35
  return { acquired: false };
34
36
  }
35
37
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/scheduler/lib/localLockStrategy.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\n\n/**\n * PostgreSQL advisory lock strategy for single-instance or local development\n */\nexport class LocalLockStrategy {\n constructor(private em: () => EntityManager) {}\n\n /**\n * Execute a function under a PostgreSQL advisory lock.\n *\n * IMPORTANT: Uses transaction-scoped advisory locks (`pg_try_advisory_xact_lock`)\n * to avoid connection pool/session mismatch issues. The lock is automatically\n * released when the transaction ends.\n */\n async runWithLock<T>(key: string, fn: () => Promise<T>): Promise<{ acquired: boolean; result?: T }> {\n const em = this.em().fork()\n const hash = this.hashString(key)\n let lockAcquired = false\n\n try {\n return await em.transactional(async (txEm) => {\n const result = await txEm.getConnection().execute<{ acquired: boolean }[]>(\n `SELECT pg_try_advisory_xact_lock(?) as acquired`,\n [hash],\n )\n\n const acquired = result[0]?.acquired === true\n if (!acquired) return { acquired: false }\n lockAcquired = true\n\n const fnResult = await fn()\n return { acquired: true, result: fnResult }\n })\n } catch (error) {\n if (lockAcquired) {\n throw error\n }\n\n console.error('[scheduler:local] Failed to acquire lock:', error)\n return { acquired: false }\n }\n }\n\n /**\n * Convert string to integer hash for PostgreSQL advisory locks\n * PostgreSQL advisory locks use bigint, so we need to hash the string\n */\n private hashString(str: string): number {\n let hash = 0\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i)\n hash = ((hash << 5) - hash) + char\n hash = hash & hash // Convert to 32bit integer\n }\n return Math.abs(hash)\n }\n}\n"],
5
- "mappings": "AAKO,MAAM,kBAAkB;AAAA,EAC7B,YAAoB,IAAyB;AAAzB;AAAA,EAA0B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAS9C,MAAM,YAAe,KAAa,IAAkE;AAClG,UAAM,KAAK,KAAK,GAAG,EAAE,KAAK;AAC1B,UAAM,OAAO,KAAK,WAAW,GAAG;AAChC,QAAI,eAAe;AAEnB,QAAI;AACF,aAAO,MAAM,GAAG,cAAc,OAAO,SAAS;AAC5C,cAAM,SAAS,MAAM,KAAK,cAAc,EAAE;AAAA,UACxC;AAAA,UACA,CAAC,IAAI;AAAA,QACP;AAEA,cAAM,WAAW,OAAO,CAAC,GAAG,aAAa;AACzC,YAAI,CAAC,SAAU,QAAO,EAAE,UAAU,MAAM;AACxC,uBAAe;AAEf,cAAM,WAAW,MAAM,GAAG;AAC1B,eAAO,EAAE,UAAU,MAAM,QAAQ,SAAS;AAAA,MAC5C,CAAC;AAAA,IACH,SAAS,OAAO;AACd,UAAI,cAAc;AAChB,cAAM;AAAA,MACR;AAEA,cAAQ,MAAM,6CAA6C,KAAK;AAChE,aAAO,EAAE,UAAU,MAAM;AAAA,IAC3B;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,WAAW,KAAqB;AACtC,QAAI,OAAO;AACX,aAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,YAAM,OAAO,IAAI,WAAW,CAAC;AAC7B,cAAS,QAAQ,KAAK,OAAQ;AAC9B,aAAO,OAAO;AAAA,IAChB;AACA,WAAO,KAAK,IAAI,IAAI;AAAA,EACtB;AACF;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'local' })\n\n/**\n * PostgreSQL advisory lock strategy for single-instance or local development\n */\nexport class LocalLockStrategy {\n constructor(private em: () => EntityManager) {}\n\n /**\n * Execute a function under a PostgreSQL advisory lock.\n *\n * IMPORTANT: Uses transaction-scoped advisory locks (`pg_try_advisory_xact_lock`)\n * to avoid connection pool/session mismatch issues. The lock is automatically\n * released when the transaction ends.\n */\n async runWithLock<T>(key: string, fn: () => Promise<T>): Promise<{ acquired: boolean; result?: T }> {\n const em = this.em().fork()\n const hash = this.hashString(key)\n let lockAcquired = false\n\n try {\n return await em.transactional(async (txEm) => {\n const result = await txEm.getConnection().execute<{ acquired: boolean }[]>(\n `SELECT pg_try_advisory_xact_lock(?) as acquired`,\n [hash],\n )\n\n const acquired = result[0]?.acquired === true\n if (!acquired) return { acquired: false }\n lockAcquired = true\n\n const fnResult = await fn()\n return { acquired: true, result: fnResult }\n })\n } catch (error) {\n if (lockAcquired) {\n throw error\n }\n\n logger.error('Failed to acquire lock', { lockKey: key, err: error })\n return { acquired: false }\n }\n }\n\n /**\n * Convert string to integer hash for PostgreSQL advisory locks\n * PostgreSQL advisory locks use bigint, so we need to hash the string\n */\n private hashString(str: string): number {\n let hash = 0\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i)\n hash = ((hash << 5) - hash) + char\n hash = hash & hash // Convert to 32bit integer\n }\n return Math.abs(hash)\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,QAAQ,CAAC;AAK9D,MAAM,kBAAkB;AAAA,EAC7B,YAAoB,IAAyB;AAAzB;AAAA,EAA0B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAS9C,MAAM,YAAe,KAAa,IAAkE;AAClG,UAAM,KAAK,KAAK,GAAG,EAAE,KAAK;AAC1B,UAAM,OAAO,KAAK,WAAW,GAAG;AAChC,QAAI,eAAe;AAEnB,QAAI;AACF,aAAO,MAAM,GAAG,cAAc,OAAO,SAAS;AAC5C,cAAM,SAAS,MAAM,KAAK,cAAc,EAAE;AAAA,UACxC;AAAA,UACA,CAAC,IAAI;AAAA,QACP;AAEA,cAAM,WAAW,OAAO,CAAC,GAAG,aAAa;AACzC,YAAI,CAAC,SAAU,QAAO,EAAE,UAAU,MAAM;AACxC,uBAAe;AAEf,cAAM,WAAW,MAAM,GAAG;AAC1B,eAAO,EAAE,UAAU,MAAM,QAAQ,SAAS;AAAA,MAC5C,CAAC;AAAA,IACH,SAAS,OAAO;AACd,UAAI,cAAc;AAChB,cAAM;AAAA,MACR;AAEA,aAAO,MAAM,0BAA0B,EAAE,SAAS,KAAK,KAAK,MAAM,CAAC;AACnE,aAAO,EAAE,UAAU,MAAM;AAAA,IAC3B;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,WAAW,KAAqB;AACtC,QAAI,OAAO;AACX,aAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,YAAM,OAAO,IAAI,WAAW,CAAC;AAC7B,cAAS,QAAQ,KAAK,OAAQ;AAC9B,aAAO,OAAO;AAAA,IAChB;AACA,WAAO,KAAK,IAAI,IAAI;AAAA,EACtB;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,4 +1,6 @@
1
1
  import { ScheduledJob } from "../data/entities.js";
2
+ import { createLogger } from "@open-mercato/shared/lib/logger";
3
+ const logger = createLogger("scheduler").child({ component: "sync" });
2
4
  class ScheduledJobSubscriber {
3
5
  constructor() {
4
6
  this.bullmqService = null;
@@ -32,7 +34,7 @@ class ScheduledJobSubscriber {
32
34
  this.bullmqService = this.container.resolve("bullmqSchedulerService");
33
35
  }
34
36
  } catch (error) {
35
- console.warn("[scheduler:sync] Could not resolve BullMQSchedulerService:", error);
37
+ logger.warn("Could not resolve BullMQSchedulerService", { err: error });
36
38
  }
37
39
  }
38
40
  return this.bullmqService;
@@ -67,21 +69,21 @@ class ScheduledJobSubscriber {
67
69
  }
68
70
  if (schedule.isEnabled && !schedule.deletedAt) {
69
71
  await bullmqService.register(schedule, { skipNextRunUpdate: true });
70
- console.log(`[scheduler:sync] Synced ${changeSet.type} to BullMQ: ${schedule.name}`);
72
+ logger.info("Synced schedule to BullMQ", { changeType: changeSet.type, scheduleId: schedule.id, scheduleName: schedule.name });
71
73
  } else {
72
74
  await bullmqService.unregister(schedule.id);
73
- console.log(`[scheduler:sync] Removed from BullMQ: ${schedule.name}`);
75
+ logger.info("Removed schedule from BullMQ", { scheduleId: schedule.id, scheduleName: schedule.name });
74
76
  }
75
77
  } else if (changeSet.type === "delete") {
76
78
  await bullmqService.unregister(schedule.id);
77
- console.log(`[scheduler:sync] Removed from BullMQ (deleted): ${schedule.id}`);
79
+ logger.info("Removed deleted schedule from BullMQ", { scheduleId: schedule.id });
78
80
  }
79
81
  } catch (error) {
80
- console.error(`[scheduler:sync] Failed to sync with BullMQ:`, {
82
+ logger.error("Failed to sync with BullMQ", {
81
83
  scheduleId: schedule.id,
82
84
  scheduleName: schedule.name,
83
85
  changeType: changeSet.type,
84
- error: error instanceof Error ? error.message : String(error)
86
+ err: error
85
87
  });
86
88
  }
87
89
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/scheduler/lib/scheduledJobSubscriber.ts"],
4
- "sourcesContent": ["import type { \n EventArgs, \n EventSubscriber, \n FlushEventArgs \n} from '@mikro-orm/core'\nimport type { AwilixContainer } from 'awilix'\nimport { ScheduledJob } from '../data/entities.js'\nimport type { BullMQSchedulerService } from '../services/bullmqSchedulerService'\n\n/**\n * MikroORM Event Subscriber for ScheduledJob\n * \n * Automatically syncs schedule changes with BullMQ when using async strategy.\n * \n * This ensures that any database changes to schedules (via commands, direct ORM access,\n * or admin UI) are immediately reflected in BullMQ repeatable jobs.\n * \n * Only runs when QUEUE_STRATEGY=async to avoid unnecessary work in local mode.\n */\nexport class ScheduledJobSubscriber implements EventSubscriber<ScheduledJob> {\n private bullmqService: BullMQSchedulerService | null = null\n private queueStrategy: string\n private container: AwilixContainer | null = null\n\n constructor() {\n this.queueStrategy = process.env.QUEUE_STRATEGY || 'local'\n }\n\n /**\n * Set the DI container for resolving services.\n * Called during DI registration to provide access to the container.\n */\n setContainer(container: AwilixContainer): void {\n this.container = container\n }\n\n /**\n * Subscribe only to ScheduledJob entity\n */\n getSubscribedEntities() {\n return [ScheduledJob]\n }\n\n /**\n * Get BullMQ service from DI container\n * Only resolves if strategy is async\n */\n private async getBullMQService(): Promise<BullMQSchedulerService | null> {\n if (this.queueStrategy !== 'async') {\n return null\n }\n\n if (!this.bullmqService) {\n try {\n if (this.container?.hasRegistration?.('bullmqSchedulerService')) {\n this.bullmqService = this.container.resolve<BullMQSchedulerService>('bullmqSchedulerService')\n }\n } catch (error) {\n console.warn('[scheduler:sync] Could not resolve BullMQSchedulerService:', error)\n }\n }\n\n return this.bullmqService\n }\n\n /**\n * After flush: sync all changed schedules with BullMQ\n * \n * This runs after the transaction commits, so we're guaranteed\n * the database state is consistent.\n */\n async afterFlush(args: FlushEventArgs): Promise<void> {\n if (this.queueStrategy !== 'async') {\n return\n }\n\n const bullmqService = await this.getBullMQService()\n if (!bullmqService) {\n return\n }\n\n const uow = args.uow\n const changeSets = uow.getChangeSets()\n\n for (const changeSet of changeSets) {\n if (changeSet.entity instanceof ScheduledJob) {\n const schedule = changeSet.entity\n\n try {\n if (changeSet.type === 'create' || changeSet.type === 'update') {\n // Skip BullMQ sync when only execution timestamps changed (lastRunAt/nextRunAt).\n // The worker updates these after every run \u2014 the repeatable job config hasn't changed.\n if (changeSet.type === 'update' && changeSet.payload) {\n const runTimeOnly = ['lastRunAt', 'nextRunAt', 'updatedAt']\n const changedFields = Object.keys(changeSet.payload)\n if (changedFields.length > 0 && changedFields.every(f => runTimeOnly.includes(f))) {\n continue\n }\n }\n\n // Register or update in BullMQ\n if (schedule.isEnabled && !schedule.deletedAt) {\n // Skip nextRunAt update since we're in afterFlush - it's already persisted\n await bullmqService.register(schedule, { skipNextRunUpdate: true })\n console.log(`[scheduler:sync] Synced ${changeSet.type} to BullMQ: ${schedule.name}`)\n } else {\n // Disabled or soft-deleted - remove from BullMQ\n await bullmqService.unregister(schedule.id)\n console.log(`[scheduler:sync] Removed from BullMQ: ${schedule.name}`)\n }\n } else if (changeSet.type === 'delete') {\n // Hard delete - remove from BullMQ\n await bullmqService.unregister(schedule.id)\n console.log(`[scheduler:sync] Removed from BullMQ (deleted): ${schedule.id}`)\n }\n } catch (error) {\n // Don't throw - we don't want to break the transaction\n // BullMQ sync is best-effort, DB is source of truth\n console.error(`[scheduler:sync] Failed to sync with BullMQ:`, {\n scheduleId: schedule.id,\n scheduleName: schedule.name,\n changeType: changeSet.type,\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n }\n }\n}\n"],
5
- "mappings": "AAMA,SAAS,oBAAoB;AAatB,MAAM,uBAAgE;AAAA,EAK3E,cAAc;AAJd,SAAQ,gBAA+C;AAEvD,SAAQ,YAAoC;AAG1C,SAAK,gBAAgB,QAAQ,IAAI,kBAAkB;AAAA,EACrD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,aAAa,WAAkC;AAC7C,SAAK,YAAY;AAAA,EACnB;AAAA;AAAA;AAAA;AAAA,EAKA,wBAAwB;AACtB,WAAO,CAAC,YAAY;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,mBAA2D;AACvE,QAAI,KAAK,kBAAkB,SAAS;AAClC,aAAO;AAAA,IACT;AAEA,QAAI,CAAC,KAAK,eAAe;AACvB,UAAI;AACF,YAAI,KAAK,WAAW,kBAAkB,wBAAwB,GAAG;AAC/D,eAAK,gBAAgB,KAAK,UAAU,QAAgC,wBAAwB;AAAA,QAC9F;AAAA,MACF,SAAS,OAAO;AACd,gBAAQ,KAAK,8DAA8D,KAAK;AAAA,MAClF;AAAA,IACF;AAEA,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,WAAW,MAAqC;AACpD,QAAI,KAAK,kBAAkB,SAAS;AAClC;AAAA,IACF;AAEA,UAAM,gBAAgB,MAAM,KAAK,iBAAiB;AAClD,QAAI,CAAC,eAAe;AAClB;AAAA,IACF;AAEA,UAAM,MAAM,KAAK;AACjB,UAAM,aAAa,IAAI,cAAc;AAErC,eAAW,aAAa,YAAY;AAClC,UAAI,UAAU,kBAAkB,cAAc;AAC5C,cAAM,WAAW,UAAU;AAE3B,YAAI;AACF,cAAI,UAAU,SAAS,YAAY,UAAU,SAAS,UAAU;AAG9D,gBAAI,UAAU,SAAS,YAAY,UAAU,SAAS;AACpD,oBAAM,cAAc,CAAC,aAAa,aAAa,WAAW;AAC1D,oBAAM,gBAAgB,OAAO,KAAK,UAAU,OAAO;AACnD,kBAAI,cAAc,SAAS,KAAK,cAAc,MAAM,OAAK,YAAY,SAAS,CAAC,CAAC,GAAG;AACjF;AAAA,cACF;AAAA,YACF;AAGA,gBAAI,SAAS,aAAa,CAAC,SAAS,WAAW;AAE7C,oBAAM,cAAc,SAAS,UAAU,EAAE,mBAAmB,KAAK,CAAC;AAClE,sBAAQ,IAAI,2BAA2B,UAAU,IAAI,eAAe,SAAS,IAAI,EAAE;AAAA,YACrF,OAAO;AAEL,oBAAM,cAAc,WAAW,SAAS,EAAE;AAC1C,sBAAQ,IAAI,yCAAyC,SAAS,IAAI,EAAE;AAAA,YACtE;AAAA,UACF,WAAW,UAAU,SAAS,UAAU;AAEtC,kBAAM,cAAc,WAAW,SAAS,EAAE;AAC1C,oBAAQ,IAAI,mDAAmD,SAAS,EAAE,EAAE;AAAA,UAC9E;AAAA,QACF,SAAS,OAAO;AAGd,kBAAQ,MAAM,gDAAgD;AAAA,YAC5D,YAAY,SAAS;AAAA,YACrB,cAAc,SAAS;AAAA,YACvB,YAAY,UAAU;AAAA,YACtB,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,UAC9D,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import type { \n EventArgs, \n EventSubscriber, \n FlushEventArgs \n} from '@mikro-orm/core'\nimport type { AwilixContainer } from 'awilix'\nimport { ScheduledJob } from '../data/entities.js'\nimport type { BullMQSchedulerService } from '../services/bullmqSchedulerService'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'sync' })\n\n/**\n * MikroORM Event Subscriber for ScheduledJob\n * \n * Automatically syncs schedule changes with BullMQ when using async strategy.\n * \n * This ensures that any database changes to schedules (via commands, direct ORM access,\n * or admin UI) are immediately reflected in BullMQ repeatable jobs.\n * \n * Only runs when QUEUE_STRATEGY=async to avoid unnecessary work in local mode.\n */\nexport class ScheduledJobSubscriber implements EventSubscriber<ScheduledJob> {\n private bullmqService: BullMQSchedulerService | null = null\n private queueStrategy: string\n private container: AwilixContainer | null = null\n\n constructor() {\n this.queueStrategy = process.env.QUEUE_STRATEGY || 'local'\n }\n\n /**\n * Set the DI container for resolving services.\n * Called during DI registration to provide access to the container.\n */\n setContainer(container: AwilixContainer): void {\n this.container = container\n }\n\n /**\n * Subscribe only to ScheduledJob entity\n */\n getSubscribedEntities() {\n return [ScheduledJob]\n }\n\n /**\n * Get BullMQ service from DI container\n * Only resolves if strategy is async\n */\n private async getBullMQService(): Promise<BullMQSchedulerService | null> {\n if (this.queueStrategy !== 'async') {\n return null\n }\n\n if (!this.bullmqService) {\n try {\n if (this.container?.hasRegistration?.('bullmqSchedulerService')) {\n this.bullmqService = this.container.resolve<BullMQSchedulerService>('bullmqSchedulerService')\n }\n } catch (error) {\n logger.warn('Could not resolve BullMQSchedulerService', { err: error })\n }\n }\n\n return this.bullmqService\n }\n\n /**\n * After flush: sync all changed schedules with BullMQ\n * \n * This runs after the transaction commits, so we're guaranteed\n * the database state is consistent.\n */\n async afterFlush(args: FlushEventArgs): Promise<void> {\n if (this.queueStrategy !== 'async') {\n return\n }\n\n const bullmqService = await this.getBullMQService()\n if (!bullmqService) {\n return\n }\n\n const uow = args.uow\n const changeSets = uow.getChangeSets()\n\n for (const changeSet of changeSets) {\n if (changeSet.entity instanceof ScheduledJob) {\n const schedule = changeSet.entity\n\n try {\n if (changeSet.type === 'create' || changeSet.type === 'update') {\n // Skip BullMQ sync when only execution timestamps changed (lastRunAt/nextRunAt).\n // The worker updates these after every run \u2014 the repeatable job config hasn't changed.\n if (changeSet.type === 'update' && changeSet.payload) {\n const runTimeOnly = ['lastRunAt', 'nextRunAt', 'updatedAt']\n const changedFields = Object.keys(changeSet.payload)\n if (changedFields.length > 0 && changedFields.every(f => runTimeOnly.includes(f))) {\n continue\n }\n }\n\n // Register or update in BullMQ\n if (schedule.isEnabled && !schedule.deletedAt) {\n // Skip nextRunAt update since we're in afterFlush - it's already persisted\n await bullmqService.register(schedule, { skipNextRunUpdate: true })\n logger.info('Synced schedule to BullMQ', { changeType: changeSet.type, scheduleId: schedule.id, scheduleName: schedule.name })\n } else {\n // Disabled or soft-deleted - remove from BullMQ\n await bullmqService.unregister(schedule.id)\n logger.info('Removed schedule from BullMQ', { scheduleId: schedule.id, scheduleName: schedule.name })\n }\n } else if (changeSet.type === 'delete') {\n // Hard delete - remove from BullMQ\n await bullmqService.unregister(schedule.id)\n logger.info('Removed deleted schedule from BullMQ', { scheduleId: schedule.id })\n }\n } catch (error) {\n // Don't throw - we don't want to break the transaction\n // BullMQ sync is best-effort, DB is source of truth\n logger.error('Failed to sync with BullMQ', {\n scheduleId: schedule.id,\n scheduleName: schedule.name,\n changeType: changeSet.type,\n err: error,\n })\n }\n }\n }\n }\n}\n"],
5
+ "mappings": "AAMA,SAAS,oBAAoB;AAE7B,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,OAAO,CAAC;AAY7D,MAAM,uBAAgE;AAAA,EAK3E,cAAc;AAJd,SAAQ,gBAA+C;AAEvD,SAAQ,YAAoC;AAG1C,SAAK,gBAAgB,QAAQ,IAAI,kBAAkB;AAAA,EACrD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,aAAa,WAAkC;AAC7C,SAAK,YAAY;AAAA,EACnB;AAAA;AAAA;AAAA;AAAA,EAKA,wBAAwB;AACtB,WAAO,CAAC,YAAY;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,mBAA2D;AACvE,QAAI,KAAK,kBAAkB,SAAS;AAClC,aAAO;AAAA,IACT;AAEA,QAAI,CAAC,KAAK,eAAe;AACvB,UAAI;AACF,YAAI,KAAK,WA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,kBAAM,cAAc,WAAW,SAAS,EAAE;AAC1C,mBAAO,KAAK,wCAAwC,EAAE,YAAY,SAAS,GAAG,CAAC;AAAA,UACjF;AAAA,QACF,SAAS,OAAO;AAGd,iBAAO,MAAM,8BAA8B;AAAA,YACzC,YAAY,SAAS;AAAA,YACrB,cAAc,SAAS;AAAA,YACvB,YAAY,UAAU;AAAA,YACtB,KAAK;AAAA,UACP,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -3,6 +3,8 @@ import { recalculateNextRun } from "../lib/nextRunCalculator.js";
3
3
  import { parseCronExpression } from "../lib/cronParser.js";
4
4
  import { parseInterval } from "../lib/intervalParser.js";
5
5
  import { getRedisUrlOrThrow } from "@open-mercato/shared/lib/redis/connection";
6
+ import { createLogger } from "@open-mercato/shared/lib/logger";
7
+ const logger = createLogger("scheduler").child({ component: "bullmq" });
6
8
  class BullMQSchedulerService {
7
9
  constructor(em) {
8
10
  this.em = em;
@@ -54,7 +56,7 @@ class BullMQSchedulerService {
54
56
  */
55
57
  async register(schedule, options = {}) {
56
58
  if (!schedule.isEnabled) {
57
- console.debug(`[scheduler:bullmq] Skipping disabled schedule: ${schedule.id}`);
59
+ logger.debug("Skipping disabled schedule", { scheduleId: schedule.id });
58
60
  return;
59
61
  }
60
62
  try {
@@ -82,14 +84,13 @@ class BullMQSchedulerService {
82
84
  },
83
85
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
84
86
  };
85
- console.debug(`[scheduler:bullmq] Adding repeatable job with data:`, {
87
+ logger.debug("Adding repeatable job", {
86
88
  jobName,
87
89
  scheduleId: schedule.id,
88
90
  scopeType: schedule.scopeType,
89
91
  tenantId: schedule.tenantId,
90
92
  organizationId: schedule.organizationId,
91
- repeatOpts,
92
- jobData
93
+ repeatOpts
93
94
  });
94
95
  await queue.add(
95
96
  jobName,
@@ -113,13 +114,15 @@ class BullMQSchedulerService {
113
114
  }
114
115
  }
115
116
  );
116
- console.debug(`[scheduler:bullmq] Registered schedule: ${schedule.name} (${schedule.id})`, {
117
+ logger.debug("Registered schedule", {
118
+ scheduleId: schedule.id,
119
+ scheduleName: schedule.name,
117
120
  type: schedule.scheduleType,
118
121
  pattern: schedule.scheduleValue,
119
122
  timezone: schedule.timezone
120
123
  });
121
124
  } catch (error) {
122
- console.error(`[scheduler:bullmq] Failed to register schedule: ${schedule.id}`, error);
125
+ logger.error("Failed to register schedule", { scheduleId: schedule.id, err: error });
123
126
  throw error;
124
127
  }
125
128
  }
@@ -131,12 +134,12 @@ class BullMQSchedulerService {
131
134
  const queue = await this.getQueue();
132
135
  const removed = await this.removeRepeatableJobsForSchedule(queue, scheduleId);
133
136
  if (removed > 0) {
134
- console.debug(`[scheduler:bullmq] Unregistered schedule: ${scheduleId}`);
137
+ logger.debug("Unregistered schedule", { scheduleId });
135
138
  } else {
136
- console.debug(`[scheduler:bullmq] No repeatable job found for schedule: ${scheduleId}`);
139
+ logger.debug("No repeatable job found for schedule", { scheduleId });
137
140
  }
138
141
  } catch (error) {
139
- console.error(`[scheduler:bullmq] Failed to unregister schedule: ${scheduleId}`, error);
142
+ logger.error("Failed to unregister schedule", { scheduleId, err: error });
140
143
  throw error;
141
144
  }
142
145
  }
@@ -147,7 +150,7 @@ class BullMQSchedulerService {
147
150
  async syncAll() {
148
151
  const em = this.em().fork();
149
152
  const queue = await this.getQueue();
150
- console.debug("[scheduler:bullmq] Starting full sync...");
153
+ logger.debug("Starting full sync");
151
154
  const repeatableJobs = await queue.getRepeatableJobs?.() || [];
152
155
  const bullmqScheduleIds = /* @__PURE__ */ new Set();
153
156
  const bullmqScheduleCounts = /* @__PURE__ */ new Map();
@@ -172,20 +175,20 @@ class BullMQSchedulerService {
172
175
  const dbScheduleIds = new Set(dbSchedules.map((s) => s.id));
173
176
  for (const schedule of dbSchedules) {
174
177
  if (!bullmqScheduleIds.has(schedule.id)) {
175
- console.debug(`[scheduler:bullmq] Registering missing schedule: ${schedule.name}`);
178
+ logger.debug("Registering missing schedule", { scheduleId: schedule.id, scheduleName: schedule.name });
176
179
  await this.register(schedule);
177
180
  } else if ((bullmqScheduleCounts.get(schedule.id) ?? 0) > 1) {
178
- console.log(`[scheduler:bullmq] Repairing duplicate repeatable jobs for schedule: ${schedule.id}`);
181
+ logger.info("Repairing duplicate repeatable jobs", { scheduleId: schedule.id });
179
182
  await this.register(schedule);
180
183
  }
181
184
  }
182
185
  for (const scheduleId of bullmqScheduleIds) {
183
186
  if (!dbScheduleIds.has(scheduleId)) {
184
- console.log(`[scheduler:bullmq] Removing orphaned schedule: ${scheduleId}`);
187
+ logger.info("Removing orphaned schedule", { scheduleId });
185
188
  await this.unregister(String(scheduleId));
186
189
  }
187
190
  }
188
- console.debug(`[scheduler:bullmq] Sync complete - ${dbSchedules.length} schedules active`);
191
+ logger.debug("Sync complete", { activeSchedules: dbSchedules.length });
189
192
  }
190
193
  /**
191
194
  * Build BullMQ repeat options from schedule configuration
@@ -216,7 +219,7 @@ class BullMQSchedulerService {
216
219
  const queue = await this.getQueue();
217
220
  return await queue.getRepeatableJobs?.() || [];
218
221
  } catch (error) {
219
- console.error("[scheduler:bullmq] Failed to get repeatable jobs:", error);
222
+ logger.error("Failed to get repeatable jobs", { err: error });
220
223
  return [];
221
224
  }
222
225
  }
@@ -229,9 +232,9 @@ class BullMQSchedulerService {
229
232
  try {
230
233
  await this.queue.close();
231
234
  this.queue = null;
232
- console.debug("[scheduler:bullmq] Queue connection closed");
235
+ logger.debug("Queue connection closed");
233
236
  } catch (error) {
234
- console.error("[scheduler:bullmq] Error closing queue:", error);
237
+ logger.error("Error closing queue", { err: error });
235
238
  }
236
239
  }
237
240
  }
@@ -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 { parseInterval } from '../lib/intervalParser'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\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 console.debug(`[scheduler:bullmq] Skipping disabled schedule: ${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 console.debug(`[scheduler:bullmq] Adding repeatable job with data:`, {\n jobName,\n scheduleId: schedule.id,\n scopeType: schedule.scopeType,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n repeatOpts,\n jobData,\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 console.debug(`[scheduler:bullmq] Registered schedule: ${schedule.name} (${schedule.id})`, {\n type: schedule.scheduleType,\n pattern: schedule.scheduleValue,\n timezone: schedule.timezone,\n })\n } catch (error: unknown) {\n console.error(`[scheduler:bullmq] Failed to register schedule: ${schedule.id}`, 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 console.debug(`[scheduler:bullmq] Unregistered schedule: ${scheduleId}`)\n } else {\n console.debug(`[scheduler:bullmq] No repeatable job found for schedule: ${scheduleId}`)\n }\n } catch (error: unknown) {\n console.error(`[scheduler:bullmq] Failed to unregister schedule: ${scheduleId}`, 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 console.debug('[scheduler:bullmq] 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 console.debug(`[scheduler:bullmq] Registering missing schedule: ${schedule.name}`)\n await this.register(schedule)\n } else if ((bullmqScheduleCounts.get(schedule.id) ?? 0) > 1) {\n console.log(`[scheduler:bullmq] Repairing duplicate repeatable jobs for schedule: ${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 console.log(`[scheduler:bullmq] Removing orphaned schedule: ${scheduleId}`)\n await this.unregister(String(scheduleId))\n }\n }\n\n console.debug(`[scheduler:bullmq] Sync complete - ${dbSchedules.length} schedules active`)\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 console.error('[scheduler:bullmq] Failed to get repeatable jobs:', 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 console.debug('[scheduler:bullmq] Queue connection closed')\n } catch (error) {\n console.error('[scheduler:bullmq] Error closing queue:', error)\n }\n }\n }\n}\n"],
5
- "mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AACpC,SAAS,qBAAqB;AAC9B,SAAS,0BAA0B;AAsC5B,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;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,+BAA+B,KAAuC;AAC5E,UAAM,YAAY,IAAI,IAAI,WAAW,WAAW,IAC5C,IAAI,KACJ,IAAI,MAAM,WAAW,WAAW,IAC9B,IAAI,OAC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AAAA,IACF;AAEA,YAAQ,MAAM,sCAAsC,YAAY,MAAM,mBAAmB;AAAA,EAC3F;AAAA;AAAA;AAAA;AAAA,EAKQ,mBAAmB,UAA2C;AACpE,UAAM,OAA0B;AAAA,MAC9B,IAAI,SAAS,YAAY;AAAA,IAC3B;AAEA,QAAI,SAAS,iBAAiB,QAAQ;AAEpC,YAAM,aAAa,oBAAoB,SAAS,eAAe,SAAS,YAAY,KAAK;AACzF,UAAI,CAAC,WAAW,SAAS;AACvB,cAAM,IAAI,MAAM,WAAW,SAAS,yBAAyB;AAAA,MAC/D;AACA,WAAK,UAAU,SAAS;AAAA,IAC1B,WAAW,SAAS,iBAAiB,YAAY;AAE/C,YAAM,aAAa,cAAc,SAAS,aAAa;AACvD,WAAK,QAAQ;AAAA,IACf,OAAO;AACL,YAAM,IAAI,MAAM,8BAA8B,SAAS,YAAY,EAAE;AAAA,IACvE;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,oBAAwC;AAC5C,QAAI;AACF,YAAM,QAAQ,MAAM,KAAK,SAAS;AAClC,aAAO,MAAM,MAAM,oBAAoB,KAAK,CAAC;AAAA,IAC/C,SAAS,OAAO;AACd,cAAQ,MAAM,qDAAqD,KAAK;AACxE,aAAO,CAAC;AAAA,IACV;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,UAAyB;AAC7B,QAAI,KAAK,OAAO;AACd,UAAI;AACF,cAAM,KAAK,MAAM,MAAM;AACvB,aAAK,QAAQ;AACb,gBAAQ,MAAM,4CAA4C;AAAA,MAC5D,SAAS,OAAO;AACd,gBAAQ,MAAM,2CAA2C,KAAK;AAAA,MAChE;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;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,+BAA+B,KAAuC;AAC5E,UAAM,YAAY,IAAI,IAAI,WAAW,WAAW,IAC5C,IAAI,KACJ,IAAI,MAAM,WAAW,WAAW,IAC9B,IAAI,OACJ;AAEN,WAAO,YAAY,UAAU,MAAM,YAAY,MAAM,IAAI;AAAA,EAC3D;AAAA,E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js";
6
6
  import { getGlobalEventBus } from "@open-mercato/shared/modules/events";
7
7
  import { buildScheduledCommandContext } from "../lib/commandContext.js";
8
+ import { createLogger } from "@open-mercato/shared/lib/logger";
9
+ const logger = createLogger("scheduler").child({ component: "local" });
8
10
  class LocalSchedulerService {
9
11
  constructor(em, queueFactory, rbacService, config = { pollIntervalMs: 3e4 }) {
10
12
  this.em = em;
@@ -19,31 +21,30 @@ class LocalSchedulerService {
19
21
  */
20
22
  async start() {
21
23
  if (this.isRunning) {
22
- console.warn("[scheduler:local] Already running");
24
+ logger.warn("Polling engine already running");
23
25
  return;
24
26
  }
25
27
  this.isRunning = true;
26
- console.log("[scheduler:local] Starting polling engine...");
27
- console.log(`[scheduler:local] Poll interval: ${this.config.pollIntervalMs}ms`);
28
+ logger.info("Starting polling engine", { pollIntervalMs: this.config.pollIntervalMs });
28
29
  await this.poll();
29
30
  this.pollTimer = setInterval(() => {
30
31
  this.poll().catch((error) => {
31
- console.error("[scheduler:local] Poll error:", error);
32
+ logger.error("Poll error", { err: error });
32
33
  });
33
34
  }, this.config.pollIntervalMs);
34
- console.log("[scheduler:local] \u2713 Polling engine started");
35
+ logger.info("Polling engine started");
35
36
  }
36
37
  /**
37
38
  * Stop the local scheduler
38
39
  */
39
40
  async stop() {
40
- console.log("[scheduler:local] Stopping polling engine...");
41
+ logger.info("Stopping polling engine");
41
42
  this.isRunning = false;
42
43
  if (this.pollTimer) {
43
44
  clearInterval(this.pollTimer);
44
45
  this.pollTimer = void 0;
45
46
  }
46
- console.log("[scheduler:local] \u2713 Polling engine stopped");
47
+ logger.info("Polling engine stopped");
47
48
  }
48
49
  /**
49
50
  * Poll for due schedules and execute them
@@ -63,15 +64,15 @@ class LocalSchedulerService {
63
64
  orderBy: { nextRunAt: "ASC" }
64
65
  });
65
66
  if (dueSchedules.length === 0) {
66
- console.log("[scheduler:local] No due schedules");
67
+ logger.debug("No due schedules");
67
68
  return;
68
69
  }
69
- console.log(`[scheduler:local] Found ${dueSchedules.length} due schedule(s)`);
70
+ logger.info("Found due schedules", { count: dueSchedules.length });
70
71
  for (const schedule of dueSchedules) {
71
72
  await this.executeSchedule(schedule);
72
73
  }
73
74
  } catch (error) {
74
- console.error("[scheduler:local] Poll failed:", error);
75
+ logger.error("Poll failed", { err: error });
75
76
  }
76
77
  }
77
78
  /**
@@ -79,8 +80,9 @@ class LocalSchedulerService {
79
80
  */
80
81
  async executeSchedule(schedule) {
81
82
  const lockKey = `schedule:${schedule.id}`;
83
+ const scheduleLogger = logger.child({ scheduleId: schedule.id, scheduleName: schedule.name });
82
84
  const { acquired } = await this.lockStrategy.runWithLock(lockKey, async () => {
83
- console.log(`[scheduler:local] Executing schedule: ${schedule.name} (${schedule.id})`);
85
+ scheduleLogger.info("Executing schedule");
84
86
  await emitSchedulerEvent("scheduler.job.started", {
85
87
  id: schedule.id,
86
88
  tenantId: schedule.tenantId,
@@ -94,7 +96,7 @@ class LocalSchedulerService {
94
96
  if (schedule.requireFeature) {
95
97
  const hasFeature = await this.checkFeature(schedule);
96
98
  if (!hasFeature) {
97
- console.log(`[scheduler:local] Schedule ${schedule.name} skipped: missing feature ${schedule.requireFeature}`);
99
+ scheduleLogger.info("Schedule skipped: missing required feature", { requireFeature: schedule.requireFeature });
98
100
  await emitSchedulerEvent("scheduler.job.skipped", {
99
101
  id: schedule.id,
100
102
  tenantId: schedule.tenantId,
@@ -129,7 +131,7 @@ class LocalSchedulerService {
129
131
  }
130
132
  await em.flush();
131
133
  }
132
- console.log(`[scheduler:local] \u2713 Schedule ${schedule.name} completed successfully`);
134
+ scheduleLogger.info("Schedule completed");
133
135
  await emitSchedulerEvent("scheduler.job.completed", {
134
136
  id: schedule.id,
135
137
  tenantId: schedule.tenantId,
@@ -139,7 +141,7 @@ class LocalSchedulerService {
139
141
  completedAt: /* @__PURE__ */ new Date()
140
142
  });
141
143
  } catch (error) {
142
- console.error(`[scheduler:local] \u2717 Schedule ${schedule.name} failed:`, error);
144
+ scheduleLogger.error("Schedule failed", { err: error });
143
145
  await emitSchedulerEvent("scheduler.job.failed", {
144
146
  id: schedule.id,
145
147
  tenantId: schedule.tenantId,
@@ -153,7 +155,7 @@ class LocalSchedulerService {
153
155
  }
154
156
  });
155
157
  if (!acquired) {
156
- console.log(`[scheduler:local] Schedule ${schedule.name} is already locked, skipping`);
158
+ scheduleLogger.debug("Schedule already locked, skipping");
157
159
  return;
158
160
  }
159
161
  }
@@ -174,7 +176,7 @@ class LocalSchedulerService {
174
176
  payload: schedule.targetPayload || {},
175
177
  triggeredAt: /* @__PURE__ */ new Date()
176
178
  });
177
- console.log(`[scheduler:local] Enqueued job to queue: ${schedule.targetQueue}`);
179
+ logger.info("Enqueued job to target queue", { scheduleId: schedule.id, targetQueue: schedule.targetQueue });
178
180
  }
179
181
  /**
180
182
  * Execute a command-based target
@@ -200,11 +202,11 @@ class LocalSchedulerService {
200
202
  }
201
203
  }
202
204
  );
203
- const result = await commandBus.execute(schedule.targetCommand, {
205
+ await commandBus.execute(schedule.targetCommand, {
204
206
  input: commandInput,
205
207
  ctx: commandCtx
206
208
  });
207
- console.log(`[scheduler:local] Executed command: ${schedule.targetCommand}`, result);
209
+ logger.info("Executed command", { scheduleId: schedule.id, targetCommand: schedule.targetCommand });
208
210
  }
209
211
  /**
210
212
  * Check if user/tenant has required feature
@@ -226,7 +228,7 @@ class LocalSchedulerService {
226
228
  );
227
229
  return hasFeature;
228
230
  } catch (error) {
229
- console.error("[scheduler:local] Feature check failed:", error);
231
+ logger.error("Feature check failed", { scheduleId: schedule.id, err: error });
230
232
  return false;
231
233
  }
232
234
  }
@@ -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 { buildScheduledCommandContext } from '../lib/commandContext.js'\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 * - 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 console.warn('[scheduler:local] Already running')\n return\n }\n\n this.isRunning = true\n console.log('[scheduler:local] Starting polling engine...')\n console.log(`[scheduler:local] Poll interval: ${this.config.pollIntervalMs}ms`)\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 console.error('[scheduler:local] Poll error:', error)\n })\n }, this.config.pollIntervalMs)\n\n console.log('[scheduler:local] \u2713 Polling engine started')\n }\n\n /**\n * Stop the local scheduler\n */\n async stop(): Promise<void> {\n console.log('[scheduler:local] Stopping polling engine...')\n this.isRunning = false\n \n if (this.pollTimer) {\n clearInterval(this.pollTimer)\n this.pollTimer = undefined\n }\n\n console.log('[scheduler:local] \u2713 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 console.log('[scheduler:local] No due schedules')\n return\n }\n\n console.log(`[scheduler:local] Found ${dueSchedules.length} due schedule(s)`)\n\n // Execute each schedule\n for (const schedule of dueSchedules) {\n await this.executeSchedule(schedule)\n }\n } catch (error: unknown) {\n console.error('[scheduler:local] Poll failed:', 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\n const { acquired } = await this.lockStrategy.runWithLock(lockKey, async () => {\n console.log(`[scheduler:local] Executing schedule: ${schedule.name} (${schedule.id})`)\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 console.log(`[scheduler:local] Schedule ${schedule.name} skipped: missing feature ${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 console.log(`[scheduler:local] \u2713 Schedule ${schedule.name} completed successfully`)\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 console.error(`[scheduler:local] \u2717 Schedule ${schedule.name} failed:`, 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 console.log(`[scheduler:local] Schedule ${schedule.name} is 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 await queue.enqueue({\n scheduleId: schedule.id,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n payload: schedule.targetPayload || {},\n triggeredAt: new Date(),\n })\n\n console.log(`[scheduler:local] Enqueued job to queue: ${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 const result = await commandBus.execute(schedule.targetCommand, {\n input: commandInput,\n ctx: commandCtx,\n })\n\n console.log(`[scheduler:local] Executed command: ${schedule.targetCommand}`, result)\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 console.error('[scheduler:local] Feature check failed:', 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 fre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AAE;AAAA,QACvE;AAAA,MACF;AAAA,IACF;AAEA,UAAM,SAAS,MAAM,WAAW,QAAQ,SAAS,eAAe;AAAA,MAC9D,OAAO;AAAA,MACP,KAAK;AAAA,IACP,CAAC;AAED,YAAQ,IAAI,uCAAuC,SAAS,aAAa,IAAI,MAAM;AAAA,EACrF;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,cAAQ,MAAM,2CAA2C,KAAK;AAC9D,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 { 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 * - 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 await queue.enqueue({\n scheduleId: schedule.id,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n payload: schedule.targetPayload || {},\n triggeredAt: new Date(),\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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