@open-mercato/scheduler 0.9.0 → 0.9.1-develop.7459.1.99e3accd30
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.
- package/.turbo/turbo-build.log +1 -1
- package/dist/modules/scheduler/api/jobs/[id]/executions/route.js +1 -1
- package/dist/modules/scheduler/api/jobs/[id]/executions/route.js.map +2 -2
- package/dist/modules/scheduler/api/jobs/route.js +1 -1
- package/dist/modules/scheduler/api/jobs/route.js.map +2 -2
- package/dist/modules/scheduler/cli.js +28 -6
- package/dist/modules/scheduler/cli.js.map +2 -2
- package/dist/modules/scheduler/data/validators.js +5 -5
- package/dist/modules/scheduler/data/validators.js.map +2 -2
- package/dist/modules/scheduler/lib/bullmqNextRun.js +61 -0
- package/dist/modules/scheduler/lib/bullmqNextRun.js.map +7 -0
- package/dist/modules/scheduler/lib/nextRunSync.js +80 -0
- package/dist/modules/scheduler/lib/nextRunSync.js.map +7 -0
- package/dist/modules/scheduler/workers/execute-schedule.worker.js +20 -0
- package/dist/modules/scheduler/workers/execute-schedule.worker.js.map +2 -2
- package/package.json +7 -6
- package/src/modules/scheduler/__tests__/cli.run.test.ts +135 -0
- package/src/modules/scheduler/api/jobs/[id]/executions/route.ts +1 -1
- package/src/modules/scheduler/api/jobs/route.ts +1 -1
- package/src/modules/scheduler/api/trigger/__tests__/route.test.ts +15 -0
- package/src/modules/scheduler/cli.ts +33 -7
- package/src/modules/scheduler/data/__tests__/validators.test.ts +29 -0
- package/src/modules/scheduler/data/validators.ts +5 -5
- package/src/modules/scheduler/lib/__tests__/bullmqNextRun.test.ts +200 -0
- package/src/modules/scheduler/lib/__tests__/nextRunSync.test.ts +222 -0
- package/src/modules/scheduler/lib/bullmqNextRun.ts +112 -0
- package/src/modules/scheduler/lib/nextRunSync.ts +131 -0
- package/src/modules/scheduler/workers/__tests__/execute-schedule.next-run.test.ts +468 -0
- package/src/modules/scheduler/workers/__tests__/execute-schedule.worker.test.ts +4 -0
- package/src/modules/scheduler/workers/execute-schedule.worker.ts +35 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/modules/scheduler/lib/nextRunSync.ts"],
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport { readBullmqNextRun, type BullmqNextRun } from './bullmqNextRun.js'\nimport { parseInterval, resolveScheduleIntervalMs } from './intervalParser.js'\n\nconst logger = createLogger('scheduler').child({ component: 'next-run-sync' })\n\n/**\n * The schedule's timing configuration as an execution loaded it, captured\n * before the target runs.\n */\nexport type ScheduleTimingSnapshot = {\n scheduleId: string\n tenantId: string | null\n organizationId: string | null\n scheduleType: 'cron' | 'interval'\n scheduleValue: string\n timezone: string\n}\n\nconst UPDATE_NEXT_RUN_AT_SQL = `update scheduled_jobs\n set next_run_at = ?\n where id = ?\n and tenant_id is not distinct from ?\n and organization_id is not distinct from ?\n and deleted_at is null\n and is_enabled = true\n and schedule_type = ?\n and schedule_value = ?\n and timezone = ?\n and ? > now()\n and next_run_at is distinct from ?`\n\nfunction intervalCandidates(scheduleValue: string): number[] {\n try {\n return [resolveScheduleIntervalMs(scheduleValue), parseInterval(scheduleValue)]\n } catch {\n return []\n }\n}\n\n/**\n * True when the BullMQ scheduler was registered from the same timing\n * configuration the execution loaded. A scheduler registered before the\n * minimum-interval clamp keeps the unclamped `every`, so both forms match.\n */\nexport function bullmqNextRunMatchesTiming(next: BullmqNextRun, timing: ScheduleTimingSnapshot): boolean {\n if (timing.scheduleType === 'cron') {\n return next.pattern === timing.scheduleValue\n && (next.timezone ?? 'UTC') === (timing.timezone || 'UTC')\n }\n return typeof next.every === 'number' && intervalCandidates(timing.scheduleValue).includes(next.every)\n}\n\n/**\n * Mirrors BullMQ's next fire time into `scheduled_jobs.next_run_at` after an\n * execution under the async strategy, where BullMQ \u2014 not this row \u2014 decides\n * when a schedule fires.\n *\n * The row is matched by id and by the tenant and organization the execution\n * verified against its job payload, so a write can only land on that scope.\n *\n * The value is written only while it is still true: the BullMQ scheduler and\n * the row must both still carry the timing configuration this execution\n * loaded (an edit in flight writes its own `nextRunAt`), and the instant must\n * still be ahead of the database clock (an execution holding an older slot,\n * or a slot that is due but not picked up, writes nothing). When BullMQ has no\n * usable value nothing is written: a locally computed time would show a run\n * BullMQ is not going to perform.\n *\n * The statement is raw so that `updated_at` stays untouched \u2014 skipped and\n * failed executions must not invalidate an editor's optimistic-lock version \u2014\n * and it runs on a pooled connection, outside the per-job unit of work, which\n * may hold whatever a failed target left behind.\n *\n * Never throws: this is bookkeeping awaited from the worker's `finally`, so a\n * failure here must neither fail a successful execution nor replace the\n * target's own error.\n */\nexport async function syncScheduleNextRunAt(\n resolveEm: () => EntityManager,\n timing: ScheduleTimingSnapshot,\n): Promise<void> {\n if (process.env.QUEUE_STRATEGY !== 'async') return\n\n try {\n const next = await readBullmqNextRun(timing.scheduleId)\n if (!next) return\n\n if (!bullmqNextRunMatchesTiming(next, timing)) {\n logger.debug('Skipping nextRunAt sync: BullMQ scheduler does not match the loaded schedule timing', {\n scheduleId: timing.scheduleId,\n scheduleType: timing.scheduleType,\n scheduleValue: timing.scheduleValue,\n timezone: timing.timezone,\n bullmqPattern: next.pattern,\n bullmqEvery: next.every,\n bullmqTimezone: next.timezone,\n })\n return\n }\n\n await resolveEm().getConnection().execute(\n UPDATE_NEXT_RUN_AT_SQL,\n [\n next.nextRunAt,\n timing.scheduleId,\n timing.tenantId,\n timing.organizationId,\n timing.scheduleType,\n timing.scheduleValue,\n timing.timezone,\n next.nextRunAt,\n next.nextRunAt,\n ],\n 'run',\n )\n } catch (error) {\n logger.warn('Failed to sync nextRunAt from BullMQ', { scheduleId: timing.scheduleId, err: error })\n try {\n getTelemetryRuntime()?.reportError(error, {\n module: 'scheduler',\n code: 'scheduler.next_run_sync_failed',\n attributes: { scheduleId: timing.scheduleId },\n })\n } catch (telemetryError) {\n logger.warn('Failed to report a nextRunAt sync error to telemetry', { err: telemetryError })\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC,SAAS,yBAA6C;AACtD,SAAS,eAAe,iCAAiC;AAEzD,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,gBAAgB,CAAC;AAe7E,MAAM,yBAAyB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAa/B,SAAS,mBAAmB,eAAiC;AAC3D,MAAI;AACF,WAAO,CAAC,0BAA0B,aAAa,GAAG,cAAc,aAAa,CAAC;AAAA,EAChF,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;AAOO,SAAS,2BAA2B,MAAqB,QAAyC;AACvG,MAAI,OAAO,iBAAiB,QAAQ;AAClC,WAAO,KAAK,YAAY,OAAO,kBACzB,KAAK,YAAY,YAAY,OAAO,YAAY;AAAA,EACxD;AACA,SAAO,OAAO,KAAK,UAAU,YAAY,mBAAmB,OAAO,aAAa,EAAE,SAAS,KAAK,KAAK;AACvG;AA2BA,eAAsB,sBACpB,WACA,QACe;AACf,MAAI,QAAQ,IAAI,mBAAmB,QAAS;AAE5C,MAAI;AACF,UAAM,OAAO,MAAM,kBAAkB,OAAO,UAAU;AACtD,QAAI,CAAC,KAAM;AAEX,QAAI,CAAC,2BAA2B,MAAM,MAAM,GAAG;AAC7C,aAAO,MAAM,uFAAuF;AAAA,QAClG,YAAY,OAAO;AAAA,QACnB,cAAc,OAAO;AAAA,QACrB,eAAe,OAAO;AAAA,QACtB,UAAU,OAAO;AAAA,QACjB,eAAe,KAAK;AAAA,QACpB,aAAa,KAAK;AAAA,QAClB,gBAAgB,KAAK;AAAA,MACvB,CAAC;AACD;AAAA,IACF;AAEA,UAAM,UAAU,EAAE,cAAc,EAAE;AAAA,MAChC;AAAA,MACA;AAAA,QACE,KAAK;AAAA,QACL,OAAO;AAAA,QACP,OAAO;AAAA,QACP,OAAO;AAAA,QACP,OAAO;AAAA,QACP,OAAO;AAAA,QACP,OAAO;AAAA,QACP,KAAK;AAAA,QACL,KAAK;AAAA,MACP;AAAA,MACA;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AACd,WAAO,KAAK,wCAAwC,EAAE,YAAY,OAAO,YAAY,KAAK,MAAM,CAAC;AACjG,QAAI;AACF,0BAAoB,GAAG,YAAY,OAAO;AAAA,QACxC,QAAQ;AAAA,QACR,MAAM;AAAA,QACN,YAAY,EAAE,YAAY,OAAO,WAAW;AAAA,MAC9C,CAAC;AAAA,IACH,SAAS,gBAAgB;AACvB,aAAO,KAAK,wDAAwD,EAAE,KAAK,eAAe,CAAC;AAAA,IAC7F;AAAA,EACF;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
sanitizeSchedulerTargetPayload,
|
|
17
17
|
validateSchedulerTargetPayload
|
|
18
18
|
} from "../lib/safeQueueTargets.js";
|
|
19
|
+
import { syncScheduleNextRunAt } from "../lib/nextRunSync.js";
|
|
19
20
|
const logger = createLogger("scheduler").child({ component: "worker" });
|
|
20
21
|
const metadata = {
|
|
21
22
|
queue: "scheduler-execution",
|
|
@@ -23,6 +24,17 @@ const metadata = {
|
|
|
23
24
|
// Process up to 5 schedules concurrently
|
|
24
25
|
};
|
|
25
26
|
async function executeScheduleWorker(job, ctx) {
|
|
27
|
+
const execution = { timing: null };
|
|
28
|
+
try {
|
|
29
|
+
await executeSchedule(job, ctx, execution);
|
|
30
|
+
} finally {
|
|
31
|
+
const { timing } = execution;
|
|
32
|
+
if (timing) {
|
|
33
|
+
await syncScheduleNextRunAt(() => ctx.resolve("em"), timing);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
async function executeSchedule(job, ctx, execution) {
|
|
26
38
|
logger.debug("Processing job", {
|
|
27
39
|
jobId: ctx.jobId,
|
|
28
40
|
attemptNumber: ctx.attemptNumber
|
|
@@ -77,6 +89,14 @@ async function executeScheduleWorker(job, ctx) {
|
|
|
77
89
|
});
|
|
78
90
|
return;
|
|
79
91
|
}
|
|
92
|
+
execution.timing = {
|
|
93
|
+
scheduleId: schedule.id,
|
|
94
|
+
tenantId: schedule.tenantId ?? null,
|
|
95
|
+
organizationId: schedule.organizationId ?? null,
|
|
96
|
+
scheduleType: schedule.scheduleType,
|
|
97
|
+
scheduleValue: schedule.scheduleValue,
|
|
98
|
+
timezone: schedule.timezone
|
|
99
|
+
};
|
|
80
100
|
await emitSchedulerEvent("scheduler.job.started", {
|
|
81
101
|
id: schedule.id,
|
|
82
102
|
tenantId: schedule.tenantId,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/scheduler/workers/execute-schedule.worker.ts"],
|
|
4
|
-
"sourcesContent": ["import type { QueuedJob, JobContext, WorkerMeta } from '@open-mercato/queue'\nimport { createQueue } from '@open-mercato/queue'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { emitSchedulerEvent } from '../events.js'\nimport {\n assertSchedulerSafeCommandAuthorized,\n SchedulerCommandAuthorizationError,\n} from '../lib/scheduler-safe-commands.js'\nimport { buildScheduledCommandContext, resolveScheduledCommandActorUserId } from '../lib/commandContext.js'\nimport { buildQueueTargetPayload, buildSchedulerIdempotencyKey } from '../lib/queueTargetPayload.js'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport {\n canDispatchScheduleQueueTarget,\n getSchedulerQueueRequiredFeatures,\n sanitizeSchedulerTargetPayload,\n validateSchedulerTargetPayload,\n} from '../lib/safeQueueTargets'\n\nconst logger = createLogger('scheduler').child({ component: 'worker' })\n\n// Worker metadata for auto-discovery\nexport const metadata: WorkerMeta = {\n queue: 'scheduler-execution',\n concurrency: 5, // Process up to 5 schedules concurrently\n}\n\nexport type ExecuteSchedulePayload = {\n scheduleId: string\n tenantId?: string | null\n organizationId?: string | null\n scopeType: 'system' | 'organization' | 'tenant'\n triggerType?: 'scheduled' | 'manual'\n triggeredByUserId?: string | null\n}\n\ntype HandlerContext = { resolve: <T = unknown>(name: string) => T }\ntype RbacServiceLike = {\n tenantHasFeature(\n tenantId: string | null | undefined,\n feature: string,\n opts?: { organizationId?: string | null },\n ): Promise<boolean>\n userHasAllFeatures(\n userId: string,\n required: readonly string[],\n scope: { tenantId: string | null; organizationId: string | null },\n ): Promise<boolean>\n}\n\n/**\n * Worker that executes scheduled jobs.\n * \n * This worker is triggered by BullMQ repeatable jobs at the scheduled times.\n * It loads the fresh schedule configuration from the database, validates\n * conditions, and enqueues the target job or executes the command.\n * \n * BullMQ handles:\n * - Timing (exact cron/interval execution)\n * - Distributed locking (prevents duplicate execution)\n * - Retries (if worker fails)\n * - Execution history (via job state, logs, timestamps)\n * \n * This worker handles:\n * - Loading fresh schedule config\n * - Checking feature flags and conditions\n * - Enqueuing target job or executing command\n * - Updating last run time\n */\nexport default async function executeScheduleWorker(\n job: QueuedJob<ExecuteSchedulePayload>,\n ctx: JobContext & HandlerContext,\n): Promise<void> {\n logger.debug('Processing job', {\n jobId: ctx.jobId,\n attemptNumber: ctx.attemptNumber,\n })\n \n // Defensive: handle both data and payload for BullMQ compatibility\n const payload = (job.payload || (job as unknown as { data?: ExecuteSchedulePayload }).data) as ExecuteSchedulePayload | undefined\n \n if (!payload || !payload.scheduleId) {\n logger.error('Invalid job payload: scheduleId missing', { jobId: ctx.jobId })\n throw new Error('scheduleId is required in job payload')\n }\n\n const { scheduleId } = payload\n\n const em = ctx.resolve<EntityManager>('em')\n const rbacService = ctx.resolve<RbacServiceLike>('rbacService')\n\n // Load fresh schedule from database\n const schedule = await em.findOne(ScheduledJob, { \n id: scheduleId,\n deletedAt: null,\n })\n\n if (!schedule) {\n logger.info('Schedule not found or deleted', { scheduleId })\n return\n }\n\n // CRITICAL: Verify scope integrity - ensure payload scope matches database\n // This prevents scope tampering and ensures proper multi-tenant isolation\n if (payload.scopeType !== schedule.scopeType) {\n logger.error('Scope type mismatch for schedule', {\n scheduleId,\n payloadScope: payload.scopeType,\n dbScope: schedule.scopeType,\n })\n throw new Error('Schedule scope type mismatch - potential security issue')\n }\n\n if (payload.tenantId !== schedule.tenantId) {\n logger.error('Tenant ID mismatch for schedule', {\n scheduleId,\n payloadTenant: payload.tenantId,\n dbTenant: schedule.tenantId,\n })\n throw new Error('Schedule tenant ID mismatch - potential security issue')\n }\n\n if (payload.organizationId !== schedule.organizationId) {\n logger.error('Organization ID mismatch for schedule', {\n scheduleId,\n payloadOrg: payload.organizationId,\n dbOrg: schedule.organizationId,\n })\n throw new Error('Schedule organization ID mismatch - potential security issue')\n }\n\n // Check if schedule is still enabled\n if (!schedule.isEnabled) {\n logger.debug('Schedule is disabled', { scheduleId })\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: 'Schedule is disabled',\n })\n return\n }\n\n // Emit started event\n await emitSchedulerEvent('scheduler.job.started', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n attemptNumber: ctx.attemptNumber || 1,\n })\n\n // Check feature flag if required\n if (schedule.requireFeature) {\n const hasFeature = await rbacService.tenantHasFeature(\n schedule.tenantId,\n schedule.requireFeature,\n { organizationId: schedule.organizationId },\n )\n \n if (!hasFeature) {\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Feature not enabled: ${schedule.requireFeature}`,\n })\n\n logger.debug('Schedule skipped: feature not enabled', { scheduleId, requireFeature: schedule.requireFeature })\n return\n }\n }\n\n // Enqueue target job or execute command\n if (schedule.targetType === 'queue' && schedule.targetQueue) {\n // Dispatch-time reauthorization (#5213): provenance is verified, never\n // trusted \u2014 module-authored rows must still be owned by their recorded\n // sourceModule and carry no acting-user stamp; API-authored rows may only\n // target workers that opted into scheduling.\n if (!canDispatchScheduleQueueTarget(schedule)) {\n logger.error('Refusing non-safe queue target for schedule', {\n scheduleId,\n targetQueue: schedule.targetQueue,\n sourceType: schedule.sourceType,\n sourceModule: schedule.sourceType === 'module' ? schedule.sourceModule : undefined,\n })\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Queue is not an approved scheduler target: ${schedule.targetQueue}`,\n })\n return\n }\n\n // Re-validate the stored payload against the target's registered schema and\n // the tenant-level features the target requires (#5213, defense in depth).\n const payloadIssue = validateSchedulerTargetPayload(schedule.targetQueue, schedule.targetPayload)\n if (payloadIssue) {\n logger.error('Refusing schedule with invalid payload for queue target', {\n scheduleId,\n targetQueue: schedule.targetQueue,\n issue: payloadIssue,\n })\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Invalid payload for scheduler queue ${schedule.targetQueue}`,\n })\n return\n }\n\n const requiredQueueFeatures = getSchedulerQueueRequiredFeatures(schedule.targetQueue)\n if (schedule.scopeType !== 'system' && requiredQueueFeatures.length > 0) {\n for (const feature of requiredQueueFeatures) {\n if (await rbacService.tenantHasFeature(schedule.tenantId, feature, { organizationId: schedule.organizationId })) continue\n logger.error('Refusing schedule whose tenant lacks a required feature of the queue target', {\n scheduleId,\n targetQueue: schedule.targetQueue,\n feature,\n })\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Tenant lacks feature required by scheduler queue ${schedule.targetQueue}: ${feature}`,\n })\n return\n }\n }\n\n // Determine queue strategy from environment\n const queueStrategy = (process.env.QUEUE_STRATEGY || 'local') as 'local' | 'async'\n const targetQueue = createQueue(schedule.targetQueue, queueStrategy, {\n connection: { url: getRedisUrlOrThrow('QUEUE') },\n })\n\n let targetJobId: string | undefined\n try {\n // The execute-schedule job id is stable across BullMQ retries, so if\n // this worker crashes between enqueue and DB flush the retried attempt\n // reuses the same idempotency key and downstream workers can dedupe.\n const idempotencyKey = buildSchedulerIdempotencyKey(schedule.id, ctx.jobId ?? Date.now())\n\n // Rebuild tenant/org authority context and the trusted dispatch origin\n // server-side; author-supplied scope/envelope keys never survive (#5213).\n const sanitizedPayload = sanitizeSchedulerTargetPayload(schedule.targetPayload, schedule)\n targetJobId = await targetQueue.enqueue({\n ...buildQueueTargetPayload({\n targetPayload: sanitizedPayload,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n idempotencyKey,\n }),\n _jobOrigin: 'scheduler' as const,\n })\n } finally {\n // Always close the queue instance to free Redis connections\n await targetQueue.close()\n }\n \n // Update schedule's last run time\n schedule.lastRunAt = new Date()\n await em.flush()\n\n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n queueJobId: targetJobId,\n queueName: schedule.targetQueue,\n })\n\n logger.debug('Successfully enqueued job', {\n scheduleId: schedule.id,\n targetQueue: schedule.targetQueue,\n queueJobId: targetJobId,\n })\n\n } else if (schedule.targetType === 'command' && schedule.targetCommand) {\n const commandBus = new CommandBus()\n // A manual run acts as whoever pressed the button; an unattended run keeps\n // acting as the schedule's creator. The gate below and the context built\n // afterwards must agree on that identity, so it is resolved once, by the same\n // helper the context itself uses.\n const triggeredByUserId = payload.triggerType === 'manual' ? payload.triggeredByUserId ?? null : null\n const actorUserId = resolveScheduledCommandActorUserId(schedule, { triggeredByUserId })\n try {\n await assertSchedulerSafeCommandAuthorized({\n commandId: schedule.targetCommand,\n actorUserId,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n rbacService,\n })\n } catch (error) {\n // A refusal is permanent, so it must not be thrown: throwing hands BullMQ an\n // error it cannot tell from an outage and it retries a decision that no\n // attempt can change, while the run leaves no trace beyond a log line. The\n // queue branch above already ends its equivalent conditions with an event and\n // a return; this does the same, and records the refusal as a failure rather\n // than a skip because a schedule whose actor may no longer run its command is\n // a state an operator has to act on.\n //\n // Only the authorization decision is swallowed. Anything else \u2014 an RBAC\n // lookup that fails because its store is down \u2014 is genuinely transient and\n // still propagates so BullMQ retries it.\n if (!(error instanceof SchedulerCommandAuthorizationError)) throw error\n\n const reason = error.message\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: reason,\n failedAt: new Date(),\n })\n\n logger.warn('Schedule refused: scheduled command is not authorized', {\n scheduleId: schedule.id,\n commandId: schedule.targetCommand,\n triggerType: payload.triggerType ?? 'scheduled',\n reason,\n })\n return\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 // The gate authorized `actorUserId`; this must execute as that same identity.\n const commandCtx = buildScheduledCommandContext(schedule, ctx as unknown as AppContainer, {\n triggeredByUserId,\n })\n \n const commandResult = await commandBus.execute(schedule.targetCommand, {\n input: commandInput,\n ctx: commandCtx,\n })\n \n // Update schedule's last run time\n schedule.lastRunAt = new Date()\n await em.flush()\n \n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n commandId: schedule.targetCommand,\n commandResult: commandResult.result,\n })\n \n logger.debug('Successfully executed command', {\n scheduleId: schedule.id,\n commandId: schedule.targetCommand,\n })\n\n } else {\n throw new Error('Invalid target configuration')\n }\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,mBAAmB;AAC5B,SAAS,0BAA0B;AAEnC,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAE3B,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,8BAA8B,0CAA0C;AACjF,SAAS,yBAAyB,oCAAoC;AACtE,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;
|
|
4
|
+
"sourcesContent": ["import type { QueuedJob, JobContext, WorkerMeta } from '@open-mercato/queue'\nimport { createQueue } from '@open-mercato/queue'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { emitSchedulerEvent } from '../events.js'\nimport {\n assertSchedulerSafeCommandAuthorized,\n SchedulerCommandAuthorizationError,\n} from '../lib/scheduler-safe-commands.js'\nimport { buildScheduledCommandContext, resolveScheduledCommandActorUserId } from '../lib/commandContext.js'\nimport { buildQueueTargetPayload, buildSchedulerIdempotencyKey } from '../lib/queueTargetPayload.js'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport {\n canDispatchScheduleQueueTarget,\n getSchedulerQueueRequiredFeatures,\n sanitizeSchedulerTargetPayload,\n validateSchedulerTargetPayload,\n} from '../lib/safeQueueTargets'\nimport { syncScheduleNextRunAt, type ScheduleTimingSnapshot } from '../lib/nextRunSync.js'\n\nconst logger = createLogger('scheduler').child({ component: 'worker' })\n\n// Worker metadata for auto-discovery\nexport const metadata: WorkerMeta = {\n queue: 'scheduler-execution',\n concurrency: 5, // Process up to 5 schedules concurrently\n}\n\nexport type ExecuteSchedulePayload = {\n scheduleId: string\n tenantId?: string | null\n organizationId?: string | null\n scopeType: 'system' | 'organization' | 'tenant'\n triggerType?: 'scheduled' | 'manual'\n triggeredByUserId?: string | null\n}\n\ntype HandlerContext = { resolve: <T = unknown>(name: string) => T }\ntype RbacServiceLike = {\n tenantHasFeature(\n tenantId: string | null | undefined,\n feature: string,\n opts?: { organizationId?: string | null },\n ): Promise<boolean>\n userHasAllFeatures(\n userId: string,\n required: readonly string[],\n scope: { tenantId: string | null; organizationId: string | null },\n ): Promise<boolean>\n}\n\n/**\n * Worker that executes scheduled jobs.\n * \n * This worker is triggered by BullMQ repeatable jobs at the scheduled times.\n * It loads the fresh schedule configuration from the database, validates\n * conditions, and enqueues the target job or executes the command.\n * \n * BullMQ handles:\n * - Timing (exact cron/interval execution)\n * - Distributed locking (prevents duplicate execution)\n * - Retries (if worker fails)\n * - Execution history (via job state, logs, timestamps)\n * \n * This worker handles:\n * - Loading fresh schedule config\n * - Checking feature flags and conditions\n * - Enqueuing target job or executing command\n * - Updating last run time\n * - Mirroring BullMQ's next fire time into nextRunAt once the run is over\n */\nexport default async function executeScheduleWorker(\n job: QueuedJob<ExecuteSchedulePayload>,\n ctx: JobContext & HandlerContext,\n): Promise<void> {\n const execution: ScheduleExecution = { timing: null }\n try {\n await executeSchedule(job, ctx, execution)\n } finally {\n // Runs on every outcome of a started execution \u2014 completed, skipped,\n // refused or thrown \u2014 because BullMQ has consumed the slot either way.\n // A job rejected before it started (unknown, mismatched or disabled\n // schedule) never sets the timing and is left alone.\n const { timing } = execution\n if (timing) {\n await syncScheduleNextRunAt(() => ctx.resolve<EntityManager>('em'), timing)\n }\n }\n}\n\ntype ScheduleExecution = { timing: ScheduleTimingSnapshot | null }\n\nasync function executeSchedule(\n job: QueuedJob<ExecuteSchedulePayload>,\n ctx: JobContext & HandlerContext,\n execution: ScheduleExecution,\n): Promise<void> {\n logger.debug('Processing job', {\n jobId: ctx.jobId,\n attemptNumber: ctx.attemptNumber,\n })\n \n // Defensive: handle both data and payload for BullMQ compatibility\n const payload = (job.payload || (job as unknown as { data?: ExecuteSchedulePayload }).data) as ExecuteSchedulePayload | undefined\n \n if (!payload || !payload.scheduleId) {\n logger.error('Invalid job payload: scheduleId missing', { jobId: ctx.jobId })\n throw new Error('scheduleId is required in job payload')\n }\n\n const { scheduleId } = payload\n\n const em = ctx.resolve<EntityManager>('em')\n const rbacService = ctx.resolve<RbacServiceLike>('rbacService')\n\n // Load fresh schedule from database\n const schedule = await em.findOne(ScheduledJob, { \n id: scheduleId,\n deletedAt: null,\n })\n\n if (!schedule) {\n logger.info('Schedule not found or deleted', { scheduleId })\n return\n }\n\n // CRITICAL: Verify scope integrity - ensure payload scope matches database\n // This prevents scope tampering and ensures proper multi-tenant isolation\n if (payload.scopeType !== schedule.scopeType) {\n logger.error('Scope type mismatch for schedule', {\n scheduleId,\n payloadScope: payload.scopeType,\n dbScope: schedule.scopeType,\n })\n throw new Error('Schedule scope type mismatch - potential security issue')\n }\n\n if (payload.tenantId !== schedule.tenantId) {\n logger.error('Tenant ID mismatch for schedule', {\n scheduleId,\n payloadTenant: payload.tenantId,\n dbTenant: schedule.tenantId,\n })\n throw new Error('Schedule tenant ID mismatch - potential security issue')\n }\n\n if (payload.organizationId !== schedule.organizationId) {\n logger.error('Organization ID mismatch for schedule', {\n scheduleId,\n payloadOrg: payload.organizationId,\n dbOrg: schedule.organizationId,\n })\n throw new Error('Schedule organization ID mismatch - potential security issue')\n }\n\n // Check if schedule is still enabled\n if (!schedule.isEnabled) {\n logger.debug('Schedule is disabled', { scheduleId })\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: 'Schedule is disabled',\n })\n return\n }\n\n // Captured before the target runs: the sync that follows the run must compare\n // against the timing this execution loaded, not whatever the entity holds later.\n execution.timing = {\n scheduleId: schedule.id,\n tenantId: schedule.tenantId ?? null,\n organizationId: schedule.organizationId ?? null,\n scheduleType: schedule.scheduleType,\n scheduleValue: schedule.scheduleValue,\n timezone: schedule.timezone,\n }\n\n // Emit started event\n await emitSchedulerEvent('scheduler.job.started', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n attemptNumber: ctx.attemptNumber || 1,\n })\n\n // Check feature flag if required\n if (schedule.requireFeature) {\n const hasFeature = await rbacService.tenantHasFeature(\n schedule.tenantId,\n schedule.requireFeature,\n { organizationId: schedule.organizationId },\n )\n \n if (!hasFeature) {\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Feature not enabled: ${schedule.requireFeature}`,\n })\n\n logger.debug('Schedule skipped: feature not enabled', { scheduleId, requireFeature: schedule.requireFeature })\n return\n }\n }\n\n // Enqueue target job or execute command\n if (schedule.targetType === 'queue' && schedule.targetQueue) {\n // Dispatch-time reauthorization (#5213): provenance is verified, never\n // trusted \u2014 module-authored rows must still be owned by their recorded\n // sourceModule and carry no acting-user stamp; API-authored rows may only\n // target workers that opted into scheduling.\n if (!canDispatchScheduleQueueTarget(schedule)) {\n logger.error('Refusing non-safe queue target for schedule', {\n scheduleId,\n targetQueue: schedule.targetQueue,\n sourceType: schedule.sourceType,\n sourceModule: schedule.sourceType === 'module' ? schedule.sourceModule : undefined,\n })\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Queue is not an approved scheduler target: ${schedule.targetQueue}`,\n })\n return\n }\n\n // Re-validate the stored payload against the target's registered schema and\n // the tenant-level features the target requires (#5213, defense in depth).\n const payloadIssue = validateSchedulerTargetPayload(schedule.targetQueue, schedule.targetPayload)\n if (payloadIssue) {\n logger.error('Refusing schedule with invalid payload for queue target', {\n scheduleId,\n targetQueue: schedule.targetQueue,\n issue: payloadIssue,\n })\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Invalid payload for scheduler queue ${schedule.targetQueue}`,\n })\n return\n }\n\n const requiredQueueFeatures = getSchedulerQueueRequiredFeatures(schedule.targetQueue)\n if (schedule.scopeType !== 'system' && requiredQueueFeatures.length > 0) {\n for (const feature of requiredQueueFeatures) {\n if (await rbacService.tenantHasFeature(schedule.tenantId, feature, { organizationId: schedule.organizationId })) continue\n logger.error('Refusing schedule whose tenant lacks a required feature of the queue target', {\n scheduleId,\n targetQueue: schedule.targetQueue,\n feature,\n })\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Tenant lacks feature required by scheduler queue ${schedule.targetQueue}: ${feature}`,\n })\n return\n }\n }\n\n // Determine queue strategy from environment\n const queueStrategy = (process.env.QUEUE_STRATEGY || 'local') as 'local' | 'async'\n const targetQueue = createQueue(schedule.targetQueue, queueStrategy, {\n connection: { url: getRedisUrlOrThrow('QUEUE') },\n })\n\n let targetJobId: string | undefined\n try {\n // The execute-schedule job id is stable across BullMQ retries, so if\n // this worker crashes between enqueue and DB flush the retried attempt\n // reuses the same idempotency key and downstream workers can dedupe.\n const idempotencyKey = buildSchedulerIdempotencyKey(schedule.id, ctx.jobId ?? Date.now())\n\n // Rebuild tenant/org authority context and the trusted dispatch origin\n // server-side; author-supplied scope/envelope keys never survive (#5213).\n const sanitizedPayload = sanitizeSchedulerTargetPayload(schedule.targetPayload, schedule)\n targetJobId = await targetQueue.enqueue({\n ...buildQueueTargetPayload({\n targetPayload: sanitizedPayload,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n idempotencyKey,\n }),\n _jobOrigin: 'scheduler' as const,\n })\n } finally {\n // Always close the queue instance to free Redis connections\n await targetQueue.close()\n }\n \n // Update schedule's last run time\n schedule.lastRunAt = new Date()\n await em.flush()\n\n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n queueJobId: targetJobId,\n queueName: schedule.targetQueue,\n })\n\n logger.debug('Successfully enqueued job', {\n scheduleId: schedule.id,\n targetQueue: schedule.targetQueue,\n queueJobId: targetJobId,\n })\n\n } else if (schedule.targetType === 'command' && schedule.targetCommand) {\n const commandBus = new CommandBus()\n // A manual run acts as whoever pressed the button; an unattended run keeps\n // acting as the schedule's creator. The gate below and the context built\n // afterwards must agree on that identity, so it is resolved once, by the same\n // helper the context itself uses.\n const triggeredByUserId = payload.triggerType === 'manual' ? payload.triggeredByUserId ?? null : null\n const actorUserId = resolveScheduledCommandActorUserId(schedule, { triggeredByUserId })\n try {\n await assertSchedulerSafeCommandAuthorized({\n commandId: schedule.targetCommand,\n actorUserId,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n rbacService,\n })\n } catch (error) {\n // A refusal is permanent, so it must not be thrown: throwing hands BullMQ an\n // error it cannot tell from an outage and it retries a decision that no\n // attempt can change, while the run leaves no trace beyond a log line. The\n // queue branch above already ends its equivalent conditions with an event and\n // a return; this does the same, and records the refusal as a failure rather\n // than a skip because a schedule whose actor may no longer run its command is\n // a state an operator has to act on.\n //\n // Only the authorization decision is swallowed. Anything else \u2014 an RBAC\n // lookup that fails because its store is down \u2014 is genuinely transient and\n // still propagates so BullMQ retries it.\n if (!(error instanceof SchedulerCommandAuthorizationError)) throw error\n\n const reason = error.message\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: reason,\n failedAt: new Date(),\n })\n\n logger.warn('Schedule refused: scheduled command is not authorized', {\n scheduleId: schedule.id,\n commandId: schedule.targetCommand,\n triggerType: payload.triggerType ?? 'scheduled',\n reason,\n })\n return\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 // The gate authorized `actorUserId`; this must execute as that same identity.\n const commandCtx = buildScheduledCommandContext(schedule, ctx as unknown as AppContainer, {\n triggeredByUserId,\n })\n \n const commandResult = await commandBus.execute(schedule.targetCommand, {\n input: commandInput,\n ctx: commandCtx,\n })\n \n // Update schedule's last run time\n schedule.lastRunAt = new Date()\n await em.flush()\n \n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n commandId: schedule.targetCommand,\n commandResult: commandResult.result,\n })\n \n logger.debug('Successfully executed command', {\n scheduleId: schedule.id,\n commandId: schedule.targetCommand,\n })\n\n } else {\n throw new Error('Invalid target configuration')\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,mBAAmB;AAC5B,SAAS,0BAA0B;AAEnC,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAE3B,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,8BAA8B,0CAA0C;AACjF,SAAS,yBAAyB,oCAAoC;AACtE,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,6BAA0D;AAEnE,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,SAAS,CAAC;AAG/D,MAAM,WAAuB;AAAA,EAClC,OAAO;AAAA,EACP,aAAa;AAAA;AACf;AA6CA,eAAO,sBACL,KACA,KACe;AACf,QAAM,YAA+B,EAAE,QAAQ,KAAK;AACpD,MAAI;AACF,UAAM,gBAAgB,KAAK,KAAK,SAAS;AAAA,EAC3C,UAAE;AAKA,UAAM,EAAE,OAAO,IAAI;AACnB,QAAI,QAAQ;AACV,YAAM,sBAAsB,MAAM,IAAI,QAAuB,IAAI,GAAG,MAAM;AAAA,IAC5E;AAAA,EACF;AACF;AAIA,eAAe,gBACb,KACA,KACA,WACe;AACf,SAAO,MAAM,kBAAkB;AAAA,IAC7B,OAAO,IAAI;AAAA,IACX,eAAe,IAAI;AAAA,EACrB,CAAC;AAGD,QAAM,UAA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AAA,MACF,CAAC;AACD;AAAA,IACF;AAEA,UAAM,eAAe;AAAA,MACnB,GAAK,SAAS,iBAA6C,CAAC;AAAA,MAC5D,UAAU,SAAS;AAAA,MACnB,gBAAgB,SAAS;AAAA,IAC3B;AAIA,UAAM,aAAa,6BAA6B,UAAU,KAAgC;AAAA,MACxF;AAAA,IACF,CAAC;AAED,UAAM,gBAAgB,MAAM,WAAW,QAAQ,SAAS,eAAe;AAAA,MACrE,OAAO;AAAA,MACP,KAAK;AAAA,IACP,CAAC;AAGD,aAAS,YAAY,oBAAI,KAAK;AAC9B,UAAM,GAAG,MAAM;AAEf,UAAM,mBAAmB,2BAA2B;AAAA,MAClD,IAAI,SAAS;AAAA,MACb,UAAU,SAAS;AAAA,MACnB,gBAAgB,SAAS;AAAA,MACzB,WAAW,SAAS;AAAA,MACpB,eAAe,cAAc;AAAA,IAC/B,CAAC;AAED,WAAO,MAAM,iCAAiC;AAAA,MAC5C,YAAY,SAAS;AAAA,MACrB,WAAW,SAAS;AAAA,IACtB,CAAC;AAAA,EAEH,OAAO;AACL,UAAM,IAAI,MAAM,8BAA8B;AAAA,EAChD;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/scheduler",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.1-develop.7459.1.99e3accd30",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Database-managed scheduled jobs with admin UI",
|
|
6
6
|
"type": "module",
|
|
@@ -59,13 +59,13 @@
|
|
|
59
59
|
"./*/*/*/*/*/*.json": "./src/*/*/*/*/*/*.json"
|
|
60
60
|
},
|
|
61
61
|
"dependencies": {
|
|
62
|
-
"@open-mercato/events": "0.9.
|
|
63
|
-
"@open-mercato/queue": "0.9.
|
|
62
|
+
"@open-mercato/events": "0.9.1-develop.7459.1.99e3accd30",
|
|
63
|
+
"@open-mercato/queue": "0.9.1-develop.7459.1.99e3accd30",
|
|
64
64
|
"cron-parser": "^5.6.2"
|
|
65
65
|
},
|
|
66
66
|
"peerDependencies": {
|
|
67
67
|
"@mikro-orm/core": "^7.0.14",
|
|
68
|
-
"@open-mercato/shared": "0.9.
|
|
68
|
+
"@open-mercato/shared": "0.9.1-develop.7459.1.99e3accd30",
|
|
69
69
|
"bullmq": "^5.0.0 || ^6.0.0",
|
|
70
70
|
"ioredis": "^5.0.0 || ^6.0.0",
|
|
71
71
|
"zod": ">=3.23.0"
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
}
|
|
80
80
|
},
|
|
81
81
|
"devDependencies": {
|
|
82
|
-
"@open-mercato/shared": "0.9.
|
|
82
|
+
"@open-mercato/shared": "0.9.1-develop.7459.1.99e3accd30",
|
|
83
83
|
"@types/jest": "^30.0.0",
|
|
84
84
|
"@types/node": "^26.4.0",
|
|
85
85
|
"jest": "^30.4.2",
|
|
@@ -93,5 +93,6 @@
|
|
|
93
93
|
"type": "git",
|
|
94
94
|
"url": "https://github.com/open-mercato/open-mercato",
|
|
95
95
|
"directory": "packages/scheduler"
|
|
96
|
-
}
|
|
96
|
+
},
|
|
97
|
+
"stableVersion": "0.9.0"
|
|
97
98
|
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
export {}
|
|
2
|
+
|
|
3
|
+
const enqueue = jest.fn()
|
|
4
|
+
const close = jest.fn()
|
|
5
|
+
const createQueue = jest.fn(() => ({ enqueue, close }))
|
|
6
|
+
|
|
7
|
+
jest.mock('@open-mercato/queue', () => ({ createQueue }), { virtual: true })
|
|
8
|
+
|
|
9
|
+
jest.mock('@open-mercato/shared/lib/redis/connection', () => ({
|
|
10
|
+
getRedisUrlOrThrow: jest.fn(() => 'redis://localhost:6379'),
|
|
11
|
+
}))
|
|
12
|
+
|
|
13
|
+
const findOne = jest.fn()
|
|
14
|
+
const resolve = jest.fn((name: string) => {
|
|
15
|
+
if (name === 'em') return { findOne }
|
|
16
|
+
throw new Error(`Could not resolve '${name}'`)
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
jest.mock('@open-mercato/shared/lib/di/container', () => ({
|
|
20
|
+
createRequestContainer: jest.fn(async () => ({ resolve })),
|
|
21
|
+
}))
|
|
22
|
+
|
|
23
|
+
jest.mock('../data/entities.js', () => ({ ScheduledJob: class ScheduledJob {} }))
|
|
24
|
+
jest.mock('../lib/safeQueueTargets', () => ({ auditSchedulerModuleQueueRows: jest.fn(() => []) }))
|
|
25
|
+
|
|
26
|
+
const SCHEDULE_ID = '11111111-1111-4111-8111-111111111111'
|
|
27
|
+
|
|
28
|
+
function makeSchedule(overrides: Record<string, unknown> = {}) {
|
|
29
|
+
return {
|
|
30
|
+
id: SCHEDULE_ID,
|
|
31
|
+
name: 'Nightly report',
|
|
32
|
+
scheduleType: 'cron',
|
|
33
|
+
scheduleValue: '0 2 * * *',
|
|
34
|
+
scopeType: 'tenant',
|
|
35
|
+
tenantId: 'tenant-a',
|
|
36
|
+
organizationId: 'org-a',
|
|
37
|
+
targetType: 'queue',
|
|
38
|
+
targetQueue: 'reports',
|
|
39
|
+
targetCommand: null,
|
|
40
|
+
...overrides,
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function loadRunCommand() {
|
|
45
|
+
let commands: Array<{ command: string; run(rest: string[]): Promise<void> }> = []
|
|
46
|
+
jest.isolateModules(() => {
|
|
47
|
+
commands = require('../cli').default
|
|
48
|
+
})
|
|
49
|
+
const run = commands.find((cmd) => cmd.command === 'run')
|
|
50
|
+
if (!run) throw new Error('run command not registered')
|
|
51
|
+
return run
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
describe('mercato scheduler run', () => {
|
|
55
|
+
const previousStrategy = process.env.QUEUE_STRATEGY
|
|
56
|
+
const previousExitCode = process.exitCode
|
|
57
|
+
let stdout: jest.SpyInstance
|
|
58
|
+
let stderr: jest.SpyInstance
|
|
59
|
+
|
|
60
|
+
beforeEach(() => {
|
|
61
|
+
jest.clearAllMocks()
|
|
62
|
+
enqueue.mockResolvedValue('queue-job-1')
|
|
63
|
+
close.mockResolvedValue(undefined)
|
|
64
|
+
stdout = jest.spyOn(process.stdout, 'write').mockImplementation(() => true)
|
|
65
|
+
stderr = jest.spyOn(process.stderr, 'write').mockImplementation(() => true)
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
afterEach(() => {
|
|
69
|
+
stdout.mockRestore()
|
|
70
|
+
stderr.mockRestore()
|
|
71
|
+
process.exitCode = previousExitCode
|
|
72
|
+
if (previousStrategy === undefined) delete process.env.QUEUE_STRATEGY
|
|
73
|
+
else process.env.QUEUE_STRATEGY = previousStrategy
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
it('enqueues a manual execution with the full payload under the async strategy', async () => {
|
|
77
|
+
process.env.QUEUE_STRATEGY = 'async'
|
|
78
|
+
findOne.mockResolvedValue(makeSchedule())
|
|
79
|
+
|
|
80
|
+
await loadRunCommand().run([SCHEDULE_ID])
|
|
81
|
+
|
|
82
|
+
expect(resolve).not.toHaveBeenCalledWith('queueService')
|
|
83
|
+
expect(createQueue).toHaveBeenCalledWith('scheduler-execution', 'async', {
|
|
84
|
+
connection: { url: 'redis://localhost:6379' },
|
|
85
|
+
})
|
|
86
|
+
expect(enqueue).toHaveBeenCalledWith({
|
|
87
|
+
scheduleId: SCHEDULE_ID,
|
|
88
|
+
tenantId: 'tenant-a',
|
|
89
|
+
organizationId: 'org-a',
|
|
90
|
+
scopeType: 'tenant',
|
|
91
|
+
triggerType: 'manual',
|
|
92
|
+
triggeredByUserId: null,
|
|
93
|
+
})
|
|
94
|
+
expect(close).toHaveBeenCalledTimes(1)
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
it('refuses without touching a queue when the strategy is not async', async () => {
|
|
98
|
+
delete process.env.QUEUE_STRATEGY
|
|
99
|
+
findOne.mockResolvedValue(makeSchedule())
|
|
100
|
+
|
|
101
|
+
await expect(loadRunCommand().run([SCHEDULE_ID])).rejects.toThrow(
|
|
102
|
+
'Manual trigger requires QUEUE_STRATEGY=async',
|
|
103
|
+
)
|
|
104
|
+
expect(createQueue).not.toHaveBeenCalled()
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
it('reports an unknown schedule without enqueueing', async () => {
|
|
108
|
+
process.env.QUEUE_STRATEGY = 'async'
|
|
109
|
+
findOne.mockResolvedValue(null)
|
|
110
|
+
|
|
111
|
+
await loadRunCommand().run([SCHEDULE_ID])
|
|
112
|
+
|
|
113
|
+
expect(stderr).toHaveBeenCalledWith(`Schedule not found: ${SCHEDULE_ID}\n`)
|
|
114
|
+
expect(createQueue).not.toHaveBeenCalled()
|
|
115
|
+
expect(process.exitCode).toBe(1)
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
it('prints usage and exits non-zero when the schedule id is missing', async () => {
|
|
119
|
+
await loadRunCommand().run([])
|
|
120
|
+
|
|
121
|
+
expect(stderr).toHaveBeenCalledWith('Usage: mercato scheduler run <schedule-id>\n')
|
|
122
|
+
expect(findOne).not.toHaveBeenCalled()
|
|
123
|
+
expect(createQueue).not.toHaveBeenCalled()
|
|
124
|
+
expect(process.exitCode).toBe(1)
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
it('closes the queue and fails when the enqueue fails', async () => {
|
|
128
|
+
process.env.QUEUE_STRATEGY = 'async'
|
|
129
|
+
findOne.mockResolvedValue(makeSchedule())
|
|
130
|
+
enqueue.mockRejectedValue(new Error('redis down'))
|
|
131
|
+
|
|
132
|
+
await expect(loadRunCommand().run([SCHEDULE_ID])).rejects.toThrow('Failed to trigger job: redis down')
|
|
133
|
+
expect(close).toHaveBeenCalledTimes(1)
|
|
134
|
+
})
|
|
135
|
+
})
|
|
@@ -154,7 +154,7 @@ const executionsQuerySchema = z.object({
|
|
|
154
154
|
// Response schemas
|
|
155
155
|
const executionItemSchema = z.object({
|
|
156
156
|
id: z.string(),
|
|
157
|
-
scheduleId: z.
|
|
157
|
+
scheduleId: z.guid(),
|
|
158
158
|
startedAt: z.string(),
|
|
159
159
|
finishedAt: z.string().nullable(),
|
|
160
160
|
status: z.enum(['running', 'completed', 'failed', 'waiting']),
|
|
@@ -171,7 +171,7 @@ export const { GET, POST, PUT, DELETE } = crud
|
|
|
171
171
|
|
|
172
172
|
// Response schemas
|
|
173
173
|
const scheduledJobListItemSchema = z.object({
|
|
174
|
-
id: z.
|
|
174
|
+
id: z.guid(),
|
|
175
175
|
name: z.string(),
|
|
176
176
|
description: z.string().nullable(),
|
|
177
177
|
scopeType: z.enum(['system', 'organization', 'tenant']),
|
|
@@ -76,6 +76,21 @@ describe('POST /api/scheduler/trigger', () => {
|
|
|
76
76
|
expect(commandBusExecuteMock).not.toHaveBeenCalled()
|
|
77
77
|
})
|
|
78
78
|
|
|
79
|
+
it('dispatches a module-registered schedule id that lacks RFC 4122 version/variant bits', async () => {
|
|
80
|
+
const moduleScheduleId = 'a1b2c3d4-e5f6-a7b8-c9d0-e1f2a3b4c5d6'
|
|
81
|
+
commandBusExecuteMock.mockResolvedValue({
|
|
82
|
+
result: outcome({ scheduleId: moduleScheduleId, queueJobId: 'job-1' }),
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
const response = await POST(request({ id: moduleScheduleId }))
|
|
86
|
+
|
|
87
|
+
expect(response.status).toBe(200)
|
|
88
|
+
expect(commandBusExecuteMock).toHaveBeenCalledWith(
|
|
89
|
+
'scheduler.jobs.trigger',
|
|
90
|
+
expect.objectContaining({ input: { id: moduleScheduleId } }),
|
|
91
|
+
)
|
|
92
|
+
})
|
|
93
|
+
|
|
79
94
|
it.each([
|
|
80
95
|
['enqueued' as const, 200],
|
|
81
96
|
['not_found' as const, 404],
|
|
@@ -4,6 +4,10 @@ import type { EntityManager } from '@mikro-orm/core'
|
|
|
4
4
|
import { ScheduledJob } from './data/entities.js'
|
|
5
5
|
import { parseBooleanToken } from '@open-mercato/shared/lib/boolean'
|
|
6
6
|
import { auditSchedulerModuleQueueRows } from './lib/safeQueueTargets'
|
|
7
|
+
import { createQueue } from '@open-mercato/queue'
|
|
8
|
+
import type { Queue } from '@open-mercato/queue'
|
|
9
|
+
import { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'
|
|
10
|
+
import type { ExecuteSchedulePayload } from './workers/execute-schedule.worker.js'
|
|
7
11
|
|
|
8
12
|
const writeLine = (text = '') => {
|
|
9
13
|
process.stdout.write(`${text}\n`)
|
|
@@ -116,16 +120,17 @@ const runCommand: ModuleCli = {
|
|
|
116
120
|
const scheduleId = rest[0]
|
|
117
121
|
if (!scheduleId) {
|
|
118
122
|
writeErrorLine('Usage: mercato scheduler run <schedule-id>')
|
|
123
|
+
process.exitCode = 1
|
|
119
124
|
return
|
|
120
125
|
}
|
|
121
126
|
|
|
122
127
|
const { resolve } = await createRequestContainer()
|
|
123
128
|
const em = resolve('em') as EntityManager
|
|
124
|
-
const queueService = resolve('queueService') as { getQueue(name: string): { add(name: string, data: unknown): Promise<unknown> } }
|
|
125
129
|
|
|
126
130
|
const job = await em.findOne(ScheduledJob, { id: scheduleId, deletedAt: null })
|
|
127
131
|
if (!job) {
|
|
128
132
|
writeErrorLine(`Schedule not found: ${scheduleId}`)
|
|
133
|
+
process.exitCode = 1
|
|
129
134
|
return
|
|
130
135
|
}
|
|
131
136
|
|
|
@@ -136,17 +141,38 @@ const runCommand: ModuleCli = {
|
|
|
136
141
|
writeLine(` Target: ${job.targetType === 'queue' ? job.targetQueue : job.targetCommand}`)
|
|
137
142
|
writeLine('')
|
|
138
143
|
|
|
144
|
+
// Mirrors scheduler.jobs.trigger: under the local strategy nothing consumes scheduler-execution.
|
|
145
|
+
if ((process.env.QUEUE_STRATEGY || 'local') !== 'async') {
|
|
146
|
+
throw new Error(
|
|
147
|
+
'Manual trigger requires QUEUE_STRATEGY=async (with the local strategy due schedules run via `mercato scheduler start`)',
|
|
148
|
+
)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const payload: ExecuteSchedulePayload = {
|
|
152
|
+
scheduleId: job.id,
|
|
153
|
+
tenantId: job.tenantId,
|
|
154
|
+
organizationId: job.organizationId,
|
|
155
|
+
scopeType: job.scopeType,
|
|
156
|
+
triggerType: 'manual',
|
|
157
|
+
triggeredByUserId: null,
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
let executionQueue: Queue<ExecuteSchedulePayload> | null = null
|
|
139
161
|
try {
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
162
|
+
executionQueue = createQueue<ExecuteSchedulePayload>('scheduler-execution', 'async', {
|
|
163
|
+
connection: { url: getRedisUrlOrThrow('QUEUE') },
|
|
164
|
+
})
|
|
165
|
+
const queueJobId = await executionQueue.enqueue(payload)
|
|
143
166
|
|
|
144
|
-
writeLine(
|
|
167
|
+
writeLine(`✓ Job successfully triggered via scheduler-execution queue (job ${queueJobId})`)
|
|
145
168
|
writeLine(` The worker will pick it up and enqueue to: ${job.targetType === 'queue' ? job.targetQueue : job.targetCommand}`)
|
|
146
169
|
writeLine('✓ Manual trigger completed\n')
|
|
147
170
|
} catch (error: unknown) {
|
|
148
|
-
|
|
149
|
-
|
|
171
|
+
throw new Error(`Failed to trigger job: ${error instanceof Error ? error.message : String(error)}`)
|
|
172
|
+
} finally {
|
|
173
|
+
await executionQueue?.close().catch((closeError: unknown) => {
|
|
174
|
+
writeErrorLine(`Failed to close scheduler execution queue: ${closeError instanceof Error ? closeError.message : String(closeError)}`)
|
|
175
|
+
})
|
|
150
176
|
}
|
|
151
177
|
},
|
|
152
178
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { describe, it, expect, beforeAll, afterAll } from '@jest/globals'
|
|
2
|
+
import { createHash } from 'node:crypto'
|
|
2
3
|
import {
|
|
3
4
|
scheduleCreateSchema,
|
|
4
5
|
scheduleUpdateSchema,
|
|
@@ -781,3 +782,31 @@ describe('scheduleRunsQuerySchema', () => {
|
|
|
781
782
|
expect(result.order).toBe('asc')
|
|
782
783
|
})
|
|
783
784
|
})
|
|
785
|
+
|
|
786
|
+
describe('schedule id format', () => {
|
|
787
|
+
const hex = createHash('sha256').update('payment_gateways:session-initialization-prune').digest('hex')
|
|
788
|
+
const moduleScheduleId = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`
|
|
789
|
+
const nonRfcScheduleId = 'a1b2c3d4-e5f6-a7b8-c9d0-e1f2a3b4c5d6'
|
|
790
|
+
|
|
791
|
+
it.each([moduleScheduleId, nonRfcScheduleId])(
|
|
792
|
+
'accepts a UUID-formatted id without RFC 4122 version/variant bits (%s)',
|
|
793
|
+
(id) => {
|
|
794
|
+
expect(scheduleTriggerSchema.parse({ id }).id).toBe(id)
|
|
795
|
+
expect(scheduleDeleteSchema.parse({ id }).id).toBe(id)
|
|
796
|
+
expect(scheduleUpdateSchema.parse({ id, name: 'Renamed' }).id).toBe(id)
|
|
797
|
+
expect(scheduleListQuerySchema.parse({ id }).id).toBe(id)
|
|
798
|
+
expect(scheduleRunsQuerySchema.parse({ scheduledJobId: id }).scheduledJobId).toBe(id)
|
|
799
|
+
}
|
|
800
|
+
)
|
|
801
|
+
|
|
802
|
+
it.each(['not-a-uuid', 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6', 'g1b2c3d4-e5f6-a7b8-c9d0-e1f2a3b4c5d6'])(
|
|
803
|
+
'rejects a non-UUID string (%s)',
|
|
804
|
+
(id) => {
|
|
805
|
+
expect(scheduleTriggerSchema.safeParse({ id }).success).toBe(false)
|
|
806
|
+
expect(scheduleDeleteSchema.safeParse({ id }).success).toBe(false)
|
|
807
|
+
expect(scheduleUpdateSchema.safeParse({ id }).success).toBe(false)
|
|
808
|
+
expect(scheduleListQuerySchema.safeParse({ id }).success).toBe(false)
|
|
809
|
+
expect(scheduleRunsQuerySchema.safeParse({ scheduledJobId: id }).success).toBe(false)
|
|
810
|
+
}
|
|
811
|
+
)
|
|
812
|
+
})
|
|
@@ -157,7 +157,7 @@ export const scheduleCreateSchema = scheduleBaseSchema
|
|
|
157
157
|
* Update schedule schema (all fields optional except id)
|
|
158
158
|
*/
|
|
159
159
|
export const scheduleUpdateSchema = z.object({
|
|
160
|
-
id: z.
|
|
160
|
+
id: z.guid(),
|
|
161
161
|
name: z.string().min(1).max(200).optional(),
|
|
162
162
|
description: z.string().max(500).optional().nullable(),
|
|
163
163
|
|
|
@@ -254,7 +254,7 @@ export const scheduleUpdateSchema = z.object({
|
|
|
254
254
|
* Delete schedule schema
|
|
255
255
|
*/
|
|
256
256
|
export const scheduleDeleteSchema = z.object({
|
|
257
|
-
id: z.
|
|
257
|
+
id: z.guid(),
|
|
258
258
|
})
|
|
259
259
|
|
|
260
260
|
/**
|
|
@@ -263,7 +263,7 @@ export const scheduleDeleteSchema = z.object({
|
|
|
263
263
|
export const scheduleListQuerySchema = z.object({
|
|
264
264
|
page: z.coerce.number().int().min(1).default(1),
|
|
265
265
|
pageSize: z.coerce.number().int().min(1).max(100).default(20),
|
|
266
|
-
id: z.
|
|
266
|
+
id: z.guid().optional(),
|
|
267
267
|
search: z.string().optional(),
|
|
268
268
|
scopeType: z.enum(['system', 'organization', 'tenant']).optional(),
|
|
269
269
|
isEnabled: z.string().optional().transform((val) => {
|
|
@@ -280,7 +280,7 @@ export const scheduleListQuerySchema = z.object({
|
|
|
280
280
|
* Trigger schedule schema (manual execution)
|
|
281
281
|
*/
|
|
282
282
|
export const scheduleTriggerSchema = z.object({
|
|
283
|
-
id: z.
|
|
283
|
+
id: z.guid(),
|
|
284
284
|
})
|
|
285
285
|
|
|
286
286
|
/**
|
|
@@ -289,7 +289,7 @@ export const scheduleTriggerSchema = z.object({
|
|
|
289
289
|
export const scheduleRunsQuerySchema = z.object({
|
|
290
290
|
page: z.coerce.number().int().min(1).default(1),
|
|
291
291
|
pageSize: z.coerce.number().int().min(1).max(100).default(20),
|
|
292
|
-
scheduledJobId: z.
|
|
292
|
+
scheduledJobId: z.guid().optional(),
|
|
293
293
|
status: z.enum(['running', 'completed', 'failed', 'skipped']).optional(),
|
|
294
294
|
triggerType: z.enum(['scheduled', 'manual']).optional(),
|
|
295
295
|
fromDate: z.string().datetime().optional(),
|