mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-02 14:04:50 +00:00
Compare commits
3
Commits
6966e5876e
...
882b03e083
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
882b03e083 | ||
|
|
c8e6f959c1 | ||
|
|
7e1e2441d7 |
@@ -422,7 +422,15 @@ To prevent the engine from indefinitely retrying fatal, expected business valida
|
||||
|
||||
- **Implementation**: Activities _can_ and _should_ call other services (e.g., `aiService`, `transcodeService`) or interact with the database directly. Database (Prisma) queries or updates are allowed in all activity types (e.g., agent or transcode) for simplicity.
|
||||
|
||||
- **Implementation**: Activities _can_ and _should_ call other services (e.g., `aiService`, `transcodeService`) or interact with the database directly. Database (Prisma) queries or updates are allowed in all activity types (e.g., agent or transcode) for simplicity.
|
||||
### Worker Identity & Multi-Instance Deployments
|
||||
|
||||
In multi-replica deployments (e.g., multiple transcode or agent worker instances), each worker instance MUST have a unique executor ID to prevent startup recovery from re-enqueueing workflows being actively processed by other live workers.
|
||||
|
||||
- **Identity Derivation**: `DbosExecutor` automatically derives a unique per-instance ID:
|
||||
- If `SHUMAI_WORKER_ID` or `DBOS__VMID` is set, it is used as the instance identifier.
|
||||
- In Kubernetes, set `POD_NAME` (via Downward API: `fieldRef: { fieldPath: metadata.name }`) to provide stable, per-pod identity across StatefulSet restarts.
|
||||
- In Docker/container environments, `HOSTNAME` (container ID) is automatically used.
|
||||
- On bare metal/multi-process hosts, `process.pid` and an instance suffix are appended to guarantee uniqueness.
|
||||
|
||||
## Import conventions
|
||||
|
||||
|
||||
@@ -11,6 +11,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
### Fixed
|
||||
|
||||
* **workflow**: Fix an issue where creating background tasks from within an active workflow step caused an invalid transition error during video processing
|
||||
* **cli**: Fix an issue where running `shumai regenerate-embeddings` would report success without enqueueing tasks to background workers
|
||||
* **workflow**: Fix an issue where multiple worker replicas could share the same executor identity and disrupt live workflows on startup recovery
|
||||
* **workflow**: Fix an issue where changes to queue concurrency environment variables were ignored after initial registration
|
||||
|
||||
### Changed
|
||||
|
||||
|
||||
@@ -53,8 +53,11 @@ const regenCmdIndex = cliArgs.findIndex((arg) => arg === 'regenerate-embeddings'
|
||||
|
||||
if (regenCmdIndex !== -1) {
|
||||
try {
|
||||
initAgentWorkflows()
|
||||
initTranscodeWorkflows()
|
||||
console.log('🔄 Regenerating embeddings...')
|
||||
const result = await embeddingService.regenerateEmbeddings()
|
||||
await workflowService.waitForPendingSubmissions()
|
||||
console.log(
|
||||
`✅ Successfully queued ${result.tasksCreated} embedding tasks for ${result.totalAssets} assets.`,
|
||||
)
|
||||
|
||||
@@ -23,6 +23,15 @@ export async function globalTestSetup() {
|
||||
},
|
||||
})
|
||||
console.log('Prisma Migrations completed.')
|
||||
|
||||
console.log('Applying DBOS Migrations...')
|
||||
await execAsync('bun packages/workflow-core/src/migrate.ts', {
|
||||
env: {
|
||||
...process.env,
|
||||
DATABASE_URL: databaseUrl,
|
||||
},
|
||||
})
|
||||
console.log('DBOS Migrations completed.')
|
||||
}
|
||||
|
||||
export async function setup() {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { DbosExecutor, getDbosDatabaseUrl, getQueueForTaskType } from './dbos-executor'
|
||||
import { TaskQueueAgent, TaskQueueTranscode } from './workflow-utils'
|
||||
import { WorkflowTaskStatus, WorkflowTaskType, WorkflowTask } from '@shumai/db'
|
||||
import { WorkflowTaskStatus, WorkflowTaskType, WorkflowTask, prisma } from '@shumai/db'
|
||||
import { DBOS } from '@dbos-inc/dbos-sdk'
|
||||
|
||||
let activeExecutor: DbosExecutor | null = null
|
||||
@@ -99,6 +99,178 @@ describe('DbosExecutor Tests', () => {
|
||||
expect(executor.getTranscodeConcurrencyLimit()).toBe(1)
|
||||
expect(executor.getAgentConcurrencyLimit()).toBe(5)
|
||||
})
|
||||
|
||||
it('should update effective queue worker concurrency when environment variables change', async () => {
|
||||
// First start with agent concurrency = 5 and transcode = 2
|
||||
process.env.CONCURRENCY_AGENT = '5'
|
||||
process.env.CONCURRENCY_TRANSCODE = '2'
|
||||
executor.start()
|
||||
await executor.ensureLaunched()
|
||||
|
||||
const agentQueueFirst = await DBOS.retrieveQueue(TaskQueueAgent)
|
||||
expect(agentQueueFirst?.workerConcurrency).toBe(5)
|
||||
const transcodeQueueFirst = await DBOS.retrieveQueue(TaskQueueTranscode)
|
||||
expect(transcodeQueueFirst?.workerConcurrency).toBe(2)
|
||||
|
||||
await executor.shutdown()
|
||||
|
||||
// Now change environment variables to safety limits (e.g. CONCURRENCY_AGENT=1, CONCURRENCY_TRANSCODE=4)
|
||||
process.env.CONCURRENCY_AGENT = '1'
|
||||
process.env.CONCURRENCY_TRANSCODE = '4'
|
||||
const executor2 = new DbosExecutor()
|
||||
try {
|
||||
executor2.start()
|
||||
await executor2.ensureLaunched()
|
||||
|
||||
const agentQueueUpdated = await DBOS.retrieveQueue(TaskQueueAgent)
|
||||
const transcodeQueueUpdated = await DBOS.retrieveQueue(TaskQueueTranscode)
|
||||
|
||||
expect(agentQueueUpdated?.workerConcurrency).toBe(1)
|
||||
expect(transcodeQueueUpdated?.workerConcurrency).toBe(4)
|
||||
} finally {
|
||||
await executor2.shutdown()
|
||||
}
|
||||
})
|
||||
|
||||
it('should only update queues the worker listens to or configures, leaving unmanaged queues untouched', async () => {
|
||||
// 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 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 {
|
||||
transcodeWorker.start()
|
||||
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)
|
||||
} finally {
|
||||
await transcodeWorker.shutdown()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('Executor Identity & Multi-instance Recovery', () => {
|
||||
let originalEnv: NodeJS.ProcessEnv
|
||||
|
||||
beforeEach(() => {
|
||||
originalEnv = { ...process.env }
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
process.env = originalEnv
|
||||
})
|
||||
|
||||
it('should derive unique executor IDs for multiple replicas of the same role when no explicit ID is provided', () => {
|
||||
process.env.NODE_ENV = 'production'
|
||||
delete process.env.DBOS__VMID
|
||||
delete process.env.SHUMAI_WORKER_ID
|
||||
delete process.env.POD_NAME
|
||||
|
||||
const worker1 = new DbosExecutor([TaskQueueTranscode])
|
||||
const worker2 = new DbosExecutor([TaskQueueTranscode])
|
||||
|
||||
const id1 = worker1.getExecutorId()
|
||||
const id2 = worker2.getExecutorId()
|
||||
|
||||
expect(id1).not.toBe(id2)
|
||||
expect(id1).toContain('shumai-transcode')
|
||||
expect(id2).toContain('shumai-transcode')
|
||||
})
|
||||
|
||||
it('should incorporate SHUMAI_WORKER_ID or POD_NAME when configured', () => {
|
||||
process.env.NODE_ENV = 'production'
|
||||
delete process.env.DBOS__VMID
|
||||
|
||||
process.env.SHUMAI_WORKER_ID = 'replica-42'
|
||||
const workerWithId = new DbosExecutor([TaskQueueTranscode])
|
||||
expect(workerWithId.getExecutorId()).toBe('shumai-transcode-replica-42')
|
||||
|
||||
delete process.env.SHUMAI_WORKER_ID
|
||||
process.env.POD_NAME = 'shumai-transcode-pod-0'
|
||||
const workerWithPod = new DbosExecutor([TaskQueueTranscode])
|
||||
expect(workerWithPod.getExecutorId()).toBe('shumai-transcode-pod-0')
|
||||
})
|
||||
|
||||
it('should allow setting explicit executorId via constructor or setExecutorId', () => {
|
||||
const customWorker = new DbosExecutor([TaskQueueAgent], 'my-custom-worker')
|
||||
expect(customWorker.getExecutorId()).toBe('my-custom-worker')
|
||||
|
||||
customWorker.setExecutorId('updated-worker-id')
|
||||
expect(customWorker.getExecutorId()).toBe('updated-worker-id')
|
||||
})
|
||||
|
||||
it('should not recover live workflows belonging to another executor ID on startup', async () => {
|
||||
const activeWorkerId = `active-worker-${Date.now()}`
|
||||
const newWorkerId = `new-worker-${Date.now()}`
|
||||
const taskUuid = `task-recovery-test-${Date.now()}`
|
||||
|
||||
// Seed a pending task claimed by activeWorkerId
|
||||
await prisma.$queryRawUnsafe(
|
||||
`
|
||||
INSERT INTO dbos.workflow_status (
|
||||
workflow_uuid, status, name, executor_id, created_at, updated_at, application_version, application_name, queue_name
|
||||
) VALUES (
|
||||
$1, 'PENDING', 'testRecoveryWorkflow', $2, 0, 0, '1.0.0', 'shumai', 'transcode_queue'
|
||||
)
|
||||
`,
|
||||
taskUuid,
|
||||
activeWorkerId,
|
||||
)
|
||||
|
||||
try {
|
||||
// Launch a new worker with a distinct executor ID
|
||||
const newWorker = new DbosExecutor([TaskQueueTranscode], newWorkerId)
|
||||
newWorker.start()
|
||||
await newWorker.ensureLaunched()
|
||||
|
||||
// Verify the active worker's task was NOT recovered (remains PENDING with activeWorkerId)
|
||||
const rowsAfterOtherWorker = await prisma.$queryRawUnsafe<
|
||||
Array<{ status: string; executorId: string }>
|
||||
>(
|
||||
'SELECT status, executor_id AS "executorId" FROM dbos.workflow_status WHERE workflow_uuid = $1',
|
||||
taskUuid,
|
||||
)
|
||||
expect(rowsAfterOtherWorker[0].status).toBe('PENDING')
|
||||
expect(rowsAfterOtherWorker[0].executorId).toBe(activeWorkerId)
|
||||
|
||||
await newWorker.shutdown()
|
||||
|
||||
// Now simulate the active worker restarting with its OWN executor ID
|
||||
const restartedWorker = new DbosExecutor([TaskQueueTranscode], activeWorkerId)
|
||||
restartedWorker.start()
|
||||
await restartedWorker.ensureLaunched()
|
||||
|
||||
// Verify that on restart with the SAME executor ID, DBOS startup recovery DOES re-enqueue it
|
||||
const rowsAfterRestart = await prisma.$queryRawUnsafe<
|
||||
Array<{ status: string; executorId: string }>
|
||||
>(
|
||||
'SELECT status, executor_id AS "executorId" FROM dbos.workflow_status WHERE workflow_uuid = $1',
|
||||
taskUuid,
|
||||
)
|
||||
expect(rowsAfterRestart[0].status).toBe('ENQUEUED')
|
||||
|
||||
await restartedWorker.shutdown()
|
||||
} finally {
|
||||
await prisma.$queryRawUnsafe(
|
||||
'DELETE FROM dbos.workflow_status WHERE workflow_uuid = $1',
|
||||
taskUuid,
|
||||
)
|
||||
}
|
||||
}, 20000)
|
||||
})
|
||||
|
||||
describe('Cancellation', () => {
|
||||
@@ -173,13 +345,49 @@ describe('DbosExecutor Tests', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('should enqueue workflow via client even when executor is not started and no local workflows are registered', async () => {
|
||||
// executor is not started and has no local workflows registered (e.g. CLI or producer mode)
|
||||
const mockClient = {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS property name
|
||||
enqueue: vi.fn().mockResolvedValue({ workflowID: 'task-cli-123' }),
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.spyOn(executor, 'getClient').mockResolvedValue(mockClient as any)
|
||||
|
||||
const mockTask = {
|
||||
id: 'task-cli-123',
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
} as WorkflowTask
|
||||
|
||||
const res = await executor.submit(mockTask)
|
||||
expect(mockClient.enqueue).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
queueName: TaskQueueAgent,
|
||||
workflowName: WorkflowTaskType.ai_embedding,
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS property name
|
||||
workflowID: 'task-cli-123',
|
||||
}),
|
||||
mockTask,
|
||||
)
|
||||
expect(res).toBe('task-cli-123')
|
||||
})
|
||||
|
||||
it('should allow submitting tasks from within a running DBOS step', async () => {
|
||||
executor.start()
|
||||
await executor.ensureLaunched()
|
||||
|
||||
const mockClient = {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS property name
|
||||
enqueue: vi.fn().mockResolvedValue({ workflowID: 'task-from-step' }),
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.spyOn(executor, 'getClient').mockResolvedValue(mockClient as any)
|
||||
|
||||
activeExecutor = executor
|
||||
const result = await wf()
|
||||
expect(result).toBe('task-from-step')
|
||||
})
|
||||
expect(mockClient.enqueue).toHaveBeenCalled()
|
||||
}, 15000)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
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'
|
||||
@@ -59,11 +60,21 @@ export class DbosExecutor implements Executor {
|
||||
private client: DBOSClient | null = null
|
||||
private listenQueues: string[] = [TaskQueueAgent, TaskQueueTranscode]
|
||||
private heartbeatIntervals = new Map<string, Timer>()
|
||||
private inFlightSubmits = new Set<Promise<string>>()
|
||||
private executorId?: string
|
||||
private instanceSuffix = Math.random().toString(36).slice(2, 8)
|
||||
|
||||
constructor(listenQueues?: string[]) {
|
||||
constructor(listenQueues?: string[], executorId?: string) {
|
||||
if (listenQueues) {
|
||||
this.listenQueues = listenQueues
|
||||
}
|
||||
if (executorId) {
|
||||
this.executorId = executorId
|
||||
}
|
||||
}
|
||||
|
||||
isStarted(): boolean {
|
||||
return this.started
|
||||
}
|
||||
|
||||
setListenQueues(queues: string[]): void {
|
||||
@@ -160,9 +171,7 @@ export class DbosExecutor implements Executor {
|
||||
}
|
||||
}
|
||||
|
||||
private getDefaultExecutorId(): string {
|
||||
if (process.env.DBOS__VMID) return process.env.DBOS__VMID
|
||||
if (process.env.SHUMAI_WORKER_ID) return process.env.SHUMAI_WORKER_ID
|
||||
getRole(): string {
|
||||
if (this.listenQueues.length === 0) return 'shumai-web'
|
||||
if (this.listenQueues.length === 1) {
|
||||
if (this.listenQueues[0] === TaskQueueTranscode) return 'shumai-transcode'
|
||||
@@ -171,6 +180,40 @@ export class DbosExecutor implements Executor {
|
||||
return 'shumai-all'
|
||||
}
|
||||
|
||||
setExecutorId(id: string): void {
|
||||
this.executorId = id
|
||||
}
|
||||
|
||||
getExecutorId(): string {
|
||||
return this.getDefaultExecutorId()
|
||||
}
|
||||
|
||||
private getDefaultExecutorId(): string {
|
||||
if (this.executorId) return this.executorId
|
||||
if (process.env.DBOS__VMID) return process.env.DBOS__VMID
|
||||
|
||||
const role = this.getRole()
|
||||
if (process.env.SHUMAI_WORKER_ID) {
|
||||
const workerId = process.env.SHUMAI_WORKER_ID
|
||||
return workerId.startsWith(role) ? workerId : `${role}-${workerId}`
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV === 'test') {
|
||||
return `shumai-test-${process.pid}-${this.instanceSuffix}`
|
||||
}
|
||||
|
||||
// In Kubernetes, POD_NAME is standard and stable across pod restarts in StatefulSets
|
||||
if (process.env.POD_NAME) {
|
||||
const pod = process.env.POD_NAME
|
||||
return pod.startsWith(role) ? pod : `${role}-${pod}`
|
||||
}
|
||||
|
||||
// In Docker containers, HOSTNAME is set to the unique container short ID.
|
||||
// If running on host machine / bare metal, disambiguate with pid and instance suffix.
|
||||
const host = process.env.HOSTNAME || os.hostname() || 'instance'
|
||||
return `${role}-${host}-${process.pid}-${this.instanceSuffix}`
|
||||
}
|
||||
|
||||
async ensureLaunched(): Promise<void> {
|
||||
if (DBOS.isInitialized()) {
|
||||
return
|
||||
@@ -183,31 +226,41 @@ export class DbosExecutor implements Executor {
|
||||
this.registerAllWorkflowsWithDbos()
|
||||
|
||||
const isTest = process.env.NODE_ENV === 'test'
|
||||
if (!isTest && !dbosMigrationsRan) {
|
||||
await DBOS.migrate(getDbosDatabaseUrl())
|
||||
dbosMigrationsRan = true
|
||||
}
|
||||
|
||||
DBOS.setConfig({
|
||||
name: 'shumai',
|
||||
systemDatabaseUrl: getDbosDatabaseUrl(),
|
||||
systemDatabasePoolSize: isTest ? 5 : undefined,
|
||||
applicationVersion: process.env.SHUMAI_VERSION || '1.0.0',
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS config property name
|
||||
executorID: this.getDefaultExecutorId(),
|
||||
listenQueues: this.listenQueues,
|
||||
runMigrations: !dbosMigrationsRan,
|
||||
runMigrations: false,
|
||||
logLevel: isTest ? 'error' : 'info',
|
||||
})
|
||||
|
||||
await DBOS.launch()
|
||||
dbosMigrationsRan = true
|
||||
|
||||
const minPollingIntervalMs = isTest ? 50 : 1000
|
||||
await DBOS.registerQueue(TaskQueueTranscode, {
|
||||
workerConcurrency: this.getTranscodeConcurrencyLimit(),
|
||||
minPollingIntervalMs,
|
||||
onConflict: 'never_update',
|
||||
})
|
||||
await DBOS.registerQueue(TaskQueueAgent, {
|
||||
workerConcurrency: this.getAgentConcurrencyLimit(),
|
||||
minPollingIntervalMs,
|
||||
onConflict: 'never_update',
|
||||
})
|
||||
for (const queueName of this.listenQueues) {
|
||||
if (queueName === TaskQueueTranscode) {
|
||||
await DBOS.registerQueue(TaskQueueTranscode, {
|
||||
workerConcurrency: this.getTranscodeConcurrencyLimit(),
|
||||
minPollingIntervalMs,
|
||||
onConflict: 'always_update',
|
||||
})
|
||||
} else if (queueName === TaskQueueAgent) {
|
||||
await DBOS.registerQueue(TaskQueueAgent, {
|
||||
workerConcurrency: this.getAgentConcurrencyLimit(),
|
||||
minPollingIntervalMs,
|
||||
onConflict: 'always_update',
|
||||
})
|
||||
}
|
||||
}
|
||||
})()
|
||||
|
||||
try {
|
||||
@@ -220,14 +273,26 @@ export class DbosExecutor implements Executor {
|
||||
|
||||
async getClient(): Promise<DBOSClient> {
|
||||
if (!this.client) {
|
||||
const isTest = process.env.NODE_ENV === 'test'
|
||||
this.client = await DBOSClient.create({
|
||||
systemDatabaseUrl: getDbosDatabaseUrl(),
|
||||
systemDatabasePoolSize: isTest ? 3 : undefined,
|
||||
})
|
||||
}
|
||||
return this.client
|
||||
}
|
||||
|
||||
async submit(task: WorkflowTask): Promise<string> {
|
||||
const submitPromise = this.doSubmit(task)
|
||||
this.inFlightSubmits.add(submitPromise)
|
||||
try {
|
||||
return await submitPromise
|
||||
} finally {
|
||||
this.inFlightSubmits.delete(submitPromise)
|
||||
}
|
||||
}
|
||||
|
||||
private async doSubmit(task: WorkflowTask): Promise<string> {
|
||||
if (task.status !== WorkflowTaskStatus.pending) {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: task.id },
|
||||
@@ -235,14 +300,10 @@ export class DbosExecutor implements Executor {
|
||||
})
|
||||
}
|
||||
|
||||
// In unit tests that do not start the workflow service or register workflows,
|
||||
// avoid launching DBOS in the background if no workflows are registered.
|
||||
if (!this.started && getRegisteredWorkflows().size === 0) {
|
||||
return task.id
|
||||
if (this.started) {
|
||||
await this.ensureLaunched()
|
||||
}
|
||||
|
||||
await this.ensureLaunched()
|
||||
|
||||
const workflowName = task.type
|
||||
if (!workflowName) {
|
||||
throw new Error(`WorkflowTask ${task.id} is missing task.type`)
|
||||
@@ -264,6 +325,12 @@ export class DbosExecutor implements Executor {
|
||||
return handle.workflowID
|
||||
}
|
||||
|
||||
async waitForPendingSubmissions(): Promise<void> {
|
||||
while (this.inFlightSubmits.size > 0) {
|
||||
await Promise.allSettled(Array.from(this.inFlightSubmits))
|
||||
}
|
||||
}
|
||||
|
||||
async cancel(taskId: string): Promise<void> {
|
||||
const timer = this.heartbeatIntervals.get(taskId)
|
||||
if (timer) {
|
||||
@@ -289,6 +356,7 @@ export class DbosExecutor implements Executor {
|
||||
|
||||
close(): void {
|
||||
this.started = false
|
||||
this.waitForPendingSubmissions().catch(() => {})
|
||||
for (const timer of this.heartbeatIntervals.values()) {
|
||||
clearInterval(timer)
|
||||
}
|
||||
@@ -298,9 +366,8 @@ export class DbosExecutor implements Executor {
|
||||
this.client = null
|
||||
}
|
||||
if (DBOS.isInitialized()) {
|
||||
DBOS.shutdown({ deregister: true })
|
||||
DBOS.shutdown()
|
||||
.then(() => {
|
||||
registeredDbosWorkflowNames.clear()
|
||||
this.launchPromise = null
|
||||
})
|
||||
.catch((err) => {
|
||||
@@ -311,6 +378,7 @@ export class DbosExecutor implements Executor {
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
this.started = false
|
||||
await this.waitForPendingSubmissions()
|
||||
for (const timer of this.heartbeatIntervals.values()) {
|
||||
clearInterval(timer)
|
||||
}
|
||||
@@ -320,8 +388,7 @@ export class DbosExecutor implements Executor {
|
||||
this.client = null
|
||||
}
|
||||
if (DBOS.isInitialized()) {
|
||||
await DBOS.shutdown({ deregister: true })
|
||||
registeredDbosWorkflowNames.clear()
|
||||
await DBOS.shutdown()
|
||||
this.launchPromise = null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { DBOS } from '@dbos-inc/dbos-sdk'
|
||||
import { getDbosDatabaseUrl } from './dbos-executor'
|
||||
|
||||
export async function migrateDbos(url?: string): Promise<void> {
|
||||
const dbUrl = getDbosDatabaseUrl(url)
|
||||
await DBOS.migrate(dbUrl)
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
await migrateDbos()
|
||||
}
|
||||
@@ -40,11 +40,11 @@ describe('WorkflowService', () => {
|
||||
vi.clearAllMocks()
|
||||
workflowService.start()
|
||||
await workflowService.ensureLaunched()
|
||||
})
|
||||
}, 15000)
|
||||
|
||||
afterEach(async () => {
|
||||
await workflowService.shutdownWorkers()
|
||||
})
|
||||
}, 15000)
|
||||
|
||||
it('should process ai_embedding task locally', async () => {
|
||||
const team = await prisma.team.create({
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { prisma, registerWorkflowCancel, registerWorkflowTrigger, WorkflowTask } from '@shumai/db'
|
||||
import { DbosExecutor } from './dbos-executor'
|
||||
import { getRegisteredWorkflows } from './registry'
|
||||
|
||||
export class WorkflowService {
|
||||
private executor: DbosExecutor
|
||||
@@ -71,6 +72,14 @@ export class WorkflowService {
|
||||
await this.executor.shutdown()
|
||||
}
|
||||
|
||||
isStarted(): boolean {
|
||||
return this.executor.isStarted()
|
||||
}
|
||||
|
||||
async waitForPendingSubmissions(): Promise<void> {
|
||||
await this.executor.waitForPendingSubmissions()
|
||||
}
|
||||
|
||||
// Starts DBOS worker for specific task queue(s)
|
||||
async startWorkers(
|
||||
queue: string | string[],
|
||||
@@ -87,6 +96,13 @@ export class WorkflowService {
|
||||
|
||||
export const workflowService = new WorkflowService()
|
||||
registerWorkflowTrigger(async (task) => {
|
||||
if (
|
||||
process.env.NODE_ENV === 'test' &&
|
||||
!workflowService.isStarted() &&
|
||||
getRegisteredWorkflows().size === 0
|
||||
) {
|
||||
return
|
||||
}
|
||||
await workflowService.submit(task)
|
||||
})
|
||||
registerWorkflowCancel(async (taskId) => {
|
||||
|
||||
Reference in New Issue
Block a user