UNPKG

@convex-dev/workflow

Version:

Convex component for durably executing workflows.

90 lines 3.01 kB
import { createFunctionHandle, getFunctionName, } from "convex/server"; import { workflowMutation } from "./workflowMutation.js"; export { vWorkflowId } from "../types.js"; export class WorkflowManager { component; options; constructor(component, options) { this.component = component; this.options = options; } /** * Define a new workflow. * * @param workflow - The workflow definition. * @returns The workflow mutation. */ define(workflow) { return workflowMutation(this.component, workflow, this.options?.workpoolOptions); } /** * Kick off a defined workflow. * * @param ctx - The Convex context. * @param workflow - The workflow to start (e.g. `internal.index.exampleWorkflow`). * @param args - The workflow arguments. * @returns The workflow ID. */ async start(ctx, workflow, args, options) { const handle = await createFunctionHandle(workflow); const onComplete = options?.onComplete ? { fnHandle: await createFunctionHandle(options.onComplete), context: options.context, } : undefined; const workflowId = await ctx.runMutation(this.component.workflow.create, { workflowName: getFunctionName(workflow), workflowHandle: handle, workflowArgs: args, maxParallelism: this.options?.workpoolOptions?.maxParallelism, onComplete, }); return workflowId; } /** * Get a workflow's status. * * @param ctx - The Convex context. * @param workflowId - The workflow ID. * @returns The workflow status. */ async status(ctx, workflowId) { const { workflow, inProgress } = await ctx.runQuery(this.component.workflow.getStatus, { workflowId }); const running = inProgress.map((entry) => entry.step); switch (workflow.runResult?.kind) { case undefined: return { type: "inProgress", running }; case "canceled": return { type: "canceled" }; case "failed": return { type: "failed", error: workflow.runResult.error }; case "success": return { type: "completed" }; } } /** * Cancel a running workflow. * * @param ctx - The Convex context. * @param workflowId - The workflow ID. */ async cancel(ctx, workflowId) { await ctx.runMutation(this.component.workflow.cancel, { workflowId, }); } /** * Clean up a completed workflow's storage. * * @param ctx - The Convex context. * @param workflowId - The workflow ID. * @returns - Whether the workflow's state was cleaned up. */ async cleanup(ctx, workflowId) { return await ctx.runMutation(this.component.workflow.cleanup, { workflowId, }); } } //# sourceMappingURL=index.js.map