@usehelical/workflows 0.0.1-alpha.12 → 0.0.1-alpha.2
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.
- package/dist/{index.d.ts → index.d.mts} +13 -2
- package/dist/index.mjs +3 -0
- package/dist/index.mjs.map +1 -0
- package/dist/{state-B89wwR8P.d.ts → state-CmpqDrnz.d.mts} +1 -13
- package/dist/workflows.d.mts +19 -0
- package/dist/workflows.mjs +7 -0
- package/dist/workflows.mjs.map +1 -0
- package/package.json +1 -3
- package/dist/chunk-WKVKC6AI.js +0 -650
- package/dist/chunk-WKVKC6AI.js.map +0 -1
- package/dist/index.js +0 -1028
- package/dist/index.js.map +0 -1
- package/dist/workflows.d.ts +0 -45
- package/dist/workflows.js +0 -334
- package/dist/workflows.js.map +0 -1
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../core/internal/events/polling-loop.ts","../core/internal/events/event-bus-core.ts","../core/internal/repository/get-state.ts","../core/internal/repository/get-state-batch.ts","../core/internal/events/state-event-bus.ts","../core/internal/repository/get-message-batch.ts","../core/internal/events/message-event-bus.ts","../client/run-workflow.ts","../core/internal/run-registry.ts","../core/internal/repository/get-operations.ts","../core/internal/repository/get-pending-runs.ts","../core/internal/repository/upsert-run.ts","../core/internal/recover-pending-runs.ts","../core/internal/workflow-registry.ts","../core/internal/repository/get-run-batch.ts","../core/internal/events/run-event-bus.ts","../core/internal/queue-registry.ts","../client/cancel-run.ts","../core/internal/repository/enqueue-run.ts","../client/queue-workflow.ts","../core/internal/repository/dequeue-run.ts","../core/internal/repository/get-executable-runs.ts","../core/internal/repository/get-queue-partitions.ts","../core/internal/queue-manager.ts","../core/internal/events/setup-postgres-notify.ts","../core/internal/db/driver-pg.ts","../core/internal/repository/resume-run.ts","../client/resume-run.ts","../core/internal/repository/insert-message.ts","../client/send-message.ts","../client/get-state.ts","../client/runtime.ts"],"names":["POLLING_FALLBACK_IN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AOC,SAAAA,CAAY,cAAA,EAAgB,MAAA,EAAQ,GAAG,CAAA;AAAA,IAChD;AAAA,GACF;AACF","file":"index.js","sourcesContent":["export class PollingLoop {\n private readonly intervalMs: number;\n private readonly jitterFactor: number;\n private intervalHandle: NodeJS.Timeout | null = null;\n private readonly callback: () => void;\n private running: boolean = false;\n\n constructor(intervalMs: number, callback: () => void, jitterFactor: number = 0.1) {\n this.intervalMs = intervalMs;\n this.callback = callback;\n this.jitterFactor = Math.max(0, Math.min(1, jitterFactor));\n }\n\n private calculateNextInterval(): number {\n const jitterRange = this.intervalMs * this.jitterFactor;\n const jitter = (Math.random() * 2 - 1) * jitterRange;\n return Math.max(0, this.intervalMs + jitter);\n }\n\n private scheduleNext() {\n if (!this.running) {\n return;\n }\n\n const nextInterval = this.calculateNextInterval();\n this.intervalHandle = setTimeout(() => {\n try {\n this.callback();\n } catch (error) {\n // Log error but continue polling\n console.error('PollingLoop callback error:', error);\n }\n this.scheduleNext();\n }, nextInterval);\n }\n\n start() {\n if (this.running) {\n return;\n }\n this.running = true;\n this.scheduleNext();\n }\n\n stop() {\n this.running = false;\n if (this.intervalHandle) {\n clearTimeout(this.intervalHandle);\n this.intervalHandle = null;\n }\n }\n\n isRunning(): boolean {\n return this.running;\n }\n}\n","import { PollingLoop } from './polling-loop';\n\nexport type SubscriptionCallback<T> = (data: T) => void;\n\nexport type Wildcard = '*';\n\ntype EventBusCoreConfig = {\n allowWildcardSubscriptions: boolean;\n};\n\nexport interface EventBus {\n handleNotify: (payload: string) => void;\n subscribe: CallableFunction;\n emitEvent: CallableFunction;\n destroy: () => void;\n}\n\nexport class EventBusCore<TEvent> {\n private readonly subscribers: Map<string, Set<SubscriptionCallback<TEvent>>> = new Map();\n private readonly eventSequence = new Map<string, number>();\n private readonly pollingLoop: PollingLoop;\n private readonly allowWildcardSubscriptions: boolean;\n\n constructor(\n private readonly config: EventBusCoreConfig,\n pollingLoop: PollingLoop,\n ) {\n this.allowWildcardSubscriptions = config.allowWildcardSubscriptions;\n this.pollingLoop = pollingLoop;\n }\n\n subscribe(subject: string, key: string | '*', callback: SubscriptionCallback<TEvent>) {\n const subscriptionKey = createSubscriptionKey(subject, key);\n if (!this.subscribers.has(subscriptionKey)) {\n this.subscribers.set(subscriptionKey, new Set());\n }\n this.subscribers.get(subscriptionKey)!.add(callback);\n this.pollingLoop.start();\n\n return () => this.unsubscribe(subscriptionKey, callback);\n }\n\n private unsubscribe(subscriptionKey: string, callback: SubscriptionCallback<TEvent>) {\n const subscriptionCallbacks = this.subscribers.get(subscriptionKey);\n if (subscriptionCallbacks) {\n subscriptionCallbacks.delete(callback);\n if (subscriptionCallbacks.size === 0) {\n this.subscribers.delete(subscriptionKey);\n this.eventSequence.delete(subscriptionKey);\n }\n }\n if (this.subscribers.size === 0) {\n this.pollingLoop.stop();\n }\n }\n\n emitEvent(subject: string, key: string, event: TEvent, eventChangeId: number) {\n const subscriptionKeys = [createSubscriptionKey(subject, key)].concat(\n this.allowWildcardSubscriptions ? [createSubscriptionKey(subject, '*')] : [],\n );\n for (const subscriptionKey of subscriptionKeys) {\n const subscribers = this.subscribers.get(subscriptionKey);\n if (subscribers) {\n for (const subscriptionCallback of subscribers) {\n subscriptionCallback(event);\n }\n }\n }\n this.eventSequence.set(subscriptionKeys[0], eventChangeId);\n }\n\n checkHasSubscribers(subject: string, key: string) {\n const subscriptionKeys = [createSubscriptionKey(subject, key)].concat(\n this.allowWildcardSubscriptions ? [createSubscriptionKey(subject, '*')] : [],\n );\n return subscriptionKeys.some((subscriptionKey) => this.subscribers.has(subscriptionKey));\n }\n\n getEventSequence(subject: string, key: string) {\n return this.eventSequence.get(createSubscriptionKey(subject, key)) ?? 0;\n }\n\n getSubscriptionKeys() {\n return Array.from(this.subscribers.keys()).map(splitSubscriptionKey);\n }\n}\n\nfunction createSubscriptionKey(subject: string, key: string) {\n return `${subject}::${key}`;\n}\n\nfunction splitSubscriptionKey(subscriptionKey: string) {\n return subscriptionKey.split('::');\n}\n","import { Database } from '../db/db';\n\nexport async function getState(\n db: Database,\n runId: string,\n key: string,\n): Promise<string | undefined> {\n const result = await db\n .selectFrom('state')\n .select(['key', 'value', 'change_id'])\n .where('run_id', '=', runId)\n .where('key', '=', key)\n .executeTakeFirst();\n\n if (!result) {\n return undefined;\n }\n\n return result.value;\n}\n","import { Database } from '../db/db';\nimport { StateRetrievalRequest } from '../events/state-event-bus';\n\nexport async function getStateBatch(db: Database, stateRetrievalRequests: StateRetrievalRequest) {\n const results = await db\n .selectFrom('state')\n .select(['key', 'value', 'change_id', 'run_id', 'change_id'])\n .where(\n 'run_id',\n 'in',\n stateRetrievalRequests.map((r) => r.runId),\n )\n .where(\n 'key',\n 'in',\n stateRetrievalRequests.map((r) => r.key),\n )\n .execute();\n return results.map((r) => ({\n runId: r.run_id,\n key: r.key,\n value: r.value,\n changeId: r.change_id,\n }));\n}\n","import { PollingLoop } from './polling-loop';\nimport { EventBus, EventBusCore } from './event-bus-core';\nimport { getState } from '../repository/get-state';\nimport { Database } from '../db/db';\nimport { getStateBatch } from '../repository/get-state-batch';\n\ntype SubscriptionCallback<T> = (data: T) => void;\n\nconst POLLING_FALLBACK_INTERVAL_MS = 10_000;\n\ntype StateEvent = unknown;\n\nexport class StateEventBus implements EventBus {\n private readonly bus: EventBusCore<StateEvent>;\n private readonly pollingLoop: PollingLoop;\n\n constructor(private readonly db: Database) {\n this.pollingLoop = new PollingLoop(POLLING_FALLBACK_INTERVAL_MS, this.handlePoll.bind(this));\n this.bus = new EventBusCore({ allowWildcardSubscriptions: false }, this.pollingLoop);\n this.pollingLoop.start();\n }\n\n handleNotify(payload: string) {\n const [workflowId, key, changeIdString] = payload.split('::');\n const changeId = Number(changeIdString);\n if (\n !this.bus.checkHasSubscribers(workflowId, key) ||\n this.bus.getEventSequence(workflowId, key) >= changeId\n ) {\n return;\n }\n getState(this.db, workflowId, key).then((state) => {\n if (!state) {\n return;\n }\n this.bus.emitEvent(workflowId, key, state, changeId);\n });\n }\n\n private async handlePoll() {\n const stateRetrievalRequests = getStateRetrievalRequests(this.bus.getSubscriptionKeys());\n if (stateRetrievalRequests.length === 0) {\n return;\n }\n const states = await getStateBatch(this.db, stateRetrievalRequests);\n for (const state of states) {\n if (this.bus.getEventSequence(state.runId, state.key) >= state.changeId) {\n continue;\n }\n this.bus.emitEvent(state.runId, state.key, state.value, state.changeId);\n }\n }\n\n subscribe<T>(workflowId: string, key: string, callback: SubscriptionCallback<T>) {\n return this.bus.subscribe(workflowId, key, callback as SubscriptionCallback<unknown>);\n }\n\n emitEvent<T>(workflowId: string, key: string, data: T, changeId: number) {\n this.bus.emitEvent(workflowId, key, data, changeId);\n }\n\n destroy() {\n this.pollingLoop.stop();\n }\n}\n\nfunction getStateRetrievalRequests(keys: string[][]) {\n return keys.map((k) => {\n const [runId, key] = k;\n return {\n runId,\n key,\n };\n });\n}\n\nexport type StateRetrievalRequest = ReturnType<typeof getStateRetrievalRequests>;\n","import { sql } from 'kysely';\nimport { Database } from '../db/db';\nimport { MessageRetrievalRequest } from '../events/message-event-bus';\n\nexport async function getMessageBatch(\n db: Database,\n messageRetrievalRequests: MessageRetrievalRequest,\n) {\n const uniquePairs = Array.from(\n new Map(\n messageRetrievalRequests.map((r) => [`${r.destinationWorkflowId}:${r.messageType}`, r]),\n ).values(),\n );\n\n const results = await db\n .selectFrom('messages')\n .select(['id', 'payload', 'type', 'destination_run_id'])\n .where(\n sql<boolean>`(destination_run_id, type) IN (${sql.join(\n uniquePairs.map((r) => sql`(${r.destinationWorkflowId}, ${r.messageType})`),\n )})`,\n )\n .execute();\n\n return results.map((r) => ({\n id: r.id,\n payload: r.payload,\n type: r.type,\n destinationRunId: r.destination_run_id,\n }));\n}\n","import { EventBus, EventBusCore } from './event-bus-core';\nimport { PollingLoop } from './polling-loop';\nimport { Database } from '../db/db';\nimport { getMessageBatch } from '../repository/get-message-batch';\n\ntype MessageEvent = undefined;\n\ntype MessageCallback = (event: MessageEvent) => void;\n\nconst POLLING_FALLBACK_INTERVAL_MS = 10_000;\n\nexport class MessageEventBus implements Omit<EventBus, 'emitEvent'> {\n private readonly bus: EventBusCore<MessageEvent>;\n private readonly pollingLoop: PollingLoop;\n\n constructor(private readonly db: Database) {\n this.pollingLoop = new PollingLoop(POLLING_FALLBACK_INTERVAL_MS, this.handlePoll.bind(this));\n this.bus = new EventBusCore({ allowWildcardSubscriptions: true }, this.pollingLoop);\n this.pollingLoop.start();\n }\n\n handleNotify(payload: string) {\n const [destinationWorkflowId, messageType, messageCount] = payload.split('::');\n if (!this.bus.checkHasSubscribers(destinationWorkflowId, messageType)) {\n return;\n }\n this.bus.emitEvent(destinationWorkflowId, messageType, undefined, Number(messageCount));\n }\n\n private async handlePoll() {\n const messageRetrievalRequests = getMessageRetrievalRequests(this.bus.getSubscriptionKeys());\n if (messageRetrievalRequests.length === 0) {\n return;\n }\n const messages = await getMessageBatch(this.db, messageRetrievalRequests);\n for (const message of messages) {\n this.bus.emitEvent(message.destinationRunId, message.type, undefined, 1);\n }\n }\n\n subscribe(destinationWorkflowId: string, type: string, cb: MessageCallback) {\n return this.bus.subscribe(destinationWorkflowId, type, cb);\n }\n\n destroy() {\n this.pollingLoop.stop();\n }\n}\n\nfunction getMessageRetrievalRequests(subscriptionKeys: string[][]) {\n return subscriptionKeys.map(([destinationWorkflowId, messageType]) => ({\n destinationWorkflowId,\n messageType,\n }));\n}\n\nexport type MessageRetrievalRequest = ReturnType<typeof getMessageRetrievalRequests>;\n","import crypto from 'node:crypto';\nimport { serialize } from '../core/internal/serialization';\nimport { WorkflowEntry, WorkflowFunction } from '../core/workflow';\nimport { executeWorkflow } from '../core/internal/execute-workflow';\nimport { RuntimeContext } from '../core/internal/runtime-context';\nimport { WorkflowNotFoundError } from '../core/internal/errors';\nimport { createRunHandle } from './run';\nimport { insertPendingRun } from '../core/internal/repository/insert-pending-run';\n\nexport type RunWorkflowOptions = {\n timeout?: number;\n deadline?: number;\n id?: string;\n};\n\nexport async function runWorkflow<TArgs extends unknown[], TReturn>(\n ctx: RuntimeContext,\n wf: WorkflowEntry<TArgs, TReturn> | string,\n args: TArgs = [] as unknown as TArgs,\n options: RunWorkflowOptions = {},\n) {\n const { db, executorId, workflowRegistry } = ctx;\n\n const workflow =\n typeof wf === 'string'\n ? workflowRegistry.getByName(wf)\n : workflowRegistry.getByWorkflowDefinition(wf);\n if (!workflow) {\n throw new WorkflowNotFoundError('Workflow not found');\n }\n\n const runId = options.id ?? crypto.randomUUID();\n\n const { path } = await insertPendingRun(db, {\n runId,\n path: [runId],\n inputs: serialize(args),\n executorId: executorId,\n workflowName: workflow.name,\n });\n\n await executeWorkflow<TArgs, TReturn>(ctx, {\n runId: runId,\n runPath: path,\n workflowName: workflow.name,\n fn: workflow.fn as WorkflowFunction<TArgs, TReturn>,\n args,\n options,\n });\n\n return createRunHandle<TReturn>(ctx, runId);\n}\n","import { ExecutionContext } from './execution-context';\n\nexport interface RunEntry<TReturn = unknown> {\n store: ExecutionContext;\n promise: Promise<TReturn>;\n abortController: AbortController;\n getPromiseState(): 'pending' | 'fulfilled' | 'rejected';\n}\n\nexport class RunRegistry {\n private readonly runs: Map<string, RunEntry> = new Map();\n\n registerRun(runId: string, entry: Omit<RunEntry, 'getPromiseState'>) {\n let state: 'pending' | 'fulfilled' | 'rejected' = 'pending';\n\n entry.promise.then(\n () => {\n state = 'fulfilled';\n },\n () => {\n state = 'rejected';\n },\n );\n\n this.runs.set(runId, {\n ...entry,\n getPromiseState: () => state,\n });\n }\n\n unregisterRun(runId: string) {\n this.runs.delete(runId);\n }\n\n getRun(runId: string) {\n return this.runs.get(runId);\n }\n}\n","import { Database } from '../db/db';\nimport { OperationResult } from '../operation-manager';\n\nexport async function getOperations(db: Database, runId: string): Promise<OperationResult[]> {\n const results = await db\n .selectFrom('operations')\n .select(['output', 'error'])\n .where('run_id', '=', runId)\n .orderBy('sequence_id', 'desc')\n .execute();\n return results.map((r) => ({\n result: r.output ?? undefined,\n error: r.error ?? undefined,\n }));\n}\n","import { WorkflowStatus } from '../../workflow';\nimport { Database } from '../db/db';\n\nexport async function getPendingRuns(db: Database, executorId: string) {\n const pendingRuns = await db\n .selectFrom('runs')\n .select(['id', 'path', 'inputs', 'workflow_name'])\n .where('status', '=', WorkflowStatus.PENDING)\n .where('executor_id', '=', executorId)\n .execute();\n\n return pendingRuns.map((run) => ({\n id: run.id,\n path: run.path,\n inputs: run.inputs,\n workflowName: run.workflow_name,\n }));\n}\n","import { sql } from 'kysely';\nimport { WorkflowStatus } from '../../workflow';\nimport { Database, Transaction } from '../db/db';\nimport { MaxRecoveryAttemptsExceededError } from '../errors';\n\nconst DEFAULT_MAX_RETRIES = 10;\n\nexport type UpsertRunOptions = {\n runId: string;\n path: string[];\n inputs: string;\n executorId: string;\n workflowName: string;\n parentRunId?: string;\n status: WorkflowStatus;\n idempotencyKey?: string;\n timeout?: number;\n deadline?: number;\n isRecovery?: boolean;\n maxRetries?: number;\n queueName?: string;\n};\n\nexport type UpsertRunResult = {\n runId: string;\n path: string[];\n changeId: number;\n executorId?: string;\n recoveryAttempts: number;\n idempotencyKey?: string;\n status: WorkflowStatus;\n shouldExecute: boolean;\n};\n\nexport async function upsertRun(\n db: Database | Transaction,\n options: UpsertRunOptions,\n): Promise<UpsertRunResult> {\n const incrementAttempts = options.isRecovery ? 1 : 0;\n const initialRecoveryAttempts = options.status === 'QUEUED' ? 0 : 1;\n\n const result = await db\n .insertInto('runs')\n .values({\n id: options.runId,\n path: options.path,\n workflow_name: options.workflowName,\n status: options.status,\n inputs: options.inputs,\n idempotency_key: options.idempotencyKey,\n executor_id: options.executorId,\n parent_run_id: options.parentRunId,\n timeout_ms: options.timeout,\n deadline_epoch_ms: options.deadline,\n recovery_attempts: initialRecoveryAttempts,\n queue_name: options.queueName,\n created_at: sql`(extract(epoch from now()) * 1000)::bigint`,\n updated_at: sql`(extract(epoch from now()) * 1000)::bigint`,\n })\n .onConflict((oc) =>\n oc.column('id').doUpdateSet({\n recovery_attempts: sql`CASE \n WHEN runs.status != 'QUEUED' \n THEN runs.recovery_attempts + ${incrementAttempts}\n ELSE runs.recovery_attempts\n END`,\n\n // Update executor_id when NEW status is not ENQUEUED\n // This allows dequeue operations to claim the workflow\n executor_id: sql`CASE \n WHEN EXCLUDED.status != 'QUEUED' \n THEN EXCLUDED.executor_id\n ELSE runs.executor_id\n END`,\n\n updated_at: sql`(extract(epoch from now()) * 1000)::bigint`,\n }),\n )\n .returning([\n 'id',\n 'change_id',\n 'recovery_attempts',\n 'executor_id',\n 'idempotency_key',\n 'status',\n 'path',\n ])\n .executeTakeFirst();\n\n if (!result) {\n throw new Error('Unexpectedly failed to upsert run');\n }\n\n // check if idempotency key matches\n const isOwner = result.idempotency_key === options.idempotencyKey;\n const shouldExecute = isOwner || options.isRecovery;\n\n // Check max recovery attempts if authorized to execute\n if (shouldExecute) {\n const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n if ((result.recovery_attempts as unknown as number) > maxRetries + 1) {\n // Mark as exceeded\n await db\n .updateTable('runs')\n .set({\n status: 'MAX_RECOVERY_ATTEMPTS_EXCEEDED',\n updated_at: sql`(extract(epoch from now()) * 1000)::bigint`,\n })\n .where('id', '=', result.id)\n .where('status', '=', 'PENDING')\n .execute();\n\n throw new MaxRecoveryAttemptsExceededError(result.id, maxRetries);\n }\n }\n\n return {\n runId: result.id,\n path: options.path,\n changeId: result.change_id,\n recoveryAttempts: result.recovery_attempts as unknown as number,\n executorId: result.executor_id ?? undefined,\n idempotencyKey: result.idempotency_key ?? undefined,\n status: result.status as WorkflowStatus,\n shouldExecute: shouldExecute ?? false,\n };\n}\n","import { WorkflowStatus } from '../workflow';\nimport { executeWorkflow } from './execute-workflow';\nimport { getOperations } from './repository/get-operations';\nimport { getPendingRuns } from './repository/get-pending-runs';\nimport { upsertRun } from './repository/upsert-run';\nimport { RuntimeContext } from './runtime-context';\nimport { deserialize } from './serialization';\n\nexport async function recoverPendingRuns(ctx: RuntimeContext) {\n const { db, executorId, workflowRegistry } = ctx;\n const pendingRuns = await getPendingRuns(db, executorId);\n for (const run of pendingRuns) {\n try {\n const operations = await getOperations(db, run.id);\n const workflow = workflowRegistry.getByName(run.workflowName);\n if (!workflow) {\n console.error(`Workflow ${run.workflowName} not found for recovery`);\n continue;\n }\n const args = run.inputs ? deserialize<unknown[]>(run.inputs) : [];\n const upsertResult = await upsertRun(db, {\n runId: run.id,\n path: run.path,\n inputs: run.inputs ?? '',\n executorId: executorId,\n workflowName: run.workflowName,\n status: WorkflowStatus.PENDING,\n isRecovery: true,\n });\n if (!upsertResult.shouldExecute) {\n console.log(`Run ${run.id} already executed, skipping recovery`);\n continue;\n }\n await executeWorkflow(ctx, {\n runId: upsertResult.runId,\n runPath: upsertResult.path,\n workflowName: run.workflowName,\n fn: workflow.fn,\n args: args,\n operations,\n });\n } catch (error) {\n console.error(`Error recovering run ${run.id}:`, error);\n }\n }\n}\n","import { WorkflowDefinition, WorkflowEntry } from '../workflow';\n\nexport class WorkflowRegistry {\n private readonly workflows: Record<string, WorkflowEntry> = {};\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n private readonly fnToName: Map<Function, string> = new Map();\n\n constructor(workflows: Record<string, WorkflowEntry>) {\n this.workflows = workflows;\n for (const [name, entry] of Object.entries(workflows)) {\n this.fnToName.set(entry, name);\n }\n }\n\n getByName(name: string): (WorkflowDefinition & { name: string }) | undefined {\n const entry = this.workflows[name];\n if (!entry) {\n return undefined;\n }\n return {\n ...entry(),\n name,\n };\n }\n\n getByWorkflowDefinition<TArgs extends unknown[], TReturn>(\n definition: WorkflowEntry<TArgs, TReturn>,\n ): (WorkflowDefinition<TArgs, TReturn> & { name: string }) | undefined {\n const name = this.fnToName.get(definition);\n if (!name) {\n return undefined;\n }\n return {\n ...definition(),\n name,\n };\n }\n}\n","import { WorkflowStatus } from '../../workflow';\nimport { Database } from '../db/db';\n\nexport async function getRunBatch(db: Database, runIds: string[]) {\n const results = await db\n .selectFrom('runs')\n .select(['id', 'inputs', 'output', 'error', 'status', 'change_id', 'queue_name'])\n .where('id', 'in', runIds)\n .execute();\n return results.map((r) => ({\n id: r.id,\n input: r.inputs ?? undefined,\n output: r.output ?? undefined,\n error: r.error ?? undefined,\n status: r.status as WorkflowStatus,\n changeId: r.change_id,\n queueName: r.queue_name ?? undefined,\n }));\n}\n","import { WorkflowStatus } from '../../workflow';\nimport { EventBus, EventBusCore } from './event-bus-core';\nimport { PollingLoop } from './polling-loop';\nimport { getRun } from '../repository/get-run';\nimport { getRunBatch } from '../repository/get-run-batch';\nimport { Database } from '../db/db';\n\ninterface RunEvent {\n status: WorkflowStatus;\n queueName?: string;\n result?: unknown;\n error?: string;\n}\n\ntype RunEventCallback = (e: RunEvent) => void;\n\nconst POLLING_FALLBACK_INTERVAL_MS = 10_000;\n\nexport class RunEventBus implements Omit<EventBus, 'emitEvent'> {\n private readonly bus: EventBusCore<RunEvent>;\n private readonly pollingLoop: PollingLoop;\n\n constructor(private readonly db: Database) {\n this.pollingLoop = new PollingLoop(POLLING_FALLBACK_INTERVAL_MS, this.handlePoll.bind(this));\n this.bus = new EventBusCore({ allowWildcardSubscriptions: true }, this.pollingLoop);\n this.pollingLoop.start();\n }\n\n handleNotify(payload: string) {\n const [runId, status, changeIdString] = payload.split('::');\n const changeId = Number(changeIdString);\n if (\n !this.bus.checkHasSubscribers(runId, status) ||\n this.bus.getEventSequence(runId, status) >= changeId\n ) {\n return;\n }\n getRun(this.db, runId).then((run) => {\n if (!run) {\n return;\n }\n this.bus.emitEvent(\n runId,\n status,\n {\n status: run.status,\n queueName: run.queueName,\n result: run.output,\n error: run.error,\n },\n changeId,\n );\n });\n }\n\n private async handlePoll() {\n const workflowIds = [\n ...new Set(this.bus.getSubscriptionKeys().map(([workflowId]) => workflowId)),\n ];\n if (workflowIds.length === 0) {\n return;\n }\n const runs = await getRunBatch(this.db, workflowIds);\n for (const run of runs) {\n this.bus.emitEvent(\n run.id,\n run.status,\n {\n status: run.status,\n queueName: run.queueName,\n result: run.output,\n error: run.error,\n },\n run.changeId,\n );\n }\n }\n\n subscribe(runId: string, status: WorkflowStatus | '*', cb: RunEventCallback) {\n return this.bus.subscribe(runId, status, cb);\n }\n\n destroy() {\n this.pollingLoop.stop();\n }\n}\n","import { QueueDefinition, QueueEntry } from '../queue';\nimport { QueueInstance } from './queue-manager';\n\nexport class QueueRegistry {\n private readonly queues: Record<string, QueueEntry> = {};\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n private readonly fnToName: Map<Function, string> = new Map();\n\n constructor(queues: Record<string, QueueEntry>) {\n this.queues = queues;\n for (const [name, entry] of Object.entries(queues)) {\n this.fnToName.set(entry, name);\n }\n }\n\n getByName(name: string): QueueDefinition | undefined {\n const entry = this.queues[name];\n if (!entry) {\n return undefined;\n }\n return {\n name,\n ...entry(),\n };\n }\n\n getByQueueEntry(entry: QueueEntry) {\n const name = this.fnToName.get(entry);\n if (!name) {\n return undefined;\n }\n return {\n ...entry(),\n name,\n };\n }\n\n getQueueInstances(): Record<string, QueueInstance> {\n return Object.entries(this.queues).reduce(\n (acc, [name, entry]) => {\n const options = entry();\n acc[name] = {\n rateLimit: options.rateLimit ?? undefined,\n workerConcurrency: options.workerConcurrency ?? undefined,\n concurrency: options.concurrency ?? undefined,\n priorityEnabled: options.priorityEnabled ?? undefined,\n };\n return acc;\n },\n {} as Record<string, QueueInstance>,\n );\n }\n}\n","import { RunNotFoundError } from '../core/internal/errors';\nimport { cancelRun as cancelRunInDb } from '../core/internal/repository/cancel-run';\nimport { RuntimeContext } from '../core/internal/runtime-context';\n\nexport async function cancelRun(ctx: RuntimeContext, runId: string) {\n const { db, runRegistry } = ctx;\n const run = await cancelRunInDb(runId, db);\n if (!run) {\n throw new RunNotFoundError(runId);\n }\n for (const pathPart of run.path) {\n const run = runRegistry.getRun(pathPart);\n if (run) {\n run.abortController.abort();\n }\n }\n}\n","import { sql } from 'kysely';\nimport { WorkflowStatus } from '../../workflow';\nimport { Database, Transaction } from '../db/db';\n\nexport type EnqueueRunOptions = {\n runId: string;\n path: string[];\n inputs: string;\n executorId: string;\n workflowName: string;\n timeout?: number;\n deadline?: number;\n recoveryAttempts?: number;\n deduplicationId?: string;\n queueName: string;\n queuePartitionKey?: string;\n};\n\nexport async function enqueueRun(db: Database | Transaction, options: EnqueueRunOptions) {\n const result = await db\n .insertInto('runs')\n .values({\n id: options.runId,\n path: options.path,\n inputs: options.inputs,\n queue_name: options.queueName,\n queue_partition_key: options.queuePartitionKey,\n queue_deduplication_id: options.deduplicationId,\n executor_id: options.executorId,\n workflow_name: options.workflowName,\n status: WorkflowStatus.QUEUED,\n recovery_attempts: options.recoveryAttempts,\n created_at: sql`(extract(epoch from now()) * 1000)::bigint`,\n updated_at: sql`(extract(epoch from now()) * 1000)::bigint`,\n })\n .onConflict((oc) => oc.columns(['queue_name', 'queue_deduplication_id']).doNothing())\n .returning(['id', 'change_id'])\n .executeTakeFirst();\n\n return {\n runId: result?.id,\n changeId: result?.change_id,\n };\n}\n","import { QueueNotFoundError, WorkflowNotFoundError } from '../core/internal/errors';\nimport { RuntimeContext } from '../core/internal/runtime-context';\nimport { serialize } from '../core/internal/serialization';\nimport { QueueEntry } from '../core/queue';\nimport { WorkflowEntry } from '../core/workflow';\nimport crypto from 'node:crypto';\nimport { createRunHandle } from './run';\nimport { enqueueRun } from '../core/internal/repository/enqueue-run';\n\nexport type QueueWorkflowOptions = {\n timeout?: number;\n deadline?: number;\n priority?: number;\n partitionKey?: string;\n deduplicationId?: string;\n};\n\nexport async function queueWorkflow<TArgs extends unknown[], TReturn>(\n ctx: RuntimeContext,\n queue: QueueEntry | string,\n wf: WorkflowEntry<TArgs, TReturn> | string,\n args?: TArgs,\n options?: QueueWorkflowOptions,\n) {\n const { db, executorId, workflowRegistry, queueRegistry } = ctx;\n\n const runId = crypto.randomUUID();\n\n const workflowName =\n typeof wf === 'string' ? wf : workflowRegistry.getByWorkflowDefinition(wf)?.name;\n if (!workflowName) {\n throw new WorkflowNotFoundError('Workflow name not specified');\n }\n\n const queueName = typeof queue === 'string' ? queue : queueRegistry.getByQueueEntry(queue)?.name;\n if (!queueName) {\n throw new QueueNotFoundError('Queue name not specified');\n }\n\n await enqueueRun(db, {\n runId,\n path: [runId],\n inputs: serialize(args),\n executorId,\n workflowName,\n timeout: options?.timeout,\n deadline: options?.deadline,\n queueName,\n });\n\n return createRunHandle<TReturn>(ctx, runId);\n}\n","import { sql } from 'kysely';\nimport { WorkflowStatus } from '../../workflow';\nimport { Transaction } from '../db/db';\nimport { RunNotFoundError } from '../errors';\n\nexport type DequeuedRun = {\n runId: string;\n changeId: number;\n path: string[];\n timeoutMs?: number;\n deadlineEpochMs?: number;\n inputs?: string;\n workflowName: string;\n};\n\nexport async function dequeueRun(\n tx: Transaction,\n runId: string,\n executorId: string,\n): Promise<DequeuedRun> {\n const result = await tx\n .updateTable('runs')\n .set({\n status: WorkflowStatus.PENDING,\n started_at_epoch_ms: sql`(extract(epoch from now()) * 1000)::bigint`,\n updated_at: sql`(extract(epoch from now()) * 1000)::bigint`,\n executor_id: executorId,\n })\n .where('id', '=', runId)\n .where('status', '=', WorkflowStatus.QUEUED)\n .returning([\n 'id',\n 'change_id',\n 'path',\n 'timeout_ms',\n 'deadline_epoch_ms',\n 'inputs',\n 'workflow_name',\n ])\n .executeTakeFirst();\n\n if (!result) {\n throw new RunNotFoundError(runId);\n }\n\n return {\n runId: result.id,\n changeId: result.change_id,\n path: result.path,\n timeoutMs: result.timeout_ms ? Number(result.timeout_ms) : undefined,\n deadlineEpochMs: result.deadline_epoch_ms ? Number(result.deadline_epoch_ms) : undefined,\n inputs: result.inputs ?? undefined,\n workflowName: result.workflow_name,\n };\n}\n","import { sql } from 'kysely';\nimport { QueueRateLimit } from '../../queue';\nimport { WorkflowStatus } from '../../workflow';\nimport { Database } from '../db/db';\nimport { withDbRetry } from '../db/retry';\nimport { DequeuedRun, dequeueRun } from './dequeue-run';\n\ntype GetExecutableRunsParams = {\n queueName: string;\n executorId: string;\n workerConcurrency?: number;\n globalConcurrency?: number;\n rateLimit?: QueueRateLimit;\n partitionKey?: string;\n priorityEnabled?: boolean;\n};\n\nexport async function getExecutableRuns(\n db: Database,\n {\n queueName,\n executorId,\n workerConcurrency,\n globalConcurrency,\n rateLimit,\n partitionKey,\n priorityEnabled,\n }: GetExecutableRunsParams,\n): Promise<DequeuedRun[]> {\n const startTimeMs = Date.now();\n const limiterPeriodMs = rateLimit ? rateLimit.period * 1000 : 0;\n\n return await withDbRetry(async () =>\n db.transaction().execute(async (tx) => {\n // rate limit check\n if (rateLimit) {\n const result = await tx\n .selectFrom('runs')\n .select(({ fn }) => [fn.count<number>('id').as('count')])\n .where('queue_name', '=', queueName)\n .where('status', '!=', WorkflowStatus.QUEUED)\n .where('started_at_epoch_ms', '>', (startTimeMs - limiterPeriodMs).toString())\n .$if(partitionKey !== undefined, (qb) =>\n qb.where('queue_partition_key', '=', partitionKey!),\n )\n .executeTakeFirstOrThrow();\n\n if (result.count >= rateLimit.limitPerPeriod) {\n return [];\n }\n }\n\n // Calculate concurrency\n let maxTasks = Infinity;\n\n if (globalConcurrency || workerConcurrency) {\n const runningTasks = await tx\n .selectFrom('runs')\n .select(['executor_id', ({ fn }) => fn.count<number>('id').as('task_count')])\n .where('queue_name', '=', queueName)\n .where('status', '=', WorkflowStatus.PENDING)\n .$if(partitionKey !== undefined, (qb) =>\n qb.where('queue_partition_key', '=', partitionKey!),\n )\n .groupBy('executor_id')\n .execute();\n\n const tasksByExecutor = Object.fromEntries(\n runningTasks.map((row) => [row.executor_id!, row.task_count]),\n );\n\n const runningForThisWorker = tasksByExecutor[executorId] ?? 0;\n\n if (workerConcurrency !== undefined) {\n maxTasks = Math.max(0, workerConcurrency - runningForThisWorker);\n }\n\n if (globalConcurrency !== undefined) {\n const totalRunning = Object.values(tasksByExecutor).reduce((a, b) => a + b, 0);\n const availableGlobal = Math.max(0, globalConcurrency - totalRunning);\n maxTasks = Math.min(maxTasks, availableGlobal);\n }\n\n if (maxTasks <= 0) {\n return [];\n }\n }\n\n const lockClause = globalConcurrency ? 'FOR UPDATE NOWAIT' : 'FOR UPDATE SKIP LOCKED';\n\n const workflowIds = await sql<{ id: string }>`\n SELECT id \n FROM runs\n WHERE status = ${WorkflowStatus.QUEUED}\n AND queue_name = ${queueName}\n ${partitionKey !== undefined ? sql`AND queue_partition_key = ${partitionKey}` : sql``}\n ${priorityEnabled ? sql`ORDER BY priority ASC, created_at ASC` : sql`ORDER BY created_at ASC`}\n ${maxTasks !== Infinity ? sql`LIMIT ${maxTasks}` : sql``}\n ${sql.raw(lockClause)}\n `.execute(tx);\n\n const claimedRuns: DequeuedRun[] = [];\n\n for (const { id } of workflowIds.rows) {\n const dequeuedRun = await dequeueRun(tx, id, executorId);\n claimedRuns.push(dequeuedRun);\n }\n\n return claimedRuns;\n }),\n );\n}\n","import { WorkflowStatus } from '../../workflow';\nimport { Database } from '../db/db';\n\nexport async function getQueuePartitions(db: Database, queueName: string): Promise<string[]> {\n const result = await db\n .selectFrom('runs')\n .select('queue_partition_key')\n .distinct()\n .where('queue_name', '=', queueName)\n .where('status', '=', WorkflowStatus.QUEUED)\n .where('queue_partition_key', 'is not', null)\n .execute();\n return result.map((row) => row.queue_partition_key!);\n}\n","import { PollingLoop } from './events/polling-loop';\nimport { getExecutableRuns } from './repository/get-executable-runs';\nimport { QueueRateLimit } from '../queue';\nimport { deserialize } from './serialization';\nimport { executeWorkflow } from './execute-workflow';\nimport { RuntimeContext } from './runtime-context';\nimport { getQueuePartitions } from './repository/get-queue-partitions';\n\nexport interface QueueInstance {\n rateLimit?: QueueRateLimit;\n workerConcurrency?: number;\n concurrency?: number;\n priorityEnabled?: boolean;\n partitioningEnabled?: boolean;\n}\n\nconst POLLING_INTERVAL_MS = 1000;\n\nexport class QueueManager {\n private readonly pollingLoop: PollingLoop;\n private readonly queues: Record<string, QueueInstance> = {};\n\n constructor(private readonly ctx: RuntimeContext) {\n this.pollingLoop = new PollingLoop(POLLING_INTERVAL_MS, this.handlePoll.bind(this));\n this.queues = this.ctx.queueRegistry.getQueueInstances();\n }\n\n private async handlePoll() {\n for (const [queueName, queue] of Object.entries(this.queues)) {\n await this.dispatch(queueName, queue);\n }\n }\n\n private async dispatch(queueName: string, queue: QueueInstance) {\n const { db, executorId } = this.ctx;\n\n let partitions: string[] = [];\n\n if (queue.partitioningEnabled) {\n partitions = await getQueuePartitions(db, queueName);\n\n for (const partition of partitions) {\n const runs = await getExecutableRuns(db, {\n queueName,\n executorId,\n workerConcurrency: queue.workerConcurrency,\n globalConcurrency: queue.concurrency,\n rateLimit: queue.rateLimit,\n partitionKey: partition,\n priorityEnabled: queue.priorityEnabled,\n });\n for (const run of runs) {\n const workflow = this.ctx.workflowRegistry.getByName(run.workflowName);\n if (!workflow) {\n console.error(`Workflow ${run.workflowName} not found`);\n continue;\n }\n await executeWorkflow(this.ctx, {\n runId: run.runId,\n runPath: run.path,\n workflowName: run.workflowName,\n fn: workflow.fn,\n args: deserialize<unknown[]>(run.inputs ?? '[]'),\n });\n }\n }\n return;\n }\n\n const runs = await getExecutableRuns(db, {\n queueName,\n executorId,\n workerConcurrency: queue.workerConcurrency,\n globalConcurrency: queue.concurrency,\n rateLimit: queue.rateLimit,\n priorityEnabled: queue.priorityEnabled,\n });\n for (const run of runs) {\n const workflow = this.ctx.workflowRegistry.getByName(run.workflowName);\n if (!workflow) {\n console.error(`Workflow ${run.workflowName} not found`);\n continue;\n }\n await executeWorkflow(this.ctx, {\n runId: run.runId,\n runPath: run.path,\n workflowName: run.workflowName,\n fn: workflow.fn,\n args: deserialize<unknown[]>(run.inputs ?? '[]'),\n });\n }\n }\n\n start() {\n this.pollingLoop.start();\n }\n\n destroy() {\n this.pollingLoop.stop();\n }\n}\n","import { Client } from '../db/driver-pg';\nimport { withDbRetry } from '../db/retry';\n\ntype SubscriptionCallback<T> = (data: T) => void;\n\nconst CHANNELS = ['runs', 'messages', 'state'];\n\ntype Channel = (typeof CHANNELS)[number];\n\ntype Subscriptions = {\n [K in Channel]: SubscriptionCallback<any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n};\n\nexport async function setupPostgresNotify(client: Client, subscriptions: Subscriptions) {\n await withDbRetry(async () => {\n try {\n await client.query(`BEGIN`);\n for (const channel of CHANNELS) {\n await client.query(`LISTEN \"helical_${channel}\"`);\n }\n await client.query(`COMMIT`);\n } catch (error) {\n await client.query(`ROLLBACK`);\n throw error;\n }\n\n for (const [channel, callback] of Object.entries(subscriptions)) {\n await client.listen(`helical_${channel}`, callback);\n }\n });\n}\n","import { Kysely, PostgresDialect } from 'kysely';\nimport { Pool, PoolClient } from 'pg';\nimport { DB } from './types';\nimport { Database } from './db';\n\nexport interface Client {\n listen(channel: string, callback: (payload: string | undefined) => void): Promise<void>;\n query(query: string): Promise<void>;\n}\n\nexport interface DbDriver {\n client: Client;\n db: Database;\n}\n\nexport function createPgDriver({ connectionString }: { connectionString: string }): DbDriver {\n const pool = new Pool({\n connectionString: connectionString,\n max: 10,\n });\n let clientPromise: Promise<PoolClient> | undefined;\n const getClient = async () => {\n if (!clientPromise) {\n clientPromise = pool.connect();\n }\n return await clientPromise;\n };\n return {\n client: {\n listen: async (channel: string, callback: (payload: string | undefined) => void) => {\n const client = await getClient();\n client.on('notification', (msg) => {\n if (msg.channel !== channel) return;\n callback(msg.payload);\n });\n },\n query: async (query: string) => {\n const client = await getClient();\n await client.query(query);\n },\n },\n db: new Kysely<DB>({ dialect: new PostgresDialect({ pool }) }),\n };\n}\n","import { sql } from 'kysely';\nimport { WorkflowStatus } from '../../workflow';\nimport { Database, Transaction } from '../db/db';\nimport { RunNotFoundError } from '../errors';\n\nconst INTERNAL_QUEUE_NAME = '_helical_internal_queue';\n\nexport async function resumeRun(db: Database | Transaction, runId: string) {\n const result = await db\n .updateTable('runs')\n .set({\n status: WorkflowStatus.QUEUED,\n queue_name: INTERNAL_QUEUE_NAME,\n deadline_epoch_ms: null,\n timeout_ms: null,\n recovery_attempts: 0,\n started_at_epoch_ms: sql`(extract(epoch from now()) * 1000)::bigint`,\n updated_at: sql`(extract(epoch from now()) * 1000)::bigint`,\n })\n .where('id', '=', runId)\n .where('status', '=', WorkflowStatus.PENDING)\n .execute();\n\n if (!result) {\n throw new RunNotFoundError(runId);\n }\n}\n","import { RuntimeContext } from '../core/internal/runtime-context';\nimport { resumeRun as resumeRunInDb } from '../core/internal/repository/resume-run';\nimport { createRunHandle } from './run';\n\nexport async function resumeRun(ctx: RuntimeContext, runId: string) {\n const { db } = ctx;\n await resumeRunInDb(db, runId);\n return createRunHandle<void>(ctx, runId);\n}\n","import { Database, Transaction } from '../db/db';\n\ntype InsertMessageOptions = {\n destinationWorkflowId: string;\n messageType: string;\n data: string;\n};\n\nexport async function insertMessage(db: Database | Transaction, options: InsertMessageOptions) {\n return await db\n .insertInto('messages')\n .values({\n destination_run_id: options.destinationWorkflowId,\n type: options.messageType,\n payload: options.data,\n })\n .execute();\n}\n","import { RuntimeContext } from '../core/internal/runtime-context';\nimport { serialize } from '../core/internal/serialization';\nimport { MessageDefinition } from '../core/message';\nimport { Run } from './run';\nimport { insertMessage } from '../core/internal/repository/insert-message';\n\nexport async function sendMessage(\n ctx: RuntimeContext,\n target: Run | string,\n name: MessageDefinition<unknown> | string,\n data?: unknown,\n) {\n const { db } = ctx;\n\n const destinationWorkflowId = typeof target === 'string' ? target : target.id;\n const messageType = typeof name === 'string' ? name : name.name;\n const serializedData = serialize(data);\n\n await insertMessage(db, {\n destinationWorkflowId,\n messageType,\n data: serializedData,\n });\n}\n","import { withDbRetry } from '../core/internal/db/retry';\nimport { RuntimeContext } from '../core/internal/runtime-context';\nimport { StateDefinition } from '../core/state';\nimport { getState as getStateRepository } from '../core/internal/repository/get-state';\nimport { Run } from './run';\nimport { deserialize } from '../core/internal/serialization';\nimport { StateEventBus } from '../core/internal/events/state-event-bus';\n\nclass StateNotAvailableError extends Error {}\n\nexport async function getState<T>(\n ctx: RuntimeContext,\n target: Run | string,\n key: StateDefinition<T> | string,\n) {\n const { db, stateEventBus } = ctx;\n\n const destinationWorkflowId = typeof target === 'string' ? target : target.id;\n const stateKey = typeof key === 'string' ? key : key.name;\n\n while (true) {\n try {\n return await withDbRetry(async () => {\n const state = await getStateRepository(db, destinationWorkflowId, stateKey);\n if (!state) {\n throw new StateNotAvailableError();\n }\n return deserialize(state) as T;\n });\n } catch (error) {\n if (error instanceof StateNotAvailableError) {\n await waitForStateNotification(stateEventBus, destinationWorkflowId, stateKey);\n continue;\n }\n throw error;\n }\n }\n}\n\nasync function waitForStateNotification(stateEventBus: StateEventBus, runId: string, key: string) {\n return new Promise((resolve) => {\n const unsubscribe = stateEventBus.subscribe(runId, key, (state) => {\n unsubscribe();\n resolve(state);\n });\n });\n}\n","import crypto from 'node:crypto';\nimport { QueueEntry } from '../core/queue';\nimport { WorkflowEntry } from '../core/workflow';\nimport { StateEventBus } from '../core/internal/events/state-event-bus';\nimport { MessageEventBus } from '../core/internal/events/message-event-bus';\nimport { runWorkflow, RunWorkflowOptions } from './run-workflow';\nimport { RunRegistry } from '../core/internal/run-registry';\nimport { recoverPendingRuns } from '../core/internal/recover-pending-runs';\nimport { RuntimeContext } from '../core/internal/runtime-context';\nimport { WorkflowRegistry } from '../core/internal/workflow-registry';\nimport { RunEventBus } from '../core/internal/events/run-event-bus';\nimport { createRunHandle, Run } from './run';\nimport { QueueRegistry } from '../core/internal/queue-registry';\nimport { cancelRun } from './cancel-run';\nimport { queueWorkflow, QueueWorkflowOptions } from './queue-workflow';\nimport { QueueManager } from '../core/internal/queue-manager';\nimport { setupPostgresNotify } from '../core/internal/events/setup-postgres-notify';\nimport { createPgDriver } from '../core/internal/db/driver-pg';\nimport { resumeRun } from './resume-run';\nimport { MessageDefinition } from '../core/message';\nimport { sendMessage } from './send-message';\nimport { StateDefinition } from '../core/state';\nimport { getState } from './get-state';\n\ntype CreateInstanceOptions = {\n instanceId?: string;\n connectionString: string;\n};\n\nexport type CreateInstanceParams = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n workflows: Record<string, WorkflowEntry<any, any>>;\n queues?: Record<string, QueueEntry>;\n options: CreateInstanceOptions;\n};\n\nexport function createInstance(props: CreateInstanceParams) {\n const { db, client } = createPgDriver({ connectionString: props.options.connectionString });\n const messageEventBus = new MessageEventBus(db);\n const stateEventBus = new StateEventBus(db);\n const executorId = props.options.instanceId || crypto.randomUUID();\n const runRegistry = new RunRegistry();\n const workflowRegistry = new WorkflowRegistry(props.workflows);\n const runEventBus = new RunEventBus(db);\n const queueRegistry = new QueueRegistry(props.queues || {});\n\n const runtimeContext: RuntimeContext = {\n db,\n executorId,\n messageEventBus,\n stateEventBus,\n runRegistry,\n workflowRegistry,\n runEventBus,\n queueRegistry,\n };\n\n const notifySetupPromise = setupPostgresNotify(client, {\n runs: runEventBus.handleNotify.bind(runEventBus),\n state: stateEventBus.handleNotify.bind(stateEventBus),\n messages: messageEventBus.handleNotify.bind(messageEventBus),\n });\n\n const queueManager = new QueueManager(runtimeContext);\n queueManager.start();\n\n recoverPendingRuns(runtimeContext);\n\n return {\n runWorkflow: async <TArgs extends unknown[], TReturn>(\n wf: WorkflowEntry<TArgs, TReturn> | string,\n args?: TArgs,\n options?: RunWorkflowOptions,\n ) => {\n await notifySetupPromise;\n return runWorkflow<TArgs, TReturn>(runtimeContext, wf, args, options);\n },\n cancelRun: async (runId: string) => cancelRun(runtimeContext, runId),\n resumeRun: async (runId: string) => resumeRun(runtimeContext, runId),\n getRun: async (runId: string) => {\n await notifySetupPromise;\n return createRunHandle(runtimeContext, runId);\n },\n queueWorkflow: async <TArgs extends unknown[], TReturn>(\n queue: QueueEntry | string,\n wf: WorkflowEntry<TArgs, TReturn> | string,\n args?: TArgs,\n options?: QueueWorkflowOptions,\n ) => {\n await notifySetupPromise;\n return queueWorkflow<TArgs, TReturn>(runtimeContext, queue, wf, args, options);\n },\n sendMessage: async <T>(target: Run | string, name: MessageDefinition<T>, data: T) => {\n await notifySetupPromise;\n return sendMessage(runtimeContext, target, name, data);\n },\n getState: async <T>(target: Run | string, key: StateDefinition<T> | string) => {\n await notifySetupPromise;\n return getState<T>(runtimeContext, target, key);\n },\n };\n}\n\nexport type Instance = ReturnType<typeof createInstance>;\n"]}
|
package/dist/workflows.d.ts
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import { S as StateDefinition, M as MessageDefinition, W as WorkflowEntry, R as RunWorkflowOptions, a as Run } from './state-B89wwR8P.js';
|
|
2
|
-
export { b as QueueDefinition, Q as QueueEntry, c as QueueOptions, d as QueueRateLimit, e as WorkflowDefinition, f as WorkflowFunction, g as WorkflowStatus, h as defineMessage, i as defineQueue, j as defineState, k as defineWorkflow } from './state-B89wwR8P.js';
|
|
3
|
-
|
|
4
|
-
type RetryConfig = {
|
|
5
|
-
maxRetries?: number;
|
|
6
|
-
retryDelay?: number;
|
|
7
|
-
backOffRate?: number;
|
|
8
|
-
};
|
|
9
|
-
type RunStepOptions = RetryConfig & {
|
|
10
|
-
name?: string;
|
|
11
|
-
};
|
|
12
|
-
declare function runStep<TReturn>(stepFn: () => Promise<TReturn>, options?: RunStepOptions): Promise<TReturn | (TReturn extends void ? void : TReturn)>;
|
|
13
|
-
declare function executeStepWithRetries<TReturn>(stepName: string, fn: () => Promise<TReturn>, retryConfig: RetryConfig): Promise<TReturn>;
|
|
14
|
-
|
|
15
|
-
declare function setState<T = unknown>(state: StateDefinition<T> | string, value: T): Promise<void>;
|
|
16
|
-
|
|
17
|
-
type ReceiveMessageOptions = {
|
|
18
|
-
timeout?: number;
|
|
19
|
-
};
|
|
20
|
-
declare function receiveMessage<T>(message: MessageDefinition<T> | string, options?: ReceiveMessageOptions): Promise<T>;
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* Generates a stable, unique step ID based on the current run ID and sequence ID.
|
|
24
|
-
* This ID is deterministic and will remain the same across retries, making it
|
|
25
|
-
* suitable for use as an idempotency key with third-party systems.
|
|
26
|
-
*
|
|
27
|
-
* The step ID is a SHA-256 hash of the run ID and sequence ID, formatted as a
|
|
28
|
-
* hex string for easy use with external APIs.
|
|
29
|
-
*
|
|
30
|
-
* @returns A unique, stable identifier for the current step execution
|
|
31
|
-
*/
|
|
32
|
-
declare function getStepId(): string;
|
|
33
|
-
|
|
34
|
-
declare function getAbortSignal(): AbortSignal;
|
|
35
|
-
|
|
36
|
-
declare function getRunId(): string;
|
|
37
|
-
|
|
38
|
-
declare function sleep(ms: number): Promise<void>;
|
|
39
|
-
declare function cancellableSleep(ms: number, signal?: AbortSignal): Promise<void>;
|
|
40
|
-
|
|
41
|
-
declare function randomUUID(): Promise<string | undefined>;
|
|
42
|
-
|
|
43
|
-
declare function runWorkflow<TArgs extends unknown[], TReturn>(wf: WorkflowEntry<TArgs, TReturn> | string, args?: TArgs, options?: RunWorkflowOptions): Promise<Run<TReturn>>;
|
|
44
|
-
|
|
45
|
-
export { MessageDefinition, type ReceiveMessageOptions, type RetryConfig, StateDefinition, WorkflowEntry, cancellableSleep, executeStepWithRetries, getAbortSignal, getRunId, getStepId, randomUUID, receiveMessage, runStep, runWorkflow, setState, sleep };
|
package/dist/workflows.js
DELETED
|
@@ -1,334 +0,0 @@
|
|
|
1
|
-
import { getExecutionContext, returnOrThrowOperationResult, executeAndRecordOperation, FatalError, MaxRetriesExceededError, sleep, ErrorThatShouldNeverHappen, withDbRetry, serialize, WorkflowNotFoundError, deserializeError, deserialize, createRunHandle, insertPendingRun, executeWorkflow, TimeoutError, serializeError, RunCancelledError } from './chunk-WKVKC6AI.js';
|
|
2
|
-
export { WorkflowStatus, defineWorkflow } from './chunk-WKVKC6AI.js';
|
|
3
|
-
import { sql } from 'kysely';
|
|
4
|
-
import crypto, { createHash } from 'crypto';
|
|
5
|
-
|
|
6
|
-
// core/message.ts
|
|
7
|
-
function defineMessage(name) {
|
|
8
|
-
return { name };
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
// core/queue.ts
|
|
12
|
-
function defineQueue(options = {}) {
|
|
13
|
-
return () => options;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
// core/state.ts
|
|
17
|
-
function defineState(name) {
|
|
18
|
-
return {
|
|
19
|
-
name
|
|
20
|
-
};
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
// core/steps/run-step.ts
|
|
24
|
-
async function runStep(stepFn, options = {}) {
|
|
25
|
-
const { maxRetries, retryDelay, backOffRate } = options;
|
|
26
|
-
const { operationManager } = getExecutionContext();
|
|
27
|
-
const stepName = options.name || stepFn.name || "<unknown>";
|
|
28
|
-
const op = operationManager.getOperationResult();
|
|
29
|
-
if (op) {
|
|
30
|
-
return returnOrThrowOperationResult(op);
|
|
31
|
-
}
|
|
32
|
-
return await executeAndRecordOperation(operationManager, stepName, async () => {
|
|
33
|
-
return await executeStepWithRetries(stepName, stepFn, { maxRetries, retryDelay, backOffRate });
|
|
34
|
-
});
|
|
35
|
-
}
|
|
36
|
-
async function executeStepWithRetries(stepName, fn, retryConfig) {
|
|
37
|
-
const maxRetries = retryConfig.maxRetries ?? 0;
|
|
38
|
-
const retryDelay = retryConfig.retryDelay ?? 0;
|
|
39
|
-
const backOffRate = retryConfig.backOffRate ?? 1;
|
|
40
|
-
const attemptErrors = [];
|
|
41
|
-
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
42
|
-
try {
|
|
43
|
-
return await fn();
|
|
44
|
-
} catch (error) {
|
|
45
|
-
const err = error instanceof Error ? error : new Error(String(error));
|
|
46
|
-
attemptErrors.push(err);
|
|
47
|
-
if (err instanceof FatalError) {
|
|
48
|
-
throw err;
|
|
49
|
-
}
|
|
50
|
-
if (maxRetries === 0) {
|
|
51
|
-
throw err;
|
|
52
|
-
}
|
|
53
|
-
if (attempt >= maxRetries) {
|
|
54
|
-
throw new MaxRetriesExceededError(stepName, maxRetries, attemptErrors);
|
|
55
|
-
}
|
|
56
|
-
const delay = retryDelay * Math.pow(backOffRate, attempt);
|
|
57
|
-
await sleep(delay);
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
throw new ErrorThatShouldNeverHappen(`Step "${stepName}" should never be reached`);
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
// core/internal/repository/insert-state.ts
|
|
64
|
-
async function insertState(tx, options) {
|
|
65
|
-
await tx.insertInto("state").values({
|
|
66
|
-
run_id: options.runId,
|
|
67
|
-
key: options.key,
|
|
68
|
-
value: options.value
|
|
69
|
-
}).onConflict(
|
|
70
|
-
(oc) => oc.column("run_id").column("key").doUpdateSet({
|
|
71
|
-
value: options.value
|
|
72
|
-
})
|
|
73
|
-
).execute();
|
|
74
|
-
await tx.insertInto("state_history").values({
|
|
75
|
-
run_id: options.runId,
|
|
76
|
-
sequence_id: options.sequenceId,
|
|
77
|
-
key: options.key,
|
|
78
|
-
value: options.value
|
|
79
|
-
}).execute();
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
// core/steps/set-state.ts
|
|
83
|
-
var SET_STATE_OPERATION_NAME = "workflow::state::set";
|
|
84
|
-
async function setState(state, value) {
|
|
85
|
-
const stateKey = typeof state === "string" ? state : state.name;
|
|
86
|
-
const { operationManager, runId, db } = getExecutionContext();
|
|
87
|
-
const op = operationManager.getOperationResult();
|
|
88
|
-
if (op) {
|
|
89
|
-
return returnOrThrowOperationResult(op);
|
|
90
|
-
}
|
|
91
|
-
const seqId = operationManager.reserveSequenceId();
|
|
92
|
-
await withDbRetry(async () => {
|
|
93
|
-
return await db.transaction().execute(async (tx) => {
|
|
94
|
-
await insertState(tx, { runId, key: stateKey, value: serialize(value), sequenceId: seqId });
|
|
95
|
-
await operationManager.recordResult(SET_STATE_OPERATION_NAME, seqId, null, tx);
|
|
96
|
-
});
|
|
97
|
-
});
|
|
98
|
-
}
|
|
99
|
-
async function readAndDeleteMessage(tx, runId, messageType) {
|
|
100
|
-
const results = await sql`
|
|
101
|
-
DELETE FROM messages
|
|
102
|
-
WHERE id IN (
|
|
103
|
-
SELECT id FROM messages
|
|
104
|
-
WHERE destination_run_id = ${runId}
|
|
105
|
-
${messageType !== void 0 ? sql`AND type = ${messageType}` : sql``}
|
|
106
|
-
ORDER BY created_at_epoch_ms ASC
|
|
107
|
-
LIMIT 1
|
|
108
|
-
)
|
|
109
|
-
RETURNING id, payload, type
|
|
110
|
-
`.execute(tx);
|
|
111
|
-
const result = results.rows[0];
|
|
112
|
-
return result ? {
|
|
113
|
-
id: result.id,
|
|
114
|
-
payload: result.payload ?? void 0,
|
|
115
|
-
type: result.type ?? void 0
|
|
116
|
-
} : void 0;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
// core/internal/with-durable-deadline.ts
|
|
120
|
-
async function withDurableDeadline(timeoutMs, operationName, fn) {
|
|
121
|
-
if (!timeoutMs) {
|
|
122
|
-
return await fn(void 0);
|
|
123
|
-
}
|
|
124
|
-
const { operationManager } = getExecutionContext();
|
|
125
|
-
let deadlineMs;
|
|
126
|
-
const op = operationManager.getOperationResult();
|
|
127
|
-
if (op) {
|
|
128
|
-
deadlineMs = Number(op.result);
|
|
129
|
-
} else {
|
|
130
|
-
deadlineMs = Date.now() + timeoutMs;
|
|
131
|
-
await executeAndRecordOperation(operationManager, operationName, async () => {
|
|
132
|
-
return deadlineMs;
|
|
133
|
-
});
|
|
134
|
-
}
|
|
135
|
-
return await fn(deadlineMs);
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
// core/steps/receive-message.ts
|
|
139
|
-
var RECEIVE_MESSAGE_OPERATION_NAME = "workflow::message::receive";
|
|
140
|
-
var RECEIVE_MESSAGE_DURABLE_DEADLINE_OPERATION_NAME = "workflow::message::receive::durable-deadline";
|
|
141
|
-
var MessageNotAvailableError = class extends Error {
|
|
142
|
-
};
|
|
143
|
-
async function receiveMessage(message, options) {
|
|
144
|
-
const messageType = typeof message === "string" ? message : message.name;
|
|
145
|
-
return await withDurableDeadline(
|
|
146
|
-
options?.timeout,
|
|
147
|
-
RECEIVE_MESSAGE_DURABLE_DEADLINE_OPERATION_NAME,
|
|
148
|
-
async (deadlineMs) => {
|
|
149
|
-
return await receiveMessageWithDeadline(messageType, deadlineMs);
|
|
150
|
-
}
|
|
151
|
-
);
|
|
152
|
-
}
|
|
153
|
-
async function receiveMessageWithDeadline(messageType, deadlineMs) {
|
|
154
|
-
const { runId, operationManager, messageEventBus, db } = getExecutionContext();
|
|
155
|
-
const op = operationManager.getOperationResult();
|
|
156
|
-
if (op) {
|
|
157
|
-
return returnOrThrowOperationResult(op);
|
|
158
|
-
}
|
|
159
|
-
const seqId = operationManager.reserveSequenceId();
|
|
160
|
-
while (true) {
|
|
161
|
-
if (deadlineMs && Date.now() >= deadlineMs) {
|
|
162
|
-
const error = new TimeoutError(`Timed out waiting for message "${messageType}"`);
|
|
163
|
-
await operationManager.recordError(
|
|
164
|
-
RECEIVE_MESSAGE_OPERATION_NAME,
|
|
165
|
-
seqId,
|
|
166
|
-
serializeError(error)
|
|
167
|
-
);
|
|
168
|
-
throw error;
|
|
169
|
-
}
|
|
170
|
-
try {
|
|
171
|
-
return await withDbRetry(async () => {
|
|
172
|
-
return await db.transaction().execute(async (tx) => {
|
|
173
|
-
const msg = await readAndDeleteMessage(tx, runId, messageType);
|
|
174
|
-
if (!msg) {
|
|
175
|
-
throw new MessageNotAvailableError();
|
|
176
|
-
}
|
|
177
|
-
await operationManager.recordResult(
|
|
178
|
-
RECEIVE_MESSAGE_OPERATION_NAME,
|
|
179
|
-
seqId,
|
|
180
|
-
serialize(msg.payload),
|
|
181
|
-
tx
|
|
182
|
-
);
|
|
183
|
-
return deserialize(msg.payload);
|
|
184
|
-
});
|
|
185
|
-
});
|
|
186
|
-
} catch (error) {
|
|
187
|
-
if (error instanceof MessageNotAvailableError) {
|
|
188
|
-
const remainingMs = deadlineMs ? deadlineMs - Date.now() : void 0;
|
|
189
|
-
await waitForMessageNotification(messageEventBus, runId, messageType, remainingMs);
|
|
190
|
-
continue;
|
|
191
|
-
}
|
|
192
|
-
await operationManager.recordError(
|
|
193
|
-
RECEIVE_MESSAGE_OPERATION_NAME,
|
|
194
|
-
seqId,
|
|
195
|
-
serializeError(error)
|
|
196
|
-
);
|
|
197
|
-
throw error;
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
async function waitForMessageNotification(messageEventBus, runId, messageType, timeoutMs) {
|
|
202
|
-
return new Promise((resolve, reject) => {
|
|
203
|
-
let timeoutId;
|
|
204
|
-
if (timeoutMs !== void 0) {
|
|
205
|
-
if (timeoutMs <= 0) {
|
|
206
|
-
reject(new TimeoutError("Timeout expired"));
|
|
207
|
-
return;
|
|
208
|
-
}
|
|
209
|
-
timeoutId = setTimeout(() => {
|
|
210
|
-
unsubscribe();
|
|
211
|
-
reject(new TimeoutError("Timeout waiting for message notification"));
|
|
212
|
-
}, timeoutMs);
|
|
213
|
-
}
|
|
214
|
-
const unsubscribe = messageEventBus.subscribe(runId, messageType, () => {
|
|
215
|
-
if (timeoutId) clearTimeout(timeoutId);
|
|
216
|
-
unsubscribe();
|
|
217
|
-
resolve();
|
|
218
|
-
});
|
|
219
|
-
});
|
|
220
|
-
}
|
|
221
|
-
function getStepId() {
|
|
222
|
-
const ctx = getExecutionContext();
|
|
223
|
-
const sequenceId = ctx.operationManager.getActiveSequenceId();
|
|
224
|
-
if (sequenceId === null) {
|
|
225
|
-
throw new Error("getStepId() can only be called from within a step function");
|
|
226
|
-
}
|
|
227
|
-
const hash = createHash("sha256");
|
|
228
|
-
hash.update(`${ctx.runId}:${sequenceId}`);
|
|
229
|
-
return hash.digest("hex");
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
// core/steps/helpers/get-abort-signal.ts
|
|
233
|
-
function getAbortSignal() {
|
|
234
|
-
return getExecutionContext().abortSignal;
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
// core/steps/helpers/get-run-id.ts
|
|
238
|
-
function getRunId() {
|
|
239
|
-
const { runId } = getExecutionContext();
|
|
240
|
-
return runId;
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
// core/steps/sleep.ts
|
|
244
|
-
var SLEEP_OPERATION_NAME = "_helical::sleep";
|
|
245
|
-
async function sleep2(ms) {
|
|
246
|
-
const { abortSignal } = getExecutionContext();
|
|
247
|
-
return await withDurableDeadline(ms, SLEEP_OPERATION_NAME, async (deadlineMs) => {
|
|
248
|
-
const remainingMs = deadlineMs - Date.now();
|
|
249
|
-
try {
|
|
250
|
-
await cancellableSleep(remainingMs, abortSignal);
|
|
251
|
-
} catch {
|
|
252
|
-
throw new RunCancelledError();
|
|
253
|
-
}
|
|
254
|
-
});
|
|
255
|
-
}
|
|
256
|
-
function cancellableSleep(ms, signal) {
|
|
257
|
-
return new Promise((resolve, reject) => {
|
|
258
|
-
if (signal?.aborted) {
|
|
259
|
-
reject(new Error("Sleep aborted"));
|
|
260
|
-
return;
|
|
261
|
-
}
|
|
262
|
-
const timeoutId = setTimeout(() => {
|
|
263
|
-
cleanup();
|
|
264
|
-
resolve();
|
|
265
|
-
}, ms);
|
|
266
|
-
const onAbort = () => {
|
|
267
|
-
cleanup();
|
|
268
|
-
reject(new Error("Sleep aborted"));
|
|
269
|
-
};
|
|
270
|
-
const cleanup = () => {
|
|
271
|
-
clearTimeout(timeoutId);
|
|
272
|
-
signal?.removeEventListener("abort", onAbort);
|
|
273
|
-
};
|
|
274
|
-
signal?.addEventListener("abort", onAbort);
|
|
275
|
-
});
|
|
276
|
-
}
|
|
277
|
-
var RANDOM_UUID_OPERATION_NAME = "_helical::randomUUID";
|
|
278
|
-
async function randomUUID() {
|
|
279
|
-
const { operationManager } = getExecutionContext();
|
|
280
|
-
const existingResult = operationManager.getOperationResult();
|
|
281
|
-
if (existingResult) {
|
|
282
|
-
return existingResult.result;
|
|
283
|
-
} else {
|
|
284
|
-
await executeAndRecordOperation(operationManager, RANDOM_UUID_OPERATION_NAME, async () => {
|
|
285
|
-
return crypto.randomUUID();
|
|
286
|
-
});
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
async function runWorkflow(wf, args = [], options = {}) {
|
|
290
|
-
const ctx = getExecutionContext();
|
|
291
|
-
const { operationManager, runPath, workflowRegistry, db, executorId } = ctx;
|
|
292
|
-
const workflow = typeof wf === "string" ? workflowRegistry.getByName(wf) : workflowRegistry.getByWorkflowDefinition(wf);
|
|
293
|
-
if (!workflow) {
|
|
294
|
-
throw new WorkflowNotFoundError("Workflow not found");
|
|
295
|
-
}
|
|
296
|
-
const op = operationManager.getOperationResult();
|
|
297
|
-
if (op) {
|
|
298
|
-
if (op.error) {
|
|
299
|
-
throw deserializeError(op.error);
|
|
300
|
-
}
|
|
301
|
-
const newRun2 = deserialize(op.result);
|
|
302
|
-
return createRunHandle(ctx, newRun2.runId);
|
|
303
|
-
}
|
|
304
|
-
const newRun = await executeAndRecordOperation(operationManager, "runWorkflow", async () => {
|
|
305
|
-
const newRunId = options.id ?? crypto.randomUUID();
|
|
306
|
-
const newRun2 = {
|
|
307
|
-
runId: newRunId,
|
|
308
|
-
runPath: [...runPath, newRunId],
|
|
309
|
-
workflowName: workflow.name
|
|
310
|
-
};
|
|
311
|
-
withDbRetry(async () => {
|
|
312
|
-
return await insertPendingRun(db, {
|
|
313
|
-
...newRun2,
|
|
314
|
-
path: newRun2.runPath,
|
|
315
|
-
inputs: serialize(args),
|
|
316
|
-
executorId
|
|
317
|
-
});
|
|
318
|
-
});
|
|
319
|
-
return newRun2;
|
|
320
|
-
});
|
|
321
|
-
await executeWorkflow(ctx, {
|
|
322
|
-
runId: newRun.runId,
|
|
323
|
-
runPath: newRun.runPath,
|
|
324
|
-
workflowName: newRun.workflowName,
|
|
325
|
-
fn: workflow.fn,
|
|
326
|
-
args,
|
|
327
|
-
options
|
|
328
|
-
});
|
|
329
|
-
return createRunHandle(ctx, newRun.runId);
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
export { cancellableSleep, defineMessage, defineQueue, defineState, executeStepWithRetries, getAbortSignal, getRunId, getStepId, randomUUID, receiveMessage, runStep, runWorkflow, setState, sleep2 as sleep };
|
|
333
|
-
//# sourceMappingURL=workflows.js.map
|
|
334
|
-
//# sourceMappingURL=workflows.js.map
|
package/dist/workflows.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../core/message.ts","../core/queue.ts","../core/state.ts","../core/steps/run-step.ts","../core/internal/repository/insert-state.ts","../core/steps/set-state.ts","../core/internal/repository/read-and-delete-message.ts","../core/internal/with-durable-deadline.ts","../core/steps/receive-message.ts","../core/steps/helpers/get-step-id.ts","../core/steps/helpers/get-abort-signal.ts","../core/steps/helpers/get-run-id.ts","../core/steps/sleep.ts","../core/steps/random-uuid.ts","../core/steps/run-workflow.ts"],"names":["sleep","newRun","crypto"],"mappings":";;;;;;AAKO,SAAS,cAAiB,IAAA,EAAoC;AACnE,EAAA,OAAO,EAAE,IAAA,EAAK;AAChB;;;ACOO,SAAS,WAAA,CAAY,OAAA,GAAwB,EAAC,EAAe;AAClE,EAAA,OAAO,MAAM,OAAA;AACf;;;ACXO,SAAS,YAAe,IAAA,EAAc;AAC3C,EAAA,OAAO;AAAA,IACL;AAAA,GACF;AACF;;;ACaA,eAAsB,OAAA,CACpB,MAAA,EACA,OAAA,GAA0B,EAAC,EAC3B;AACA,EAAA,MAAM,EAAE,UAAA,EAAY,UAAA,EAAY,WAAA,EAAY,GAAI,OAAA;AAChD,EAAA,MAAM,EAAE,gBAAA,EAAiB,GAAI,mBAAA,EAAoB;AACjD,EAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,IAAA,IAAQ,MAAA,CAAO,IAAA,IAAQ,WAAA;AAEhD,EAAA,MAAM,EAAA,GAAK,iBAAiB,kBAAA,EAAmB;AAC/C,EAAA,IAAI,EAAA,EAAI;AACN,IAAA,OAAO,6BAAsC,EAAE,CAAA;AAAA,EACjD;AACA,EAAA,OAAO,MAAM,yBAAA,CAA0B,gBAAA,EAAkB,QAAA,EAAU,YAAY;AAC7E,IAAA,OAAO,MAAM,uBAAuB,QAAA,EAAU,MAAA,EAAQ,EAAE,UAAA,EAAY,UAAA,EAAY,aAAa,CAAA;AAAA,EAC/F,CAAC,CAAA;AACH;AAEA,eAAsB,sBAAA,CACpB,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AAc,QAAA,CAAS;AAAA,KACzB;AACA,IAAA,WAAA,CAAY,YAAY;AACtB,MAAA,OAAO,MAAM,iBAAiB,EAAA,EAAI;AAAA,QAChC,GAAGA,OAAAA;AAAA,QACH,MAAMA,OAAAA,CAAO,OAAA;AAAA,QACb,MAAA,EAAQ,UAAU,IAAI,CAAA;AAAA,QACtB;AAAA,OACD,CAAA;AAAA,IACH,CAAC,CAAA;AACD,IAAA,OAAOA,OAAAA;AAAA,EACT,CAAC,CAAA;AAED,EAAA,MAAM,gBAAgB,GAAA,EAAK;AAAA,IACzB,OAAO,MAAA,CAAO,KAAA;AAAA,IACd,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,cAAc,MAAA,CAAO,YAAA;AAAA,IACrB,IAAI,QAAA,CAAS,EAAA;AAAA,IACb,IAAA;AAAA,IACA;AAAA,GACD,CAAA;AAED,EAAA,OAAO,eAAA,CAAyB,GAAA,EAAK,MAAA,CAAO,KAAK,CAAA;AACnD","file":"workflows.js","sourcesContent":["export type MessageDefinition<T> = {\n name: string;\n data?: T;\n};\n\nexport function defineMessage<T>(name: string): MessageDefinition<T> {\n return { name } as MessageDefinition<T>;\n}\n","export type QueueRateLimit = {\n limitPerPeriod: number;\n period: number;\n};\n\nexport type QueueOptions = {\n workerConcurrency?: number;\n concurrency?: number;\n rateLimit?: QueueRateLimit;\n priorityEnabled?: boolean;\n partitioningEnabled?: boolean;\n name?: string;\n};\n\nexport function defineQueue(options: QueueOptions = {}): QueueEntry {\n return () => options;\n}\n\nexport type QueueEntry = () => QueueOptions;\n\nexport type QueueDefinition = QueueOptions & { name: string };\n","export interface StateDefinition<T> {\n name: string;\n data?: T;\n}\n\nexport function defineState<T>(name: string) {\n return {\n name,\n } as StateDefinition<T>;\n}\n","import {\n ErrorThatShouldNeverHappen,\n FatalError,\n MaxRetriesExceededError,\n} from '../internal/errors';\nimport { getExecutionContext } from '../internal/execution-context';\nimport { sleep } from '../internal/utils/sleep';\nimport {\n executeAndRecordOperation,\n returnOrThrowOperationResult,\n} from '../internal/operation-manager';\n\nexport type RetryConfig = {\n maxRetries?: number;\n retryDelay?: number;\n backOffRate?: number;\n};\n\ntype RunStepOptions = RetryConfig & {\n name?: string;\n};\n\nexport async function runStep<TReturn>(\n stepFn: () => Promise<TReturn>,\n options: RunStepOptions = {},\n) {\n const { maxRetries, retryDelay, backOffRate } = options;\n const { operationManager } = getExecutionContext();\n const stepName = options.name || stepFn.name || '<unknown>';\n\n const op = operationManager.getOperationResult();\n if (op) {\n return returnOrThrowOperationResult<TReturn>(op);\n }\n return await executeAndRecordOperation(operationManager, stepName, async () => {\n return await executeStepWithRetries(stepName, stepFn, { maxRetries, retryDelay, backOffRate });\n });\n}\n\nexport async function executeStepWithRetries<TReturn>(\n stepName: string,\n fn: () => Promise<TReturn>,\n retryConfig: RetryConfig,\n): Promise<TReturn> {\n const maxRetries = retryConfig.maxRetries ?? 0;\n const retryDelay = retryConfig.retryDelay ?? 0;\n const backOffRate = retryConfig.backOffRate ?? 1;\n\n const attemptErrors: Error[] = [];\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await fn();\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n attemptErrors.push(err);\n if (err instanceof FatalError) {\n throw err;\n }\n if (maxRetries === 0) {\n throw err;\n }\n if (attempt >= maxRetries) {\n throw new MaxRetriesExceededError(stepName, maxRetries, attemptErrors);\n }\n const delay = retryDelay * Math.pow(backOffRate, attempt);\n await sleep(delay);\n }\n }\n throw new ErrorThatShouldNeverHappen(`Step \"${stepName}\" should never be reached`);\n}\n","import { Database, Transaction } from '../db/db';\n\ntype InsertStateOptions = {\n runId: string;\n key: string;\n value: string;\n sequenceId: number;\n};\n\nexport async function insertState(tx: Transaction | Database, options: InsertStateOptions) {\n await tx\n .insertInto('state')\n .values({\n run_id: options.runId,\n key: options.key,\n value: options.value,\n })\n .onConflict((oc) =>\n oc.column('run_id').column('key').doUpdateSet({\n value: options.value,\n }),\n )\n .execute();\n\n await tx\n .insertInto('state_history')\n .values({\n run_id: options.runId,\n sequence_id: options.sequenceId,\n key: options.key,\n value: options.value,\n })\n .execute();\n}\n","import { withDbRetry } from '../internal/db/retry';\nimport { getExecutionContext } from '../internal/execution-context';\nimport { returnOrThrowOperationResult } from '../internal/operation-manager';\nimport { insertState } from '../internal/repository/insert-state';\nimport { serialize } from '../internal/serialization';\nimport { StateDefinition } from '../state';\n\nconst SET_STATE_OPERATION_NAME = 'workflow::state::set';\n\nexport async function setState<T = unknown>(state: StateDefinition<T> | string, value: T) {\n const stateKey = typeof state === 'string' ? state : state.name;\n const { operationManager, runId, db } = getExecutionContext();\n\n const op = operationManager.getOperationResult();\n if (op) {\n return returnOrThrowOperationResult<void>(op);\n }\n\n const seqId = operationManager.reserveSequenceId();\n\n await withDbRetry(async () => {\n return await db.transaction().execute(async (tx) => {\n await insertState(tx, { runId, key: stateKey, value: serialize(value), sequenceId: seqId });\n await operationManager.recordResult(SET_STATE_OPERATION_NAME, seqId, null, tx);\n });\n });\n}\n","import { sql } from 'kysely';\nimport { Transaction } from '../db/db';\n\ntype Message = {\n id: string;\n payload?: string;\n type?: string;\n};\n\nexport async function readAndDeleteMessage(\n tx: Transaction,\n runId: string,\n messageType?: string,\n): Promise<Message | undefined> {\n const results = await sql<Message>`\n DELETE FROM messages\n WHERE id IN (\n SELECT id FROM messages\n WHERE destination_run_id = ${runId}\n ${messageType !== undefined ? sql`AND type = ${messageType}` : sql``}\n ORDER BY created_at_epoch_ms ASC\n LIMIT 1\n )\n RETURNING id, payload, type\n `.execute(tx);\n\n const result = results.rows[0];\n\n return result\n ? {\n id: result.id,\n payload: result.payload ?? undefined,\n type: result.type ?? undefined,\n }\n : undefined;\n}\n","import { getExecutionContext } from './execution-context';\nimport { executeAndRecordOperation } from './operation-manager';\n\nexport async function withDurableDeadline<T>(\n timeoutMs: number | undefined,\n operationName: string,\n fn: (deadlineMs: number | undefined) => Promise<T>,\n): Promise<T> {\n if (!timeoutMs) {\n return await fn(undefined);\n }\n\n const { operationManager } = getExecutionContext();\n\n let deadlineMs: number;\n const op = operationManager.getOperationResult();\n if (op) {\n deadlineMs = Number(op.result);\n } else {\n deadlineMs = Date.now() + timeoutMs;\n await executeAndRecordOperation(operationManager, operationName, async () => {\n return deadlineMs;\n });\n }\n\n return await fn(deadlineMs);\n}\n","import { withDbRetry } from '../internal/db/retry';\nimport { TimeoutError } from '../internal/errors';\nimport { MessageEventBus } from '../internal/events/message-event-bus';\nimport { getExecutionContext } from '../internal/execution-context';\nimport { returnOrThrowOperationResult } from '../internal/operation-manager';\nimport { readAndDeleteMessage } from '../internal/repository/read-and-delete-message';\nimport { deserialize, serialize, serializeError } from '../internal/serialization';\nimport { withDurableDeadline } from '../internal/with-durable-deadline';\nimport { MessageDefinition } from '../message';\n\nconst RECEIVE_MESSAGE_OPERATION_NAME = 'workflow::message::receive';\n\nconst RECEIVE_MESSAGE_DURABLE_DEADLINE_OPERATION_NAME =\n 'workflow::message::receive::durable-deadline';\n\nclass MessageNotAvailableError extends Error {}\n\nexport type ReceiveMessageOptions = {\n timeout?: number;\n};\n\nexport async function receiveMessage<T>(\n message: MessageDefinition<T> | string,\n options?: ReceiveMessageOptions,\n): Promise<T> {\n const messageType = typeof message === 'string' ? message : message.name;\n return await withDurableDeadline(\n options?.timeout,\n RECEIVE_MESSAGE_DURABLE_DEADLINE_OPERATION_NAME,\n async (deadlineMs) => {\n return await receiveMessageWithDeadline(messageType, deadlineMs);\n },\n );\n}\n\nasync function receiveMessageWithDeadline<T>(\n messageType: string,\n deadlineMs: number | undefined,\n): Promise<T> {\n const { runId, operationManager, messageEventBus, db } = getExecutionContext();\n\n const op = operationManager.getOperationResult();\n if (op) {\n return returnOrThrowOperationResult<T>(op) as T;\n }\n\n const seqId = operationManager.reserveSequenceId();\n\n while (true) {\n // Check if timeout expired\n if (deadlineMs && Date.now() >= deadlineMs) {\n const error = new TimeoutError(`Timed out waiting for message \"${messageType}\"`);\n await operationManager.recordError(\n RECEIVE_MESSAGE_OPERATION_NAME,\n seqId,\n serializeError(error),\n );\n throw error;\n }\n\n try {\n return await withDbRetry(async () => {\n return await db.transaction().execute(async (tx) => {\n const msg = await readAndDeleteMessage(tx, runId, messageType);\n if (!msg) {\n throw new MessageNotAvailableError();\n }\n await operationManager.recordResult(\n RECEIVE_MESSAGE_OPERATION_NAME,\n seqId,\n serialize(msg.payload),\n tx,\n );\n return deserialize(msg.payload!) as T;\n });\n });\n } catch (error) {\n if (error instanceof MessageNotAvailableError) {\n const remainingMs = deadlineMs ? deadlineMs - Date.now() : undefined;\n await waitForMessageNotification(messageEventBus, runId, messageType, remainingMs);\n continue;\n }\n // Record and re-throw other errors\n await operationManager.recordError(\n RECEIVE_MESSAGE_OPERATION_NAME,\n seqId,\n serializeError(error as Error),\n );\n throw error;\n }\n }\n}\n\nasync function waitForMessageNotification(\n messageEventBus: MessageEventBus,\n runId: string,\n messageType: string,\n timeoutMs?: number,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n let timeoutId: NodeJS.Timeout | undefined;\n\n if (timeoutMs !== undefined) {\n if (timeoutMs <= 0) {\n reject(new TimeoutError('Timeout expired'));\n return;\n }\n\n timeoutId = setTimeout(() => {\n unsubscribe();\n reject(new TimeoutError('Timeout waiting for message notification'));\n }, timeoutMs);\n }\n\n const unsubscribe = messageEventBus.subscribe(runId, messageType, () => {\n if (timeoutId) clearTimeout(timeoutId);\n unsubscribe();\n resolve();\n });\n });\n}\n","import { getExecutionContext } from '../../internal/execution-context';\nimport { createHash } from 'node:crypto';\n\n/**\n * Generates a stable, unique step ID based on the current run ID and sequence ID.\n * This ID is deterministic and will remain the same across retries, making it\n * suitable for use as an idempotency key with third-party systems.\n *\n * The step ID is a SHA-256 hash of the run ID and sequence ID, formatted as a\n * hex string for easy use with external APIs.\n *\n * @returns A unique, stable identifier for the current step execution\n */\nexport function getStepId(): string {\n const ctx = getExecutionContext();\n const sequenceId = ctx.operationManager.getActiveSequenceId();\n\n if (sequenceId === null) {\n throw new Error('getStepId() can only be called from within a step function');\n }\n\n const hash = createHash('sha256');\n hash.update(`${ctx.runId}:${sequenceId}`);\n return hash.digest('hex');\n}\n","import { getExecutionContext } from '../../internal/execution-context';\n\nexport function getAbortSignal() {\n return getExecutionContext().abortSignal;\n}\n","import { getExecutionContext } from '../../internal/execution-context';\n\nexport function getRunId() {\n const { runId } = getExecutionContext();\n return runId;\n}\n","import { RunCancelledError } from '../internal/errors';\nimport { getExecutionContext } from '../internal/execution-context';\nimport { withDurableDeadline } from '../internal/with-durable-deadline';\n\nconst SLEEP_OPERATION_NAME = '_helical::sleep';\n\nexport async function sleep(ms: number) {\n const { abortSignal } = getExecutionContext();\n return await withDurableDeadline(ms, SLEEP_OPERATION_NAME, async (deadlineMs) => {\n const remainingMs = deadlineMs! - Date.now();\n try {\n await cancellableSleep(remainingMs, abortSignal);\n } catch {\n throw new RunCancelledError();\n }\n });\n}\n\nexport function cancellableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new Error('Sleep aborted'));\n return;\n }\n\n const timeoutId = setTimeout(() => {\n cleanup();\n resolve();\n }, ms);\n\n const onAbort = () => {\n cleanup();\n reject(new Error('Sleep aborted'));\n };\n\n const cleanup = () => {\n clearTimeout(timeoutId);\n signal?.removeEventListener('abort', onAbort);\n };\n\n signal?.addEventListener('abort', onAbort);\n });\n}\n","import { getExecutionContext } from '../internal/execution-context';\nimport crypto from 'node:crypto';\nimport { executeAndRecordOperation } from '../internal/operation-manager';\n\nconst RANDOM_UUID_OPERATION_NAME = '_helical::randomUUID';\n\nexport async function randomUUID() {\n const { operationManager } = getExecutionContext();\n const existingResult = operationManager.getOperationResult();\n if (existingResult) {\n return existingResult.result as string;\n } else {\n await executeAndRecordOperation(operationManager, RANDOM_UUID_OPERATION_NAME, async () => {\n return crypto.randomUUID();\n });\n }\n}\n","import { createRunHandle } from '../../client/run';\nimport { RunWorkflowOptions } from '../../client/run-workflow';\nimport { withDbRetry } from '../internal/db/retry';\nimport { WorkflowNotFoundError } from '../internal/errors';\nimport { executeWorkflow } from '../internal/execute-workflow';\nimport { getExecutionContext } from '../internal/execution-context';\nimport { executeAndRecordOperation } from '../internal/operation-manager';\nimport { insertPendingRun } from '../internal/repository/insert-pending-run';\nimport { deserialize, deserializeError, serialize } from '../internal/serialization';\nimport { WorkflowEntry } from '../workflow';\nimport crypto from 'node:crypto';\n\ntype RunWorkflowOperationResult = {\n runId: string;\n runPath: string[];\n workflowName: string;\n};\n\nexport async function runWorkflow<TArgs extends unknown[], TReturn>(\n wf: WorkflowEntry<TArgs, TReturn> | string,\n args: TArgs = [] as unknown as TArgs,\n options: RunWorkflowOptions = {},\n) {\n const ctx = getExecutionContext();\n const { operationManager, runPath, workflowRegistry, db, executorId } = ctx;\n\n const workflow =\n typeof wf === 'string'\n ? workflowRegistry.getByName(wf)\n : workflowRegistry.getByWorkflowDefinition(wf);\n if (!workflow) {\n throw new WorkflowNotFoundError('Workflow not found');\n }\n\n const op = operationManager.getOperationResult();\n if (op) {\n if (op.error) {\n throw deserializeError(op.error);\n }\n const newRun = deserialize<RunWorkflowOperationResult>(op.result!);\n return createRunHandle<TReturn>(ctx, newRun.runId);\n }\n\n const newRun = await executeAndRecordOperation(operationManager, 'runWorkflow', async () => {\n const newRunId = options.id ?? crypto.randomUUID();\n const newRun: RunWorkflowOperationResult = {\n runId: newRunId,\n runPath: [...runPath, newRunId],\n workflowName: workflow.name,\n };\n withDbRetry(async () => {\n return await insertPendingRun(db, {\n ...newRun,\n path: newRun.runPath,\n inputs: serialize(args),\n executorId: executorId,\n });\n });\n return newRun;\n });\n\n await executeWorkflow(ctx, {\n runId: newRun.runId,\n runPath: newRun.runPath,\n workflowName: newRun.workflowName,\n fn: workflow.fn,\n args,\n options,\n });\n\n return createRunHandle<TReturn>(ctx, newRun.runId);\n}\n"]}
|