@open-mercato/scheduler 0.6.7 → 0.6.8-develop.6875.1.871a4afc94

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 (69) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/scheduler/__integration__/TC-SCHED-007.spec.js +4 -1
  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 +4 -2
  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 +4 -2
  7. package/dist/modules/scheduler/api/queue-jobs/[jobId]/route.js.map +2 -2
  8. package/dist/modules/scheduler/api/targets/route.js +5 -4
  9. package/dist/modules/scheduler/api/targets/route.js.map +2 -2
  10. package/dist/modules/scheduler/commands/jobs.js +33 -14
  11. package/dist/modules/scheduler/commands/jobs.js.map +2 -2
  12. package/dist/modules/scheduler/components/ExecutionDetailsDialog.js +1 -1
  13. package/dist/modules/scheduler/components/ExecutionDetailsDialog.js.map +2 -2
  14. package/dist/modules/scheduler/components/JobLogsModal.js +1 -1
  15. package/dist/modules/scheduler/components/JobLogsModal.js.map +2 -2
  16. package/dist/modules/scheduler/data/validators.js +27 -1
  17. package/dist/modules/scheduler/data/validators.js.map +2 -2
  18. package/dist/modules/scheduler/i18n/de.json +2 -0
  19. package/dist/modules/scheduler/i18n/en.json +2 -0
  20. package/dist/modules/scheduler/i18n/es.json +2 -0
  21. package/dist/modules/scheduler/i18n/ko.json +157 -0
  22. package/dist/modules/scheduler/i18n/pl.json +2 -0
  23. package/dist/modules/scheduler/lib/activeScheduleLimits.js +44 -0
  24. package/dist/modules/scheduler/lib/activeScheduleLimits.js.map +7 -0
  25. package/dist/modules/scheduler/lib/intervalParser.js +8 -3
  26. package/dist/modules/scheduler/lib/intervalParser.js.map +2 -2
  27. package/dist/modules/scheduler/lib/nextRunCalculator.js +8 -1
  28. package/dist/modules/scheduler/lib/nextRunCalculator.js.map +2 -2
  29. package/dist/modules/scheduler/lib/scheduler-safe-commands.js +73 -0
  30. package/dist/modules/scheduler/lib/scheduler-safe-commands.js.map +7 -0
  31. package/dist/modules/scheduler/services/bullmqSchedulerService.js +92 -43
  32. package/dist/modules/scheduler/services/bullmqSchedulerService.js.map +2 -2
  33. package/dist/modules/scheduler/services/localSchedulerService.js +9 -0
  34. package/dist/modules/scheduler/services/localSchedulerService.js.map +2 -2
  35. package/dist/modules/scheduler/services/schedulerService.js +23 -11
  36. package/dist/modules/scheduler/services/schedulerService.js.map +2 -2
  37. package/dist/modules/scheduler/workers/execute-schedule.worker.js +9 -0
  38. package/dist/modules/scheduler/workers/execute-schedule.worker.js.map +2 -2
  39. package/package.json +10 -9
  40. package/src/modules/scheduler/__integration__/TC-SCHED-007.spec.ts +6 -4
  41. package/src/modules/scheduler/api/jobs/[id]/executions/route.ts +4 -2
  42. package/src/modules/scheduler/api/queue-jobs/[jobId]/route.ts +4 -2
  43. package/src/modules/scheduler/api/targets/__tests__/route.test.ts +76 -0
  44. package/src/modules/scheduler/api/targets/route.ts +7 -7
  45. package/src/modules/scheduler/commands/__tests__/jobs.active-limit.test.ts +184 -0
  46. package/src/modules/scheduler/commands/jobs.ts +40 -15
  47. package/src/modules/scheduler/components/ExecutionDetailsDialog.tsx +1 -1
  48. package/src/modules/scheduler/components/JobLogsModal.tsx +1 -1
  49. package/src/modules/scheduler/data/__tests__/validators.test.ts +69 -9
  50. package/src/modules/scheduler/data/validators.ts +30 -1
  51. package/src/modules/scheduler/i18n/de.json +2 -0
  52. package/src/modules/scheduler/i18n/en.json +2 -0
  53. package/src/modules/scheduler/i18n/es.json +2 -0
  54. package/src/modules/scheduler/i18n/ko.json +157 -0
  55. package/src/modules/scheduler/i18n/pl.json +2 -0
  56. package/src/modules/scheduler/lib/__tests__/intervalParser.test.ts +27 -9
  57. package/src/modules/scheduler/lib/__tests__/nextRunCalculator.test.ts +18 -7
  58. package/src/modules/scheduler/lib/activeScheduleLimits.ts +48 -0
  59. package/src/modules/scheduler/lib/intervalParser.ts +8 -3
  60. package/src/modules/scheduler/lib/nextRunCalculator.ts +14 -1
  61. package/src/modules/scheduler/lib/scheduler-safe-commands.ts +98 -0
  62. package/src/modules/scheduler/services/__tests__/bullmqSchedulerService.test.ts +246 -149
  63. package/src/modules/scheduler/services/__tests__/localSchedulerService.test.ts +97 -1
  64. package/src/modules/scheduler/services/__tests__/schedulerService.test.ts +101 -0
  65. package/src/modules/scheduler/services/bullmqSchedulerService.ts +135 -49
  66. package/src/modules/scheduler/services/localSchedulerService.ts +11 -0
  67. package/src/modules/scheduler/services/schedulerService.ts +27 -12
  68. package/src/modules/scheduler/workers/__tests__/execute-schedule.worker.test.ts +12 -0
  69. package/src/modules/scheduler/workers/execute-schedule.worker.ts +15 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/scheduler/lib/intervalParser.ts"],
4
- "sourcesContent": ["/**\n * Parse simple interval strings like '15m', '2h', '1d' into milliseconds\n */\nexport function parseInterval(interval: string): number {\n const regex = /^(\\d+)(s|m|h|d)$/\n const match = interval.match(regex)\n \n if (!match) {\n throw new Error(`Invalid interval format: ${interval}. Expected format: <number><unit> (e.g., 15m, 2h, 1d)`)\n }\n \n const value = parseInt(match[1], 10)\n const unit = match[2]\n \n const multipliers: Record<string, number> = {\n s: 1000, // seconds\n m: 60 * 1000, // minutes\n h: 60 * 60 * 1000, // hours\n d: 24 * 60 * 60 * 1000, // days\n }\n \n return value * multipliers[unit]\n}\n\n/**\n * Calculate next run time based on interval\n */\nexport function calculateNextRunFromInterval(\n interval: string,\n fromDate: Date = new Date()\n): Date {\n const ms = parseInterval(interval)\n return new Date(fromDate.getTime() + ms)\n}\n\n/**\n * Validate an interval string\n */\nexport function validateInterval(interval: string): boolean {\n try {\n parseInterval(interval)\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Convert interval to human-readable string\n * Preserves the original unit unless it can be cleanly converted to a larger unit\n * Special case: Zero always displays as \"0 seconds\"\n */\nexport function intervalToHuman(interval: string): string {\n try {\n const regex = /^(\\d+)(s|m|h|d)$/\n const match = interval.match(regex)\n \n if (!match) {\n return interval\n }\n \n const unit = match[2]\n \n const ms = parseInterval(interval)\n const seconds = ms / 1000\n \n // Special case: zero always displays as \"0 seconds\"\n if (seconds === 0) {\n return '0 seconds'\n }\n \n const minutes = seconds / 60\n const hours = minutes / 60\n const days = hours / 24\n \n // Only convert to larger units based on the input unit\n // This preserves the original unit choice (e.g., 60s stays as \"60 seconds\")\n switch (unit) {\n case 's':\n // Seconds never convert up (preserve user's choice)\n return `${seconds} second${seconds !== 1 ? 's' : ''}`\n \n case 'm':\n // Minutes can convert to hours or days\n if (days >= 1 && days === Math.floor(days)) {\n return `${days} day${days !== 1 ? 's' : ''}`\n }\n if (hours >= 1 && hours === Math.floor(hours)) {\n return `${hours} hour${hours !== 1 ? 's' : ''}`\n }\n return `${minutes} minute${minutes !== 1 ? 's' : ''}`\n \n case 'h':\n // Hours can convert to days\n if (days >= 1 && days === Math.floor(days)) {\n return `${days} day${days !== 1 ? 's' : ''}`\n }\n return `${hours} hour${hours !== 1 ? 's' : ''}`\n \n case 'd':\n // Days stay as days\n return `${days} day${days !== 1 ? 's' : ''}`\n \n default:\n return interval\n }\n } catch {\n return interval\n }\n}\n"],
5
- "mappings": "AAGO,SAAS,cAAc,UAA0B;AACtD,QAAM,QAAQ;AACd,QAAM,QAAQ,SAAS,MAAM,KAAK;AAElC,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,4BAA4B,QAAQ,uDAAuD;AAAA,EAC7G;AAEA,QAAM,QAAQ,SAAS,MAAM,CAAC,GAAG,EAAE;AACnC,QAAM,OAAO,MAAM,CAAC;AAEpB,QAAM,cAAsC;AAAA,IAC1C,GAAG;AAAA;AAAA,IACH,GAAG,KAAK;AAAA;AAAA,IACR,GAAG,KAAK,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I,MAAM,EAAE;AAAA,QAC5C;AACA,eAAO,GAAG,KAAK,QAAQ,UAAU,IAAI,MAAM,EAAE;AAAA,MAE/C,KAAK;AAEH,eAAO,GAAG,IAAI,OAAO,SAAS,IAAI,MAAM,EAAE;AAAA,MAE5C;AACE,eAAO;AAAA,IACX;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,EACT;AACF;",
4
+ "sourcesContent": ["/**\n * Parse simple interval strings like '15m', '2h', '1d' into milliseconds\n */\nexport const MIN_SCHEDULE_INTERVAL_MS = 60 * 1000\n\nexport function parseInterval(interval: string): number {\n const regex = /^(\\d+)(s|m|h|d)$/\n const match = interval.match(regex)\n \n if (!match) {\n throw new Error(`Invalid interval format: ${interval}. Expected format: <number><unit> (e.g., 15m, 2h, 1d)`)\n }\n \n const value = parseInt(match[1], 10)\n const unit = match[2]\n \n const multipliers: Record<string, number> = {\n s: 1000, // seconds\n m: 60 * 1000, // minutes\n h: 60 * 60 * 1000, // hours\n d: 24 * 60 * 60 * 1000, // days\n }\n \n return value * multipliers[unit]\n}\n\nexport function resolveScheduleIntervalMs(interval: string): number {\n return Math.max(parseInterval(interval), MIN_SCHEDULE_INTERVAL_MS)\n}\n\n/**\n * Calculate next run time based on interval\n */\nexport function calculateNextRunFromInterval(\n interval: string,\n fromDate: Date = new Date()\n): Date {\n const ms = resolveScheduleIntervalMs(interval)\n return new Date(fromDate.getTime() + ms)\n}\n\n/**\n * Validate an interval string\n */\nexport function validateInterval(interval: string): boolean {\n try {\n return parseInterval(interval) >= MIN_SCHEDULE_INTERVAL_MS\n } catch {\n return false\n }\n}\n\n/**\n * Convert interval to human-readable string\n * Preserves the original unit unless it can be cleanly converted to a larger unit\n * Special case: Zero always displays as \"0 seconds\"\n */\nexport function intervalToHuman(interval: string): string {\n try {\n const regex = /^(\\d+)(s|m|h|d)$/\n const match = interval.match(regex)\n \n if (!match) {\n return interval\n }\n \n const unit = match[2]\n \n const ms = parseInterval(interval)\n const seconds = ms / 1000\n \n // Special case: zero always displays as \"0 seconds\"\n if (seconds === 0) {\n return '0 seconds'\n }\n \n const minutes = seconds / 60\n const hours = minutes / 60\n const days = hours / 24\n \n // Only convert to larger units based on the input unit\n // This preserves the original unit choice (e.g., 60s stays as \"60 seconds\")\n switch (unit) {\n case 's':\n // Seconds never convert up (preserve user's choice)\n return `${seconds} second${seconds !== 1 ? 's' : ''}`\n \n case 'm':\n // Minutes can convert to hours or days\n if (days >= 1 && days === Math.floor(days)) {\n return `${days} day${days !== 1 ? 's' : ''}`\n }\n if (hours >= 1 && hours === Math.floor(hours)) {\n return `${hours} hour${hours !== 1 ? 's' : ''}`\n }\n return `${minutes} minute${minutes !== 1 ? 's' : ''}`\n \n case 'h':\n // Hours can convert to days\n if (days >= 1 && days === Math.floor(days)) {\n return `${days} day${days !== 1 ? 's' : ''}`\n }\n return `${hours} hour${hours !== 1 ? 's' : ''}`\n \n case 'd':\n // Days stay as days\n return `${days} day${days !== 1 ? 's' : ''}`\n \n default:\n return interval\n }\n } catch {\n return interval\n }\n}\n"],
5
+ "mappings": "AAGO,MAAM,2BAA2B,KAAK;AAEtC,SAAS,cAAc,UAA0B;AACtD,QAAM,QAAQ;AACd,QAAM,QAAQ,SAAS,MAAM,KAAK;AAElC,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,4BAA4B,QAAQ,uDAAuD;AAAA,EAC7G;AAEA,QAAM,QAAQ,SAAS,MAAM,CAAC,GAAG,EAAE;AACnC,QAAM,OAAO,MAAM,CAAC;AAEpB,QAAM,cAAsC;AAAA,IAC1C,GAAG;AAAA;AAAA,IACH,GAAG,KAAK;AAAA;AAAA,IACR,GAAG,KAAK,KAAK;AAAA;AAAA,IACb,GAAG,KAAK,KAAK,KAAK;AAAA;AAAA,EACpB;AAEA,SAAO,QAAQ,YAAY,IAAI;AACjC;AAEO,SAAS,0BAA0B,UAA0B;AAClE,SAAO,KAAK,IAAI,cAAc,QAAQ,GAAG,wBAAwB;AACnE;AAKO,SAAS,6BACd,U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,IAAI,OAAO,SAAS,IAAI,MAAM,EAAE;AAAA,MAE5C;AACE,eAAO;AAAA,IACX;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,EACT;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,5 +1,5 @@
1
1
  import { parseCronExpression } from "./cronParser.js";
2
- import { calculateNextRunFromInterval } from "./intervalParser.js";
2
+ import { calculateNextRunFromInterval, validateInterval } from "./intervalParser.js";
3
3
  function calculateNextRun(scheduleType, scheduleValue, timezone = "UTC", fromDate) {
4
4
  const baseDate = fromDate || /* @__PURE__ */ new Date();
5
5
  if (scheduleType === "cron") {
@@ -15,11 +15,18 @@ function calculateNextRun(scheduleType, scheduleValue, timezone = "UTC", fromDat
15
15
  }
16
16
  return null;
17
17
  }
18
+ function calculateNextRunForWrite(scheduleType, scheduleValue, timezone = "UTC", fromDate) {
19
+ if (scheduleType === "interval" && !validateInterval(scheduleValue)) {
20
+ return null;
21
+ }
22
+ return calculateNextRun(scheduleType, scheduleValue, timezone, fromDate);
23
+ }
18
24
  function recalculateNextRun(scheduleType, scheduleValue, timezone = "UTC") {
19
25
  return calculateNextRun(scheduleType, scheduleValue, timezone, /* @__PURE__ */ new Date());
20
26
  }
21
27
  export {
22
28
  calculateNextRun,
29
+ calculateNextRunForWrite,
23
30
  recalculateNextRun
24
31
  };
25
32
  //# sourceMappingURL=nextRunCalculator.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/scheduler/lib/nextRunCalculator.ts"],
4
- "sourcesContent": ["import { parseCronExpression } from './cronParser.js'\nimport { calculateNextRunFromInterval } from './intervalParser.js'\n\n/**\n * Calculate the next run time for a schedule\n */\nexport function calculateNextRun(\n scheduleType: 'cron' | 'interval',\n scheduleValue: string,\n timezone: string = 'UTC',\n fromDate?: Date\n): Date | null {\n const baseDate = fromDate || new Date()\n \n if (scheduleType === 'cron') {\n const result = parseCronExpression(scheduleValue, timezone, baseDate)\n return result.nextRun || null\n }\n \n if (scheduleType === 'interval') {\n try {\n return calculateNextRunFromInterval(scheduleValue, baseDate)\n } catch {\n return null\n }\n }\n \n return null\n}\n\n/**\n * Recalculate next run for a schedule after execution\n */\nexport function recalculateNextRun(\n scheduleType: 'cron' | 'interval',\n scheduleValue: string,\n timezone: string = 'UTC'\n): Date | null {\n // Always calculate from current time (not from last run)\n // This prevents drift and missed executions\n return calculateNextRun(scheduleType, scheduleValue, timezone, new Date())\n}\n"],
5
- "mappings": "AAAA,SAAS,2BAA2B;AACpC,SAAS,oCAAoC;AAKtC,SAAS,iBACd,cACA,eACA,WAAmB,OACnB,UACa;AACb,QAAM,WAAW,YAAY,oBAAI,KAAK;AAEtC,MAAI,iBAAiB,QAAQ;AAC3B,UAAM,SAAS,oBAAoB,eAAe,UAAU,QAAQ;AACpE,WAAO,OAAO,WAAW;AAAA,EAC3B;AAEA,MAAI,iBAAiB,YAAY;AAC/B,QAAI;AACF,aAAO,6BAA6B,eAAe,QAAQ;AAAA,IAC7D,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;AAKO,SAAS,mBACd,cACA,eACA,WAAmB,OACN;AAGb,SAAO,iBAAiB,cAAc,eAAe,UAAU,oBAAI,KAAK,CAAC;AAC3E;",
4
+ "sourcesContent": ["import { parseCronExpression } from './cronParser.js'\nimport { calculateNextRunFromInterval, validateInterval } from './intervalParser.js'\n\n/**\n * Calculate the next run time for a schedule\n */\nexport function calculateNextRun(\n scheduleType: 'cron' | 'interval',\n scheduleValue: string,\n timezone: string = 'UTC',\n fromDate?: Date\n): Date | null {\n const baseDate = fromDate || new Date()\n \n if (scheduleType === 'cron') {\n const result = parseCronExpression(scheduleValue, timezone, baseDate)\n return result.nextRun || null\n }\n \n if (scheduleType === 'interval') {\n try {\n return calculateNextRunFromInterval(scheduleValue, baseDate)\n } catch {\n return null\n }\n }\n \n return null\n}\n\nexport function calculateNextRunForWrite(\n scheduleType: 'cron' | 'interval',\n scheduleValue: string,\n timezone: string = 'UTC',\n fromDate?: Date,\n): Date | null {\n if (scheduleType === 'interval' && !validateInterval(scheduleValue)) {\n return null\n }\n\n return calculateNextRun(scheduleType, scheduleValue, timezone, fromDate)\n}\n\n/**\n * Recalculate next run for a schedule after execution\n */\nexport function recalculateNextRun(\n scheduleType: 'cron' | 'interval',\n scheduleValue: string,\n timezone: string = 'UTC'\n): Date | null {\n // Always calculate from current time (not from last run)\n // This prevents drift and missed executions\n return calculateNextRun(scheduleType, scheduleValue, timezone, new Date())\n}\n"],
5
+ "mappings": "AAAA,SAAS,2BAA2B;AACpC,SAAS,8BAA8B,wBAAwB;AAKxD,SAAS,iBACd,cACA,eACA,WAAmB,OACnB,UACa;AACb,QAAM,WAAW,YAAY,oBAAI,KAAK;AAEtC,MAAI,iBAAiB,QAAQ;AAC3B,UAAM,SAAS,oBAAoB,eAAe,UAAU,QAAQ;AACpE,WAAO,OAAO,WAAW;AAAA,EAC3B;AAEA,MAAI,iBAAiB,YAAY;AAC/B,QAAI;AACF,aAAO,6BAA6B,eAAe,QAAQ;AAAA,IAC7D,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;AAEO,SAAS,yBACd,cACA,eACA,WAAmB,OACnB,UACa;AACb,MAAI,iBAAiB,cAAc,CAAC,iBAAiB,aAAa,GAAG;AACnE,WAAO;AAAA,EACT;AAEA,SAAO,iBAAiB,cAAc,eAAe,UAAU,QAAQ;AACzE;AAKO,SAAS,mBACd,cACA,eACA,WAAmB,OACN;AAGb,SAAO,iBAAiB,cAAc,eAAe,UAAU,oBAAI,KAAK,CAAC;AAC3E;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,73 @@
1
+ const schedulerSafeCommands = /* @__PURE__ */ new Map();
2
+ function normalizeCommandId(commandId) {
3
+ if (typeof commandId !== "string") return null;
4
+ const trimmed = commandId.trim();
5
+ return trimmed.length > 0 ? trimmed : null;
6
+ }
7
+ function normalizeFeatures(features) {
8
+ const normalized = features.map((feature) => feature.trim()).filter((feature) => feature.length > 0);
9
+ return normalized.length > 0 ? normalized : null;
10
+ }
11
+ function registerSchedulerSafeCommands(commands) {
12
+ for (const command of commands) {
13
+ const commandId = normalizeCommandId(command.commandId);
14
+ const requiredFeatures = normalizeFeatures(command.requiredFeatures);
15
+ if (!commandId || !requiredFeatures) {
16
+ throw new Error("[internal] Scheduler-safe commands require a commandId and requiredFeatures");
17
+ }
18
+ schedulerSafeCommands.set(commandId, { commandId, requiredFeatures });
19
+ }
20
+ }
21
+ function getSchedulerSafeCommand(commandId) {
22
+ const normalized = normalizeCommandId(commandId);
23
+ if (!normalized) return null;
24
+ return schedulerSafeCommands.get(normalized) ?? null;
25
+ }
26
+ function isSchedulerSafeCommandId(commandId) {
27
+ return getSchedulerSafeCommand(commandId) !== null;
28
+ }
29
+ function listSchedulerSafeCommands() {
30
+ return Array.from(schedulerSafeCommands.values()).sort((a, b) => a.commandId.localeCompare(b.commandId));
31
+ }
32
+ async function assertSchedulerSafeCommandAuthorized(params) {
33
+ const command = getSchedulerSafeCommand(params.commandId);
34
+ if (!command) {
35
+ throw new Error("Scheduled command is not allowed");
36
+ }
37
+ const actorUserId = normalizeCommandId(params.actorUserId);
38
+ if (!actorUserId) {
39
+ throw new Error("Scheduled command requires an authenticated creator");
40
+ }
41
+ if (typeof params.rbacService.userHasAllFeatures !== "function") {
42
+ throw new Error("Scheduled command authorization is unavailable");
43
+ }
44
+ const authorized = await params.rbacService.userHasAllFeatures(actorUserId, command.requiredFeatures, {
45
+ tenantId: params.tenantId ?? null,
46
+ organizationId: params.organizationId ?? null
47
+ });
48
+ if (!authorized) {
49
+ throw new Error("Scheduled command creator is not authorized");
50
+ }
51
+ return command;
52
+ }
53
+ function clearSchedulerSafeCommandsForTests() {
54
+ if (process.env.NODE_ENV !== "test") {
55
+ throw new Error("[internal] clearSchedulerSafeCommandsForTests is test-only");
56
+ }
57
+ schedulerSafeCommands.clear();
58
+ }
59
+ registerSchedulerSafeCommands([
60
+ {
61
+ commandId: "scheduler.test.echo",
62
+ requiredFeatures: ["scheduler.jobs.manage"]
63
+ }
64
+ ]);
65
+ export {
66
+ assertSchedulerSafeCommandAuthorized,
67
+ clearSchedulerSafeCommandsForTests,
68
+ getSchedulerSafeCommand,
69
+ isSchedulerSafeCommandId,
70
+ listSchedulerSafeCommands,
71
+ registerSchedulerSafeCommands
72
+ };
73
+ //# sourceMappingURL=scheduler-safe-commands.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/scheduler/lib/scheduler-safe-commands.ts"],
4
+ "sourcesContent": ["export type SchedulerSafeCommandDefinition = {\n commandId: string\n requiredFeatures: readonly [string, ...string[]]\n}\n\nexport type SchedulerCommandRbacService = {\n userHasAllFeatures?: (\n userId: string,\n required: readonly string[],\n scope: { tenantId: string | null; organizationId: string | null }\n ) => Promise<boolean>\n}\n\nconst schedulerSafeCommands = new Map<string, SchedulerSafeCommandDefinition>()\n\nfunction normalizeCommandId(commandId: unknown): string | null {\n if (typeof commandId !== 'string') return null\n const trimmed = commandId.trim()\n return trimmed.length > 0 ? trimmed : null\n}\n\nfunction normalizeFeatures(features: readonly string[]): [string, ...string[]] | null {\n const normalized = features\n .map((feature) => feature.trim())\n .filter((feature) => feature.length > 0)\n return normalized.length > 0 ? (normalized as [string, ...string[]]) : null\n}\n\nexport function registerSchedulerSafeCommands(commands: readonly SchedulerSafeCommandDefinition[]): void {\n for (const command of commands) {\n const commandId = normalizeCommandId(command.commandId)\n const requiredFeatures = normalizeFeatures(command.requiredFeatures)\n if (!commandId || !requiredFeatures) {\n throw new Error('[internal] Scheduler-safe commands require a commandId and requiredFeatures')\n }\n schedulerSafeCommands.set(commandId, { commandId, requiredFeatures })\n }\n}\n\nexport function getSchedulerSafeCommand(commandId: unknown): SchedulerSafeCommandDefinition | null {\n const normalized = normalizeCommandId(commandId)\n if (!normalized) return null\n return schedulerSafeCommands.get(normalized) ?? null\n}\n\nexport function isSchedulerSafeCommandId(commandId: unknown): boolean {\n return getSchedulerSafeCommand(commandId) !== null\n}\n\nexport function listSchedulerSafeCommands(): SchedulerSafeCommandDefinition[] {\n return Array.from(schedulerSafeCommands.values()).sort((a, b) => a.commandId.localeCompare(b.commandId))\n}\n\nexport async function assertSchedulerSafeCommandAuthorized(params: {\n commandId: unknown\n actorUserId: string | null | undefined\n tenantId: string | null | undefined\n organizationId: string | null | undefined\n rbacService: SchedulerCommandRbacService\n}): Promise<SchedulerSafeCommandDefinition> {\n const command = getSchedulerSafeCommand(params.commandId)\n if (!command) {\n throw new Error('Scheduled command is not allowed')\n }\n\n const actorUserId = normalizeCommandId(params.actorUserId)\n if (!actorUserId) {\n throw new Error('Scheduled command requires an authenticated creator')\n }\n\n if (typeof params.rbacService.userHasAllFeatures !== 'function') {\n throw new Error('Scheduled command authorization is unavailable')\n }\n\n const authorized = await params.rbacService.userHasAllFeatures(actorUserId, command.requiredFeatures, {\n tenantId: params.tenantId ?? null,\n organizationId: params.organizationId ?? null,\n })\n if (!authorized) {\n throw new Error('Scheduled command creator is not authorized')\n }\n\n return command\n}\n\nexport function clearSchedulerSafeCommandsForTests(): void {\n if (process.env.NODE_ENV !== 'test') {\n throw new Error('[internal] clearSchedulerSafeCommandsForTests is test-only')\n }\n schedulerSafeCommands.clear()\n}\n\nregisterSchedulerSafeCommands([\n {\n commandId: 'scheduler.test.echo',\n requiredFeatures: ['scheduler.jobs.manage'],\n },\n])\n"],
5
+ "mappings": "AAaA,MAAM,wBAAwB,oBAAI,IAA4C;AAE9E,SAAS,mBAAmB,WAAmC;AAC7D,MAAI,OAAO,cAAc,SAAU,QAAO;AAC1C,QAAM,UAAU,UAAU,KAAK;AAC/B,SAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;AAEA,SAAS,kBAAkB,UAA2D;AACpF,QAAM,aAAa,SAChB,IAAI,CAAC,YAAY,QAAQ,KAAK,CAAC,EAC/B,OAAO,CAAC,YAAY,QAAQ,SAAS,CAAC;AACzC,SAAO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AAEO,SAAS,qCAA2C;AACzD,MAAI,QAAQ,IAAI,aAAa,QAAQ;AACnC,UAAM,IAAI,MAAM,4DAA4D;AAAA,EAC9E;AACA,wBAAsB,MAAM;AAC9B;AAEA,8BAA8B;AAAA,EAC5B;AAAA,IACE,WAAW;AAAA,IACX,kBAAkB,CAAC,uBAAuB;AAAA,EAC5C;AACF,CAAC;",
6
+ "names": []
7
+ }
@@ -1,8 +1,8 @@
1
1
  import { ScheduledJob } from "../data/entities.js";
2
2
  import { recalculateNextRun } from "../lib/nextRunCalculator.js";
3
3
  import { parseCronExpression } from "../lib/cronParser.js";
4
- import { parseInterval } from "../lib/intervalParser.js";
5
- import { getRedisUrlOrThrow } from "@open-mercato/shared/lib/redis/connection";
4
+ import { resolveScheduleIntervalMs } from "../lib/intervalParser.js";
5
+ import { getRedisUrlOrThrow, parseRedisUrl } from "@open-mercato/shared/lib/redis/connection";
6
6
  import { createLogger } from "@open-mercato/shared/lib/logger";
7
7
  const logger = createLogger("scheduler").child({ component: "bullmq" });
8
8
  class BullMQSchedulerService {
@@ -17,7 +17,9 @@ class BullMQSchedulerService {
17
17
  if (!this.queue) {
18
18
  try {
19
19
  const { Queue } = await import("bullmq");
20
- this.queue = new Queue("scheduler-execution", { connection: { url: getRedisUrlOrThrow("QUEUE") } });
20
+ this.queue = new Queue("scheduler-execution", {
21
+ connection: parseRedisUrl(getRedisUrlOrThrow("QUEUE"))
22
+ });
21
23
  } catch {
22
24
  throw new Error("BullMQ is required for async scheduler. Install it with: npm install bullmq");
23
25
  }
@@ -27,15 +29,24 @@ class BullMQSchedulerService {
27
29
  getScheduleJobName(scheduleId) {
28
30
  return `schedule-${scheduleId}`;
29
31
  }
30
- getScheduleIdFromRepeatableJob(job) {
31
- const candidate = job.id?.startsWith("schedule-") ? job.id : job.name?.startsWith("schedule-") ? job.name : null;
32
+ getScheduleIdFromJobScheduler(job) {
33
+ const candidate = [job.key, job.id, job.name].find((value) => value?.startsWith("schedule-"));
32
34
  return candidate ? candidate.slice("schedule-".length) : null;
33
35
  }
36
+ isJobSchedulerForSchedule(job, scheduleId) {
37
+ return this.getScheduleIdFromJobScheduler(job) === scheduleId;
38
+ }
39
+ isCanonicalJobScheduler(job, scheduleId) {
40
+ return job.key === this.getScheduleJobName(scheduleId);
41
+ }
42
+ supportsJobSchedulers(queue) {
43
+ return typeof queue.upsertJobScheduler === "function" && typeof queue.getJobSchedulers === "function" && typeof queue.removeJobScheduler === "function";
44
+ }
34
45
  isRepeatableJobForSchedule(job, scheduleId) {
35
46
  const jobName = this.getScheduleJobName(scheduleId);
36
47
  return job.id === jobName || job.name === jobName;
37
48
  }
38
- async removeRepeatableJobsForSchedule(queue, scheduleId) {
49
+ async removeLegacyRepeatableJobs(queue, scheduleId) {
39
50
  const repeatableJobs = await queue.getRepeatableJobs?.();
40
51
  if (!repeatableJobs || typeof queue.removeRepeatableByKey !== "function") {
41
52
  return 0;
@@ -49,7 +60,7 @@ class BullMQSchedulerService {
49
60
  return removed;
50
61
  }
51
62
  /**
52
- * Register a schedule with BullMQ repeatable jobs
63
+ * Register a schedule with BullMQ Job Schedulers
53
64
  * @param schedule - The schedule to register
54
65
  * @param options - Optional configuration
55
66
  * @param options.skipNextRunUpdate - If true, skip updating nextRunAt (used when called from hooks)
@@ -73,7 +84,6 @@ class BullMQSchedulerService {
73
84
  const repeatOpts = this.buildRepeatOptions(schedule);
74
85
  const queue = await this.getQueue();
75
86
  const jobName = this.getScheduleJobName(schedule.id);
76
- await this.removeRepeatableJobsForSchedule(queue, schedule.id);
77
87
  const jobData = {
78
88
  id: jobName,
79
89
  payload: {
@@ -84,7 +94,7 @@ class BullMQSchedulerService {
84
94
  },
85
95
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
86
96
  };
87
- logger.debug("Adding repeatable job", {
97
+ logger.debug("Upserting job scheduler", {
88
98
  jobName,
89
99
  scheduleId: schedule.id,
90
100
  scopeType: schedule.scopeType,
@@ -92,28 +102,36 @@ class BullMQSchedulerService {
92
102
  organizationId: schedule.organizationId,
93
103
  repeatOpts
94
104
  });
95
- await queue.add(
96
- jobName,
97
- // Job name - used as part of repeatable job key
98
- jobData,
99
- // Job data in QueuedJob format
100
- {
101
- repeat: repeatOpts,
102
- // Don't set jobId for repeatable jobs - BullMQ generates unique IDs for each instance
103
- removeOnComplete: {
104
- age: 86400 * 30,
105
- // Keep completed jobs for 30 days (execution history)
106
- count: 1e3
107
- // Keep last 1000 completed jobs
108
- },
109
- removeOnFail: {
110
- age: 86400 * 90,
111
- // Keep failed jobs for 90 days (debugging/audit)
112
- count: 5e3
113
- // Keep last 5000 failed jobs
105
+ const jobOptions = {
106
+ removeOnComplete: {
107
+ age: 86400 * 30,
108
+ count: 1e3
109
+ },
110
+ removeOnFail: {
111
+ age: 86400 * 90,
112
+ count: 5e3
113
+ }
114
+ };
115
+ if (this.supportsJobSchedulers(queue)) {
116
+ const existingJobSchedulers = await queue.getJobSchedulers();
117
+ await queue.upsertJobScheduler(
118
+ jobName,
119
+ repeatOpts,
120
+ {
121
+ name: jobName,
122
+ data: jobData,
123
+ opts: jobOptions
124
+ }
125
+ );
126
+ for (const jobScheduler of existingJobSchedulers) {
127
+ if (this.isJobSchedulerForSchedule(jobScheduler, schedule.id) && !this.isCanonicalJobScheduler(jobScheduler, schedule.id)) {
128
+ await queue.removeJobScheduler(jobScheduler.key);
114
129
  }
115
130
  }
116
- );
131
+ } else {
132
+ await this.removeLegacyRepeatableJobs(queue, schedule.id);
133
+ await queue.add(jobName, jobData, { repeat: repeatOpts, ...jobOptions });
134
+ }
117
135
  logger.debug("Registered schedule", {
118
136
  scheduleId: schedule.id,
119
137
  scheduleName: schedule.name,
@@ -127,12 +145,25 @@ class BullMQSchedulerService {
127
145
  }
128
146
  }
129
147
  /**
130
- * Unregister a schedule from BullMQ repeatable jobs
148
+ * Unregister a schedule from BullMQ Job Schedulers
131
149
  */
132
150
  async unregister(scheduleId) {
133
151
  try {
134
152
  const queue = await this.getQueue();
135
- const removed = await this.removeRepeatableJobsForSchedule(queue, scheduleId);
153
+ if (this.supportsJobSchedulers(queue)) {
154
+ const jobSchedulers = await queue.getJobSchedulers();
155
+ const matchingJobSchedulers = jobSchedulers.filter((job) => this.isJobSchedulerForSchedule(job, scheduleId));
156
+ if (matchingJobSchedulers.length > 0) {
157
+ for (const jobScheduler of matchingJobSchedulers) {
158
+ await queue.removeJobScheduler(jobScheduler.key);
159
+ }
160
+ logger.debug("Unregistered schedule", { scheduleId });
161
+ } else {
162
+ logger.debug("No job scheduler found for schedule", { scheduleId });
163
+ }
164
+ return;
165
+ }
166
+ const removed = await this.removeLegacyRepeatableJobs(queue, scheduleId);
136
167
  if (removed > 0) {
137
168
  logger.debug("Unregistered schedule", { scheduleId });
138
169
  } else {
@@ -151,14 +182,29 @@ class BullMQSchedulerService {
151
182
  const em = this.em().fork();
152
183
  const queue = await this.getQueue();
153
184
  logger.debug("Starting full sync");
154
- const repeatableJobs = await queue.getRepeatableJobs?.() || [];
155
185
  const bullmqScheduleIds = /* @__PURE__ */ new Set();
156
186
  const bullmqScheduleCounts = /* @__PURE__ */ new Map();
157
- for (const job of repeatableJobs) {
158
- const scheduleId = this.getScheduleIdFromRepeatableJob(job);
159
- if (!scheduleId) continue;
160
- bullmqScheduleIds.add(scheduleId);
161
- bullmqScheduleCounts.set(scheduleId, (bullmqScheduleCounts.get(scheduleId) ?? 0) + 1);
187
+ const canonicalJobSchedulerIds = /* @__PURE__ */ new Set();
188
+ if (this.supportsJobSchedulers(queue)) {
189
+ const jobSchedulers = await queue.getJobSchedulers();
190
+ for (const job of jobSchedulers) {
191
+ const scheduleId = this.getScheduleIdFromJobScheduler(job);
192
+ if (!scheduleId) continue;
193
+ bullmqScheduleIds.add(scheduleId);
194
+ bullmqScheduleCounts.set(scheduleId, (bullmqScheduleCounts.get(scheduleId) ?? 0) + 1);
195
+ if (this.isCanonicalJobScheduler(job, scheduleId)) {
196
+ canonicalJobSchedulerIds.add(scheduleId);
197
+ }
198
+ }
199
+ } else {
200
+ const repeatableJobs = await queue.getRepeatableJobs?.() ?? [];
201
+ for (const job of repeatableJobs) {
202
+ const candidate = job.id?.startsWith("schedule-") ? job.id : job.name?.startsWith("schedule-") ? job.name : null;
203
+ if (!candidate) continue;
204
+ const scheduleId = candidate.slice("schedule-".length);
205
+ bullmqScheduleIds.add(scheduleId);
206
+ bullmqScheduleCounts.set(scheduleId, (bullmqScheduleCounts.get(scheduleId) ?? 0) + 1);
207
+ }
162
208
  }
163
209
  const BATCH_SIZE = 500;
164
210
  const dbSchedules = [];
@@ -177,8 +223,8 @@ class BullMQSchedulerService {
177
223
  if (!bullmqScheduleIds.has(schedule.id)) {
178
224
  logger.debug("Registering missing schedule", { scheduleId: schedule.id, scheduleName: schedule.name });
179
225
  await this.register(schedule);
180
- } else if ((bullmqScheduleCounts.get(schedule.id) ?? 0) > 1) {
181
- logger.info("Repairing duplicate repeatable jobs", { scheduleId: schedule.id });
226
+ } else if ((bullmqScheduleCounts.get(schedule.id) ?? 0) > 1 || !canonicalJobSchedulerIds.has(schedule.id)) {
227
+ logger.info("Migrating legacy or duplicate job scheduler", { scheduleId: schedule.id });
182
228
  await this.register(schedule);
183
229
  }
184
230
  }
@@ -204,7 +250,7 @@ class BullMQSchedulerService {
204
250
  }
205
251
  opts.pattern = schedule.scheduleValue;
206
252
  } else if (schedule.scheduleType === "interval") {
207
- const intervalMs = parseInterval(schedule.scheduleValue);
253
+ const intervalMs = resolveScheduleIntervalMs(schedule.scheduleValue);
208
254
  opts.every = intervalMs;
209
255
  } else {
210
256
  throw new Error(`Unsupported schedule type: ${schedule.scheduleType}`);
@@ -212,14 +258,17 @@ class BullMQSchedulerService {
212
258
  return opts;
213
259
  }
214
260
  /**
215
- * Get list of all repeatable jobs from BullMQ
261
+ * Get list of all scheduled jobs from BullMQ
216
262
  */
217
263
  async getRepeatableJobs() {
218
264
  try {
219
265
  const queue = await this.getQueue();
220
- return await queue.getRepeatableJobs?.() || [];
266
+ if (this.supportsJobSchedulers(queue)) {
267
+ return await queue.getJobSchedulers();
268
+ }
269
+ return await queue.getRepeatableJobs?.() ?? [];
221
270
  } catch (error) {
222
- logger.error("Failed to get repeatable jobs", { err: error });
271
+ logger.error("Failed to get job schedulers", { err: error });
223
272
  return [];
224
273
  }
225
274
  }
@@ -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'\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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;AAC5D,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,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 { 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,qB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,7 @@ 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";
7
8
  import { buildScheduledCommandContext } from "../lib/commandContext.js";
8
9
  import { buildQueueTargetPayload, buildSchedulerIdempotencyKey } from "../lib/queueTargetPayload.js";
9
10
  import { createLogger } from "@open-mercato/shared/lib/logger";
@@ -187,6 +188,14 @@ class LocalSchedulerService {
187
188
  throw new Error("Target command is required for command target type");
188
189
  }
189
190
  const commandBus = new CommandBus();
191
+ const actorUserId = typeof schedule.createdByUserId === "string" ? schedule.createdByUserId.trim() : "";
192
+ await assertSchedulerSafeCommandAuthorized({
193
+ commandId: schedule.targetCommand,
194
+ actorUserId,
195
+ tenantId: schedule.tenantId,
196
+ organizationId: schedule.organizationId,
197
+ rbacService: this.rbacService
198
+ });
190
199
  const commandInput = {
191
200
  ...schedule.targetPayload || {},
192
201
  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 { 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;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,OAAsB;AAC1B,WAAO,KAAK,yBAAyB;AACrC,SAAK,YAAY;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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 { 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 * - 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 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,o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