@open-mercato/scheduler 0.6.7-develop.6696.1.4236709f7e → 0.6.7-develop.6725.1.07a748cfc2

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 (29) 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/commands/jobs.js +20 -11
  5. package/dist/modules/scheduler/commands/jobs.js.map +2 -2
  6. package/dist/modules/scheduler/lib/activeScheduleLimits.js +29 -0
  7. package/dist/modules/scheduler/lib/activeScheduleLimits.js.map +7 -0
  8. package/dist/modules/scheduler/lib/intervalParser.js +8 -3
  9. package/dist/modules/scheduler/lib/intervalParser.js.map +2 -2
  10. package/dist/modules/scheduler/lib/nextRunCalculator.js +8 -1
  11. package/dist/modules/scheduler/lib/nextRunCalculator.js.map +2 -2
  12. package/dist/modules/scheduler/services/bullmqSchedulerService.js +2 -2
  13. package/dist/modules/scheduler/services/bullmqSchedulerService.js.map +2 -2
  14. package/dist/modules/scheduler/services/schedulerService.js +23 -11
  15. package/dist/modules/scheduler/services/schedulerService.js.map +2 -2
  16. package/package.json +5 -5
  17. package/src/modules/scheduler/__integration__/TC-SCHED-007.spec.ts +6 -4
  18. package/src/modules/scheduler/commands/__tests__/jobs.active-limit.test.ts +173 -0
  19. package/src/modules/scheduler/commands/jobs.ts +26 -12
  20. package/src/modules/scheduler/data/__tests__/validators.test.ts +29 -1
  21. package/src/modules/scheduler/lib/__tests__/intervalParser.test.ts +27 -9
  22. package/src/modules/scheduler/lib/__tests__/nextRunCalculator.test.ts +18 -7
  23. package/src/modules/scheduler/lib/activeScheduleLimits.ts +32 -0
  24. package/src/modules/scheduler/lib/intervalParser.ts +8 -3
  25. package/src/modules/scheduler/lib/nextRunCalculator.ts +14 -1
  26. package/src/modules/scheduler/services/__tests__/bullmqSchedulerService.test.ts +36 -0
  27. package/src/modules/scheduler/services/__tests__/schedulerService.test.ts +87 -0
  28. package/src/modules/scheduler/services/bullmqSchedulerService.ts +2 -2
  29. package/src/modules/scheduler/services/schedulerService.ts +27 -12
@@ -1,2 +1,2 @@
1
- [build:scheduler] found 53 entry points
1
+ [build:scheduler] found 54 entry points
2
2
  [build:scheduler] built successfully
@@ -6,7 +6,10 @@ const invalidCases = [
6
6
  { label: "cron: not a cron expression", scheduleType: "cron", scheduleValue: "not-a-cron" },
7
7
  { label: "cron: too few fields", scheduleType: "cron", scheduleValue: "* * *" },
8
8
  { label: "interval: unsupported unit", scheduleType: "interval", scheduleValue: "15x" },
9
- { label: "interval: missing unit", scheduleType: "interval", scheduleValue: "99" }
9
+ { label: "interval: missing unit", scheduleType: "interval", scheduleValue: "99" },
10
+ { label: "interval: zero seconds", scheduleType: "interval", scheduleValue: "0s" },
11
+ { label: "interval: one second", scheduleType: "interval", scheduleValue: "1s" },
12
+ { label: "interval: below one minute", scheduleType: "interval", scheduleValue: "59s" }
10
13
  ];
11
14
  test.describe("TC-SCHED-007: POST /api/scheduler/jobs validates schedule value format", () => {
12
15
  for (const testCase of invalidCases) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/scheduler/__integration__/TC-SCHED-007.spec.ts"],
4
- "sourcesContent": ["import { expect, test } from '@playwright/test'\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'\nimport { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'\nimport { SCHEDULER_EXECUTION_QUEUE, SCHEDULER_JOBS_PATH, uniqueScheduleName } from './helpers/scheduler'\n\ntype ValidationError = { error?: string; details?: Array<{ path?: Array<string | number> }> }\n\n/**\n * TC-SCHED-007: POST /api/scheduler/jobs rejects invalid cron and interval\n * `scheduleValue`s with 400 and an error scoped to the `scheduleValue` path.\n *\n * Interval format is `<number><unit>` with unit in s|m|h|d, so the inputs below\n * are genuinely malformed (the issue's \"99h\"/\"0m\" drafts are actually valid).\n * All cases are rejected at validation, so no records are created and no\n * teardown is required.\n */\nconst invalidCases = [\n { label: 'cron: not a cron expression', scheduleType: 'cron' as const, scheduleValue: 'not-a-cron' },\n { label: 'cron: too few fields', scheduleType: 'cron' as const, scheduleValue: '* * *' },\n { label: 'interval: unsupported unit', scheduleType: 'interval' as const, scheduleValue: '15x' },\n { label: 'interval: missing unit', scheduleType: 'interval' as const, scheduleValue: '99' },\n]\n\ntest.describe('TC-SCHED-007: POST /api/scheduler/jobs validates schedule value format', () => {\n for (const testCase of invalidCases) {\n test(`rejects ${testCase.label} with 400 on scheduleValue`, async ({ request }) => {\n const token = await getAuthToken(request, 'admin')\n\n const response = await apiRequest(request, 'POST', SCHEDULER_JOBS_PATH, {\n token,\n data: {\n name: uniqueScheduleName('Invalid Schedule Value'),\n scopeType: 'organization',\n scheduleType: testCase.scheduleType,\n scheduleValue: testCase.scheduleValue,\n timezone: 'UTC',\n targetType: 'queue',\n targetQueue: SCHEDULER_EXECUTION_QUEUE,\n isEnabled: true,\n sourceType: 'user',\n },\n })\n\n expect(response.status(), `${testCase.label} should be rejected with 400`).toBe(400)\n const body = await readJsonSafe<ValidationError>(response)\n const issuePaths = (body?.details ?? []).map((issue) => (issue.path ?? []).join('.'))\n expect(issuePaths, `${testCase.label} error should target scheduleValue`).toContain('scheduleValue')\n })\n }\n})\n"],
5
- "mappings": "AAAA,SAAS,QAAQ,YAAY;AAC7B,SAAS,YAAY,oBAAoB;AACzC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B,qBAAqB,0BAA0B;AAanF,MAAM,eAAe;AAAA,EACnB,EAAE,OAAO,+BAA+B,cAAc,QAAiB,eAAe,aAAa;AAAA,EACnG,EAAE,OAAO,wBAAwB,cAAc,QAAiB,eAAe,QAAQ;AAAA,EACvF,EAAE,OAAO,8BAA8B,cAAc,YAAqB,eAAe,MAAM;AAAA,EAC/F,EAAE,OAAO,0BAA0B,cAAc,YAAqB,eAAe,KAAK;AAC5F;AAEA,KAAK,SAAS,0EAA0E,MAAM;AAC5F,aAAW,YAAY,cAAc;AACnC,SAAK,WAAW,SAAS,KAAK,8BAA8B,OAAO,EAAE,QAAQ,MAAM;AACjF,YAAM,QAAQ,MAAM,aAAa,SAAS,OAAO;AAEjD,YAAM,WAAW,MAAM,WAAW,SAAS,QAAQ,qBAAqB;AAAA,QACtE;AAAA,QACA,MAAM;AAAA,UACJ,MAAM,mBAAmB,wBAAwB;AAAA,UACjD,WAAW;AAAA,UACX,cAAc,SAAS;AAAA,UACvB,eAAe,SAAS;AAAA,UACxB,UAAU;AAAA,UACV,YAAY;AAAA,UACZ,aAAa;AAAA,UACb,WAAW;AAAA,UACX,YAAY;AAAA,QACd;AAAA,MACF,CAAC;AAED,aAAO,SAAS,OAAO,GAAG,GAAG,SAAS,KAAK,8BAA8B,EAAE,KAAK,GAAG;AACnF,YAAM,OAAO,MAAM,aAA8B,QAAQ;AACzD,YAAM,cAAc,MAAM,WAAW,CAAC,GAAG,IAAI,CAAC,WAAW,MAAM,QAAQ,CAAC,GAAG,KAAK,GAAG,CAAC;AACpF,aAAO,YAAY,GAAG,SAAS,KAAK,oCAAoC,EAAE,UAAU,eAAe;AAAA,IACrG,CAAC;AAAA,EACH;AACF,CAAC;",
4
+ "sourcesContent": ["import { expect, test } from '@playwright/test'\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'\nimport { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'\nimport { SCHEDULER_EXECUTION_QUEUE, SCHEDULER_JOBS_PATH, uniqueScheduleName } from './helpers/scheduler'\n\ntype ValidationError = { error?: string; details?: Array<{ path?: Array<string | number> }> }\n\n/**\n * TC-SCHED-007: POST /api/scheduler/jobs rejects invalid cron and interval\n * `scheduleValue`s with 400 and an error scoped to the `scheduleValue` path.\n *\n * Interval format is `<number><unit>` with unit in s|m|h|d and a minimum floor\n * of one minute. All cases are rejected at validation, so no records are\n * created and no teardown is required.\n */\nconst invalidCases = [\n { label: 'cron: not a cron expression', scheduleType: 'cron' as const, scheduleValue: 'not-a-cron' },\n { label: 'cron: too few fields', scheduleType: 'cron' as const, scheduleValue: '* * *' },\n { label: 'interval: unsupported unit', scheduleType: 'interval' as const, scheduleValue: '15x' },\n { label: 'interval: missing unit', scheduleType: 'interval' as const, scheduleValue: '99' },\n { label: 'interval: zero seconds', scheduleType: 'interval' as const, scheduleValue: '0s' },\n { label: 'interval: one second', scheduleType: 'interval' as const, scheduleValue: '1s' },\n { label: 'interval: below one minute', scheduleType: 'interval' as const, scheduleValue: '59s' },\n]\n\ntest.describe('TC-SCHED-007: POST /api/scheduler/jobs validates schedule value format', () => {\n for (const testCase of invalidCases) {\n test(`rejects ${testCase.label} with 400 on scheduleValue`, async ({ request }) => {\n const token = await getAuthToken(request, 'admin')\n\n const response = await apiRequest(request, 'POST', SCHEDULER_JOBS_PATH, {\n token,\n data: {\n name: uniqueScheduleName('Invalid Schedule Value'),\n scopeType: 'organization',\n scheduleType: testCase.scheduleType,\n scheduleValue: testCase.scheduleValue,\n timezone: 'UTC',\n targetType: 'queue',\n targetQueue: SCHEDULER_EXECUTION_QUEUE,\n isEnabled: true,\n sourceType: 'user',\n },\n })\n\n expect(response.status(), `${testCase.label} should be rejected with 400`).toBe(400)\n const body = await readJsonSafe<ValidationError>(response)\n const issuePaths = (body?.details ?? []).map((issue) => (issue.path ?? []).join('.'))\n expect(issuePaths, `${testCase.label} error should target scheduleValue`).toContain('scheduleValue')\n })\n }\n})\n"],
5
+ "mappings": "AAAA,SAAS,QAAQ,YAAY;AAC7B,SAAS,YAAY,oBAAoB;AACzC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B,qBAAqB,0BAA0B;AAYnF,MAAM,eAAe;AAAA,EACnB,EAAE,OAAO,+BAA+B,cAAc,QAAiB,eAAe,aAAa;AAAA,EACnG,EAAE,OAAO,wBAAwB,cAAc,QAAiB,eAAe,QAAQ;AAAA,EACvF,EAAE,OAAO,8BAA8B,cAAc,YAAqB,eAAe,MAAM;AAAA,EAC/F,EAAE,OAAO,0BAA0B,cAAc,YAAqB,eAAe,KAAK;AAAA,EAC1F,EAAE,OAAO,0BAA0B,cAAc,YAAqB,eAAe,KAAK;AAAA,EAC1F,EAAE,OAAO,wBAAwB,cAAc,YAAqB,eAAe,KAAK;AAAA,EACxF,EAAE,OAAO,8BAA8B,cAAc,YAAqB,eAAe,MAAM;AACjG;AAEA,KAAK,SAAS,0EAA0E,MAAM;AAC5F,aAAW,YAAY,cAAc;AACnC,SAAK,WAAW,SAAS,KAAK,8BAA8B,OAAO,EAAE,QAAQ,MAAM;AACjF,YAAM,QAAQ,MAAM,aAAa,SAAS,OAAO;AAEjD,YAAM,WAAW,MAAM,WAAW,SAAS,QAAQ,qBAAqB;AAAA,QACtE;AAAA,QACA,MAAM;AAAA,UACJ,MAAM,mBAAmB,wBAAwB;AAAA,UACjD,WAAW;AAAA,UACX,cAAc,SAAS;AAAA,UACvB,eAAe,SAAS;AAAA,UACxB,UAAU;AAAA,UACV,YAAY;AAAA,UACZ,aAAa;AAAA,UACb,WAAW;AAAA,UACX,YAAY;AAAA,QACd;AAAA,MACF,CAAC;AAED,aAAO,SAAS,OAAO,GAAG,GAAG,SAAS,KAAK,8BAA8B,EAAE,KAAK,GAAG;AACnF,YAAM,OAAO,MAAM,aAA8B,QAAQ;AACzD,YAAM,cAAc,MAAM,WAAW,CAAC,GAAG,IAAI,CAAC,WAAW,MAAM,QAAQ,CAAC,GAAG,KAAK,GAAG,CAAC;AACpF,aAAO,YAAY,GAAG,SAAS,KAAK,oCAAoC,EAAE,UAAU,eAAe;AAAA,IACrG,CAAC;AAAA,EACH;AACF,CAAC;",
6
6
  "names": []
7
7
  }
@@ -4,7 +4,8 @@ import { makeCreateRedo } from "@open-mercato/shared/lib/commands/redo";
4
4
  import { ensureOrganizationScope } from "@open-mercato/shared/lib/commands/scope";
5
5
  import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
6
6
  import { ScheduledJob } from "../data/entities.js";
7
- import { calculateNextRun } from "../lib/nextRunCalculator.js";
7
+ import { calculateNextRunForWrite } from "../lib/nextRunCalculator.js";
8
+ import { enforceTenantActiveScheduleLimit } from "../lib/activeScheduleLimits.js";
8
9
  import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
9
10
  async function loadScheduleSnapshot(em, scheduleId) {
10
11
  const schedule = await em.findOne(ScheduledJob, { id: scheduleId });
@@ -101,7 +102,10 @@ const createScheduleCommand = {
101
102
  if (input.organizationId) ensureOrganizationScope(ctx, input.organizationId);
102
103
  ensureCanManageSystemScopedJob(ctx, { scopeType: input.scopeType, tenantId: input.tenantId });
103
104
  const em = ctx.container.resolve("em").fork();
104
- const nextRunAt = calculateNextRun(
105
+ if (input.isEnabled ?? true) {
106
+ await enforceTenantActiveScheduleLimit(em, input.tenantId);
107
+ }
108
+ const nextRunAt = calculateNextRunForWrite(
105
109
  input.scheduleType,
106
110
  input.scheduleValue,
107
111
  input.timezone || "UTC"
@@ -188,6 +192,18 @@ const updateScheduleCommand = {
188
192
  ensureTenantScope(ctx, schedule.tenantId);
189
193
  if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId);
190
194
  ensureCanManageSystemScopedJob(ctx, schedule);
195
+ if (input.isEnabled === true && schedule.isEnabled !== true) {
196
+ await enforceTenantActiveScheduleLimit(em, schedule.tenantId);
197
+ }
198
+ const scheduleChanged = input.scheduleType !== void 0 || input.scheduleValue !== void 0 || input.timezone !== void 0;
199
+ const nextRunAt = scheduleChanged ? calculateNextRunForWrite(
200
+ input.scheduleType ?? schedule.scheduleType,
201
+ input.scheduleValue ?? schedule.scheduleValue,
202
+ input.timezone ?? schedule.timezone
203
+ ) : null;
204
+ if (scheduleChanged && !nextRunAt) {
205
+ throw new CrudHttpError(422, { error: "Invalid schedule value." });
206
+ }
191
207
  if (input.name !== void 0) schedule.name = input.name;
192
208
  if (input.description !== void 0) schedule.description = input.description ?? null;
193
209
  if (input.scheduleType !== void 0) schedule.scheduleType = input.scheduleType;
@@ -209,15 +225,8 @@ const updateScheduleCommand = {
209
225
  if (input.targetQueue !== void 0) schedule.targetQueue = input.targetQueue;
210
226
  if (input.targetCommand !== void 0) schedule.targetCommand = input.targetCommand;
211
227
  }
212
- if (input.scheduleType !== void 0 || input.scheduleValue !== void 0 || input.timezone !== void 0) {
213
- const nextRunAt = calculateNextRun(
214
- schedule.scheduleType,
215
- schedule.scheduleValue,
216
- schedule.timezone
217
- );
218
- if (nextRunAt) {
219
- schedule.nextRunAt = nextRunAt;
220
- }
228
+ if (nextRunAt) {
229
+ schedule.nextRunAt = nextRunAt;
221
230
  }
222
231
  schedule.updatedAt = /* @__PURE__ */ new Date();
223
232
  schedule.updatedByUserId = ctx.auth?.userId ?? null;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/scheduler/commands/jobs.ts"],
4
- "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { extractUndoPayload, type UndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { makeCreateRedo } from '@open-mercato/shared/lib/commands/redo'\nimport { ensureOrganizationScope } from '@open-mercato/shared/lib/commands/scope'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { calculateNextRun } from '../lib/nextRunCalculator.js'\nimport type {\n ScheduleCreateInput,\n ScheduleUpdateInput,\n} from '../data/validators.js'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { BullMQSchedulerService } from '../services/bullmqSchedulerService.js'\n\n/**\n * Snapshot of a schedule for undo/redo\n */\ntype ScheduleSnapshot = {\n id: string\n name: string\n description: string | null\n scopeType: 'system' | 'organization' | 'tenant'\n organizationId: string | null\n tenantId: string | null\n scheduleType: 'cron' | 'interval'\n scheduleValue: string\n timezone: string\n targetType: 'queue' | 'command'\n targetQueue: string | null\n targetCommand: string | null\n targetPayload: Record<string, unknown> | null\n requireFeature: string | null\n isEnabled: boolean\n sourceType: 'user' | 'module'\n sourceModule: string | null\n nextRunAt: Date | null\n lastRunAt: Date | null\n}\n\n/**\n * Load a schedule snapshot\n */\nasync function loadScheduleSnapshot(\n em: EntityManager,\n scheduleId: string\n): Promise<ScheduleSnapshot | null> {\n const schedule = await em.findOne(ScheduledJob, { id: scheduleId })\n if (!schedule) return null\n\n return {\n id: schedule.id,\n name: schedule.name,\n description: schedule.description ?? null,\n scopeType: schedule.scopeType,\n organizationId: schedule.organizationId ?? null,\n tenantId: schedule.tenantId ?? null,\n scheduleType: schedule.scheduleType,\n scheduleValue: schedule.scheduleValue,\n timezone: schedule.timezone,\n targetType: schedule.targetType,\n targetQueue: schedule.targetQueue ?? null,\n targetCommand: schedule.targetCommand ?? null,\n targetPayload: schedule.targetPayload ?? null,\n requireFeature: schedule.requireFeature ?? null,\n isEnabled: schedule.isEnabled,\n sourceType: schedule.sourceType,\n sourceModule: schedule.sourceModule ?? null,\n nextRunAt: schedule.nextRunAt ?? null,\n lastRunAt: schedule.lastRunAt ?? null,\n }\n}\n\n/**\n * Snapshots are persisted as JSON (in the action log's command payload), so Date\n * fields come back as ISO strings on undo. Coerce them to Date before writing\n * them onto the entity, otherwise MikroORM throws while flushing a Date column.\n */\nfunction toDate(value: Date | string | null | undefined): Date | null {\n if (!value) return null\n return value instanceof Date ? value : new Date(value)\n}\n\n/**\n * Build a full create seed (including the original id and Date-coerced timestamps)\n * from a snapshot. Shared by `materializeScheduleFromSnapshot` (delete-undo) and the\n * create command's id-preserving `redo`.\n */\nfunction scheduleSeedFromSnapshot(snapshot: ScheduleSnapshot): Record<string, unknown> {\n const now = new Date()\n return {\n id: snapshot.id,\n name: snapshot.name,\n description: snapshot.description,\n scopeType: snapshot.scopeType,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n scheduleType: snapshot.scheduleType,\n scheduleValue: snapshot.scheduleValue,\n timezone: snapshot.timezone,\n targetType: snapshot.targetType,\n targetQueue: snapshot.targetQueue,\n targetCommand: snapshot.targetCommand,\n targetPayload: snapshot.targetPayload,\n requireFeature: snapshot.requireFeature,\n isEnabled: snapshot.isEnabled,\n sourceType: snapshot.sourceType,\n sourceModule: snapshot.sourceModule,\n nextRunAt: toDate(snapshot.nextRunAt),\n lastRunAt: toDate(snapshot.lastRunAt),\n deletedAt: null,\n createdAt: now,\n updatedAt: now,\n }\n}\n\n/**\n * Re-create a ScheduledJob entity from a snapshot, preserving its original id.\n * Used by delete-undo when the row was hard-removed rather than soft-deleted.\n */\nfunction materializeScheduleFromSnapshot(em: EntityManager, snapshot: ScheduleSnapshot): ScheduledJob {\n return em.create(ScheduledJob, scheduleSeedFromSnapshot(snapshot) as never)\n}\n\n/**\n * Trigger BullMQ sync after undo operations.\n * Best-effort: if BullMQ service is unavailable (e.g. local strategy), this is a no-op.\n */\nasync function syncBullMQAfterUndo(ctx: CommandRuntimeContext, schedule: ScheduledJob | null): Promise<void> {\n try {\n if (!ctx.container?.resolve) return\n const bullmqService = ctx.container.resolve<BullMQSchedulerService>('bullmqSchedulerService')\n if (!bullmqService) return\n\n if (schedule && schedule.isEnabled && !schedule.deletedAt) {\n await bullmqService.register(schedule, { skipNextRunUpdate: true })\n } else if (schedule) {\n await bullmqService.unregister(schedule.id)\n }\n } catch {\n // Best-effort: BullMQ service may not be registered (local strategy)\n }\n}\n\n/**\n * Ensure tenant/org scope for security\n */\nfunction ensureTenantScope(ctx: CommandRuntimeContext, tenantId: string | null | undefined) {\n if (tenantId && ctx.auth?.tenantId && ctx.auth.tenantId !== tenantId) {\n throw new Error('Tenant mismatch')\n }\n}\n\n// Super-admin status is the immutable `isSuperAdmin` flag derived from\n// RoleAcl/UserAcl at session resolution. Never compare role names to a string\n// like 'superadmin' \u2014 role names are tenant-mutable and trivially spoofable.\nfunction isSuperAdminActor(ctx: CommandRuntimeContext): boolean {\n return ctx.auth?.isSuperAdmin === true\n}\n\n// `ensureTenantScope` is a no-op for system-scoped jobs (tenantId === null), so a\n// `scheduler.jobs.manage` holder could otherwise update/delete a system schedule\n// belonging to the whole deployment. System-scoped jobs MUST be super-admin only,\n// mirroring the create route's system-scope gate.\nfunction ensureCanManageSystemScopedJob(\n ctx: CommandRuntimeContext,\n job: { scopeType?: string | null; tenantId?: string | null },\n): void {\n const isSystemScoped = job.scopeType === 'system' || job.tenantId == null\n if (!isSystemScoped) return\n if (isSuperAdminActor(ctx)) return\n throw new CrudHttpError(403, {\n error: 'System-scoped scheduled jobs can only be managed by a super administrator.',\n })\n}\n\n/**\n * CREATE SCHEDULE COMMAND\n */\nconst createScheduleCommand: CommandHandler<ScheduleCreateInput, { id: string }> = {\n id: 'scheduler.jobs.create',\n\n async execute(input, ctx) {\n ensureTenantScope(ctx, input.tenantId)\n if (input.organizationId) ensureOrganizationScope(ctx, input.organizationId)\n ensureCanManageSystemScopedJob(ctx, { scopeType: input.scopeType, tenantId: input.tenantId })\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n\n // Calculate next run time\n const nextRunAt = calculateNextRun(\n input.scheduleType,\n input.scheduleValue,\n input.timezone || 'UTC'\n )\n\n if (!nextRunAt) {\n throw new Error('Failed to calculate next run time')\n }\n\n // Create schedule\n const schedule = em.create(ScheduledJob, {\n name: input.name,\n description: input.description ?? null,\n scopeType: input.scopeType,\n organizationId: input.organizationId ?? null,\n tenantId: input.tenantId ?? null,\n scheduleType: input.scheduleType,\n scheduleValue: input.scheduleValue,\n timezone: input.timezone ?? 'UTC',\n targetType: input.targetType,\n targetQueue: input.targetQueue ?? null,\n targetCommand: input.targetCommand ?? null,\n targetPayload: input.targetPayload ?? null,\n requireFeature: input.requireFeature ?? null,\n isEnabled: input.isEnabled ?? true,\n sourceType: input.sourceType ?? 'user',\n sourceModule: input.sourceModule ?? null,\n nextRunAt,\n createdByUserId: (ctx.auth?.userId as string | undefined) ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n\n em.persist(schedule)\n await em.flush()\n\n return { id: schedule.id }\n },\n\n async captureAfter(_input, result, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n return await loadScheduleSnapshot(em, result.id)\n },\n\n async buildLog({ result, ctx, snapshots }) {\n const { translate } = await resolveTranslations()\n const after = snapshots.after as ScheduleSnapshot | undefined\n\n return {\n actionLabel: translate('scheduler.audit.create', 'Create schedule'),\n resourceKind: 'scheduler.job',\n resourceId: result.id,\n tenantId: after?.tenantId || null,\n organizationId: after?.organizationId || null,\n snapshotAfter: after,\n payload: { undo: { after } },\n }\n },\n\n async undo({ logEntry, ctx }) {\n const after = extractUndoPayload<UndoPayload<ScheduleSnapshot>>(logEntry)?.after\n if (!after) return\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n const schedule = await em.findOne(ScheduledJob, { id: after.id })\n\n if (schedule) {\n await em.remove(schedule).flush()\n await syncBullMQAfterUndo(ctx, schedule)\n }\n },\n\n redo: makeCreateRedo<ScheduledJob, ScheduleSnapshot, ScheduleCreateInput, { id: string }>({\n entityClass: ScheduledJob,\n getSnapshotId: (snapshot) => snapshot.id,\n seedFromSnapshot: scheduleSeedFromSnapshot,\n buildResult: (entity) => ({ id: entity.id }),\n afterRestore: async ({ ctx, entity }) => {\n await syncBullMQAfterUndo(ctx, entity)\n },\n }),\n}\n\n/**\n * UPDATE SCHEDULE COMMAND\n */\nconst updateScheduleCommand: CommandHandler<ScheduleUpdateInput, { ok: boolean }> = {\n id: 'scheduler.jobs.update',\n\n async prepare(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n const before = await loadScheduleSnapshot(em, input.id)\n return { before }\n },\n\n async execute(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em').fork()\n\n const schedule = await em.findOne(ScheduledJob, { id: input.id, deletedAt: null })\n if (!schedule) {\n throw new Error('Schedule not found')\n }\n\n ensureTenantScope(ctx, schedule.tenantId)\n if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId)\n ensureCanManageSystemScopedJob(ctx, schedule)\n\n // Update fields\n if (input.name !== undefined) schedule.name = input.name\n if (input.description !== undefined) schedule.description = input.description ?? null\n if (input.scheduleType !== undefined) schedule.scheduleType = input.scheduleType\n if (input.scheduleValue !== undefined) schedule.scheduleValue = input.scheduleValue\n if (input.timezone !== undefined) schedule.timezone = input.timezone\n if (input.targetPayload !== undefined) schedule.targetPayload = input.targetPayload ?? null\n if (input.requireFeature !== undefined) schedule.requireFeature = input.requireFeature || null\n if (input.isEnabled !== undefined) schedule.isEnabled = input.isEnabled\n \n // Handle target type changes - clear stale values when switching between queue and command\n if (input.targetType !== undefined) {\n schedule.targetType = input.targetType\n \n if (input.targetType === 'queue') {\n // Switching to queue: set new queue and clear command\n if (input.targetQueue !== undefined) schedule.targetQueue = input.targetQueue\n schedule.targetCommand = null\n } else if (input.targetType === 'command') {\n // Switching to command: set new command and clear queue\n if (input.targetCommand !== undefined) schedule.targetCommand = input.targetCommand\n schedule.targetQueue = null\n }\n } else {\n // targetType not changing, but allow updating individual target fields\n if (input.targetQueue !== undefined) schedule.targetQueue = input.targetQueue\n if (input.targetCommand !== undefined) schedule.targetCommand = input.targetCommand\n }\n\n // Recalculate next run if schedule changed\n if (input.scheduleType !== undefined || input.scheduleValue !== undefined || input.timezone !== undefined) {\n const nextRunAt = calculateNextRun(\n schedule.scheduleType,\n schedule.scheduleValue,\n schedule.timezone\n )\n if (nextRunAt) {\n schedule.nextRunAt = nextRunAt\n }\n }\n\n schedule.updatedAt = new Date()\n schedule.updatedByUserId = (ctx.auth?.userId as string | undefined) ?? null\n\n await em.flush()\n\n return { ok: true }\n },\n\n async captureAfter(input, _result, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n return await loadScheduleSnapshot(em, input.id)\n },\n\n async buildLog({ input, ctx, snapshots }) {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as ScheduleSnapshot | undefined\n const after = snapshots.after as ScheduleSnapshot | undefined\n\n return {\n actionLabel: translate('scheduler.audit.update', 'Update schedule'),\n resourceKind: 'scheduler.job',\n resourceId: input.id,\n tenantId: after?.tenantId || null,\n organizationId: after?.organizationId || null,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: { undo: { before, after } },\n }\n },\n\n async undo({ logEntry, ctx }) {\n const before = extractUndoPayload<UndoPayload<ScheduleSnapshot>>(logEntry)?.before\n if (!before) return\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n const schedule = await em.findOne(ScheduledJob, { id: before.id })\n\n if (schedule) {\n // Restore all fields\n schedule.name = before.name\n schedule.description = before.description\n schedule.scopeType = before.scopeType\n schedule.organizationId = before.organizationId\n schedule.tenantId = before.tenantId\n schedule.scheduleType = before.scheduleType\n schedule.scheduleValue = before.scheduleValue\n schedule.timezone = before.timezone\n schedule.targetType = before.targetType\n schedule.targetQueue = before.targetQueue\n schedule.targetCommand = before.targetCommand\n schedule.targetPayload = before.targetPayload\n schedule.requireFeature = before.requireFeature\n schedule.isEnabled = before.isEnabled\n schedule.sourceType = before.sourceType\n schedule.sourceModule = before.sourceModule\n schedule.nextRunAt = toDate(before.nextRunAt)\n schedule.lastRunAt = toDate(before.lastRunAt)\n schedule.updatedAt = new Date()\n\n await em.flush()\n await syncBullMQAfterUndo(ctx, schedule)\n }\n },\n}\n\n/**\n * DELETE SCHEDULE COMMAND\n */\nconst deleteScheduleCommand: CommandHandler<{ id: string }, { ok: boolean }> = {\n id: 'scheduler.jobs.delete',\n\n async prepare(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n const before = await loadScheduleSnapshot(em, input.id)\n return { before }\n },\n\n async execute(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em').fork()\n\n const schedule = await em.findOne(ScheduledJob, { id: input.id, deletedAt: null })\n if (!schedule) {\n throw new Error('Schedule not found')\n }\n\n ensureTenantScope(ctx, schedule.tenantId)\n if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId)\n ensureCanManageSystemScopedJob(ctx, schedule)\n\n // Soft delete\n schedule.deletedAt = new Date()\n schedule.updatedAt = new Date()\n schedule.updatedByUserId = (ctx.auth?.userId as string | undefined) ?? null\n\n await em.flush()\n\n return { ok: true }\n },\n\n async buildLog({ input, ctx, snapshots }) {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as ScheduleSnapshot | undefined\n\n return {\n actionLabel: translate('scheduler.audit.delete', 'Delete schedule'),\n resourceKind: 'scheduler.job',\n resourceId: input.id,\n tenantId: before?.tenantId || null,\n organizationId: before?.organizationId || null,\n snapshotBefore: before,\n payload: { undo: { before } },\n }\n },\n\n async undo({ logEntry, ctx }) {\n const before = extractUndoPayload<UndoPayload<ScheduleSnapshot>>(logEntry)?.before\n if (!before) return\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n const existing = await em.findOne(ScheduledJob, { id: before.id })\n\n // Soft-deleted rows are restored by clearing `deletedAt`. A hard-removed row\n // (no surviving record) is re-materialized from the snapshot so undo is\n // robust to either deletion strategy \u2014 mirroring the sales reference undo.\n const schedule = existing ?? materializeScheduleFromSnapshot(em, before)\n if (existing) {\n schedule.deletedAt = null\n schedule.updatedAt = new Date()\n }\n await em.flush()\n await syncBullMQAfterUndo(ctx, schedule)\n },\n}\n\n// Register all commands\nregisterCommand(createScheduleCommand)\nregisterCommand(updateScheduleCommand)\nregisterCommand(deleteScheduleCommand)\n"],
5
- "mappings": "AAAA,SAAS,uBAAuB;AAEhC,SAAS,0BAA4C;AACrD,SAAS,sBAAsB;AAC/B,SAAS,+BAA+B;AACxC,SAAS,qBAAqB;AAE9B,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AAKjC,SAAS,2BAA2B;AA+BpC,eAAe,qBACb,IACA,YACkC;AAClC,QAAM,WAAW,MAAM,GAAG,QAAQ,cAAc,EAAE,IAAI,WAAW,CAAC;AAClE,MAAI,CAAC,SAAU,QAAO;AAEpB,SAAO;AAAA,IACP,IAAI,SAAS;AAAA,IACb,MAAM,SAAS;AAA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AAQ,YAAY;AAAA,MAC9B,gBAAgB,QAAQ,kBAAkB;AAAA,MAC1C,gBAAgB;AAAA,MAChB,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE;AAAA,IAC9B;AAAA,EACF;AAAA,EAEA,MAAM,KAAK,EAAE,UAAU,IAAI,GAAG;AAC5B,UAAM,SAAS,mBAAkD,QAAQ,GAAG;AAC5E,QAAI,CAAC,OAAQ;AAEb,UAAM,KAAK,IAAI,UAAU,QAAuB,IAAI,EAAE,KAAK;AAC3D,UAAM,WAAW,MAAM,GAAG,QAAQ,cAAc,EAAE,IAAI,OAAO,GAAG,CAAC;AAKjE,UAAM,WAAW,YAAY,gCAAgC,IAAI,MAAM;AACvE,QAAI,UAAU;AACZ,eAAS,YAAY;AACrB,eAAS,YAAY,oBAAI,KAAK;AAAA,IAChC;AACA,UAAM,GAAG,MAAM;AACf,UAAM,oBAAoB,KAAK,QAAQ;AAAA,EACzC;AACF;AAGA,gBAAgB,qBAAqB;AACrC,gBAAgB,qBAAqB;AACrC,gBAAgB,qBAAqB;",
4
+ "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { extractUndoPayload, type UndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { makeCreateRedo } from '@open-mercato/shared/lib/commands/redo'\nimport { ensureOrganizationScope } from '@open-mercato/shared/lib/commands/scope'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { calculateNextRunForWrite } from '../lib/nextRunCalculator.js'\nimport { enforceTenantActiveScheduleLimit } from '../lib/activeScheduleLimits.js'\nimport type {\n ScheduleCreateInput,\n ScheduleUpdateInput,\n} from '../data/validators.js'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { BullMQSchedulerService } from '../services/bullmqSchedulerService.js'\n\n/**\n * Snapshot of a schedule for undo/redo\n */\ntype ScheduleSnapshot = {\n id: string\n name: string\n description: string | null\n scopeType: 'system' | 'organization' | 'tenant'\n organizationId: string | null\n tenantId: string | null\n scheduleType: 'cron' | 'interval'\n scheduleValue: string\n timezone: string\n targetType: 'queue' | 'command'\n targetQueue: string | null\n targetCommand: string | null\n targetPayload: Record<string, unknown> | null\n requireFeature: string | null\n isEnabled: boolean\n sourceType: 'user' | 'module'\n sourceModule: string | null\n nextRunAt: Date | null\n lastRunAt: Date | null\n}\n\n/**\n * Load a schedule snapshot\n */\nasync function loadScheduleSnapshot(\n em: EntityManager,\n scheduleId: string\n): Promise<ScheduleSnapshot | null> {\n const schedule = await em.findOne(ScheduledJob, { id: scheduleId })\n if (!schedule) return null\n\n return {\n id: schedule.id,\n name: schedule.name,\n description: schedule.description ?? null,\n scopeType: schedule.scopeType,\n organizationId: schedule.organizationId ?? null,\n tenantId: schedule.tenantId ?? null,\n scheduleType: schedule.scheduleType,\n scheduleValue: schedule.scheduleValue,\n timezone: schedule.timezone,\n targetType: schedule.targetType,\n targetQueue: schedule.targetQueue ?? null,\n targetCommand: schedule.targetCommand ?? null,\n targetPayload: schedule.targetPayload ?? null,\n requireFeature: schedule.requireFeature ?? null,\n isEnabled: schedule.isEnabled,\n sourceType: schedule.sourceType,\n sourceModule: schedule.sourceModule ?? null,\n nextRunAt: schedule.nextRunAt ?? null,\n lastRunAt: schedule.lastRunAt ?? null,\n }\n}\n\n/**\n * Snapshots are persisted as JSON (in the action log's command payload), so Date\n * fields come back as ISO strings on undo. Coerce them to Date before writing\n * them onto the entity, otherwise MikroORM throws while flushing a Date column.\n */\nfunction toDate(value: Date | string | null | undefined): Date | null {\n if (!value) return null\n return value instanceof Date ? value : new Date(value)\n}\n\n/**\n * Build a full create seed (including the original id and Date-coerced timestamps)\n * from a snapshot. Shared by `materializeScheduleFromSnapshot` (delete-undo) and the\n * create command's id-preserving `redo`.\n */\nfunction scheduleSeedFromSnapshot(snapshot: ScheduleSnapshot): Record<string, unknown> {\n const now = new Date()\n return {\n id: snapshot.id,\n name: snapshot.name,\n description: snapshot.description,\n scopeType: snapshot.scopeType,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n scheduleType: snapshot.scheduleType,\n scheduleValue: snapshot.scheduleValue,\n timezone: snapshot.timezone,\n targetType: snapshot.targetType,\n targetQueue: snapshot.targetQueue,\n targetCommand: snapshot.targetCommand,\n targetPayload: snapshot.targetPayload,\n requireFeature: snapshot.requireFeature,\n isEnabled: snapshot.isEnabled,\n sourceType: snapshot.sourceType,\n sourceModule: snapshot.sourceModule,\n nextRunAt: toDate(snapshot.nextRunAt),\n lastRunAt: toDate(snapshot.lastRunAt),\n deletedAt: null,\n createdAt: now,\n updatedAt: now,\n }\n}\n\n/**\n * Re-create a ScheduledJob entity from a snapshot, preserving its original id.\n * Used by delete-undo when the row was hard-removed rather than soft-deleted.\n */\nfunction materializeScheduleFromSnapshot(em: EntityManager, snapshot: ScheduleSnapshot): ScheduledJob {\n return em.create(ScheduledJob, scheduleSeedFromSnapshot(snapshot) as never)\n}\n\n/**\n * Trigger BullMQ sync after undo operations.\n * Best-effort: if BullMQ service is unavailable (e.g. local strategy), this is a no-op.\n */\nasync function syncBullMQAfterUndo(ctx: CommandRuntimeContext, schedule: ScheduledJob | null): Promise<void> {\n try {\n if (!ctx.container?.resolve) return\n const bullmqService = ctx.container.resolve<BullMQSchedulerService>('bullmqSchedulerService')\n if (!bullmqService) return\n\n if (schedule && schedule.isEnabled && !schedule.deletedAt) {\n await bullmqService.register(schedule, { skipNextRunUpdate: true })\n } else if (schedule) {\n await bullmqService.unregister(schedule.id)\n }\n } catch {\n // Best-effort: BullMQ service may not be registered (local strategy)\n }\n}\n\n/**\n * Ensure tenant/org scope for security\n */\nfunction ensureTenantScope(ctx: CommandRuntimeContext, tenantId: string | null | undefined) {\n if (tenantId && ctx.auth?.tenantId && ctx.auth.tenantId !== tenantId) {\n throw new Error('Tenant mismatch')\n }\n}\n\n// Super-admin status is the immutable `isSuperAdmin` flag derived from\n// RoleAcl/UserAcl at session resolution. Never compare role names to a string\n// like 'superadmin' \u2014 role names are tenant-mutable and trivially spoofable.\nfunction isSuperAdminActor(ctx: CommandRuntimeContext): boolean {\n return ctx.auth?.isSuperAdmin === true\n}\n\n// `ensureTenantScope` is a no-op for system-scoped jobs (tenantId === null), so a\n// `scheduler.jobs.manage` holder could otherwise update/delete a system schedule\n// belonging to the whole deployment. System-scoped jobs MUST be super-admin only,\n// mirroring the create route's system-scope gate.\nfunction ensureCanManageSystemScopedJob(\n ctx: CommandRuntimeContext,\n job: { scopeType?: string | null; tenantId?: string | null },\n): void {\n const isSystemScoped = job.scopeType === 'system' || job.tenantId == null\n if (!isSystemScoped) return\n if (isSuperAdminActor(ctx)) return\n throw new CrudHttpError(403, {\n error: 'System-scoped scheduled jobs can only be managed by a super administrator.',\n })\n}\n\n/**\n * CREATE SCHEDULE COMMAND\n */\nconst createScheduleCommand: CommandHandler<ScheduleCreateInput, { id: string }> = {\n id: 'scheduler.jobs.create',\n\n async execute(input, ctx) {\n ensureTenantScope(ctx, input.tenantId)\n if (input.organizationId) ensureOrganizationScope(ctx, input.organizationId)\n ensureCanManageSystemScopedJob(ctx, { scopeType: input.scopeType, tenantId: input.tenantId })\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n\n if (input.isEnabled ?? true) {\n await enforceTenantActiveScheduleLimit(em, input.tenantId)\n }\n\n // Calculate next run time\n const nextRunAt = calculateNextRunForWrite(\n input.scheduleType,\n input.scheduleValue,\n input.timezone || 'UTC'\n )\n\n if (!nextRunAt) {\n throw new Error('Failed to calculate next run time')\n }\n\n // Create schedule\n const schedule = em.create(ScheduledJob, {\n name: input.name,\n description: input.description ?? null,\n scopeType: input.scopeType,\n organizationId: input.organizationId ?? null,\n tenantId: input.tenantId ?? null,\n scheduleType: input.scheduleType,\n scheduleValue: input.scheduleValue,\n timezone: input.timezone ?? 'UTC',\n targetType: input.targetType,\n targetQueue: input.targetQueue ?? null,\n targetCommand: input.targetCommand ?? null,\n targetPayload: input.targetPayload ?? null,\n requireFeature: input.requireFeature ?? null,\n isEnabled: input.isEnabled ?? true,\n sourceType: input.sourceType ?? 'user',\n sourceModule: input.sourceModule ?? null,\n nextRunAt,\n createdByUserId: (ctx.auth?.userId as string | undefined) ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n\n em.persist(schedule)\n await em.flush()\n\n return { id: schedule.id }\n },\n\n async captureAfter(_input, result, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n return await loadScheduleSnapshot(em, result.id)\n },\n\n async buildLog({ result, ctx, snapshots }) {\n const { translate } = await resolveTranslations()\n const after = snapshots.after as ScheduleSnapshot | undefined\n\n return {\n actionLabel: translate('scheduler.audit.create', 'Create schedule'),\n resourceKind: 'scheduler.job',\n resourceId: result.id,\n tenantId: after?.tenantId || null,\n organizationId: after?.organizationId || null,\n snapshotAfter: after,\n payload: { undo: { after } },\n }\n },\n\n async undo({ logEntry, ctx }) {\n const after = extractUndoPayload<UndoPayload<ScheduleSnapshot>>(logEntry)?.after\n if (!after) return\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n const schedule = await em.findOne(ScheduledJob, { id: after.id })\n\n if (schedule) {\n await em.remove(schedule).flush()\n await syncBullMQAfterUndo(ctx, schedule)\n }\n },\n\n redo: makeCreateRedo<ScheduledJob, ScheduleSnapshot, ScheduleCreateInput, { id: string }>({\n entityClass: ScheduledJob,\n getSnapshotId: (snapshot) => snapshot.id,\n seedFromSnapshot: scheduleSeedFromSnapshot,\n buildResult: (entity) => ({ id: entity.id }),\n afterRestore: async ({ ctx, entity }) => {\n await syncBullMQAfterUndo(ctx, entity)\n },\n }),\n}\n\n/**\n * UPDATE SCHEDULE COMMAND\n */\nconst updateScheduleCommand: CommandHandler<ScheduleUpdateInput, { ok: boolean }> = {\n id: 'scheduler.jobs.update',\n\n async prepare(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n const before = await loadScheduleSnapshot(em, input.id)\n return { before }\n },\n\n async execute(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em').fork()\n\n const schedule = await em.findOne(ScheduledJob, { id: input.id, deletedAt: null })\n if (!schedule) {\n throw new Error('Schedule not found')\n }\n\n ensureTenantScope(ctx, schedule.tenantId)\n if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId)\n ensureCanManageSystemScopedJob(ctx, schedule)\n\n if (input.isEnabled === true && schedule.isEnabled !== true) {\n await enforceTenantActiveScheduleLimit(em, schedule.tenantId)\n }\n\n const scheduleChanged = input.scheduleType !== undefined || input.scheduleValue !== undefined || input.timezone !== undefined\n const nextRunAt = scheduleChanged\n ? calculateNextRunForWrite(\n input.scheduleType ?? schedule.scheduleType,\n input.scheduleValue ?? schedule.scheduleValue,\n input.timezone ?? schedule.timezone,\n )\n : null\n\n if (scheduleChanged && !nextRunAt) {\n throw new CrudHttpError(422, { error: 'Invalid schedule value.' })\n }\n\n // Update fields\n if (input.name !== undefined) schedule.name = input.name\n if (input.description !== undefined) schedule.description = input.description ?? null\n if (input.scheduleType !== undefined) schedule.scheduleType = input.scheduleType\n if (input.scheduleValue !== undefined) schedule.scheduleValue = input.scheduleValue\n if (input.timezone !== undefined) schedule.timezone = input.timezone\n if (input.targetPayload !== undefined) schedule.targetPayload = input.targetPayload ?? null\n if (input.requireFeature !== undefined) schedule.requireFeature = input.requireFeature || null\n if (input.isEnabled !== undefined) schedule.isEnabled = input.isEnabled\n \n // Handle target type changes - clear stale values when switching between queue and command\n if (input.targetType !== undefined) {\n schedule.targetType = input.targetType\n \n if (input.targetType === 'queue') {\n // Switching to queue: set new queue and clear command\n if (input.targetQueue !== undefined) schedule.targetQueue = input.targetQueue\n schedule.targetCommand = null\n } else if (input.targetType === 'command') {\n // Switching to command: set new command and clear queue\n if (input.targetCommand !== undefined) schedule.targetCommand = input.targetCommand\n schedule.targetQueue = null\n }\n } else {\n // targetType not changing, but allow updating individual target fields\n if (input.targetQueue !== undefined) schedule.targetQueue = input.targetQueue\n if (input.targetCommand !== undefined) schedule.targetCommand = input.targetCommand\n }\n\n if (nextRunAt) {\n schedule.nextRunAt = nextRunAt\n }\n\n schedule.updatedAt = new Date()\n schedule.updatedByUserId = (ctx.auth?.userId as string | undefined) ?? null\n\n await em.flush()\n\n return { ok: true }\n },\n\n async captureAfter(input, _result, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n return await loadScheduleSnapshot(em, input.id)\n },\n\n async buildLog({ input, ctx, snapshots }) {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as ScheduleSnapshot | undefined\n const after = snapshots.after as ScheduleSnapshot | undefined\n\n return {\n actionLabel: translate('scheduler.audit.update', 'Update schedule'),\n resourceKind: 'scheduler.job',\n resourceId: input.id,\n tenantId: after?.tenantId || null,\n organizationId: after?.organizationId || null,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: { undo: { before, after } },\n }\n },\n\n async undo({ logEntry, ctx }) {\n const before = extractUndoPayload<UndoPayload<ScheduleSnapshot>>(logEntry)?.before\n if (!before) return\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n const schedule = await em.findOne(ScheduledJob, { id: before.id })\n\n if (schedule) {\n // Restore all fields\n schedule.name = before.name\n schedule.description = before.description\n schedule.scopeType = before.scopeType\n schedule.organizationId = before.organizationId\n schedule.tenantId = before.tenantId\n schedule.scheduleType = before.scheduleType\n schedule.scheduleValue = before.scheduleValue\n schedule.timezone = before.timezone\n schedule.targetType = before.targetType\n schedule.targetQueue = before.targetQueue\n schedule.targetCommand = before.targetCommand\n schedule.targetPayload = before.targetPayload\n schedule.requireFeature = before.requireFeature\n schedule.isEnabled = before.isEnabled\n schedule.sourceType = before.sourceType\n schedule.sourceModule = before.sourceModule\n schedule.nextRunAt = toDate(before.nextRunAt)\n schedule.lastRunAt = toDate(before.lastRunAt)\n schedule.updatedAt = new Date()\n\n await em.flush()\n await syncBullMQAfterUndo(ctx, schedule)\n }\n },\n}\n\n/**\n * DELETE SCHEDULE COMMAND\n */\nconst deleteScheduleCommand: CommandHandler<{ id: string }, { ok: boolean }> = {\n id: 'scheduler.jobs.delete',\n\n async prepare(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n const before = await loadScheduleSnapshot(em, input.id)\n return { before }\n },\n\n async execute(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em').fork()\n\n const schedule = await em.findOne(ScheduledJob, { id: input.id, deletedAt: null })\n if (!schedule) {\n throw new Error('Schedule not found')\n }\n\n ensureTenantScope(ctx, schedule.tenantId)\n if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId)\n ensureCanManageSystemScopedJob(ctx, schedule)\n\n // Soft delete\n schedule.deletedAt = new Date()\n schedule.updatedAt = new Date()\n schedule.updatedByUserId = (ctx.auth?.userId as string | undefined) ?? null\n\n await em.flush()\n\n return { ok: true }\n },\n\n async buildLog({ input, ctx, snapshots }) {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as ScheduleSnapshot | undefined\n\n return {\n actionLabel: translate('scheduler.audit.delete', 'Delete schedule'),\n resourceKind: 'scheduler.job',\n resourceId: input.id,\n tenantId: before?.tenantId || null,\n organizationId: before?.organizationId || null,\n snapshotBefore: before,\n payload: { undo: { before } },\n }\n },\n\n async undo({ logEntry, ctx }) {\n const before = extractUndoPayload<UndoPayload<ScheduleSnapshot>>(logEntry)?.before\n if (!before) return\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n const existing = await em.findOne(ScheduledJob, { id: before.id })\n\n // Soft-deleted rows are restored by clearing `deletedAt`. A hard-removed row\n // (no surviving record) is re-materialized from the snapshot so undo is\n // robust to either deletion strategy \u2014 mirroring the sales reference undo.\n const schedule = existing ?? materializeScheduleFromSnapshot(em, before)\n if (existing) {\n schedule.deletedAt = null\n schedule.updatedAt = new Date()\n }\n await em.flush()\n await syncBullMQAfterUndo(ctx, schedule)\n },\n}\n\n// Register all commands\nregisterCommand(createScheduleCommand)\nregisterCommand(updateScheduleCommand)\nregisterCommand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S,YAAY,oBAAI,KAAK;AAAA,IAChC;AACA,UAAM,GAAG,MAAM;AACf,UAAM,oBAAoB,KAAK,QAAQ;AAAA,EACzC;AACF;AAGA,gBAAgB,qBAAqB;AACrC,gBAAgB,qBAAqB;AACrC,gBAAgB,qBAAqB;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,29 @@
1
+ import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
2
+ import { ScheduledJob } from "../data/entities.js";
3
+ const DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT = 100;
4
+ const ACTIVE_SCHEDULE_LIMIT_ENV = "OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT";
5
+ function getMaxActiveSchedulesPerTenant() {
6
+ const parsed = Number.parseInt(process.env[ACTIVE_SCHEDULE_LIMIT_ENV] ?? "", 10);
7
+ if (Number.isFinite(parsed) && parsed > 0) return parsed;
8
+ return DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT;
9
+ }
10
+ async function enforceTenantActiveScheduleLimit(em, tenantId) {
11
+ if (!tenantId) return;
12
+ const maxActiveSchedules = getMaxActiveSchedulesPerTenant();
13
+ const activeScheduleCount = await em.count(ScheduledJob, {
14
+ tenantId,
15
+ isEnabled: true,
16
+ deletedAt: null
17
+ });
18
+ if (activeScheduleCount >= maxActiveSchedules) {
19
+ throw new CrudHttpError(422, {
20
+ error: `Active scheduled job limit reached for this tenant (${maxActiveSchedules}).`
21
+ });
22
+ }
23
+ }
24
+ export {
25
+ DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT,
26
+ enforceTenantActiveScheduleLimit,
27
+ getMaxActiveSchedulesPerTenant
28
+ };
29
+ //# sourceMappingURL=activeScheduleLimits.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/scheduler/lib/activeScheduleLimits.ts"],
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { ScheduledJob } from '../data/entities.js'\n\nexport const DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT = 100\nconst ACTIVE_SCHEDULE_LIMIT_ENV = 'OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT'\n\nexport function getMaxActiveSchedulesPerTenant(): number {\n const parsed = Number.parseInt(process.env[ACTIVE_SCHEDULE_LIMIT_ENV] ?? '', 10)\n if (Number.isFinite(parsed) && parsed > 0) return parsed\n return DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT\n}\n\nexport async function enforceTenantActiveScheduleLimit(\n em: EntityManager,\n tenantId: string | null | undefined,\n): Promise<void> {\n if (!tenantId) return\n\n const maxActiveSchedules = getMaxActiveSchedulesPerTenant()\n const activeScheduleCount = await em.count(ScheduledJob, {\n tenantId,\n isEnabled: true,\n deletedAt: null,\n })\n\n if (activeScheduleCount >= maxActiveSchedules) {\n throw new CrudHttpError(422, {\n error: `Active scheduled job limit reached for this tenant (${maxActiveSchedules}).`,\n })\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAEtB,MAAM,0CAA0C;AACvD,MAAM,4BAA4B;AAE3B,SAAS,iCAAyC;AACvD,QAAM,SAAS,OAAO,SAAS,QAAQ,IAAI,yBAAyB,KAAK,IAAI,EAAE;AAC/E,MAAI,OAAO,SAAS,MAAM,KAAK,SAAS,EAAG,QAAO;AAClD,SAAO;AACT;AAEA,eAAsB,iCACpB,IACA,UACe;AACf,MAAI,CAAC,SAAU;AAEf,QAAM,qBAAqB,+BAA+B;AAC1D,QAAM,sBAAsB,MAAM,GAAG,MAAM,cAAc;AAAA,IACvD;AAAA,IACA,WAAW;AAAA,IACX,WAAW;AAAA,EACb,CAAC;AAED,MAAI,uBAAuB,oBAAoB;AAC7C,UAAM,IAAI,cAAc,KAAK;AAAA,MAC3B,OAAO,uDAAuD,kBAAkB;AAAA,IAClF,CAAC;AAAA,EACH;AACF;",
6
+ "names": []
7
+ }
@@ -1,3 +1,4 @@
1
+ const MIN_SCHEDULE_INTERVAL_MS = 60 * 1e3;
1
2
  function parseInterval(interval) {
2
3
  const regex = /^(\d+)(s|m|h|d)$/;
3
4
  const match = interval.match(regex);
@@ -18,14 +19,16 @@ function parseInterval(interval) {
18
19
  };
19
20
  return value * multipliers[unit];
20
21
  }
22
+ function resolveScheduleIntervalMs(interval) {
23
+ return Math.max(parseInterval(interval), MIN_SCHEDULE_INTERVAL_MS);
24
+ }
21
25
  function calculateNextRunFromInterval(interval, fromDate = /* @__PURE__ */ new Date()) {
22
- const ms = parseInterval(interval);
26
+ const ms = resolveScheduleIntervalMs(interval);
23
27
  return new Date(fromDate.getTime() + ms);
24
28
  }
25
29
  function validateInterval(interval) {
26
30
  try {
27
- parseInterval(interval);
28
- return true;
31
+ return parseInterval(interval) >= MIN_SCHEDULE_INTERVAL_MS;
29
32
  } catch {
30
33
  return false;
31
34
  }
@@ -72,9 +75,11 @@ function intervalToHuman(interval) {
72
75
  }
73
76
  }
74
77
  export {
78
+ MIN_SCHEDULE_INTERVAL_MS,
75
79
  calculateNextRunFromInterval,
76
80
  intervalToHuman,
77
81
  parseInterval,
82
+ resolveScheduleIntervalMs,
78
83
  validateInterval
79
84
  };
80
85
  //# sourceMappingURL=intervalParser.js.map
@@ -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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AAK,UAAU,KAAK,MAAM,KAAK,GAAG;AAC7C,iBAAO,GAAG,KAAK,QAAQ,UAAU,IAAI,MAAM,EAAE;AAAA,QAC/C;AACA,eAAO,GAAG,OAAO,UAAU,YAAY,IAAI,MAAM,EAAE;AAAA,MAErD,KAAK;AAEH,YAAI,QAAQ,KAAK,SAAS,KAAK,MAAM,IAAI,GAAG;AAC1C,iBAAO,GAAG,IAAI,OAAO,SAAS,IAAI,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,IAC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AAG,OAAO,UAAU,YAAY,IAAI,MAAM,EAAE;AAAA,MAErD,KAAK;AAEH,YAAI,QAAQ,KAAK,SAAS,KAAK,MAAM,IAAI,GAAG;AAC1C,iBAAO,GAAG,IAAI,OAAO,SAAS,IAAI,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;",
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
  }
@@ -1,7 +1,7 @@
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";
4
+ import { resolveScheduleIntervalMs } from "../lib/intervalParser.js";
5
5
  import { getRedisUrlOrThrow } 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" });
@@ -204,7 +204,7 @@ class BullMQSchedulerService {
204
204
  }
205
205
  opts.pattern = schedule.scheduleValue;
206
206
  } else if (schedule.scheduleType === "interval") {
207
- const intervalMs = parseInterval(schedule.scheduleValue);
207
+ const intervalMs = resolveScheduleIntervalMs(schedule.scheduleValue);
208
208
  opts.every = intervalMs;
209
209
  } else {
210
210
  throw new Error(`Unsupported schedule type: ${schedule.scheduleType}`);
@@ -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 }\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M,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,aAAO,MAAM,iCAAiC,EAAE,KAAK,MAAM,CAAC;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 } 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 = 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 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.que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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,0BAA0B,SAAS,aAAa;AACnE,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,aAAO,MAAM,iCAAiC,EAAE,KAAK,MAAM,CAAC;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;",
6
6
  "names": []
7
7
  }
@@ -1,5 +1,6 @@
1
1
  import { ScheduledJob } from "../data/entities.js";
2
- import { calculateNextRun } from "../lib/nextRunCalculator.js";
2
+ import { calculateNextRunForWrite } from "../lib/nextRunCalculator.js";
3
+ import { enforceTenantActiveScheduleLimit } from "../lib/activeScheduleLimits.js";
3
4
  import { createLogger } from "@open-mercato/shared/lib/logger";
4
5
  const logger = createLogger("scheduler");
5
6
  class SchedulerService {
@@ -14,7 +15,7 @@ class SchedulerService {
14
15
  const em = this.em().fork();
15
16
  this.validateScope(registration);
16
17
  this.validateTarget(registration);
17
- const nextRunAt = calculateNextRun(
18
+ const nextRunAt = calculateNextRunForWrite(
18
19
  registration.scheduleType,
19
20
  registration.scheduleValue,
20
21
  registration.timezone || "UTC"
@@ -23,6 +24,12 @@ class SchedulerService {
23
24
  throw new Error(`Failed to calculate next run time for schedule: ${registration.id}`);
24
25
  }
25
26
  let schedule = await em.findOne(ScheduledJob, { id: registration.id });
27
+ const nextTenantId = registration.tenantId || null;
28
+ const nextIsEnabled = registration.isEnabled !== void 0 ? registration.isEnabled : schedule?.isEnabled ?? true;
29
+ const tenantChanged = schedule ? (schedule.tenantId || null) !== nextTenantId : false;
30
+ if (nextIsEnabled && (schedule?.isEnabled !== true || tenantChanged)) {
31
+ await enforceTenantActiveScheduleLimit(em, nextTenantId);
32
+ }
26
33
  if (schedule) {
27
34
  schedule.name = registration.name;
28
35
  schedule.description = registration.description || null;
@@ -114,6 +121,18 @@ class SchedulerService {
114
121
  if (!schedule) {
115
122
  throw new Error(`Schedule not found: ${scheduleId}`);
116
123
  }
124
+ if (changes.isEnabled === true && schedule.isEnabled !== true) {
125
+ await enforceTenantActiveScheduleLimit(em, schedule.tenantId);
126
+ }
127
+ const scheduleChanged = changes.scheduleType !== void 0 || changes.scheduleValue !== void 0 || changes.timezone !== void 0;
128
+ const nextRunAt = scheduleChanged ? calculateNextRunForWrite(
129
+ changes.scheduleType ?? schedule.scheduleType,
130
+ changes.scheduleValue ?? schedule.scheduleValue,
131
+ changes.timezone ?? schedule.timezone
132
+ ) : null;
133
+ if (scheduleChanged && !nextRunAt) {
134
+ throw new Error(`Failed to calculate next run time for schedule: ${scheduleId}`);
135
+ }
117
136
  if (changes.name !== void 0) schedule.name = changes.name;
118
137
  if (changes.description !== void 0) schedule.description = changes.description || null;
119
138
  if (changes.scheduleType !== void 0) schedule.scheduleType = changes.scheduleType;
@@ -137,15 +156,8 @@ class SchedulerService {
137
156
  if (changes.targetQueue !== void 0) schedule.targetQueue = changes.targetQueue || null;
138
157
  if (changes.targetCommand !== void 0) schedule.targetCommand = changes.targetCommand || null;
139
158
  }
140
- if (changes.scheduleType !== void 0 || changes.scheduleValue !== void 0 || changes.timezone !== void 0) {
141
- const nextRunAt = calculateNextRun(
142
- schedule.scheduleType,
143
- schedule.scheduleValue,
144
- schedule.timezone
145
- );
146
- if (nextRunAt) {
147
- schedule.nextRunAt = nextRunAt;
148
- }
159
+ if (nextRunAt) {
160
+ schedule.nextRunAt = nextRunAt;
149
161
  }
150
162
  schedule.updatedAt = /* @__PURE__ */ new Date();
151
163
  await em.flush();