@open-mercato/scheduler 0.6.6-develop.6431.1.g1037269810 → 0.6.6-develop.6450.1.b493fb430c
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/lib/commandContext.js +38 -0
- package/dist/modules/scheduler/lib/commandContext.js.map +7 -0
- package/dist/modules/scheduler/services/localSchedulerService.js +6 -10
- package/dist/modules/scheduler/services/localSchedulerService.js.map +2 -2
- package/dist/modules/scheduler/workers/execute-schedule.worker.js +2 -10
- package/dist/modules/scheduler/workers/execute-schedule.worker.js.map +2 -2
- package/jest.config.cjs +1 -0
- package/package.json +5 -5
- package/src/modules/scheduler/lib/__tests__/commandContext.test.ts +60 -0
- package/src/modules/scheduler/lib/commandContext.ts +55 -0
- package/src/modules/scheduler/services/localSchedulerService.ts +7 -12
- package/src/modules/scheduler/workers/__tests__/execute-schedule.worker.test.ts +102 -0
- package/src/modules/scheduler/workers/execute-schedule.worker.ts +2 -11
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
[build:scheduler] found
|
|
1
|
+
[build:scheduler] found 52 entry points
|
|
2
2
|
[build:scheduler] built successfully
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
const SCHEDULER_SYSTEM_ACTOR_ID = "00000000-0000-0000-0000-000000000000";
|
|
2
|
+
function buildScheduledCommandAuth(schedule) {
|
|
3
|
+
const actorId = schedule.createdByUserId || SCHEDULER_SYSTEM_ACTOR_ID;
|
|
4
|
+
return {
|
|
5
|
+
sub: actorId,
|
|
6
|
+
userId: actorId,
|
|
7
|
+
tenantId: schedule.tenantId ?? null,
|
|
8
|
+
orgId: schedule.organizationId ?? null,
|
|
9
|
+
isSuperAdmin: false
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
function buildScheduledCommandContext(schedule, container) {
|
|
13
|
+
const tenantId = schedule.tenantId ?? null;
|
|
14
|
+
const organizationId = schedule.organizationId ?? null;
|
|
15
|
+
const organizationIds = organizationId ? [organizationId] : null;
|
|
16
|
+
return {
|
|
17
|
+
container,
|
|
18
|
+
auth: buildScheduledCommandAuth(schedule),
|
|
19
|
+
organizationScope: schedule.scopeType === "organization" && organizationId ? {
|
|
20
|
+
selectedId: organizationId,
|
|
21
|
+
filterIds: [organizationId],
|
|
22
|
+
allowedIds: [organizationId],
|
|
23
|
+
tenantId
|
|
24
|
+
} : {
|
|
25
|
+
selectedId: null,
|
|
26
|
+
filterIds: null,
|
|
27
|
+
allowedIds: null,
|
|
28
|
+
tenantId
|
|
29
|
+
},
|
|
30
|
+
selectedOrganizationId: organizationId,
|
|
31
|
+
organizationIds,
|
|
32
|
+
request: void 0
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
export {
|
|
36
|
+
buildScheduledCommandContext
|
|
37
|
+
};
|
|
38
|
+
//# sourceMappingURL=commandContext.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/modules/scheduler/lib/commandContext.ts"],
|
|
4
|
+
"sourcesContent": ["import type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\n\nconst SCHEDULER_SYSTEM_ACTOR_ID = '00000000-0000-0000-0000-000000000000'\n\ntype ScheduledCommandContextSchedule = {\n id: string\n tenantId?: string | null\n organizationId?: string | null\n scopeType: 'system' | 'organization' | 'tenant'\n createdByUserId?: string | null\n}\n\nfunction buildScheduledCommandAuth(schedule: ScheduledCommandContextSchedule): Exclude<AuthContext, null> {\n const actorId = schedule.createdByUserId || SCHEDULER_SYSTEM_ACTOR_ID\n return {\n sub: actorId,\n userId: actorId,\n tenantId: schedule.tenantId ?? null,\n orgId: schedule.organizationId ?? null,\n isSuperAdmin: false,\n }\n}\n\nexport function buildScheduledCommandContext(\n schedule: ScheduledCommandContextSchedule,\n container: AppContainer,\n): CommandRuntimeContext {\n const tenantId = schedule.tenantId ?? null\n const organizationId = schedule.organizationId ?? null\n const organizationIds = organizationId ? [organizationId] : null\n\n return {\n container,\n auth: buildScheduledCommandAuth(schedule),\n organizationScope:\n schedule.scopeType === 'organization' && organizationId\n ? {\n selectedId: organizationId,\n filterIds: [organizationId],\n allowedIds: [organizationId],\n tenantId,\n }\n : {\n selectedId: null,\n filterIds: null,\n allowedIds: null,\n tenantId,\n },\n selectedOrganizationId: organizationId,\n organizationIds,\n request: undefined,\n }\n}\n"],
|
|
5
|
+
"mappings": "AAIA,MAAM,4BAA4B;AAUlC,SAAS,0BAA0B,UAAuE;AACxG,QAAM,UAAU,SAAS,mBAAmB;AAC5C,SAAO;AAAA,IACL,KAAK;AAAA,IACL,QAAQ;AAAA,IACR,UAAU,SAAS,YAAY;AAAA,IAC/B,OAAO,SAAS,kBAAkB;AAAA,IAClC,cAAc;AAAA,EAChB;AACF;AAEO,SAAS,6BACd,UACA,WACuB;AACvB,QAAM,WAAW,SAAS,YAAY;AACtC,QAAM,iBAAiB,SAAS,kBAAkB;AAClD,QAAM,kBAAkB,iBAAiB,CAAC,cAAc,IAAI;AAE5D,SAAO;AAAA,IACL;AAAA,IACA,MAAM,0BAA0B,QAAQ;AAAA,IACxC,mBACE,SAAS,cAAc,kBAAkB,iBACrC;AAAA,MACE,YAAY;AAAA,MACZ,WAAW,CAAC,cAAc;AAAA,MAC1B,YAAY,CAAC,cAAc;AAAA,MAC3B;AAAA,IACF,IACA;AAAA,MACE,YAAY;AAAA,MACZ,WAAW;AAAA,MACX,YAAY;AAAA,MACZ;AAAA,IACF;AAAA,IACN,wBAAwB;AAAA,IACxB;AAAA,IACA,SAAS;AAAA,EACX;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -4,6 +4,7 @@ import { LocalLockStrategy } from "../lib/localLockStrategy.js";
|
|
|
4
4
|
import { recalculateNextRun } from "../lib/nextRunCalculator.js";
|
|
5
5
|
import { emitSchedulerEvent } from "../events.js";
|
|
6
6
|
import { getGlobalEventBus } from "@open-mercato/shared/modules/events";
|
|
7
|
+
import { buildScheduledCommandContext } from "../lib/commandContext.js";
|
|
7
8
|
class LocalSchedulerService {
|
|
8
9
|
constructor(em, queueFactory, rbacService, config = { pollIntervalMs: 3e4 }) {
|
|
9
10
|
this.em = em;
|
|
@@ -188,22 +189,17 @@ class LocalSchedulerService {
|
|
|
188
189
|
tenantId: schedule.tenantId,
|
|
189
190
|
organizationId: schedule.organizationId
|
|
190
191
|
};
|
|
191
|
-
const commandCtx =
|
|
192
|
-
|
|
192
|
+
const commandCtx = buildScheduledCommandContext(
|
|
193
|
+
schedule,
|
|
194
|
+
{
|
|
193
195
|
resolve: (name) => {
|
|
194
196
|
if (name === "em") return this.em();
|
|
195
197
|
if (name === "eventBus") return getGlobalEventBus();
|
|
196
198
|
if (name === "rbacService") return this.rbacService;
|
|
197
199
|
throw new Error(`Service not available in scheduler context: ${name}`);
|
|
198
200
|
}
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
// Scheduled commands run without user authentication
|
|
202
|
-
organizationScope: null,
|
|
203
|
-
selectedOrganizationId: schedule.organizationId || null,
|
|
204
|
-
organizationIds: schedule.organizationId ? [schedule.organizationId] : null,
|
|
205
|
-
request: void 0
|
|
206
|
-
};
|
|
201
|
+
}
|
|
202
|
+
);
|
|
207
203
|
const result = await commandBus.execute(schedule.targetCommand, {
|
|
208
204
|
input: commandInput,
|
|
209
205
|
ctx: commandCtx
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/scheduler/services/localSchedulerService.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport type { Queue } from '@open-mercato/queue'\nimport { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { ScheduledJob } from '../data/entities.js'\nimport { LocalLockStrategy } from '../lib/localLockStrategy'\nimport { recalculateNextRun } from '../lib/nextRunCalculator'\nimport { emitSchedulerEvent } from '../events.js'\nimport { getGlobalEventBus } from '@open-mercato/shared/modules/events'\n\nexport interface RbacServiceLike {\n tenantHasFeature(tenantId: string | null | undefined, feature: string, opts?: { organizationId?: string | null }): Promise<boolean>\n}\n\nexport interface LocalSchedulerConfig {\n pollIntervalMs: number\n}\n\n/**\n * Local scheduler service for development\n * \n * This service polls the database for due schedules and executes them locally\n * without requiring Redis. Perfect for local development.\n * \n * Features:\n * - PostgreSQL polling (configurable interval, default 30s)\n * - PostgreSQL advisory locks for duplicate prevention\n * - Supports both queue and command targets\n * - Emits the same events as async strategy\n * - Updates nextRunAt after execution\n * \n * Limitations:\n * - Polling delay (up to configured interval)\n * - Single instance only (no distributed locking across instances)\n * - Higher database load than async strategy\n * \n * Set QUEUE_STRATEGY=local to use this service.\n */\nexport class LocalSchedulerService {\n private isRunning = false\n private pollTimer?: NodeJS.Timeout\n private lockStrategy: LocalLockStrategy\n\n constructor(\n private em: () => EntityManager,\n private queueFactory: (name: string) => Queue,\n private rbacService: RbacServiceLike,\n private config: LocalSchedulerConfig = { pollIntervalMs: 30000 },\n ) {\n this.lockStrategy = new LocalLockStrategy(em)\n }\n\n /**\n * Start the local scheduler polling engine\n */\n async start(): Promise<void> {\n if (this.isRunning) {\n console.warn('[scheduler:local] Already running')\n return\n }\n\n this.isRunning = true\n console.log('[scheduler:local] Starting polling engine...')\n console.log(`[scheduler:local] Poll interval: ${this.config.pollIntervalMs}ms`)\n\n // Run initial poll immediately\n await this.poll()\n\n // Schedule recurring polls\n this.pollTimer = setInterval(() => {\n this.poll().catch((error) => {\n console.error('[scheduler:local] Poll error:', error)\n })\n }, this.config.pollIntervalMs)\n\n console.log('[scheduler:local] \u2713 Polling engine started')\n }\n\n /**\n * Stop the local scheduler\n */\n async stop(): Promise<void> {\n console.log('[scheduler:local] Stopping polling engine...')\n this.isRunning = false\n \n if (this.pollTimer) {\n clearInterval(this.pollTimer)\n this.pollTimer = undefined\n }\n\n console.log('[scheduler:local] \u2713 Polling engine stopped')\n }\n\n /**\n * Poll for due schedules and execute them\n */\n private async poll(): Promise<void> {\n if (!this.isRunning) {\n return\n }\n\n const em = this.em().fork()\n\n try {\n // Find enabled schedules that are due (limited to avoid spikes after outages)\n const dueSchedules = await em.find(ScheduledJob, {\n isEnabled: true,\n deletedAt: null,\n nextRunAt: { $lte: new Date() },\n }, {\n limit: 100,\n orderBy: { nextRunAt: 'ASC' },\n })\n\n if (dueSchedules.length === 0) {\n console.log('[scheduler:local] No due schedules')\n return\n }\n\n console.log(`[scheduler:local] Found ${dueSchedules.length} due schedule(s)`)\n\n // Execute each schedule\n for (const schedule of dueSchedules) {\n await this.executeSchedule(schedule)\n }\n } catch (error: unknown) {\n console.error('[scheduler:local] Poll failed:', error)\n }\n }\n\n /**\n * Execute a single schedule\n */\n private async executeSchedule(schedule: ScheduledJob): Promise<void> {\n const lockKey = `schedule:${schedule.id}`\n\n const { acquired } = await this.lockStrategy.runWithLock(lockKey, async () => {\n console.log(`[scheduler:local] Executing schedule: ${schedule.name} (${schedule.id})`)\n\n // Emit started event\n await emitSchedulerEvent('scheduler.job.started', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n triggerType: 'scheduled',\n startedAt: new Date(),\n })\n\n try {\n // Check feature flag if required\n if (schedule.requireFeature) {\n const hasFeature = await this.checkFeature(schedule)\n \n if (!hasFeature) {\n console.log(`[scheduler:local] Schedule ${schedule.name} skipped: missing feature ${schedule.requireFeature}`)\n \n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n reason: `Missing required feature: ${schedule.requireFeature}`,\n skippedAt: new Date(),\n })\n\n // Still update next run time\n await this.updateNextRun(schedule)\n return\n }\n }\n\n // Execute based on target type\n if (schedule.targetType === 'queue') {\n await this.executeQueueTarget(schedule)\n } else if (schedule.targetType === 'command') {\n await this.executeCommandTarget(schedule)\n } else {\n throw new Error(`Unknown target type: ${schedule.targetType}`)\n }\n\n // Update last run and next run times\n const em = this.em().fork()\n const freshSchedule = await em.findOne(ScheduledJob, { id: schedule.id })\n \n if (freshSchedule) {\n freshSchedule.lastRunAt = new Date()\n \n // Calculate next run time\n const nextRun = recalculateNextRun(\n freshSchedule.scheduleType,\n freshSchedule.scheduleValue,\n freshSchedule.timezone\n )\n \n if (nextRun) {\n freshSchedule.nextRunAt = nextRun\n }\n \n await em.flush()\n }\n\n console.log(`[scheduler:local] \u2713 Schedule ${schedule.name} completed successfully`)\n\n // Emit completed event\n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n completedAt: new Date(),\n })\n } catch (error: unknown) {\n console.error(`[scheduler:local] \u2717 Schedule ${schedule.name} failed:`, error)\n\n // Emit failed event\n await emitSchedulerEvent('scheduler.job.failed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n error: error instanceof Error ? error.message : String(error),\n failedAt: new Date(),\n })\n\n // Still update next run time even on failure\n await this.updateNextRun(schedule)\n }\n })\n\n if (!acquired) {\n console.log(`[scheduler:local] Schedule ${schedule.name} is already locked, skipping`)\n return\n }\n }\n\n /**\n * Execute a queue-based target\n */\n private async executeQueueTarget(schedule: ScheduledJob): Promise<void> {\n if (!schedule.targetQueue) {\n throw new Error('Target queue is required for queue target type')\n }\n\n const queue = this.queueFactory(schedule.targetQueue)\n \n await queue.enqueue({\n scheduleId: schedule.id,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n payload: schedule.targetPayload || {},\n triggeredAt: new Date(),\n })\n\n console.log(`[scheduler:local] Enqueued job to queue: ${schedule.targetQueue}`)\n }\n\n /**\n * Execute a command-based target\n */\n private async executeCommandTarget(schedule: ScheduledJob): Promise<void> {\n if (!schedule.targetCommand) {\n throw new Error('Target command is required for command target type')\n }\n\n const commandBus = new CommandBus()\n \n const commandInput = {\n ...((schedule.targetPayload as Record<string, unknown>) || {}),\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n }\n \n // Build command context with tenant/org scope but no user\n // Commands run without user authentication for scheduled jobs\n const commandCtx: CommandRuntimeContext = {\n container: {\n resolve: (name: string) => {\n // Simple resolver that forwards to our dependencies\n if (name === 'em') return this.em()\n if (name === 'eventBus') return getGlobalEventBus()\n if (name === 'rbacService') return this.rbacService\n throw new Error(`Service not available in scheduler context: ${name}`)\n },\n } as CommandRuntimeContext['container'],\n auth: null, // Scheduled commands run without user authentication\n organizationScope: null,\n selectedOrganizationId: schedule.organizationId || null,\n organizationIds: schedule.organizationId ? [schedule.organizationId] : null,\n request: undefined,\n }\n\n const result = await commandBus.execute(schedule.targetCommand, {\n input: commandInput,\n ctx: commandCtx,\n })\n\n console.log(`[scheduler:local] Executed command: ${schedule.targetCommand}`, result)\n }\n\n /**\n * Check if user/tenant has required feature\n */\n private async checkFeature(schedule: ScheduledJob): Promise<boolean> {\n if (!schedule.requireFeature) {\n return true\n }\n\n try {\n // For system-scoped schedules, no RBAC check needed\n if (schedule.scopeType === 'system') {\n return true\n }\n\n // For tenant/org scoped schedules, check if ANY admin user has the feature\n // This is a simplified check - in reality, scheduled jobs run without a user context\n // so we're just checking if the feature is enabled for the tenant\n const hasFeature = await this.rbacService.tenantHasFeature(\n schedule.tenantId,\n schedule.requireFeature,\n {\n organizationId: schedule.organizationId,\n }\n )\n\n return hasFeature\n } catch (error: unknown) {\n console.error('[scheduler:local] Feature check failed:', error)\n return false\n }\n }\n\n /**\n * Update next run time for a schedule\n */\n private async updateNextRun(schedule: ScheduledJob): Promise<void> {\n const em = this.em().fork()\n const freshSchedule = await em.findOne(ScheduledJob, { id: schedule.id })\n \n if (freshSchedule) {\n const nextRun = recalculateNextRun(\n freshSchedule.scheduleType,\n freshSchedule.scheduleValue,\n freshSchedule.timezone\n )\n \n if (nextRun) {\n freshSchedule.nextRunAt = nextRun\n await em.flush()\n }\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "AAEA,SAAS,kBAAkB;AAE3B,SAAS,oBAAoB;AAC7B,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AACnC,SAAS,0BAA0B;AACnC,SAAS,yBAAyB;
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport type { Queue } from '@open-mercato/queue'\nimport { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { ScheduledJob } from '../data/entities.js'\nimport { LocalLockStrategy } from '../lib/localLockStrategy'\nimport { recalculateNextRun } from '../lib/nextRunCalculator'\nimport { emitSchedulerEvent } from '../events.js'\nimport { getGlobalEventBus } from '@open-mercato/shared/modules/events'\nimport { buildScheduledCommandContext } from '../lib/commandContext.js'\n\nexport interface RbacServiceLike {\n tenantHasFeature(tenantId: string | null | undefined, feature: string, opts?: { organizationId?: string | null }): Promise<boolean>\n}\n\nexport interface LocalSchedulerConfig {\n pollIntervalMs: number\n}\n\n/**\n * Local scheduler service for development\n * \n * This service polls the database for due schedules and executes them locally\n * without requiring Redis. Perfect for local development.\n * \n * Features:\n * - PostgreSQL polling (configurable interval, default 30s)\n * - PostgreSQL advisory locks for duplicate prevention\n * - Supports both queue and command targets\n * - Emits the same events as async strategy\n * - Updates nextRunAt after execution\n * \n * Limitations:\n * - Polling delay (up to configured interval)\n * - Single instance only (no distributed locking across instances)\n * - Higher database load than async strategy\n * \n * Set QUEUE_STRATEGY=local to use this service.\n */\nexport class LocalSchedulerService {\n private isRunning = false\n private pollTimer?: NodeJS.Timeout\n private lockStrategy: LocalLockStrategy\n\n constructor(\n private em: () => EntityManager,\n private queueFactory: (name: string) => Queue,\n private rbacService: RbacServiceLike,\n private config: LocalSchedulerConfig = { pollIntervalMs: 30000 },\n ) {\n this.lockStrategy = new LocalLockStrategy(em)\n }\n\n /**\n * Start the local scheduler polling engine\n */\n async start(): Promise<void> {\n if (this.isRunning) {\n console.warn('[scheduler:local] Already running')\n return\n }\n\n this.isRunning = true\n console.log('[scheduler:local] Starting polling engine...')\n console.log(`[scheduler:local] Poll interval: ${this.config.pollIntervalMs}ms`)\n\n // Run initial poll immediately\n await this.poll()\n\n // Schedule recurring polls\n this.pollTimer = setInterval(() => {\n this.poll().catch((error) => {\n console.error('[scheduler:local] Poll error:', error)\n })\n }, this.config.pollIntervalMs)\n\n console.log('[scheduler:local] \u2713 Polling engine started')\n }\n\n /**\n * Stop the local scheduler\n */\n async stop(): Promise<void> {\n console.log('[scheduler:local] Stopping polling engine...')\n this.isRunning = false\n \n if (this.pollTimer) {\n clearInterval(this.pollTimer)\n this.pollTimer = undefined\n }\n\n console.log('[scheduler:local] \u2713 Polling engine stopped')\n }\n\n /**\n * Poll for due schedules and execute them\n */\n private async poll(): Promise<void> {\n if (!this.isRunning) {\n return\n }\n\n const em = this.em().fork()\n\n try {\n // Find enabled schedules that are due (limited to avoid spikes after outages)\n const dueSchedules = await em.find(ScheduledJob, {\n isEnabled: true,\n deletedAt: null,\n nextRunAt: { $lte: new Date() },\n }, {\n limit: 100,\n orderBy: { nextRunAt: 'ASC' },\n })\n\n if (dueSchedules.length === 0) {\n console.log('[scheduler:local] No due schedules')\n return\n }\n\n console.log(`[scheduler:local] Found ${dueSchedules.length} due schedule(s)`)\n\n // Execute each schedule\n for (const schedule of dueSchedules) {\n await this.executeSchedule(schedule)\n }\n } catch (error: unknown) {\n console.error('[scheduler:local] Poll failed:', error)\n }\n }\n\n /**\n * Execute a single schedule\n */\n private async executeSchedule(schedule: ScheduledJob): Promise<void> {\n const lockKey = `schedule:${schedule.id}`\n\n const { acquired } = await this.lockStrategy.runWithLock(lockKey, async () => {\n console.log(`[scheduler:local] Executing schedule: ${schedule.name} (${schedule.id})`)\n\n // Emit started event\n await emitSchedulerEvent('scheduler.job.started', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n triggerType: 'scheduled',\n startedAt: new Date(),\n })\n\n try {\n // Check feature flag if required\n if (schedule.requireFeature) {\n const hasFeature = await this.checkFeature(schedule)\n \n if (!hasFeature) {\n console.log(`[scheduler:local] Schedule ${schedule.name} skipped: missing feature ${schedule.requireFeature}`)\n \n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n reason: `Missing required feature: ${schedule.requireFeature}`,\n skippedAt: new Date(),\n })\n\n // Still update next run time\n await this.updateNextRun(schedule)\n return\n }\n }\n\n // Execute based on target type\n if (schedule.targetType === 'queue') {\n await this.executeQueueTarget(schedule)\n } else if (schedule.targetType === 'command') {\n await this.executeCommandTarget(schedule)\n } else {\n throw new Error(`Unknown target type: ${schedule.targetType}`)\n }\n\n // Update last run and next run times\n const em = this.em().fork()\n const freshSchedule = await em.findOne(ScheduledJob, { id: schedule.id })\n \n if (freshSchedule) {\n freshSchedule.lastRunAt = new Date()\n \n // Calculate next run time\n const nextRun = recalculateNextRun(\n freshSchedule.scheduleType,\n freshSchedule.scheduleValue,\n freshSchedule.timezone\n )\n \n if (nextRun) {\n freshSchedule.nextRunAt = nextRun\n }\n \n await em.flush()\n }\n\n console.log(`[scheduler:local] \u2713 Schedule ${schedule.name} completed successfully`)\n\n // Emit completed event\n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n completedAt: new Date(),\n })\n } catch (error: unknown) {\n console.error(`[scheduler:local] \u2717 Schedule ${schedule.name} failed:`, error)\n\n // Emit failed event\n await emitSchedulerEvent('scheduler.job.failed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n error: error instanceof Error ? error.message : String(error),\n failedAt: new Date(),\n })\n\n // Still update next run time even on failure\n await this.updateNextRun(schedule)\n }\n })\n\n if (!acquired) {\n console.log(`[scheduler:local] Schedule ${schedule.name} is already locked, skipping`)\n return\n }\n }\n\n /**\n * Execute a queue-based target\n */\n private async executeQueueTarget(schedule: ScheduledJob): Promise<void> {\n if (!schedule.targetQueue) {\n throw new Error('Target queue is required for queue target type')\n }\n\n const queue = this.queueFactory(schedule.targetQueue)\n \n await queue.enqueue({\n scheduleId: schedule.id,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n payload: schedule.targetPayload || {},\n triggeredAt: new Date(),\n })\n\n console.log(`[scheduler:local] Enqueued job to queue: ${schedule.targetQueue}`)\n }\n\n /**\n * Execute a command-based target\n */\n private async executeCommandTarget(schedule: ScheduledJob): Promise<void> {\n if (!schedule.targetCommand) {\n throw new Error('Target command is required for command target type')\n }\n\n const commandBus = new CommandBus()\n \n const commandInput = {\n ...((schedule.targetPayload as Record<string, unknown>) || {}),\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n }\n \n const commandCtx = buildScheduledCommandContext(\n schedule,\n {\n resolve: (name: string) => {\n // Simple resolver that forwards to our dependencies\n if (name === 'em') return this.em()\n if (name === 'eventBus') return getGlobalEventBus()\n if (name === 'rbacService') return this.rbacService\n throw new Error(`Service not available in scheduler context: ${name}`)\n },\n } as AppContainer,\n )\n\n const result = await commandBus.execute(schedule.targetCommand, {\n input: commandInput,\n ctx: commandCtx,\n })\n\n console.log(`[scheduler:local] Executed command: ${schedule.targetCommand}`, result)\n }\n\n /**\n * Check if user/tenant has required feature\n */\n private async checkFeature(schedule: ScheduledJob): Promise<boolean> {\n if (!schedule.requireFeature) {\n return true\n }\n\n try {\n // For system-scoped schedules, no RBAC check needed\n if (schedule.scopeType === 'system') {\n return true\n }\n\n // For tenant/org scoped schedules, check if ANY admin user has the feature\n // This is a simplified check - in reality, scheduled jobs run without a user context\n // so we're just checking if the feature is enabled for the tenant\n const hasFeature = await this.rbacService.tenantHasFeature(\n schedule.tenantId,\n schedule.requireFeature,\n {\n organizationId: schedule.organizationId,\n }\n )\n\n return hasFeature\n } catch (error: unknown) {\n console.error('[scheduler:local] Feature check failed:', error)\n return false\n }\n }\n\n /**\n * Update next run time for a schedule\n */\n private async updateNextRun(schedule: ScheduledJob): Promise<void> {\n const em = this.em().fork()\n const freshSchedule = await em.findOne(ScheduledJob, { id: schedule.id })\n \n if (freshSchedule) {\n const nextRun = recalculateNextRun(\n freshSchedule.scheduleType,\n freshSchedule.scheduleValue,\n freshSchedule.timezone\n )\n \n if (nextRun) {\n freshSchedule.nextRunAt = nextRun\n await em.flush()\n }\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "AAEA,SAAS,kBAAkB;AAE3B,SAAS,oBAAoB;AAC7B,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AACnC,SAAS,0BAA0B;AACnC,SAAS,yBAAyB;AAClC,SAAS,oCAAoC;AA8BtC,MAAM,sBAAsB;AAAA,EAKjC,YACU,IACA,cACA,aACA,SAA+B,EAAE,gBAAgB,IAAM,GAC/D;AAJQ;AACA;AACA;AACA;AARV,SAAQ,YAAY;AAUlB,SAAK,eAAe,IAAI,kBAAkB,EAAE;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,QAAuB;AAC3B,QAAI,KAAK,WAAW;AAClB,cAAQ,KAAK,mCAAmC;AAChD;AAAA,IACF;AAEA,SAAK,YAAY;AACjB,YAAQ,IAAI,8CAA8C;AAC1D,YAAQ,IAAI,oCAAoC,KAAK,OAAO,cAAc,IA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c,UAAuC;AACjE,UAAM,KAAK,KAAK,GAAG,EAAE,KAAK;AAC1B,UAAM,gBAAgB,MAAM,GAAG,QAAQ,cAAc,EAAE,IAAI,SAAS,GAAG,CAAC;AAExE,QAAI,eAAe;AACjB,YAAM,UAAU;AAAA,QACd,cAAc;AAAA,QACd,cAAc;AAAA,QACd,cAAc;AAAA,MAChB;AAEA,UAAI,SAAS;AACX,sBAAc,YAAY;AAC1B,cAAM,GAAG,MAAM;AAAA,MACjB;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -3,6 +3,7 @@ import { getRedisUrlOrThrow } from "@open-mercato/shared/lib/redis/connection";
|
|
|
3
3
|
import { ScheduledJob } from "../data/entities.js";
|
|
4
4
|
import { CommandBus } from "@open-mercato/shared/lib/commands";
|
|
5
5
|
import { emitSchedulerEvent } from "../events.js";
|
|
6
|
+
import { buildScheduledCommandContext } from "../lib/commandContext.js";
|
|
6
7
|
const metadata = {
|
|
7
8
|
queue: "scheduler-execution",
|
|
8
9
|
concurrency: 5
|
|
@@ -127,16 +128,7 @@ async function executeScheduleWorker(job, ctx) {
|
|
|
127
128
|
tenantId: schedule.tenantId,
|
|
128
129
|
organizationId: schedule.organizationId
|
|
129
130
|
};
|
|
130
|
-
const commandCtx =
|
|
131
|
-
container: ctx,
|
|
132
|
-
auth: null,
|
|
133
|
-
// Scheduled commands run without user authentication
|
|
134
|
-
organizationScope: null,
|
|
135
|
-
// No organization scope filtering for scheduled commands
|
|
136
|
-
selectedOrganizationId: schedule.organizationId || null,
|
|
137
|
-
organizationIds: schedule.organizationId ? [schedule.organizationId] : null,
|
|
138
|
-
request: void 0
|
|
139
|
-
};
|
|
131
|
+
const commandCtx = buildScheduledCommandContext(schedule, ctx);
|
|
140
132
|
const commandResult = await commandBus.execute(schedule.targetCommand, {
|
|
141
133
|
input: commandInput,
|
|
142
134
|
ctx: commandCtx
|
|
@@ -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 {
|
|
5
|
-
"mappings": "AACA,SAAS,mBAAmB;AAC5B,SAAS,0BAA0B;AAEnC,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;
|
|
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 { buildScheduledCommandContext } from '../lib/commandContext.js'\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}\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 console.debug('[scheduler:execute] 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 console.error('[scheduler:execute] Invalid job payload:', {\n jobId: ctx.jobId,\n payload: job.payload,\n })\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 console.log(`[scheduler:worker] 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 console.error(`[scheduler:worker] Scope type mismatch for schedule ${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 console.error(`[scheduler:worker] Tenant ID mismatch for schedule ${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 console.error(`[scheduler:worker] Organization ID mismatch for schedule ${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 console.debug(`[scheduler:worker] 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 console.debug(`[scheduler:worker] Schedule skipped - feature not enabled: ${schedule.requireFeature}`)\n return\n }\n }\n\n // Enqueue target job or execute command\n if (schedule.targetType === 'queue' && schedule.targetQueue) {\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 // Generate a deterministic idempotency key so that if BullMQ retries\n // this worker after a crash between enqueue and DB flush, downstream\n // workers can deduplicate using this key.\n const executionTimestamp = Date.now()\n const idempotencyKey = `scheduler-${schedule.id}-${executionTimestamp}`\n\n const queuePayload = {\n ...((schedule.targetPayload as Record<string, unknown>) || {}),\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n _idempotencyKey: idempotencyKey,\n }\n\n targetJobId = await targetQueue.enqueue(queuePayload)\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 console.debug(`[scheduler:worker] 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 \n const commandInput = {\n ...((schedule.targetPayload as Record<string, unknown>) || {}),\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n }\n \n const commandCtx = buildScheduledCommandContext(schedule, ctx as unknown as AppContainer)\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 console.debug(`[scheduler:worker] Successfully executed command`, {\n scheduleId: schedule.id,\n commandId: schedule.targetCommand,\n result: commandResult.result,\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,SAAS,oCAAoC;AAGtC,MAAM,WAAuB;AAAA,EAClC,OAAO;AAAA,EACP,aAAa;AAAA;AACf;AAuCA,eAAO,sBACL,KACA,KACe;AACf,UAAQ,MAAM,uCAAuC;AAAA,IACnD,OAAO,IAAI;AAAA,IACX,eAAe,IAAI;AAA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,UAAM,GAAG,MAAM;AAEf,UAAM,mBAAmB,2BAA2B;AAAA,MAClD,IAAI,SAAS;AAAA,MACb,UAAU,SAAS;AAAA,MACnB,gBAAgB,SAAS;AAAA,MACzB,YAAY;AAAA,MACZ,WAAW,SAAS;AAAA,IACtB,CAAC;AAED,YAAQ,MAAM,gDAAgD;AAAA,MAC5D,YAAY,SAAS;AAAA,MACrB,aAAa,SAAS;AAAA,MACtB,YAAY;AAAA,IACd,CAAC;AAAA,EAEH,WAAW,SAAS,eAAe,aAAa,SAAS,eAAe;AACtE,UAAM,aAAa,IAAI,WAAW;AAElC,UAAM,eAAe;AAAA,MACnB,GAAK,SAAS,iBAA6C,CAAC;AAAA,MAC5D,UAAU,SAAS;AAAA,MACnB,gBAAgB,SAAS;AAAA,IAC3B;AAEA,UAAM,aAAa,6BAA6B,UAAU,GAA8B;AAExF,UAAM,gBAAgB,MAAM,WAAW,QAAQ,SAAS,eAAe;AAAA,MACrE,OAAO;AAAA,MACP,KAAK;AAAA,IACP,CAAC;AAGD,aAAS,YAAY,oBAAI,KAAK;AAC9B,UAAM,GAAG,MAAM;AAEf,UAAM,mBAAmB,2BAA2B;AAAA,MAClD,IAAI,SAAS;AAAA,MACb,UAAU,SAAS;AAAA,MACnB,gBAAgB,SAAS;AAAA,MACzB,WAAW,SAAS;AAAA,MACpB,eAAe,cAAc;AAAA,IAC/B,CAAC;AAED,YAAQ,MAAM,oDAAoD;AAAA,MAChE,YAAY,SAAS;AAAA,MACrB,WAAW,SAAS;AAAA,MACpB,QAAQ,cAAc;AAAA,IACxB,CAAC;AAAA,EAEH,OAAO;AACL,UAAM,IAAI,MAAM,8BAA8B;AAAA,EAChD;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/jest.config.cjs
CHANGED
|
@@ -11,6 +11,7 @@ module.exports = {
|
|
|
11
11
|
moduleNameMapper: {
|
|
12
12
|
'^@open-mercato/core/(.*)$': '<rootDir>/../core/src/$1',
|
|
13
13
|
'^@open-mercato/shared/(.*)$': '<rootDir>/../shared/src/$1',
|
|
14
|
+
'^@open-mercato/cache$': '<rootDir>/../cache/src/index.ts',
|
|
14
15
|
'^@open-mercato/queue/(.*)$': '<rootDir>/../queue/src/$1',
|
|
15
16
|
'^@open-mercato/events/(.*)$': '<rootDir>/../events/src/$1',
|
|
16
17
|
'^@open-mercato/ui/(.*)$': '<rootDir>/../ui/src/$1',
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/scheduler",
|
|
3
|
-
"version": "0.6.6-develop.
|
|
3
|
+
"version": "0.6.6-develop.6450.1.b493fb430c",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Database-managed scheduled jobs with admin UI",
|
|
6
6
|
"type": "module",
|
|
@@ -59,13 +59,13 @@
|
|
|
59
59
|
"./*/*/*/*/*/*.json": "./src/*/*/*/*/*/*.json"
|
|
60
60
|
},
|
|
61
61
|
"dependencies": {
|
|
62
|
-
"@open-mercato/events": "0.6.6-develop.
|
|
63
|
-
"@open-mercato/queue": "0.6.6-develop.
|
|
62
|
+
"@open-mercato/events": "0.6.6-develop.6450.1.b493fb430c",
|
|
63
|
+
"@open-mercato/queue": "0.6.6-develop.6450.1.b493fb430c",
|
|
64
64
|
"cron-parser": "^5.6.1"
|
|
65
65
|
},
|
|
66
66
|
"peerDependencies": {
|
|
67
67
|
"@mikro-orm/core": "^7.0.14",
|
|
68
|
-
"@open-mercato/shared": "0.6.6-develop.
|
|
68
|
+
"@open-mercato/shared": "0.6.6-develop.6450.1.b493fb430c",
|
|
69
69
|
"bullmq": "^5.0.0",
|
|
70
70
|
"ioredis": "^5.0.0",
|
|
71
71
|
"zod": ">=3.23.0"
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
}
|
|
80
80
|
},
|
|
81
81
|
"devDependencies": {
|
|
82
|
-
"@open-mercato/shared": "0.6.6-develop.
|
|
82
|
+
"@open-mercato/shared": "0.6.6-develop.6450.1.b493fb430c",
|
|
83
83
|
"@types/jest": "^30.0.0",
|
|
84
84
|
"@types/node": "^26.0.1",
|
|
85
85
|
"jest": "^30.4.2",
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { buildScheduledCommandContext } from '../commandContext'
|
|
2
|
+
|
|
3
|
+
describe('buildScheduledCommandContext', () => {
|
|
4
|
+
it('binds organization-scoped scheduled commands to the schedule tenant and organization', () => {
|
|
5
|
+
const ctx = buildScheduledCommandContext(
|
|
6
|
+
{
|
|
7
|
+
id: 'schedule-1',
|
|
8
|
+
tenantId: 'tenant-a',
|
|
9
|
+
organizationId: 'org-a',
|
|
10
|
+
scopeType: 'organization',
|
|
11
|
+
createdByUserId: 'user-a',
|
|
12
|
+
},
|
|
13
|
+
{} as Parameters<typeof buildScheduledCommandContext>[1],
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
expect(ctx.auth).toMatchObject({
|
|
17
|
+
sub: 'user-a',
|
|
18
|
+
userId: 'user-a',
|
|
19
|
+
tenantId: 'tenant-a',
|
|
20
|
+
orgId: 'org-a',
|
|
21
|
+
isSuperAdmin: false,
|
|
22
|
+
})
|
|
23
|
+
expect(ctx.organizationScope).toEqual({
|
|
24
|
+
selectedId: 'org-a',
|
|
25
|
+
filterIds: ['org-a'],
|
|
26
|
+
allowedIds: ['org-a'],
|
|
27
|
+
tenantId: 'tenant-a',
|
|
28
|
+
})
|
|
29
|
+
expect(ctx.selectedOrganizationId).toBe('org-a')
|
|
30
|
+
expect(ctx.organizationIds).toEqual(['org-a'])
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('uses a non-superadmin system actor when the schedule has no creator', () => {
|
|
34
|
+
const ctx = buildScheduledCommandContext(
|
|
35
|
+
{
|
|
36
|
+
id: 'schedule-2',
|
|
37
|
+
tenantId: 'tenant-a',
|
|
38
|
+
organizationId: null,
|
|
39
|
+
scopeType: 'tenant',
|
|
40
|
+
createdByUserId: null,
|
|
41
|
+
},
|
|
42
|
+
{} as Parameters<typeof buildScheduledCommandContext>[1],
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
expect(ctx.auth).toMatchObject({
|
|
46
|
+
sub: '00000000-0000-0000-0000-000000000000',
|
|
47
|
+
userId: '00000000-0000-0000-0000-000000000000',
|
|
48
|
+
tenantId: 'tenant-a',
|
|
49
|
+
orgId: null,
|
|
50
|
+
isSuperAdmin: false,
|
|
51
|
+
})
|
|
52
|
+
expect(ctx.organizationScope).toEqual({
|
|
53
|
+
selectedId: null,
|
|
54
|
+
filterIds: null,
|
|
55
|
+
allowedIds: null,
|
|
56
|
+
tenantId: 'tenant-a',
|
|
57
|
+
})
|
|
58
|
+
expect(ctx.organizationIds).toBeNull()
|
|
59
|
+
})
|
|
60
|
+
})
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { AuthContext } from '@open-mercato/shared/lib/auth/server'
|
|
2
|
+
import type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'
|
|
3
|
+
import type { AppContainer } from '@open-mercato/shared/lib/di/container'
|
|
4
|
+
|
|
5
|
+
const SCHEDULER_SYSTEM_ACTOR_ID = '00000000-0000-0000-0000-000000000000'
|
|
6
|
+
|
|
7
|
+
type ScheduledCommandContextSchedule = {
|
|
8
|
+
id: string
|
|
9
|
+
tenantId?: string | null
|
|
10
|
+
organizationId?: string | null
|
|
11
|
+
scopeType: 'system' | 'organization' | 'tenant'
|
|
12
|
+
createdByUserId?: string | null
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function buildScheduledCommandAuth(schedule: ScheduledCommandContextSchedule): Exclude<AuthContext, null> {
|
|
16
|
+
const actorId = schedule.createdByUserId || SCHEDULER_SYSTEM_ACTOR_ID
|
|
17
|
+
return {
|
|
18
|
+
sub: actorId,
|
|
19
|
+
userId: actorId,
|
|
20
|
+
tenantId: schedule.tenantId ?? null,
|
|
21
|
+
orgId: schedule.organizationId ?? null,
|
|
22
|
+
isSuperAdmin: false,
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function buildScheduledCommandContext(
|
|
27
|
+
schedule: ScheduledCommandContextSchedule,
|
|
28
|
+
container: AppContainer,
|
|
29
|
+
): CommandRuntimeContext {
|
|
30
|
+
const tenantId = schedule.tenantId ?? null
|
|
31
|
+
const organizationId = schedule.organizationId ?? null
|
|
32
|
+
const organizationIds = organizationId ? [organizationId] : null
|
|
33
|
+
|
|
34
|
+
return {
|
|
35
|
+
container,
|
|
36
|
+
auth: buildScheduledCommandAuth(schedule),
|
|
37
|
+
organizationScope:
|
|
38
|
+
schedule.scopeType === 'organization' && organizationId
|
|
39
|
+
? {
|
|
40
|
+
selectedId: organizationId,
|
|
41
|
+
filterIds: [organizationId],
|
|
42
|
+
allowedIds: [organizationId],
|
|
43
|
+
tenantId,
|
|
44
|
+
}
|
|
45
|
+
: {
|
|
46
|
+
selectedId: null,
|
|
47
|
+
filterIds: null,
|
|
48
|
+
allowedIds: null,
|
|
49
|
+
tenantId,
|
|
50
|
+
},
|
|
51
|
+
selectedOrganizationId: organizationId,
|
|
52
|
+
organizationIds,
|
|
53
|
+
request: undefined,
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import type { EntityManager } from '@mikro-orm/core'
|
|
2
2
|
import type { Queue } from '@open-mercato/queue'
|
|
3
3
|
import { CommandBus } from '@open-mercato/shared/lib/commands'
|
|
4
|
-
import type {
|
|
4
|
+
import type { AppContainer } from '@open-mercato/shared/lib/di/container'
|
|
5
5
|
import { ScheduledJob } from '../data/entities.js'
|
|
6
6
|
import { LocalLockStrategy } from '../lib/localLockStrategy'
|
|
7
7
|
import { recalculateNextRun } from '../lib/nextRunCalculator'
|
|
8
8
|
import { emitSchedulerEvent } from '../events.js'
|
|
9
9
|
import { getGlobalEventBus } from '@open-mercato/shared/modules/events'
|
|
10
|
+
import { buildScheduledCommandContext } from '../lib/commandContext.js'
|
|
10
11
|
|
|
11
12
|
export interface RbacServiceLike {
|
|
12
13
|
tenantHasFeature(tenantId: string | null | undefined, feature: string, opts?: { organizationId?: string | null }): Promise<boolean>
|
|
@@ -277,10 +278,9 @@ export class LocalSchedulerService {
|
|
|
277
278
|
organizationId: schedule.organizationId,
|
|
278
279
|
}
|
|
279
280
|
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
container: {
|
|
281
|
+
const commandCtx = buildScheduledCommandContext(
|
|
282
|
+
schedule,
|
|
283
|
+
{
|
|
284
284
|
resolve: (name: string) => {
|
|
285
285
|
// Simple resolver that forwards to our dependencies
|
|
286
286
|
if (name === 'em') return this.em()
|
|
@@ -288,13 +288,8 @@ export class LocalSchedulerService {
|
|
|
288
288
|
if (name === 'rbacService') return this.rbacService
|
|
289
289
|
throw new Error(`Service not available in scheduler context: ${name}`)
|
|
290
290
|
},
|
|
291
|
-
} as
|
|
292
|
-
|
|
293
|
-
organizationScope: null,
|
|
294
|
-
selectedOrganizationId: schedule.organizationId || null,
|
|
295
|
-
organizationIds: schedule.organizationId ? [schedule.organizationId] : null,
|
|
296
|
-
request: undefined,
|
|
297
|
-
}
|
|
291
|
+
} as AppContainer,
|
|
292
|
+
)
|
|
298
293
|
|
|
299
294
|
const result = await commandBus.execute(schedule.targetCommand, {
|
|
300
295
|
input: commandInput,
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'
|
|
2
|
+
import { ensureTenantScope } from '@open-mercato/shared/lib/commands/scope'
|
|
3
|
+
import { ScheduledJob } from '../../data/entities'
|
|
4
|
+
import executeScheduleWorker from '../execute-schedule.worker'
|
|
5
|
+
|
|
6
|
+
const mockCommandExecute = jest.fn()
|
|
7
|
+
|
|
8
|
+
jest.mock('@open-mercato/shared/lib/commands', () => ({
|
|
9
|
+
CommandBus: jest.fn().mockImplementation(() => ({
|
|
10
|
+
execute: mockCommandExecute,
|
|
11
|
+
})),
|
|
12
|
+
}))
|
|
13
|
+
|
|
14
|
+
jest.mock('@open-mercato/queue', () => ({
|
|
15
|
+
createQueue: jest.fn(),
|
|
16
|
+
}), { virtual: true })
|
|
17
|
+
|
|
18
|
+
jest.mock('../../events', () => ({
|
|
19
|
+
emitSchedulerEvent: jest.fn(async () => undefined),
|
|
20
|
+
}))
|
|
21
|
+
|
|
22
|
+
const scheduleId = '11111111-1111-4111-8111-111111111111'
|
|
23
|
+
|
|
24
|
+
function buildCommandSchedule(overrides: Partial<ScheduledJob> = {}): ScheduledJob {
|
|
25
|
+
const schedule = new ScheduledJob()
|
|
26
|
+
schedule.id = scheduleId
|
|
27
|
+
schedule.name = 'Scoped command'
|
|
28
|
+
schedule.scopeType = 'organization'
|
|
29
|
+
schedule.tenantId = 'tenant-a'
|
|
30
|
+
schedule.organizationId = 'org-a'
|
|
31
|
+
schedule.isEnabled = true
|
|
32
|
+
schedule.targetType = 'command'
|
|
33
|
+
schedule.targetCommand = 'scheduler.test.assert-tenant-scope'
|
|
34
|
+
schedule.targetPayload = { checkedTenantId: 'tenant-b' }
|
|
35
|
+
schedule.scheduleType = 'cron'
|
|
36
|
+
schedule.scheduleValue = '* * * * *'
|
|
37
|
+
schedule.timezone = 'UTC'
|
|
38
|
+
schedule.sourceType = 'user'
|
|
39
|
+
schedule.createdAt = new Date('2026-01-01T00:00:00.000Z')
|
|
40
|
+
schedule.updatedAt = new Date('2026-01-01T00:00:00.000Z')
|
|
41
|
+
Object.assign(schedule, overrides)
|
|
42
|
+
return schedule
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function buildWorkerContext(schedule: ScheduledJob) {
|
|
46
|
+
const em = {
|
|
47
|
+
findOne: jest.fn(async () => schedule),
|
|
48
|
+
flush: jest.fn(async () => undefined),
|
|
49
|
+
}
|
|
50
|
+
const rbacService = {
|
|
51
|
+
tenantHasFeature: jest.fn(async () => true),
|
|
52
|
+
}
|
|
53
|
+
return {
|
|
54
|
+
context: {
|
|
55
|
+
jobId: 'worker-job-1',
|
|
56
|
+
attemptNumber: 1,
|
|
57
|
+
resolve: jest.fn((name: string) => {
|
|
58
|
+
if (name === 'em') return em
|
|
59
|
+
if (name === 'rbacService') return rbacService
|
|
60
|
+
throw new Error(`Unexpected dependency: ${name}`)
|
|
61
|
+
}),
|
|
62
|
+
},
|
|
63
|
+
em,
|
|
64
|
+
rbacService,
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
describe('executeScheduleWorker command scope', () => {
|
|
69
|
+
afterEach(() => {
|
|
70
|
+
mockCommandExecute.mockReset()
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('runs scheduled commands with schedule-bound tenant auth so command guards enforce tenant scope (#3899)', async () => {
|
|
74
|
+
mockCommandExecute.mockImplementation(async (_commandId, { input, ctx }) => {
|
|
75
|
+
ensureTenantScope(ctx, String((input as { checkedTenantId: string }).checkedTenantId))
|
|
76
|
+
return { result: { ok: true }, logEntry: null }
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
const schedule = buildCommandSchedule()
|
|
80
|
+
const { context, em } = buildWorkerContext(schedule)
|
|
81
|
+
|
|
82
|
+
await expect(
|
|
83
|
+
executeScheduleWorker(
|
|
84
|
+
{
|
|
85
|
+
id: 'queued-job-1',
|
|
86
|
+
queue: 'scheduler-execution',
|
|
87
|
+
payload: {
|
|
88
|
+
scheduleId,
|
|
89
|
+
tenantId: 'tenant-a',
|
|
90
|
+
organizationId: 'org-a',
|
|
91
|
+
scopeType: 'organization',
|
|
92
|
+
},
|
|
93
|
+
attempts: 0,
|
|
94
|
+
createdAt: Date.now(),
|
|
95
|
+
},
|
|
96
|
+
context,
|
|
97
|
+
),
|
|
98
|
+
).rejects.toBeInstanceOf(CrudHttpError)
|
|
99
|
+
|
|
100
|
+
expect(em.flush).not.toHaveBeenCalled()
|
|
101
|
+
})
|
|
102
|
+
})
|
|
@@ -4,9 +4,9 @@ import { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'
|
|
|
4
4
|
import type { EntityManager } from '@mikro-orm/core'
|
|
5
5
|
import { ScheduledJob } from '../data/entities.js'
|
|
6
6
|
import { CommandBus } from '@open-mercato/shared/lib/commands'
|
|
7
|
-
import type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'
|
|
8
7
|
import type { AppContainer } from '@open-mercato/shared/lib/di/container'
|
|
9
8
|
import { emitSchedulerEvent } from '../events.js'
|
|
9
|
+
import { buildScheduledCommandContext } from '../lib/commandContext.js'
|
|
10
10
|
|
|
11
11
|
// Worker metadata for auto-discovery
|
|
12
12
|
export const metadata: WorkerMeta = {
|
|
@@ -211,16 +211,7 @@ export default async function executeScheduleWorker(
|
|
|
211
211
|
organizationId: schedule.organizationId,
|
|
212
212
|
}
|
|
213
213
|
|
|
214
|
-
|
|
215
|
-
// Scheduled commands run without user auth but with proper tenant/org scope
|
|
216
|
-
const commandCtx: CommandRuntimeContext = {
|
|
217
|
-
container: ctx as unknown as AppContainer,
|
|
218
|
-
auth: null, // Scheduled commands run without user authentication
|
|
219
|
-
organizationScope: null, // No organization scope filtering for scheduled commands
|
|
220
|
-
selectedOrganizationId: schedule.organizationId || null,
|
|
221
|
-
organizationIds: schedule.organizationId ? [schedule.organizationId] : null,
|
|
222
|
-
request: undefined,
|
|
223
|
-
}
|
|
214
|
+
const commandCtx = buildScheduledCommandContext(schedule, ctx as unknown as AppContainer)
|
|
224
215
|
|
|
225
216
|
const commandResult = await commandBus.execute(schedule.targetCommand, {
|
|
226
217
|
input: commandInput,
|