mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 11:24:43 +00:00
refactor(workflow): simplify activities to use defineStep and direct calls (#482)
* refactor(workflow): simplify activities to use defineStep and direct calls - Wrap activities using defineStep from @shumai/workflow-core - Remove obsolete getActivities, registerActivities, dynamic activity proxies, and workerQueue arguments - Remove executor.ts and registry.ts, consolidating workflow registration into workflow.ts - Call activities directly across transcode and agent workflows - Update all corresponding workflow tests and developer guide documentation * fix(workflow): properly detect DBOSWorkflowCancelledError in runOnCancel fallback - DBOSWorkflowCancelledError in DBOS SDK does not set name, inheriting 'Error' - Implement isDbosWorkflowCancelledError checking instanceof, constructor.name, and dbosErrorCode - Update unit tests to verify real DBOS SDK cancellation error instances
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { WorkflowTaskStatus, AssetStatus, AssetType, Prisma } from '@shumai/db'
|
||||
import { defineStep } from '../workflow-utils'
|
||||
|
||||
export async function getAssetStatusActivity(params: {
|
||||
export const getAssetStatusActivity = defineStep(async function getAssetStatusActivity(params: {
|
||||
assetId: string
|
||||
}): Promise<AssetStatus | null> {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
@@ -9,9 +10,9 @@ export async function getAssetStatusActivity(params: {
|
||||
select: { status: true },
|
||||
})
|
||||
return asset?.status || null
|
||||
}
|
||||
})
|
||||
|
||||
export async function getAssetActivity(assetId: string) {
|
||||
export const getAssetActivity = defineStep(async function getAssetActivity(assetId: string) {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
include: {
|
||||
@@ -53,7 +54,7 @@ export async function getAssetActivity(assetId: string) {
|
||||
...asset,
|
||||
sizeByte: Number(asset.sizeByte),
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface UpdateTaskStatusParams {
|
||||
taskId: string
|
||||
@@ -61,15 +62,18 @@ export interface UpdateTaskStatusParams {
|
||||
output?: unknown
|
||||
}
|
||||
|
||||
export async function updateTaskStatusActivity(params: UpdateTaskStatusParams): Promise<void> {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
status: params.status,
|
||||
output: params.output as Prisma.InputJsonValue,
|
||||
},
|
||||
})
|
||||
}
|
||||
export const updateTaskStatusActivity = defineStep(
|
||||
async function updateTaskStatusActivity(params: UpdateTaskStatusParams): Promise<void> {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
status: params.status,
|
||||
output: params.output as Prisma.InputJsonValue,
|
||||
},
|
||||
})
|
||||
},
|
||||
{ runOnCancel: true },
|
||||
)
|
||||
|
||||
export interface UpdateAssetStatusParams {
|
||||
assetId: string
|
||||
@@ -77,36 +81,39 @@ export interface UpdateAssetStatusParams {
|
||||
error?: string
|
||||
}
|
||||
|
||||
export async function updateAssetStatusActivity(params: UpdateAssetStatusParams): Promise<void> {
|
||||
if (params.status === AssetStatus.failed) {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
select: { media: true, status: true },
|
||||
})
|
||||
// Never overwrite an asset that has already completed media processing
|
||||
if (asset?.status === AssetStatus.processed) {
|
||||
export const updateAssetStatusActivity = defineStep(
|
||||
async function updateAssetStatusActivity(params: UpdateAssetStatusParams): Promise<void> {
|
||||
if (params.status === AssetStatus.failed) {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
select: { media: true, status: true },
|
||||
})
|
||||
// Never overwrite an asset that has already completed media processing
|
||||
if (asset?.status === AssetStatus.processed) {
|
||||
return
|
||||
}
|
||||
const data: Prisma.AssetUpdateInput = { status: params.status }
|
||||
if (params.error !== undefined) {
|
||||
const existingMedia = (asset?.media as PrismaJson.MediaInfo | null) || {}
|
||||
data.media = {
|
||||
...existingMedia,
|
||||
error: params.error.slice(0, 500),
|
||||
} as PrismaJson.MediaInfo
|
||||
}
|
||||
await prisma.asset.updateMany({
|
||||
where: { id: params.assetId, isDeleted: false, status: { not: AssetStatus.processed } },
|
||||
data,
|
||||
})
|
||||
return
|
||||
}
|
||||
const data: Prisma.AssetUpdateInput = { status: params.status }
|
||||
if (params.error !== undefined) {
|
||||
const existingMedia = (asset?.media as PrismaJson.MediaInfo | null) || {}
|
||||
data.media = {
|
||||
...existingMedia,
|
||||
error: params.error.slice(0, 500),
|
||||
} as PrismaJson.MediaInfo
|
||||
}
|
||||
await prisma.asset.updateMany({
|
||||
where: { id: params.assetId, isDeleted: false, status: { not: AssetStatus.processed } },
|
||||
data,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
await prisma.asset.updateMany({
|
||||
where: { id: params.assetId, isDeleted: false },
|
||||
data: { status: params.status },
|
||||
})
|
||||
}
|
||||
await prisma.asset.updateMany({
|
||||
where: { id: params.assetId, isDeleted: false },
|
||||
data: { status: params.status },
|
||||
})
|
||||
},
|
||||
{ runOnCancel: true },
|
||||
)
|
||||
|
||||
export interface UpdateTaskUsageParams {
|
||||
taskId: string
|
||||
@@ -115,7 +122,9 @@ export interface UpdateTaskUsageParams {
|
||||
model: string
|
||||
}
|
||||
|
||||
export async function updateTaskUsageActivity(params: UpdateTaskUsageParams): Promise<void> {
|
||||
export const updateTaskUsageActivity = defineStep(async function updateTaskUsageActivity(
|
||||
params: UpdateTaskUsageParams,
|
||||
): Promise<void> {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
@@ -124,7 +133,7 @@ export async function updateTaskUsageActivity(params: UpdateTaskUsageParams): Pr
|
||||
model: params.model,
|
||||
},
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
export interface UpdateWorkflowTaskParams {
|
||||
taskId: string
|
||||
@@ -136,16 +145,19 @@ export interface UpdateWorkflowTaskParams {
|
||||
model?: string | null
|
||||
}
|
||||
|
||||
export async function updateWorkflowTaskActivity(params: UpdateWorkflowTaskParams): Promise<void> {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
...(params.status !== undefined ? { status: params.status } : {}),
|
||||
...(params.heartbeat ? { heartbeat: new Date() } : {}),
|
||||
...(params.output !== undefined ? { output: params.output as Prisma.InputJsonValue } : {}),
|
||||
...(params.inputTokens !== undefined ? { inputTokens: params.inputTokens } : {}),
|
||||
...(params.outputTokens !== undefined ? { outputTokens: params.outputTokens } : {}),
|
||||
...(params.model !== undefined ? { model: params.model } : {}),
|
||||
},
|
||||
})
|
||||
}
|
||||
export const updateWorkflowTaskActivity = defineStep(
|
||||
async function updateWorkflowTaskActivity(params: UpdateWorkflowTaskParams): Promise<void> {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
...(params.status !== undefined ? { status: params.status } : {}),
|
||||
...(params.heartbeat ? { heartbeat: new Date() } : {}),
|
||||
...(params.output !== undefined ? { output: params.output as Prisma.InputJsonValue } : {}),
|
||||
...(params.inputTokens !== undefined ? { inputTokens: params.inputTokens } : {}),
|
||||
...(params.outputTokens !== undefined ? { outputTokens: params.outputTokens } : {}),
|
||||
...(params.model !== undefined ? { model: params.model } : {}),
|
||||
},
|
||||
})
|
||||
},
|
||||
{ runOnCancel: true },
|
||||
)
|
||||
|
||||
@@ -2,8 +2,6 @@ import os from 'node:os'
|
||||
import { DBOS, DBOSClient } 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,
|
||||
@@ -14,6 +12,17 @@ import {
|
||||
unregisterLocalTaskAbortController,
|
||||
} from './workflow-utils'
|
||||
|
||||
export type WorkflowFn = (task: WorkflowTask) => Promise<void>
|
||||
const workflowRegistry = new Map<string, WorkflowFn>()
|
||||
|
||||
export function registerWorkflow(type: string, fn: WorkflowFn): void {
|
||||
workflowRegistry.set(type, fn)
|
||||
}
|
||||
|
||||
export function getRegisteredWorkflows(): Map<string, WorkflowFn> {
|
||||
return workflowRegistry
|
||||
}
|
||||
|
||||
export function getDbosDatabaseUrl(rawUrl?: string): string {
|
||||
const urlStr =
|
||||
rawUrl || process.env.DATABASE_URL || 'postgresql://postgres:postgres@localhost:5432/shumai'
|
||||
@@ -54,7 +63,7 @@ export function getQueueForTaskType(type: string | null | undefined): string {
|
||||
let dbosMigrationsRan = false
|
||||
const registeredDbosWorkflowNames = new Set<string>()
|
||||
|
||||
export class DbosExecutor implements Executor {
|
||||
export class DbosExecutor {
|
||||
private launchPromise: Promise<void> | null = null
|
||||
private started = false
|
||||
private client: DBOSClient | null = null
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
import { WorkflowTask } from '@shumai/db'
|
||||
|
||||
export interface Executor {
|
||||
submit(task: WorkflowTask): Promise<string>
|
||||
cancel?(taskId: string): Promise<void>
|
||||
start(): void
|
||||
close(): void
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
export * from './executor'
|
||||
export * from './dbos-executor'
|
||||
export * from './registry'
|
||||
export * from './workflow-utils'
|
||||
export * from './workflow'
|
||||
export * from './activities/task'
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
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,60 +1,42 @@
|
||||
import { describe, it, expect, vi, beforeAll } from 'vitest'
|
||||
import { DBOS } from '@dbos-inc/dbos-sdk'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { DBOS, Error as DBOSError } from '@dbos-inc/dbos-sdk'
|
||||
import {
|
||||
getActivities,
|
||||
executeActivity,
|
||||
defineStep,
|
||||
WorkflowFailure,
|
||||
ApplicationFailure,
|
||||
isNonRetryableError,
|
||||
isDbosWorkflowCancelledError,
|
||||
sleep,
|
||||
getLocalTaskAbortSignal,
|
||||
registerLocalTaskAbortController,
|
||||
unregisterLocalTaskAbortController,
|
||||
} from './workflow-utils'
|
||||
|
||||
describe('workflow-utils executeActivity and DBOS steps', () => {
|
||||
beforeAll(() => {
|
||||
// Inject mock activities for execution tests
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(globalThis as any).__localActivities = {
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
describe('workflow-utils defineStep and DBOS steps', () => {
|
||||
it('should preserve function name by default or use custom name', () => {
|
||||
async function sampleActivity(arg: string) {
|
||||
return `result-${arg}`
|
||||
}
|
||||
})
|
||||
const step1 = defineStep(sampleActivity)
|
||||
expect(step1.name).toBe('sampleActivity')
|
||||
|
||||
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')
|
||||
const step2 = defineStep(async () => 'ok', { name: 'customName' })
|
||||
expect(step2.name).toBe('customName')
|
||||
})
|
||||
|
||||
it('should execute the function directly when outside DBOS workflow context', async () => {
|
||||
const mockFn = vi.fn().mockResolvedValue('success-result')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(mockFn as any)._activityName = 'mockActivity'
|
||||
const step = defineStep(mockFn, { name: 'mockStep' })
|
||||
|
||||
const result = await executeActivity(
|
||||
'test-queue',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
mockFn as any,
|
||||
{ some: 'args' },
|
||||
)
|
||||
const result = await step({ some: 'args' })
|
||||
|
||||
expect(mockFn).toHaveBeenCalledWith({ some: 'args' })
|
||||
expect(result).toBe('success-result')
|
||||
})
|
||||
|
||||
it('should throw error if function does not have _activityName', async () => {
|
||||
const normalFn = async () => {}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await expect(executeActivity('queue', normalFn as any)).rejects.toThrow(
|
||||
'executeActivity must be called with an activity function obtained from getActivities()',
|
||||
)
|
||||
})
|
||||
|
||||
it('should execute via DBOS.runStep when within workflow context', async () => {
|
||||
const mockFn = vi.fn().mockResolvedValue('step-success')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(mockFn as any)._activityName = 'myStepActivity'
|
||||
const step = defineStep(mockFn, { name: 'myStepActivity' })
|
||||
|
||||
const isWithinWorkflowSpy = vi.spyOn(DBOS, 'isWithinWorkflow').mockReturnValue(true)
|
||||
const runStepSpy = vi
|
||||
@@ -62,8 +44,7 @@ describe('workflow-utils executeActivity and DBOS steps', () => {
|
||||
// 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')
|
||||
const result = await step('step-arg')
|
||||
|
||||
expect(runStepSpy).toHaveBeenCalledWith(
|
||||
expect.any(Function),
|
||||
@@ -79,6 +60,41 @@ describe('workflow-utils executeActivity and DBOS steps', () => {
|
||||
runStepSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('should execute cleanup fallback if cancelled with DBOSWorkflowCancelledError and runOnCancel is true', async () => {
|
||||
const mockFn = vi.fn().mockResolvedValue('cleanup-done')
|
||||
const step = defineStep(mockFn, { name: 'cleanupStep', runOnCancel: true })
|
||||
|
||||
// SDK's real DBOSWorkflowCancelledError does not set err.name (err.name is 'Error')
|
||||
const realCancelErr = new DBOSError.DBOSWorkflowCancelledError('test-workflow-id')
|
||||
expect(realCancelErr.name).toBe('Error')
|
||||
|
||||
const isWithinWorkflowSpy = vi.spyOn(DBOS, 'isWithinWorkflow').mockReturnValue(true)
|
||||
const runStepSpy = vi.spyOn(DBOS, 'runStep').mockRejectedValue(realCancelErr)
|
||||
|
||||
const result = await step('arg')
|
||||
|
||||
expect(result).toBe('cleanup-done')
|
||||
expect(mockFn).toHaveBeenCalledWith('arg')
|
||||
|
||||
isWithinWorkflowSpy.mockRestore()
|
||||
runStepSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('should correctly identify DBOS workflow cancellation errors', () => {
|
||||
const realCancelErr = new DBOSError.DBOSWorkflowCancelledError('wf-1')
|
||||
expect(isDbosWorkflowCancelledError(realCancelErr)).toBe(true)
|
||||
|
||||
const duckTypedErr = { name: 'DBOSWorkflowCancelledError' }
|
||||
expect(isDbosWorkflowCancelledError(duckTypedErr)).toBe(true)
|
||||
|
||||
const codeErr = { dbosErrorCode: 24 }
|
||||
expect(isDbosWorkflowCancelledError(codeErr)).toBe(true)
|
||||
|
||||
expect(isDbosWorkflowCancelledError(new Error('other error'))).toBe(false)
|
||||
expect(isDbosWorkflowCancelledError(null)).toBe(false)
|
||||
expect(isDbosWorkflowCancelledError(undefined)).toBe(false)
|
||||
})
|
||||
|
||||
describe('WorkflowFailure / ApplicationFailure', () => {
|
||||
it('should correctly configure nonRetryable errors', () => {
|
||||
const err = WorkflowFailure.create({ message: 'fatal error', nonRetryable: true })
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { DBOS } from '@dbos-inc/dbos-sdk'
|
||||
import { DBOS, Error as DBOSError } from '@dbos-inc/dbos-sdk'
|
||||
|
||||
/**
|
||||
* Task queue constants.
|
||||
@@ -36,37 +36,27 @@ export function isNonRetryableError(err: unknown): boolean {
|
||||
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
|
||||
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 */
|
||||
|
||||
function localActivitiesProxy(): Record<string, unknown> {
|
||||
const acts = globalObj.__localActivities
|
||||
if (!acts) {
|
||||
throw new Error('Local activities not injected into globalThis.__localActivities')
|
||||
export function isDbosWorkflowCancelledError(err: unknown): boolean {
|
||||
if (!err || typeof err !== 'object') {
|
||||
return false
|
||||
}
|
||||
return acts
|
||||
if (err instanceof DBOSError.DBOSWorkflowCancelledError) {
|
||||
return true
|
||||
}
|
||||
const errorObj = err as {
|
||||
name?: unknown
|
||||
constructor?: { name?: unknown }
|
||||
dbosErrorCode?: unknown
|
||||
}
|
||||
return (
|
||||
errorObj.name === 'DBOSWorkflowCancelledError' ||
|
||||
errorObj.constructor?.name === 'DBOSWorkflowCancelledError' ||
|
||||
errorObj.dbosErrorCode === 24
|
||||
)
|
||||
}
|
||||
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
|
||||
/**
|
||||
* Environment-aware sleep function. Uses DBOS.sleepms in workflow context.
|
||||
*/
|
||||
@@ -78,124 +68,63 @@ export async function sleep(ms: number): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
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
|
||||
// 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)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function getLogger(): LocalLogger | Console {
|
||||
return globalObj.__localLogger || console
|
||||
export interface StepOptions {
|
||||
name?: string
|
||||
runOnCancel?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* Wraps an activity function so that when invoked within a DBOS workflow, it executes
|
||||
* as a durable checkpointed step with retries, timeout, and cancellation handling.
|
||||
* When called outside a workflow (e.g. in unit tests), it invokes the underlying function directly.
|
||||
*/
|
||||
// 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()',
|
||||
)
|
||||
}
|
||||
export function defineStep<TArgs extends unknown[], TRet>(
|
||||
fn: (...args: TArgs) => Promise<TRet>,
|
||||
options?: StepOptions,
|
||||
): (...args: TArgs) => Promise<TRet> {
|
||||
const stepName = options?.name || fn.name || 'anonymousStep'
|
||||
const runOnCancel = options?.runOnCancel ?? false
|
||||
|
||||
const logger = getLogger()
|
||||
logger.debug({ queue, activityName }, `Executing activity ${activityName} on queue ${queue}`)
|
||||
const wrapped = async (...args: TArgs): Promise<TRet> => {
|
||||
logger.debug({ activityName: stepName }, `Executing step ${stepName}`)
|
||||
|
||||
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 (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
|
||||
try {
|
||||
let result: TRet
|
||||
if (DBOS.isWithinWorkflow()) {
|
||||
try {
|
||||
result = await DBOS.runStep(() => fn(...args), {
|
||||
name: stepName,
|
||||
retriesAllowed: true,
|
||||
maxAttempts: 5,
|
||||
intervalSeconds: process.env.NODE_ENV === 'test' ? 1 : 10,
|
||||
backoffRate: 2,
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS StepOptions property name
|
||||
timeoutMS: 120 * 60 * 1000,
|
||||
shouldRetry: (err) => !isNonRetryableError(err),
|
||||
})
|
||||
} catch (stepErr) {
|
||||
if (runOnCancel && isDbosWorkflowCancelledError(stepErr)) {
|
||||
result = await fn(...args)
|
||||
} else {
|
||||
throw stepErr
|
||||
}
|
||||
}
|
||||
} else {
|
||||
result = await fn(...args)
|
||||
}
|
||||
} else {
|
||||
result = await activityFunc(...args)
|
||||
logger.debug({ activityName: stepName }, `Step ${stepName} completed successfully`)
|
||||
return result
|
||||
} catch (err) {
|
||||
logger.error(
|
||||
{ activityName: stepName, err },
|
||||
`Step ${stepName} failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
)
|
||||
throw err
|
||||
}
|
||||
logger.debug(
|
||||
{ queue, activityName },
|
||||
`Activity ${activityName} completed successfully on queue ${queue}`,
|
||||
)
|
||||
return result
|
||||
} catch (err) {
|
||||
logger.error(
|
||||
{ queue, activityName, err },
|
||||
`Activity ${activityName} failed on queue ${queue}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
)
|
||||
throw err
|
||||
}
|
||||
|
||||
Object.defineProperty(wrapped, 'name', { value: stepName })
|
||||
return wrapped
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { prisma, registerWorkflowCancel, registerWorkflowTrigger, WorkflowTask } from '@shumai/db'
|
||||
import { DbosExecutor } from './dbos-executor'
|
||||
import { getRegisteredWorkflows } from './registry'
|
||||
import { DbosExecutor, getRegisteredWorkflows } from './dbos-executor'
|
||||
|
||||
export class WorkflowService {
|
||||
private executor: DbosExecutor
|
||||
@@ -13,11 +12,6 @@ export class WorkflowService {
|
||||
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> {
|
||||
return this.executor.submit(task)
|
||||
}
|
||||
@@ -81,11 +75,7 @@ export class WorkflowService {
|
||||
}
|
||||
|
||||
// Starts DBOS worker for specific task queue(s)
|
||||
async startWorkers(
|
||||
queue: string | string[],
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
_options: { workflowBundle?: unknown; workflowsPath?: string } = {},
|
||||
): Promise<void> {
|
||||
async startWorkers(queue: string | string[]): Promise<void> {
|
||||
const queues = Array.isArray(queue) ? queue : [queue]
|
||||
console.log(`Starting DBOS worker for queue(s): ${queues.join(', ')}`)
|
||||
this.executor.setListenQueues(queues)
|
||||
|
||||
Reference in New Issue
Block a user