mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 00:09:22 +00:00
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.
This commit is contained in:
@@ -1,14 +1,6 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { WorkflowTaskStatus, AssetStatus, AssetType, Prisma } from '@shumai/db'
|
||||
|
||||
export async function getTranscodeWorkerQueueActivity(): Promise<string> {
|
||||
return 'transcode_queue'
|
||||
}
|
||||
|
||||
export async function getAgentWorkerQueueActivity(): Promise<string> {
|
||||
return 'agent_queue'
|
||||
}
|
||||
|
||||
export async function getAssetStatusActivity(params: {
|
||||
assetId: string
|
||||
}): Promise<AssetStatus | null> {
|
||||
|
||||
@@ -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,154 @@
|
||||
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 } from '@shumai/db'
|
||||
import { DBOS } from '@dbos-inc/dbos-sdk'
|
||||
|
||||
describe('DbosExecutor Tests', () => {
|
||||
let executor: DbosExecutor
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
executor = new DbosExecutor()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
executor.close()
|
||||
})
|
||||
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
||||
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 () => {
|
||||
executor.start()
|
||||
const enqueueSpy = vi
|
||||
.spyOn(DBOS, 'enqueueWorkflowWithOptions')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/naming-convention -- mock handle
|
||||
.mockResolvedValueOnce({ workflowID: 'task-123' } as any)
|
||||
vi.spyOn(executor, 'ensureLaunched').mockResolvedValueOnce(undefined)
|
||||
|
||||
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(enqueueSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
queueName: TaskQueueAgent,
|
||||
workflowName: WorkflowTaskType.chat,
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS property name
|
||||
workflowID: 'task-123',
|
||||
}),
|
||||
mockTask,
|
||||
)
|
||||
|
||||
enqueueSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,310 @@
|
||||
import { DBOS } from '@dbos-inc/dbos-sdk'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { prisma, WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import type { Executor } from './executor'
|
||||
import { getRegisteredWorkflows } from './registry'
|
||||
import {
|
||||
getConcurrencyLimit,
|
||||
registerLocalTaskAbortController,
|
||||
runInLocalTaskContext,
|
||||
TaskQueueAgent,
|
||||
TaskQueueTranscode,
|
||||
triggerLocalCancel,
|
||||
unregisterLocalTaskAbortController,
|
||||
} from './workflow-utils'
|
||||
|
||||
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 implements Executor {
|
||||
private launchPromise: Promise<void> | null = null
|
||||
private started = false
|
||||
private listenQueues: string[] = [TaskQueueAgent, TaskQueueTranscode]
|
||||
private heartbeatIntervals = new Map<string, Timer>()
|
||||
|
||||
constructor(listenQueues?: string[]) {
|
||||
if (listenQueues) {
|
||||
this.listenQueues = listenQueues
|
||||
}
|
||||
}
|
||||
|
||||
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}`)
|
||||
}
|
||||
// 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)
|
||||
|
||||
try {
|
||||
await runInLocalTaskContext({ taskId: task.id, abortController }, async () => {
|
||||
await fn(task)
|
||||
})
|
||||
} catch (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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private getDefaultExecutorId(): string {
|
||||
if (process.env.DBOS__VMID) return process.env.DBOS__VMID
|
||||
if (process.env.SHUMAI_WORKER_ID) return process.env.SHUMAI_WORKER_ID
|
||||
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'
|
||||
}
|
||||
|
||||
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'
|
||||
DBOS.setConfig({
|
||||
name: 'shumai',
|
||||
systemDatabaseUrl: getDbosDatabaseUrl(),
|
||||
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: !dbosMigrationsRan,
|
||||
logLevel: isTest ? 'error' : 'info',
|
||||
})
|
||||
|
||||
await DBOS.launch()
|
||||
dbosMigrationsRan = true
|
||||
|
||||
const minPollingIntervalMs = isTest ? 50 : 1000
|
||||
await DBOS.registerQueue(TaskQueueTranscode, {
|
||||
workerConcurrency: this.getTranscodeConcurrencyLimit(),
|
||||
minPollingIntervalMs,
|
||||
onConflict: 'never_update',
|
||||
})
|
||||
await DBOS.registerQueue(TaskQueueAgent, {
|
||||
workerConcurrency: this.getAgentConcurrencyLimit(),
|
||||
minPollingIntervalMs,
|
||||
onConflict: 'never_update',
|
||||
})
|
||||
})()
|
||||
|
||||
try {
|
||||
await this.launchPromise
|
||||
} catch (err) {
|
||||
this.launchPromise = null
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
async submit(task: WorkflowTask): Promise<string> {
|
||||
if (task.status !== WorkflowTaskStatus.pending) {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: task.id },
|
||||
data: { status: WorkflowTaskStatus.pending },
|
||||
})
|
||||
}
|
||||
|
||||
// In unit tests that do not start the workflow service or register workflows,
|
||||
// avoid launching DBOS in the background if no workflows are registered.
|
||||
if (!this.started && getRegisteredWorkflows().size === 0) {
|
||||
return task.id
|
||||
}
|
||||
|
||||
await this.ensureLaunched()
|
||||
|
||||
const workflowName = task.type
|
||||
if (!workflowName) {
|
||||
throw new Error(`WorkflowTask ${task.id} is missing task.type`)
|
||||
}
|
||||
|
||||
const queueName = getQueueForTaskType(workflowName)
|
||||
const handle = await DBOS.enqueueWorkflowWithOptions(
|
||||
{
|
||||
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 cancel(taskId: string): Promise<void> {
|
||||
const timer = this.heartbeatIntervals.get(taskId)
|
||||
if (timer) {
|
||||
clearInterval(timer)
|
||||
this.heartbeatIntervals.delete(taskId)
|
||||
}
|
||||
triggerLocalCancel(taskId)
|
||||
if (DBOS.isInitialized()) {
|
||||
try {
|
||||
await DBOS.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
|
||||
for (const timer of this.heartbeatIntervals.values()) {
|
||||
clearInterval(timer)
|
||||
}
|
||||
this.heartbeatIntervals.clear()
|
||||
if (DBOS.isInitialized()) {
|
||||
DBOS.shutdown({ deregister: true })
|
||||
.then(() => {
|
||||
registeredDbosWorkflowNames.clear()
|
||||
this.launchPromise = null
|
||||
})
|
||||
.catch((err) => {
|
||||
logger.warn({ err }, '[DbosExecutor] Error during DBOS shutdown')
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
this.started = false
|
||||
for (const timer of this.heartbeatIntervals.values()) {
|
||||
clearInterval(timer)
|
||||
}
|
||||
this.heartbeatIntervals.clear()
|
||||
if (DBOS.isInitialized()) {
|
||||
await DBOS.shutdown({ deregister: true })
|
||||
registeredDbosWorkflowNames.clear()
|
||||
this.launchPromise = null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
export * from './executor'
|
||||
export * from './local-executor'
|
||||
export * from './temporal-executor'
|
||||
export * from './dbos-executor'
|
||||
export * from './registry'
|
||||
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,36 @@
|
||||
import { WorkflowTask } from '@shumai/db'
|
||||
import * as taskActivities from './activities/task'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
|
||||
export 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): void {
|
||||
workflowRegistry.set(type, fn)
|
||||
}
|
||||
|
||||
export function getRegisteredWorkflows(): Map<string, WorkflowFn> {
|
||||
return workflowRegistry
|
||||
}
|
||||
|
||||
/* 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>): void {
|
||||
Object.assign(activityRegistry, acts)
|
||||
globalObj.__localActivities = activityRegistry
|
||||
}
|
||||
|
||||
export function getActivityRegistry(): Record<string, unknown> {
|
||||
return activityRegistry
|
||||
}
|
||||
|
||||
// Inject dependencies into global scope for workflow-utils
|
||||
globalObj.__localActivities = activityRegistry
|
||||
globalObj.__localLogger = logger
|
||||
@@ -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,30 +1,20 @@
|
||||
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, beforeAll } from 'vitest'
|
||||
import { DBOS } from '@dbos-inc/dbos-sdk'
|
||||
import {
|
||||
getActivities,
|
||||
executeActivity,
|
||||
WorkflowFailure,
|
||||
ApplicationFailure,
|
||||
isNonRetryableError,
|
||||
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', () => {
|
||||
describe('workflow-utils executeActivity and DBOS steps', () => {
|
||||
beforeAll(() => {
|
||||
// Inject mock activities for local execution tests
|
||||
// Inject mock activities for execution tests
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(globalThis as any).__localActivities = {
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
@@ -37,7 +27,7 @@ describe('workflow-utils executeActivity', () => {
|
||||
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'
|
||||
@@ -61,36 +51,74 @@ describe('workflow-utils executeActivity', () => {
|
||||
)
|
||||
})
|
||||
|
||||
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 via DBOS.runStep when within workflow context', async () => {
|
||||
const mockFn = vi.fn().mockResolvedValue('step-success')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(mockFn as any)._activityName = '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)
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const result = await executeActivity('test-queue', mockFn as any, '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('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 } from '@dbos-inc/dbos-sdk'
|
||||
|
||||
/**
|
||||
* Task queue constants.
|
||||
@@ -7,19 +6,45 @@ 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 {
|
||||
return false
|
||||
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
|
||||
}
|
||||
|
||||
const CLEANUP_OR_FINALIZE_ACTIVITIES = new Set([
|
||||
'cleanupTmpDirActivity',
|
||||
'updateTaskStatusActivity',
|
||||
'updateWorkflowTaskActivity',
|
||||
'updateAssetStatusActivity',
|
||||
'updateCommentActivity',
|
||||
'deleteS3ObjectActivity',
|
||||
])
|
||||
|
||||
interface LocalLogger {
|
||||
debug(obj: Record<string, unknown>, msg: string): void
|
||||
info(obj: Record<string, unknown>, msg: string): void
|
||||
@@ -34,9 +59,6 @@ const globalObj = globalThis as typeof globalThis & {
|
||||
}
|
||||
/* 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) {
|
||||
@@ -46,39 +68,24 @@ function localActivitiesProxy(): Record<string, unknown> {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Dynamic activities proxy that exposes registered activities and attaches metadata.
|
||||
*/
|
||||
// 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()
|
||||
}
|
||||
const baseProxy = localActivitiesProxy()
|
||||
|
||||
// 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
|
||||
@@ -102,23 +109,12 @@ export function getActivities<T = any>(): T {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 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),
|
||||
}
|
||||
}
|
||||
function getLogger(): LocalLogger | Console {
|
||||
return globalObj.__localLogger || console
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute an activity on a specific task queue.
|
||||
* Execute an activity on a specific task queue. In DBOS context, executes as a checkpointed step.
|
||||
* @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
|
||||
@@ -162,19 +158,30 @@ export async function executeActivity(
|
||||
// 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)
|
||||
if (DBOS.isWithinWorkflow()) {
|
||||
try {
|
||||
result = await DBOS.runStep(() => activityFunc(...args), {
|
||||
name: activityName,
|
||||
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 (
|
||||
stepErr instanceof Error &&
|
||||
stepErr.name === 'DBOSWorkflowCancelledError' &&
|
||||
CLEANUP_OR_FINALIZE_ACTIVITIES.has(activityName)
|
||||
) {
|
||||
result = await activityFunc(...args)
|
||||
} else {
|
||||
throw stepErr
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// For local execution, queue is ignored and we just execute the function
|
||||
result = await activityFunc(...args)
|
||||
}
|
||||
logger.debug(
|
||||
@@ -253,6 +260,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,9 +37,6 @@ describe('WorkflowService', () => {
|
||||
beforeEach(async () => {
|
||||
initAgentWorkflows()
|
||||
initTranscodeWorkflows()
|
||||
await prisma.workflowTask.deleteMany()
|
||||
await prisma.assetComment.deleteMany()
|
||||
await prisma.asset.deleteMany()
|
||||
vi.clearAllMocks()
|
||||
workflowService.start()
|
||||
})
|
||||
@@ -80,7 +77,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 +93,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 +124,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 +138,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({
|
||||
|
||||
@@ -1,33 +1,20 @@
|
||||
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 { DbosExecutor } from './dbos-executor'
|
||||
|
||||
export class WorkflowService {
|
||||
private executor: Executor
|
||||
private activeWorkers: Worker[] = []
|
||||
private executor: DbosExecutor
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
setExecutorType(_type: string): void {
|
||||
// Retained for backwards compatibility in tests
|
||||
}
|
||||
|
||||
async submit(task: WorkflowTask): Promise<string> {
|
||||
@@ -35,9 +22,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,18 +41,21 @@ 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()
|
||||
}
|
||||
|
||||
@@ -76,110 +64,20 @@ export class WorkflowService {
|
||||
}
|
||||
|
||||
async shutdownWorkers(): Promise<void> {
|
||||
await Promise.all(this.activeWorkers.map((w) => w.shutdown()))
|
||||
this.activeWorkers = []
|
||||
await this.executor.shutdown()
|
||||
}
|
||||
|
||||
// Starts Temporal workers for specific task queues
|
||||
// Starts DBOS worker for specific task queue(s)
|
||||
async startWorkers(
|
||||
queue: string,
|
||||
options: { workflowBundle?: unknown; workflowsPath?: string } = {},
|
||||
queue: string | string[],
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
_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')
|
||||
|
||||
const connection = await NativeConnection.connect({
|
||||
address: process.env.TEMPORAL_ADDRESS || 'localhost:7233',
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const activities = (globalThis as any).__localActivities
|
||||
|
||||
// For agent_queue and transcode_queue, use worker-specific unique queues
|
||||
const workerId = ulid()
|
||||
const workerSpecificQueue = `${queue}-${workerId}`
|
||||
|
||||
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.`,
|
||||
)
|
||||
}
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user