@mastra/core
Version:
551 lines (550 loc) • 19.8 kB
JavaScript
import { Ct as getStepEntry, St as getNestedWorkflow, al as resolveAgentById, bt as computeScheduleDefinitionHash, hu as waitMs, mu as assertDrainTimeout, vt as WorkflowEventProcessor, yt as StepExecutor } from "./run-registry-Ca8idv6o.js";
import { t as Scheduler } from "./scheduler-DOueSa7x.js";
import { s as BackgroundTaskManager } from "./background-tasks-CChqE9Qy.js";
import { u as RequestContext } from "./request-context-COnZHt2-.js";
// src/worker/worker.ts
/**
* Abstract base class for Mastra workers.
*
* Each worker is a self-contained, independently deployable unit of
* background processing. Concrete implementations include:
* - OrchestrationWorker: processes workflow events
* - SchedulerWorker: fires cron-based workflow schedules
* - BackgroundTaskWorker: manages background tool execution
*
* Workers are registered on a Mastra instance and run inline by default.
* They can also be launched standalone via the CLI for separate deployment.
*/
var MastraWorker = class {
mastra;
deps;
/** Called by Mastra during registration to provide the instance reference. */
__registerMastra(mastra) {
this.mastra = mastra;
}
/** Initialize with infrastructure deps. Called before start(). */
async init(deps) {
this.deps = deps;
if (!this.mastra && deps.mastra) this.mastra = deps.mastra;
}
};
// src/worker/strategies/http-remote-strategy.ts
/**
* Executes workflow steps by calling a remote server endpoint over HTTP.
* Used in standalone worker deployments where the worker runs orchestration
* logic but delegates actual step execution to the server.
*
* Authentication piggy-backs on Mastra's existing auth pipeline: the route
* is marked `requiresAuth: true` and the deployer's `authenticateToken`
* provider validates the credential we send here. There is no separate
* "worker secret" — whatever auth scheme the rest of the server uses is
* what the worker uses too.
*/
var HttpRemoteStrategy = class HttpRemoteStrategy {
#baseUrl;
#auth;
#timeoutMs;
constructor({ serverUrl, auth, timeoutMs }) {
const normalized = serverUrl.endsWith("/") ? serverUrl : `${serverUrl}/`;
this.#baseUrl = new URL(normalized);
this.#auth = auth ?? HttpRemoteStrategy.#authFromEnv();
this.#timeoutMs = timeoutMs ?? 3e4;
}
/**
* Default credential resolution: when `MASTRA_WORKER_AUTH_TOKEN` is set,
* send it as a bearer token. The server's auth provider decides whether
* to accept it.
*/
static #authFromEnv() {
const token = process.env.MASTRA_WORKER_AUTH_TOKEN;
if (!token) return void 0;
return {
type: "bearer",
token
};
}
async executeStep(params) {
const url = new URL(`workflows/${encodeURIComponent(params.workflowId)}/runs/${encodeURIComponent(params.runId)}/steps/execute`, this.#baseUrl);
const body = this.#buildBody(params);
const signal = this.#combineSignals(params.abortSignal);
const res = await fetch(url, {
method: "POST",
headers: {
"content-type": "application/json",
...this.#buildAuthHeaders()
},
body,
signal
});
if (!res.ok) {
const text = await res.text();
throw new StepExecutionError(res.status, text);
}
return res.json();
}
/**
* Build a JSON-serializable request body. The `params.requestContext` is
* a plain object; if a caller stuffed a non-serializable value into it we
* surface a clear error instead of silently dropping fields.
*
* `abortSignal` is consumed via fetch's `signal` argument — it must not
* be in the body.
*/
#buildBody(params) {
const { abortSignal: _abortSignal, requestContext, ...rest } = params;
let safeRequestContext;
try {
safeRequestContext = JSON.parse(JSON.stringify(requestContext ?? {}));
} catch (err) {
throw new Error(`HttpRemoteStrategy: requestContext is not JSON-serializable. ${err instanceof Error ? err.message : String(err)}`);
}
return JSON.stringify({
...rest,
requestContext: safeRequestContext
});
}
#combineSignals(externalSignal) {
const timeoutSignal = AbortSignal.timeout(this.#timeoutMs);
if (!externalSignal) return timeoutSignal;
if (typeof AbortSignal.any === "function") return AbortSignal.any([timeoutSignal, externalSignal]);
const controller = new AbortController();
const onAbort = (reason) => controller.abort(reason);
if (externalSignal.aborted) onAbort(externalSignal.reason);
else externalSignal.addEventListener("abort", () => onAbort(externalSignal.reason), { once: true });
if (timeoutSignal.aborted) onAbort(timeoutSignal.reason);
else timeoutSignal.addEventListener("abort", () => onAbort(timeoutSignal.reason), { once: true });
return controller.signal;
}
#buildAuthHeaders() {
if (!this.#auth) return {};
if (this.#auth.type === "api-key") return { "x-worker-api-key": this.#auth.key };
if (this.#auth.type === "header") return { [this.#auth.name]: this.#auth.value };
return { authorization: `Bearer ${this.#auth.token}` };
}
};
var StepExecutionError = class extends Error {
status;
body;
constructor(status, body) {
super(`Step execution failed with status ${status}: ${body}`);
this.name = "StepExecutionError";
this.status = status;
this.body = body;
}
};
// src/worker/transport/pull-transport.ts
const TOPIC_WORKFLOWS = "workflows";
const DEFAULT_DRAIN_TIMEOUT_MS = 5e3;
var PullTransport = class {
#pubsub;
#group;
#topic;
#logger;
#drainTimeout;
#callbacks = [];
#inFlight = /* @__PURE__ */ new Set();
constructor({ pubsub, group, topic, logger, drainTimeout }) {
this.#pubsub = pubsub;
this.#group = group;
this.#topic = topic ?? TOPIC_WORKFLOWS;
this.#logger = logger;
this.#drainTimeout = assertDrainTimeout(drainTimeout ?? waitMs(DEFAULT_DRAIN_TIMEOUT_MS, 50), "PullTransport");
}
async start(router) {
if (this.#callbacks.length > 0) {
this.#logger?.debug("[PullTransport] start() called while already subscribed; ignoring duplicate call");
return;
}
const cb = (event, ack, nack, extend) => {
const inFlight = router.route(event, ack, nack, extend).catch((err) => {
try {
if (typeof nack === "function") nack();
} finally {
this.#logger?.error("[PullTransport] router.route rejected", { err });
}
});
this.#inFlight.add(inFlight);
inFlight.finally(() => this.#inFlight.delete(inFlight));
};
await this.#pubsub.subscribe(this.#topic, cb, { group: this.#group });
this.#callbacks.push({
topic: this.#topic,
cb
});
}
async stop(options) {
const drainTimeout = assertDrainTimeout(options?.drainTimeout ?? this.#drainTimeout, "PullTransport.stop()");
for (const { topic, cb } of this.#callbacks) await this.#pubsub.unsubscribe(topic, cb);
this.#callbacks = [];
await this.#drainInFlight(drainTimeout);
await this.#pubsub.flush();
}
async #drainInFlight(drainTimeout) {
if (this.#inFlight.size === 0) return;
const pending = this.#inFlight.size;
let timeoutHandle;
try {
if (await Promise.race([Promise.allSettled([...this.#inFlight]).then(() => false), new Promise((resolve) => {
timeoutHandle = setTimeout(() => resolve(true), drainTimeout);
})])) this.#logger?.warn(`[PullTransport] stop() timed out after ${drainTimeout}ms waiting for ${pending} in-flight event(s)`);
} finally {
if (timeoutHandle) clearTimeout(timeoutHandle);
}
}
};
// src/worker/workers/orchestration-worker.ts
const DEFAULT_GROUP = "mastra-orchestration";
const DEFAULT_LEASE_RENEW_INTERVAL_MS = 1e4;
/**
* Processes workflow events (step.run, step.end, start, cancel, etc.)
* by delegating to the WorkflowEventProcessor.
*
* Subscribes to the PubSub "workflows" topic and routes events to WEP.
*
* When MASTRA_STEP_EXECUTION_URL is set, injects HttpRemoteStrategy into
* WEP so step execution happens over HTTP to the server. Otherwise WEP
* executes steps directly in-process.
*/
var OrchestrationWorker = class extends MastraWorker {
name = "orchestration";
#config;
#transport;
#processor;
#strategy;
#running = false;
constructor(config = {}) {
super();
const interval = config.leaseRenewIntervalMs;
if (interval !== void 0 && (!Number.isFinite(interval) || interval <= 0)) throw new Error(`OrchestrationWorker: leaseRenewIntervalMs must be a positive number, got ${interval}`);
this.#config = config;
}
async init(deps) {
await super.init(deps);
if (!deps.mastra) throw new Error("OrchestrationWorker requires Mastra instance");
const modes = deps.pubsub.supportedModes ?? ["pull"];
if (!modes.includes("pull")) throw new Error(`OrchestrationWorker requires a pull-capable PubSub, but the configured pubsub only supports: ${modes.join(", ")}. Either remove OrchestrationWorker from the workers list or use a pull-capable PubSub (e.g. Redis Streams).`);
const remoteUrl = process.env.MASTRA_STEP_EXECUTION_URL;
if (remoteUrl) this.#strategy = new HttpRemoteStrategy({ serverUrl: remoteUrl });
this.#processor = new WorkflowEventProcessor({
mastra: deps.mastra,
stepExecutionStrategy: this.#strategy
});
}
async start() {
if (this.#running) return;
if (!this.deps) throw new Error("OrchestrationWorker: call init() before start()");
const group = this.#config.group ?? DEFAULT_GROUP;
this.#transport = new PullTransport({
pubsub: this.deps.pubsub,
group,
logger: this.deps.logger
});
await this.#transport.start({ route: (event, ack, nack, extend) => this.#processEvent(event, ack, nack, extend) });
this.#running = true;
}
async stop(options) {
if (!this.#running) return;
try {
if (this.#transport) {
await this.#transport.stop(options);
this.#transport = void 0;
}
} finally {
this.#running = false;
}
}
get isRunning() {
return this.#running;
}
async #processEvent(event, ack, nack, extend) {
if (!this.#processor) throw new Error("OrchestrationWorker not initialized");
const heartbeat = extend ? setInterval(() => {
extend().catch((e) => {
this.deps?.logger?.error("OrchestrationWorker: error extending event lease", { error: e });
});
}, this.#config.leaseRenewIntervalMs ?? DEFAULT_LEASE_RENEW_INTERVAL_MS) : void 0;
let result;
try {
result = await this.#processor.handle(event);
} finally {
if (heartbeat) clearInterval(heartbeat);
}
if (result.ok) {
try {
await ack?.();
} catch (e) {
this.deps?.logger?.error("OrchestrationWorker: error acking event", { error: e });
}
return;
}
this.deps?.logger?.error("OrchestrationWorker: error processing event", {
type: event.type,
runId: event.runId,
retry: result.retry
});
if (result.retry) {
if (nack) try {
await nack();
} catch (e) {
this.deps?.logger?.error("OrchestrationWorker: error nacking event", { error: e });
}
return;
}
if (ack) try {
await ack();
} catch (e) {
this.deps?.logger?.error("OrchestrationWorker: error acking terminal event", { error: e });
}
}
};
// src/worker/workers/scheduler-worker.ts
/**
* Drives cron-based workflow and agent schedules. On each tick it polls
* storage for due schedules, computes next fire times, and publishes fire
* events. Does not consume events — only produces them.
*
* This is the **single** scheduler code path. `Mastra.startWorkers()` adds it
* when scheduling work exists or the scheduler is explicitly enabled.
*/
var SchedulerWorker = class extends MastraWorker {
name = "scheduler";
#scheduler;
#config;
#running = false;
constructor(config = {}) {
super();
this.#config = config;
}
async init(deps) {
await super.init(deps);
if (!deps.storage) {
deps.logger.warn("SchedulerWorker: no storage configured, scheduler will not run");
return;
}
const schedulesStore = await deps.storage.getStore("schedules");
if (!schedulesStore) {
deps.logger.warn("SchedulerWorker: no schedules store available, scheduler will not run");
return;
}
const mastra = this.mastra;
const isTargetReady = mastra ? async (target) => {
if (target.type === "workflow") try {
mastra.getWorkflowById(target.workflowId);
return true;
} catch {
return false;
}
if (target.type === "agent") return (await resolveAgentById(mastra, target.agentId)).status !== "missing";
return false;
} : void 0;
const isTargetCurrent = mastra ? (target) => {
if (target.type !== "workflow" || !target.definitionHash) return true;
try {
const workflow = mastra.getWorkflowById(target.workflowId);
const localHash = computeScheduleDefinitionHash(workflow.serializedStepGraph);
if (!localHash) return true;
return localHash === target.definitionHash;
} catch {
return true;
}
} : void 0;
const canExecuteLocally = mastra ? () => mastra.__hasLocalWorkflowExecution() : void 0;
this.#scheduler = new Scheduler({
schedulesStore,
pubsub: deps.pubsub,
config: {
...this.#config,
isTargetReady,
isTargetCurrent,
canExecuteLocally
}
});
this.#scheduler.__setLogger(deps.logger);
if (this.mastra) try {
await this.mastra.registerDeclarativeSchedules(schedulesStore);
} catch (err) {
deps.logger.error?.("SchedulerWorker: failed to register declarative schedules", { error: err });
}
}
async start() {
if (this.#running) return;
if (this.#scheduler) await this.#scheduler.start();
this.#running = true;
}
async stop() {
if (!this.#running) return;
if (this.#scheduler) await this.#scheduler.stop();
this.#running = false;
}
get isRunning() {
return this.#running;
}
/** Expose the underlying scheduler for direct API access (e.g., schedule management). */
get scheduler() {
return this.#scheduler;
}
};
// src/worker/workers/background-task-worker.ts
/**
* Manages background tool execution for agents. Handles task queuing,
* concurrency limits, and lifecycle. Subscribes to PubSub internally
* via BackgroundTaskManager's own subscription mechanism.
*/
var BackgroundTaskWorker = class extends MastraWorker {
name = "backgroundTasks";
#manager;
#ownsManager = false;
#config;
#running = false;
constructor(config = {}) {
super();
this.#config = config;
}
async init(deps) {
await super.init(deps);
const existing = deps.mastra?.backgroundTaskManager;
if (existing) {
this.#manager = existing;
this.#ownsManager = false;
return;
}
this.#createOwnedManager(deps);
}
#createOwnedManager(deps) {
this.#manager = new BackgroundTaskManager({
enabled: true,
mode: "worker",
globalConcurrency: this.#config.globalConcurrency,
perAgentConcurrency: this.#config.perAgentConcurrency,
perOwnerConcurrency: this.#config.perOwnerConcurrency,
backpressure: this.#config.backpressure,
defaultTimeoutMs: this.#config.defaultTimeoutMs
});
this.#ownsManager = true;
if (deps.mastra) {
this.#manager.__registerMastra(deps.mastra);
this.#wireStaticTools(deps.mastra);
}
}
/**
* Populate the manager's static executor registry from tools registered
* on `Mastra`, so that cross-process dispatches can be resolved by tool
* name on this worker. Mirrors the wiring Mastra does for its own
* managed background-task manager — the worker owns a separate manager
* instance, so it has to populate its own registry.
*/
#wireStaticTools(mastra) {
const tools = mastra.listTools?.call(mastra);
if (!tools || !this.#manager) return;
for (const [name, tool] of Object.entries(tools)) {
if (!tool || typeof tool.execute !== "function") continue;
const execute = tool.execute.bind(tool);
this.#manager.registerStaticExecutor(name, { execute: async (args, options) => {
return execute(args, {
toolCallId: "",
messages: [],
abortSignal: options?.abortSignal
});
} });
}
}
async start() {
if (this.#running) return;
if (!this.deps) throw new Error("BackgroundTaskWorker: call init() before start()");
if (!this.#manager) this.#createOwnedManager(this.deps);
const manager = this.#manager;
if (!manager) throw new Error("BackgroundTaskWorker: failed to initialize background task manager");
if (this.#ownsManager) await manager.init(this.deps.pubsub);
this.#running = true;
}
async stop() {
if (!this.#running) return;
if (this.#manager && this.#ownsManager) try {
await this.#manager.shutdown();
} finally {
this.#manager = void 0;
this.#ownsManager = false;
}
this.#running = false;
}
get isRunning() {
return this.#running;
}
/** Expose the underlying manager for direct API access. */
get manager() {
return this.#manager;
}
};
// src/worker/strategies/in-process-strategy.ts
/**
* Executes workflow steps in the same process by delegating to StepExecutor.
* This is the default strategy used when the worker runs co-located with the server.
*/
var InProcessStrategy = class {
#mastra;
constructor({ mastra } = {}) {
this.#mastra = mastra;
}
__registerMastra(mastra) {
this.#mastra = mastra;
}
async executeStep(params) {
if (!this.#mastra) throw new Error("InProcessStrategy requires Mastra instance. Call __registerMastra() first.");
const workflow = this.#resolveWorkflow(params);
const entry = workflow ? getStepEntry(workflow, params.executionPath) : null;
if (!entry) throw new Error(`InProcessStrategy: could not resolve step "${params.stepId}" at executionPath [${params.executionPath.join(",")}] in workflow "${params.workflowId}"`);
const rc = new RequestContext(Object.entries(params.requestContext ?? {}));
let abortController;
if (params.abortSignal) {
abortController = new AbortController();
if (params.abortSignal.aborted) abortController.abort(params.abortSignal.reason);
else params.abortSignal.addEventListener("abort", () => {
abortController.abort(params.abortSignal.reason);
}, { once: true });
}
return new StepExecutor({ mastra: this.#mastra }).execute({
workflowId: params.workflowId,
entry,
runId: params.runId,
stepResults: params.stepResults,
state: params.state,
requestContext: rc,
input: params.input,
resumeData: params.resumeData,
retryCount: params.retryCount,
foreachIdx: params.foreachIdx,
validateInputs: params.validateInputs,
abortController,
format: params.format,
perStep: params.perStep,
storageVersion: params.storageVersion
});
}
/**
* Resolves the workflow in the same order the dispatching
* `WorkflowEventProcessor` does: internal registrations first, then descent
* from the parent chain for nested workflows (which may be registered
* nowhere), then the public registry. Public lookups go through
* `getWorkflowById` because events carry the workflow's `id` property
* (e.g. "scheduled-workflow"), not the config key ("scheduledWorkflow").
*/
#resolveWorkflow(params) {
const mastra = this.#mastra;
if (mastra.__hasInternalWorkflow(params.workflowId, params.runId)) return mastra.__getInternalWorkflow(params.workflowId, params.runId);
if (params.parentWorkflow) return resolveNestedWorkflow(mastra, params.workflowId, params.parentWorkflow);
return mastra.getWorkflowById(params.workflowId);
}
};
/**
* Descends from `parentWorkflow` and returns the nested workflow only when it,
* and every workflow passed on the way, has the id the request names. The
* parent chain addresses workflows by position, so a worker and server running
* different builds could otherwise land on a different workflow and run it.
*/
function resolveNestedWorkflow(mastra, workflowId, parentWorkflow) {
if (parentWorkflow.parentWorkflow && !resolveNestedWorkflow(mastra, parentWorkflow.workflowId, parentWorkflow.parentWorkflow)) return null;
const workflow = getNestedWorkflow(mastra, parentWorkflow);
return workflow?.id === workflowId ? workflow : null;
}
export { PullTransport as a, MastraWorker as c, OrchestrationWorker as i, BackgroundTaskWorker as n, HttpRemoteStrategy as o, SchedulerWorker as r, StepExecutionError as s, InProcessStrategy as t };
//# sourceMappingURL=worker-Dz7t0AMX.js.map