UNPKG

@mastra/core

Version:
492 lines (491 loc) • 16.8 kB
import { t as MastraBase } from "./base-CKLWBhDo.js"; import { a as RegisteredLogger } from "./logger-BwbmRqfc.js"; import { u as computeNextFire } from "./schedules-CGkeqNro.js"; // src/workflows/scheduler/scheduler.ts const TOPIC_WORKFLOWS = "workflows"; const TOPIC_AGENT_SCHEDULES = "agent-schedules"; const DEFAULT_TICK_INTERVAL_MS = 1e4; const DEFAULT_BATCH_SIZE = 100; const DEFAULT_MISSES_BEFORE_DELETE = 3; const DEFAULT_STALE_SKIPS_BEFORE_ESCALATION = 5; /** Longest delay `setTimeout` accepts; larger values fire immediately. */ const MAX_TIMER_DELAY_MS = 2 ** 31 - 1; /** * Drives cron-based workflow triggers. * * On each tick the scheduler: * 1. Loads schedules whose `nextFireAt <= now` from storage. * 2. Computes the next fire time from the cron expression. * 3. Atomically advances `nextFireAt` via compare-and-swap. Only one * instance across many polling the same storage can claim a fire. * 4. Publishes a `workflow.start` event on the `workflows` pubsub topic. * 5. Records the trigger in the schedule's history. * * The scheduler does **not** execute workflows. The existing * `WorkflowEventProcessor` consumes `workflow.start` events and runs them. */ var Scheduler = class extends MastraBase { #schedulesStore; #pubsub; #config; #timerHandle; #inflightTick; #loop; #wakeRequested = false; /** Whether the last tick saw due schedules, or failed to list them. */ #lastTickBusy = false; #started = false; #stopping = false; /** * Per-schedule count of consecutive ticks where the target workflow was * not registered with the host Mastra instance. Reset when the workflow * resolves or the schedule is deleted. Used to ride out deploy/startup * ordering races before reclaiming a ghost row. */ #missingWorkflowCounts = /* @__PURE__ */ new Map(); /** * Consecutive ticks each schedule has been skipped because the local target * definition is stale (see `#ensureTargetCurrent`). Doubles as the * "already logged" marker so a straggler doesn't re-log every tick, and as * the counter that escalates a skip that is never being picked up by anyone. * * Scoped to the fire window (`nextFireAt`) the skips were observed against. * A window that advances is proof some other instance claimed and fired the * previous one, so the count restarts rather than accumulating across * unrelated fires — otherwise a long-lived straggler would escalate even * though every fire is being served correctly by a current-build instance. */ #staleDefinitionCounts = /* @__PURE__ */ new Map(); constructor({ schedulesStore, pubsub, config }) { super({ component: RegisteredLogger.WORKFLOW, name: "Scheduler" }); this.#schedulesStore = schedulesStore; this.#pubsub = pubsub; this.#config = { ...config, tickIntervalMs: config?.tickIntervalMs ?? DEFAULT_TICK_INTERVAL_MS, batchSize: config?.batchSize ?? DEFAULT_BATCH_SIZE }; } /** Start the tick loop. Runs an immediate tick first. */ async start() { if (this.#started) return; this.#started = true; this.#stopping = false; this.#missingWorkflowCounts.clear(); this.#staleDefinitionCounts.clear(); try { this.#wakeRequested = true; await this.#runLoop(); } catch (err) { this.#started = false; this.#stopping = false; throw err; } } /** Stop the tick loop and wait for any in-flight tick to finish. */ async stop() { if (!this.#started) return; this.#stopping = true; this.#clearTimer(); if (this.#loop) try { await this.#loop; } catch {} if (this.#inflightTick) try { await this.#inflightTick; } catch {} this.#started = false; this.#stopping = false; } /** True when the scheduler is currently running its tick loop. */ get isRunning() { return this.#started; } /** * Run a single tick. Public for tests; production callers should rely * on the timer started by `start()`. */ async tick() { await this.#runTick(); } /** * Tick now and re-arm the timer. Call when a schedule was created, resumed * or moved earlier, since the scheduler may be sleeping until a later fire. */ wake() { if (!this.#started || this.#stopping) return; this.#wakeRequested = true; if (this.#loop) return; this.#clearTimer(); this.#runLoop().catch((err) => { this.logger.error("Scheduler tick crashed", { error: err }); }); } /** * Tick, then sleep until the earliest active schedule is due instead of * polling storage on a fixed interval. A wake that lands mid-loop ticks * again before the timer is armed. */ #runLoop() { const loop = this.#loopOnce().finally(() => { if (this.#loop === loop) this.#loop = void 0; }); this.#loop = loop; return loop; } async #loopOnce() { let delay; do { this.#wakeRequested = false; try { await this.#runTick(); } catch (err) { this.logger.error("Scheduler tick crashed", { error: err }); this.#lastTickBusy = true; } if (this.#stopping || !this.#started) return; delay = await this.#nextDelay(); } while (this.#wakeRequested && !this.#stopping && this.#started); if (this.#stopping || !this.#started) return; this.#clearTimer(); if (delay === void 0) return; this.#timerHandle = setTimeout(() => { this.#timerHandle = void 0; this.wake(); }, delay); this.#timerHandle.unref?.(); } /** * How long to sleep before the next tick. Keeps the fixed interval while * schedules are due (fires, retries, skipped targets), on storage errors, * and for a scheduler explicitly enabled with `enabled: true` (a dedicated * scheduler that must find rows written by processes it shares no pubsub * with). Otherwise waits for the earliest active `nextFireAt` and relies on * `wake()` for new schedules; with no active schedules it returns undefined * and no timer is armed, so an idle app never touches storage. */ async #nextDelay() { const interval = this.#config.tickIntervalMs; if (this.#config.enabled === true || this.#lastTickBusy) return interval; let next; try { next = await this.#schedulesStore.listDueSchedules(Number.MAX_SAFE_INTEGER, 1); } catch (err) { this.logger.error("Failed to look up the next scheduled fire", { error: err }); return interval; } if (next.length === 0) return void 0; return Math.max(interval, Math.min(next[0].nextFireAt - Date.now(), MAX_TIMER_DELAY_MS)); } #clearTimer() { if (this.#timerHandle) { clearTimeout(this.#timerHandle); this.#timerHandle = void 0; } } async #runTick() { if (this.#stopping || this.#inflightTick) return; const promise = this.#processTick().finally(() => { this.#inflightTick = void 0; }); this.#inflightTick = promise; await promise; } async #processTick() { let due; this.#lastTickBusy = true; try { due = await this.#schedulesStore.listDueSchedules(Date.now(), this.#config.batchSize); } catch (err) { this.logger.error("Failed to list due schedules", { error: err }); return; } this.#lastTickBusy = due.length > 0; for (const schedule of due) { if (this.#stopping) break; await this.#fireSchedule(schedule); } } /** * Check whether a schedule's target is registered with the host * Mastra instance. Returns `true` if no predicate is configured (we can't * verify, so assume the consumer will reject) or if the target resolves. * * When the target is missing, we increment an in-memory counter and * delete the schedule after `missesBeforeDelete` consecutive misses. The * grace window protects against deploy/startup ordering races where the * scheduler ticks before workflows/agents finish registering on a fresh * process. Returns `false` to tell `#fireSchedule` to skip publishing for * this tick. */ async #ensureTargetReady(schedule) { const predicate = this.#config.isTargetReady; if (!predicate) return true; if (await predicate(schedule.target)) { this.#missingWorkflowCounts.delete(schedule.id); return true; } const targetSummary = schedule.target.type === "workflow" ? { workflowId: schedule.target.workflowId } : { agentId: schedule.target.agentId }; const limit = this.#config.missesBeforeDelete ?? DEFAULT_MISSES_BEFORE_DELETE; const prev = this.#missingWorkflowCounts.get(schedule.id) ?? 0; const next = prev + 1; if (next < limit) { this.#missingWorkflowCounts.set(schedule.id, next); if (prev === 0) this.logger.warn("Schedule target is not registered; skipping until it appears", { scheduleId: schedule.id, targetType: schedule.target.type, ...targetSummary, missesBeforeDelete: limit }); return false; } this.logger.error("Deleting schedule whose target has not been registered", { scheduleId: schedule.id, targetType: schedule.target.type, ...targetSummary, consecutiveMisses: next }); try { await this.#schedulesStore.deleteSchedule(schedule.id); } catch (err) { this.logger.error("Failed to delete ghost schedule", { scheduleId: schedule.id, targetType: schedule.target.type, ...targetSummary, error: err }); return false; } this.#missingWorkflowCounts.delete(schedule.id); return false; } /** * Stale-build fence (#19169). Scheduled runs execute `localOnly` in the * claiming process against its own workflow registry, so an instance whose * local target definition differs from the one recorded on the schedule * row must not claim the fire — it would silently run an outdated step * graph. Returning `false` skips the CAS claim entirely, leaving * `nextFireAt` untouched so an instance with a matching definition can * claim the fire on its own tick. * * Fails open when no predicate is configured or when the predicate * throws — fencing is a safety net, not a reason to stop firing. */ #ensureTargetCurrent(schedule) { const predicate = this.#config.isTargetCurrent; if (!predicate) return true; let current; try { current = predicate(schedule.target); } catch (err) { this.logger.error("isTargetCurrent predicate threw; treating target as current", { scheduleId: schedule.id, error: err }); return true; } if (current) { this.#staleDefinitionCounts.delete(schedule.id); return true; } const prevEntry = this.#staleDefinitionCounts.get(schedule.id); const prev = prevEntry?.fireAt === schedule.nextFireAt ? prevEntry.count : 0; const next = prev + 1; this.#staleDefinitionCounts.set(schedule.id, { fireAt: schedule.nextFireAt, count: next }); const targetSummary = schedule.target.type === "workflow" ? { workflowId: schedule.target.workflowId } : { agentId: schedule.target.agentId }; const limit = this.#config.staleSkipsBeforeEscalation ?? DEFAULT_STALE_SKIPS_BEFORE_ESCALATION; if (prev === 0) this.logger.warn("Local target definition differs from the schedule row; leaving fire for an instance running the current build", { scheduleId: schedule.id, targetType: schedule.target.type, ...targetSummary }); else if (next === limit) { this.logger.error("Schedule has been skipped repeatedly because no local target definition matches the schedule row; it will not fire until an instance running the recorded build is available", { scheduleId: schedule.id, targetType: schedule.target.type, ...targetSummary, consecutiveStaleSkips: next }); this.#recordStaleSkip(schedule, next); } return false; } /** * Best-effort history entry for an escalated stale skip so the stall is * visible to anyone inspecting the schedule, not just in process logs. */ async #recordStaleSkip(schedule, consecutiveStaleSkips) { try { await this.#schedulesStore.recordTrigger({ scheduleId: schedule.id, runId: `sched_${schedule.id}_${schedule.nextFireAt}`, scheduledFireAt: schedule.nextFireAt, actualFireAt: Date.now(), outcome: "failed", error: `Skipped: no local target definition matches the schedule row after ${consecutiveStaleSkips} consecutive ticks`, triggerKind: "schedule-fire" }); } catch (err) { this.logger.warn("Failed to record stale-definition skip", { scheduleId: schedule.id, error: err }); } } async #fireSchedule(schedule) { if (!await this.#ensureTargetReady(schedule)) return; if (!this.#ensureTargetCurrent(schedule)) return; const actualFireAt = Date.now(); let newNextFireAt; let completed; try { ({nextFireAt: newNextFireAt, completed} = computeNextFire(schedule, actualFireAt)); } catch (err) { this.logger.error("Failed to compute next fire time for schedule", { scheduleId: schedule.id, cron: schedule.cron, error: err }); this.#notifyError(err, schedule.id); return; } const runId = `sched_${schedule.id}_${schedule.nextFireAt}`; let claimed = false; try { claimed = await this.#schedulesStore.updateScheduleNextFire(schedule.id, schedule.nextFireAt, newNextFireAt, actualFireAt, runId, completed ? "completed" : void 0); } catch (err) { this.logger.error("Failed to claim due schedule fire", { scheduleId: schedule.id, runId, error: err }); this.#notifyError(err, schedule.id); return; } if (!claimed) return; this.logger.info("Claimed schedule occurrence", { scheduleId: schedule.id, runId, scheduledFireAt: schedule.nextFireAt }); let triggerStatus = "published"; let triggerError; try { for (let attempt = 0; attempt < 3; attempt++) try { await this.#publishTargetStart(schedule, runId); break; } catch (err) { if (attempt === 2) throw err; await new Promise((resolve) => setTimeout(resolve, 100 * 2 ** attempt)); } this.logger.info("Published schedule occurrence", { scheduleId: schedule.id, runId, scheduledFireAt: schedule.nextFireAt }); } catch (err) { triggerStatus = "failed"; triggerError = err instanceof Error ? err.message : String(err); this.logger.error("Failed to publish target.start for schedule", { scheduleId: schedule.id, runId, targetType: schedule.target.type, scheduledFireAt: schedule.nextFireAt, publicationOutcome: "unknown", automaticReplay: false, error: err }); this.#notifyError(err, schedule.id); } if (schedule.target.type === "workflow" || triggerStatus === "failed") try { await this.#schedulesStore.recordTrigger({ scheduleId: schedule.id, runId, scheduledFireAt: schedule.nextFireAt, actualFireAt, outcome: triggerStatus, error: triggerError, triggerKind: "schedule-fire" }); } catch (err) { this.logger.error("Failed to record schedule trigger", { scheduleId: schedule.id, runId, error: err }); } } /** * Invoke the user-supplied onError hook in isolation. A throwing hook * must not abort the scheduler tick loop, so we swallow + log any error * the callback itself raises. */ #notifyError(error, scheduleId) { if (!this.#config.onError) return; try { this.#config.onError(error, { scheduleId }); } catch (callbackError) { this.logger.error("Scheduler onError handler threw", { scheduleId, error: callbackError }); } } async #publishTargetStart(schedule, claimId) { switch (schedule.target.type) { case "workflow": { const { workflowId, inputData, initialState, requestContext, resourceId, definitionHash } = schedule.target; const localOnly = this.#config.canExecuteLocally?.() === true; await this.#pubsub.publish(TOPIC_WORKFLOWS, { type: "workflow.start", runId: claimId, data: { workflowId, runId: claimId, prevResult: { status: "success", output: inputData ?? {} }, requestContext: requestContext ?? {}, initialState: initialState ?? {}, ...resourceId ? { resourceId } : {}, ...definitionHash ? { scheduleDefinitionHash: definitionHash } : {}, scheduleTrigger: { scheduleId: schedule.id, scheduledFireAt: schedule.nextFireAt, triggerKind: "schedule-fire" } } }, localOnly ? { localOnly: true } : void 0); return; } case "agent": await this.#pubsub.publish(TOPIC_AGENT_SCHEDULES, { type: "agent-schedule.fire", runId: claimId, data: { scheduleId: schedule.id, claimId, scheduledFireAt: schedule.nextFireAt, target: schedule.target, ...schedule.runAt != null ? { oneOff: true } : {} } }); return; default: throw new Error(`Unsupported schedule target type: ${schedule.target.type}`); } } }; /** * @deprecated Renamed to {@link Scheduler}. The scheduler now drives both * workflow and agent schedules, so the `Workflow`-prefixed name is no longer * accurate. This alias will be removed in a future major release. */ const WorkflowScheduler = Scheduler; export { WorkflowScheduler as n, Scheduler as t }; //# sourceMappingURL=scheduler-DOueSa7x.js.map