@open-mercato/scheduler 0.9.1-develop.7574.1.837288eec1 → 0.9.1-develop.7575.1.8480826a9b
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 +6 -28
- 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/workers/execute-schedule.worker.js +0 -20
- package/dist/modules/scheduler/workers/execute-schedule.worker.js.map +2 -2
- package/package.json +5 -5
- 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 +0 -15
- package/src/modules/scheduler/cli.ts +7 -33
- package/src/modules/scheduler/data/__tests__/validators.test.ts +0 -29
- package/src/modules/scheduler/data/validators.ts +5 -5
- package/src/modules/scheduler/workers/__tests__/execute-schedule.worker.test.ts +0 -4
- package/src/modules/scheduler/workers/execute-schedule.worker.ts +0 -35
- package/dist/modules/scheduler/lib/bullmqNextRun.js +0 -61
- package/dist/modules/scheduler/lib/bullmqNextRun.js.map +0 -7
- package/dist/modules/scheduler/lib/nextRunSync.js +0 -80
- package/dist/modules/scheduler/lib/nextRunSync.js.map +0 -7
- package/src/modules/scheduler/__tests__/cli.run.test.ts +0 -135
- package/src/modules/scheduler/lib/__tests__/bullmqNextRun.test.ts +0 -200
- package/src/modules/scheduler/lib/__tests__/nextRunSync.test.ts +0 -222
- package/src/modules/scheduler/lib/bullmqNextRun.ts +0 -112
- package/src/modules/scheduler/lib/nextRunSync.ts +0 -131
- package/src/modules/scheduler/workers/__tests__/execute-schedule.next-run.test.ts +0 -468
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
[build:scheduler] found
|
|
1
|
+
[build:scheduler] found 62 entry points
|
|
2
2
|
[build:scheduler] built successfully
|
|
@@ -107,7 +107,7 @@ const executionsQuerySchema = z.object({
|
|
|
107
107
|
});
|
|
108
108
|
const executionItemSchema = z.object({
|
|
109
109
|
id: z.string(),
|
|
110
|
-
scheduleId: z.
|
|
110
|
+
scheduleId: z.string().uuid(),
|
|
111
111
|
startedAt: z.string(),
|
|
112
112
|
finishedAt: z.string().nullable(),
|
|
113
113
|
status: z.enum(["running", "completed", "failed", "waiting"]),
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/scheduler/api/jobs/%5Bid%5D/executions/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextRequest, NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/core'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { ScheduledJob } from '../../../../data/entities.js'\nimport { resolveScheduleAccess } from '../../../../lib/scheduleAccess.js'\nimport { getRedisUrlOrThrow, parseRedisUrl } from '@open-mercato/shared/lib/redis/connection'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'executions' })\n\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['scheduler.jobs.view'],\n}\n\n/**\n * GET /api/scheduler/jobs/[id]/executions\n * Fetch execution history for a schedule from BullMQ\n * \n * Returns jobs from the scheduler-execution queue filtered by scheduleId.\n * This replaces the old /api/scheduler/runs endpoint that used the database table.\n */\nexport async function GET(\n req: NextRequest,\n { params }: { params: { id: string } }\n) {\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub) {\n return NextResponse.json({ error: translate('scheduler.error.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve<EntityManager>('em')\n\n const scheduleId = params.id\n\n try {\n // Load by id alone, then apply isolation to the loaded row. Folding the actor's\n // tenant/org into the lookup would make every system-scoped schedule unmatchable.\n const schedule = await em.findOne(ScheduledJob, { id: scheduleId, deletedAt: null })\n\n if (!schedule) {\n return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })\n }\n\n const access = resolveScheduleAccess(schedule, auth)\n if (access === 'not_found') {\n return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })\n }\n if (access === 'forbidden') {\n return NextResponse.json({ error: translate('scheduler.error.access_denied', 'Access denied') }, { status: 403 })\n }\n\n // Check if using async strategy\n const queueStrategy = process.env.QUEUE_STRATEGY || 'local'\n if (queueStrategy !== 'async') {\n return NextResponse.json({\n error: translate('scheduler.error.async_strategy_required', 'Execution history requires QUEUE_STRATEGY=async'),\n message: translate('scheduler.error.async_strategy_hint', 'Please set QUEUE_STRATEGY=async to view execution history'),\n items: [],\n }, { status: 400 })\n }\n\n // Fetch jobs from BullMQ scheduler-execution queue\n const { Queue } = await import('bullmq')\n const queue = new Queue('scheduler-execution', {\n connection: parseRedisUrl(getRedisUrlOrThrow('QUEUE')),\n })\n\n try {\n // Validate query params with Zod schema\n const queryResult = executionsQuerySchema.safeParse({\n pageSize: req.nextUrl.searchParams.get('pageSize') ?? undefined,\n })\n const limit = queryResult.success ? queryResult.data.pageSize : 20\n\n const [completed, failed, active, waiting, delayed] = await Promise.all([\n queue.getCompleted(0, limit - 1),\n queue.getFailed(0, limit - 1),\n queue.getActive(0, limit - 1),\n queue.getWaiting(0, limit - 1),\n queue.getDelayed(0, limit - 1),\n ])\n\n // Combine all jobs and filter by scheduleId\n const allJobs = [...completed, ...failed, ...active, ...waiting, ...delayed]\n type BullJobData = { payload?: { scheduleId?: string; triggerType?: string; triggeredByUserId?: string }; scheduleId?: string; triggerType?: string; triggeredByUserId?: string }\n\n const filteredJobs = allJobs\n .filter(job => {\n const data = job.data as BullJobData | undefined\n return data?.payload?.scheduleId === scheduleId || data?.scheduleId === scheduleId\n })\n .slice(0, limit)\n\n // Get state for each job (parallel)\n const jobsWithState = await Promise.all(\n filteredJobs.map(async (job) => {\n const state = await job.getState()\n const data = job.data as BullJobData | undefined\n \n return {\n id: job.id,\n scheduleId: data?.payload?.scheduleId || data?.scheduleId,\n startedAt: job.processedOn ? new Date(job.processedOn).toISOString() : new Date(job.timestamp).toISOString(),\n finishedAt: job.finishedOn ? new Date(job.finishedOn).toISOString() : null,\n status: state === 'completed' ? 'completed' : state === 'failed' ? 'failed' : state === 'active' ? 'running' : 'waiting',\n triggerType: data?.payload?.triggerType || data?.triggerType || 'scheduled',\n triggeredByUserId: data?.payload?.triggeredByUserId || data?.triggeredByUserId || null,\n errorMessage: job.failedReason || null,\n errorStack: job.stacktrace ? job.stacktrace.join('\\n') : null,\n durationMs: (job.finishedOn && job.processedOn) ? (job.finishedOn - job.processedOn) : null,\n queueJobId: job.id,\n queueName: 'scheduler-execution',\n attemptsMade: job.attemptsMade,\n result: job.returnvalue,\n }\n })\n )\n\n // Sort by startedAt descending (most recent first)\n jobsWithState.sort((a, b) => new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime())\n\n return NextResponse.json({\n items: jobsWithState,\n total: jobsWithState.length,\n page: 1,\n pageSize: limit,\n })\n } finally {\n await queue.close()\n }\n\n } catch (error: unknown) {\n logger.error('Error fetching execution history', { err: error })\n return NextResponse.json(\n { error: error instanceof Error ? error.message : translate('scheduler.error.fetch_executions_failed', 'Failed to fetch execution history') },\n { status: 500 }\n )\n }\n}\n\n// Query schemas\nconst executionsQuerySchema = z.object({\n pageSize: z.coerce.number().int().min(1).max(100).default(20),\n})\n\n// Response schemas\nconst executionItemSchema = z.object({\n id: z.string(),\n scheduleId: z.
|
|
5
|
-
"mappings": "AAAA,SAAsB,oBAAoB;AAC1C,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAGvC,SAAS,oBAAoB;AAC7B,SAAS,6BAA6B;AACtC,SAAS,oBAAoB,qBAAqB;AAClD,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,aAAa,CAAC;AAGnE,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,qBAAqB;AACzC;AASA,eAAsB,IACpB,KACA,EAAE,OAAO,GACT;AACA,QAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,MAAM,KAAK;AACd,WAAO,aAAa,KAAK,EAAE,OAAO,UAAU,gCAAgC,cAAc,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAChH;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,KAAK,UAAU,QAAuB,IAAI;AAEhD,QAAM,aAAa,OAAO;AAE1B,MAAI;AAGF,UAAM,WAAW,MAAM,GAAG,QAAQ,cAAc,EAAE,IAAI,YAAY,WAAW,KAAK,CAAC;AAEnF,QAAI,CAAC,UAAU;AACb,aAAO,aAAa,KAAK,EAAE,OAAO,UAAU,6BAA6B,oBAAoB,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACnH;AAEA,UAAM,SAAS,sBAAsB,UAAU,IAAI;AACnD,QAAI,WAAW,aAAa;AAC1B,aAAO,aAAa,KAAK,EAAE,OAAO,UAAU,6BAA6B,oBAAoB,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACnH;AACA,QAAI,WAAW,aAAa;AAC1B,aAA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D,WAAO,aAAa;AAAA,MAClB,EAAE,OAAO,iBAAiB,QAAQ,MAAM,UAAU,UAAU,2CAA2C,mCAAmC,EAAE;AAAA,MAC5I,EAAE,QAAQ,IAAI;AAAA,IAChB;AAAA,EACF;AACF;AAGA,MAAM,wBAAwB,EAAE,OAAO;AAAA,EACrC,UAAU,EAAE,OAAO,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,QAAQ,EAAE;AAC9D,CAAC;AAGD,MAAM,sBAAsB,EAAE,OAAO;AAAA,EACnC,IAAI,EAAE,OAAO;AAAA,EACb,YAAY,EAAE,KAAK;AAAA,
|
|
4
|
+
"sourcesContent": ["import { NextRequest, NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/core'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { ScheduledJob } from '../../../../data/entities.js'\nimport { resolveScheduleAccess } from '../../../../lib/scheduleAccess.js'\nimport { getRedisUrlOrThrow, parseRedisUrl } from '@open-mercato/shared/lib/redis/connection'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'executions' })\n\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['scheduler.jobs.view'],\n}\n\n/**\n * GET /api/scheduler/jobs/[id]/executions\n * Fetch execution history for a schedule from BullMQ\n * \n * Returns jobs from the scheduler-execution queue filtered by scheduleId.\n * This replaces the old /api/scheduler/runs endpoint that used the database table.\n */\nexport async function GET(\n req: NextRequest,\n { params }: { params: { id: string } }\n) {\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub) {\n return NextResponse.json({ error: translate('scheduler.error.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve<EntityManager>('em')\n\n const scheduleId = params.id\n\n try {\n // Load by id alone, then apply isolation to the loaded row. Folding the actor's\n // tenant/org into the lookup would make every system-scoped schedule unmatchable.\n const schedule = await em.findOne(ScheduledJob, { id: scheduleId, deletedAt: null })\n\n if (!schedule) {\n return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })\n }\n\n const access = resolveScheduleAccess(schedule, auth)\n if (access === 'not_found') {\n return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })\n }\n if (access === 'forbidden') {\n return NextResponse.json({ error: translate('scheduler.error.access_denied', 'Access denied') }, { status: 403 })\n }\n\n // Check if using async strategy\n const queueStrategy = process.env.QUEUE_STRATEGY || 'local'\n if (queueStrategy !== 'async') {\n return NextResponse.json({\n error: translate('scheduler.error.async_strategy_required', 'Execution history requires QUEUE_STRATEGY=async'),\n message: translate('scheduler.error.async_strategy_hint', 'Please set QUEUE_STRATEGY=async to view execution history'),\n items: [],\n }, { status: 400 })\n }\n\n // Fetch jobs from BullMQ scheduler-execution queue\n const { Queue } = await import('bullmq')\n const queue = new Queue('scheduler-execution', {\n connection: parseRedisUrl(getRedisUrlOrThrow('QUEUE')),\n })\n\n try {\n // Validate query params with Zod schema\n const queryResult = executionsQuerySchema.safeParse({\n pageSize: req.nextUrl.searchParams.get('pageSize') ?? undefined,\n })\n const limit = queryResult.success ? queryResult.data.pageSize : 20\n\n const [completed, failed, active, waiting, delayed] = await Promise.all([\n queue.getCompleted(0, limit - 1),\n queue.getFailed(0, limit - 1),\n queue.getActive(0, limit - 1),\n queue.getWaiting(0, limit - 1),\n queue.getDelayed(0, limit - 1),\n ])\n\n // Combine all jobs and filter by scheduleId\n const allJobs = [...completed, ...failed, ...active, ...waiting, ...delayed]\n type BullJobData = { payload?: { scheduleId?: string; triggerType?: string; triggeredByUserId?: string }; scheduleId?: string; triggerType?: string; triggeredByUserId?: string }\n\n const filteredJobs = allJobs\n .filter(job => {\n const data = job.data as BullJobData | undefined\n return data?.payload?.scheduleId === scheduleId || data?.scheduleId === scheduleId\n })\n .slice(0, limit)\n\n // Get state for each job (parallel)\n const jobsWithState = await Promise.all(\n filteredJobs.map(async (job) => {\n const state = await job.getState()\n const data = job.data as BullJobData | undefined\n \n return {\n id: job.id,\n scheduleId: data?.payload?.scheduleId || data?.scheduleId,\n startedAt: job.processedOn ? new Date(job.processedOn).toISOString() : new Date(job.timestamp).toISOString(),\n finishedAt: job.finishedOn ? new Date(job.finishedOn).toISOString() : null,\n status: state === 'completed' ? 'completed' : state === 'failed' ? 'failed' : state === 'active' ? 'running' : 'waiting',\n triggerType: data?.payload?.triggerType || data?.triggerType || 'scheduled',\n triggeredByUserId: data?.payload?.triggeredByUserId || data?.triggeredByUserId || null,\n errorMessage: job.failedReason || null,\n errorStack: job.stacktrace ? job.stacktrace.join('\\n') : null,\n durationMs: (job.finishedOn && job.processedOn) ? (job.finishedOn - job.processedOn) : null,\n queueJobId: job.id,\n queueName: 'scheduler-execution',\n attemptsMade: job.attemptsMade,\n result: job.returnvalue,\n }\n })\n )\n\n // Sort by startedAt descending (most recent first)\n jobsWithState.sort((a, b) => new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime())\n\n return NextResponse.json({\n items: jobsWithState,\n total: jobsWithState.length,\n page: 1,\n pageSize: limit,\n })\n } finally {\n await queue.close()\n }\n\n } catch (error: unknown) {\n logger.error('Error fetching execution history', { err: error })\n return NextResponse.json(\n { error: error instanceof Error ? error.message : translate('scheduler.error.fetch_executions_failed', 'Failed to fetch execution history') },\n { status: 500 }\n )\n }\n}\n\n// Query schemas\nconst executionsQuerySchema = z.object({\n pageSize: z.coerce.number().int().min(1).max(100).default(20),\n})\n\n// Response schemas\nconst executionItemSchema = z.object({\n id: z.string(),\n scheduleId: z.string().uuid(),\n startedAt: z.string(),\n finishedAt: z.string().nullable(),\n status: z.enum(['running', 'completed', 'failed', 'waiting']),\n triggerType: z.enum(['scheduled', 'manual']),\n triggeredByUserId: z.string().uuid().nullable(),\n errorMessage: z.string().nullable(),\n errorStack: z.string().nullable(),\n durationMs: z.number().nullable(),\n queueJobId: z.string(),\n queueName: z.string(),\n attemptsMade: z.number(),\n result: z.unknown().nullable(),\n})\n\nconst executionsResponseSchema = z.object({\n items: z.array(executionItemSchema),\n total: z.number(),\n page: z.number(),\n pageSize: z.number(),\n})\n\nconst errorResponseSchema = z.object({\n error: z.string(),\n message: z.string().optional(),\n items: z.array(z.any()).optional(),\n})\n\n// OpenAPI specification\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Scheduler',\n summary: 'Get execution history',\n description: 'Fetches recent execution history for a scheduled job from BullMQ.',\n methods: {\n GET: {\n operationId: 'getScheduleExecutions',\n summary: 'Get execution history for a schedule',\n description: 'Fetch recent executions from BullMQ for a scheduled job. Requires QUEUE_STRATEGY=async.',\n query: executionsQuerySchema,\n responses: [\n {\n status: 200,\n description: 'Execution history',\n schema: executionsResponseSchema,\n },\n ],\n errors: [\n { status: 400, description: 'Local strategy not supported', schema: errorResponseSchema },\n { status: 401, description: 'Unauthorized', schema: errorResponseSchema },\n { status: 403, description: 'Access denied', schema: errorResponseSchema },\n { status: 404, description: 'Schedule not found', schema: errorResponseSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAsB,oBAAoB;AAC1C,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAGvC,SAAS,oBAAoB;AAC7B,SAAS,6BAA6B;AACtC,SAAS,oBAAoB,qBAAqB;AAClD,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,aAAa,CAAC;AAGnE,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,qBAAqB;AACzC;AASA,eAAsB,IACpB,KACA,EAAE,OAAO,GACT;AACA,QAAM,EAAE,UAAU,IAAI,MAAM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BAAoB;AAAA,QACzE,EAAE,QAAQ,KAAK,aAAa,sBAAsB,QAAQ,oBAAoB;AAAA,MAChF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -155,7 +155,7 @@ const crud = makeCrudRoute({
|
|
|
155
155
|
});
|
|
156
156
|
const { GET, POST, PUT, DELETE } = crud;
|
|
157
157
|
const scheduledJobListItemSchema = z.object({
|
|
158
|
-
id: z.
|
|
158
|
+
id: z.string().uuid(),
|
|
159
159
|
name: z.string(),
|
|
160
160
|
description: z.string().nullable(),
|
|
161
161
|
scopeType: z.enum(["system", "organization", "tenant"]),
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/scheduler/api/jobs/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { z } from 'zod'\nimport { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'\nimport { resolveCrudRecordId } from '@open-mercato/shared/lib/api/scoped'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { ScheduledJob } from '../../data/entities.js'\nimport {\n scheduleCreateSchema,\n scheduleUpdateSchema,\n scheduleDeleteSchema,\n scheduleListQuerySchema,\n} from '../../data/validators.js'\nimport { buildSchedulerJobsFilters } from './buildFilters.js'\nimport {\n createSchedulerCrudOpenApi,\n createPagedListResponseSchema,\n defaultOkResponseSchema,\n} from '../openapi.js'\n\nconst rawBodySchema = z.object({}).passthrough()\n\nconst routeMetadata = {\n GET: { requireAuth: true, requireFeatures: ['scheduler.jobs.view'] },\n POST: { requireAuth: true, requireFeatures: ['scheduler.jobs.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['scheduler.jobs.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['scheduler.jobs.manage'] },\n}\n\nexport const metadata = routeMetadata\n\nconst crud = makeCrudRoute({\n metadata: routeMetadata,\n orm: {\n entity: ScheduledJob,\n idField: 'id',\n tenantField: 'tenantId',\n softDeleteField: 'deletedAt',\n },\n indexer: { entityType: 'scheduler:scheduled_job' },\n list: {\n entityId: 'scheduler:scheduled_job',\n schema: scheduleListQuerySchema,\n fields: [\n 'id',\n 'name',\n 'description',\n 'scope_type',\n 'organization_id',\n 'tenant_id',\n 'schedule_type',\n 'schedule_value',\n 'timezone',\n 'target_type',\n 'target_queue',\n 'target_command',\n 'target_payload',\n 'require_feature',\n 'is_enabled',\n 'last_run_at',\n 'next_run_at',\n 'source_type',\n 'source_module',\n 'created_at',\n 'updated_at',\n ],\n sortFieldMap: {\n name: 'name',\n nextRunAt: 'next_run_at',\n lastRunAt: 'last_run_at',\n createdAt: 'created_at',\n },\n omitAutomaticTenantOrgScope: true,\n transformItem: (item: Record<string, unknown>) => {\n if (!item) return item\n return {\n id: item.id,\n name: item.name,\n description: item.description,\n scopeType: item.scope_type,\n organizationId: item.organization_id,\n tenantId: item.tenant_id,\n scheduleType: item.schedule_type,\n scheduleValue: item.schedule_value,\n timezone: item.timezone,\n targetType: item.target_type,\n targetQueue: item.target_queue,\n targetCommand: item.target_command,\n targetPayload: item.target_payload,\n requireFeature: item.require_feature,\n isEnabled: item.is_enabled,\n lastRunAt: item.last_run_at,\n nextRunAt: item.next_run_at,\n sourceType: item.source_type,\n sourceModule: item.source_module,\n createdAt: item.created_at,\n updatedAt: item.updated_at,\n }\n },\n buildFilters: buildSchedulerJobsFilters,\n },\n actions: {\n create: {\n commandId: 'scheduler.jobs.create',\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n // Auto-populate organizationId and tenantId based on scopeType\n const scopeType = raw.scopeType\n let organizationId = raw.organizationId\n let tenantId = raw.tenantId\n \n if (scopeType === 'system') {\n // System scope requires super-admin. Use the immutable `isSuperAdmin`\n // flag (derived from RoleAcl/UserAcl) \u2014 never compare role names, which\n // are tenant-mutable and spoofable.\n if (ctx.auth?.isSuperAdmin !== true) {\n throw new CrudHttpError(403, { error: 'System-scoped schedules require superadmin privileges' })\n }\n // System scope: no org/tenant\n organizationId = null\n tenantId = null\n } else if (scopeType === 'organization') {\n // Organization scope: use auth context (orgId and tenantId)\n organizationId = ctx.auth?.orgId ?? null\n tenantId = ctx.auth?.tenantId ?? null\n } else if (scopeType === 'tenant') {\n // Tenant scope: use auth context tenantId only\n organizationId = null\n tenantId = ctx.auth?.tenantId ?? null\n }\n \n const parsed = scheduleCreateSchema.parse({\n ...raw,\n organizationId,\n tenantId,\n })\n return parsed\n },\n response: ({ result }) => ({\n id: result?.id ?? null,\n }),\n status: 201,\n },\n update: {\n commandId: 'scheduler.jobs.update',\n schema: rawBodySchema,\n mapInput: async ({ raw }) => {\n const parsed = scheduleUpdateSchema.parse(raw)\n return parsed\n },\n response: () => ({ ok: true }),\n },\n delete: {\n commandId: 'scheduler.jobs.delete',\n schema: rawBodySchema,\n mapInput: async ({ parsed, ctx }) => {\n const { translate } = await resolveTranslations()\n const id = resolveCrudRecordId(parsed, ctx, translate)\n if (!id) {\n throw new CrudHttpError(400, { \n error: translate('scheduler.errors.id_required', 'Schedule id is required') \n })\n }\n return { id }\n },\n response: () => ({ ok: true }),\n },\n },\n})\n\nexport const { GET, POST, PUT, DELETE } = crud\n\n// Response schemas\nconst scheduledJobListItemSchema = z.object({\n id: z.
|
|
5
|
-
"mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AACpC,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iCAAiC;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,gBAAgB,EAAE,OAAO,CAAC,CAAC,EAAE,YAAY;AAE/C,MAAM,gBAAgB;AAAA,EACpB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC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;AAAA,MACN,WAAW;AAAA,MACX,QAAQ;AAAA,MACR,UAAU,OAAO,EAAE,QAAQ,IAAI,MAAM;AACnC,cAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,cAAM,KAAK,oBAAoB,QAAQ,KAAK,SAAS;AACrD,YAAI,CAAC,IAAI;AACP,gBAAM,IAAI,cAAc,KAAK;AAAA,YAC3B,OAAO,UAAU,gCAAgC,yBAAyB;AAAA,UAC5E,CAAC;AAAA,QACH;AACA,eAAO,EAAE,GAAG;AAAA,MACd;AAAA,MACA,UAAU,OAAO,EAAE,IAAI,KAAK;AAAA,IAC9B;AAAA,EACF;AACF,CAAC;AAEM,MAAM,EAAE,KAAK,MAAM,KAAK,OAAO,IAAI;AAG1C,MAAM,6BAA6B,EAAE,OAAO;AAAA,EAC1C,IAAI,EAAE,KAAK;AAAA,
|
|
4
|
+
"sourcesContent": ["import { z } from 'zod'\nimport { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'\nimport { resolveCrudRecordId } from '@open-mercato/shared/lib/api/scoped'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { ScheduledJob } from '../../data/entities.js'\nimport {\n scheduleCreateSchema,\n scheduleUpdateSchema,\n scheduleDeleteSchema,\n scheduleListQuerySchema,\n} from '../../data/validators.js'\nimport { buildSchedulerJobsFilters } from './buildFilters.js'\nimport {\n createSchedulerCrudOpenApi,\n createPagedListResponseSchema,\n defaultOkResponseSchema,\n} from '../openapi.js'\n\nconst rawBodySchema = z.object({}).passthrough()\n\nconst routeMetadata = {\n GET: { requireAuth: true, requireFeatures: ['scheduler.jobs.view'] },\n POST: { requireAuth: true, requireFeatures: ['scheduler.jobs.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['scheduler.jobs.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['scheduler.jobs.manage'] },\n}\n\nexport const metadata = routeMetadata\n\nconst crud = makeCrudRoute({\n metadata: routeMetadata,\n orm: {\n entity: ScheduledJob,\n idField: 'id',\n tenantField: 'tenantId',\n softDeleteField: 'deletedAt',\n },\n indexer: { entityType: 'scheduler:scheduled_job' },\n list: {\n entityId: 'scheduler:scheduled_job',\n schema: scheduleListQuerySchema,\n fields: [\n 'id',\n 'name',\n 'description',\n 'scope_type',\n 'organization_id',\n 'tenant_id',\n 'schedule_type',\n 'schedule_value',\n 'timezone',\n 'target_type',\n 'target_queue',\n 'target_command',\n 'target_payload',\n 'require_feature',\n 'is_enabled',\n 'last_run_at',\n 'next_run_at',\n 'source_type',\n 'source_module',\n 'created_at',\n 'updated_at',\n ],\n sortFieldMap: {\n name: 'name',\n nextRunAt: 'next_run_at',\n lastRunAt: 'last_run_at',\n createdAt: 'created_at',\n },\n omitAutomaticTenantOrgScope: true,\n transformItem: (item: Record<string, unknown>) => {\n if (!item) return item\n return {\n id: item.id,\n name: item.name,\n description: item.description,\n scopeType: item.scope_type,\n organizationId: item.organization_id,\n tenantId: item.tenant_id,\n scheduleType: item.schedule_type,\n scheduleValue: item.schedule_value,\n timezone: item.timezone,\n targetType: item.target_type,\n targetQueue: item.target_queue,\n targetCommand: item.target_command,\n targetPayload: item.target_payload,\n requireFeature: item.require_feature,\n isEnabled: item.is_enabled,\n lastRunAt: item.last_run_at,\n nextRunAt: item.next_run_at,\n sourceType: item.source_type,\n sourceModule: item.source_module,\n createdAt: item.created_at,\n updatedAt: item.updated_at,\n }\n },\n buildFilters: buildSchedulerJobsFilters,\n },\n actions: {\n create: {\n commandId: 'scheduler.jobs.create',\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n // Auto-populate organizationId and tenantId based on scopeType\n const scopeType = raw.scopeType\n let organizationId = raw.organizationId\n let tenantId = raw.tenantId\n \n if (scopeType === 'system') {\n // System scope requires super-admin. Use the immutable `isSuperAdmin`\n // flag (derived from RoleAcl/UserAcl) \u2014 never compare role names, which\n // are tenant-mutable and spoofable.\n if (ctx.auth?.isSuperAdmin !== true) {\n throw new CrudHttpError(403, { error: 'System-scoped schedules require superadmin privileges' })\n }\n // System scope: no org/tenant\n organizationId = null\n tenantId = null\n } else if (scopeType === 'organization') {\n // Organization scope: use auth context (orgId and tenantId)\n organizationId = ctx.auth?.orgId ?? null\n tenantId = ctx.auth?.tenantId ?? null\n } else if (scopeType === 'tenant') {\n // Tenant scope: use auth context tenantId only\n organizationId = null\n tenantId = ctx.auth?.tenantId ?? null\n }\n \n const parsed = scheduleCreateSchema.parse({\n ...raw,\n organizationId,\n tenantId,\n })\n return parsed\n },\n response: ({ result }) => ({\n id: result?.id ?? null,\n }),\n status: 201,\n },\n update: {\n commandId: 'scheduler.jobs.update',\n schema: rawBodySchema,\n mapInput: async ({ raw }) => {\n const parsed = scheduleUpdateSchema.parse(raw)\n return parsed\n },\n response: () => ({ ok: true }),\n },\n delete: {\n commandId: 'scheduler.jobs.delete',\n schema: rawBodySchema,\n mapInput: async ({ parsed, ctx }) => {\n const { translate } = await resolveTranslations()\n const id = resolveCrudRecordId(parsed, ctx, translate)\n if (!id) {\n throw new CrudHttpError(400, { \n error: translate('scheduler.errors.id_required', 'Schedule id is required') \n })\n }\n return { id }\n },\n response: () => ({ ok: true }),\n },\n },\n})\n\nexport const { GET, POST, PUT, DELETE } = crud\n\n// Response schemas\nconst scheduledJobListItemSchema = z.object({\n id: z.string().uuid(),\n name: z.string(),\n description: z.string().nullable(),\n scopeType: z.enum(['system', 'organization', 'tenant']),\n organizationId: z.string().uuid().nullable(),\n tenantId: z.string().uuid().nullable(),\n scheduleType: z.enum(['cron', 'interval']),\n scheduleValue: z.string(),\n timezone: z.string(),\n targetType: z.enum(['queue', 'command']),\n targetQueue: z.string().nullable(),\n targetCommand: z.string().nullable(),\n targetPayload: z.record(z.string(), z.unknown()).nullable(),\n requireFeature: z.string().nullable(),\n isEnabled: z.boolean(),\n lastRunAt: z.string().nullable(),\n nextRunAt: z.string().nullable(),\n sourceType: z.enum(['user', 'module']),\n sourceModule: z.string().nullable(),\n createdAt: z.string(),\n updatedAt: z.string(),\n})\n\n// OpenAPI specification\nexport const openApi = createSchedulerCrudOpenApi({\n resourceName: 'ScheduledJob',\n pluralName: 'ScheduledJobs',\n querySchema: scheduleListQuerySchema,\n listResponseSchema: createPagedListResponseSchema(scheduledJobListItemSchema),\n create: {\n schema: scheduleCreateSchema,\n description: 'Creates a new scheduled job with cron or interval-based scheduling.',\n },\n update: {\n schema: scheduleUpdateSchema,\n responseSchema: defaultOkResponseSchema,\n description: 'Updates an existing scheduled job by ID.',\n },\n del: {\n schema: scheduleDeleteSchema,\n responseSchema: defaultOkResponseSchema,\n description: 'Deletes a scheduled job by ID.',\n },\n})\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AACpC,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iCAAiC;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,gBAAgB,EAAE,OAAO,CAAC,CAAC,EAAE,YAAY;AAE/C,MAAM,gBAAgB;AAAA,EACpB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,qBAAqB,EAAE;AAAA,EACnE,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,uBAAuB,EAAE;AAAA,EACtE,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,uBAAuB,EAAE;AAAA,EACrE,QAAQ,EAAE,aAAa,MAAM,iBAAiB,CAAC,uBAAuB,EAAE;AAC1E;AAEO,MAAM,WAAW;AAExB,MAAM,OAAO,cAAc;AAAA,EACzB,UAAU;AAAA,EACV,KAAK;AAAA,IACH,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,aAAa;AAAA,IACb,iBAAiB;AAAA,EACnB;AAAA,EACA,SAAS,EAAE,YA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A,EACA,QAAQ;AAAA,IACN,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,aAAa;AAAA,EACf;AAAA,EACA,KAAK;AAAA,IACH,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,aAAa;AAAA,EACf;AACF,CAAC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -2,8 +2,6 @@ import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
|
|
|
2
2
|
import { ScheduledJob } from "./data/entities.js";
|
|
3
3
|
import { parseBooleanToken } from "@open-mercato/shared/lib/boolean";
|
|
4
4
|
import { auditSchedulerModuleQueueRows } from "./lib/safeQueueTargets.js";
|
|
5
|
-
import { createQueue } from "@open-mercato/queue";
|
|
6
|
-
import { getRedisUrlOrThrow } from "@open-mercato/shared/lib/redis/connection";
|
|
7
5
|
const writeLine = (text = "") => {
|
|
8
6
|
process.stdout.write(`${text}
|
|
9
7
|
`);
|
|
@@ -97,15 +95,14 @@ const runCommand = {
|
|
|
97
95
|
const scheduleId = rest[0];
|
|
98
96
|
if (!scheduleId) {
|
|
99
97
|
writeErrorLine("Usage: mercato scheduler run <schedule-id>");
|
|
100
|
-
process.exitCode = 1;
|
|
101
98
|
return;
|
|
102
99
|
}
|
|
103
100
|
const { resolve } = await createRequestContainer();
|
|
104
101
|
const em = resolve("em");
|
|
102
|
+
const queueService = resolve("queueService");
|
|
105
103
|
const job = await em.findOne(ScheduledJob, { id: scheduleId, deletedAt: null });
|
|
106
104
|
if (!job) {
|
|
107
105
|
writeErrorLine(`Schedule not found: ${scheduleId}`);
|
|
108
|
-
process.exitCode = 1;
|
|
109
106
|
return;
|
|
110
107
|
}
|
|
111
108
|
writeLine(`
|
|
@@ -116,34 +113,15 @@ const runCommand = {
|
|
|
116
113
|
writeLine(` Schedule: ${job.scheduleValue}`);
|
|
117
114
|
writeLine(` Target: ${job.targetType === "queue" ? job.targetQueue : job.targetCommand}`);
|
|
118
115
|
writeLine("");
|
|
119
|
-
if ((process.env.QUEUE_STRATEGY || "local") !== "async") {
|
|
120
|
-
throw new Error(
|
|
121
|
-
"Manual trigger requires QUEUE_STRATEGY=async (with the local strategy due schedules run via `mercato scheduler start`)"
|
|
122
|
-
);
|
|
123
|
-
}
|
|
124
|
-
const payload = {
|
|
125
|
-
scheduleId: job.id,
|
|
126
|
-
tenantId: job.tenantId,
|
|
127
|
-
organizationId: job.organizationId,
|
|
128
|
-
scopeType: job.scopeType,
|
|
129
|
-
triggerType: "manual",
|
|
130
|
-
triggeredByUserId: null
|
|
131
|
-
};
|
|
132
|
-
let executionQueue = null;
|
|
133
116
|
try {
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
const queueJobId = await executionQueue.enqueue(payload);
|
|
138
|
-
writeLine(`\u2713 Job successfully triggered via scheduler-execution queue (job ${queueJobId})`);
|
|
117
|
+
const schedulerQueue = queueService.getQueue("scheduler-execution");
|
|
118
|
+
await schedulerQueue.add("execute-schedule", { scheduleId: job.id });
|
|
119
|
+
writeLine("\u2713 Job successfully triggered via scheduler-execution queue");
|
|
139
120
|
writeLine(` The worker will pick it up and enqueue to: ${job.targetType === "queue" ? job.targetQueue : job.targetCommand}`);
|
|
140
121
|
writeLine("\u2713 Manual trigger completed\n");
|
|
141
122
|
} catch (error) {
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
await executionQueue?.close().catch((closeError) => {
|
|
145
|
-
writeErrorLine(`Failed to close scheduler execution queue: ${closeError instanceof Error ? closeError.message : String(closeError)}`);
|
|
146
|
-
});
|
|
123
|
+
writeErrorLine(`\u2717 Failed to trigger job: ${error instanceof Error ? error.message : String(error)}`);
|
|
124
|
+
process.exit(1);
|
|
147
125
|
}
|
|
148
126
|
}
|
|
149
127
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/modules/scheduler/cli.ts"],
|
|
4
|
-
"sourcesContent": ["import type { ModuleCli } from '@open-mercato/shared/modules/registry'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from './data/entities.js'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { auditSchedulerModuleQueueRows } from './lib/safeQueueTargets'\nimport { createQueue } from '@open-mercato/queue'\nimport type { Queue } from '@open-mercato/queue'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport type { ExecuteSchedulePayload } from './workers/execute-schedule.worker.js'\n\nconst writeLine = (text = '') => {\n process.stdout.write(`${text}\\n`)\n}\n\nconst writeErrorLine = (text: string) => {\n process.stderr.write(`${text}\\n`)\n}\n\nfunction parseArgs(rest: string[]): Record<string, string> {\n const args: Record<string, string> = {}\n for (let i = 0; i < rest.length; i += 2) {\n const key = rest[i]?.replace(/^--/, '')\n const value = rest[i + 1]\n if (key) args[key] = value ?? ''\n }\n return args\n}\n\nconst listCommand: ModuleCli = {\n command: 'list',\n async run(rest) {\n const args = parseArgs(rest)\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n\n const where: Record<string, unknown> = { deletedAt: null }\n\n // Filter by tenant if provided\n if (args.tenant || args.tenantId) {\n where.tenantId = args.tenant || args.tenantId\n }\n\n // Filter by scope type if provided\n if (args.scope || args.scopeType) {\n where.scopeType = args.scope || args.scopeType\n }\n\n // Filter by enabled status if provided\n if (args.enabled) {\n const parsed = parseBooleanToken(args.enabled)\n if (parsed !== null) {\n where.isEnabled = parsed\n }\n }\n\n const jobs = await em.find(ScheduledJob, where, {\n orderBy: { isEnabled: 'DESC', name: 'ASC' },\n })\n\n if (jobs.length === 0) {\n writeLine('No scheduled jobs found.')\n return\n }\n\n writeLine(`\\nFound ${jobs.length} scheduled job(s):\\n`)\n writeLine('ID'.padEnd(38) + 'Name'.padEnd(35) + 'Type'.padEnd(12) + 'Schedule'.padEnd(20) + 'Status'.padEnd(10) + 'Next Run')\n writeLine('-'.repeat(140))\n\n for (const job of jobs) {\n const id = String(job.id).padEnd(38)\n const name = (job.name || '').substring(0, 33).padEnd(35)\n const type = job.scheduleType.padEnd(12)\n const schedule = (job.scheduleValue || '').substring(0, 18).padEnd(20)\n const status = (job.isEnabled ? '\u2713 Enabled' : '\u2717 Disabled').padEnd(10)\n const nextRun = job.nextRunAt ? new Date(job.nextRunAt).toISOString() : 'N/A'\n writeLine(`${id}${name}${type}${schedule}${status}${nextRun}`)\n }\n\n writeLine('')\n },\n}\n\nconst statusCommand: ModuleCli = {\n command: 'status',\n async run() {\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n\n const totalCount = await em.count(ScheduledJob, { deletedAt: null })\n const enabledCount = await em.count(ScheduledJob, { isEnabled: true, deletedAt: null })\n const dueCount = await em.count(ScheduledJob, {\n isEnabled: true,\n deletedAt: null,\n nextRunAt: { $lte: new Date() },\n })\n\n const queueStrategy = process.env.QUEUE_STRATEGY || 'local'\n\n writeLine('\\n\uD83D\uDCCA Scheduler Status\\n')\n writeLine(`Strategy: ${queueStrategy === 'async' ? 'BullMQ (async)' : 'Local (polling)'}`)\n \n if (queueStrategy === 'local') {\n const pollInterval = parseInt(process.env.SCHEDULER_POLL_INTERVAL_MS || '30000', 10)\n writeLine(`Poll Interval: ${Math.round(pollInterval / 1000)}s`)\n }\n \n writeLine('')\n writeLine('Schedules:')\n writeLine(` Total: ${totalCount}`)\n writeLine(` Enabled: ${enabledCount}`)\n writeLine(` Due Now: ${dueCount}`)\n writeLine('')\n },\n}\n\nconst runCommand: ModuleCli = {\n command: 'run',\n async run(rest) {\n const scheduleId = rest[0]\n if (!scheduleId) {\n writeErrorLine('Usage: mercato scheduler run <schedule-id>')\n process.exitCode = 1\n return\n }\n\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n\n const job = await em.findOne(ScheduledJob, { id: scheduleId, deletedAt: null })\n if (!job) {\n writeErrorLine(`Schedule not found: ${scheduleId}`)\n process.exitCode = 1\n return\n }\n\n writeLine(`\\n\uD83D\uDE80 Manually triggering schedule: ${job.name}\\n`)\n writeLine(` ID: ${job.id}`)\n writeLine(` Type: ${job.scheduleType}`)\n writeLine(` Schedule: ${job.scheduleValue}`)\n writeLine(` Target: ${job.targetType === 'queue' ? job.targetQueue : job.targetCommand}`)\n writeLine('')\n\n // Mirrors scheduler.jobs.trigger: under the local strategy nothing consumes scheduler-execution.\n if ((process.env.QUEUE_STRATEGY || 'local') !== 'async') {\n throw new Error(\n 'Manual trigger requires QUEUE_STRATEGY=async (with the local strategy due schedules run via `mercato scheduler start`)',\n )\n }\n\n const payload: ExecuteSchedulePayload = {\n scheduleId: job.id,\n tenantId: job.tenantId,\n organizationId: job.organizationId,\n scopeType: job.scopeType,\n triggerType: 'manual',\n triggeredByUserId: null,\n }\n\n let executionQueue: Queue<ExecuteSchedulePayload> | null = null\n try {\n executionQueue = createQueue<ExecuteSchedulePayload>('scheduler-execution', 'async', {\n connection: { url: getRedisUrlOrThrow('QUEUE') },\n })\n const queueJobId = await executionQueue.enqueue(payload)\n\n writeLine(`\u2713 Job successfully triggered via scheduler-execution queue (job ${queueJobId})`)\n writeLine(` The worker will pick it up and enqueue to: ${job.targetType === 'queue' ? job.targetQueue : job.targetCommand}`)\n writeLine('\u2713 Manual trigger completed\\n')\n } catch (error: unknown) {\n throw new Error(`Failed to trigger job: ${error instanceof Error ? error.message : String(error)}`)\n } finally {\n await executionQueue?.close().catch((closeError: unknown) => {\n writeErrorLine(`Failed to close scheduler execution queue: ${closeError instanceof Error ? closeError.message : String(closeError)}`)\n })\n }\n },\n}\n\nconst startCommand: ModuleCli = {\n command: 'start',\n async run() {\n const { resolve } = await createRequestContainer()\n const queueStrategy = process.env.QUEUE_STRATEGY || 'local'\n\n writeLine(`\uD83D\uDE80 Starting scheduler (strategy: ${queueStrategy})...\\n`)\n\n if (queueStrategy === 'async') {\n // BullMQ strategy: Sync schedules with BullMQ repeatable jobs\n try {\n const bullmqService = resolve('bullmqSchedulerService') as { syncAll(): Promise<void> } | undefined\n \n if (!bullmqService) {\n writeErrorLine('\u274C BullMQSchedulerService not available.')\n writeErrorLine(' Set QUEUE_STRATEGY=async and configure REDIS_URL.')\n process.exit(1)\n }\n\n // Sync all enabled schedules with BullMQ\n await bullmqService.syncAll()\n\n writeLine('\u2713 Scheduler sync completed')\n writeLine('')\n writeLine('BullMQ is managing all schedules.')\n writeLine('Start workers to process jobs:')\n writeLine(' yarn mercato worker:start')\n writeLine('')\n } catch (error: unknown) {\n writeErrorLine(`\u274C Failed to sync schedules: ${error instanceof Error ? error.message : String(error)}`)\n process.exit(1)\n }\n } else {\n // Local strategy: Start polling engine\n try {\n const localService = resolve('localSchedulerService') as { start(): Promise<void>; stop(): Promise<void> } | undefined\n \n if (!localService) {\n writeErrorLine('\u274C LocalSchedulerService not available.')\n writeErrorLine(' This should not happen in local mode.')\n process.exit(1)\n }\n\n const pollInterval = parseInt(process.env.SCHEDULER_POLL_INTERVAL_MS || '30000', 10)\n\n // Start the local polling engine\n await localService.start()\n\n writeLine(`\u2713 Local scheduler started (polling every ${Math.round(pollInterval / 1000)} seconds)`)\n writeLine('Press Ctrl+C to stop.')\n writeLine('')\n writeLine('\uD83D\uDCA1 Tip: For production, use QUEUE_STRATEGY=async with Redis.')\n writeLine('')\n\n // Keep the process alive and handle graceful shutdown\n const gracefulShutdown = async () => {\n writeLine('\\n\uD83D\uDCDB Shutting down...')\n await localService.stop()\n writeLine('\u2713 Stopped')\n process.exit(0)\n }\n\n process.on('SIGINT', gracefulShutdown)\n process.on('SIGTERM', gracefulShutdown)\n\n // Keep process alive\n await new Promise(() => {}) // Never resolves\n } catch (error: unknown) {\n writeErrorLine(`\u274C Failed to start local scheduler: ${error instanceof Error ? error.message : String(error)}`)\n process.exit(1)\n }\n }\n },\n}\n\n// Lists every persisted module-authored queue-target row with its current\n// dispatch verdict (#5213). Rows authored before the hardening by a\n// non-user-bound API key are indistinguishable from genuine registrations at\n// rest, so operators review the ALLOWED entries against their known integrations.\nconst auditQueueTargetsCommand: ModuleCli = {\n command: 'audit-queue-targets',\n async run(rest) {\n const args = parseArgs(rest)\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n\n const where: Record<string, unknown> = { deletedAt: null, sourceType: 'module' }\n if (args.tenant || args.tenantId) where.tenantId = args.tenant || args.tenantId\n\n const rows = await em.find(ScheduledJob, where, {\n orderBy: { name: 'ASC' },\n })\n\n const audits = auditSchedulerModuleQueueRows(rows)\n\n writeLine(`Module-authored queue-target schedules: ${audits.length}`)\n let allowedCount = 0\n for (const audit of audits) {\n const verdict = audit.dispatchAllowed ? 'ALLOWED' : 'blocked'\n if (audit.dispatchAllowed) allowedCount += 1\n writeLine(\n `[${verdict}] ${audit.scheduleId}${audit.name ? ` \u2014 ${audit.name}` : ''}` +\n ` module=${audit.sourceModule ?? '(none)'} queue=${audit.targetQueue ?? '(none)'}` +\n ` enabled=${audit.isEnabled ? 'yes' : 'no'}`,\n )\n }\n\n if (allowedCount > 0) {\n writeLine('')\n writeLine(`Review the ${allowedCount} ALLOWED row(s) above against your known module integrations.`)\n writeLine('Pre-upgrade rows created with a non-user-bound API key cannot be distinguished')\n writeLine('from genuine registrations at rest; disable anything unrecognized:')\n writeLine(' yarn mercato scheduler list --tenant <tenantId>')\n }\n },\n}\n\nexport default [listCommand, statusCommand, runCommand, startCommand, auditQueueTargetsCommand]\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,8BAA8B;AAEvC,SAAS,oBAAoB;AAC7B,SAAS,yBAAyB;AAClC,SAAS,qCAAqC;
|
|
4
|
+
"sourcesContent": ["import type { ModuleCli } from '@open-mercato/shared/modules/registry'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from './data/entities.js'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { auditSchedulerModuleQueueRows } from './lib/safeQueueTargets'\n\nconst writeLine = (text = '') => {\n process.stdout.write(`${text}\\n`)\n}\n\nconst writeErrorLine = (text: string) => {\n process.stderr.write(`${text}\\n`)\n}\n\nfunction parseArgs(rest: string[]): Record<string, string> {\n const args: Record<string, string> = {}\n for (let i = 0; i < rest.length; i += 2) {\n const key = rest[i]?.replace(/^--/, '')\n const value = rest[i + 1]\n if (key) args[key] = value ?? ''\n }\n return args\n}\n\nconst listCommand: ModuleCli = {\n command: 'list',\n async run(rest) {\n const args = parseArgs(rest)\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n\n const where: Record<string, unknown> = { deletedAt: null }\n\n // Filter by tenant if provided\n if (args.tenant || args.tenantId) {\n where.tenantId = args.tenant || args.tenantId\n }\n\n // Filter by scope type if provided\n if (args.scope || args.scopeType) {\n where.scopeType = args.scope || args.scopeType\n }\n\n // Filter by enabled status if provided\n if (args.enabled) {\n const parsed = parseBooleanToken(args.enabled)\n if (parsed !== null) {\n where.isEnabled = parsed\n }\n }\n\n const jobs = await em.find(ScheduledJob, where, {\n orderBy: { isEnabled: 'DESC', name: 'ASC' },\n })\n\n if (jobs.length === 0) {\n writeLine('No scheduled jobs found.')\n return\n }\n\n writeLine(`\\nFound ${jobs.length} scheduled job(s):\\n`)\n writeLine('ID'.padEnd(38) + 'Name'.padEnd(35) + 'Type'.padEnd(12) + 'Schedule'.padEnd(20) + 'Status'.padEnd(10) + 'Next Run')\n writeLine('-'.repeat(140))\n\n for (const job of jobs) {\n const id = String(job.id).padEnd(38)\n const name = (job.name || '').substring(0, 33).padEnd(35)\n const type = job.scheduleType.padEnd(12)\n const schedule = (job.scheduleValue || '').substring(0, 18).padEnd(20)\n const status = (job.isEnabled ? '\u2713 Enabled' : '\u2717 Disabled').padEnd(10)\n const nextRun = job.nextRunAt ? new Date(job.nextRunAt).toISOString() : 'N/A'\n writeLine(`${id}${name}${type}${schedule}${status}${nextRun}`)\n }\n\n writeLine('')\n },\n}\n\nconst statusCommand: ModuleCli = {\n command: 'status',\n async run() {\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n\n const totalCount = await em.count(ScheduledJob, { deletedAt: null })\n const enabledCount = await em.count(ScheduledJob, { isEnabled: true, deletedAt: null })\n const dueCount = await em.count(ScheduledJob, {\n isEnabled: true,\n deletedAt: null,\n nextRunAt: { $lte: new Date() },\n })\n\n const queueStrategy = process.env.QUEUE_STRATEGY || 'local'\n\n writeLine('\\n\uD83D\uDCCA Scheduler Status\\n')\n writeLine(`Strategy: ${queueStrategy === 'async' ? 'BullMQ (async)' : 'Local (polling)'}`)\n \n if (queueStrategy === 'local') {\n const pollInterval = parseInt(process.env.SCHEDULER_POLL_INTERVAL_MS || '30000', 10)\n writeLine(`Poll Interval: ${Math.round(pollInterval / 1000)}s`)\n }\n \n writeLine('')\n writeLine('Schedules:')\n writeLine(` Total: ${totalCount}`)\n writeLine(` Enabled: ${enabledCount}`)\n writeLine(` Due Now: ${dueCount}`)\n writeLine('')\n },\n}\n\nconst runCommand: ModuleCli = {\n command: 'run',\n async run(rest) {\n const scheduleId = rest[0]\n if (!scheduleId) {\n writeErrorLine('Usage: mercato scheduler run <schedule-id>')\n return\n }\n\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n const queueService = resolve('queueService') as { getQueue(name: string): { add(name: string, data: unknown): Promise<unknown> } }\n\n const job = await em.findOne(ScheduledJob, { id: scheduleId, deletedAt: null })\n if (!job) {\n writeErrorLine(`Schedule not found: ${scheduleId}`)\n return\n }\n\n writeLine(`\\n\uD83D\uDE80 Manually triggering schedule: ${job.name}\\n`)\n writeLine(` ID: ${job.id}`)\n writeLine(` Type: ${job.scheduleType}`)\n writeLine(` Schedule: ${job.scheduleValue}`)\n writeLine(` Target: ${job.targetType === 'queue' ? job.targetQueue : job.targetCommand}`)\n writeLine('')\n\n try {\n // Manually enqueue the job (triggering the scheduler-execution worker)\n const schedulerQueue = queueService.getQueue('scheduler-execution')\n await schedulerQueue.add('execute-schedule', { scheduleId: job.id })\n\n writeLine('\u2713 Job successfully triggered via scheduler-execution queue')\n writeLine(` The worker will pick it up and enqueue to: ${job.targetType === 'queue' ? job.targetQueue : job.targetCommand}`)\n writeLine('\u2713 Manual trigger completed\\n')\n } catch (error: unknown) {\n writeErrorLine(`\u2717 Failed to trigger job: ${error instanceof Error ? error.message : String(error)}`)\n process.exit(1)\n }\n },\n}\n\nconst startCommand: ModuleCli = {\n command: 'start',\n async run() {\n const { resolve } = await createRequestContainer()\n const queueStrategy = process.env.QUEUE_STRATEGY || 'local'\n\n writeLine(`\uD83D\uDE80 Starting scheduler (strategy: ${queueStrategy})...\\n`)\n\n if (queueStrategy === 'async') {\n // BullMQ strategy: Sync schedules with BullMQ repeatable jobs\n try {\n const bullmqService = resolve('bullmqSchedulerService') as { syncAll(): Promise<void> } | undefined\n \n if (!bullmqService) {\n writeErrorLine('\u274C BullMQSchedulerService not available.')\n writeErrorLine(' Set QUEUE_STRATEGY=async and configure REDIS_URL.')\n process.exit(1)\n }\n\n // Sync all enabled schedules with BullMQ\n await bullmqService.syncAll()\n\n writeLine('\u2713 Scheduler sync completed')\n writeLine('')\n writeLine('BullMQ is managing all schedules.')\n writeLine('Start workers to process jobs:')\n writeLine(' yarn mercato worker:start')\n writeLine('')\n } catch (error: unknown) {\n writeErrorLine(`\u274C Failed to sync schedules: ${error instanceof Error ? error.message : String(error)}`)\n process.exit(1)\n }\n } else {\n // Local strategy: Start polling engine\n try {\n const localService = resolve('localSchedulerService') as { start(): Promise<void>; stop(): Promise<void> } | undefined\n \n if (!localService) {\n writeErrorLine('\u274C LocalSchedulerService not available.')\n writeErrorLine(' This should not happen in local mode.')\n process.exit(1)\n }\n\n const pollInterval = parseInt(process.env.SCHEDULER_POLL_INTERVAL_MS || '30000', 10)\n\n // Start the local polling engine\n await localService.start()\n\n writeLine(`\u2713 Local scheduler started (polling every ${Math.round(pollInterval / 1000)} seconds)`)\n writeLine('Press Ctrl+C to stop.')\n writeLine('')\n writeLine('\uD83D\uDCA1 Tip: For production, use QUEUE_STRATEGY=async with Redis.')\n writeLine('')\n\n // Keep the process alive and handle graceful shutdown\n const gracefulShutdown = async () => {\n writeLine('\\n\uD83D\uDCDB Shutting down...')\n await localService.stop()\n writeLine('\u2713 Stopped')\n process.exit(0)\n }\n\n process.on('SIGINT', gracefulShutdown)\n process.on('SIGTERM', gracefulShutdown)\n\n // Keep process alive\n await new Promise(() => {}) // Never resolves\n } catch (error: unknown) {\n writeErrorLine(`\u274C Failed to start local scheduler: ${error instanceof Error ? error.message : String(error)}`)\n process.exit(1)\n }\n }\n },\n}\n\n// Lists every persisted module-authored queue-target row with its current\n// dispatch verdict (#5213). Rows authored before the hardening by a\n// non-user-bound API key are indistinguishable from genuine registrations at\n// rest, so operators review the ALLOWED entries against their known integrations.\nconst auditQueueTargetsCommand: ModuleCli = {\n command: 'audit-queue-targets',\n async run(rest) {\n const args = parseArgs(rest)\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as EntityManager\n\n const where: Record<string, unknown> = { deletedAt: null, sourceType: 'module' }\n if (args.tenant || args.tenantId) where.tenantId = args.tenant || args.tenantId\n\n const rows = await em.find(ScheduledJob, where, {\n orderBy: { name: 'ASC' },\n })\n\n const audits = auditSchedulerModuleQueueRows(rows)\n\n writeLine(`Module-authored queue-target schedules: ${audits.length}`)\n let allowedCount = 0\n for (const audit of audits) {\n const verdict = audit.dispatchAllowed ? 'ALLOWED' : 'blocked'\n if (audit.dispatchAllowed) allowedCount += 1\n writeLine(\n `[${verdict}] ${audit.scheduleId}${audit.name ? ` \u2014 ${audit.name}` : ''}` +\n ` module=${audit.sourceModule ?? '(none)'} queue=${audit.targetQueue ?? '(none)'}` +\n ` enabled=${audit.isEnabled ? 'yes' : 'no'}`,\n )\n }\n\n if (allowedCount > 0) {\n writeLine('')\n writeLine(`Review the ${allowedCount} ALLOWED row(s) above against your known module integrations.`)\n writeLine('Pre-upgrade rows created with a non-user-bound API key cannot be distinguished')\n writeLine('from genuine registrations at rest; disable anything unrecognized:')\n writeLine(' yarn mercato scheduler list --tenant <tenantId>')\n }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MAAM,gBAAgB,QAAQ,UAAU,MAAM,eAAe,QAAQ,YACpE,MAAM,YAAY,QAAQ,IAAI;AAAA,MAC5C;AAAA,IACF;AAEA,QAAI,eAAe,GAAG;AACpB,gBAAU,EAAE;AACZ,gBAAU,cAAc,YAAY,+DAA+D;AACnG,gBAAU,gFAAgF;AAC1F,gBAAU,oEAAoE;AAC9E,gBAAU,mDAAmD;AAAA,IAC/D;AAAA,EACF;AACF;AAEA,IAAO,cAAQ,CAAC,aAAa,eAAe,YAAY,cAAc,wBAAwB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -121,7 +121,7 @@ const scheduleCreateSchema = scheduleBaseSchema.refine(
|
|
|
121
121
|
}
|
|
122
122
|
);
|
|
123
123
|
const scheduleUpdateSchema = z.object({
|
|
124
|
-
id: z.
|
|
124
|
+
id: z.uuid(),
|
|
125
125
|
name: z.string().min(1).max(200).optional(),
|
|
126
126
|
description: z.string().max(500).optional().nullable(),
|
|
127
127
|
scheduleType: z.enum(["cron", "interval"]).optional(),
|
|
@@ -198,12 +198,12 @@ const scheduleUpdateSchema = z.object({
|
|
|
198
198
|
}
|
|
199
199
|
);
|
|
200
200
|
const scheduleDeleteSchema = z.object({
|
|
201
|
-
id: z.
|
|
201
|
+
id: z.uuid()
|
|
202
202
|
});
|
|
203
203
|
const scheduleListQuerySchema = z.object({
|
|
204
204
|
page: z.coerce.number().int().min(1).default(1),
|
|
205
205
|
pageSize: z.coerce.number().int().min(1).max(100).default(20),
|
|
206
|
-
id: z.
|
|
206
|
+
id: z.string().uuid().optional(),
|
|
207
207
|
search: z.string().optional(),
|
|
208
208
|
scopeType: z.enum(["system", "organization", "tenant"]).optional(),
|
|
209
209
|
isEnabled: z.string().optional().transform((val) => {
|
|
@@ -216,12 +216,12 @@ const scheduleListQuerySchema = z.object({
|
|
|
216
216
|
order: z.enum(["asc", "desc"]).optional()
|
|
217
217
|
});
|
|
218
218
|
const scheduleTriggerSchema = z.object({
|
|
219
|
-
id: z.
|
|
219
|
+
id: z.uuid()
|
|
220
220
|
});
|
|
221
221
|
const scheduleRunsQuerySchema = z.object({
|
|
222
222
|
page: z.coerce.number().int().min(1).default(1),
|
|
223
223
|
pageSize: z.coerce.number().int().min(1).max(100).default(20),
|
|
224
|
-
scheduledJobId: z.
|
|
224
|
+
scheduledJobId: z.uuid().optional(),
|
|
225
225
|
status: z.enum(["running", "completed", "failed", "skipped"]).optional(),
|
|
226
226
|
triggerType: z.enum(["scheduled", "manual"]).optional(),
|
|
227
227
|
fromDate: z.string().datetime().optional(),
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/scheduler/data/validators.ts"],
|
|
4
|
-
"sourcesContent": ["import { z } from 'zod'\nimport { validateCron } from '../lib/cronParser'\nimport { validateInterval } from '../lib/intervalParser'\nimport { commandRegistry } from '@open-mercato/shared/lib/commands/registry'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { isSchedulerSafeCommandId } from '../lib/scheduler-safe-commands'\nimport { isSchedulerSafeQueue, validateSchedulerTargetPayload } from '../lib/safeQueueTargets'\n\n/**\n * Validate that a command exists in the command registry\n */\nfunction validateCommandExists(commandId: string): boolean {\n return commandRegistry.has(commandId)\n}\n\nfunction validateCommandIsSchedulable(commandId: string): boolean {\n return isSchedulerSafeCommandId(commandId)\n}\n\n/**\n * Validate that a queue was declared scheduler-safe by its owning worker.\n * Internal and system-only workers (webhook processors, indexers, \u2026) stay\n * undiscoverable as schedule targets \u2014 see issue #5213.\n */\nfunction validateSchedulerSafeQueue(queue: string | null | undefined): boolean {\n return isSchedulerSafeQueue(queue)\n}\n\n/**\n * Base schedule fields\n */\nconst scheduleBaseSchema = z.object({\n name: z.string().min(1, 'Name is required').max(200),\n description: z.string().max(500).optional().nullable(),\n \n scopeType: z.enum(['system', 'organization', 'tenant']),\n organizationId: z.uuid().optional().nullable(),\n tenantId: z.uuid().optional().nullable(),\n \n scheduleType: z.enum(['cron', 'interval']),\n scheduleValue: z.string().min(1, 'Schedule value is required'),\n timezone: z.string().default('UTC'),\n \n targetType: z.enum(['queue', 'command']),\n targetQueue: z.string().optional().nullable(),\n targetCommand: z.string().optional().nullable(),\n targetPayload: z.record(z.string(), z.unknown()).optional().nullable(),\n \n requireFeature: z.string().optional().nullable(),\n \n isEnabled: z.boolean().default(true),\n})\n\n/**\n * Create schedule schema\n */\nexport const scheduleCreateSchema = scheduleBaseSchema\n .refine(\n (data) => {\n if (data.scopeType === 'system') {\n return !data.organizationId && !data.tenantId\n }\n if (data.scopeType === 'organization') {\n return !!data.organizationId && !!data.tenantId\n }\n if (data.scopeType === 'tenant') {\n return !data.organizationId && !!data.tenantId\n }\n return false\n },\n {\n message: 'Invalid scope configuration',\n path: ['scopeType'],\n }\n )\n .refine(\n (data) => {\n if (data.targetType === 'queue') {\n return !!data.targetQueue\n }\n if (data.targetType === 'command') {\n return !!data.targetCommand\n }\n return false\n },\n {\n message: 'Target queue or command is required based on target type',\n path: ['targetType'],\n }\n )\n .refine(\n (data) => {\n if (data.scheduleType === 'cron') {\n return validateCron(data.scheduleValue)\n }\n if (data.scheduleType === 'interval') {\n return validateInterval(data.scheduleValue)\n }\n return false\n },\n {\n message: 'Invalid schedule value. For cron: use valid cron expression (e.g., \"0 0 * * *\"). For interval: use <number><unit> format (e.g., \"15m\", \"2h\", \"1d\")',\n path: ['scheduleValue'],\n }\n )\n .refine(\n (data) => {\n // Validate that command exists if targetType is 'command'\n if (data.targetType === 'command' && data.targetCommand) {\n return validateCommandExists(data.targetCommand)\n }\n return true\n },\n {\n message: 'Command does not exist. Please ensure the command is registered before creating a schedule.',\n path: ['targetCommand'],\n }\n )\n .refine(\n (data) => {\n if (data.targetType === 'command' && data.targetCommand) {\n return validateCommandIsSchedulable(data.targetCommand)\n }\n return true\n },\n {\n message: 'Command is not schedulable. Only scheduler-safe commands can be used as schedule targets.',\n path: ['targetCommand'],\n }\n )\n .refine(\n (data) => {\n if (data.targetType === 'queue' && data.targetQueue) {\n return validateSchedulerSafeQueue(data.targetQueue)\n }\n return true\n },\n {\n message: 'Target queue is not an approved scheduler target. Only workers that opted into scheduling can be selected.',\n path: ['targetQueue'],\n }\n )\n .refine(\n (data) => {\n if (data.targetType === 'queue' && data.targetQueue) {\n return validateSchedulerTargetPayload(data.targetQueue, data.targetPayload) === null\n }\n return true\n },\n {\n message: 'Invalid target payload for the selected scheduler queue.',\n path: ['targetPayload'],\n }\n )\n\n/**\n * Update schedule schema (all fields optional except id)\n */\nexport const scheduleUpdateSchema = z.object({\n id: z.guid(),\n name: z.string().min(1).max(200).optional(),\n description: z.string().max(500).optional().nullable(),\n \n scheduleType: z.enum(['cron', 'interval']).optional(),\n scheduleValue: z.string().min(1).optional(),\n timezone: z.string().optional(),\n \n targetType: z.enum(['queue', 'command']).optional(),\n targetQueue: z.string().optional().nullable(),\n targetCommand: z.string().optional().nullable(),\n targetPayload: z.record(z.string(), z.unknown()).optional().nullable(),\n requireFeature: z.string().optional().nullable(),\n \n isEnabled: z.boolean().optional(),\n})\n .refine(\n (data) => {\n // If scheduleValue is provided, scheduleType must also be provided\n // This ensures we can validate the value against its type\n if (data.scheduleValue !== undefined && data.scheduleType === undefined) {\n return false\n }\n return true\n },\n {\n message: 'scheduleType is required when updating scheduleValue',\n path: ['scheduleType'],\n }\n )\n .refine(\n (data) => {\n // If scheduleValue is provided, validate it based on scheduleType\n if (data.scheduleValue && data.scheduleType) {\n if (data.scheduleType === 'cron') {\n return validateCron(data.scheduleValue)\n }\n if (data.scheduleType === 'interval') {\n return validateInterval(data.scheduleValue)\n }\n }\n return true\n },\n {\n message: 'Invalid schedule value. For cron: use valid cron expression (e.g., \"0 0 * * *\"). For interval: use <number><unit> format (e.g., \"15m\", \"2h\", \"1d\")',\n path: ['scheduleValue'],\n }\n )\n .refine(\n (data) => {\n // If targetType is provided, ensure appropriate target is set\n if (data.targetType === 'queue') {\n return data.targetQueue !== undefined\n }\n if (data.targetType === 'command') {\n return data.targetCommand !== undefined\n }\n return true\n },\n {\n message: 'When changing target type, you must provide the corresponding targetQueue or targetCommand',\n path: ['targetType'],\n }\n )\n .refine(\n (data) => {\n // Validate that command exists if targetCommand is provided\n if (data.targetCommand) {\n return validateCommandExists(data.targetCommand)\n }\n return true\n },\n {\n message: 'Command does not exist. Please ensure the command is registered before updating.',\n path: ['targetCommand'],\n }\n )\n .refine(\n (data) => {\n if (data.targetCommand) {\n return validateCommandIsSchedulable(data.targetCommand)\n }\n return true\n },\n {\n message: 'Command is not schedulable. Only scheduler-safe commands can be used as schedule targets.',\n path: ['targetCommand'],\n }\n )\n // Queue-target safety and payload-shape rules for updates are enforced in the\n // scheduler.jobs.update command against the stored row, so unchanged targets\n // (always resent by the edit form) and legacy remediation stays possible (#5213).\n\n/**\n * Delete schedule schema\n */\nexport const scheduleDeleteSchema = z.object({\n id: z.guid(),\n})\n\n/**\n * List schedules query schema\n */\nexport const scheduleListQuerySchema = z.object({\n page: z.coerce.number().int().min(1).default(1),\n pageSize: z.coerce.number().int().min(1).max(100).default(20),\n id: z.guid().optional(),\n search: z.string().optional(),\n scopeType: z.enum(['system', 'organization', 'tenant']).optional(),\n isEnabled: z.string().optional().transform((val) => {\n if (val === undefined) return undefined\n return parseBooleanToken(val) ?? undefined\n }),\n sourceType: z.enum(['user', 'module']).optional(),\n sourceModule: z.string().optional(),\n sort: z.string().optional(),\n order: z.enum(['asc', 'desc']).optional(),\n})\n\n/**\n * Trigger schedule schema (manual execution)\n */\nexport const scheduleTriggerSchema = z.object({\n id: z.guid(),\n})\n\n/**\n * Get schedule runs query schema\n */\nexport const scheduleRunsQuerySchema = z.object({\n page: z.coerce.number().int().min(1).default(1),\n pageSize: z.coerce.number().int().min(1).max(100).default(20),\n scheduledJobId: z.guid().optional(),\n status: z.enum(['running', 'completed', 'failed', 'skipped']).optional(),\n triggerType: z.enum(['scheduled', 'manual']).optional(),\n fromDate: z.string().datetime().optional(),\n toDate: z.string().datetime().optional(),\n sort: z.string().optional(),\n order: z.enum(['asc', 'desc']).optional(),\n})\n\n/**\n * Type exports\n */\nexport type ScheduleCreateInput = z.infer<typeof scheduleCreateSchema>\nexport type ScheduleUpdateInput = z.infer<typeof scheduleUpdateSchema>\nexport type ScheduleDeleteInput = z.infer<typeof scheduleDeleteSchema>\nexport type ScheduleListQuery = z.infer<typeof scheduleListQuerySchema>\nexport type ScheduleTriggerInput = z.infer<typeof scheduleTriggerSchema>\nexport type ScheduleRunsQuery = z.infer<typeof scheduleRunsQuerySchema>\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC,SAAS,uBAAuB;AAChC,SAAS,yBAAyB;AAClC,SAAS,gCAAgC;AACzC,SAAS,sBAAsB,sCAAsC;AAKrE,SAAS,sBAAsB,WAA4B;AACzD,SAAO,gBAAgB,IAAI,SAAS;AACtC;AAEA,SAAS,6BAA6B,WAA4B;AAChE,SAAO,yBAAyB,SAAS;AAC3C;AAOA,SAAS,2BAA2B,OAA2C;AAC7E,SAAO,qBAAqB,KAAK;AACnC;AAKA,MAAM,qBAAqB,EAAE,OAAO;AAAA,EAClC,MAAM,EAAE,OAAO,EAAE,IAAI,GAAG,kBAAkB,EAAE,IAAI,GAAG;AAAA,EACnD,aAAa,EAAE,OAAO,EAAE,IAAI,GAAG,EAAE,SAAS,EAAE,SAAS;AAAA,EAErD,WAAW,EAAE,KAAK,CAAC,UAAU,gBAAgB,QAAQ,CAAC;AAAA,EACtD,gBAAgB,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS;AAAA,EAC7C,UAAU,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS;AAAA,EAEvC,cAAc,EAAE,KAAK,CAAC,QAAQ,UAAU,CAAC;AAAA,EACzC,eAAe,EAAE,OAAO,EAAE,IAAI,GAAG,4BAA4B;AAAA,EAC7D,UAAU,EAAE,OAAO,EAAE,QAAQ,KAAK;AAAA,EAElC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,MAAM,CAAC,YAAY;AAAA,EACrB;AACF,EACC;AAAA,EACC,CAAC,SAAS;AAER,QAAI,KAAK,eAAe;AACtB,aAAO,sBAAsB,KAAK,aAAa;AAAA,IACjD;AACA,WAAO;AAAA,EACT;AAAA,EACA;AAAA,IACE,SAAS;AAAA,IACT,MAAM,CAAC,eAAe;AAAA,EACxB;AACF,EACC;AAAA,EACC,CAAC,SAAS;AACR,QAAI,KAAK,eAAe;AACtB,aAAO,6BAA6B,KAAK,aAAa;AAAA,IACxD;AACA,WAAO;AAAA,EACT;AAAA,EACA;AAAA,IACE,SAAS;AAAA,IACT,MAAM,CAAC,eAAe;AAAA,EACxB;AACF;AAQK,MAAM,uBAAuB,EAAE,OAAO;AAAA,EAC3C,IAAI,EAAE,KAAK;AACb,CAAC;AAKM,MAAM,0BAA0B,EAAE,OAAO;AAAA,EAC9C,MAAM,EAAE,OAAO,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,QAAQ,CAAC;AAAA,EAC9C,UAAU,EAAE,OAAO,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,QAAQ,EAAE;AAAA,EAC5D,IAAI,EAAE,KAAK,EAAE,SAAS;AAAA,
|
|
4
|
+
"sourcesContent": ["import { z } from 'zod'\nimport { validateCron } from '../lib/cronParser'\nimport { validateInterval } from '../lib/intervalParser'\nimport { commandRegistry } from '@open-mercato/shared/lib/commands/registry'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { isSchedulerSafeCommandId } from '../lib/scheduler-safe-commands'\nimport { isSchedulerSafeQueue, validateSchedulerTargetPayload } from '../lib/safeQueueTargets'\n\n/**\n * Validate that a command exists in the command registry\n */\nfunction validateCommandExists(commandId: string): boolean {\n return commandRegistry.has(commandId)\n}\n\nfunction validateCommandIsSchedulable(commandId: string): boolean {\n return isSchedulerSafeCommandId(commandId)\n}\n\n/**\n * Validate that a queue was declared scheduler-safe by its owning worker.\n * Internal and system-only workers (webhook processors, indexers, \u2026) stay\n * undiscoverable as schedule targets \u2014 see issue #5213.\n */\nfunction validateSchedulerSafeQueue(queue: string | null | undefined): boolean {\n return isSchedulerSafeQueue(queue)\n}\n\n/**\n * Base schedule fields\n */\nconst scheduleBaseSchema = z.object({\n name: z.string().min(1, 'Name is required').max(200),\n description: z.string().max(500).optional().nullable(),\n \n scopeType: z.enum(['system', 'organization', 'tenant']),\n organizationId: z.uuid().optional().nullable(),\n tenantId: z.uuid().optional().nullable(),\n \n scheduleType: z.enum(['cron', 'interval']),\n scheduleValue: z.string().min(1, 'Schedule value is required'),\n timezone: z.string().default('UTC'),\n \n targetType: z.enum(['queue', 'command']),\n targetQueue: z.string().optional().nullable(),\n targetCommand: z.string().optional().nullable(),\n targetPayload: z.record(z.string(), z.unknown()).optional().nullable(),\n \n requireFeature: z.string().optional().nullable(),\n \n isEnabled: z.boolean().default(true),\n})\n\n/**\n * Create schedule schema\n */\nexport const scheduleCreateSchema = scheduleBaseSchema\n .refine(\n (data) => {\n if (data.scopeType === 'system') {\n return !data.organizationId && !data.tenantId\n }\n if (data.scopeType === 'organization') {\n return !!data.organizationId && !!data.tenantId\n }\n if (data.scopeType === 'tenant') {\n return !data.organizationId && !!data.tenantId\n }\n return false\n },\n {\n message: 'Invalid scope configuration',\n path: ['scopeType'],\n }\n )\n .refine(\n (data) => {\n if (data.targetType === 'queue') {\n return !!data.targetQueue\n }\n if (data.targetType === 'command') {\n return !!data.targetCommand\n }\n return false\n },\n {\n message: 'Target queue or command is required based on target type',\n path: ['targetType'],\n }\n )\n .refine(\n (data) => {\n if (data.scheduleType === 'cron') {\n return validateCron(data.scheduleValue)\n }\n if (data.scheduleType === 'interval') {\n return validateInterval(data.scheduleValue)\n }\n return false\n },\n {\n message: 'Invalid schedule value. For cron: use valid cron expression (e.g., \"0 0 * * *\"). For interval: use <number><unit> format (e.g., \"15m\", \"2h\", \"1d\")',\n path: ['scheduleValue'],\n }\n )\n .refine(\n (data) => {\n // Validate that command exists if targetType is 'command'\n if (data.targetType === 'command' && data.targetCommand) {\n return validateCommandExists(data.targetCommand)\n }\n return true\n },\n {\n message: 'Command does not exist. Please ensure the command is registered before creating a schedule.',\n path: ['targetCommand'],\n }\n )\n .refine(\n (data) => {\n if (data.targetType === 'command' && data.targetCommand) {\n return validateCommandIsSchedulable(data.targetCommand)\n }\n return true\n },\n {\n message: 'Command is not schedulable. Only scheduler-safe commands can be used as schedule targets.',\n path: ['targetCommand'],\n }\n )\n .refine(\n (data) => {\n if (data.targetType === 'queue' && data.targetQueue) {\n return validateSchedulerSafeQueue(data.targetQueue)\n }\n return true\n },\n {\n message: 'Target queue is not an approved scheduler target. Only workers that opted into scheduling can be selected.',\n path: ['targetQueue'],\n }\n )\n .refine(\n (data) => {\n if (data.targetType === 'queue' && data.targetQueue) {\n return validateSchedulerTargetPayload(data.targetQueue, data.targetPayload) === null\n }\n return true\n },\n {\n message: 'Invalid target payload for the selected scheduler queue.',\n path: ['targetPayload'],\n }\n )\n\n/**\n * Update schedule schema (all fields optional except id)\n */\nexport const scheduleUpdateSchema = z.object({\n id: z.uuid(),\n name: z.string().min(1).max(200).optional(),\n description: z.string().max(500).optional().nullable(),\n \n scheduleType: z.enum(['cron', 'interval']).optional(),\n scheduleValue: z.string().min(1).optional(),\n timezone: z.string().optional(),\n \n targetType: z.enum(['queue', 'command']).optional(),\n targetQueue: z.string().optional().nullable(),\n targetCommand: z.string().optional().nullable(),\n targetPayload: z.record(z.string(), z.unknown()).optional().nullable(),\n requireFeature: z.string().optional().nullable(),\n \n isEnabled: z.boolean().optional(),\n})\n .refine(\n (data) => {\n // If scheduleValue is provided, scheduleType must also be provided\n // This ensures we can validate the value against its type\n if (data.scheduleValue !== undefined && data.scheduleType === undefined) {\n return false\n }\n return true\n },\n {\n message: 'scheduleType is required when updating scheduleValue',\n path: ['scheduleType'],\n }\n )\n .refine(\n (data) => {\n // If scheduleValue is provided, validate it based on scheduleType\n if (data.scheduleValue && data.scheduleType) {\n if (data.scheduleType === 'cron') {\n return validateCron(data.scheduleValue)\n }\n if (data.scheduleType === 'interval') {\n return validateInterval(data.scheduleValue)\n }\n }\n return true\n },\n {\n message: 'Invalid schedule value. For cron: use valid cron expression (e.g., \"0 0 * * *\"). For interval: use <number><unit> format (e.g., \"15m\", \"2h\", \"1d\")',\n path: ['scheduleValue'],\n }\n )\n .refine(\n (data) => {\n // If targetType is provided, ensure appropriate target is set\n if (data.targetType === 'queue') {\n return data.targetQueue !== undefined\n }\n if (data.targetType === 'command') {\n return data.targetCommand !== undefined\n }\n return true\n },\n {\n message: 'When changing target type, you must provide the corresponding targetQueue or targetCommand',\n path: ['targetType'],\n }\n )\n .refine(\n (data) => {\n // Validate that command exists if targetCommand is provided\n if (data.targetCommand) {\n return validateCommandExists(data.targetCommand)\n }\n return true\n },\n {\n message: 'Command does not exist. Please ensure the command is registered before updating.',\n path: ['targetCommand'],\n }\n )\n .refine(\n (data) => {\n if (data.targetCommand) {\n return validateCommandIsSchedulable(data.targetCommand)\n }\n return true\n },\n {\n message: 'Command is not schedulable. Only scheduler-safe commands can be used as schedule targets.',\n path: ['targetCommand'],\n }\n )\n // Queue-target safety and payload-shape rules for updates are enforced in the\n // scheduler.jobs.update command against the stored row, so unchanged targets\n // (always resent by the edit form) and legacy remediation stays possible (#5213).\n\n/**\n * Delete schedule schema\n */\nexport const scheduleDeleteSchema = z.object({\n id: z.uuid(),\n})\n\n/**\n * List schedules query schema\n */\nexport const scheduleListQuerySchema = z.object({\n page: z.coerce.number().int().min(1).default(1),\n pageSize: z.coerce.number().int().min(1).max(100).default(20),\n id: z.string().uuid().optional(),\n search: z.string().optional(),\n scopeType: z.enum(['system', 'organization', 'tenant']).optional(),\n isEnabled: z.string().optional().transform((val) => {\n if (val === undefined) return undefined\n return parseBooleanToken(val) ?? undefined\n }),\n sourceType: z.enum(['user', 'module']).optional(),\n sourceModule: z.string().optional(),\n sort: z.string().optional(),\n order: z.enum(['asc', 'desc']).optional(),\n})\n\n/**\n * Trigger schedule schema (manual execution)\n */\nexport const scheduleTriggerSchema = z.object({\n id: z.uuid(),\n})\n\n/**\n * Get schedule runs query schema\n */\nexport const scheduleRunsQuerySchema = z.object({\n page: z.coerce.number().int().min(1).default(1),\n pageSize: z.coerce.number().int().min(1).max(100).default(20),\n scheduledJobId: z.uuid().optional(),\n status: z.enum(['running', 'completed', 'failed', 'skipped']).optional(),\n triggerType: z.enum(['scheduled', 'manual']).optional(),\n fromDate: z.string().datetime().optional(),\n toDate: z.string().datetime().optional(),\n sort: z.string().optional(),\n order: z.enum(['asc', 'desc']).optional(),\n})\n\n/**\n * Type exports\n */\nexport type ScheduleCreateInput = z.infer<typeof scheduleCreateSchema>\nexport type ScheduleUpdateInput = z.infer<typeof scheduleUpdateSchema>\nexport type ScheduleDeleteInput = z.infer<typeof scheduleDeleteSchema>\nexport type ScheduleListQuery = z.infer<typeof scheduleListQuerySchema>\nexport type ScheduleTriggerInput = z.infer<typeof scheduleTriggerSchema>\nexport type ScheduleRunsQuery = z.infer<typeof scheduleRunsQuerySchema>\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC,SAAS,uBAAuB;AAChC,SAAS,yBAAyB;AAClC,SAAS,gCAAgC;AACzC,SAAS,sBAAsB,sCAAsC;AAKrE,SAAS,sBAAsB,WAA4B;AACzD,SAAO,gBAAgB,IAAI,SAAS;AACtC;AAEA,SAAS,6BAA6B,WAA4B;AAChE,SAAO,yBAAyB,SAAS;AAC3C;AAOA,SAAS,2BAA2B,OAA2C;AAC7E,SAAO,qBAAqB,KAAK;AACnC;AAKA,MAAM,qBAAqB,EAAE,OAAO;AAAA,EAClC,MAAM,EAAE,OAAO,EAAE,IAAI,GAAG,kBAAkB,EAAE,IAAI,GAAG;AAAA,EACnD,aAAa,EAAE,OAAO,EAAE,IAAI,GAAG,EAAE,SAAS,EAAE,SAAS;AAAA,EAErD,WAAW,EAAE,KAAK,CAA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QueueTargets.js";
|
|
19
|
-
import { syncScheduleNextRunAt } from "../lib/nextRunSync.js";
|
|
20
19
|
const logger = createLogger("scheduler").child({ component: "worker" });
|
|
21
20
|
const metadata = {
|
|
22
21
|
queue: "scheduler-execution",
|
|
@@ -24,17 +23,6 @@ const metadata = {
|
|
|
24
23
|
// Process up to 5 schedules concurrently
|
|
25
24
|
};
|
|
26
25
|
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) {
|
|
38
26
|
logger.debug("Processing job", {
|
|
39
27
|
jobId: ctx.jobId,
|
|
40
28
|
attemptNumber: ctx.attemptNumber
|
|
@@ -89,14 +77,6 @@ async function executeSchedule(job, ctx, execution) {
|
|
|
89
77
|
});
|
|
90
78
|
return;
|
|
91
79
|
}
|
|
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
|
-
};
|
|
100
80
|
await emitSchedulerEvent("scheduler.job.started", {
|
|
101
81
|
id: schedule.id,
|
|
102
82
|
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'\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;
|
|
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;AAEP,MA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