mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-29 04:14:30 +00:00
feat(workflow): migrate workflow engine from temporal to dbos (#481)
* feat(workflow): migrate workflow engine from temporal to dbos Replace Temporal and LocalExecutor with DBOS Transact (@dbos-inc/dbos-sdk) as the unified workflow engine. Background tasks, media transcoding, and AI agent workflows now execute with durable steps and task queues directly against PostgreSQL, eliminating the need for an external Temporal cluster and separate polling executors. * fix(workflow): submit tasks via DBOSClient to allow enqueueing from steps Enqueuing workflows using DBOS.enqueueWorkflowWithOptions threw a DBOSInvalidWorkflowTransitionError when triggered from within a running step or activity (e.g. creating embedding or autofill tasks during video transcoding). Use DBOSClient to submit and cancel workflow tasks directly against the system database, detaching execution from the ambient workflow/step context. * feat(web): support SHUMAI_WORKERS environment variable * fix(workflow): ensure CLI tasks are enqueued to DBOS and run DBOS migrations in global setup - Initialize workflows and wait for pending DBOS submissions in shumai regenerate-embeddings CLI - Remove no-op submit bypass and enqueue tasks via DBOSClient in producer and CLI contexts - Add DBOS migration runner in test global setup to avoid concurrent migration deadlocks across test forks - Update changelog and add regression tests * fix(workflow): ensure unique per-instance executor identity for worker replicas - Derive unique per-instance DBOS executor IDs across worker replicas - Support SHUMAI_WORKER_ID, DBOS__VMID, and POD_NAME (Kubernetes Downward API) - Disambiguate multi-replica bare metal/container deployments with host, PID, and instance suffix - Prevent startup recovery from re-enqueueing workflows actively executed by other live workers - Add multi-instance startup recovery tests and update deployment documentation * fix(workflow): only register listened queues and update concurrency on change - Only register queues that the executor instance actively listens to - Use always_update conflict resolution so environment variable changes take effect on restart - Prevent dedicated workers from overwriting unmanaged queue concurrency configurations - Add tests verifying concurrency updates and queue isolation across worker roles * refactor(workflow): simplify activities to use defineStep and direct calls (#482) * refactor(workflow): simplify activities to use defineStep and direct calls - Wrap activities using defineStep from @shumai/workflow-core - Remove obsolete getActivities, registerActivities, dynamic activity proxies, and workerQueue arguments - Remove executor.ts and registry.ts, consolidating workflow registration into workflow.ts - Call activities directly across transcode and agent workflows - Update all corresponding workflow tests and developer guide documentation * fix(workflow): properly detect DBOSWorkflowCancelledError in runOnCancel fallback - DBOSWorkflowCancelledError in DBOS SDK does not set name, inheriting 'Error' - Implement isDbosWorkflowCancelledError checking instanceof, constructor.name, and dbosErrorCode - Update unit tests to verify real DBOS SDK cancellation error instances * docs(workflow): update documentation and readme for dbos migration - Rename docs/configuration/temporal.mdx to docs/configuration/distributed.mdx - Document DBOS-based distributed worker architecture and task queues - Remove obsolete docker-compose/temporal/ - Update environment variables documentation in docs/configuration/env-variables.mdx - Update references in README.md, README_CN.md, docs/docs.json, and related guides * feat(deploy): implement KEDA ScaledJob and scale-to-zero On-Demand transcoding (#483) * feat(deploy): add shumai-transcode docker image and k8s autoscaling example with garage s3 * docs(k8s): document port-forwarding and in-cluster s3 domain mapping * feat(storage): support public s3 endpoint for browser uploads and update k8s example * fix(k8s): configure s3 bucket cors rules in garage initialization * fix(k8s): increase transcode worker memory limit to 4Gi for 4K video encoding * feat(deploy): add AWS EKS deployment with Graviton3 Spot nodegroups and autoscaling * docs(deploy): redesign EKS documentation, rename k8s to eks, and add scalable deployment feature * docs: rephrase DBOS feature bullet to Durable Workflows via DBOS * docs(eks): upgrade default instances to Graviton5 c9g.large and c9g.xlarge * feat(eks): use On-Demand for general nodegroup and add spot capacity diversification * docs(eks): fix Architecture diagram to locate all transcode worker pods in Transcode Compute Pool * feat(deploy): implement KEDA ScaledJob and scale-to-zero On-Demand transcoding * feat(transcode): support idle-timeout auto-drain for KEDA scaled jobs * fix(deploy): fix EKS deployment manifests and documentation based on cluster verification
This commit is contained in:
@@ -1,15 +1,8 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { WorkflowTaskStatus, AssetStatus, AssetType, Prisma } from '@shumai/db'
|
||||
import { defineStep } from '../workflow-utils'
|
||||
|
||||
export async function getTranscodeWorkerQueueActivity(): Promise<string> {
|
||||
return 'transcode_queue'
|
||||
}
|
||||
|
||||
export async function getAgentWorkerQueueActivity(): Promise<string> {
|
||||
return 'agent_queue'
|
||||
}
|
||||
|
||||
export async function getAssetStatusActivity(params: {
|
||||
export const getAssetStatusActivity = defineStep(async function getAssetStatusActivity(params: {
|
||||
assetId: string
|
||||
}): Promise<AssetStatus | null> {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
@@ -17,9 +10,9 @@ export async function getAssetStatusActivity(params: {
|
||||
select: { status: true },
|
||||
})
|
||||
return asset?.status || null
|
||||
}
|
||||
})
|
||||
|
||||
export async function getAssetActivity(assetId: string) {
|
||||
export const getAssetActivity = defineStep(async function getAssetActivity(assetId: string) {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
include: {
|
||||
@@ -61,7 +54,7 @@ export async function getAssetActivity(assetId: string) {
|
||||
...asset,
|
||||
sizeByte: Number(asset.sizeByte),
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface UpdateTaskStatusParams {
|
||||
taskId: string
|
||||
@@ -69,15 +62,18 @@ export interface UpdateTaskStatusParams {
|
||||
output?: unknown
|
||||
}
|
||||
|
||||
export async function updateTaskStatusActivity(params: UpdateTaskStatusParams): Promise<void> {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
status: params.status,
|
||||
output: params.output as Prisma.InputJsonValue,
|
||||
},
|
||||
})
|
||||
}
|
||||
export const updateTaskStatusActivity = defineStep(
|
||||
async function updateTaskStatusActivity(params: UpdateTaskStatusParams): Promise<void> {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
status: params.status,
|
||||
output: params.output as PrismaJson.WorkflowTaskOutput,
|
||||
},
|
||||
})
|
||||
},
|
||||
{ runOnCancel: true },
|
||||
)
|
||||
|
||||
export interface UpdateAssetStatusParams {
|
||||
assetId: string
|
||||
@@ -85,36 +81,39 @@ export interface UpdateAssetStatusParams {
|
||||
error?: string
|
||||
}
|
||||
|
||||
export async function updateAssetStatusActivity(params: UpdateAssetStatusParams): Promise<void> {
|
||||
if (params.status === AssetStatus.failed) {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
select: { media: true, status: true },
|
||||
})
|
||||
// Never overwrite an asset that has already completed media processing
|
||||
if (asset?.status === AssetStatus.processed) {
|
||||
export const updateAssetStatusActivity = defineStep(
|
||||
async function updateAssetStatusActivity(params: UpdateAssetStatusParams): Promise<void> {
|
||||
if (params.status === AssetStatus.failed) {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
select: { media: true, status: true },
|
||||
})
|
||||
// Never overwrite an asset that has already completed media processing
|
||||
if (asset?.status === AssetStatus.processed) {
|
||||
return
|
||||
}
|
||||
const data: Prisma.AssetUpdateInput = { status: params.status }
|
||||
if (params.error !== undefined) {
|
||||
const existingMedia = (asset?.media as PrismaJson.MediaInfo | null) || {}
|
||||
data.media = {
|
||||
...existingMedia,
|
||||
error: params.error.slice(0, 500),
|
||||
} as PrismaJson.MediaInfo
|
||||
}
|
||||
await prisma.asset.updateMany({
|
||||
where: { id: params.assetId, isDeleted: false, status: { not: AssetStatus.processed } },
|
||||
data,
|
||||
})
|
||||
return
|
||||
}
|
||||
const data: Prisma.AssetUpdateInput = { status: params.status }
|
||||
if (params.error !== undefined) {
|
||||
const existingMedia = (asset?.media as PrismaJson.MediaInfo | null) || {}
|
||||
data.media = {
|
||||
...existingMedia,
|
||||
error: params.error.slice(0, 500),
|
||||
} as PrismaJson.MediaInfo
|
||||
}
|
||||
await prisma.asset.updateMany({
|
||||
where: { id: params.assetId, isDeleted: false, status: { not: AssetStatus.processed } },
|
||||
data,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
await prisma.asset.updateMany({
|
||||
where: { id: params.assetId, isDeleted: false },
|
||||
data: { status: params.status },
|
||||
})
|
||||
}
|
||||
await prisma.asset.updateMany({
|
||||
where: { id: params.assetId, isDeleted: false },
|
||||
data: { status: params.status },
|
||||
})
|
||||
},
|
||||
{ runOnCancel: true },
|
||||
)
|
||||
|
||||
export interface UpdateTaskUsageParams {
|
||||
taskId: string
|
||||
@@ -123,7 +122,9 @@ export interface UpdateTaskUsageParams {
|
||||
model: string
|
||||
}
|
||||
|
||||
export async function updateTaskUsageActivity(params: UpdateTaskUsageParams): Promise<void> {
|
||||
export const updateTaskUsageActivity = defineStep(async function updateTaskUsageActivity(
|
||||
params: UpdateTaskUsageParams,
|
||||
): Promise<void> {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
@@ -132,7 +133,7 @@ export async function updateTaskUsageActivity(params: UpdateTaskUsageParams): Pr
|
||||
model: params.model,
|
||||
},
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
export interface UpdateWorkflowTaskParams {
|
||||
taskId: string
|
||||
@@ -144,16 +145,21 @@ export interface UpdateWorkflowTaskParams {
|
||||
model?: string | null
|
||||
}
|
||||
|
||||
export async function updateWorkflowTaskActivity(params: UpdateWorkflowTaskParams): Promise<void> {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
...(params.status !== undefined ? { status: params.status } : {}),
|
||||
...(params.heartbeat ? { heartbeat: new Date() } : {}),
|
||||
...(params.output !== undefined ? { output: params.output as Prisma.InputJsonValue } : {}),
|
||||
...(params.inputTokens !== undefined ? { inputTokens: params.inputTokens } : {}),
|
||||
...(params.outputTokens !== undefined ? { outputTokens: params.outputTokens } : {}),
|
||||
...(params.model !== undefined ? { model: params.model } : {}),
|
||||
},
|
||||
})
|
||||
}
|
||||
export const updateWorkflowTaskActivity = defineStep(
|
||||
async function updateWorkflowTaskActivity(params: UpdateWorkflowTaskParams): Promise<void> {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
...(params.status !== undefined ? { status: params.status } : {}),
|
||||
...(params.heartbeat ? { heartbeat: new Date() } : {}),
|
||||
...(params.output !== undefined
|
||||
? { output: params.output as PrismaJson.WorkflowTaskOutput }
|
||||
: {}),
|
||||
...(params.inputTokens !== undefined ? { inputTokens: params.inputTokens } : {}),
|
||||
...(params.outputTokens !== undefined ? { outputTokens: params.outputTokens } : {}),
|
||||
...(params.model !== undefined ? { model: params.model } : {}),
|
||||
},
|
||||
})
|
||||
},
|
||||
{ runOnCancel: true },
|
||||
)
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { temporalWorkflow } from './bun-temporal-plugin'
|
||||
import * as worker from '@temporalio/worker'
|
||||
|
||||
vi.mock('@temporalio/worker', () => ({
|
||||
bundleWorkflowCode: vi.fn().mockResolvedValue({ code: 'mock-code', sourceMap: '' }),
|
||||
}))
|
||||
|
||||
describe('temporalWorkflow plugin', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should register onLoad and configure webpackConfigHook with @temporalio/workflow alias', async () => {
|
||||
const plugin = temporalWorkflow()
|
||||
|
||||
let onLoadCallback: ((...args: unknown[]) => unknown) | null = null
|
||||
|
||||
const mockBuild = {
|
||||
onResolve: vi.fn(),
|
||||
onLoad: vi.fn((opts, callback) => {
|
||||
onLoadCallback = callback
|
||||
}),
|
||||
}
|
||||
|
||||
// Run setup
|
||||
// @ts-ignore
|
||||
plugin.setup(mockBuild)
|
||||
|
||||
expect(onLoadCallback).toBeDefined()
|
||||
|
||||
// Trigger onLoad callback
|
||||
await onLoadCallback!({ path: 'dummy-path' })
|
||||
|
||||
// Verify bundleWorkflowCode was called
|
||||
expect(worker.bundleWorkflowCode).toHaveBeenCalled()
|
||||
|
||||
// Webpack's configuration type is complex and varies across versions.
|
||||
// We cast it to any here to allow indexing the config aliases dynamically.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const callArgs = vi.mocked(worker.bundleWorkflowCode).mock.calls[0][0] as any
|
||||
expect(callArgs.webpackConfigHook).toBeDefined()
|
||||
|
||||
// Invoke the hook with a dummy config
|
||||
const config = { resolve: { alias: {} } }
|
||||
const updatedConfig = callArgs.webpackConfigHook(config)
|
||||
|
||||
// Check that aliases are set
|
||||
expect(updatedConfig.resolve.alias['@shumai/workflow-core']).toBeDefined()
|
||||
expect(updatedConfig.resolve.alias['@temporalio/workflow']).toBeDefined()
|
||||
})
|
||||
})
|
||||
@@ -1,74 +0,0 @@
|
||||
import { bundleWorkflowCode } from '@temporalio/worker'
|
||||
import type { BunPlugin } from 'bun'
|
||||
import { resolve, dirname } from 'node:path'
|
||||
|
||||
export interface TemporalWorkflowPluginOptions {
|
||||
/** Query param identifier. Default: 'workflow' */
|
||||
identifier?: string
|
||||
/** Forwarded to bundleWorkflowCode (minus workflowsPath) */
|
||||
bundleOptions?: Omit<Parameters<typeof bundleWorkflowCode>[0], 'workflowsPath'>
|
||||
}
|
||||
|
||||
export function temporalWorkflow(options: TemporalWorkflowPluginOptions = {}): BunPlugin {
|
||||
return {
|
||||
name: 'temporal-workflow',
|
||||
setup(build) {
|
||||
// Resolve imports with the workflow query parameter
|
||||
build.onResolve({ filter: /:::workflow$/ }, (args) => {
|
||||
console.log(args)
|
||||
|
||||
const cleanPath = args.path.split(':::')[0]!
|
||||
const resolveDir = args.importer
|
||||
? args.importer.replace(/[/\\\\][^/\\\\]*$/, '')
|
||||
: (args.resolveDir ?? process.cwd())
|
||||
const resolved = resolve(resolveDir, cleanPath)
|
||||
|
||||
return {
|
||||
path: resolved,
|
||||
namespace: 'temporal-workflow',
|
||||
}
|
||||
})
|
||||
|
||||
// Load and bundle workflow code
|
||||
build.onLoad({ filter: /.*/, namespace: 'temporal-workflow' }, async (args) => {
|
||||
const workflowsPath = args.path
|
||||
|
||||
// The bundleOptions contains raw parameters for Temporal bundleWorkflowCode which uses Webpack.
|
||||
// We cast options.bundleOptions to any to check for webpackConfigHook.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const originalHook = (options.bundleOptions as any)?.webpackConfigHook
|
||||
const bundleOptions = {
|
||||
...options.bundleOptions,
|
||||
// Webpack config is untyped inside Temporal's webpackConfigHook callback.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
webpackConfigHook: (config: any) => {
|
||||
config.resolve = config.resolve || {}
|
||||
config.resolve.alias = {
|
||||
...config.resolve.alias,
|
||||
'@shumai/workflow-core':
|
||||
require.resolve('@shumai/workflow-core/src/workflow-utils.ts'),
|
||||
'@temporalio/workflow': dirname(require.resolve('@temporalio/workflow/package.json')),
|
||||
}
|
||||
console.log('Webpack config aliases:', config.resolve.alias)
|
||||
if (originalHook) {
|
||||
return originalHook(config)
|
||||
}
|
||||
return config
|
||||
},
|
||||
}
|
||||
|
||||
const bundle = await bundleWorkflowCode({
|
||||
workflowsPath,
|
||||
...bundleOptions,
|
||||
})
|
||||
|
||||
return {
|
||||
contents: `export default { code: ${JSON.stringify(bundle.code)}, sourceMap: ${JSON.stringify(bundle.sourceMap ?? '')} };`,
|
||||
loader: 'js',
|
||||
}
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export default temporalWorkflow
|
||||
@@ -0,0 +1,476 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { DbosExecutor, getDbosDatabaseUrl, getQueueForTaskType } from './dbos-executor'
|
||||
import { TaskQueueAgent, TaskQueueTranscode } from './workflow-utils'
|
||||
import { WorkflowTaskStatus, WorkflowTaskType, WorkflowTask, prisma } from '@shumai/db'
|
||||
import { DBOS } from '@dbos-inc/dbos-sdk'
|
||||
|
||||
let activeExecutor: DbosExecutor | null = null
|
||||
|
||||
const stepFn = DBOS.registerStep(
|
||||
async () => {
|
||||
const mockTask = {
|
||||
id: 'task-from-step',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
} as WorkflowTask
|
||||
return await activeExecutor!.submit(mockTask)
|
||||
},
|
||||
{ name: 'testStepSubmittingTask' },
|
||||
)
|
||||
|
||||
const wf = DBOS.registerWorkflow(
|
||||
async () => {
|
||||
return await stepFn()
|
||||
},
|
||||
{ name: 'testWfRunningStep' },
|
||||
)
|
||||
|
||||
describe('DbosExecutor Tests', () => {
|
||||
let executor: DbosExecutor
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
executor = new DbosExecutor()
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await executor.shutdown()
|
||||
})
|
||||
|
||||
describe('Queue and URL resolution', () => {
|
||||
it('should map task types to proper queues', () => {
|
||||
expect(getQueueForTaskType(WorkflowTaskType.transcode)).toBe(TaskQueueTranscode)
|
||||
expect(getQueueForTaskType(WorkflowTaskType.transcode_video)).toBe(TaskQueueTranscode)
|
||||
expect(getQueueForTaskType(WorkflowTaskType.transcode_image)).toBe(TaskQueueTranscode)
|
||||
expect(getQueueForTaskType(WorkflowTaskType.ai_embedding)).toBe(TaskQueueAgent)
|
||||
expect(getQueueForTaskType(WorkflowTaskType.chat)).toBe(TaskQueueAgent)
|
||||
expect(getQueueForTaskType('unknown_type')).toBe(TaskQueueAgent)
|
||||
})
|
||||
|
||||
it('should sanitize query parameters for dbos database url', () => {
|
||||
const sanitized = getDbosDatabaseUrl(
|
||||
'postgresql://user:pass@localhost:5432/shumai?schema=public&search_path=public',
|
||||
)
|
||||
expect(sanitized).toBe('postgresql://user:pass@localhost:5432/shumai')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Concurrency Configuration', () => {
|
||||
let originalTranscode: string | undefined
|
||||
let originalAgent: string | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
originalTranscode = process.env.CONCURRENCY_TRANSCODE
|
||||
originalAgent = process.env.CONCURRENCY_AGENT
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (originalTranscode === undefined) {
|
||||
delete process.env.CONCURRENCY_TRANSCODE
|
||||
} else {
|
||||
process.env.CONCURRENCY_TRANSCODE = originalTranscode
|
||||
}
|
||||
|
||||
if (originalAgent === undefined) {
|
||||
delete process.env.CONCURRENCY_AGENT
|
||||
} else {
|
||||
process.env.CONCURRENCY_AGENT = originalAgent
|
||||
}
|
||||
})
|
||||
|
||||
it('should initialize with values from environment variables', () => {
|
||||
process.env.CONCURRENCY_TRANSCODE = '3'
|
||||
process.env.CONCURRENCY_AGENT = '7'
|
||||
|
||||
expect(executor.getTranscodeConcurrencyLimit()).toBe(3)
|
||||
expect(executor.getAgentConcurrencyLimit()).toBe(7)
|
||||
})
|
||||
|
||||
it('should fallback to defaults when environment variables are not set or invalid', () => {
|
||||
delete process.env.CONCURRENCY_TRANSCODE
|
||||
delete process.env.CONCURRENCY_AGENT
|
||||
|
||||
expect(executor.getTranscodeConcurrencyLimit()).toBe(1)
|
||||
expect(executor.getAgentConcurrencyLimit()).toBe(5)
|
||||
|
||||
process.env.CONCURRENCY_TRANSCODE = 'invalid'
|
||||
process.env.CONCURRENCY_AGENT = '-1'
|
||||
|
||||
expect(executor.getTranscodeConcurrencyLimit()).toBe(1)
|
||||
expect(executor.getAgentConcurrencyLimit()).toBe(5)
|
||||
})
|
||||
|
||||
it('should update effective queue worker concurrency when environment variables change', async () => {
|
||||
// First start with agent concurrency = 5 and transcode = 2
|
||||
process.env.CONCURRENCY_AGENT = '5'
|
||||
process.env.CONCURRENCY_TRANSCODE = '2'
|
||||
executor.start()
|
||||
await executor.ensureLaunched()
|
||||
|
||||
const agentQueueFirst = await DBOS.retrieveQueue(TaskQueueAgent)
|
||||
expect(agentQueueFirst?.workerConcurrency).toBe(5)
|
||||
const transcodeQueueFirst = await DBOS.retrieveQueue(TaskQueueTranscode)
|
||||
expect(transcodeQueueFirst?.workerConcurrency).toBe(2)
|
||||
|
||||
await executor.shutdown()
|
||||
|
||||
// Now change environment variables to safety limits (e.g. CONCURRENCY_AGENT=1, CONCURRENCY_TRANSCODE=4)
|
||||
process.env.CONCURRENCY_AGENT = '1'
|
||||
process.env.CONCURRENCY_TRANSCODE = '4'
|
||||
const executor2 = new DbosExecutor()
|
||||
try {
|
||||
executor2.start()
|
||||
await executor2.ensureLaunched()
|
||||
|
||||
const agentQueueUpdated = await DBOS.retrieveQueue(TaskQueueAgent)
|
||||
const transcodeQueueUpdated = await DBOS.retrieveQueue(TaskQueueTranscode)
|
||||
|
||||
expect(agentQueueUpdated?.workerConcurrency).toBe(1)
|
||||
expect(transcodeQueueUpdated?.workerConcurrency).toBe(4)
|
||||
} finally {
|
||||
await executor2.shutdown()
|
||||
}
|
||||
})
|
||||
|
||||
it('should only update queues the worker listens to or configures, leaving unmanaged queues untouched', async () => {
|
||||
const registerQueueSpy = vi.spyOn(DBOS, 'registerQueue')
|
||||
|
||||
process.env.CONCURRENCY_TRANSCODE = '3'
|
||||
const transcodeWorker = new DbosExecutor([TaskQueueTranscode])
|
||||
try {
|
||||
transcodeWorker.start()
|
||||
await transcodeWorker.ensureLaunched()
|
||||
|
||||
const transcodeQueue = await DBOS.retrieveQueue(TaskQueueTranscode)
|
||||
expect(transcodeQueue?.workerConcurrency).toBe(3)
|
||||
|
||||
// transcodeWorker should only have registered TaskQueueTranscode, not unmanaged queues like TaskQueueAgent
|
||||
const registeredQueueNames = registerQueueSpy.mock.calls.map((call) => call[0])
|
||||
expect(registeredQueueNames).toContain(TaskQueueTranscode)
|
||||
expect(registeredQueueNames).not.toContain(TaskQueueAgent)
|
||||
} finally {
|
||||
registerQueueSpy.mockRestore()
|
||||
delete process.env.CONCURRENCY_TRANSCODE
|
||||
await transcodeWorker.shutdown()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('Executor Identity & Multi-instance Recovery', () => {
|
||||
let originalEnv: NodeJS.ProcessEnv
|
||||
|
||||
beforeEach(() => {
|
||||
originalEnv = { ...process.env }
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
process.env = originalEnv
|
||||
})
|
||||
|
||||
it('should derive unique executor IDs for multiple replicas of the same role when no explicit ID is provided', () => {
|
||||
process.env.NODE_ENV = 'production'
|
||||
delete process.env.DBOS__VMID
|
||||
delete process.env.SHUMAI_WORKER_ID
|
||||
delete process.env.POD_NAME
|
||||
|
||||
const worker1 = new DbosExecutor([TaskQueueTranscode])
|
||||
const worker2 = new DbosExecutor([TaskQueueTranscode])
|
||||
|
||||
const id1 = worker1.getExecutorId()
|
||||
const id2 = worker2.getExecutorId()
|
||||
|
||||
expect(id1).not.toBe(id2)
|
||||
expect(id1).toContain('shumai-transcode')
|
||||
expect(id2).toContain('shumai-transcode')
|
||||
})
|
||||
|
||||
it('should incorporate SHUMAI_WORKER_ID or POD_NAME when configured', () => {
|
||||
process.env.NODE_ENV = 'production'
|
||||
delete process.env.DBOS__VMID
|
||||
|
||||
process.env.SHUMAI_WORKER_ID = 'replica-42'
|
||||
const workerWithId = new DbosExecutor([TaskQueueTranscode])
|
||||
expect(workerWithId.getExecutorId()).toBe('shumai-transcode-replica-42')
|
||||
|
||||
delete process.env.SHUMAI_WORKER_ID
|
||||
process.env.POD_NAME = 'shumai-transcode-pod-0'
|
||||
const workerWithPod = new DbosExecutor([TaskQueueTranscode])
|
||||
expect(workerWithPod.getExecutorId()).toBe('shumai-transcode-pod-0')
|
||||
})
|
||||
|
||||
it('should allow setting explicit executorId via constructor or setExecutorId', () => {
|
||||
const customWorker = new DbosExecutor([TaskQueueAgent], 'my-custom-worker')
|
||||
expect(customWorker.getExecutorId()).toBe('my-custom-worker')
|
||||
|
||||
customWorker.setExecutorId('updated-worker-id')
|
||||
expect(customWorker.getExecutorId()).toBe('updated-worker-id')
|
||||
})
|
||||
|
||||
it('should not recover live workflows belonging to another executor ID on startup', async () => {
|
||||
const activeWorkerId = `active-worker-${Date.now()}`
|
||||
const newWorkerId = `new-worker-${Date.now()}`
|
||||
const taskUuid = `task-recovery-test-${Date.now()}`
|
||||
|
||||
// Seed a pending task claimed by activeWorkerId
|
||||
await prisma.$queryRawUnsafe(
|
||||
`
|
||||
INSERT INTO dbos.workflow_status (
|
||||
workflow_uuid, status, name, executor_id, created_at, updated_at, application_version, application_name, queue_name
|
||||
) VALUES (
|
||||
$1, 'PENDING', 'testRecoveryWorkflow', $2, 0, 0, '1.0.0', 'shumai', 'transcode_queue'
|
||||
)
|
||||
`,
|
||||
taskUuid,
|
||||
activeWorkerId,
|
||||
)
|
||||
|
||||
try {
|
||||
// Launch a new worker with a distinct executor ID
|
||||
const newWorker = new DbosExecutor([TaskQueueTranscode], newWorkerId)
|
||||
newWorker.start()
|
||||
await newWorker.ensureLaunched()
|
||||
|
||||
// Verify the active worker's task was NOT recovered (remains PENDING with activeWorkerId)
|
||||
const rowsAfterOtherWorker = await prisma.$queryRawUnsafe<
|
||||
Array<{ status: string; executorId: string }>
|
||||
>(
|
||||
'SELECT status, executor_id AS "executorId" FROM dbos.workflow_status WHERE workflow_uuid = $1',
|
||||
taskUuid,
|
||||
)
|
||||
expect(rowsAfterOtherWorker[0].status).toBe('PENDING')
|
||||
expect(rowsAfterOtherWorker[0].executorId).toBe(activeWorkerId)
|
||||
|
||||
await newWorker.shutdown()
|
||||
|
||||
// Now simulate the active worker restarting with its OWN executor ID
|
||||
const restartedWorker = new DbosExecutor([TaskQueueTranscode], activeWorkerId)
|
||||
restartedWorker.start()
|
||||
await restartedWorker.ensureLaunched()
|
||||
|
||||
// Verify that on restart with the SAME executor ID, DBOS startup recovery DOES re-enqueue it
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
const rowsAfterRestart = await prisma.$queryRawUnsafe<
|
||||
Array<{ status: string; executorId: string }>
|
||||
>(
|
||||
'SELECT status, executor_id AS "executorId" FROM dbos.workflow_status WHERE workflow_uuid = $1',
|
||||
taskUuid,
|
||||
)
|
||||
expect(rowsAfterRestart[0]?.status).toBe('ENQUEUED')
|
||||
},
|
||||
{ timeout: 5000, interval: 50 },
|
||||
)
|
||||
|
||||
await restartedWorker.shutdown()
|
||||
} finally {
|
||||
await prisma.$queryRawUnsafe(
|
||||
'DELETE FROM dbos.workflow_status WHERE workflow_uuid = $1',
|
||||
taskUuid,
|
||||
)
|
||||
}
|
||||
}, 20000)
|
||||
})
|
||||
|
||||
describe('Cancellation', () => {
|
||||
it('should trigger local cancellation and abort signal', async () => {
|
||||
const {
|
||||
registerLocalCancelHandler,
|
||||
unregisterLocalCancelHandler,
|
||||
getLocalTaskAbortSignal,
|
||||
runInLocalTaskContext,
|
||||
} = await import('./workflow-utils')
|
||||
|
||||
const cancelSpy = vi.fn()
|
||||
const taskId = 'task-cancel-dbos-test'
|
||||
const abortController = new AbortController()
|
||||
|
||||
registerLocalCancelHandler(taskId, cancelSpy)
|
||||
|
||||
await runInLocalTaskContext({ taskId, abortController }, async () => {
|
||||
const signal = getLocalTaskAbortSignal(taskId)
|
||||
expect(signal?.aborted).toBe(false)
|
||||
|
||||
await executor.cancel(taskId)
|
||||
|
||||
expect(cancelSpy).toHaveBeenCalled()
|
||||
expect(signal?.aborted).toBe(true)
|
||||
})
|
||||
|
||||
unregisterLocalCancelHandler(taskId)
|
||||
})
|
||||
|
||||
it('should clear heartbeat intervals on cancel', async () => {
|
||||
const taskId = 'test-heartbeat-cancel'
|
||||
const interval = setInterval(() => {}, 1000)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accessing private field for verification
|
||||
const heartbeats = (executor as any).heartbeatIntervals as Map<string, Timer>
|
||||
heartbeats.set(taskId, interval)
|
||||
|
||||
await executor.cancel(taskId)
|
||||
|
||||
expect(heartbeats.has(taskId)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Submit', () => {
|
||||
it('should enqueue workflow with correct parameters', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(executor as any).started = true
|
||||
vi.spyOn(executor, 'ensureLaunched').mockResolvedValueOnce(undefined)
|
||||
const mockClient = {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS property name
|
||||
enqueue: vi.fn().mockResolvedValue({ workflowID: 'task-123' }),
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.spyOn(executor, 'getClient').mockResolvedValue(mockClient as any)
|
||||
|
||||
const mockTask = {
|
||||
id: 'task-123',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
} as WorkflowTask
|
||||
|
||||
const res = await executor.submit(mockTask)
|
||||
expect(res).toBe('task-123')
|
||||
expect(mockClient.enqueue).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
queueName: TaskQueueAgent,
|
||||
workflowName: WorkflowTaskType.chat,
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS property name
|
||||
workflowID: 'task-123',
|
||||
}),
|
||||
mockTask,
|
||||
)
|
||||
})
|
||||
|
||||
it('should enqueue workflow via client even when executor is not started and no local workflows are registered', async () => {
|
||||
// executor is not started and has no local workflows registered (e.g. CLI or producer mode)
|
||||
const mockClient = {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS property name
|
||||
enqueue: vi.fn().mockResolvedValue({ workflowID: 'task-cli-123' }),
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.spyOn(executor, 'getClient').mockResolvedValue(mockClient as any)
|
||||
|
||||
const mockTask = {
|
||||
id: 'task-cli-123',
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
} as WorkflowTask
|
||||
|
||||
const res = await executor.submit(mockTask)
|
||||
expect(mockClient.enqueue).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
queueName: TaskQueueAgent,
|
||||
workflowName: WorkflowTaskType.ai_embedding,
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS property name
|
||||
workflowID: 'task-cli-123',
|
||||
}),
|
||||
mockTask,
|
||||
)
|
||||
expect(res).toBe('task-cli-123')
|
||||
})
|
||||
|
||||
it('should allow submitting tasks from within a running DBOS step', async () => {
|
||||
executor.start()
|
||||
await executor.ensureLaunched()
|
||||
|
||||
const mockClient = {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS property name
|
||||
enqueue: vi.fn().mockResolvedValue({ workflowID: 'task-from-step' }),
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.spyOn(executor, 'getClient').mockResolvedValue(mockClient as any)
|
||||
|
||||
activeExecutor = executor
|
||||
const result = await wf()
|
||||
expect(result).toBe('task-from-step')
|
||||
expect(mockClient.enqueue).toHaveBeenCalled()
|
||||
}, 15000)
|
||||
})
|
||||
|
||||
describe('Workflow events and conflict handling', () => {
|
||||
it('should emit workflowStarted and workflowFinished events during execution', async () => {
|
||||
let startedTask: WorkflowTask | null = null
|
||||
let finishedPayload: { taskId: string; success: boolean } | null = null
|
||||
|
||||
executor.on('workflowStarted', (task) => {
|
||||
startedTask = task
|
||||
})
|
||||
executor.on('workflowFinished', (payload) => {
|
||||
finishedPayload = payload
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const wrapper = (executor as any).createDbosWorkflowWrapper('test-events-workflow')
|
||||
const { registerWorkflow } = await import('./dbos-executor')
|
||||
registerWorkflow('test-events-workflow', async () => {
|
||||
// do work
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
id: 'test-events-task',
|
||||
assetId: 'asset-events',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
await wrapper(task)
|
||||
|
||||
expect(startedTask).toBeDefined()
|
||||
expect((startedTask as WorkflowTask | null)?.id).toBe('test-events-task')
|
||||
expect(finishedPayload).toBeDefined()
|
||||
expect((finishedPayload as { taskId: string; success: boolean } | null)?.taskId).toBe(
|
||||
'test-events-task',
|
||||
)
|
||||
expect((finishedPayload as { taskId: string; success: boolean } | null)?.success).toBe(true)
|
||||
})
|
||||
|
||||
it('should handle DBOSWorkflowConflictError without marking task failed', async () => {
|
||||
const { DBOSWorkflowConflictError: DbosWorkflowConflictError } =
|
||||
await import('@dbos-inc/dbos-sdk')
|
||||
const { registerWorkflow } = await import('./dbos-executor')
|
||||
|
||||
registerWorkflow('test-conflict-workflow', async () => {
|
||||
throw new DbosWorkflowConflictError('test-conflict-task')
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const wrapper = (executor as any).createDbosWorkflowWrapper('test-conflict-workflow')
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
id: 'test-conflict-task',
|
||||
assetId: 'asset-conflict',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
await expect(wrapper(task)).rejects.toThrow('is no longer owned by this execution')
|
||||
|
||||
const updatedTask = await prisma.workflowTask.findUnique({
|
||||
where: { id: 'test-conflict-task' },
|
||||
})
|
||||
// Task should NOT be marked as failed!
|
||||
expect(updatedTask?.status).not.toBe(WorkflowTaskStatus.failed)
|
||||
})
|
||||
|
||||
it('should pass workflowCompletionTimeoutMs to DBOS.shutdown', async () => {
|
||||
const shutdownSpy = vi.spyOn(DBOS, 'shutdown').mockResolvedValue(undefined)
|
||||
const isInitSpy = vi.spyOn(DBOS, 'isInitialized').mockReturnValue(true)
|
||||
|
||||
await executor.shutdown({ workflowCompletionTimeoutMs: 290000 })
|
||||
|
||||
expect(shutdownSpy).toHaveBeenCalledWith({
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS SDK parameter name
|
||||
workflowCompletionTimeoutMS: 290000,
|
||||
})
|
||||
|
||||
shutdownSpy.mockRestore()
|
||||
isInitSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,461 @@
|
||||
import EventEmitter from 'node:events'
|
||||
import os from 'node:os'
|
||||
import { DBOS, DBOSClient, DBOSWorkflowConflictError } from '@dbos-inc/dbos-sdk'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { prisma, WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import {
|
||||
getConcurrencyLimit,
|
||||
registerLocalTaskAbortController,
|
||||
runInLocalTaskContext,
|
||||
TaskQueueAgent,
|
||||
TaskQueueTranscode,
|
||||
triggerLocalCancel,
|
||||
unregisterLocalTaskAbortController,
|
||||
} from './workflow-utils'
|
||||
|
||||
export function isWorkflowConflictError(err: unknown): boolean {
|
||||
if (err instanceof DBOSWorkflowConflictError) return true
|
||||
if (
|
||||
err &&
|
||||
typeof err === 'object' &&
|
||||
'dbosErrorCode' in err &&
|
||||
(err as { dbosErrorCode: unknown }).dbosErrorCode === 5
|
||||
) {
|
||||
return true
|
||||
}
|
||||
if (err instanceof Error && err.message.includes('is no longer owned by this execution')) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export type WorkflowFn = (task: WorkflowTask) => Promise<void>
|
||||
const workflowRegistry = new Map<string, WorkflowFn>()
|
||||
|
||||
export function registerWorkflow(type: string, fn: WorkflowFn): void {
|
||||
workflowRegistry.set(type, fn)
|
||||
}
|
||||
|
||||
export function getRegisteredWorkflows(): Map<string, WorkflowFn> {
|
||||
return workflowRegistry
|
||||
}
|
||||
|
||||
export function getDbosDatabaseUrl(rawUrl?: string): string {
|
||||
const urlStr =
|
||||
rawUrl || process.env.DATABASE_URL || 'postgresql://postgres:postgres@localhost:5432/shumai'
|
||||
try {
|
||||
const parsed = new URL(urlStr)
|
||||
parsed.searchParams.delete('schema')
|
||||
parsed.searchParams.delete('search_path')
|
||||
return parsed.toString()
|
||||
} catch {
|
||||
return urlStr
|
||||
}
|
||||
}
|
||||
|
||||
export function getQueueForTaskType(type: string | null | undefined): string {
|
||||
switch (type) {
|
||||
case WorkflowTaskType.ai_embedding:
|
||||
case WorkflowTaskType.ai_metadata_autofill:
|
||||
case WorkflowTaskType.chat:
|
||||
return TaskQueueAgent
|
||||
case WorkflowTaskType.transcode:
|
||||
case WorkflowTaskType.transcode_video:
|
||||
case WorkflowTaskType.transcode_image:
|
||||
case WorkflowTaskType.transcode_pdf:
|
||||
case WorkflowTaskType.transcode_pdf_pages:
|
||||
case WorkflowTaskType.transcode_screenshot:
|
||||
case WorkflowTaskType.transcode_image_annotation:
|
||||
case WorkflowTaskType.transcode_watermark:
|
||||
case WorkflowTaskType.transcode_3d:
|
||||
return TaskQueueTranscode
|
||||
default:
|
||||
if (type && type.startsWith('transcode')) {
|
||||
return TaskQueueTranscode
|
||||
}
|
||||
return TaskQueueAgent
|
||||
}
|
||||
}
|
||||
|
||||
let dbosMigrationsRan = false
|
||||
const registeredDbosWorkflowNames = new Set<string>()
|
||||
|
||||
export class DbosExecutor extends EventEmitter {
|
||||
private launchPromise: Promise<void> | null = null
|
||||
private started = false
|
||||
private client: DBOSClient | null = null
|
||||
private listenQueues: string[] = [TaskQueueAgent, TaskQueueTranscode]
|
||||
private heartbeatIntervals = new Map<string, Timer>()
|
||||
private inFlightSubmits = new Set<Promise<string>>()
|
||||
private executorId?: string
|
||||
private instanceSuffix = Math.random().toString(36).slice(2, 8)
|
||||
|
||||
constructor(listenQueues?: string[], executorId?: string) {
|
||||
super()
|
||||
if (listenQueues) {
|
||||
this.listenQueues = listenQueues
|
||||
}
|
||||
if (executorId) {
|
||||
this.executorId = executorId
|
||||
}
|
||||
}
|
||||
|
||||
isStarted(): boolean {
|
||||
return this.started
|
||||
}
|
||||
|
||||
setListenQueues(queues: string[]): void {
|
||||
this.listenQueues = queues
|
||||
}
|
||||
|
||||
getTranscodeConcurrencyLimit(): number {
|
||||
return getConcurrencyLimit(process.env.CONCURRENCY_TRANSCODE, 1)
|
||||
}
|
||||
|
||||
getAgentConcurrencyLimit(): number {
|
||||
return getConcurrencyLimit(process.env.CONCURRENCY_AGENT, 5)
|
||||
}
|
||||
|
||||
private registerAllWorkflowsWithDbos(): void {
|
||||
const workflows = getRegisteredWorkflows()
|
||||
for (const type of workflows.keys()) {
|
||||
if (registeredDbosWorkflowNames.has(type)) {
|
||||
continue
|
||||
}
|
||||
const wrappedFn = this.createDbosWorkflowWrapper(type)
|
||||
DBOS.registerWorkflow(wrappedFn, { name: type })
|
||||
registeredDbosWorkflowNames.add(type)
|
||||
}
|
||||
}
|
||||
|
||||
private createDbosWorkflowWrapper(type: string): (task: WorkflowTask) => Promise<void> {
|
||||
return async (task: WorkflowTask): Promise<void> => {
|
||||
const fn = getRegisteredWorkflows().get(type)
|
||||
if (!fn) {
|
||||
throw new Error(`No workflow registered for type: ${type}`)
|
||||
}
|
||||
this.emit('workflowStarted', task)
|
||||
// Mark task as processing and start heartbeat
|
||||
try {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: {
|
||||
id: task.id,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
data: {
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: new Date(),
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
logger.warn({ taskId: task.id, err }, '[DbosExecutor] Failed to mark task as processing')
|
||||
}
|
||||
|
||||
const heartbeatInterval = setInterval(async () => {
|
||||
try {
|
||||
const { count } = await prisma.workflowTask.updateMany({
|
||||
where: { id: task.id },
|
||||
data: { heartbeat: new Date() },
|
||||
})
|
||||
if (count === 0) {
|
||||
clearInterval(heartbeatInterval)
|
||||
this.heartbeatIntervals.delete(task.id)
|
||||
}
|
||||
} catch {
|
||||
// Ignore transient heartbeat errors
|
||||
}
|
||||
}, 5000)
|
||||
this.heartbeatIntervals.set(task.id, heartbeatInterval)
|
||||
|
||||
const abortController = new AbortController()
|
||||
registerLocalTaskAbortController(task.id, abortController)
|
||||
|
||||
let workflowError: unknown
|
||||
try {
|
||||
await runInLocalTaskContext({ taskId: task.id, abortController }, async () => {
|
||||
await fn(task)
|
||||
})
|
||||
} catch (err) {
|
||||
workflowError = err
|
||||
if (isWorkflowConflictError(err)) {
|
||||
logger.warn(
|
||||
{ taskId: task.id, type, err },
|
||||
'[DbosExecutor] Workflow execution superseded (ownership lost or conflict). Skipping marking task as failed.',
|
||||
)
|
||||
throw err
|
||||
}
|
||||
logger.error({ taskId: task.id, type, err }, `[DbosExecutor] Error in workflow ${type}`)
|
||||
try {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: task.id },
|
||||
data: {
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
},
|
||||
})
|
||||
} catch (updateErr) {
|
||||
logger.error(
|
||||
{ taskId: task.id, err: updateErr },
|
||||
'[DbosExecutor] Failed to mark task failed',
|
||||
)
|
||||
}
|
||||
throw err
|
||||
} finally {
|
||||
clearInterval(heartbeatInterval)
|
||||
this.heartbeatIntervals.delete(task.id)
|
||||
unregisterLocalTaskAbortController(task.id)
|
||||
this.emit('workflowFinished', {
|
||||
taskId: task.id,
|
||||
type,
|
||||
success: !workflowError,
|
||||
error: workflowError,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getRole(): string {
|
||||
if (this.listenQueues.length === 0) return 'shumai-web'
|
||||
if (this.listenQueues.length === 1) {
|
||||
if (this.listenQueues[0] === TaskQueueTranscode) return 'shumai-transcode'
|
||||
if (this.listenQueues[0] === TaskQueueAgent) return 'shumai-agent'
|
||||
}
|
||||
return 'shumai-all'
|
||||
}
|
||||
|
||||
setExecutorId(id: string): void {
|
||||
this.executorId = id
|
||||
}
|
||||
|
||||
getExecutorId(): string {
|
||||
return this.getDefaultExecutorId()
|
||||
}
|
||||
|
||||
private getDefaultExecutorId(): string {
|
||||
if (this.executorId) return this.executorId
|
||||
if (process.env.DBOS__VMID) return process.env.DBOS__VMID
|
||||
|
||||
const role = this.getRole()
|
||||
if (process.env.SHUMAI_WORKER_ID) {
|
||||
const workerId = process.env.SHUMAI_WORKER_ID
|
||||
return workerId.startsWith(role) ? workerId : `${role}-${workerId}`
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV === 'test') {
|
||||
return `shumai-test-${process.pid}-${this.instanceSuffix}`
|
||||
}
|
||||
|
||||
// In Kubernetes, POD_NAME is standard and stable across pod restarts in StatefulSets
|
||||
if (process.env.POD_NAME) {
|
||||
const pod = process.env.POD_NAME
|
||||
return pod.startsWith(role) ? pod : `${role}-${pod}`
|
||||
}
|
||||
|
||||
// In Docker containers, HOSTNAME is set to the unique container short ID.
|
||||
// If running on host machine / bare metal, disambiguate with pid and instance suffix.
|
||||
const host = process.env.HOSTNAME || os.hostname() || 'instance'
|
||||
return `${role}-${host}-${process.pid}-${this.instanceSuffix}`
|
||||
}
|
||||
|
||||
async ensureLaunched(): Promise<void> {
|
||||
if (DBOS.isInitialized()) {
|
||||
return
|
||||
}
|
||||
if (this.launchPromise) {
|
||||
return this.launchPromise
|
||||
}
|
||||
|
||||
this.launchPromise = (async () => {
|
||||
this.registerAllWorkflowsWithDbos()
|
||||
|
||||
const isTest = process.env.NODE_ENV === 'test'
|
||||
if (!isTest && !dbosMigrationsRan) {
|
||||
await DBOS.migrate(getDbosDatabaseUrl())
|
||||
dbosMigrationsRan = true
|
||||
}
|
||||
|
||||
DBOS.setConfig({
|
||||
name: 'shumai',
|
||||
systemDatabaseUrl: getDbosDatabaseUrl(),
|
||||
systemDatabasePoolSize: isTest ? 5 : undefined,
|
||||
applicationVersion: process.env.SHUMAI_VERSION || '1.0.0',
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS config property name
|
||||
executorID: this.getDefaultExecutorId(),
|
||||
listenQueues: this.listenQueues,
|
||||
runMigrations: false,
|
||||
logLevel: isTest ? 'error' : 'info',
|
||||
})
|
||||
|
||||
await DBOS.launch()
|
||||
|
||||
const minPollingIntervalMs = isTest ? 50 : 1000
|
||||
for (const queueName of this.listenQueues) {
|
||||
if (queueName === TaskQueueTranscode) {
|
||||
await DBOS.registerQueue(TaskQueueTranscode, {
|
||||
workerConcurrency: this.getTranscodeConcurrencyLimit(),
|
||||
minPollingIntervalMs,
|
||||
onConflict: 'always_update',
|
||||
})
|
||||
} else if (queueName === TaskQueueAgent) {
|
||||
await DBOS.registerQueue(TaskQueueAgent, {
|
||||
workerConcurrency: this.getAgentConcurrencyLimit(),
|
||||
minPollingIntervalMs,
|
||||
onConflict: 'always_update',
|
||||
})
|
||||
}
|
||||
}
|
||||
})()
|
||||
|
||||
try {
|
||||
await this.launchPromise
|
||||
} catch (err) {
|
||||
this.launchPromise = null
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
async getClient(): Promise<DBOSClient> {
|
||||
if (!this.client) {
|
||||
const isTest = process.env.NODE_ENV === 'test'
|
||||
this.client = await DBOSClient.create({
|
||||
systemDatabaseUrl: getDbosDatabaseUrl(),
|
||||
systemDatabasePoolSize: isTest ? 3 : undefined,
|
||||
})
|
||||
}
|
||||
return this.client
|
||||
}
|
||||
|
||||
async submit(task: WorkflowTask): Promise<string> {
|
||||
const submitPromise = this.doSubmit(task)
|
||||
this.inFlightSubmits.add(submitPromise)
|
||||
try {
|
||||
return await submitPromise
|
||||
} finally {
|
||||
this.inFlightSubmits.delete(submitPromise)
|
||||
}
|
||||
}
|
||||
|
||||
private async doSubmit(task: WorkflowTask): Promise<string> {
|
||||
if (task.status !== WorkflowTaskStatus.pending) {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: task.id },
|
||||
data: { status: WorkflowTaskStatus.pending },
|
||||
})
|
||||
}
|
||||
|
||||
if (this.started) {
|
||||
await this.ensureLaunched()
|
||||
}
|
||||
|
||||
const workflowName = task.type
|
||||
if (!workflowName) {
|
||||
throw new Error(`WorkflowTask ${task.id} is missing task.type`)
|
||||
}
|
||||
|
||||
const queueName = getQueueForTaskType(workflowName)
|
||||
const client = await this.getClient()
|
||||
const handle = await client.enqueue(
|
||||
{
|
||||
queueName,
|
||||
workflowName,
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS property name
|
||||
workflowID: task.id,
|
||||
appVersion: process.env.SHUMAI_VERSION || '1.0.0',
|
||||
},
|
||||
task,
|
||||
)
|
||||
|
||||
return handle.workflowID
|
||||
}
|
||||
|
||||
async waitForPendingSubmissions(): Promise<void> {
|
||||
while (this.inFlightSubmits.size > 0) {
|
||||
await Promise.allSettled(Array.from(this.inFlightSubmits))
|
||||
}
|
||||
}
|
||||
|
||||
async cancel(taskId: string): Promise<void> {
|
||||
const timer = this.heartbeatIntervals.get(taskId)
|
||||
if (timer) {
|
||||
clearInterval(timer)
|
||||
this.heartbeatIntervals.delete(taskId)
|
||||
}
|
||||
triggerLocalCancel(taskId)
|
||||
try {
|
||||
const client = await this.getClient()
|
||||
await client.cancelWorkflow(taskId)
|
||||
logger.info({ taskId }, '[DbosExecutor] Cancelled workflow task')
|
||||
} catch (err) {
|
||||
logger.warn({ taskId, err }, '[DbosExecutor] Failed to cancel workflow task in DBOS')
|
||||
}
|
||||
}
|
||||
|
||||
start(): void {
|
||||
this.started = true
|
||||
this.ensureLaunched().catch((err) => {
|
||||
logger.error({ err }, '[DbosExecutor] Failed to launch DBOS on start()')
|
||||
})
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.started = false
|
||||
this.waitForPendingSubmissions().catch(() => {})
|
||||
const cleanupResources = () => {
|
||||
for (const timer of this.heartbeatIntervals.values()) {
|
||||
clearInterval(timer)
|
||||
}
|
||||
this.heartbeatIntervals.clear()
|
||||
if (this.client) {
|
||||
this.client.destroy().catch(() => {})
|
||||
this.client = null
|
||||
}
|
||||
}
|
||||
|
||||
if (DBOS.isInitialized()) {
|
||||
DBOS.shutdown()
|
||||
.then(() => {
|
||||
this.launchPromise = null
|
||||
})
|
||||
.catch((err) => {
|
||||
logger.warn({ err }, '[DbosExecutor] Error during DBOS shutdown')
|
||||
})
|
||||
.finally(cleanupResources)
|
||||
} else {
|
||||
cleanupResources()
|
||||
}
|
||||
}
|
||||
|
||||
async shutdown(options?: { workflowCompletionTimeoutMs?: number }): Promise<void> {
|
||||
this.started = false
|
||||
await this.waitForPendingSubmissions()
|
||||
|
||||
const timeoutMs =
|
||||
options?.workflowCompletionTimeoutMs ??
|
||||
(process.env.SHUMAI_WORKER_DRAIN_TIMEOUT_MS
|
||||
? parseInt(process.env.SHUMAI_WORKER_DRAIN_TIMEOUT_MS, 10)
|
||||
: undefined)
|
||||
|
||||
try {
|
||||
if (DBOS.isInitialized()) {
|
||||
await DBOS.shutdown(
|
||||
timeoutMs !== undefined
|
||||
? {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS SDK parameter name
|
||||
workflowCompletionTimeoutMS: timeoutMs,
|
||||
}
|
||||
: undefined,
|
||||
)
|
||||
this.launchPromise = null
|
||||
}
|
||||
} finally {
|
||||
for (const timer of this.heartbeatIntervals.values()) {
|
||||
clearInterval(timer)
|
||||
}
|
||||
this.heartbeatIntervals.clear()
|
||||
if (this.client) {
|
||||
await this.client.destroy().catch(() => {})
|
||||
this.client = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
import { WorkflowTask } from '@shumai/db'
|
||||
|
||||
export interface Executor {
|
||||
submit(task: WorkflowTask): Promise<string>
|
||||
cancel?(taskId: string): Promise<void>
|
||||
start(): void
|
||||
close(): void
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
export * from './executor'
|
||||
export * from './local-executor'
|
||||
export * from './temporal-executor'
|
||||
export * from './dbos-executor'
|
||||
export * from './workflow-utils'
|
||||
export * from './workflow'
|
||||
export * from './activities/task'
|
||||
|
||||
@@ -1,561 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { workflowService } from './workflow'
|
||||
import { LocalExecutor, ConcurrencyLimiter, registerWorkflow } from './local-executor'
|
||||
import { WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
|
||||
// Mock the individual workflows
|
||||
const mocks = {
|
||||
agentEmbeddingMedia: vi.fn(),
|
||||
agentAutofillMedia: vi.fn(),
|
||||
agentChat: vi.fn(),
|
||||
transcodeMedia: vi.fn(),
|
||||
}
|
||||
|
||||
describe('LocalExecutor Integration Tests', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let executor: LocalExecutor
|
||||
|
||||
beforeEach(() => {
|
||||
// Get the global executor instance which processes tasks submitted via the Prisma Client Extension
|
||||
executor = (workflowService as unknown as { executor: LocalExecutor }).executor
|
||||
vi.clearAllMocks()
|
||||
|
||||
// Register workflows dynamically for testing
|
||||
registerWorkflow(WorkflowTaskType.ai_embedding, async (task) => mocks.agentEmbeddingMedia(task))
|
||||
registerWorkflow(WorkflowTaskType.ai_metadata_autofill, async (task) =>
|
||||
mocks.agentAutofillMedia(task),
|
||||
)
|
||||
registerWorkflow(WorkflowTaskType.chat, async (task) => mocks.agentChat(task))
|
||||
registerWorkflow(WorkflowTaskType.transcode, async (task) => mocks.transcodeMedia(task))
|
||||
})
|
||||
|
||||
describe('Heartbeat & Task Status transition', () => {
|
||||
it('should immediately transition task to processing and set initial heartbeat', async () => {
|
||||
let resolveChat: (value: unknown) => void = () => {}
|
||||
const chatPromise = new Promise((resolve) => {
|
||||
resolveChat = resolve
|
||||
})
|
||||
mocks.agentChat.mockImplementationOnce(() => chatPromise)
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'test-asset',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
// Wait briefly for the Prisma Client Extension's async submit (setTimeout 0) to execute and transition task
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
|
||||
const intermediateTask = await prisma.workflowTask.findUnique({
|
||||
where: { id: task.id },
|
||||
})
|
||||
|
||||
expect(intermediateTask?.status).toBe(WorkflowTaskStatus.processing)
|
||||
expect(intermediateTask?.heartbeat).toBeInstanceOf(Date)
|
||||
|
||||
// Clean up
|
||||
resolveChat(undefined)
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
})
|
||||
|
||||
it('should immediately lock task and start heartbeat updates in database even when queued in limiter', async () => {
|
||||
let resolveFirstTranscode: (value: unknown) => void = () => {}
|
||||
const firstTranscodePromise = new Promise((resolve) => {
|
||||
resolveFirstTranscode = resolve
|
||||
})
|
||||
mocks.transcodeMedia.mockImplementationOnce(() => firstTranscodePromise)
|
||||
mocks.transcodeMedia.mockImplementationOnce(() => Promise.resolve())
|
||||
|
||||
// 1. Create task 1 (will run immediately and hold the transcode limiter slot)
|
||||
const task1 = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
// 2. Create task 2 (will be blocked and queued in memory by transcode limiter)
|
||||
const task2 = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'asset-2',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
// Wait briefly for Prisma Client Extension's async submits to queue task2
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
|
||||
// 3. Verify task 1 is running
|
||||
expect(mocks.transcodeMedia).toHaveBeenCalledWith(expect.objectContaining({ id: task1.id }))
|
||||
|
||||
// 4. Verify task 2 has NOT started executing yet
|
||||
expect(mocks.transcodeMedia).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: task2.id }),
|
||||
)
|
||||
|
||||
// 5. BUT verify task 2 is already locked in database and has heartbeat set!
|
||||
const dbTask2 = await prisma.workflowTask.findUnique({
|
||||
where: { id: task2.id },
|
||||
})
|
||||
|
||||
expect(dbTask2?.status).toBe(WorkflowTaskStatus.processing)
|
||||
expect(dbTask2?.heartbeat).toBeInstanceOf(Date)
|
||||
|
||||
// Clean up
|
||||
resolveFirstTranscode(undefined)
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
})
|
||||
|
||||
it('should atomically claim tasks using CAS updateMany to prevent double-execution when tick() runs concurrently', async () => {
|
||||
mocks.agentChat.mockResolvedValue(undefined)
|
||||
|
||||
// Mock submit to prevent automatic execution by the Prisma Client Extension
|
||||
const submitSpy = vi.spyOn(workflowService, 'submit').mockResolvedValue('dummy-id')
|
||||
|
||||
// Create a single pending task (will NOT be run automatically because submit is mocked)
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'asset-concurrent-test',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
// We trigger two ticks concurrently to simulate overlapping polling cycles or multi-replica triggers.
|
||||
// Both ticks will query the database at approximately the same time.
|
||||
const tick1 = executor.tick()
|
||||
const tick2 = executor.tick()
|
||||
|
||||
const [promises1, promises2] = await Promise.all([tick1, tick2])
|
||||
await Promise.all([...promises1, ...promises2])
|
||||
|
||||
// Verify that the mock workflow is called EXACTLY ONCE for this task ID,
|
||||
// proving that one tick successfully claimed the task and the other was atomically blocked.
|
||||
expect(mocks.agentChat).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.agentChat).toHaveBeenCalledWith(expect.objectContaining({ id: task.id }))
|
||||
|
||||
submitSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('should query and retry stale tasks in tick() but ignore non-stale processing tasks', async () => {
|
||||
mocks.agentChat.mockResolvedValue(undefined)
|
||||
|
||||
// 1. Create a stale task (processing, heartbeat 40 seconds ago)
|
||||
const staleTask = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'asset-stale',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: new Date(Date.now() - 40 * 1000),
|
||||
},
|
||||
})
|
||||
|
||||
// 2. Create a non-stale task (processing, heartbeat 5 seconds ago)
|
||||
const activeTask = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'asset-active',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: new Date(Date.now() - 5 * 1000),
|
||||
},
|
||||
})
|
||||
|
||||
// Trigger tick manually on the executor and await the returned task promises
|
||||
const promises = await executor.tick()
|
||||
await Promise.all(promises)
|
||||
|
||||
// The stale task should be picked up and processed (mocks.agentChat called for staleTask)
|
||||
expect(mocks.agentChat).toHaveBeenCalledWith(expect.objectContaining({ id: staleTask.id }))
|
||||
|
||||
// The active task should NOT be called
|
||||
expect(mocks.agentChat).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: activeTask.id }),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Concurrency Control', () => {
|
||||
it('should limit transcode tasks to a concurrency of 1', async () => {
|
||||
let resolveFirstTranscode: (value: unknown) => void = () => {}
|
||||
const firstTranscodePromise = new Promise((resolve) => {
|
||||
resolveFirstTranscode = resolve
|
||||
})
|
||||
mocks.transcodeMedia.mockImplementationOnce(() => firstTranscodePromise)
|
||||
mocks.transcodeMedia.mockImplementationOnce(() => Promise.resolve())
|
||||
|
||||
const task1 = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
const task2 = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'asset-2',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
// Wait briefly for Prisma Client Extension's async submits to trigger
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
|
||||
// The first task should be actively running
|
||||
expect(mocks.transcodeMedia).toHaveBeenCalledWith(expect.objectContaining({ id: task1.id }))
|
||||
// The second task should NOT have started yet because transcode pool limit is 1
|
||||
expect(mocks.transcodeMedia).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: task2.id }),
|
||||
)
|
||||
|
||||
// Resolve the first task to let the second task execute
|
||||
resolveFirstTranscode(undefined)
|
||||
|
||||
// Wait briefly for the pool queue to process next item
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
|
||||
// The second task should now be running
|
||||
expect(mocks.transcodeMedia).toHaveBeenCalledWith(expect.objectContaining({ id: task2.id }))
|
||||
})
|
||||
|
||||
it('should limit general tasks to a concurrency of 5 and run them concurrently', async () => {
|
||||
const activeResolvers: ((value: unknown) => void)[] = []
|
||||
mocks.agentChat.mockImplementation(() => {
|
||||
return new Promise((resolve) => {
|
||||
activeResolvers.push(resolve)
|
||||
})
|
||||
})
|
||||
|
||||
// Create 7 general workflow tasks (limit is 5)
|
||||
await Promise.all(
|
||||
Array.from({ length: 7 }).map((_, i) =>
|
||||
prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: `asset-chat-${i}`,
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
// Wait briefly for Prisma Client Extension's async submits to trigger
|
||||
await vi.waitFor(() => expect(mocks.agentChat).toHaveBeenCalledTimes(5))
|
||||
|
||||
// Resolve 2 tasks to let the remaining 2 start
|
||||
activeResolvers[0](undefined)
|
||||
activeResolvers[1](undefined)
|
||||
|
||||
// Now all 7 tasks should have started
|
||||
await vi.waitFor(() => expect(mocks.agentChat).toHaveBeenCalledTimes(7))
|
||||
|
||||
// Clean up remaining tasks
|
||||
activeResolvers.slice(2).forEach((resolve) => resolve(undefined))
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
})
|
||||
})
|
||||
|
||||
describe('ConcurrencyLimiter Unit Tests', () => {
|
||||
it('should not allow concurrency limit violation during microtask race conditions', async () => {
|
||||
const limiter = new ConcurrencyLimiter(1)
|
||||
|
||||
// Task A starts and runs
|
||||
let resolveA: () => void = () => {}
|
||||
const promiseA = limiter.run(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
resolveA = resolve
|
||||
}),
|
||||
)
|
||||
|
||||
// Task B enters and is queued
|
||||
let resolveB: () => void = () => {}
|
||||
const promiseB = limiter.run(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
resolveB = resolve
|
||||
}),
|
||||
)
|
||||
|
||||
// Wait briefly for Task B to queue up
|
||||
await new Promise((resolve) => setTimeout(resolve, 10))
|
||||
|
||||
expect(limiter.getActiveCount()).toBe(1)
|
||||
expect(limiter.getQueueLength()).toBe(1)
|
||||
|
||||
// Complete Task A (schedules Task A's body to resume)
|
||||
resolveA()
|
||||
|
||||
// Wait exactly one microtask tick to let Task A exit and trigger finally block (resolving Task B)
|
||||
// This positions us in the microtask gap before Task B resumes execution
|
||||
await Promise.resolve()
|
||||
|
||||
// Task C immediately enters the limiter synchronously
|
||||
let resolveC: () => void = () => {}
|
||||
const promiseC = limiter.run(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
resolveC = resolve
|
||||
}),
|
||||
)
|
||||
|
||||
// Under the buggy implementation:
|
||||
// - Task A's finally block decremented activeCount to 0.
|
||||
// - Task C sees activeCount = 0 and runs immediately instead of queueing.
|
||||
// - So queue length would be 0, and Task C is active.
|
||||
//
|
||||
// Under the fixed implementation:
|
||||
// - Task A's finally block transferred the slot to Task B without decrementing activeCount.
|
||||
// - So activeCount remains 1.
|
||||
// - Task C sees activeCount = 1 and is correctly queued.
|
||||
// - So queue length is 1, and Task C is NOT active.
|
||||
expect(limiter.getActiveCount()).toBe(1)
|
||||
expect(limiter.getQueueLength()).toBe(1)
|
||||
|
||||
// Clean up by resolving the rest in order
|
||||
// 1. Let Task B resume and run
|
||||
await new Promise((resolve) => setTimeout(resolve, 10))
|
||||
resolveB()
|
||||
|
||||
// 2. Let Task C resume and run
|
||||
await new Promise((resolve) => setTimeout(resolve, 10))
|
||||
resolveC()
|
||||
|
||||
await Promise.all([promiseA, promiseB, promiseC])
|
||||
|
||||
expect(limiter.getActiveCount()).toBe(0)
|
||||
expect(limiter.getQueueLength()).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Environment Variable Concurrency Config', () => {
|
||||
let originalTranscode: string | undefined
|
||||
let originalAgent: string | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
originalTranscode = process.env.CONCURRENCY_TRANSCODE
|
||||
originalAgent = process.env.CONCURRENCY_AGENT
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (originalTranscode === undefined) {
|
||||
delete process.env.CONCURRENCY_TRANSCODE
|
||||
} else {
|
||||
process.env.CONCURRENCY_TRANSCODE = originalTranscode
|
||||
}
|
||||
|
||||
if (originalAgent === undefined) {
|
||||
delete process.env.CONCURRENCY_AGENT
|
||||
} else {
|
||||
process.env.CONCURRENCY_AGENT = originalAgent
|
||||
}
|
||||
})
|
||||
|
||||
it('should initialize with values from environment variables', () => {
|
||||
process.env.CONCURRENCY_TRANSCODE = '2'
|
||||
process.env.CONCURRENCY_AGENT = '8'
|
||||
|
||||
const customExecutor = new LocalExecutor()
|
||||
expect(customExecutor.getTranscodeConcurrencyLimit()).toBe(2)
|
||||
expect(customExecutor.getAgentConcurrencyLimit()).toBe(8)
|
||||
})
|
||||
|
||||
it('should fallback to defaults when environment variables are not set', () => {
|
||||
delete process.env.CONCURRENCY_TRANSCODE
|
||||
delete process.env.CONCURRENCY_AGENT
|
||||
|
||||
const defaultExecutor = new LocalExecutor()
|
||||
expect(defaultExecutor.getTranscodeConcurrencyLimit()).toBe(1)
|
||||
expect(defaultExecutor.getAgentConcurrencyLimit()).toBe(5)
|
||||
})
|
||||
|
||||
it('should fallback to defaults when environment variables are invalid or <= 0', () => {
|
||||
process.env.CONCURRENCY_TRANSCODE = 'invalid'
|
||||
process.env.CONCURRENCY_AGENT = '0'
|
||||
|
||||
const executor1 = new LocalExecutor()
|
||||
expect(executor1.getTranscodeConcurrencyLimit()).toBe(1)
|
||||
expect(executor1.getAgentConcurrencyLimit()).toBe(5)
|
||||
|
||||
process.env.CONCURRENCY_TRANSCODE = '-2'
|
||||
process.env.CONCURRENCY_AGENT = 'abc'
|
||||
|
||||
const executor2 = new LocalExecutor()
|
||||
expect(executor2.getTranscodeConcurrencyLimit()).toBe(1)
|
||||
expect(executor2.getAgentConcurrencyLimit()).toBe(5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Cancellation', () => {
|
||||
it('registers and triggers local cancel handlers', async () => {
|
||||
const { registerLocalCancelHandler, unregisterLocalCancelHandler } =
|
||||
await import('./workflow-utils')
|
||||
|
||||
const cancelSpy = vi.fn()
|
||||
const taskId = 'task-cancel-test'
|
||||
|
||||
registerLocalCancelHandler(taskId, cancelSpy)
|
||||
|
||||
await executor.cancel(taskId)
|
||||
expect(cancelSpy).toHaveBeenCalled()
|
||||
|
||||
unregisterLocalCancelHandler(taskId)
|
||||
})
|
||||
|
||||
it('clears active heartbeat timer when cancelling a task', async () => {
|
||||
let resolveChat: (value: unknown) => void = () => {}
|
||||
const chatPromise = new Promise((resolve) => {
|
||||
resolveChat = resolve
|
||||
})
|
||||
mocks.agentChat.mockImplementationOnce(() => chatPromise)
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'test-asset-cancel',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
// Wait briefly for submit to start and establish heartbeat
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
|
||||
// Heartbeat timer should be tracked
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const heartbeats = (executor as any).heartbeatIntervals as Map<string, Timer>
|
||||
expect(heartbeats.has(task.id)).toBe(true)
|
||||
|
||||
await executor.cancel(task.id)
|
||||
|
||||
// Timer should be cleared and removed
|
||||
expect(heartbeats.has(task.id)).toBe(false)
|
||||
|
||||
resolveChat(undefined)
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
})
|
||||
|
||||
it('handles heartbeat updateMany returning 0 when task is deleted from database', async () => {
|
||||
let resolveChat: (value: unknown) => void = () => {}
|
||||
const chatPromise = new Promise((resolve) => {
|
||||
resolveChat = resolve
|
||||
})
|
||||
mocks.agentChat.mockImplementationOnce(() => chatPromise)
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'test-asset-deleted',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
|
||||
// Delete the task from DB while task is running
|
||||
await prisma.workflowTask.delete({ where: { id: task.id } })
|
||||
|
||||
// UpdateMany should safely return count 0 without throwing P2025
|
||||
const { count } = await prisma.workflowTask.updateMany({
|
||||
where: { id: task.id },
|
||||
data: { heartbeat: new Date() },
|
||||
})
|
||||
expect(count).toBe(0)
|
||||
|
||||
resolveChat(undefined)
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
})
|
||||
|
||||
it('aborts local task abort signal when task is cancelled', async () => {
|
||||
const { getLocalTaskAbortSignal } = await import('./workflow-utils')
|
||||
let resolveChat: (value: unknown) => void = () => {}
|
||||
const chatPromise = new Promise((resolve) => {
|
||||
resolveChat = resolve
|
||||
})
|
||||
mocks.agentChat.mockImplementationOnce(() => chatPromise)
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'test-asset-abort-signal',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
|
||||
const signal = getLocalTaskAbortSignal(task.id)
|
||||
expect(signal).toBeDefined()
|
||||
expect(signal?.aborted).toBe(false)
|
||||
|
||||
await executor.cancel(task.id)
|
||||
|
||||
expect(signal?.aborted).toBe(true)
|
||||
|
||||
resolveChat(undefined)
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
})
|
||||
|
||||
it('cancels queued local tasks before execution when limiter is saturated', async () => {
|
||||
let resolveFirstTranscode: (value: unknown) => void = () => {}
|
||||
const firstTranscodePromise = new Promise((resolve) => {
|
||||
resolveFirstTranscode = resolve
|
||||
})
|
||||
mocks.transcodeMedia.mockImplementationOnce(() => firstTranscodePromise)
|
||||
mocks.transcodeMedia.mockImplementationOnce(() => Promise.resolve())
|
||||
|
||||
// 1. Task 1 starts and occupies the single transcode slot
|
||||
const task1 = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'asset-queued-cancel-1',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
// 2. Task 2 is submitted and queued because concurrency limit is 1
|
||||
const task2 = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'asset-queued-cancel-2',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
|
||||
// Task 1 should be running
|
||||
expect(mocks.transcodeMedia).toHaveBeenCalledWith(expect.objectContaining({ id: task1.id }))
|
||||
// Task 2 should not have started yet
|
||||
expect(mocks.transcodeMedia).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: task2.id }),
|
||||
)
|
||||
|
||||
// 3. Cancel task 2 while it is still waiting in the queue
|
||||
await executor.cancel(task2.id)
|
||||
|
||||
// 4. Release task 1 so the concurrency slot becomes available
|
||||
resolveFirstTranscode(undefined)
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
|
||||
// 5. Verify task 2's workflow was NEVER executed
|
||||
expect(mocks.transcodeMedia).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: task2.id }),
|
||||
)
|
||||
|
||||
// 6. Verify task 2 was marked failed / cancelled
|
||||
const dbTask2 = await prisma.workflowTask.findUnique({
|
||||
where: { id: task2.id },
|
||||
})
|
||||
expect(dbTask2?.status).toBe(WorkflowTaskStatus.failed)
|
||||
expect((dbTask2?.output as { error?: string })?.error).toContain('cancelled')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,397 +0,0 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { WorkflowTask, WorkflowTaskStatus } from '@shumai/db'
|
||||
import { Executor } from './executor'
|
||||
import * as taskActivities from './activities/task'
|
||||
import {
|
||||
getConcurrencyLimit,
|
||||
registerLocalTaskAbortController,
|
||||
runInLocalTaskContext,
|
||||
triggerLocalCancel,
|
||||
unregisterLocalTaskAbortController,
|
||||
} from './workflow-utils'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import './local-task-storage'
|
||||
|
||||
type WorkflowFn = (task: WorkflowTask) => Promise<void>
|
||||
|
||||
const workflowRegistry = new Map<string, WorkflowFn>()
|
||||
const activityRegistry: Record<string, unknown> = { ...taskActivities }
|
||||
|
||||
export function registerWorkflow(type: string, fn: WorkflowFn) {
|
||||
workflowRegistry.set(type, fn)
|
||||
}
|
||||
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
const globalObj = globalThis as typeof globalThis & {
|
||||
__localActivities?: Record<string, unknown>
|
||||
__localLogger?: unknown
|
||||
}
|
||||
/* eslint-enable @typescript-eslint/naming-convention */
|
||||
|
||||
export function registerActivities(acts: Record<string, unknown>) {
|
||||
Object.assign(activityRegistry, acts)
|
||||
globalObj.__localActivities = activityRegistry
|
||||
}
|
||||
|
||||
// Inject local dependencies into global scope for workflow-utils
|
||||
globalObj.__localActivities = activityRegistry
|
||||
globalObj.__localLogger = logger
|
||||
|
||||
// ConcurrencyLimiter manages concurrent execution of promises with a FIFO queue.
|
||||
export class ConcurrencyLimiter {
|
||||
private activeCount = 0
|
||||
private queue: (() => void)[] = []
|
||||
|
||||
constructor(private readonly limit: number) {}
|
||||
|
||||
getLimit(): number {
|
||||
return this.limit
|
||||
}
|
||||
|
||||
async run<T>(fn: () => Promise<T>): Promise<T> {
|
||||
if (this.activeCount >= this.limit) {
|
||||
await new Promise<void>((resolve) => this.queue.push(resolve))
|
||||
} else {
|
||||
this.activeCount++
|
||||
}
|
||||
|
||||
try {
|
||||
return await fn()
|
||||
} finally {
|
||||
const next = this.queue.shift()
|
||||
if (next) {
|
||||
next()
|
||||
} else {
|
||||
this.activeCount--
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Exposed for testing concurrency status
|
||||
getActiveCount(): number {
|
||||
return this.activeCount
|
||||
}
|
||||
|
||||
getQueueLength(): number {
|
||||
return this.queue.length
|
||||
}
|
||||
}
|
||||
|
||||
export class LocalExecutor implements Executor {
|
||||
private interval: Timer | null = null
|
||||
private processingTasks = new Set<string>()
|
||||
private heartbeatIntervals = new Map<string, Timer>()
|
||||
|
||||
private transcodeLimiter: ConcurrencyLimiter
|
||||
private generalLimiter: ConcurrencyLimiter
|
||||
|
||||
constructor() {
|
||||
const transcodeLimit = getConcurrencyLimit(process.env.CONCURRENCY_TRANSCODE, 1)
|
||||
const agentLimit = getConcurrencyLimit(process.env.CONCURRENCY_AGENT, 5)
|
||||
|
||||
this.transcodeLimiter = new ConcurrencyLimiter(transcodeLimit)
|
||||
this.generalLimiter = new ConcurrencyLimiter(agentLimit)
|
||||
}
|
||||
|
||||
getTranscodeConcurrencyLimit(): number {
|
||||
return this.transcodeLimiter.getLimit()
|
||||
}
|
||||
|
||||
getAgentConcurrencyLimit(): number {
|
||||
return this.generalLimiter.getLimit()
|
||||
}
|
||||
|
||||
async submit(task: WorkflowTask): Promise<string> {
|
||||
if (task.status !== WorkflowTaskStatus.pending) {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: task.id },
|
||||
data: { status: WorkflowTaskStatus.pending },
|
||||
})
|
||||
}
|
||||
|
||||
// In tests, we trigger processing immediately using the appropriate limiter
|
||||
if (process.env.NODE_ENV === 'test') {
|
||||
setTimeout(async () => {
|
||||
if (this.processingTasks.has(task.id)) return
|
||||
this.processingTasks.add(task.id)
|
||||
|
||||
// 1. Immediately mark task as processing and set initial heartbeat in DB
|
||||
// atomically, only if the task is still pending.
|
||||
try {
|
||||
const affected = await prisma.workflowTask.updateMany({
|
||||
where: {
|
||||
id: task.id,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
data: {
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: new Date(),
|
||||
},
|
||||
})
|
||||
if (affected.count === 0) {
|
||||
this.processingTasks.delete(task.id)
|
||||
return
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(
|
||||
`[LocalExecutor] Failed to mark task ${task.id} as processing in submit:`,
|
||||
err,
|
||||
)
|
||||
this.processingTasks.delete(task.id)
|
||||
return
|
||||
}
|
||||
|
||||
// 2. Start heartbeat updater immediately
|
||||
const heartbeatInterval = setInterval(async () => {
|
||||
try {
|
||||
const { count } = await prisma.workflowTask.updateMany({
|
||||
where: { id: task.id },
|
||||
data: { heartbeat: new Date() },
|
||||
})
|
||||
if (count === 0) {
|
||||
clearInterval(heartbeatInterval)
|
||||
this.heartbeatIntervals.delete(task.id)
|
||||
logger.debug(
|
||||
{ taskId: task.id },
|
||||
'[LocalExecutor] Stopped heartbeat for deleted or cancelled task',
|
||||
)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[LocalExecutor] Failed to update heartbeat for task ${task.id}:`, err)
|
||||
}
|
||||
}, 5000)
|
||||
this.heartbeatIntervals.set(task.id, heartbeatInterval)
|
||||
|
||||
const abortController = new AbortController()
|
||||
registerLocalTaskAbortController(task.id, abortController)
|
||||
|
||||
const limiter =
|
||||
task.type && task.type.startsWith('transcode')
|
||||
? this.transcodeLimiter
|
||||
: this.generalLimiter
|
||||
|
||||
limiter
|
||||
.run(async () => {
|
||||
try {
|
||||
if (abortController.signal.aborted) {
|
||||
logger.info(
|
||||
{ taskId: task.id },
|
||||
'[LocalExecutor] Queued task was aborted before execution',
|
||||
)
|
||||
try {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: task.id, status: WorkflowTaskStatus.processing },
|
||||
data: {
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: { error: 'Workflow task was cancelled before execution' },
|
||||
},
|
||||
})
|
||||
} catch {
|
||||
// Ignore if task was already deleted
|
||||
}
|
||||
return
|
||||
}
|
||||
await runInLocalTaskContext({ taskId: task.id, abortController }, async () => {
|
||||
await this.processTaskWrapper(task)
|
||||
})
|
||||
} finally {
|
||||
// 3. Clean up the heartbeat updater and processing set when the task finishes
|
||||
clearInterval(heartbeatInterval)
|
||||
this.heartbeatIntervals.delete(task.id)
|
||||
unregisterLocalTaskAbortController(task.id)
|
||||
this.processingTasks.delete(task.id)
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(`[LocalExecutor] Failed to process task ${task.id}:`, err)
|
||||
})
|
||||
}, 0)
|
||||
}
|
||||
return task.id
|
||||
}
|
||||
|
||||
async cancel(taskId: string): Promise<void> {
|
||||
const timer = this.heartbeatIntervals.get(taskId)
|
||||
if (timer) {
|
||||
clearInterval(timer)
|
||||
this.heartbeatIntervals.delete(taskId)
|
||||
}
|
||||
triggerLocalCancel(taskId)
|
||||
logger.info({ taskId }, '[LocalExecutor] Cancelled workflow task')
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (this.interval) return
|
||||
this.interval = setInterval(() => this.tick(), 5000)
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.interval) {
|
||||
clearInterval(this.interval)
|
||||
this.interval = null
|
||||
}
|
||||
for (const timer of this.heartbeatIntervals.values()) {
|
||||
clearInterval(timer)
|
||||
}
|
||||
this.heartbeatIntervals.clear()
|
||||
for (const taskId of this.processingTasks) {
|
||||
triggerLocalCancel(taskId)
|
||||
}
|
||||
}
|
||||
|
||||
// Returns the array of task promises so tests can await them to avoid early rollback.
|
||||
async tick(): Promise<Promise<void>[]> {
|
||||
const promises: Promise<void>[] = []
|
||||
try {
|
||||
const staleTime = new Date(Date.now() - 30 * 1000)
|
||||
|
||||
// Find tasks that are:
|
||||
// 1. Pending (new tasks)
|
||||
// 2. Processing but stale (worker crashed, heartbeat > 30s ago)
|
||||
const tasks = await prisma.workflowTask.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ status: WorkflowTaskStatus.pending },
|
||||
{
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: { lt: staleTime },
|
||||
},
|
||||
],
|
||||
},
|
||||
orderBy: { id: 'asc' },
|
||||
take: 50,
|
||||
})
|
||||
|
||||
for (const task of tasks) {
|
||||
if (this.processingTasks.has(task.id)) continue
|
||||
this.processingTasks.add(task.id)
|
||||
|
||||
// 1. Immediately mark task as processing and set initial heartbeat in DB
|
||||
// atomically, ensuring no two workers pick up the same task.
|
||||
try {
|
||||
const affected = await prisma.workflowTask.updateMany({
|
||||
where: {
|
||||
id: task.id,
|
||||
OR: [
|
||||
{ status: WorkflowTaskStatus.pending },
|
||||
{
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: { lt: staleTime },
|
||||
},
|
||||
],
|
||||
},
|
||||
data: {
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: new Date(),
|
||||
},
|
||||
})
|
||||
if (affected.count === 0) {
|
||||
this.processingTasks.delete(task.id)
|
||||
continue
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(
|
||||
`[LocalExecutor] Failed to mark task ${task.id} as processing in tick:`,
|
||||
err,
|
||||
)
|
||||
this.processingTasks.delete(task.id)
|
||||
continue
|
||||
}
|
||||
|
||||
// 2. Start heartbeat updater immediately to prevent other workers from considering it stale
|
||||
// even while the task is queued waiting for limiter capacity.
|
||||
const heartbeatInterval = setInterval(async () => {
|
||||
try {
|
||||
const { count } = await prisma.workflowTask.updateMany({
|
||||
where: { id: task.id },
|
||||
data: { heartbeat: new Date() },
|
||||
})
|
||||
if (count === 0) {
|
||||
clearInterval(heartbeatInterval)
|
||||
this.heartbeatIntervals.delete(task.id)
|
||||
logger.debug(
|
||||
{ taskId: task.id },
|
||||
'[LocalExecutor] Stopped heartbeat for deleted or cancelled task',
|
||||
)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[LocalExecutor] Failed to update heartbeat for task ${task.id}:`, err)
|
||||
}
|
||||
}, 5000)
|
||||
this.heartbeatIntervals.set(task.id, heartbeatInterval)
|
||||
|
||||
const abortController = new AbortController()
|
||||
registerLocalTaskAbortController(task.id, abortController)
|
||||
|
||||
const limiter =
|
||||
task.type && task.type.startsWith('transcode')
|
||||
? this.transcodeLimiter
|
||||
: this.generalLimiter
|
||||
|
||||
const promise = limiter
|
||||
.run(async () => {
|
||||
try {
|
||||
if (abortController.signal.aborted) {
|
||||
logger.info(
|
||||
{ taskId: task.id },
|
||||
'[LocalExecutor] Queued task was aborted before execution',
|
||||
)
|
||||
try {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: task.id, status: WorkflowTaskStatus.processing },
|
||||
data: {
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: { error: 'Workflow task was cancelled before execution' },
|
||||
},
|
||||
})
|
||||
} catch {
|
||||
// Ignore if task was already deleted
|
||||
}
|
||||
return
|
||||
}
|
||||
await runInLocalTaskContext({ taskId: task.id, abortController }, async () => {
|
||||
await this.processTaskWrapper(task)
|
||||
})
|
||||
} finally {
|
||||
// 3. Clean up the heartbeat updater and processing set when the task finishes
|
||||
clearInterval(heartbeatInterval)
|
||||
this.heartbeatIntervals.delete(task.id)
|
||||
unregisterLocalTaskAbortController(task.id)
|
||||
this.processingTasks.delete(task.id)
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(`[LocalExecutor] Failed to process task ${task.id}:`, err)
|
||||
})
|
||||
promises.push(promise)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch tasks:', err)
|
||||
}
|
||||
return promises
|
||||
}
|
||||
|
||||
private async processTaskWrapper(task: WorkflowTask) {
|
||||
try {
|
||||
const fn = task.type ? workflowRegistry.get(task.type) : undefined
|
||||
if (fn) {
|
||||
await fn(task)
|
||||
} else {
|
||||
console.warn(`Unknown or unregistered task type: ${task.type}`)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Error in workflow ${task.type} for task ${task.id}:`, err)
|
||||
try {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: task.id },
|
||||
data: {
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
},
|
||||
})
|
||||
} catch (updateErr) {
|
||||
console.error(`Failed to set task ${task.id} to failed:`, updateErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
import { AsyncLocalStorage } from 'node:async_hooks'
|
||||
import type { LocalTaskContext } from './workflow-utils'
|
||||
|
||||
// Store AsyncLocalStorage on globalThis to share with workflow-utils without
|
||||
// requiring workflow-utils to import node:async_hooks (which would break Temporal's Webpack workflow bundler).
|
||||
// Store AsyncLocalStorage on globalThis to share with workflow-utils.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const globalObj = globalThis as any
|
||||
if (!globalObj.__localTaskStorage) {
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { DBOS } from '@dbos-inc/dbos-sdk'
|
||||
import { getDbosDatabaseUrl } from './dbos-executor'
|
||||
|
||||
export async function migrateDbos(url?: string): Promise<void> {
|
||||
const dbUrl = getDbosDatabaseUrl(url)
|
||||
await DBOS.migrate(dbUrl)
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
await migrateDbos()
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
import { Connection, Client } from '@temporalio/client'
|
||||
import { prisma, WorkflowTask, WorkflowTaskType } from '@shumai/db'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { Executor } from './executor'
|
||||
import { TaskQueueAgent, TaskQueueTranscode } from './workflow-utils'
|
||||
|
||||
export class TemporalExecutor implements Executor {
|
||||
private client: Client | null = null
|
||||
private connection: Connection | null = null
|
||||
|
||||
constructor(private address: string = 'localhost:7233') {}
|
||||
|
||||
async submit(task: WorkflowTask): Promise<string> {
|
||||
const client = await this.getClient()
|
||||
const workflowId = `${task.type}-${task.id}`
|
||||
|
||||
let workflowName: string
|
||||
let taskQueue: string
|
||||
|
||||
switch (task.type) {
|
||||
case WorkflowTaskType.ai_embedding:
|
||||
workflowName = 'agentEmbeddingWorkflow'
|
||||
taskQueue = TaskQueueAgent
|
||||
break
|
||||
case WorkflowTaskType.ai_metadata_autofill:
|
||||
workflowName = 'agentAutofillWorkflow'
|
||||
taskQueue = TaskQueueAgent
|
||||
break
|
||||
case WorkflowTaskType.chat:
|
||||
workflowName = 'agentChatWorkflow'
|
||||
taskQueue = TaskQueueAgent
|
||||
break
|
||||
case WorkflowTaskType.transcode:
|
||||
workflowName = 'transcodeWorkflow'
|
||||
taskQueue = TaskQueueTranscode
|
||||
break
|
||||
case WorkflowTaskType.transcode_video:
|
||||
workflowName = 'transcodeVideoWorkflow'
|
||||
taskQueue = TaskQueueTranscode
|
||||
break
|
||||
case WorkflowTaskType.transcode_image:
|
||||
workflowName = 'transcodeImageWorkflow'
|
||||
taskQueue = TaskQueueTranscode
|
||||
break
|
||||
case WorkflowTaskType.transcode_pdf:
|
||||
workflowName = 'transcodePdfWorkflow'
|
||||
taskQueue = TaskQueueTranscode
|
||||
break
|
||||
case WorkflowTaskType.transcode_pdf_pages:
|
||||
workflowName = 'renderPdfPagesWorkflow'
|
||||
taskQueue = TaskQueueTranscode
|
||||
break
|
||||
case WorkflowTaskType.transcode_screenshot:
|
||||
workflowName = 'takeVideoScreenshotsWorkflow'
|
||||
taskQueue = TaskQueueTranscode
|
||||
break
|
||||
case WorkflowTaskType.transcode_image_annotation:
|
||||
workflowName = 'overlayImageAnnotationWorkflow'
|
||||
taskQueue = TaskQueueTranscode
|
||||
break
|
||||
case WorkflowTaskType.transcode_watermark:
|
||||
workflowName = 'transcodeWatermarkWorkflow'
|
||||
taskQueue = TaskQueueTranscode
|
||||
break
|
||||
case WorkflowTaskType.transcode_3d:
|
||||
workflowName = 'transcode3dWorkflow'
|
||||
taskQueue = TaskQueueTranscode
|
||||
break
|
||||
default:
|
||||
throw new Error(`Unknown task type: ${task.type}`)
|
||||
}
|
||||
|
||||
const handle = await client.workflow.start(workflowName, {
|
||||
taskQueue,
|
||||
workflowId,
|
||||
args: [task],
|
||||
})
|
||||
|
||||
return handle.workflowId
|
||||
}
|
||||
|
||||
async cancel(taskId: string): Promise<void> {
|
||||
const client = await this.getClient()
|
||||
const task = await prisma.workflowTask.findUnique({
|
||||
where: { id: taskId },
|
||||
select: { type: true },
|
||||
})
|
||||
const workflowId = task?.type ? `${task.type}-${taskId}` : `chat-${taskId}`
|
||||
try {
|
||||
const handle = client.workflow.getHandle(workflowId)
|
||||
await handle.cancel()
|
||||
logger.info({ taskId, workflowId }, '[TemporalExecutor] Cancelled workflow task')
|
||||
} catch (err) {
|
||||
logger.warn({ taskId, workflowId, err }, '[TemporalExecutor] Failed to cancel workflow task')
|
||||
}
|
||||
}
|
||||
|
||||
start(): void {
|
||||
// Client doesn't need explicit start
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.connection) {
|
||||
this.connection.close()
|
||||
this.connection = null
|
||||
this.client = null
|
||||
}
|
||||
}
|
||||
|
||||
private async getClient(): Promise<Client> {
|
||||
if (this.client) return this.client
|
||||
this.connection = await Connection.connect({ address: this.address })
|
||||
this.client = new Client({ connection: this.connection })
|
||||
return this.client
|
||||
}
|
||||
}
|
||||
@@ -1,96 +1,140 @@
|
||||
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
|
||||
import * as wf from '@temporalio/workflow'
|
||||
import { getActivities, executeActivity } from './workflow-utils'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { DBOS, Error as DBOSError } from '@dbos-inc/dbos-sdk'
|
||||
import {
|
||||
defineStep,
|
||||
WorkflowFailure,
|
||||
ApplicationFailure,
|
||||
isNonRetryableError,
|
||||
isDbosWorkflowCancelledError,
|
||||
sleep,
|
||||
getLocalTaskAbortSignal,
|
||||
registerLocalTaskAbortController,
|
||||
unregisterLocalTaskAbortController,
|
||||
} from './workflow-utils'
|
||||
|
||||
const mockWorkflowInfo = vi.fn().mockImplementation(() => {
|
||||
throw new Error('Not in workflow context')
|
||||
})
|
||||
const mockProxyActivities = vi.fn()
|
||||
|
||||
vi.mock('@temporalio/workflow', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@temporalio/workflow')>()
|
||||
return {
|
||||
...actual,
|
||||
workflowInfo: () => mockWorkflowInfo(),
|
||||
proxyActivities: (...args: unknown[]) => mockProxyActivities(...args),
|
||||
log: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
describe('workflow-utils executeActivity', () => {
|
||||
beforeAll(() => {
|
||||
// Inject mock activities for local execution tests
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(globalThis as any).__localActivities = {
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
describe('workflow-utils defineStep and DBOS steps', () => {
|
||||
it('should preserve function name by default or use custom name', () => {
|
||||
async function sampleActivity(arg: string) {
|
||||
return `result-${arg}`
|
||||
}
|
||||
const step1 = defineStep(sampleActivity)
|
||||
expect(step1.name).toBe('sampleActivity')
|
||||
|
||||
const step2 = defineStep(async () => 'ok', { name: 'customName' })
|
||||
expect(step2.name).toBe('customName')
|
||||
})
|
||||
|
||||
it('should attach _activityName to proxy functions from getActivities', () => {
|
||||
const { updateTaskStatusActivity } = getActivities()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((updateTaskStatusActivity as any)._activityName).toBe('updateTaskStatusActivity')
|
||||
})
|
||||
|
||||
it('should execute the function and pass arguments in local mode', async () => {
|
||||
it('should execute the function directly when outside DBOS workflow context', async () => {
|
||||
const mockFn = vi.fn().mockResolvedValue('success-result')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(mockFn as any)._activityName = 'mockActivity'
|
||||
const step = defineStep(mockFn, { name: 'mockStep' })
|
||||
|
||||
const result = await executeActivity(
|
||||
'test-queue',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
mockFn as any,
|
||||
{ some: 'args' },
|
||||
)
|
||||
const result = await step({ some: 'args' })
|
||||
|
||||
expect(mockFn).toHaveBeenCalledWith({ some: 'args' })
|
||||
expect(result).toBe('success-result')
|
||||
})
|
||||
|
||||
it('should throw error if function does not have _activityName', async () => {
|
||||
const normalFn = async () => {}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await expect(executeActivity('queue', normalFn as any)).rejects.toThrow(
|
||||
'executeActivity must be called with an activity function obtained from getActivities()',
|
||||
it('should execute via DBOS.runStep when within workflow context', async () => {
|
||||
const mockFn = vi.fn().mockResolvedValue('step-success')
|
||||
const step = defineStep(mockFn, { name: 'myStepActivity' })
|
||||
|
||||
const isWithinWorkflowSpy = vi.spyOn(DBOS, 'isWithinWorkflow').mockReturnValue(true)
|
||||
const runStepSpy = vi
|
||||
.spyOn(DBOS, 'runStep')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
.mockImplementation(async (fn: () => unknown) => fn() as any)
|
||||
|
||||
const result = await step('step-arg')
|
||||
|
||||
expect(runStepSpy).toHaveBeenCalledWith(
|
||||
expect.any(Function),
|
||||
expect.objectContaining({
|
||||
name: 'myStepActivity',
|
||||
retriesAllowed: true,
|
||||
shouldRetry: expect.any(Function),
|
||||
}),
|
||||
)
|
||||
expect(result).toBe('step-success')
|
||||
|
||||
isWithinWorkflowSpy.mockRestore()
|
||||
runStepSpy.mockRestore()
|
||||
})
|
||||
|
||||
describe('Temporal mode', () => {
|
||||
beforeAll(() => {
|
||||
// Mock workflowInfo to simulate running in Temporal by returning a fake object
|
||||
mockWorkflowInfo.mockReturnValue({} as unknown as wf.WorkflowInfo)
|
||||
it('should execute cleanup fallback if cancelled with DBOSWorkflowCancelledError and runOnCancel is true', async () => {
|
||||
const mockFn = vi.fn().mockResolvedValue('cleanup-done')
|
||||
const step = defineStep(mockFn, { name: 'cleanupStep', runOnCancel: true })
|
||||
|
||||
// SDK's real DBOSWorkflowCancelledError does not set err.name (err.name is 'Error')
|
||||
const realCancelErr = new DBOSError.DBOSWorkflowCancelledError('test-workflow-id')
|
||||
expect(realCancelErr.name).toBe('Error')
|
||||
|
||||
const isWithinWorkflowSpy = vi.spyOn(DBOS, 'isWithinWorkflow').mockReturnValue(true)
|
||||
const runStepSpy = vi.spyOn(DBOS, 'runStep').mockRejectedValue(realCancelErr)
|
||||
|
||||
const result = await step('arg')
|
||||
|
||||
expect(result).toBe('cleanup-done')
|
||||
expect(mockFn).toHaveBeenCalledWith('arg')
|
||||
|
||||
isWithinWorkflowSpy.mockRestore()
|
||||
runStepSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('should correctly identify DBOS workflow cancellation errors', () => {
|
||||
const realCancelErr = new DBOSError.DBOSWorkflowCancelledError('wf-1')
|
||||
expect(isDbosWorkflowCancelledError(realCancelErr)).toBe(true)
|
||||
|
||||
const duckTypedErr = { name: 'DBOSWorkflowCancelledError' }
|
||||
expect(isDbosWorkflowCancelledError(duckTypedErr)).toBe(true)
|
||||
|
||||
const codeErr = { dbosErrorCode: 24 }
|
||||
expect(isDbosWorkflowCancelledError(codeErr)).toBe(true)
|
||||
|
||||
expect(isDbosWorkflowCancelledError(new Error('other error'))).toBe(false)
|
||||
expect(isDbosWorkflowCancelledError(null)).toBe(false)
|
||||
expect(isDbosWorkflowCancelledError(undefined)).toBe(false)
|
||||
})
|
||||
|
||||
describe('WorkflowFailure / ApplicationFailure', () => {
|
||||
it('should correctly configure nonRetryable errors', () => {
|
||||
const err = WorkflowFailure.create({ message: 'fatal error', nonRetryable: true })
|
||||
expect(err.message).toBe('fatal error')
|
||||
expect(err.nonRetryable).toBe(true)
|
||||
expect(isNonRetryableError(err)).toBe(true)
|
||||
|
||||
const appErr = ApplicationFailure.create({ message: 'fatal app error', nonRetryable: true })
|
||||
expect(appErr.nonRetryable).toBe(true)
|
||||
expect(isNonRetryableError(appErr)).toBe(true)
|
||||
|
||||
const retryableErr = ApplicationFailure.create({ message: 'transient', nonRetryable: false })
|
||||
expect(retryableErr.nonRetryable).toBe(false)
|
||||
expect(isNonRetryableError(retryableErr)).toBe(false)
|
||||
|
||||
expect(isNonRetryableError(new Error('generic'))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('sleep and abort signals', () => {
|
||||
it('should call DBOS.sleepms when within workflow', async () => {
|
||||
const isWithinWorkflowSpy = vi.spyOn(DBOS, 'isWithinWorkflow').mockReturnValue(true)
|
||||
const sleepmsSpy = vi.spyOn(DBOS, 'sleepms').mockResolvedValue()
|
||||
|
||||
await sleep(100)
|
||||
expect(sleepmsSpy).toHaveBeenCalledWith(100)
|
||||
|
||||
isWithinWorkflowSpy.mockRestore()
|
||||
sleepmsSpy.mockRestore()
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
mockWorkflowInfo.mockImplementation(() => {
|
||||
throw new Error('Not in workflow context')
|
||||
})
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
it('should resolve abort signals registered for a taskId', () => {
|
||||
const controller = new AbortController()
|
||||
registerLocalTaskAbortController('task-123', controller)
|
||||
|
||||
it('should configure proxyActivities with retry options', async () => {
|
||||
mockProxyActivities.mockReturnValue({
|
||||
mockActivity: vi.fn().mockResolvedValue('temporal-success'),
|
||||
})
|
||||
const signal = getLocalTaskAbortSignal('task-123')
|
||||
expect(signal).toBe(controller.signal)
|
||||
|
||||
const { mockActivity } = getActivities()
|
||||
const result = await executeActivity('test-queue', mockActivity, 'arg1')
|
||||
|
||||
expect(mockProxyActivities).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
retry: {
|
||||
maximumAttempts: 5,
|
||||
initialInterval: '10s',
|
||||
},
|
||||
}),
|
||||
)
|
||||
expect(result).toBe('temporal-success')
|
||||
unregisterLocalTaskAbortController('task-123')
|
||||
expect(getLocalTaskAbortSignal('task-123')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
// Use type-only imports for activities to avoid bundling them in Temporal workflows
|
||||
import * as wf from '@temporalio/workflow'
|
||||
import { DBOS, Error as DBOSError } from '@dbos-inc/dbos-sdk'
|
||||
|
||||
/**
|
||||
* Task queue constants.
|
||||
@@ -7,188 +6,125 @@ import * as wf from '@temporalio/workflow'
|
||||
export const TaskQueueAgent = 'agent_queue'
|
||||
export const TaskQueueTranscode = 'transcode_queue'
|
||||
|
||||
/**
|
||||
* Detects if the current execution is within a Temporal Workflow isolate.
|
||||
*/
|
||||
export function isTemporal(): boolean {
|
||||
try {
|
||||
// In Temporal TS SDK, workflowInfo() throws if called outside of a workflow context.
|
||||
wf.workflowInfo()
|
||||
return true
|
||||
} catch {
|
||||
export class WorkflowFailure extends Error {
|
||||
readonly nonRetryable: boolean
|
||||
|
||||
private constructor(message: string, nonRetryable: boolean, cause?: unknown) {
|
||||
super(message, { cause })
|
||||
this.name = 'WorkflowFailure'
|
||||
this.nonRetryable = nonRetryable
|
||||
}
|
||||
|
||||
static create(opts: {
|
||||
message: string
|
||||
nonRetryable?: boolean
|
||||
cause?: unknown
|
||||
}): WorkflowFailure {
|
||||
return new WorkflowFailure(opts.message, opts.nonRetryable ?? false, opts.cause)
|
||||
}
|
||||
}
|
||||
|
||||
export const ApplicationFailure = WorkflowFailure
|
||||
|
||||
export function isNonRetryableError(err: unknown): boolean {
|
||||
if (err instanceof WorkflowFailure) {
|
||||
return err.nonRetryable
|
||||
}
|
||||
if (err && typeof err === 'object' && 'nonRetryable' in err) {
|
||||
return (err as { nonRetryable?: unknown }).nonRetryable === true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export function isDbosWorkflowCancelledError(err: unknown): boolean {
|
||||
if (!err || typeof err !== 'object') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
interface LocalLogger {
|
||||
debug(obj: Record<string, unknown>, msg: string): void
|
||||
info(obj: Record<string, unknown>, msg: string): void
|
||||
error(obj: Record<string, unknown>, msg: string): void
|
||||
warn(obj: Record<string, unknown>, msg: string): void
|
||||
}
|
||||
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
const globalObj = globalThis as typeof globalThis & {
|
||||
__localActivities?: Record<string, unknown>
|
||||
__localLogger?: LocalLogger
|
||||
}
|
||||
/* eslint-enable @typescript-eslint/naming-convention */
|
||||
|
||||
/**
|
||||
* A proxy that mimics proxyActivities for local execution.
|
||||
*/
|
||||
function localActivitiesProxy(): Record<string, unknown> {
|
||||
const acts = globalObj.__localActivities
|
||||
if (!acts) {
|
||||
throw new Error('Local activities not injected into globalThis.__localActivities')
|
||||
if (err instanceof DBOSError.DBOSWorkflowCancelledError) {
|
||||
return true
|
||||
}
|
||||
return acts
|
||||
const errorObj = err as {
|
||||
name?: unknown
|
||||
constructor?: { name?: unknown }
|
||||
dbosErrorCode?: unknown
|
||||
}
|
||||
return (
|
||||
errorObj.name === 'DBOSWorkflowCancelledError' ||
|
||||
errorObj.constructor?.name === 'DBOSWorkflowCancelledError' ||
|
||||
errorObj.dbosErrorCode === 24
|
||||
)
|
||||
}
|
||||
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
|
||||
/**
|
||||
* Environment-aware sleep function.
|
||||
* Environment-aware sleep function. Uses DBOS.sleepms in workflow context.
|
||||
*/
|
||||
export async function sleep(ms: number): Promise<void> {
|
||||
if (isTemporal()) {
|
||||
await wf.sleep(ms)
|
||||
if (DBOS.isWithinWorkflow()) {
|
||||
await DBOS.sleepms(ms)
|
||||
} else {
|
||||
await new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Environment-aware activity proxy.
|
||||
*/
|
||||
// getActivities must default to `any` so that workflows can dynamically
|
||||
// destructure and call any activity when they do not supply a precise type parameter.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export function getActivities<T = any>(): T {
|
||||
// baseProxy is dynamically proxying all activities, so we must type it as any.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let baseProxy: any
|
||||
if (isTemporal()) {
|
||||
// Temporal's proxyActivities requires a type parameter, so we use any for generic activities.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
baseProxy = wf.proxyActivities<any>({
|
||||
startToCloseTimeout: '120 minutes',
|
||||
retry: {
|
||||
maximumAttempts: 5,
|
||||
initialInterval: '10s',
|
||||
},
|
||||
})
|
||||
} else {
|
||||
baseProxy = localActivitiesProxy()
|
||||
}
|
||||
export interface StepOptions {
|
||||
name?: string
|
||||
runOnCancel?: boolean
|
||||
}
|
||||
|
||||
// Wrap the base proxy to attach the activity name to the returned functions
|
||||
// We use any here because we are dynamically intercepting properties on the proxy
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return new Proxy(baseProxy as any, {
|
||||
get(target, prop) {
|
||||
if (typeof prop === 'string') {
|
||||
const original = target[prop]
|
||||
if (typeof original === 'function') {
|
||||
// Return a wrapper function that has the _activityName property
|
||||
const wrapped = (...args: unknown[]) => original(...args)
|
||||
// We attach a hidden property to track the activity name for executeActivity
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(wrapped as any)._activityName = prop
|
||||
return wrapped
|
||||
/**
|
||||
* Wraps an activity function so that when invoked within a DBOS workflow, it executes
|
||||
* as a durable checkpointed step with retries, timeout, and cancellation handling.
|
||||
* When called outside a workflow (e.g. in unit tests), it invokes the underlying function directly.
|
||||
*/
|
||||
export function defineStep<TArgs extends unknown[], TRet>(
|
||||
fn: (...args: TArgs) => Promise<TRet>,
|
||||
options?: StepOptions,
|
||||
): (...args: TArgs) => Promise<TRet> {
|
||||
const stepName = options?.name || fn.name || 'anonymousStep'
|
||||
const runOnCancel = options?.runOnCancel ?? false
|
||||
|
||||
const wrapped = async (...args: TArgs): Promise<TRet> => {
|
||||
logger.debug({ activityName: stepName }, `Executing step ${stepName}`)
|
||||
|
||||
try {
|
||||
let result: TRet
|
||||
if (DBOS.isWithinWorkflow()) {
|
||||
try {
|
||||
result = await DBOS.runStep(() => fn(...args), {
|
||||
name: stepName,
|
||||
retriesAllowed: true,
|
||||
maxAttempts: 5,
|
||||
intervalSeconds: process.env.NODE_ENV === 'test' ? 1 : 10,
|
||||
backoffRate: 2,
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS StepOptions property name
|
||||
timeoutMS: 120 * 60 * 1000,
|
||||
shouldRetry: (err) => !isNonRetryableError(err),
|
||||
})
|
||||
} catch (stepErr) {
|
||||
if (runOnCancel && isDbosWorkflowCancelledError(stepErr)) {
|
||||
result = await fn(...args)
|
||||
} else {
|
||||
throw stepErr
|
||||
}
|
||||
}
|
||||
return original
|
||||
} else {
|
||||
result = await fn(...args)
|
||||
}
|
||||
return Reflect.get(target, prop)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Environment-aware logger for workflows and activities.
|
||||
*/
|
||||
function getLogger() {
|
||||
if (isTemporal()) {
|
||||
return {
|
||||
debug: (obj: Record<string, unknown>, msg: string) => wf.log.debug(msg, obj),
|
||||
info: (obj: Record<string, unknown>, msg: string) => wf.log.info(msg, obj),
|
||||
error: (obj: Record<string, unknown>, msg: string) => wf.log.error(msg, obj),
|
||||
warn: (obj: Record<string, unknown>, msg: string) => wf.log.warn(msg, obj),
|
||||
logger.debug({ activityName: stepName }, `Step ${stepName} completed successfully`)
|
||||
return result
|
||||
} catch (err) {
|
||||
logger.error(
|
||||
{ activityName: stepName, err },
|
||||
`Step ${stepName} failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
return globalObj.__localLogger || console
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute an activity on a specific task queue.
|
||||
* @param queue The task queue to run the activity on
|
||||
* @param activityFunc The proxy function obtained from `getActivities()`
|
||||
* @param args The arguments to pass to the activity
|
||||
*/
|
||||
// Overload signature for untyped or generic activity callbacks.
|
||||
export async function executeActivity(
|
||||
queue: string,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
activityFunc: any,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
...args: any[]
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
): Promise<any>
|
||||
export async function executeActivity<TArgs extends unknown[], TRet>(
|
||||
queue: string,
|
||||
activityFunc: (...args: TArgs) => Promise<TRet>,
|
||||
...args: TArgs
|
||||
): Promise<TRet>
|
||||
// Implementation signature for executeActivity.
|
||||
export async function executeActivity(
|
||||
queue: string,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
activityFunc: any,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
...args: any[]
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
): Promise<any> {
|
||||
// We extract the hidden _activityName property attached by getActivities()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const activityName = (activityFunc as any)._activityName
|
||||
if (!activityName) {
|
||||
throw new Error(
|
||||
'executeActivity must be called with an activity function obtained from getActivities()',
|
||||
)
|
||||
}
|
||||
|
||||
const logger = getLogger()
|
||||
logger.debug({ queue, activityName }, `Executing activity ${activityName} on queue ${queue}`)
|
||||
|
||||
try {
|
||||
// result holds the untyped return value from the dynamic activity proxy, so we type it as any.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let result: any
|
||||
if (isTemporal()) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const handle = wf.proxyActivities<any>({
|
||||
startToCloseTimeout: '120 minutes',
|
||||
taskQueue: queue,
|
||||
retry: {
|
||||
maximumAttempts: 5,
|
||||
initialInterval: '10s',
|
||||
},
|
||||
})
|
||||
result = await handle[activityName](...args)
|
||||
} else {
|
||||
// For local execution, queue is ignored and we just execute the function
|
||||
result = await activityFunc(...args)
|
||||
}
|
||||
logger.debug(
|
||||
{ queue, activityName },
|
||||
`Activity ${activityName} completed successfully on queue ${queue}`,
|
||||
)
|
||||
return result
|
||||
} catch (err) {
|
||||
logger.error(
|
||||
{ queue, activityName, err },
|
||||
`Activity ${activityName} failed on queue ${queue}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
)
|
||||
throw err
|
||||
}
|
||||
Object.defineProperty(wrapped, 'name', { value: stepName })
|
||||
return wrapped
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -253,6 +189,9 @@ export function runInLocalTaskContext<T>(context: LocalTaskContext, fn: () => T)
|
||||
}
|
||||
|
||||
export function getLocalTaskAbortSignal(taskId?: string): AbortSignal | undefined {
|
||||
if (DBOS.stepStatus?.cancelSignal) {
|
||||
return DBOS.stepStatus.cancelSignal
|
||||
}
|
||||
if (taskId) {
|
||||
const controller = localTaskAbortControllers.get(taskId)
|
||||
if (controller) {
|
||||
|
||||
@@ -1,38 +1,17 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import { workflowService } from './workflow'
|
||||
import { TaskQueueAgent, TaskQueueTranscode } from './workflow-utils'
|
||||
import { DbosExecutor } from './dbos-executor'
|
||||
|
||||
const mockCreate = vi.fn().mockResolvedValue({
|
||||
run: vi.fn().mockResolvedValue(undefined),
|
||||
})
|
||||
|
||||
const mockConnect = vi.fn().mockResolvedValue({})
|
||||
|
||||
vi.mock('@temporalio/worker', () => ({
|
||||
Worker: {
|
||||
create: (options: Record<string, unknown>) => mockCreate(options),
|
||||
},
|
||||
NativeConnection: {
|
||||
connect: (options: Record<string, unknown>) => mockConnect(options),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('WorkflowService Temporal Workers Concurrency Control', () => {
|
||||
let originalExecutor: string | undefined
|
||||
describe('WorkflowService DBOS Workers Concurrency Control', () => {
|
||||
let originalTranscode: string | undefined
|
||||
let originalAgent: string | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
originalExecutor = process.env.WORKFLOW_EXECUTOR
|
||||
originalTranscode = process.env.CONCURRENCY_TRANSCODE
|
||||
originalAgent = process.env.CONCURRENCY_AGENT
|
||||
workflowService.setExecutorType('temporal')
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
workflowService.setExecutorType(originalExecutor === 'temporal' ? 'temporal' : 'local')
|
||||
|
||||
if (originalTranscode === undefined) {
|
||||
delete process.env.CONCURRENCY_TRANSCODE
|
||||
} else {
|
||||
@@ -46,68 +25,31 @@ describe('WorkflowService Temporal Workers Concurrency Control', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('should pass default concurrency limits to specific workers', async () => {
|
||||
it('should return default concurrency limits', () => {
|
||||
delete process.env.CONCURRENCY_TRANSCODE
|
||||
delete process.env.CONCURRENCY_AGENT
|
||||
|
||||
// Test Transcode Worker
|
||||
await workflowService.startWorkers(TaskQueueTranscode)
|
||||
// Worker.create should be called twice (shared worker + specific worker)
|
||||
expect(mockCreate).toHaveBeenCalledTimes(2)
|
||||
|
||||
// The second call is for the specific worker
|
||||
const transcodeSpecificWorkerOptions = mockCreate.mock.calls[1][0]
|
||||
expect(transcodeSpecificWorkerOptions.maxConcurrentActivityTaskExecutions).toBe(1)
|
||||
|
||||
vi.clearAllMocks()
|
||||
|
||||
// Test Agent Worker
|
||||
await workflowService.startWorkers(TaskQueueAgent)
|
||||
expect(mockCreate).toHaveBeenCalledTimes(2)
|
||||
|
||||
const agentSpecificWorkerOptions = mockCreate.mock.calls[1][0]
|
||||
expect(agentSpecificWorkerOptions.maxConcurrentActivityTaskExecutions).toBe(5)
|
||||
const executor = workflowService.getExecutor()
|
||||
expect(executor).toBeInstanceOf(DbosExecutor)
|
||||
expect(executor.getTranscodeConcurrencyLimit()).toBe(1)
|
||||
expect(executor.getAgentConcurrencyLimit()).toBe(5)
|
||||
})
|
||||
|
||||
it('should pass environment variable overridden concurrency limits to specific workers', async () => {
|
||||
it('should return environment variable overridden concurrency limits', () => {
|
||||
process.env.CONCURRENCY_TRANSCODE = '3'
|
||||
process.env.CONCURRENCY_AGENT = '12'
|
||||
|
||||
// Test Transcode Worker
|
||||
await workflowService.startWorkers(TaskQueueTranscode)
|
||||
expect(mockCreate).toHaveBeenCalledTimes(2)
|
||||
|
||||
const transcodeSpecificWorkerOptions = mockCreate.mock.calls[1][0]
|
||||
expect(transcodeSpecificWorkerOptions.maxConcurrentActivityTaskExecutions).toBe(3)
|
||||
|
||||
vi.clearAllMocks()
|
||||
|
||||
// Test Agent Worker
|
||||
await workflowService.startWorkers(TaskQueueAgent)
|
||||
expect(mockCreate).toHaveBeenCalledTimes(2)
|
||||
|
||||
const agentSpecificWorkerOptions = mockCreate.mock.calls[1][0]
|
||||
expect(agentSpecificWorkerOptions.maxConcurrentActivityTaskExecutions).toBe(12)
|
||||
const executor = workflowService.getExecutor()
|
||||
expect(executor.getTranscodeConcurrencyLimit()).toBe(3)
|
||||
expect(executor.getAgentConcurrencyLimit()).toBe(12)
|
||||
})
|
||||
|
||||
it('should fallback to defaults when environment variables are invalid or <= 0 for specific workers', async () => {
|
||||
it('should fallback to defaults when environment variables are invalid or <= 0', () => {
|
||||
process.env.CONCURRENCY_TRANSCODE = 'invalid'
|
||||
process.env.CONCURRENCY_AGENT = '-5'
|
||||
|
||||
// Test Transcode Worker
|
||||
await workflowService.startWorkers(TaskQueueTranscode)
|
||||
expect(mockCreate).toHaveBeenCalledTimes(2)
|
||||
|
||||
const transcodeSpecificWorkerOptions = mockCreate.mock.calls[1][0]
|
||||
expect(transcodeSpecificWorkerOptions.maxConcurrentActivityTaskExecutions).toBe(1)
|
||||
|
||||
vi.clearAllMocks()
|
||||
|
||||
// Test Agent Worker
|
||||
await workflowService.startWorkers(TaskQueueAgent)
|
||||
expect(mockCreate).toHaveBeenCalledTimes(2)
|
||||
|
||||
const agentSpecificWorkerOptions = mockCreate.mock.calls[1][0]
|
||||
expect(agentSpecificWorkerOptions.maxConcurrentActivityTaskExecutions).toBe(5)
|
||||
const executor = workflowService.getExecutor()
|
||||
expect(executor.getTranscodeConcurrencyLimit()).toBe(1)
|
||||
expect(executor.getAgentConcurrencyLimit()).toBe(5)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -37,16 +37,14 @@ describe('WorkflowService', () => {
|
||||
beforeEach(async () => {
|
||||
initAgentWorkflows()
|
||||
initTranscodeWorkflows()
|
||||
await prisma.workflowTask.deleteMany()
|
||||
await prisma.assetComment.deleteMany()
|
||||
await prisma.asset.deleteMany()
|
||||
vi.clearAllMocks()
|
||||
workflowService.start()
|
||||
})
|
||||
await workflowService.ensureLaunched()
|
||||
}, 15000)
|
||||
|
||||
afterEach(() => {
|
||||
workflowService.close()
|
||||
})
|
||||
afterEach(async () => {
|
||||
await workflowService.shutdownWorkers()
|
||||
}, 15000)
|
||||
|
||||
it('should process ai_embedding task locally', async () => {
|
||||
const team = await prisma.team.create({
|
||||
@@ -80,7 +78,7 @@ describe('WorkflowService', () => {
|
||||
// However, let's see if it gets to 'failed' or 'completed' depending on the environment.
|
||||
|
||||
let finishedTask = null
|
||||
for (let i = 0; i < 20; i++) {
|
||||
for (let i = 0; i < 50; i++) {
|
||||
finishedTask = await prisma.workflowTask.findUnique({
|
||||
where: { id: task.id },
|
||||
})
|
||||
@@ -96,7 +94,7 @@ describe('WorkflowService', () => {
|
||||
expect(finishedTask?.status).toBeDefined()
|
||||
// Even if it fails due to missing API keys, the fact that it's no longer 'pending' means the workflow was triggered.
|
||||
expect(finishedTask?.status).not.toBe(WorkflowTaskStatus.pending)
|
||||
}, 15000)
|
||||
}, 30000)
|
||||
|
||||
it('should propagate ApplicationFailure correctly in local executor', async () => {
|
||||
// Creating an ai_embedding task without any embedding agent configured for the team
|
||||
@@ -127,7 +125,7 @@ describe('WorkflowService', () => {
|
||||
})
|
||||
|
||||
let finishedTask = null
|
||||
for (let i = 0; i < 20; i++) {
|
||||
for (let i = 0; i < 50; i++) {
|
||||
finishedTask = await prisma.workflowTask.findUnique({
|
||||
where: { id: task.id },
|
||||
})
|
||||
@@ -141,7 +139,7 @@ describe('WorkflowService', () => {
|
||||
expect((finishedTask?.output as Record<string, unknown>)?.error).toBe(
|
||||
'embedding feature is disabled or agent not found',
|
||||
)
|
||||
}, 15000)
|
||||
}, 30000)
|
||||
|
||||
it('should not double-submit the task when executeWait is called', async () => {
|
||||
const team = await prisma.team.create({
|
||||
@@ -190,4 +188,144 @@ describe('WorkflowService', () => {
|
||||
|
||||
submitSpy.mockRestore()
|
||||
})
|
||||
|
||||
describe('Stale Task Recovery', () => {
|
||||
it('should resume stale pending workflow task in DBOS and increment recoveryAttempts', async () => {
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'stale-asset-1',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: new Date(Date.now() - 100_000), // 100s ago
|
||||
},
|
||||
})
|
||||
|
||||
const mockClient = {
|
||||
retrieveWorkflow: vi.fn().mockReturnValue({
|
||||
getStatus: vi.fn().mockResolvedValue({ status: 'PENDING' }),
|
||||
}),
|
||||
resumeWorkflow: vi.fn().mockResolvedValue(undefined),
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.spyOn(workflowService.getExecutor(), 'getClient').mockResolvedValue(mockClient as any)
|
||||
|
||||
const recoveredCount = await workflowService.recoverStaleTasks({
|
||||
staleThresholdMs: 90_000,
|
||||
maxRecoveryAttempts: 3,
|
||||
})
|
||||
|
||||
expect(recoveredCount).toBe(1)
|
||||
expect(mockClient.resumeWorkflow).toHaveBeenCalledWith(
|
||||
task.id,
|
||||
expect.objectContaining({ queueName: expect.any(String) }),
|
||||
)
|
||||
|
||||
const updatedTask = await prisma.workflowTask.findUnique({
|
||||
where: { id: task.id },
|
||||
})
|
||||
const output = updatedTask?.output as { recoveryAttempts?: number } | null
|
||||
expect(output?.recoveryAttempts).toBe(1)
|
||||
expect(updatedTask?.heartbeat?.getTime()).toBeGreaterThan(Date.now() - 5000)
|
||||
})
|
||||
|
||||
it('should mark task and asset as failed when recoveryAttempts exceeds maxRecoveryAttempts', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
id: 'poison-asset-1',
|
||||
name: 'poison.mp4',
|
||||
type: 'file',
|
||||
status: 'processing',
|
||||
},
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: new Date(Date.now() - 100_000),
|
||||
output: { recoveryAttempts: 3 },
|
||||
},
|
||||
})
|
||||
|
||||
const mockClient = {
|
||||
retrieveWorkflow: vi.fn(),
|
||||
resumeWorkflow: vi.fn(),
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.spyOn(workflowService.getExecutor(), 'getClient').mockResolvedValue(mockClient as any)
|
||||
|
||||
const recoveredCount = await workflowService.recoverStaleTasks({
|
||||
staleThresholdMs: 90_000,
|
||||
maxRecoveryAttempts: 3,
|
||||
})
|
||||
|
||||
expect(recoveredCount).toBe(1)
|
||||
expect(mockClient.resumeWorkflow).not.toHaveBeenCalled()
|
||||
|
||||
const updatedTask = await prisma.workflowTask.findUnique({
|
||||
where: { id: task.id },
|
||||
})
|
||||
expect(updatedTask?.status).toBe(WorkflowTaskStatus.failed)
|
||||
const output = updatedTask?.output as { error?: string; recoveryAttempts?: number } | null
|
||||
expect(output?.recoveryAttempts).toBe(4)
|
||||
expect(output?.error).toContain('exceeded maximum stale recovery attempts')
|
||||
|
||||
const updatedAsset = await prisma.asset.findUnique({
|
||||
where: { id: asset.id },
|
||||
})
|
||||
expect(updatedAsset?.status).toBe('failed')
|
||||
})
|
||||
|
||||
it('should reconcile completed or cancelled DBOS workflow status', async () => {
|
||||
const taskSuccess = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'stale-asset-success',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: new Date(Date.now() - 100_000),
|
||||
},
|
||||
})
|
||||
|
||||
const taskCancelled = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'stale-asset-cancelled',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: new Date(Date.now() - 100_000),
|
||||
},
|
||||
})
|
||||
|
||||
const mockClient = {
|
||||
retrieveWorkflow: vi.fn().mockImplementation((taskId: string) => ({
|
||||
getStatus: vi.fn().mockResolvedValue({
|
||||
status: taskId === taskSuccess.id ? 'SUCCESS' : 'CANCELLED',
|
||||
}),
|
||||
})),
|
||||
resumeWorkflow: vi.fn(),
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.spyOn(workflowService.getExecutor(), 'getClient').mockResolvedValue(mockClient as any)
|
||||
|
||||
const count = await workflowService.recoverStaleTasks({
|
||||
staleThresholdMs: 90_000,
|
||||
maxRecoveryAttempts: 3,
|
||||
})
|
||||
|
||||
expect(count).toBe(2)
|
||||
expect(mockClient.resumeWorkflow).not.toHaveBeenCalled()
|
||||
|
||||
const updatedSuccess = await prisma.workflowTask.findUnique({
|
||||
where: { id: taskSuccess.id },
|
||||
})
|
||||
expect(updatedSuccess?.status).toBe(WorkflowTaskStatus.completed)
|
||||
|
||||
const updatedCancelled = await prisma.workflowTask.findUnique({
|
||||
where: { id: taskCancelled.id },
|
||||
})
|
||||
expect(updatedCancelled?.status).toBe(WorkflowTaskStatus.failed)
|
||||
const cancelledOutput = updatedCancelled?.output as { error?: string } | null
|
||||
expect(cancelledOutput?.error).toBe('Workflow was cancelled')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,33 +1,24 @@
|
||||
import { prisma, registerWorkflowCancel, registerWorkflowTrigger, WorkflowTask } from '@shumai/db'
|
||||
import path from 'path'
|
||||
import { ulid } from 'ulid'
|
||||
import * as taskActivities from './activities/task'
|
||||
import { Executor } from './executor'
|
||||
import { LocalExecutor } from './local-executor'
|
||||
import { TemporalExecutor } from './temporal-executor'
|
||||
import { TaskQueueAgent, TaskQueueTranscode, getConcurrencyLimit } from './workflow-utils'
|
||||
|
||||
import type { Worker } from '@temporalio/worker'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import {
|
||||
AssetStatus,
|
||||
prisma,
|
||||
registerWorkflowCancel,
|
||||
registerWorkflowTrigger,
|
||||
WorkflowTask,
|
||||
WorkflowTaskStatus,
|
||||
} from '@shumai/db'
|
||||
import { DbosExecutor, getQueueForTaskType, getRegisteredWorkflows } from './dbos-executor'
|
||||
|
||||
export class WorkflowService {
|
||||
private executor: Executor
|
||||
private activeWorkers: Worker[] = []
|
||||
private executor: DbosExecutor
|
||||
private staleRecoveryTimer: Timer | null = null
|
||||
|
||||
constructor() {
|
||||
const type = process.env.WORKFLOW_EXECUTOR || 'local'
|
||||
if (type === 'temporal') {
|
||||
this.executor = new TemporalExecutor(process.env.TEMPORAL_ADDRESS)
|
||||
} else {
|
||||
this.executor = new LocalExecutor()
|
||||
}
|
||||
this.executor = new DbosExecutor()
|
||||
}
|
||||
|
||||
setExecutorType(type: 'local' | 'temporal') {
|
||||
if (type === 'temporal') {
|
||||
this.executor = new TemporalExecutor(process.env.TEMPORAL_ADDRESS)
|
||||
} else {
|
||||
this.executor = new LocalExecutor()
|
||||
}
|
||||
getExecutor(): DbosExecutor {
|
||||
return this.executor
|
||||
}
|
||||
|
||||
async submit(task: WorkflowTask): Promise<string> {
|
||||
@@ -35,9 +26,7 @@ export class WorkflowService {
|
||||
}
|
||||
|
||||
async cancel(taskId: string): Promise<void> {
|
||||
if (this.executor.cancel) {
|
||||
await this.executor.cancel(taskId)
|
||||
}
|
||||
await this.executor.cancel(taskId)
|
||||
}
|
||||
|
||||
async executeWait(task: WorkflowTask, timeoutMs: number = 30000): Promise<WorkflowTask> {
|
||||
@@ -56,135 +45,211 @@ export class WorkflowService {
|
||||
}
|
||||
|
||||
if (updatedTask.status === 'failed') {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const error = (updatedTask.output as any)?.error || 'Workflow task failed'
|
||||
const output = updatedTask.output as Record<string, unknown> | null
|
||||
const error = typeof output?.error === 'string' ? output.error : 'Workflow task failed'
|
||||
throw new Error(error)
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 500))
|
||||
await new Promise((resolve) => setTimeout(resolve, 200))
|
||||
}
|
||||
|
||||
throw new Error('Workflow task timed out')
|
||||
}
|
||||
|
||||
start(): void {
|
||||
start(listenQueues?: string[]): void {
|
||||
if (listenQueues) {
|
||||
this.executor.setListenQueues(listenQueues)
|
||||
}
|
||||
this.executor.start()
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.stopStaleTaskRecovery()
|
||||
this.executor.close()
|
||||
}
|
||||
|
||||
async shutdownWorkers(): Promise<void> {
|
||||
await Promise.all(this.activeWorkers.map((w) => w.shutdown()))
|
||||
this.activeWorkers = []
|
||||
async ensureLaunched(): Promise<void> {
|
||||
await this.executor.ensureLaunched()
|
||||
}
|
||||
|
||||
// Starts Temporal workers for specific task queues
|
||||
async startWorkers(
|
||||
queue: string,
|
||||
options: { workflowBundle?: unknown; workflowsPath?: string } = {},
|
||||
): Promise<void> {
|
||||
const type = this.executor instanceof TemporalExecutor ? 'temporal' : 'local'
|
||||
if (type === 'temporal') {
|
||||
const { Worker, NativeConnection } = await import('@temporalio/worker')
|
||||
async shutdownWorkers(options?: { workflowCompletionTimeoutMs?: number }): Promise<void> {
|
||||
this.stopStaleTaskRecovery()
|
||||
await this.executor.shutdown(options)
|
||||
}
|
||||
|
||||
const connection = await NativeConnection.connect({
|
||||
address: process.env.TEMPORAL_ADDRESS || 'localhost:7233',
|
||||
})
|
||||
isStarted(): boolean {
|
||||
return this.executor.isStarted()
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const activities = (globalThis as any).__localActivities
|
||||
async waitForPendingSubmissions(): Promise<void> {
|
||||
await this.executor.waitForPendingSubmissions()
|
||||
}
|
||||
|
||||
// For agent_queue and transcode_queue, use worker-specific unique queues
|
||||
const workerId = ulid()
|
||||
const workerSpecificQueue = `${queue}-${workerId}`
|
||||
// Starts DBOS worker for specific task queue(s)
|
||||
async startWorkers(queue: string | string[]): Promise<void> {
|
||||
const queues = Array.isArray(queue) ? queue : [queue]
|
||||
console.log(`Starting DBOS worker for queue(s): ${queues.join(', ')}`)
|
||||
this.executor.setListenQueues(queues)
|
||||
this.executor.start()
|
||||
await this.executor.ensureLaunched()
|
||||
}
|
||||
|
||||
console.log(`Starting Temporal workers for domain: ${queue}`)
|
||||
console.log(` - Shared queue: ${queue}`)
|
||||
console.log(` - Worker-specific queue: ${workerSpecificQueue}`)
|
||||
|
||||
// Create a specific activities object for the shared worker that ONLY overrides the queue lookup
|
||||
const sharedActivities: Record<string, unknown> = {}
|
||||
if (queue === 'agent_queue') {
|
||||
sharedActivities.getAgentWorkerQueueActivity = async () => workerSpecificQueue
|
||||
} else if (queue === 'transcode_queue') {
|
||||
sharedActivities.getTranscodeWorkerQueueActivity = async () => workerSpecificQueue
|
||||
}
|
||||
|
||||
const { workflowBundle, workflowsPath } = options
|
||||
|
||||
const sharedWorker = await Worker.create({
|
||||
connection,
|
||||
// The workflowBundle is a pre-bundled set of workflows, its internal structure
|
||||
// is managed by the Temporal worker and doesn't need explicit typing here.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
...(workflowBundle ? { workflowBundle: workflowBundle as any } : {}),
|
||||
...(workflowsPath ? { workflowsPath } : {}),
|
||||
activities: sharedActivities,
|
||||
taskQueue: queue,
|
||||
|
||||
bundlerOptions: {
|
||||
webpackConfigHook: (config) => {
|
||||
config.resolve = config.resolve || {}
|
||||
config.resolve.alias = {
|
||||
...config.resolve.alias,
|
||||
// Find the exact absolute path to the package directory
|
||||
'@temporalio/workflow': path.dirname(
|
||||
require.resolve('@temporalio/workflow/package.json'),
|
||||
),
|
||||
'@shumai/workflow-core': require.resolve('./workflow-utils'),
|
||||
}
|
||||
return config
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
let maxConcurrentActivityTaskExecutions: number | undefined
|
||||
if (queue === TaskQueueTranscode) {
|
||||
maxConcurrentActivityTaskExecutions = getConcurrencyLimit(
|
||||
process.env.CONCURRENCY_TRANSCODE,
|
||||
1,
|
||||
)
|
||||
} else if (queue === TaskQueueAgent) {
|
||||
maxConcurrentActivityTaskExecutions = getConcurrencyLimit(process.env.CONCURRENCY_AGENT, 5)
|
||||
}
|
||||
|
||||
const specificWorker = await Worker.create({
|
||||
connection,
|
||||
// Register both domain-specific activities and shared task activities
|
||||
activities: { ...activities, ...taskActivities },
|
||||
taskQueue: workerSpecificQueue,
|
||||
maxConcurrentActivityTaskExecutions,
|
||||
bundlerOptions: {
|
||||
webpackConfigHook: (config) => {
|
||||
config.resolve = config.resolve || {}
|
||||
config.resolve.alias = {
|
||||
...config.resolve.alias,
|
||||
// Find the exact absolute path to the package directory
|
||||
'@temporalio/workflow': path.dirname(
|
||||
require.resolve('@temporalio/workflow/package.json'),
|
||||
),
|
||||
'@shumai/workflow-core': require.resolve('./workflow-utils'),
|
||||
}
|
||||
return config
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
this.activeWorkers.push(sharedWorker, specificWorker)
|
||||
|
||||
await Promise.all([sharedWorker.run(), specificWorker.run()])
|
||||
} else {
|
||||
console.log(
|
||||
`Workflow executor is set to "${type}". Separate worker processes are only needed for "temporal" mode.`,
|
||||
)
|
||||
startStaleTaskRecovery(options?: {
|
||||
intervalMs?: number
|
||||
staleThresholdMs?: number
|
||||
maxRecoveryAttempts?: number
|
||||
}): void {
|
||||
if (this.staleRecoveryTimer) {
|
||||
return
|
||||
}
|
||||
const intervalMs = options?.intervalMs ?? 30_000
|
||||
this.staleRecoveryTimer = setInterval(() => {
|
||||
this.recoverStaleTasks(options).catch((err) => {
|
||||
logger.error({ err }, '[WorkflowService] Stale task recovery sweep encountered an error')
|
||||
})
|
||||
}, intervalMs)
|
||||
}
|
||||
|
||||
stopStaleTaskRecovery(): void {
|
||||
if (this.staleRecoveryTimer) {
|
||||
clearInterval(this.staleRecoveryTimer)
|
||||
this.staleRecoveryTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
async recoverStaleTasks(options?: {
|
||||
staleThresholdMs?: number
|
||||
maxRecoveryAttempts?: number
|
||||
}): Promise<number> {
|
||||
const staleThresholdMs = options?.staleThresholdMs ?? 90_000
|
||||
const maxRecoveryAttempts = options?.maxRecoveryAttempts ?? 3
|
||||
const cutoff = new Date(Date.now() - staleThresholdMs)
|
||||
|
||||
const staleTasks = await prisma.workflowTask.findMany({
|
||||
where: {
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: { lt: cutoff },
|
||||
},
|
||||
})
|
||||
|
||||
if (staleTasks.length === 0) return 0
|
||||
|
||||
let recoveredCount = 0
|
||||
const client = await this.executor.getClient()
|
||||
|
||||
for (const task of staleTasks) {
|
||||
try {
|
||||
const currentTask = await prisma.workflowTask.findUnique({
|
||||
where: { id: task.id },
|
||||
})
|
||||
if (
|
||||
!currentTask ||
|
||||
currentTask.status !== WorkflowTaskStatus.processing ||
|
||||
(currentTask.heartbeat &&
|
||||
currentTask.heartbeat.getTime() >= Date.now() - staleThresholdMs)
|
||||
) {
|
||||
continue
|
||||
}
|
||||
|
||||
const output = (currentTask.output as PrismaJson.WorkflowTaskOutput | null) || {}
|
||||
const recoveryAttempts = (output.recoveryAttempts ?? 0) + 1
|
||||
|
||||
if (recoveryAttempts > maxRecoveryAttempts) {
|
||||
logger.error(
|
||||
{ taskId: task.id, recoveryAttempts, maxRecoveryAttempts },
|
||||
'[WorkflowService] Stale task exceeded max recovery attempts. Marking as failed.',
|
||||
)
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: task.id },
|
||||
data: {
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: {
|
||||
...output,
|
||||
recoveryAttempts,
|
||||
error: `Task exceeded maximum stale recovery attempts (${maxRecoveryAttempts}). Marked as failed.`,
|
||||
},
|
||||
},
|
||||
})
|
||||
if (task.assetId && task.type && task.type.startsWith('transcode')) {
|
||||
await prisma.asset.updateMany({
|
||||
where: { id: task.assetId, status: AssetStatus.processing },
|
||||
data: { status: AssetStatus.failed },
|
||||
})
|
||||
}
|
||||
recoveredCount++
|
||||
continue
|
||||
}
|
||||
|
||||
const handle = client.retrieveWorkflow(task.id)
|
||||
const wfStatus = await handle.getStatus().catch(() => null)
|
||||
|
||||
if (wfStatus?.status === 'PENDING') {
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: task.id },
|
||||
data: {
|
||||
heartbeat: new Date(),
|
||||
output: {
|
||||
...output,
|
||||
recoveryAttempts,
|
||||
},
|
||||
},
|
||||
})
|
||||
const queueName = getQueueForTaskType(task.type)
|
||||
await client.resumeWorkflow(task.id, { queueName })
|
||||
logger.info(
|
||||
{ taskId: task.id, queueName, recoveryAttempts },
|
||||
'[WorkflowService] Resumed stale pending workflow task in DBOS',
|
||||
)
|
||||
recoveredCount++
|
||||
} else if (wfStatus?.status === 'SUCCESS') {
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: task.id },
|
||||
data: { status: WorkflowTaskStatus.completed },
|
||||
})
|
||||
recoveredCount++
|
||||
} else if (wfStatus?.status === 'ERROR') {
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: task.id },
|
||||
data: {
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: {
|
||||
...output,
|
||||
error: wfStatus.error ? String(wfStatus.error) : 'Workflow failed in DBOS',
|
||||
},
|
||||
},
|
||||
})
|
||||
recoveredCount++
|
||||
} else if (wfStatus?.status === 'CANCELLED') {
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: task.id },
|
||||
data: {
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: {
|
||||
...output,
|
||||
error: 'Workflow was cancelled',
|
||||
},
|
||||
},
|
||||
})
|
||||
recoveredCount++
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn({ taskId: task.id, err }, '[WorkflowService] Error while checking stale task')
|
||||
}
|
||||
}
|
||||
|
||||
return recoveredCount
|
||||
}
|
||||
}
|
||||
|
||||
export const workflowService = new WorkflowService()
|
||||
registerWorkflowTrigger(async (task) => {
|
||||
if (
|
||||
process.env.NODE_ENV === 'test' &&
|
||||
!workflowService.isStarted() &&
|
||||
getRegisteredWorkflows().size === 0
|
||||
) {
|
||||
return
|
||||
}
|
||||
await workflowService.submit(task)
|
||||
})
|
||||
registerWorkflowCancel(async (taskId) => {
|
||||
|
||||
Reference in New Issue
Block a user