@open-mercato/scheduler 0.6.7-develop.6870.1.b69802067a → 0.6.8-develop.6874.1.982d6097d8

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.
@@ -3,36 +3,58 @@ const logger = createLogger("scheduler").child({ component: "local" });
3
3
  class LocalLockStrategy {
4
4
  constructor(em) {
5
5
  this.em = em;
6
+ // Process-local by construction, so it only guards a single strategy
7
+ // instance. Invariant relied upon: exactly one LocalLockStrategy exists per
8
+ // process, because the only construction site is LocalSchedulerService
9
+ // (an Awilix singleton) and only the CLI entry points start the polling
10
+ // engine. A caller that resolves a second container would silently get an
11
+ // independent guard — see the single-instance warning in
12
+ // LocalSchedulerService.start().
13
+ this.heldKeys = /* @__PURE__ */ new Set();
6
14
  }
7
15
  /**
8
- * Execute a function under a PostgreSQL advisory lock.
16
+ * Execute a function under a mutual-exclusion lock.
9
17
  *
10
- * IMPORTANT: Uses transaction-scoped advisory locks (`pg_try_advisory_xact_lock`)
11
- * to avoid connection pool/session mismatch issues. The lock is automatically
12
- * released when the transaction ends.
18
+ * In-process exclusion for the whole duration of `fn` comes from `heldKeys`
19
+ * (this strategy is single-instance by contract). The transaction-scoped
20
+ * advisory lock (`pg_try_advisory_xact_lock`) only guards the claim itself
21
+ * against a concurrently claiming process and is released when the short
22
+ * claim transaction commits, BEFORE `fn` runs.
23
+ *
24
+ * IMPORTANT: `fn` must NOT run inside that transaction. Holding the
25
+ * transaction open across `fn` leaves the connection idle-in-transaction
26
+ * while `fn` awaits non-DB work; the pool's default
27
+ * `idle_in_transaction_session_timeout` (120s) then makes Postgres kill the
28
+ * connection (FATAL 25P03), which crashes the scheduler process.
13
29
  */
14
30
  async runWithLock(key, fn) {
15
- const em = this.em().fork();
16
- const hash = this.hashString(key);
17
- let lockAcquired = false;
31
+ if (this.heldKeys.has(key)) {
32
+ return { acquired: false };
33
+ }
34
+ this.heldKeys.add(key);
18
35
  try {
19
- return await em.transactional(async (txEm) => {
20
- const result = await txEm.getConnection().execute(
21
- `SELECT pg_try_advisory_xact_lock(?) as acquired`,
22
- [hash]
23
- );
24
- const acquired = result[0]?.acquired === true;
25
- if (!acquired) return { acquired: false };
26
- lockAcquired = true;
27
- const fnResult = await fn();
28
- return { acquired: true, result: fnResult };
29
- });
30
- } catch (error) {
31
- if (lockAcquired) {
32
- throw error;
36
+ const em = this.em().fork();
37
+ const hash = this.hashString(key);
38
+ let claimed = false;
39
+ try {
40
+ claimed = await em.transactional(async (txEm) => {
41
+ const result = await txEm.getConnection().execute(
42
+ `SELECT pg_try_advisory_xact_lock(?) as acquired`,
43
+ [hash]
44
+ );
45
+ return result[0]?.acquired === true;
46
+ });
47
+ } catch (error) {
48
+ logger.error("Failed to acquire lock", { lockKey: key, err: error });
49
+ return { acquired: false };
33
50
  }
34
- logger.error("Failed to acquire lock", { lockKey: key, err: error });
35
- return { acquired: false };
51
+ if (!claimed) {
52
+ return { acquired: false };
53
+ }
54
+ const fnResult = await fn();
55
+ return { acquired: true, result: fnResult };
56
+ } finally {
57
+ this.heldKeys.delete(key);
36
58
  }
37
59
  }
38
60
  /**
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/scheduler/lib/localLockStrategy.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'local' })\n\n/**\n * PostgreSQL advisory lock strategy for single-instance or local development\n */\nexport class LocalLockStrategy {\n constructor(private em: () => EntityManager) {}\n\n /**\n * Execute a function under a PostgreSQL advisory lock.\n *\n * IMPORTANT: Uses transaction-scoped advisory locks (`pg_try_advisory_xact_lock`)\n * to avoid connection pool/session mismatch issues. The lock is automatically\n * released when the transaction ends.\n */\n async runWithLock<T>(key: string, fn: () => Promise<T>): Promise<{ acquired: boolean; result?: T }> {\n const em = this.em().fork()\n const hash = this.hashString(key)\n let lockAcquired = false\n\n try {\n return await em.transactional(async (txEm) => {\n const result = await txEm.getConnection().execute<{ acquired: boolean }[]>(\n `SELECT pg_try_advisory_xact_lock(?) as acquired`,\n [hash],\n )\n\n const acquired = result[0]?.acquired === true\n if (!acquired) return { acquired: false }\n lockAcquired = true\n\n const fnResult = await fn()\n return { acquired: true, result: fnResult }\n })\n } catch (error) {\n if (lockAcquired) {\n throw error\n }\n\n logger.error('Failed to acquire lock', { lockKey: key, err: error })\n return { acquired: false }\n }\n }\n\n /**\n * Convert string to integer hash for PostgreSQL advisory locks\n * PostgreSQL advisory locks use bigint, so we need to hash the string\n */\n private hashString(str: string): number {\n let hash = 0\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i)\n hash = ((hash << 5) - hash) + char\n hash = hash & hash // Convert to 32bit integer\n }\n return Math.abs(hash)\n }\n}\n"],
5
- "mappings": "AACA,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,QAAQ,CAAC;AAK9D,MAAM,kBAAkB;AAAA,EAC7B,YAAoB,IAAyB;AAAzB;AAAA,EAA0B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAS9C,MAAM,YAAe,KAAa,IAAkE;AAClG,UAAM,KAAK,KAAK,GAAG,EAAE,KAAK;AAC1B,UAAM,OAAO,KAAK,WAAW,GAAG;AAChC,QAAI,eAAe;AAEnB,QAAI;AACF,aAAO,MAAM,GAAG,cAAc,OAAO,SAAS;AAC5C,cAAM,SAAS,MAAM,KAAK,cAAc,EAAE;AAAA,UACxC;AAAA,UACA,CAAC,IAAI;AAAA,QACP;AAEA,cAAM,WAAW,OAAO,CAAC,GAAG,aAAa;AACzC,YAAI,CAAC,SAAU,QAAO,EAAE,UAAU,MAAM;AACxC,uBAAe;AAEf,cAAM,WAAW,MAAM,GAAG;AAC1B,eAAO,EAAE,UAAU,MAAM,QAAQ,SAAS;AAAA,MAC5C,CAAC;AAAA,IACH,SAAS,OAAO;AACd,UAAI,cAAc;AAChB,cAAM;AAAA,MACR;AAEA,aAAO,MAAM,0BAA0B,EAAE,SAAS,KAAK,KAAK,MAAM,CAAC;AACnE,aAAO,EAAE,UAAU,MAAM;AAAA,IAC3B;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,WAAW,KAAqB;AACtC,QAAI,OAAO;AACX,aAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,YAAM,OAAO,IAAI,WAAW,CAAC;AAC7B,cAAS,QAAQ,KAAK,OAAQ;AAC9B,aAAO,OAAO;AAAA,IAChB;AACA,WAAO,KAAK,IAAI,IAAI;AAAA,EACtB;AACF;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'local' })\n\n/**\n * Mutual-exclusion strategy for single-instance or local development.\n *\n * Exclusion for the duration of the guarded run is IN-PROCESS (`heldKeys`).\n * The PostgreSQL advisory lock only serialises concurrent *claims* \u2014 it is\n * transaction-scoped and released as soon as the short claim transaction\n * commits, before the guarded function runs. It therefore does NOT protect\n * against two processes executing the same key concurrently; that matches the\n * documented single-instance contract of the local scheduler strategy, and\n * `LocalSchedulerService.start()` warns about it at startup.\n */\nexport class LocalLockStrategy {\n // Process-local by construction, so it only guards a single strategy\n // instance. Invariant relied upon: exactly one LocalLockStrategy exists per\n // process, because the only construction site is LocalSchedulerService\n // (an Awilix singleton) and only the CLI entry points start the polling\n // engine. A caller that resolves a second container would silently get an\n // independent guard \u2014 see the single-instance warning in\n // LocalSchedulerService.start().\n private heldKeys = new Set<string>()\n\n constructor(private em: () => EntityManager) {}\n\n /**\n * Execute a function under a mutual-exclusion lock.\n *\n * In-process exclusion for the whole duration of `fn` comes from `heldKeys`\n * (this strategy is single-instance by contract). The transaction-scoped\n * advisory lock (`pg_try_advisory_xact_lock`) only guards the claim itself\n * against a concurrently claiming process and is released when the short\n * claim transaction commits, BEFORE `fn` runs.\n *\n * IMPORTANT: `fn` must NOT run inside that transaction. Holding the\n * transaction open across `fn` leaves the connection idle-in-transaction\n * while `fn` awaits non-DB work; the pool's default\n * `idle_in_transaction_session_timeout` (120s) then makes Postgres kill the\n * connection (FATAL 25P03), which crashes the scheduler process.\n */\n async runWithLock<T>(key: string, fn: () => Promise<T>): Promise<{ acquired: boolean; result?: T }> {\n if (this.heldKeys.has(key)) {\n return { acquired: false }\n }\n // Reserve synchronously before the async claim so a concurrent in-process\n // caller cannot slip in between our claim transaction committing (which\n // releases the advisory xact lock) and the start of `fn`.\n this.heldKeys.add(key)\n\n try {\n const em = this.em().fork()\n const hash = this.hashString(key)\n let claimed = false\n\n try {\n claimed = await em.transactional(async (txEm) => {\n const result = await txEm.getConnection().execute<{ acquired: boolean }[]>(\n `SELECT pg_try_advisory_xact_lock(?) as acquired`,\n [hash],\n )\n return result[0]?.acquired === true\n })\n } catch (error) {\n logger.error('Failed to acquire lock', { lockKey: key, err: error })\n return { acquired: false }\n }\n\n if (!claimed) {\n return { acquired: false }\n }\n\n const fnResult = await fn()\n return { acquired: true, result: fnResult }\n } finally {\n this.heldKeys.delete(key)\n }\n }\n\n /**\n * Convert string to integer hash for PostgreSQL advisory locks\n * PostgreSQL advisory locks use bigint, so we need to hash the string\n */\n private hashString(str: string): number {\n let hash = 0\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i)\n hash = ((hash << 5) - hash) + char\n hash = hash & hash // Convert to 32bit integer\n }\n return Math.abs(hash)\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,QAAQ,CAAC;AAa9D,MAAM,kBAAkB;AAAA,EAU7B,YAAoB,IAAyB;AAAzB;AAFpB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAQ,WAAW,oBAAI,IAAY;AAAA,EAEW;AAAA;AAAA;AAAA;AAAA;AAAA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ine", { pollIntervalMs: this.config.pollIntervalMs });
31
+ logger.warn(
32
+ "Local scheduler strategy provides no cross-process protection: duplicate prevention is in-process only, so a second process polling the same database will execute the same due schedule. Run exactly one process with QUEUE_STRATEGY=local, or use the async strategy for distributed locking."
33
+ );
31
34
  await this.poll();
32
35
  this.pollTimer = setInterval(() => {
33
36
  this.poll().catch((error) => {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/scheduler/services/localSchedulerService.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport type { Queue } from '@open-mercato/queue'\nimport { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { ScheduledJob } from '../data/entities.js'\nimport { LocalLockStrategy } from '../lib/localLockStrategy'\nimport { recalculateNextRun } from '../lib/nextRunCalculator'\nimport { emitSchedulerEvent } from '../events.js'\nimport { getGlobalEventBus } from '@open-mercato/shared/modules/events'\nimport { assertSchedulerSafeCommandAuthorized } from '../lib/scheduler-safe-commands.js'\nimport { buildScheduledCommandContext } from '../lib/commandContext.js'\nimport { buildQueueTargetPayload, buildSchedulerIdempotencyKey } from '../lib/queueTargetPayload.js'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'local' })\n\nexport interface RbacServiceLike {\n tenantHasFeature(tenantId: string | null | undefined, feature: string, opts?: { organizationId?: string | null }): Promise<boolean>\n userHasAllFeatures(userId: string, required: readonly string[], scope: { tenantId: string | null; organizationId: string | null }): Promise<boolean>\n}\n\nexport interface LocalSchedulerConfig {\n pollIntervalMs: number\n}\n\n/**\n * Local scheduler service for development\n * \n * This service polls the database for due schedules and executes them locally\n * without requiring Redis. Perfect for local development.\n * \n * Features:\n * - PostgreSQL polling (configurable interval, default 30s)\n * - 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 logger.warn('Polling engine already running')\n return\n }\n\n this.isRunning = true\n logger.info('Starting polling engine', { pollIntervalMs: this.config.pollIntervalMs })\n\n // Run initial poll immediately\n await this.poll()\n\n // Schedule recurring polls\n this.pollTimer = setInterval(() => {\n this.poll().catch((error) => {\n logger.error('Poll error', { err: error })\n })\n }, this.config.pollIntervalMs)\n\n logger.info('Polling engine started')\n }\n\n /**\n * Stop the local scheduler\n */\n async stop(): Promise<void> {\n logger.info('Stopping polling engine')\n this.isRunning = false\n \n if (this.pollTimer) {\n clearInterval(this.pollTimer)\n this.pollTimer = undefined\n }\n\n logger.info('Polling engine stopped')\n }\n\n /**\n * Poll for due schedules and execute them\n */\n private async poll(): Promise<void> {\n if (!this.isRunning) {\n return\n }\n\n const em = this.em().fork()\n\n try {\n // Find enabled schedules that are due (limited to avoid spikes after outages)\n const dueSchedules = await em.find(ScheduledJob, {\n isEnabled: true,\n deletedAt: null,\n nextRunAt: { $lte: new Date() },\n }, {\n limit: 100,\n orderBy: { nextRunAt: 'ASC' },\n })\n\n if (dueSchedules.length === 0) {\n logger.debug('No due schedules')\n return\n }\n\n logger.info('Found due schedules', { count: dueSchedules.length })\n\n // Execute each schedule\n for (const schedule of dueSchedules) {\n await this.executeSchedule(schedule)\n }\n } catch (error: unknown) {\n logger.error('Poll failed', { err: error })\n }\n }\n\n /**\n * Execute a single schedule\n */\n private async executeSchedule(schedule: ScheduledJob): Promise<void> {\n const lockKey = `schedule:${schedule.id}`\n const scheduleLogger = logger.child({ scheduleId: schedule.id, scheduleName: schedule.name })\n\n const { acquired } = await this.lockStrategy.runWithLock(lockKey, async () => {\n scheduleLogger.info('Executing schedule')\n\n // Emit started event\n await emitSchedulerEvent('scheduler.job.started', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n triggerType: 'scheduled',\n startedAt: new Date(),\n })\n\n try {\n // Check feature flag if required\n if (schedule.requireFeature) {\n const hasFeature = await this.checkFeature(schedule)\n \n if (!hasFeature) {\n scheduleLogger.info('Schedule skipped: missing required feature', { requireFeature: schedule.requireFeature })\n \n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n reason: `Missing required feature: ${schedule.requireFeature}`,\n skippedAt: new Date(),\n })\n\n // Still update next run time\n await this.updateNextRun(schedule)\n return\n }\n }\n\n // Execute based on target type\n if (schedule.targetType === 'queue') {\n await this.executeQueueTarget(schedule)\n } else if (schedule.targetType === 'command') {\n await this.executeCommandTarget(schedule)\n } else {\n throw new Error(`Unknown target type: ${schedule.targetType}`)\n }\n\n // Update last run and next run times\n const em = this.em().fork()\n const freshSchedule = await em.findOne(ScheduledJob, { id: schedule.id })\n \n if (freshSchedule) {\n freshSchedule.lastRunAt = new Date()\n \n // Calculate next run time\n const nextRun = recalculateNextRun(\n freshSchedule.scheduleType,\n freshSchedule.scheduleValue,\n freshSchedule.timezone\n )\n \n if (nextRun) {\n freshSchedule.nextRunAt = nextRun\n }\n \n await em.flush()\n }\n\n scheduleLogger.info('Schedule completed')\n\n // Emit completed event\n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n completedAt: new Date(),\n })\n } catch (error: unknown) {\n scheduleLogger.error('Schedule failed', { err: error })\n\n // Emit failed event\n await emitSchedulerEvent('scheduler.job.failed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n error: error instanceof Error ? error.message : String(error),\n failedAt: new Date(),\n })\n\n // Still update next run time even on failure\n await this.updateNextRun(schedule)\n }\n })\n\n if (!acquired) {\n scheduleLogger.debug('Schedule already locked, skipping')\n return\n }\n }\n\n /**\n * Execute a queue-based target\n */\n private async executeQueueTarget(schedule: ScheduledJob): Promise<void> {\n if (!schedule.targetQueue) {\n throw new Error('Target queue is required for queue target type')\n }\n\n const queue = this.queueFactory(schedule.targetQueue)\n\n // Deliver the same flat contract as the asynchronous execute-schedule\n // worker: targetPayload fields on the root, scheduler-owned scope and\n // idempotency fields applied last. Local mode runs each firing exactly\n // once, so the firing timestamp is a valid logical execution key.\n await queue.enqueue(buildQueueTargetPayload({\n targetPayload: schedule.targetPayload,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n idempotencyKey: buildSchedulerIdempotencyKey(schedule.id, Date.now()),\n }))\n\n logger.info('Enqueued job to target queue', { scheduleId: schedule.id, targetQueue: schedule.targetQueue })\n }\n\n /**\n * Execute a command-based target\n */\n private async executeCommandTarget(schedule: ScheduledJob): Promise<void> {\n if (!schedule.targetCommand) {\n throw new Error('Target command is required for command target type')\n }\n\n const commandBus = new CommandBus()\n const actorUserId = typeof schedule.createdByUserId === 'string' ? schedule.createdByUserId.trim() : ''\n await assertSchedulerSafeCommandAuthorized({\n commandId: schedule.targetCommand,\n actorUserId,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n rbacService: this.rbacService,\n })\n \n const commandInput = {\n ...((schedule.targetPayload as Record<string, unknown>) || {}),\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n }\n \n // Build the schedule-scoped command context after the allowlist/RBAC gate.\n const commandCtx = buildScheduledCommandContext(\n schedule,\n {\n resolve: (name: string) => {\n // Simple resolver that forwards to our dependencies\n if (name === 'em') return this.em()\n if (name === 'eventBus') return getGlobalEventBus()\n if (name === 'rbacService') return this.rbacService\n throw new Error(`Service not available in scheduler context: ${name}`)\n },\n } as AppContainer,\n )\n\n await commandBus.execute(schedule.targetCommand, {\n input: commandInput,\n ctx: commandCtx,\n })\n\n logger.info('Executed command', { scheduleId: schedule.id, targetCommand: schedule.targetCommand })\n }\n\n /**\n * Check if user/tenant has required feature\n */\n private async checkFeature(schedule: ScheduledJob): Promise<boolean> {\n if (!schedule.requireFeature) {\n return true\n }\n\n try {\n // For system-scoped schedules, no RBAC check needed\n if (schedule.scopeType === 'system') {\n return true\n }\n\n // For tenant/org scoped schedules, check if ANY admin user has the feature\n // This is a simplified check - in reality, scheduled jobs run without a user context\n // so we're just checking if the feature is enabled for the tenant\n const hasFeature = await this.rbacService.tenantHasFeature(\n schedule.tenantId,\n schedule.requireFeature,\n {\n organizationId: schedule.organizationId,\n }\n )\n\n return hasFeature\n } catch (error: unknown) {\n logger.error('Feature check failed', { scheduleId: schedule.id, err: error })\n return false\n }\n }\n\n /**\n * Update next run time for a schedule\n */\n private async updateNextRun(schedule: ScheduledJob): Promise<void> {\n const em = this.em().fork()\n const freshSchedule = await em.findOne(ScheduledJob, { id: schedule.id })\n \n if (freshSchedule) {\n const nextRun = recalculateNextRun(\n freshSchedule.scheduleType,\n freshSchedule.scheduleValue,\n freshSchedule.timezone\n )\n \n if (nextRun) {\n freshSchedule.nextRunAt = nextRun\n await em.flush()\n }\n }\n }\n}\n"],
5
- "mappings": "AAEA,SAAS,kBAAkB;AAE3B,SAAS,oBAAoB;AAC7B,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AACnC,SAAS,0BAA0B;AACnC,SAAS,yBAAyB;AAClC,SAAS,4CAA4C;AACrD,SAAS,oCAAoC;AAC7C,SAAS,yBAAyB,oCAAoC;AAC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;AACxC,gBAAM,IAAI,MAAM,+CAA+C,IAAI,EAAE;AAAA,QACvE;AAAA,MACF;AAAA,IACF;AAEA,UAAM,WAAW,QAAQ,SAAS,eAAe;AAAA,MAC/C,OAAO;AAAA,MACP,KAAK;AAAA,IACP,CAAC;AAED,WAAO,KAAK,oBAAoB,EAAE,YAAY,SAAS,IAAI,eAAe,SAAS,cAAc,CAAC;AAAA,EACpG;AAAA;AAAA;AAAA;AAAA,EAKA,MAAc,aAAa,UAA0C;AACnE,QAAI,CAAC,SAAS,gBAAgB;AAC5B,aAAO;AAAA,IACT;AAEA,QAAI;AAEF,UAAI,SAAS,cAAc,UAAU;AACnC,eAAO;AAAA,MACT;AAKA,YAAM,aAAa,MAAM,KAAK,YAAY;AAAA,QACxC,SAAS;AAAA,QACT,SAAS;AAAA,QACT;AAAA,UACE,gBAAgB,SAAS;AAAA,QAC3B;AAAA,MACF;AAEA,aAAO;AAAA,IACT,SAAS,OAAgB;AACvB,aAAO,MAAM,wBAAwB,EAAE,YAAY,SAAS,IAAI,KAAK,MAAM,CAAC;AAC5E,aAAO;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAc,cAAc,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;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport type { Queue } from '@open-mercato/queue'\nimport { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { ScheduledJob } from '../data/entities.js'\nimport { LocalLockStrategy } from '../lib/localLockStrategy'\nimport { recalculateNextRun } from '../lib/nextRunCalculator'\nimport { emitSchedulerEvent } from '../events.js'\nimport { getGlobalEventBus } from '@open-mercato/shared/modules/events'\nimport { assertSchedulerSafeCommandAuthorized } from '../lib/scheduler-safe-commands.js'\nimport { buildScheduledCommandContext } from '../lib/commandContext.js'\nimport { buildQueueTargetPayload, buildSchedulerIdempotencyKey } from '../lib/queueTargetPayload.js'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'local' })\n\nexport interface RbacServiceLike {\n tenantHasFeature(tenantId: string | null | undefined, feature: string, opts?: { organizationId?: string | null }): Promise<boolean>\n userHasAllFeatures(userId: string, required: readonly string[], scope: { tenantId: string | null; organizationId: string | null }): Promise<boolean>\n}\n\nexport interface LocalSchedulerConfig {\n pollIntervalMs: number\n}\n\n/**\n * Local scheduler service for development\n * \n * This service polls the database for due schedules and executes them locally\n * without requiring Redis. Perfect for local development.\n * \n * Features:\n * - PostgreSQL polling (configurable interval, default 30s)\n * - In-process duplicate prevention across overlapping poll ticks\n * - Supports both queue and command targets\n * - Emits the same events as async strategy\n * - Updates nextRunAt after execution\n *\n * Limitations:\n * - Polling delay (up to configured interval)\n * - Single instance only (no distributed locking across instances). Duplicate\n * prevention is in-process only: the advisory lock serialises the claim, not\n * the execution, and nextRunAt is advanced only after the target has run, so\n * two processes polling the same database will both execute a due schedule.\n * Run exactly one process with QUEUE_STRATEGY=local, or use the async\n * strategy, which locks across instances.\n * - Higher database load than async strategy\n * \n * Set QUEUE_STRATEGY=local to use this service.\n */\nexport class LocalSchedulerService {\n private isRunning = false\n private pollTimer?: NodeJS.Timeout\n private lockStrategy: LocalLockStrategy\n\n constructor(\n private em: () => EntityManager,\n private queueFactory: (name: string) => Queue,\n private rbacService: RbacServiceLike,\n private config: LocalSchedulerConfig = { pollIntervalMs: 30000 },\n ) {\n this.lockStrategy = new LocalLockStrategy(em)\n }\n\n /**\n * Start the local scheduler polling engine\n */\n async start(): Promise<void> {\n if (this.isRunning) {\n logger.warn('Polling engine already running')\n return\n }\n\n this.isRunning = true\n logger.info('Starting polling engine', { pollIntervalMs: this.config.pollIntervalMs })\n logger.warn(\n 'Local scheduler strategy provides no cross-process protection: duplicate prevention is in-process only, so a second process polling the same database will execute the same due schedule. Run exactly one process with QUEUE_STRATEGY=local, or use the async strategy for distributed locking.',\n )\n\n // Run initial poll immediately\n await this.poll()\n\n // Schedule recurring polls\n this.pollTimer = setInterval(() => {\n this.poll().catch((error) => {\n logger.error('Poll error', { err: error })\n })\n }, this.config.pollIntervalMs)\n\n logger.info('Polling engine started')\n }\n\n /**\n * Stop the local scheduler\n */\n async stop(): Promise<void> {\n logger.info('Stopping polling engine')\n this.isRunning = false\n \n if (this.pollTimer) {\n clearInterval(this.pollTimer)\n this.pollTimer = undefined\n }\n\n logger.info('Polling engine stopped')\n }\n\n /**\n * Poll for due schedules and execute them\n */\n private async poll(): Promise<void> {\n if (!this.isRunning) {\n return\n }\n\n const em = this.em().fork()\n\n try {\n // Find enabled schedules that are due (limited to avoid spikes after outages)\n const dueSchedules = await em.find(ScheduledJob, {\n isEnabled: true,\n deletedAt: null,\n nextRunAt: { $lte: new Date() },\n }, {\n limit: 100,\n orderBy: { nextRunAt: 'ASC' },\n })\n\n if (dueSchedules.length === 0) {\n logger.debug('No due schedules')\n return\n }\n\n logger.info('Found due schedules', { count: dueSchedules.length })\n\n // Execute each schedule\n for (const schedule of dueSchedules) {\n await this.executeSchedule(schedule)\n }\n } catch (error: unknown) {\n logger.error('Poll failed', { err: error })\n }\n }\n\n /**\n * Execute a single schedule\n */\n private async executeSchedule(schedule: ScheduledJob): Promise<void> {\n const lockKey = `schedule:${schedule.id}`\n const scheduleLogger = logger.child({ scheduleId: schedule.id, scheduleName: schedule.name })\n\n const { acquired } = await this.lockStrategy.runWithLock(lockKey, async () => {\n scheduleLogger.info('Executing schedule')\n\n // Emit started event\n await emitSchedulerEvent('scheduler.job.started', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n triggerType: 'scheduled',\n startedAt: new Date(),\n })\n\n try {\n // Check feature flag if required\n if (schedule.requireFeature) {\n const hasFeature = await this.checkFeature(schedule)\n \n if (!hasFeature) {\n scheduleLogger.info('Schedule skipped: missing required feature', { requireFeature: schedule.requireFeature })\n \n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n reason: `Missing required feature: ${schedule.requireFeature}`,\n skippedAt: new Date(),\n })\n\n // Still update next run time\n await this.updateNextRun(schedule)\n return\n }\n }\n\n // Execute based on target type\n if (schedule.targetType === 'queue') {\n await this.executeQueueTarget(schedule)\n } else if (schedule.targetType === 'command') {\n await this.executeCommandTarget(schedule)\n } else {\n throw new Error(`Unknown target type: ${schedule.targetType}`)\n }\n\n // Update last run and next run times\n const em = this.em().fork()\n const freshSchedule = await em.findOne(ScheduledJob, { id: schedule.id })\n \n if (freshSchedule) {\n freshSchedule.lastRunAt = new Date()\n \n // Calculate next run time\n const nextRun = recalculateNextRun(\n freshSchedule.scheduleType,\n freshSchedule.scheduleValue,\n freshSchedule.timezone\n )\n \n if (nextRun) {\n freshSchedule.nextRunAt = nextRun\n }\n \n await em.flush()\n }\n\n scheduleLogger.info('Schedule completed')\n\n // Emit completed event\n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n completedAt: new Date(),\n })\n } catch (error: unknown) {\n scheduleLogger.error('Schedule failed', { err: error })\n\n // Emit failed event\n await emitSchedulerEvent('scheduler.job.failed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n error: error instanceof Error ? error.message : String(error),\n failedAt: new Date(),\n })\n\n // Still update next run time even on failure\n await this.updateNextRun(schedule)\n }\n })\n\n if (!acquired) {\n scheduleLogger.debug('Schedule already locked, skipping')\n return\n }\n }\n\n /**\n * Execute a queue-based target\n */\n private async executeQueueTarget(schedule: ScheduledJob): Promise<void> {\n if (!schedule.targetQueue) {\n throw new Error('Target queue is required for queue target type')\n }\n\n const queue = this.queueFactory(schedule.targetQueue)\n\n // Deliver the same flat contract as the asynchronous execute-schedule\n // worker: targetPayload fields on the root, scheduler-owned scope and\n // idempotency fields applied last. Local mode runs each firing exactly\n // once, so the firing timestamp is a valid logical execution key.\n await queue.enqueue(buildQueueTargetPayload({\n targetPayload: schedule.targetPayload,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n idempotencyKey: buildSchedulerIdempotencyKey(schedule.id, Date.now()),\n }))\n\n logger.info('Enqueued job to target queue', { scheduleId: schedule.id, targetQueue: schedule.targetQueue })\n }\n\n /**\n * Execute a command-based target\n */\n private async executeCommandTarget(schedule: ScheduledJob): Promise<void> {\n if (!schedule.targetCommand) {\n throw new Error('Target command is required for command target type')\n }\n\n const commandBus = new CommandBus()\n const actorUserId = typeof schedule.createdByUserId === 'string' ? schedule.createdByUserId.trim() : ''\n await assertSchedulerSafeCommandAuthorized({\n commandId: schedule.targetCommand,\n actorUserId,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n rbacService: this.rbacService,\n })\n \n const commandInput = {\n ...((schedule.targetPayload as Record<string, unknown>) || {}),\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n }\n \n // Build the schedule-scoped command context after the allowlist/RBAC gate.\n const commandCtx = buildScheduledCommandContext(\n schedule,\n {\n resolve: (name: string) => {\n // Simple resolver that forwards to our dependencies\n if (name === 'em') return this.em()\n if (name === 'eventBus') return getGlobalEventBus()\n if (name === 'rbacService') return this.rbacService\n throw new Error(`Service not available in scheduler context: ${name}`)\n },\n } as AppContainer,\n )\n\n await commandBus.execute(schedule.targetCommand, {\n input: commandInput,\n ctx: commandCtx,\n })\n\n logger.info('Executed command', { scheduleId: schedule.id, targetCommand: schedule.targetCommand })\n }\n\n /**\n * Check if user/tenant has required feature\n */\n private async checkFeature(schedule: ScheduledJob): Promise<boolean> {\n if (!schedule.requireFeature) {\n return true\n }\n\n try {\n // For system-scoped schedules, no RBAC check needed\n if (schedule.scopeType === 'system') {\n return true\n }\n\n // For tenant/org scoped schedules, check if ANY admin user has the feature\n // This is a simplified check - in reality, scheduled jobs run without a user context\n // so we're just checking if the feature is enabled for the tenant\n const hasFeature = await this.rbacService.tenantHasFeature(\n schedule.tenantId,\n schedule.requireFeature,\n {\n organizationId: schedule.organizationId,\n }\n )\n\n return hasFeature\n } catch (error: unknown) {\n logger.error('Feature check failed', { scheduleId: schedule.id, err: error })\n return false\n }\n }\n\n /**\n * Update next run time for a schedule\n */\n private async updateNextRun(schedule: ScheduledJob): Promise<void> {\n const em = this.em().fork()\n const freshSchedule = await em.findOne(ScheduledJob, { id: schedule.id })\n \n if (freshSchedule) {\n const nextRun = recalculateNextRun(\n freshSchedule.scheduleType,\n freshSchedule.scheduleValue,\n freshSchedule.timezone\n )\n \n if (nextRun) {\n freshSchedule.nextRunAt = nextRun\n await em.flush()\n }\n }\n }\n}\n"],
5
+ "mappings": "AAEA,SAAS,kBAAkB;AAE3B,SAAS,oBAAoB;AAC7B,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AACnC,SAAS,0BAA0B;AACnC,SAAS,yBAAyB;AAClC,SAAS,4CAA4C;AACrD,SAAS,oCAAoC;AAC7C,SAAS,yBAAyB,oCAAoC;AACtE,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,QAAQ,CAAC;AAoC9D,MAAM,sBAAsB;AAAA,EAKjC,YACU,IACA,cACA,aACA,SAA+B,EAAE,gBAAgB,IAAM,GAC/D;AAJQ;AACA;AACA;AACA;AARV,SAAQ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WAAO,KAAK,oBAAoB,EAAE,YAAY,SAAS,IAAI,eAAe,SAAS,cAAc,CAAC;AAAA,EACpG;AAAA;AAAA;AAAA;AAAA,EAKA,MAAc,aAAa,UAA0C;AACnE,QAAI,CAAC,SAAS,gBAAgB;AAC5B,aAAO;AAAA,IACT;AAEA,QAAI;AAEF,UAAI,SAAS,cAAc,UAAU;AACnC,eAAO;AAAA,MACT;AAKA,YAAM,aAAa,MAAM,KAAK,YAAY;AAAA,QACxC,SAAS;AAAA,QACT,SAAS;AAAA,QACT;AAAA,UACE,gBAAgB,SAAS;AAAA,QAC3B;AAAA,MACF;AAEA,aAAO;AAAA,IACT,SAAS,OAAgB;AACvB,aAAO,MAAM,wBAAwB,EAAE,YAAY,SAAS,IAAI,KAAK,MAAM,CAAC;AAC5E,aAAO;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAc,cAAc,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
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/scheduler",
3
- "version": "0.6.7-develop.6870.1.b69802067a",
3
+ "version": "0.6.8-develop.6874.1.982d6097d8",
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.7-develop.6870.1.b69802067a",
63
- "@open-mercato/queue": "0.6.7-develop.6870.1.b69802067a",
62
+ "@open-mercato/events": "0.6.8-develop.6874.1.982d6097d8",
63
+ "@open-mercato/queue": "0.6.8-develop.6874.1.982d6097d8",
64
64
  "cron-parser": "^5.6.2"
65
65
  },
66
66
  "peerDependencies": {
67
67
  "@mikro-orm/core": "^7.0.14",
68
- "@open-mercato/shared": "0.6.7-develop.6870.1.b69802067a",
68
+ "@open-mercato/shared": "0.6.8-develop.6874.1.982d6097d8",
69
69
  "bullmq": "^5.0.0 || ^6.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.7-develop.6870.1.b69802067a",
82
+ "@open-mercato/shared": "0.6.8-develop.6874.1.982d6097d8",
83
83
  "@types/jest": "^30.0.0",
84
84
  "@types/node": "^26.1.2",
85
85
  "jest": "^30.4.2",
@@ -94,5 +94,5 @@
94
94
  "url": "https://github.com/open-mercato/open-mercato",
95
95
  "directory": "packages/scheduler"
96
96
  },
97
- "stableVersion": "0.6.6"
97
+ "stableVersion": "0.6.7"
98
98
  }
@@ -87,5 +87,111 @@ describe('LocalLockStrategy', () => {
87
87
  await expect(strategy.runWithLock('test-key', fn)).rejects.toThrow(fnError)
88
88
  expect(fn).toHaveBeenCalledTimes(1)
89
89
  })
90
+
91
+ it('should run fn outside the claim transaction', async () => {
92
+ ;(mockConnection.execute as any).mockResolvedValue([{ acquired: true }])
93
+
94
+ let transactionOpen = false
95
+ transactionalImpl.mockImplementation(async (cb: any) => {
96
+ transactionOpen = true
97
+ const result = await cb(mockForkedEm)
98
+ transactionOpen = false
99
+ return result
100
+ })
101
+
102
+ let openDuringFn: boolean | null = null
103
+ const fn = jest.fn(async () => {
104
+ openDuringFn = transactionOpen
105
+ return 'ok'
106
+ })
107
+
108
+ const result = await strategy.runWithLock('test-key', fn)
109
+
110
+ expect(result).toEqual({ acquired: true, result: 'ok' })
111
+ expect(openDuringFn).toBe(false)
112
+ })
113
+
114
+ it('should reject a concurrent run for the same key without touching the database', async () => {
115
+ ;(mockConnection.execute as any).mockResolvedValue([{ acquired: true }])
116
+
117
+ let releaseFirst: () => void = () => {}
118
+ const firstDone = new Promise<void>((resolve) => {
119
+ releaseFirst = resolve
120
+ })
121
+ const firstRun = strategy.runWithLock('test-key', async () => {
122
+ await firstDone
123
+ return 'first'
124
+ })
125
+ await Promise.resolve()
126
+
127
+ const secondFn = jest.fn(async () => 'second')
128
+ const secondRun = await strategy.runWithLock('test-key', secondFn)
129
+
130
+ expect(secondRun).toEqual({ acquired: false })
131
+ expect(secondFn).not.toHaveBeenCalled()
132
+ expect(mockConnection.execute).toHaveBeenCalledTimes(1)
133
+
134
+ releaseFirst()
135
+ await expect(firstRun).resolves.toEqual({ acquired: true, result: 'first' })
136
+ })
137
+
138
+ it('should release the key after fn completes or throws', async () => {
139
+ ;(mockConnection.execute as any).mockResolvedValue([{ acquired: true }])
140
+
141
+ await expect(
142
+ strategy.runWithLock('test-key', async () => {
143
+ throw new Error('Callback failed')
144
+ }),
145
+ ).rejects.toThrow('Callback failed')
146
+
147
+ const fn = jest.fn(async () => 'ok')
148
+ await expect(strategy.runWithLock('test-key', fn)).resolves.toEqual({ acquired: true, result: 'ok' })
149
+ expect(fn).toHaveBeenCalledTimes(1)
150
+ })
151
+
152
+ it('should release the key when the claim is not acquired', async () => {
153
+ ;(mockConnection.execute as any).mockResolvedValueOnce([{ acquired: false }])
154
+ ;(mockConnection.execute as any).mockResolvedValueOnce([{ acquired: true }])
155
+
156
+ await expect(strategy.runWithLock('test-key', async () => 'ok')).resolves.toEqual({ acquired: false })
157
+
158
+ const fn = jest.fn(async () => 'ok')
159
+ await expect(strategy.runWithLock('test-key', fn)).resolves.toEqual({ acquired: true, result: 'ok' })
160
+ })
161
+
162
+ it('should release the key when the claim transaction itself rejects', async () => {
163
+ ;(mockConnection.execute as any).mockRejectedValueOnce(new Error('Database connection failed'))
164
+ ;(mockConnection.execute as any).mockResolvedValueOnce([{ acquired: true }])
165
+
166
+ await expect(strategy.runWithLock('test-key', async () => 'ok')).resolves.toEqual({ acquired: false })
167
+
168
+ const fn = jest.fn(async () => 'ok')
169
+ await expect(strategy.runWithLock('test-key', fn)).resolves.toEqual({ acquired: true, result: 'ok' })
170
+ expect(fn).toHaveBeenCalledTimes(1)
171
+ })
172
+
173
+ it('should not let a held key block a different key', async () => {
174
+ ;(mockConnection.execute as any).mockResolvedValue([{ acquired: true }])
175
+
176
+ let releaseFirst: () => void = () => {}
177
+ const firstDone = new Promise<void>((resolve) => {
178
+ releaseFirst = resolve
179
+ })
180
+ const firstRun = strategy.runWithLock('key-a', async () => {
181
+ await firstDone
182
+ return 'first'
183
+ })
184
+ await Promise.resolve()
185
+
186
+ const secondFn = jest.fn(async () => 'second')
187
+ await expect(strategy.runWithLock('key-b', secondFn)).resolves.toEqual({
188
+ acquired: true,
189
+ result: 'second',
190
+ })
191
+ expect(secondFn).toHaveBeenCalledTimes(1)
192
+
193
+ releaseFirst()
194
+ await expect(firstRun).resolves.toEqual({ acquired: true, result: 'first' })
195
+ })
90
196
  })
91
197
  })
@@ -4,44 +4,78 @@ import { createLogger } from '@open-mercato/shared/lib/logger'
4
4
  const logger = createLogger('scheduler').child({ component: 'local' })
5
5
 
6
6
  /**
7
- * PostgreSQL advisory lock strategy for single-instance or local development
7
+ * Mutual-exclusion strategy for single-instance or local development.
8
+ *
9
+ * Exclusion for the duration of the guarded run is IN-PROCESS (`heldKeys`).
10
+ * The PostgreSQL advisory lock only serialises concurrent *claims* — it is
11
+ * transaction-scoped and released as soon as the short claim transaction
12
+ * commits, before the guarded function runs. It therefore does NOT protect
13
+ * against two processes executing the same key concurrently; that matches the
14
+ * documented single-instance contract of the local scheduler strategy, and
15
+ * `LocalSchedulerService.start()` warns about it at startup.
8
16
  */
9
17
  export class LocalLockStrategy {
18
+ // Process-local by construction, so it only guards a single strategy
19
+ // instance. Invariant relied upon: exactly one LocalLockStrategy exists per
20
+ // process, because the only construction site is LocalSchedulerService
21
+ // (an Awilix singleton) and only the CLI entry points start the polling
22
+ // engine. A caller that resolves a second container would silently get an
23
+ // independent guard — see the single-instance warning in
24
+ // LocalSchedulerService.start().
25
+ private heldKeys = new Set<string>()
26
+
10
27
  constructor(private em: () => EntityManager) {}
11
28
 
12
29
  /**
13
- * Execute a function under a PostgreSQL advisory lock.
30
+ * Execute a function under a mutual-exclusion lock.
31
+ *
32
+ * In-process exclusion for the whole duration of `fn` comes from `heldKeys`
33
+ * (this strategy is single-instance by contract). The transaction-scoped
34
+ * advisory lock (`pg_try_advisory_xact_lock`) only guards the claim itself
35
+ * against a concurrently claiming process and is released when the short
36
+ * claim transaction commits, BEFORE `fn` runs.
14
37
  *
15
- * IMPORTANT: Uses transaction-scoped advisory locks (`pg_try_advisory_xact_lock`)
16
- * to avoid connection pool/session mismatch issues. The lock is automatically
17
- * released when the transaction ends.
38
+ * IMPORTANT: `fn` must NOT run inside that transaction. Holding the
39
+ * transaction open across `fn` leaves the connection idle-in-transaction
40
+ * while `fn` awaits non-DB work; the pool's default
41
+ * `idle_in_transaction_session_timeout` (120s) then makes Postgres kill the
42
+ * connection (FATAL 25P03), which crashes the scheduler process.
18
43
  */
19
44
  async runWithLock<T>(key: string, fn: () => Promise<T>): Promise<{ acquired: boolean; result?: T }> {
20
- const em = this.em().fork()
21
- const hash = this.hashString(key)
22
- let lockAcquired = false
45
+ if (this.heldKeys.has(key)) {
46
+ return { acquired: false }
47
+ }
48
+ // Reserve synchronously before the async claim so a concurrent in-process
49
+ // caller cannot slip in between our claim transaction committing (which
50
+ // releases the advisory xact lock) and the start of `fn`.
51
+ this.heldKeys.add(key)
23
52
 
24
53
  try {
25
- return await em.transactional(async (txEm) => {
26
- const result = await txEm.getConnection().execute<{ acquired: boolean }[]>(
27
- `SELECT pg_try_advisory_xact_lock(?) as acquired`,
28
- [hash],
29
- )
30
-
31
- const acquired = result[0]?.acquired === true
32
- if (!acquired) return { acquired: false }
33
- lockAcquired = true
34
-
35
- const fnResult = await fn()
36
- return { acquired: true, result: fnResult }
37
- })
38
- } catch (error) {
39
- if (lockAcquired) {
40
- throw error
54
+ const em = this.em().fork()
55
+ const hash = this.hashString(key)
56
+ let claimed = false
57
+
58
+ try {
59
+ claimed = await em.transactional(async (txEm) => {
60
+ const result = await txEm.getConnection().execute<{ acquired: boolean }[]>(
61
+ `SELECT pg_try_advisory_xact_lock(?) as acquired`,
62
+ [hash],
63
+ )
64
+ return result[0]?.acquired === true
65
+ })
66
+ } catch (error) {
67
+ logger.error('Failed to acquire lock', { lockKey: key, err: error })
68
+ return { acquired: false }
41
69
  }
42
70
 
43
- logger.error('Failed to acquire lock', { lockKey: key, err: error })
44
- return { acquired: false }
71
+ if (!claimed) {
72
+ return { acquired: false }
73
+ }
74
+
75
+ const fnResult = await fn()
76
+ return { acquired: true, result: fnResult }
77
+ } finally {
78
+ this.heldKeys.delete(key)
45
79
  }
46
80
  }
47
81
 
@@ -125,6 +125,16 @@ describe('LocalSchedulerService', () => {
125
125
  expect(loggerInfo).toHaveBeenCalledWith('Polling engine started')
126
126
  })
127
127
 
128
+ it('should warn that the local strategy has no cross-process protection', async () => {
129
+ mockForkedEm.find.mockResolvedValue([])
130
+
131
+ await service.start()
132
+
133
+ expect(loggerWarn).toHaveBeenCalledWith(
134
+ expect.stringContaining('no cross-process protection'),
135
+ )
136
+ })
137
+
128
138
  it('should run initial poll immediately', async () => {
129
139
  mockForkedEm.find.mockResolvedValue([])
130
140
 
@@ -31,14 +31,19 @@ export interface LocalSchedulerConfig {
31
31
  *
32
32
  * Features:
33
33
  * - PostgreSQL polling (configurable interval, default 30s)
34
- * - PostgreSQL advisory locks for duplicate prevention
34
+ * - In-process duplicate prevention across overlapping poll ticks
35
35
  * - Supports both queue and command targets
36
36
  * - Emits the same events as async strategy
37
37
  * - Updates nextRunAt after execution
38
- *
38
+ *
39
39
  * Limitations:
40
40
  * - Polling delay (up to configured interval)
41
- * - Single instance only (no distributed locking across instances)
41
+ * - Single instance only (no distributed locking across instances). Duplicate
42
+ * prevention is in-process only: the advisory lock serialises the claim, not
43
+ * the execution, and nextRunAt is advanced only after the target has run, so
44
+ * two processes polling the same database will both execute a due schedule.
45
+ * Run exactly one process with QUEUE_STRATEGY=local, or use the async
46
+ * strategy, which locks across instances.
42
47
  * - Higher database load than async strategy
43
48
  *
44
49
  * Set QUEUE_STRATEGY=local to use this service.
@@ -68,6 +73,9 @@ export class LocalSchedulerService {
68
73
 
69
74
  this.isRunning = true
70
75
  logger.info('Starting polling engine', { pollIntervalMs: this.config.pollIntervalMs })
76
+ logger.warn(
77
+ 'Local scheduler strategy provides no cross-process protection: duplicate prevention is in-process only, so a second process polling the same database will execute the same due schedule. Run exactly one process with QUEUE_STRATEGY=local, or use the async strategy for distributed locking.',
78
+ )
71
79
 
72
80
  // Run initial poll immediately
73
81
  await this.poll()