UNPKG

@mastra/core

Version:
276 lines • 13.6 kB
import type { Mastra } from '..'; import type { PubSub } from '../events/pubsub.js'; import type { BackgroundTask, BackgroundTaskManagerConfig, EnqueueOptions, EnqueueResult, ResumeOptions, TaskContext, TaskFilter, TaskPayload, TaskListResult, ToolExecutor, BackgroundTaskEvent } from './types.js'; /** * Runs, persists, and recovers background tasks for one Mastra process. * * Several managers (processes or replicas) may share one storage backend. * Execution is owned through a lease persisted on each task record: * * - Identity: each manager has a random `ownerId` (`workerId`), so a restarted * process is a new owner. * - Acquisition: `handleDispatch` claims a task with a compare-and-set on the * observed status/owner/lease, writing `ownerId` and * `leaseExpiresAt = now + leaseDurationMs`. Losers of a race skip the task. * - Renewal: the heartbeat renews owned leases every `leaseDurationMs / 3`, * fenced on `running` + this owner. Workflow terminal writes carry the same * fence, so a superseded owner cannot commit results. * - Expiry and adoption: `recoverStaleTasks` only reclaims a `running` task * once its lease has expired (or was released on shutdown), fenced on the * owner/lease it read so one manager wins. It re-runs when the earliest live * lease lapses. `restart()` is the one deliberate takeover of a live lease. * - Loss: a failed renewal aborts the local run's signal when another owner * holds the task or it was cancelled. * * Guarantee: at most one owner can commit a task's state at a time, except * for the shutdown rollback of an interrupted resume in `handleResume`, which is * conditional on status only. The tool * itself may still run more than once (stalled owner past its lease, crash * before the result is saved, explicit restart), so external side effects need * idempotency. Assumes storage applies `updateTask` conditions atomically and * that clock skew between managers is well below `leaseDurationMs`, since * `leaseExpiresAt` is written by the owner's clock and read by others'. */ export declare class BackgroundTaskManager { #private; private pubsub; private readonly workerId; private readonly processAffineDispatchTopic; config: Required<Pick<BackgroundTaskManagerConfig, 'globalConcurrency' | 'perAgentConcurrency' | 'backpressure' | 'defaultTimeoutMs' | 'recoverStaleTasksOnStart' | 'leaseDurationMs'>> & BackgroundTaskManagerConfig; /** @internal — read by the workflow-engine step bodies in workflow.ts */ taskContexts: Map<string, TaskContext>; private staticExecutors; /** @internal — read by the workflow-engine step bodies in workflow.ts */ activeAbortControllers: Map<string, AbortController>; private localReservations; private localPendingTaskIds; private localPendingResumes; private inFlightPortableResumes; private drainingPending; private ownedLeases; private pinnedPendingLeases; private heartbeatInterval?; private staleRecoveryTimeout?; private pinSweepInterval?; private sweepingPins; private pinSweepPage; private workerCallback?; private resultCallback?; private shuttingDown; private cleanupInterval?; private initPromise?; private shutdownPromise?; private shutdownDeadline?; constructor(config?: BackgroundTaskManagerConfig); __registerMastra(mastra: Mastra): void; /** * @internal — execution-lease owner identity for this manager process. * Persisted when a task is claimed so recovery can distinguish a live owner * from a dead one, and used by the workflow step bodies to fence their * terminal writes against a superseded owner. */ get ownerId(): string; getStorage(): Promise<import("../storage").BackgroundTasksStorage>; init(pubsub: PubSub): Promise<void>; /** * Register per-task hooks (executor, stream emitter, result injector). * Called internally by createBackgroundTask or directly for advanced usage. */ registerTaskContext(taskId: string, context: TaskContext): void; /** * Remove per-task hooks. Called after task reaches terminal state. */ deregisterTaskContext(taskId: string): void; /** @internal — called by the workflow step immediately before executor invocation. */ registerActiveAbortController(taskId: string, controller: AbortController): boolean; /** @internal — read by workflow error classification during graceful shutdown. */ isShuttingDown(): boolean; /** * Register a tool executor by tool name. Used for cross-process dispatch: * when a worker in a different process picks up a `task.dispatch` event, * it has no per-task closure (`taskContexts`) for that taskId, but it can * resolve the executor by tool name via this registry. */ registerStaticExecutor(toolName: string, executor: ToolExecutor): void; /** * Symmetric to `registerStaticExecutor`. Called when a tool is removed * from `Mastra`. */ unregisterStaticExecutor(toolName: string): void; /** * Look up an executor by tool name. Read by the workflow-step body in * `workflow.ts:runAttemptStep` as a fallback when no per-task `TaskContext` * is registered (cross-process path). */ getStaticExecutor(toolName: string): ToolExecutor | undefined; /** * Enqueue a task for background execution. * Prefer `createBackgroundTask()` which returns a self-contained handle. */ enqueue(payload: TaskPayload, context?: TaskContext, options?: EnqueueOptions): Promise<EnqueueResult>; cancel(taskId: string): Promise<void>; /** * Resume a suspended task. The tool executor must be re-registered via * `registerTaskContext(taskId, ...)` before calling this if the original * registration is gone (e.g. process restart) — the manager doesn't * rehydrate executor closures from storage. * * `resumeData` is forwarded to the tool's `execute` options on the * resumed run. */ resume(taskId: string, resumeData?: unknown, options?: ResumeOptions): Promise<BackgroundTask>; /** * Re-dispatches a previously pending or running task. The tool executor is * re-registered via `registerTaskContext(taskId, ...)` because the original * registration is gone (e.g. process restart) — the manager doesn't * rehydrate executor closures from storage. * * Restarting a `running` task is an explicit takeover: the claim is fenced on * status only, so it succeeds even while another manager holds a live lease. * The previous owner's next renewal fails and aborts its run, but that run * may overlap this one until then. */ restart(taskId: string, context?: TaskContext): Promise<BackgroundTask>; getTask(taskId: string): Promise<BackgroundTask | null>; listTasks(filter?: TaskFilter): Promise<TaskListResult>; /** * Deletes old completed/failed/cancelled/timed_out task records from storage. */ cleanup(): Promise<void>; /** * Returns a promise that resolves when the next task from the given set * reaches a terminal state. */ waitForNextTask(taskIds: string[], options?: { timeoutMs?: number; onProgress?: (elapsedMs: number) => void; progressIntervalMs?: number; abortSignal?: AbortSignal; }): Promise<BackgroundTask>; /** * Returns a ReadableStream of all background task lifecycle events, * filtered by optional criteria. Intended to be piped directly to an SSE response. * * On connection, emits the current state of all non-terminal tasks as a snapshot, * then subscribes to live pubsub events for subsequent updates. * * Events include: * - `task.running` (status: 'running') — task picked up by a worker * - `task.completed` (status: 'completed') — task finished successfully * - `task.failed` (status: 'failed' or 'timed_out') — task errored or timed out * - `task.cancelled` (status: 'cancelled') — task was cancelled * - `task.suspended` (status: 'suspended') — task paused via `suspend()` from * inside its tool executor; resume with `manager.resume(taskId, data)` * - `task.resumed` (status: 'running') — suspended task resumed * * The stream stays open until the caller's AbortSignal fires (client disconnect). * * Events are scoped to a resource: when `resourceId` is omitted, only tasks without a * `resourceId` are delivered. Pass `allResources: true` to receive events for every * resource (privileged consumers only — payloads include task args and results). */ stream(options?: { agentId?: string; runId?: string; threadId?: string; resourceId?: string; taskId?: string; abortSignal?: AbortSignal; includeExisting?: boolean; allResources?: boolean; }): ReadableStream<Record<string, unknown>>; /** * @param options.deadline - Absolute wall-clock deadline (ms since epoch) to * bound teardown by. `Mastra.shutdown()` passes the deadline shared with * its workflow drain so the two do not stack. Defaults to * `SHUTDOWN_GRACE_PERIOD_MS` from now when called standalone. */ shutdown(options?: { deadline?: number; }): Promise<void>; private dispatch; /** * Handles a task.dispatch and task.restart events. * Both events are similar, but the latter is used to restart a running task. */ private handleDispatch; /** * Handles a task.resume event. Mirrors the workflow branch of handleDispatch * but resumes an existing run from its suspended snapshot instead of starting * a fresh one. Concurrency gating, suspended-status validation, and the * `task.resumed` lifecycle publish all happen here so a different process * than the one that suspended the task can drive the resume. */ private handleResume; /** * Settles a task whose background-task workflow run ended in a non-success, * non-suspended state (or rejected). On the ordinary failure path * classify-outcome has already moved the task to `failed`, so the CAS below * is a no-op. It only takes effect when a step threw before persisting a * terminal status (e.g. the `completed` write failed), which would otherwise * leave the task `running` forever. */ private failUnsettledTask; /** * Run per-task hooks (onChunk, onResult, onComplete/onFailed) locally in the * worker path, before publishing the terminal lifecycle event. Ensures * memory / stream state is consistent by the time any pubsub subscriber is * notified. After running, the task context is deregistered so * `handleResult` (which also fires from pubsub) becomes a no-op for this * task in the same process. * * In distributed deployments where the worker runs in a different process * from the dispatcher, `this.taskContexts` won't contain an entry for * `task.id` — this method is a no-op there, and `handleResult` in the * dispatching process runs the hooks instead. */ /** * Terminal-state hooks only. Called when a task reaches `'completed'` or * `'failed'`. Suspend is non-terminal — see `runLocalSuspendHooks` for that * path. * * @internal — also called by the workflow-engine step bodies in workflow.ts */ runLocalCompletionHooks(task: BackgroundTask, status: 'completed' | 'failed', extras: { result?: unknown; error?: { message: string; stack?: string; }; }): Promise<void>; /** * Per-task suspend hooks. Fires `ctx.onExecution({ suspendedAt, suspendPayload, ... })` * so the message list / memory record the open suspension on the tool * call. Does NOT deregister the task context — resume needs the executor * closure intact. * * @internal — called by the workflow-engine step bodies in workflow.ts */ runLocalSuspendHooks(task: BackgroundTask): Promise<void>; /** @internal — also called by the workflow-engine step bodies in workflow.ts */ runLocalExecutionHook(task: BackgroundTask): Promise<void>; /** * Another process cancelled a task this one dispatched. Run its execution * hook, so the dispatcher drops an open request it recorded for the task, * and release the task's context. A cancel made here has already done both. */ private handleRemoteCancel; private handleResult; private handleCancel; /** @internal — also called by the workflow-engine step bodies in workflow.ts */ publishLifecycleEvent(type: 'task.running' | 'task.completed' | 'task.failed' | 'task.cancelled' | 'task.output' | 'task.suspended' | 'task.resumed', task: BackgroundTaskEvent): Promise<void>; private reserveLocalSlot; private releaseLocalSlot; private checkConcurrency; private drainPending; /** * Recovers tasks left in 'running' or 'pending' state from a previous process. * * Running tasks are only reclaimed once their execution lease has lapsed, so * one whose owner died moments before this scan is still protected. When that * happens the scan reschedules itself for the moment the earliest such lease * expires — see `#scheduleStaleRecovery`. */ private recoverStaleTasks; } //# sourceMappingURL=manager.d.ts.map