mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-02 05:54:44 +00:00
feat(deploy): implement KEDA ScaledJob and scale-to-zero On-Demand transcoding
This commit is contained in:
@@ -68,7 +68,7 @@ export const updateTaskStatusActivity = defineStep(
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
status: params.status,
|
||||
output: params.output as Prisma.InputJsonValue,
|
||||
output: params.output as PrismaJson.WorkflowTaskOutput,
|
||||
},
|
||||
})
|
||||
},
|
||||
@@ -152,7 +152,9 @@ export const updateWorkflowTaskActivity = defineStep(
|
||||
data: {
|
||||
...(params.status !== undefined ? { status: params.status } : {}),
|
||||
...(params.heartbeat ? { heartbeat: new Date() } : {}),
|
||||
...(params.output !== undefined ? { output: params.output as Prisma.InputJsonValue } : {}),
|
||||
...(params.output !== undefined
|
||||
? { output: params.output as PrismaJson.WorkflowTaskOutput }
|
||||
: {}),
|
||||
...(params.inputTokens !== undefined ? { inputTokens: params.inputTokens } : {}),
|
||||
...(params.outputTokens !== undefined ? { outputTokens: params.outputTokens } : {}),
|
||||
...(params.model !== undefined ? { model: params.model } : {}),
|
||||
|
||||
@@ -133,18 +133,8 @@ describe('DbosExecutor Tests', () => {
|
||||
})
|
||||
|
||||
it('should only update queues the worker listens to or configures, leaving unmanaged queues untouched', async () => {
|
||||
// Step 1: Agent worker sets agent concurrency to 1
|
||||
process.env.CONCURRENCY_AGENT = '1'
|
||||
const agentWorker = new DbosExecutor([TaskQueueAgent])
|
||||
agentWorker.start()
|
||||
await agentWorker.ensureLaunched()
|
||||
const registerQueueSpy = vi.spyOn(DBOS, 'registerQueue')
|
||||
|
||||
const agentQueue = await DBOS.retrieveQueue(TaskQueueAgent)
|
||||
expect(agentQueue?.workerConcurrency).toBe(1)
|
||||
await agentWorker.shutdown()
|
||||
|
||||
// Step 2: Dedicated transcode worker starts with transcode concurrency = 3 and unconfigured agent env
|
||||
delete process.env.CONCURRENCY_AGENT
|
||||
process.env.CONCURRENCY_TRANSCODE = '3'
|
||||
const transcodeWorker = new DbosExecutor([TaskQueueTranscode])
|
||||
try {
|
||||
@@ -152,12 +142,15 @@ describe('DbosExecutor Tests', () => {
|
||||
await transcodeWorker.ensureLaunched()
|
||||
|
||||
const transcodeQueue = await DBOS.retrieveQueue(TaskQueueTranscode)
|
||||
const agentQueueAfter = await DBOS.retrieveQueue(TaskQueueAgent)
|
||||
|
||||
expect(transcodeQueue?.workerConcurrency).toBe(3)
|
||||
// Agent queue should still be 1, NOT overwritten by default 5
|
||||
expect(agentQueueAfter?.workerConcurrency).toBe(1)
|
||||
|
||||
// transcodeWorker should only have registered TaskQueueTranscode, not unmanaged queues like TaskQueueAgent
|
||||
const registeredQueueNames = registerQueueSpy.mock.calls.map((call) => call[0])
|
||||
expect(registeredQueueNames).toContain(TaskQueueTranscode)
|
||||
expect(registeredQueueNames).not.toContain(TaskQueueAgent)
|
||||
} finally {
|
||||
registerQueueSpy.mockRestore()
|
||||
delete process.env.CONCURRENCY_TRANSCODE
|
||||
await transcodeWorker.shutdown()
|
||||
}
|
||||
})
|
||||
@@ -390,4 +383,95 @@ describe('DbosExecutor Tests', () => {
|
||||
expect(mockClient.enqueue).toHaveBeenCalled()
|
||||
}, 15000)
|
||||
})
|
||||
|
||||
describe('Once mode, events, and conflict handling', () => {
|
||||
it('should force concurrency to 1 in onceMode', () => {
|
||||
executor.setOnceMode(true)
|
||||
expect(executor.isOnceMode()).toBe(true)
|
||||
expect(executor.getTranscodeConcurrencyLimit()).toBe(1)
|
||||
})
|
||||
|
||||
it('should emit workflowStarted and workflowFinished events during execution', async () => {
|
||||
let startedTask: WorkflowTask | null = null
|
||||
let finishedPayload: { taskId: string; success: boolean } | null = null
|
||||
|
||||
executor.on('workflowStarted', (task) => {
|
||||
startedTask = task
|
||||
})
|
||||
executor.on('workflowFinished', (payload) => {
|
||||
finishedPayload = payload
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const wrapper = (executor as any).createDbosWorkflowWrapper('test-events-workflow')
|
||||
const { registerWorkflow } = await import('./dbos-executor')
|
||||
registerWorkflow('test-events-workflow', async () => {
|
||||
// do work
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
id: 'test-events-task',
|
||||
assetId: 'asset-events',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
await wrapper(task)
|
||||
|
||||
expect(startedTask).toBeDefined()
|
||||
expect((startedTask as WorkflowTask | null)?.id).toBe('test-events-task')
|
||||
expect(finishedPayload).toBeDefined()
|
||||
expect((finishedPayload as { taskId: string; success: boolean } | null)?.taskId).toBe(
|
||||
'test-events-task',
|
||||
)
|
||||
expect((finishedPayload as { taskId: string; success: boolean } | null)?.success).toBe(true)
|
||||
})
|
||||
|
||||
it('should handle DBOSWorkflowConflictError without marking task failed', async () => {
|
||||
const { DBOSWorkflowConflictError: DbosWorkflowConflictError } =
|
||||
await import('@dbos-inc/dbos-sdk')
|
||||
const { registerWorkflow } = await import('./dbos-executor')
|
||||
|
||||
registerWorkflow('test-conflict-workflow', async () => {
|
||||
throw new DbosWorkflowConflictError('test-conflict-task')
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const wrapper = (executor as any).createDbosWorkflowWrapper('test-conflict-workflow')
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
id: 'test-conflict-task',
|
||||
assetId: 'asset-conflict',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
await expect(wrapper(task)).rejects.toThrow('is no longer owned by this execution')
|
||||
|
||||
const updatedTask = await prisma.workflowTask.findUnique({
|
||||
where: { id: 'test-conflict-task' },
|
||||
})
|
||||
// Task should NOT be marked as failed!
|
||||
expect(updatedTask?.status).not.toBe(WorkflowTaskStatus.failed)
|
||||
})
|
||||
|
||||
it('should pass workflowCompletionTimeoutMs to DBOS.shutdown', async () => {
|
||||
const shutdownSpy = vi.spyOn(DBOS, 'shutdown').mockResolvedValue(undefined)
|
||||
const isInitSpy = vi.spyOn(DBOS, 'isInitialized').mockReturnValue(true)
|
||||
|
||||
await executor.shutdown({ workflowCompletionTimeoutMs: 290000 })
|
||||
|
||||
expect(shutdownSpy).toHaveBeenCalledWith({
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS SDK parameter name
|
||||
workflowCompletionTimeoutMS: 290000,
|
||||
})
|
||||
|
||||
shutdownSpy.mockRestore()
|
||||
isInitSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import EventEmitter from 'node:events'
|
||||
import os from 'node:os'
|
||||
import { DBOS, DBOSClient } from '@dbos-inc/dbos-sdk'
|
||||
import { DBOS, DBOSClient, DBOSWorkflowConflictError } from '@dbos-inc/dbos-sdk'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { prisma, WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import {
|
||||
@@ -12,6 +13,22 @@ import {
|
||||
unregisterLocalTaskAbortController,
|
||||
} from './workflow-utils'
|
||||
|
||||
export function isWorkflowConflictError(err: unknown): boolean {
|
||||
if (err instanceof DBOSWorkflowConflictError) return true
|
||||
if (
|
||||
err &&
|
||||
typeof err === 'object' &&
|
||||
'dbosErrorCode' in err &&
|
||||
(err as { dbosErrorCode: unknown }).dbosErrorCode === 5
|
||||
) {
|
||||
return true
|
||||
}
|
||||
if (err instanceof Error && err.message.includes('is no longer owned by this execution')) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export type WorkflowFn = (task: WorkflowTask) => Promise<void>
|
||||
const workflowRegistry = new Map<string, WorkflowFn>()
|
||||
|
||||
@@ -63,7 +80,7 @@ export function getQueueForTaskType(type: string | null | undefined): string {
|
||||
let dbosMigrationsRan = false
|
||||
const registeredDbosWorkflowNames = new Set<string>()
|
||||
|
||||
export class DbosExecutor {
|
||||
export class DbosExecutor extends EventEmitter {
|
||||
private launchPromise: Promise<void> | null = null
|
||||
private started = false
|
||||
private client: DBOSClient | null = null
|
||||
@@ -72,8 +89,10 @@ export class DbosExecutor {
|
||||
private inFlightSubmits = new Set<Promise<string>>()
|
||||
private executorId?: string
|
||||
private instanceSuffix = Math.random().toString(36).slice(2, 8)
|
||||
private onceMode = false
|
||||
|
||||
constructor(listenQueues?: string[], executorId?: string) {
|
||||
super()
|
||||
if (listenQueues) {
|
||||
this.listenQueues = listenQueues
|
||||
}
|
||||
@@ -82,6 +101,14 @@ export class DbosExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
setOnceMode(once: boolean): void {
|
||||
this.onceMode = once
|
||||
}
|
||||
|
||||
isOnceMode(): boolean {
|
||||
return this.onceMode
|
||||
}
|
||||
|
||||
isStarted(): boolean {
|
||||
return this.started
|
||||
}
|
||||
@@ -91,6 +118,7 @@ export class DbosExecutor {
|
||||
}
|
||||
|
||||
getTranscodeConcurrencyLimit(): number {
|
||||
if (this.onceMode) return 1
|
||||
return getConcurrencyLimit(process.env.CONCURRENCY_TRANSCODE, 1)
|
||||
}
|
||||
|
||||
@@ -116,6 +144,7 @@ export class DbosExecutor {
|
||||
if (!fn) {
|
||||
throw new Error(`No workflow registered for type: ${type}`)
|
||||
}
|
||||
this.emit('workflowStarted', task)
|
||||
// Mark task as processing and start heartbeat
|
||||
try {
|
||||
await prisma.workflowTask.updateMany({
|
||||
@@ -151,11 +180,20 @@ export class DbosExecutor {
|
||||
const abortController = new AbortController()
|
||||
registerLocalTaskAbortController(task.id, abortController)
|
||||
|
||||
let workflowError: unknown
|
||||
try {
|
||||
await runInLocalTaskContext({ taskId: task.id, abortController }, async () => {
|
||||
await fn(task)
|
||||
})
|
||||
} catch (err) {
|
||||
workflowError = err
|
||||
if (isWorkflowConflictError(err)) {
|
||||
logger.warn(
|
||||
{ taskId: task.id, type, err },
|
||||
'[DbosExecutor] Workflow execution superseded (ownership lost or conflict). Skipping marking task as failed.',
|
||||
)
|
||||
throw err
|
||||
}
|
||||
logger.error({ taskId: task.id, type, err }, `[DbosExecutor] Error in workflow ${type}`)
|
||||
try {
|
||||
await prisma.workflowTask.updateMany({
|
||||
@@ -176,6 +214,12 @@ export class DbosExecutor {
|
||||
clearInterval(heartbeatInterval)
|
||||
this.heartbeatIntervals.delete(task.id)
|
||||
unregisterLocalTaskAbortController(task.id)
|
||||
this.emit('workflowFinished', {
|
||||
taskId: task.id,
|
||||
type,
|
||||
success: !workflowError,
|
||||
error: workflowError,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -366,14 +410,17 @@ export class DbosExecutor {
|
||||
close(): void {
|
||||
this.started = false
|
||||
this.waitForPendingSubmissions().catch(() => {})
|
||||
for (const timer of this.heartbeatIntervals.values()) {
|
||||
clearInterval(timer)
|
||||
}
|
||||
this.heartbeatIntervals.clear()
|
||||
if (this.client) {
|
||||
this.client.destroy().catch(() => {})
|
||||
this.client = null
|
||||
const cleanupResources = () => {
|
||||
for (const timer of this.heartbeatIntervals.values()) {
|
||||
clearInterval(timer)
|
||||
}
|
||||
this.heartbeatIntervals.clear()
|
||||
if (this.client) {
|
||||
this.client.destroy().catch(() => {})
|
||||
this.client = null
|
||||
}
|
||||
}
|
||||
|
||||
if (DBOS.isInitialized()) {
|
||||
DBOS.shutdown()
|
||||
.then(() => {
|
||||
@@ -382,23 +429,43 @@ export class DbosExecutor {
|
||||
.catch((err) => {
|
||||
logger.warn({ err }, '[DbosExecutor] Error during DBOS shutdown')
|
||||
})
|
||||
.finally(cleanupResources)
|
||||
} else {
|
||||
cleanupResources()
|
||||
}
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
async shutdown(options?: { workflowCompletionTimeoutMs?: number }): Promise<void> {
|
||||
this.started = false
|
||||
await this.waitForPendingSubmissions()
|
||||
for (const timer of this.heartbeatIntervals.values()) {
|
||||
clearInterval(timer)
|
||||
}
|
||||
this.heartbeatIntervals.clear()
|
||||
if (this.client) {
|
||||
await this.client.destroy().catch(() => {})
|
||||
this.client = null
|
||||
}
|
||||
if (DBOS.isInitialized()) {
|
||||
await DBOS.shutdown()
|
||||
this.launchPromise = null
|
||||
|
||||
const timeoutMs =
|
||||
options?.workflowCompletionTimeoutMs ??
|
||||
(process.env.SHUMAI_WORKER_DRAIN_TIMEOUT_MS
|
||||
? parseInt(process.env.SHUMAI_WORKER_DRAIN_TIMEOUT_MS, 10)
|
||||
: undefined)
|
||||
|
||||
try {
|
||||
if (DBOS.isInitialized()) {
|
||||
await DBOS.shutdown(
|
||||
timeoutMs !== undefined
|
||||
? {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS SDK parameter name
|
||||
workflowCompletionTimeoutMS: timeoutMs,
|
||||
}
|
||||
: undefined,
|
||||
)
|
||||
this.launchPromise = null
|
||||
}
|
||||
} finally {
|
||||
for (const timer of this.heartbeatIntervals.values()) {
|
||||
clearInterval(timer)
|
||||
}
|
||||
this.heartbeatIntervals.clear()
|
||||
if (this.client) {
|
||||
await this.client.destroy().catch(() => {})
|
||||
this.client = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,4 +188,144 @@ describe('WorkflowService', () => {
|
||||
|
||||
submitSpy.mockRestore()
|
||||
})
|
||||
|
||||
describe('Stale Task Recovery', () => {
|
||||
it('should resume stale pending workflow task in DBOS and increment recoveryAttempts', async () => {
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'stale-asset-1',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: new Date(Date.now() - 100_000), // 100s ago
|
||||
},
|
||||
})
|
||||
|
||||
const mockClient = {
|
||||
retrieveWorkflow: vi.fn().mockReturnValue({
|
||||
getStatus: vi.fn().mockResolvedValue({ status: 'PENDING' }),
|
||||
}),
|
||||
resumeWorkflow: vi.fn().mockResolvedValue(undefined),
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.spyOn(workflowService.getExecutor(), 'getClient').mockResolvedValue(mockClient as any)
|
||||
|
||||
const recoveredCount = await workflowService.recoverStaleTasks({
|
||||
staleThresholdMs: 90_000,
|
||||
maxRecoveryAttempts: 3,
|
||||
})
|
||||
|
||||
expect(recoveredCount).toBe(1)
|
||||
expect(mockClient.resumeWorkflow).toHaveBeenCalledWith(
|
||||
task.id,
|
||||
expect.objectContaining({ queueName: expect.any(String) }),
|
||||
)
|
||||
|
||||
const updatedTask = await prisma.workflowTask.findUnique({
|
||||
where: { id: task.id },
|
||||
})
|
||||
const output = updatedTask?.output as { recoveryAttempts?: number } | null
|
||||
expect(output?.recoveryAttempts).toBe(1)
|
||||
expect(updatedTask?.heartbeat?.getTime()).toBeGreaterThan(Date.now() - 5000)
|
||||
})
|
||||
|
||||
it('should mark task and asset as failed when recoveryAttempts exceeds maxRecoveryAttempts', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
id: 'poison-asset-1',
|
||||
name: 'poison.mp4',
|
||||
type: 'file',
|
||||
status: 'processing',
|
||||
},
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: new Date(Date.now() - 100_000),
|
||||
output: { recoveryAttempts: 3 },
|
||||
},
|
||||
})
|
||||
|
||||
const mockClient = {
|
||||
retrieveWorkflow: vi.fn(),
|
||||
resumeWorkflow: vi.fn(),
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.spyOn(workflowService.getExecutor(), 'getClient').mockResolvedValue(mockClient as any)
|
||||
|
||||
const recoveredCount = await workflowService.recoverStaleTasks({
|
||||
staleThresholdMs: 90_000,
|
||||
maxRecoveryAttempts: 3,
|
||||
})
|
||||
|
||||
expect(recoveredCount).toBe(1)
|
||||
expect(mockClient.resumeWorkflow).not.toHaveBeenCalled()
|
||||
|
||||
const updatedTask = await prisma.workflowTask.findUnique({
|
||||
where: { id: task.id },
|
||||
})
|
||||
expect(updatedTask?.status).toBe(WorkflowTaskStatus.failed)
|
||||
const output = updatedTask?.output as { error?: string; recoveryAttempts?: number } | null
|
||||
expect(output?.recoveryAttempts).toBe(4)
|
||||
expect(output?.error).toContain('exceeded maximum stale recovery attempts')
|
||||
|
||||
const updatedAsset = await prisma.asset.findUnique({
|
||||
where: { id: asset.id },
|
||||
})
|
||||
expect(updatedAsset?.status).toBe('failed')
|
||||
})
|
||||
|
||||
it('should reconcile completed or cancelled DBOS workflow status', async () => {
|
||||
const taskSuccess = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'stale-asset-success',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: new Date(Date.now() - 100_000),
|
||||
},
|
||||
})
|
||||
|
||||
const taskCancelled = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: 'stale-asset-cancelled',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: new Date(Date.now() - 100_000),
|
||||
},
|
||||
})
|
||||
|
||||
const mockClient = {
|
||||
retrieveWorkflow: vi.fn().mockImplementation((taskId: string) => ({
|
||||
getStatus: vi.fn().mockResolvedValue({
|
||||
status: taskId === taskSuccess.id ? 'SUCCESS' : 'CANCELLED',
|
||||
}),
|
||||
})),
|
||||
resumeWorkflow: vi.fn(),
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.spyOn(workflowService.getExecutor(), 'getClient').mockResolvedValue(mockClient as any)
|
||||
|
||||
const count = await workflowService.recoverStaleTasks({
|
||||
staleThresholdMs: 90_000,
|
||||
maxRecoveryAttempts: 3,
|
||||
})
|
||||
|
||||
expect(count).toBe(2)
|
||||
expect(mockClient.resumeWorkflow).not.toHaveBeenCalled()
|
||||
|
||||
const updatedSuccess = await prisma.workflowTask.findUnique({
|
||||
where: { id: taskSuccess.id },
|
||||
})
|
||||
expect(updatedSuccess?.status).toBe(WorkflowTaskStatus.completed)
|
||||
|
||||
const updatedCancelled = await prisma.workflowTask.findUnique({
|
||||
where: { id: taskCancelled.id },
|
||||
})
|
||||
expect(updatedCancelled?.status).toBe(WorkflowTaskStatus.failed)
|
||||
const cancelledOutput = updatedCancelled?.output as { error?: string } | null
|
||||
expect(cancelledOutput?.error).toBe('Workflow was cancelled')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,8 +1,17 @@
|
||||
import { prisma, registerWorkflowCancel, registerWorkflowTrigger, WorkflowTask } from '@shumai/db'
|
||||
import { DbosExecutor, getRegisteredWorkflows } from './dbos-executor'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import {
|
||||
AssetStatus,
|
||||
prisma,
|
||||
registerWorkflowCancel,
|
||||
registerWorkflowTrigger,
|
||||
WorkflowTask,
|
||||
WorkflowTaskStatus,
|
||||
} from '@shumai/db'
|
||||
import { DbosExecutor, getQueueForTaskType, getRegisteredWorkflows } from './dbos-executor'
|
||||
|
||||
export class WorkflowService {
|
||||
private executor: DbosExecutor
|
||||
private staleRecoveryTimer: Timer | null = null
|
||||
|
||||
constructor() {
|
||||
this.executor = new DbosExecutor()
|
||||
@@ -55,6 +64,7 @@ export class WorkflowService {
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.stopStaleTaskRecovery()
|
||||
this.executor.close()
|
||||
}
|
||||
|
||||
@@ -62,8 +72,9 @@ export class WorkflowService {
|
||||
await this.executor.ensureLaunched()
|
||||
}
|
||||
|
||||
async shutdownWorkers(): Promise<void> {
|
||||
await this.executor.shutdown()
|
||||
async shutdownWorkers(options?: { workflowCompletionTimeoutMs?: number }): Promise<void> {
|
||||
this.stopStaleTaskRecovery()
|
||||
await this.executor.shutdown(options)
|
||||
}
|
||||
|
||||
isStarted(): boolean {
|
||||
@@ -82,6 +93,152 @@ export class WorkflowService {
|
||||
this.executor.start()
|
||||
await this.executor.ensureLaunched()
|
||||
}
|
||||
|
||||
startStaleTaskRecovery(options?: {
|
||||
intervalMs?: number
|
||||
staleThresholdMs?: number
|
||||
maxRecoveryAttempts?: number
|
||||
}): void {
|
||||
if (this.staleRecoveryTimer) {
|
||||
return
|
||||
}
|
||||
const intervalMs = options?.intervalMs ?? 30_000
|
||||
this.staleRecoveryTimer = setInterval(() => {
|
||||
this.recoverStaleTasks(options).catch((err) => {
|
||||
logger.error({ err }, '[WorkflowService] Stale task recovery sweep encountered an error')
|
||||
})
|
||||
}, intervalMs)
|
||||
}
|
||||
|
||||
stopStaleTaskRecovery(): void {
|
||||
if (this.staleRecoveryTimer) {
|
||||
clearInterval(this.staleRecoveryTimer)
|
||||
this.staleRecoveryTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
async recoverStaleTasks(options?: {
|
||||
staleThresholdMs?: number
|
||||
maxRecoveryAttempts?: number
|
||||
}): Promise<number> {
|
||||
const staleThresholdMs = options?.staleThresholdMs ?? 90_000
|
||||
const maxRecoveryAttempts = options?.maxRecoveryAttempts ?? 3
|
||||
const cutoff = new Date(Date.now() - staleThresholdMs)
|
||||
|
||||
const staleTasks = await prisma.workflowTask.findMany({
|
||||
where: {
|
||||
status: WorkflowTaskStatus.processing,
|
||||
heartbeat: { lt: cutoff },
|
||||
},
|
||||
})
|
||||
|
||||
if (staleTasks.length === 0) return 0
|
||||
|
||||
let recoveredCount = 0
|
||||
const client = await this.executor.getClient()
|
||||
|
||||
for (const task of staleTasks) {
|
||||
try {
|
||||
const currentTask = await prisma.workflowTask.findUnique({
|
||||
where: { id: task.id },
|
||||
})
|
||||
if (
|
||||
!currentTask ||
|
||||
currentTask.status !== WorkflowTaskStatus.processing ||
|
||||
(currentTask.heartbeat &&
|
||||
currentTask.heartbeat.getTime() >= Date.now() - staleThresholdMs)
|
||||
) {
|
||||
continue
|
||||
}
|
||||
|
||||
const output = (currentTask.output as PrismaJson.WorkflowTaskOutput | null) || {}
|
||||
const recoveryAttempts = (output.recoveryAttempts ?? 0) + 1
|
||||
|
||||
if (recoveryAttempts > maxRecoveryAttempts) {
|
||||
logger.error(
|
||||
{ taskId: task.id, recoveryAttempts, maxRecoveryAttempts },
|
||||
'[WorkflowService] Stale task exceeded max recovery attempts. Marking as failed.',
|
||||
)
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: task.id },
|
||||
data: {
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: {
|
||||
...output,
|
||||
recoveryAttempts,
|
||||
error: `Task exceeded maximum stale recovery attempts (${maxRecoveryAttempts}). Marked as failed.`,
|
||||
},
|
||||
},
|
||||
})
|
||||
if (task.assetId && task.type && task.type.startsWith('transcode')) {
|
||||
await prisma.asset.updateMany({
|
||||
where: { id: task.assetId, status: AssetStatus.processing },
|
||||
data: { status: AssetStatus.failed },
|
||||
})
|
||||
}
|
||||
recoveredCount++
|
||||
continue
|
||||
}
|
||||
|
||||
const handle = client.retrieveWorkflow(task.id)
|
||||
const wfStatus = await handle.getStatus().catch(() => null)
|
||||
|
||||
if (wfStatus?.status === 'PENDING') {
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: task.id },
|
||||
data: {
|
||||
heartbeat: new Date(),
|
||||
output: {
|
||||
...output,
|
||||
recoveryAttempts,
|
||||
},
|
||||
},
|
||||
})
|
||||
const queueName = getQueueForTaskType(task.type)
|
||||
await client.resumeWorkflow(task.id, { queueName })
|
||||
logger.info(
|
||||
{ taskId: task.id, queueName, recoveryAttempts },
|
||||
'[WorkflowService] Resumed stale pending workflow task in DBOS',
|
||||
)
|
||||
recoveredCount++
|
||||
} else if (wfStatus?.status === 'SUCCESS') {
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: task.id },
|
||||
data: { status: WorkflowTaskStatus.completed },
|
||||
})
|
||||
recoveredCount++
|
||||
} else if (wfStatus?.status === 'ERROR') {
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: task.id },
|
||||
data: {
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: {
|
||||
...output,
|
||||
error: wfStatus.error ? String(wfStatus.error) : 'Workflow failed in DBOS',
|
||||
},
|
||||
},
|
||||
})
|
||||
recoveredCount++
|
||||
} else if (wfStatus?.status === 'CANCELLED') {
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: task.id },
|
||||
data: {
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: {
|
||||
...output,
|
||||
error: 'Workflow was cancelled',
|
||||
},
|
||||
},
|
||||
})
|
||||
recoveredCount++
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn({ taskId: task.id, err }, '[WorkflowService] Error while checking stale task')
|
||||
}
|
||||
}
|
||||
|
||||
return recoveredCount
|
||||
}
|
||||
}
|
||||
|
||||
export const workflowService = new WorkflowService()
|
||||
|
||||
Reference in New Issue
Block a user