refactor(monorepo): decouple and split background workflow workers into packages

Splits monolithic workflow workers into four decoupled workspaces under the Bun workspaces monorepo:
- @shumai/workflow-core containing the core execution engine and utilities.
- @shumai/agent containing agent-specific logic, workflows, and activities.
- @shumai/transcode containing transcoding workflows, transcoder, and transcode activities.
- @shumai/worker-db containing database activities.

Introduces a dynamic workflow and activity registration pattern on LocalExecutor to eliminate circular dependencies. Updates worker bootstrapping and test suites to cleanly leverage generic workspace modules.
This commit is contained in:
yiling
2026-06-01 23:29:11 +08:00
parent cb80822637
commit e3f4fa219e
66 changed files with 421 additions and 150 deletions
@@ -0,0 +1,72 @@
import { describe, it, expect } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import {
updateTaskStatusActivity,
updateAssetStatusActivity,
updateTaskUsageActivity,
} from '@shumai/worker-db'
import { WorkflowTaskStatus, WorkflowTaskType, AssetStatus } from '@shumai/db'
describe('Task Activities', () => {
setupTestDbHooks()
it('should update task status', async () => {
const task = await prisma.workflowTask.create({
data: {
assetId: 'asset-1',
type: WorkflowTaskType.ai_embedding,
status: WorkflowTaskStatus.pending,
},
})
await updateTaskStatusActivity({
taskId: task.id,
status: WorkflowTaskStatus.processing,
})
const updated = await prisma.workflowTask.findUnique({ where: { id: task.id } })
expect(updated?.status).toBe(WorkflowTaskStatus.processing)
})
it('should update asset status', async () => {
const asset = await prisma.asset.create({
data: {
name: 'test.mp4',
storageKey: { create: { key: 'test.mp4' } },
status: 'uploaded',
type: 'file',
},
})
await updateAssetStatusActivity({
assetId: asset.id,
status: AssetStatus.processing,
})
const updated = await prisma.asset.findUnique({ where: { id: asset.id } })
expect(updated?.status).toBe(AssetStatus.processing)
})
it('should update task usage', async () => {
const task = await prisma.workflowTask.create({
data: {
assetId: 'asset-1',
type: WorkflowTaskType.ai_embedding,
status: WorkflowTaskStatus.pending,
},
})
await updateTaskUsageActivity({
taskId: task.id,
inputTokens: 100,
outputTokens: 200,
model: 'gpt-4o',
})
const updated = await prisma.workflowTask.findUnique({ where: { id: task.id } })
expect(updated?.inputTokens).toBe(100)
expect(updated?.outputTokens).toBe(200)
expect(updated?.model).toBe('gpt-4o')
})
})
@@ -0,0 +1,7 @@
export async function getTranscodeWorkerQueueActivity(): Promise<string> {
return 'transcode_queue'
}
export async function getAgentWorkerQueueActivity(): Promise<string> {
return 'agent_queue'
}
+7
View File
@@ -0,0 +1,7 @@
import { WorkflowTask } from '@shumai/db'
export interface Executor {
submit(task: WorkflowTask): Promise<string>
start(): void
close(): void
}
+6
View File
@@ -0,0 +1,6 @@
export * from './executor'
export * from './local-executor'
export * from './temporal-executor'
export * from './workflow-utils'
export * from './workflow'
export * from './activities/task'
@@ -0,0 +1,348 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
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(),
queryEmbeddingForSearch: 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.query_embedding_for_search, async (task) =>
mocks.queryEmbeddingForSearch(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 new Promise((resolve) => setTimeout(resolve, 100))
// Exactly 5 tasks should be running concurrently
expect(mocks.agentChat).toHaveBeenCalledTimes(5)
// Resolve 2 tasks to let the remaining 2 start
activeResolvers[0](undefined)
activeResolvers[1](undefined)
// Wait briefly for the pool to dequeue
await new Promise((resolve) => setTimeout(resolve, 50))
// Now all 7 tasks should have started
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)
})
})
})
@@ -0,0 +1,272 @@
import { prisma } from '@shumai/db'
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import { Executor } from './executor'
import * as taskActivities from './activities/task'
import { logger } from '@/logger'
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
export class ConcurrencyLimiter {
private activeCount = 0
private queue: (() => void)[] = []
constructor(private readonly limit: number) {}
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>()
// 1 concurrency for transcode, 5 for other workflows
private transcodeLimiter = new ConcurrencyLimiter(1)
private generalLimiter = new ConcurrencyLimiter(5)
async submit(task: WorkflowTask): Promise<string> {
if (task.status !== WorkflowTaskStatus.pending) {
await prisma.workflowTask.update({
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 {
await prisma.workflowTask.update({
where: { id: task.id },
data: { heartbeat: new Date() },
})
} catch (err) {
console.error(`[LocalExecutor] Failed to update heartbeat for task ${task.id}:`, err)
}
}, 5000)
const limiter =
task.type === WorkflowTaskType.transcode ? this.transcodeLimiter : this.generalLimiter
limiter
.run(async () => {
try {
await this.processTaskWrapper(task)
} finally {
// 3. Clean up the heartbeat updater and processing set when the task finishes
clearInterval(heartbeatInterval)
this.processingTasks.delete(task.id)
}
})
.catch((err) => {
console.error(`[LocalExecutor] Failed to process task ${task.id}:`, err)
})
}, 0)
}
return task.id
}
start(): void {
if (this.interval) return
this.interval = setInterval(() => this.tick(), 5000)
}
close(): void {
if (this.interval) {
clearInterval(this.interval)
this.interval = null
}
}
// 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)
const tasks = await prisma.workflowTask.findMany({
where: {
OR: [
{ status: WorkflowTaskStatus.pending },
{
status: WorkflowTaskStatus.processing,
heartbeat: { lt: staleTime },
},
],
},
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
// to guarantee no other ticks/replicas can double-query it.
// We use updateMany to atomically claim it only if it is still pending or stale.
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:`, err)
this.processingTasks.delete(task.id)
continue
}
// 2. Start heartbeat updater immediately so it updates heartbeat
// even while the task is queued waiting for limiter capacity.
const heartbeatInterval = setInterval(async () => {
try {
await prisma.workflowTask.update({
where: { id: task.id },
data: { heartbeat: new Date() },
})
} catch (err) {
console.error(`[LocalExecutor] Failed to update heartbeat for task ${task.id}:`, err)
}
}, 5000)
const limiter =
task.type === WorkflowTaskType.transcode ? this.transcodeLimiter : this.generalLimiter
const promise = limiter
.run(async () => {
try {
await this.processTaskWrapper(task)
} finally {
// 3. Clean up the heartbeat updater and processing set when the task finishes
clearInterval(heartbeatInterval)
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.update({
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)
}
}
}
}
@@ -0,0 +1,65 @@
import { Connection, Client } from '@temporalio/client'
import { WorkflowTask, WorkflowTaskType } from '@shumai/db'
import { Executor } from './executor'
export const TASK_QUEUE_DB = 'db_queue'
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
switch (task.type) {
case WorkflowTaskType.ai_embedding:
workflowName = 'agentEmbeddingWorkflow'
break
case WorkflowTaskType.query_embedding_for_search:
workflowName = 'queryEmbeddingForSearch'
break
case WorkflowTaskType.ai_metadata_autofill:
workflowName = 'agentAutofillWorkflow'
break
case WorkflowTaskType.chat:
workflowName = 'agentChatWorkflow'
break
case WorkflowTaskType.transcode:
workflowName = 'transcodeWorkflow'
break
default:
throw new Error(`Unknown task type: ${task.type}`)
}
const handle = await client.workflow.start(workflowName, {
taskQueue: TASK_QUEUE_DB,
workflowId,
args: [task],
})
return handle.workflowId
}
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
}
}
@@ -0,0 +1,42 @@
import { describe, it, expect, vi, beforeAll } from 'vitest'
import { getActivities, executeActivity } from './workflow-utils'
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(),
}
})
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 () => {
const mockFn = vi.fn().mockResolvedValue('success-result')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(mockFn as any)._activityName = 'mockActivity'
const result = await executeActivity(
'test-queue',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mockFn as any,
{ 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()',
)
})
})
@@ -0,0 +1,185 @@
// Use type-only imports for activities to avoid bundling them in Temporal workflows
import * as wf from '@temporalio/workflow'
/**
* Task queue constants.
*/
export const TaskQueueDb = 'db_queue'
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
}
}
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')
}
return acts
}
/**
* Environment-aware sleep function.
*/
export async function sleep(ms: number): Promise<void> {
if (isTemporal()) {
await wf.sleep(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: '10 minutes',
})
} else {
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
// 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
}
return original
}
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),
}
}
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: '10 minutes',
taskQueue: queue,
})
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
}
}
+195
View File
@@ -0,0 +1,195 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { prisma } from '@shumai/db'
import { workflowService } from './workflow'
import { WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import { initAgentWorkflows } from '@shumai/agent'
import { initTranscodeWorkflows } from '@shumai/transcode'
import { initDbWorkflows } from '@shumai/worker-db'
vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: {
getObject: vi.fn(),
putObject: vi.fn(),
headObject: vi.fn(),
listObjects: vi.fn().mockResolvedValue([]),
downloadToFile: vi.fn().mockResolvedValue(undefined),
},
}))
vi.mock('@shumai/transcode', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>
return {
...actual,
transcodeService: {
createTempDir: vi.fn().mockReturnValue('/tmp/shumai-test'),
removeDir: vi.fn(),
extractAudio: vi.fn(),
extractVideoFrames: vi.fn().mockResolvedValue([]),
getVideoInfo: vi.fn(),
getImageInfo: vi.fn(),
transcodeVideo: vi.fn(),
transcodeImage: vi.fn(),
generateSprite: vi.fn(),
},
}
})
describe('WorkflowService', () => {
beforeEach(async () => {
initAgentWorkflows()
initTranscodeWorkflows()
initDbWorkflows()
await prisma.workflowTask.deleteMany()
await prisma.assetComment.deleteMany()
await prisma.asset.deleteMany()
vi.clearAllMocks()
workflowService.start()
})
afterEach(() => {
workflowService.close()
})
it('should process ai_embedding task locally', async () => {
const team = await prisma.team.create({
data: { name: 'Embedding Team' },
})
const project = await prisma.project.create({
data: { name: 'Embedding Project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'test.png',
storageKey: { create: { key: 'test/test.png' } },
status: 'uploaded',
type: 'file',
mediaType: 'image/png',
project: { connect: { id: project.id } },
},
})
const task = await prisma.workflowTask.create({
data: {
assetId: asset.id,
type: WorkflowTaskType.ai_embedding,
status: WorkflowTaskStatus.pending,
teamId: team.id,
},
})
// Note: This might fail if AI providers are not configured, but we want to check the workflow flow.
// In a real test environment, we might mock the AI service.
// 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++) {
finishedTask = await prisma.workflowTask.findUnique({
where: { id: task.id },
})
if (
finishedTask?.status === WorkflowTaskStatus.completed ||
finishedTask?.status === WorkflowTaskStatus.failed
) {
break
}
await new Promise((resolve) => setTimeout(resolve, 500))
}
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)
it('should propagate ApplicationFailure correctly in local executor', async () => {
// Creating an ai_embedding task without any embedding agent configured for the team
const team = await prisma.team.create({
data: { name: 'Failure Team' },
})
const project = await prisma.project.create({
data: { name: 'Failure Project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'test.png',
storageKey: { create: { key: 'test/failure-test.png' } },
status: 'uploaded',
type: 'file',
mediaType: 'image/png',
project: { connect: { id: project.id } },
},
})
const task = await prisma.workflowTask.create({
data: {
assetId: asset.id,
type: WorkflowTaskType.ai_embedding,
status: WorkflowTaskStatus.pending,
teamId: team.id,
},
})
let finishedTask = null
for (let i = 0; i < 20; i++) {
finishedTask = await prisma.workflowTask.findUnique({
where: { id: task.id },
})
if (finishedTask?.status === WorkflowTaskStatus.failed) {
break
}
await new Promise((resolve) => setTimeout(resolve, 500))
}
expect(finishedTask?.status).toBe(WorkflowTaskStatus.failed)
expect((finishedTask?.output as Record<string, unknown>)?.error).toBe(
'embedding feature is disabled or agent not found',
)
}, 15000)
it('should not double-submit the task when executeWait is called', async () => {
const team = await prisma.team.create({
data: { name: 'Test Team' },
})
const project = await prisma.project.create({
data: { name: 'Test Project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'test-double.png',
storageKey: { create: { key: 'test/test-double.png' } },
status: 'uploaded',
type: 'file',
mediaType: 'image/png',
project: { connect: { id: project.id } },
},
})
const submitSpy = vi.spyOn(workflowService, 'submit')
const task = await prisma.workflowTask.create({
data: {
assetId: asset.id,
type: WorkflowTaskType.ai_embedding,
status: WorkflowTaskStatus.pending,
teamId: team.id,
},
})
// Wait briefly for the Prisma extension's async import/submit to fire
await new Promise((resolve) => setTimeout(resolve, 100))
expect(submitSpy).toHaveBeenCalledTimes(1)
// Complete the task in the database so executeWait returns immediately
await prisma.workflowTask.update({
where: { id: task.id },
data: { status: 'completed' },
})
await workflowService.executeWait(task)
// Verify it was not submitted a second time by executeWait
expect(submitSpy).toHaveBeenCalledTimes(1)
submitSpy.mockRestore()
})
})
+135
View File
@@ -0,0 +1,135 @@
import { WorkflowTask } from '@shumai/db'
import { Executor } from './executor'
import { LocalExecutor } from './local-executor'
import { TemporalExecutor } from './temporal-executor'
import { prisma, registerWorkflowTrigger } from '@shumai/db'
export class WorkflowService {
private executor: Executor
constructor() {
const type = process.env.WORKFLOW_EXECUTOR || 'local'
if (type === 'temporal') {
this.executor = new TemporalExecutor(process.env.TEMPORAL_ADDRESS)
} else {
this.executor = new LocalExecutor()
}
}
async submit(task: WorkflowTask): Promise<string> {
return this.executor.submit(task)
}
async executeWait(task: WorkflowTask, timeoutMs: number = 30000): Promise<WorkflowTask> {
const start = Date.now()
while (Date.now() - start < timeoutMs) {
const updatedTask = await prisma.workflowTask.findUnique({
where: { id: task.id },
})
if (!updatedTask) {
throw new Error(`WorkflowTask ${task.id} not found`)
}
if (updatedTask.status === 'completed') {
return updatedTask
}
if (updatedTask.status === 'failed') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const error = (updatedTask.output as any)?.error || 'Workflow task failed'
throw new Error(error)
}
await new Promise((resolve) => setTimeout(resolve, 500))
}
throw new Error('Workflow task timed out')
}
start(): void {
this.executor.start()
}
close(): void {
this.executor.close()
}
// Starts Temporal workers for specific task queues
async startWorkers(
queue: string = 'db_queue',
options?: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
workflowBundle?: any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
activities?: any
},
): Promise<void> {
const type = process.env.WORKFLOW_EXECUTOR || '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 = options?.activities || (globalThis as any).__localActivities
const workflowBundle = options?.workflowBundle
if (queue === 'db_queue') {
console.log(`Starting Temporal worker for queue: ${queue}`)
const worker = await Worker.create({
connection,
workflowBundle,
activities,
taskQueue: queue,
})
await worker.run()
return
}
// For agent_queue and transcode_queue, use worker-specific unique queues
const crypto = await import('crypto')
const workerId = crypto.randomUUID()
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 sharedWorker = await Worker.create({
connection,
workflowBundle,
activities: sharedActivities,
taskQueue: queue,
})
const specificWorker = await Worker.create({
connection,
// No workflows needed for the unique queue
activities,
taskQueue: workerSpecificQueue,
})
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.`,
)
}
}
}
export const workflowService = new WorkflowService()
registerWorkflowTrigger(async (task) => {
await workflowService.submit(task)
})