From 8e3522eab60a19af05ddc27f2698ff07229be7ec Mon Sep 17 00:00:00 2001 From: yiling Date: Mon, 19 Oct 2026 09:23:17 +0800 Subject: [PATCH] feat(transcode): support idle-timeout auto-drain for KEDA scaled jobs --- CHANGELOG.md | 2 +- apps/transcode/src/index.ts | 58 +++++++++++++------ docs/configuration/distributed.mdx | 6 +- eks/README.md | 26 ++++----- eks/shumai-transcode.yaml | 7 +-- .../workflow-core/src/dbos-executor.test.ts | 8 +-- packages/workflow-core/src/dbos-executor.ts | 10 ---- 7 files changed, 61 insertions(+), 56 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 45376f64..87c89f52 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added -* **deploy**: Add dedicated `shumaione/shumai-transcode` Docker image and a complete AWS EKS deployment example (`eks/`) featuring KEDA queue-driven autoscaling, `--once` worker execution mode, and Scale-to-Zero On-Demand Graviton5 instances for media processing +* **deploy**: Add dedicated `shumaione/shumai-transcode` Docker image and a complete AWS EKS deployment example (`eks/`) featuring KEDA queue-driven autoscaling, idle-timeout auto-drain worker mode, and Scale-to-Zero On-Demand Graviton5 instances for media processing * **workflow**: Add automated stale-heartbeat recovery sweep to detect dead or terminated worker nodes and resume pending tasks in DBOS without losing completed steps * **storage**: Support configuring a separate public endpoint (`AWS_PUBLIC_ENDPOINT_URL_S3`) for browser-facing presigned URLs while preserving internal cluster endpoints for backend workers diff --git a/apps/transcode/src/index.ts b/apps/transcode/src/index.ts index 17c1cdd2..68c0df06 100644 --- a/apps/transcode/src/index.ts +++ b/apps/transcode/src/index.ts @@ -14,18 +14,29 @@ async function run() { // Initialize workflows and activities initTranscodeWorkflows() - const isOnce = process.argv.includes('--once') || process.env.SHUMAI_WORKER_ONCE === 'true' - if (isOnce) { - workflowService.getExecutor().setOnceMode(true) - console.log('πŸš€ Starting Transcode Worker in --once mode (single-task execution)...') + let idleTimeoutMs = process.env.SHUMAI_WORKER_IDLE_TIMEOUT_MS + ? parseInt(process.env.SHUMAI_WORKER_IDLE_TIMEOUT_MS, 10) + : 0 + + const idleTimeoutArg = process.argv.find((arg) => arg.startsWith('--idle-timeout=')) + if (idleTimeoutArg) { + const val = parseInt(idleTimeoutArg.split('=')[1], 10) + if (!isNaN(val)) idleTimeoutMs = val + } + + if (idleTimeoutMs > 0) { + console.log( + `πŸš€ Starting Transcode Worker with idle timeout (${idleTimeoutMs / 1000}s auto-drain)...`, + ) } else { - console.log('πŸš€ Starting Transcode Worker...') + console.log('πŸš€ Starting Transcode Worker (persistent daemon mode)...') } await workflowService.startWorkers(TaskQueueTranscode) let isShuttingDown = false let idleTimer: Timer | null = null + let activeWorkflows = 0 const shutdown = async () => { if (isShuttingDown) return @@ -43,20 +54,30 @@ async function run() { process.exit(0) } - if (isOnce) { - const idleTimeoutMs = process.env.SHUMAI_WORKER_IDLE_TIMEOUT_MS - ? parseInt(process.env.SHUMAI_WORKER_IDLE_TIMEOUT_MS, 10) - : 15_000 + if (idleTimeoutMs > 0) { + const resetIdleTimer = () => { + if (idleTimer) { + clearTimeout(idleTimer) + idleTimer = null + } + if (activeWorkflows === 0 && !isShuttingDown) { + idleTimer = setTimeout(async () => { + console.log( + `[Transcode Worker] Inactive for ${idleTimeoutMs / 1000}s with no active workflows, shutting down.`, + ) + await shutdown() + }, idleTimeoutMs) + } + } - idleTimer = setTimeout(async () => { - console.log( - `[Transcode Worker] No tasks received within idle timeout (${idleTimeoutMs / 1000}s), shutting down.`, - ) - await shutdown() - }, idleTimeoutMs) + // Start idle timer immediately on startup in case no tasks are enqueued + resetIdleTimer() workflowService.getExecutor().on('workflowStarted', (task) => { - console.log(`[Transcode Worker] Claimed task ${task.id}, cancelling idle timer.`) + activeWorkflows++ + console.log( + `[Transcode Worker] Claimed task ${task.id} (active: ${activeWorkflows}), cancelling idle timer.`, + ) if (idleTimer) { clearTimeout(idleTimer) idleTimer = null @@ -64,8 +85,9 @@ async function run() { }) workflowService.getExecutor().on('workflowFinished', async ({ taskId }) => { - console.log(`[Transcode Worker] Completed task ${taskId} in --once mode, shutting down.`) - await shutdown() + activeWorkflows = Math.max(0, activeWorkflows - 1) + console.log(`[Transcode Worker] Completed task ${taskId} (active: ${activeWorkflows}).`) + resetIdleTimer() }) } diff --git a/docs/configuration/distributed.mdx b/docs/configuration/distributed.mdx index 42466e03..11f299b1 100644 --- a/docs/configuration/distributed.mdx +++ b/docs/configuration/distributed.mdx @@ -141,8 +141,8 @@ graph TD Server -->|Direct Uploads / Stream Proxies| Storage[(S3 / Garage Storage)] KEDA[KEDA ScaledJob
PostgreSQL Trigger
min: 0, max: 10] -.->|Monitors Queue| DB - KEDA -->|Spawns 1 Job per task| Job1[Job: shumai-transcode-1
--once mode] - KEDA -->|Spawns 1 Job per task| JobN[Job: shumai-transcode-N
--once mode] + KEDA -->|Spawns Jobs for queue| Job1[Job: shumai-transcode-1
Auto-drain worker] + KEDA -->|Spawns Jobs for queue| JobN[Job: shumai-transcode-N
Auto-drain worker] Job1 -->|Fetch Source / Store Proxies| Storage JobN -->|Fetch Source / Store Proxies| Storage @@ -157,7 +157,7 @@ graph TD - **Decoupled Stateless Workers**: The main web and API server, database, and storage run on reliable On-Demand compute (`c9g.large`, `SHUMAI_WORKERS=agent`), delegating media transcoding to background workers orchestrated via DBOS task queues in PostgreSQL. - **Dedicated Graviton5 On-Demand Compute (`c9g.xlarge`)**: Media encoding runs on 4 vCPU / 8 GiB RAM AWS Graviton5 On-Demand instances (~$0.174/hr), utilizing ARM64 vector optimizations and high-speed DDR5 memory without involuntary Spot interruptions. - **Queue-Driven Scale-to-Zero via KEDA**: KEDA monitors `dbos.workflow_status` for enqueued and pending transcode tasks and dynamically provisions Kubernetes `ScaledJob` resources (scaling 0 to 10). When the queue is empty, transcode nodes scale down to zero (`minSize: 0`), incurring **$0/hr** in worker costs. -- **Single-Workflow `--once` Mode**: Each worker pod runs in `--once` mode, claims exactly 1 workflow task, processes it to completion, and exits `0`. Because each task runs in an isolated Kubernetes Job, terminating or finishing jobs never interrupts peer tasks. +- **Idle-Timeout Auto-Drain**: Worker pods continuously process queued tasks with concurrency `1`. When the queue is fully drained and a pod has been idle for 10 seconds (`SHUMAI_WORKER_IDLE_TIMEOUT_MS=10000`), it exits `0` cleanly so the node can scale down, processing batch uploads without cold-start pod churn. - **Automated Stale Task Recovery**: The core web server runs an integrated recovery sweep that detects stale or orphaned tasks (e.g. from node crash) and resumes them automatically in DBOS, with a 3-attempt cap to safely handle poison-pill media. ### Complete Deployment Example & Source Code diff --git a/eks/README.md b/eks/README.md index 7e3b85ea..992ac4eb 100644 --- a/eks/README.md +++ b/eks/README.md @@ -27,7 +27,7 @@ To demonstrate a fully self-hosted setup, it uses Garage as an S3-compatible obj β”‚ β–Ό β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” Enqueue DBOS Tasks β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ shumai-server β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Ίβ”‚ shumai-postgres β”‚ β”‚ -β”‚ β”‚(SHUMAI_WORKERS=agent) β”‚ (task_queue_transcode) β”‚ (pgvector:pg18) β”‚ β”‚ +β”‚ β”‚(SHUMAI_WORKERS=agent) β”‚ (transcode_queue) β”‚ (pgvector:pg18) β”‚ β”‚ β”‚ β”‚ [Stale Recovery Loop] β”‚ β”‚ β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ Internal S3 Traffic β”‚ β”‚ @@ -42,7 +42,7 @@ To demonstrate a fully self-hosted setup, it uses Garage as an S3-compatible obj β”‚ β–Ό dbos.workflow_status β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ KEDA Controller: ScaledJob β”‚ - β”‚ β”‚ Spawns 1 Job per enqueued task (0..10)β”‚ + β”‚ β”‚ Spawns Jobs based on pending tasks β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β–Ό Creates K8s Jobs @@ -51,7 +51,7 @@ To demonstrate a fully self-hosted setup, it uses Garage as an S3-compatible obj β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ Job: transcode-job-1 β”‚ β”‚ Job: transcode-job-2 β”‚ β”‚Job: transcode-job-Nβ”‚ β”‚ -β”‚ β”‚ (Worker Pod: --once) β”‚ β”‚ (Worker Pod: --once) β”‚ β”‚ (Worker Pod: --onceβ”‚ β”‚ +β”‚ β”‚ (Auto-Drain Worker) β”‚ β”‚ (Auto-Drain Worker) β”‚ β”‚ (Auto-Drain Worker)β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β–Ό β–Ό β–Ό β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ @@ -83,20 +83,20 @@ Standard Kubernetes Horizontal Pod Autoscaler (HPA) scales `Deployment` replicas **KEDA `ScaledJob` solves this natively**: - KEDA queries PostgreSQL directly: ```sql - SELECT COUNT(*) FROM dbos.workflow_status WHERE queue_name = 'task_queue_transcode' AND status IN ('ENQUEUED', 'PENDING'); + SELECT COUNT(*) FROM dbos.workflow_status WHERE queue_name = 'transcode_queue' AND status IN ('ENQUEUED', 'PENDING'); ``` -- KEDA spawns an independent Kubernetes `Job` for each enqueued task. -- Each Job runs the transcode worker in `--once` mode. -- When the job's video finishes transcoding, the pod exits `0` and Kubernetes marks the Job completed. +- KEDA spawns independent Kubernetes `Job` pods based on enqueued workload. +- Each Job runs the transcode worker with an idle timeout (`SHUMAI_WORKER_IDLE_TIMEOUT_MS=10000`). +- When the job drains its tasks and becomes idle, the pod exits `0` and Kubernetes marks the Job completed. - Completing or terminating one job **never impacts any other job**! -### 3. Single-Task Worker Execution (`--once` Mode) +### 3. Idle-Timeout Auto-Drain (10s Inactivity Shutdown) -In [`eks/shumai-transcode.yaml`](./shumai-transcode.yaml), the worker container runs with `bun run /app/apps/transcode/src/index.ts --once`: -- Transcode concurrency is strictly set to `1`. -- The worker claims 1 DBOS workflow task from `task_queue_transcode`. -- As soon as that task finishes (success, failure, or cancellation), the worker initiates graceful DBOS drain and exits with code `0`. -- **Idle Timeout**: If a job was spawned but another worker claimed the task first, the worker waits 15 seconds. If no task arrives within 15 seconds, it exits `0` cleanly so the pod and node can shut down. +In [`eks/shumai-transcode.yaml`](./shumai-transcode.yaml), the worker container runs with `SHUMAI_WORKER_IDLE_TIMEOUT_MS: "10000"`: +- **Concurrency Isolation**: Transcode concurrency is set to `1` per pod (`CONCURRENCY_TRANSCODE=1`). Each pod has exclusive access to the node's 4 vCPUs for FFmpeg. +- **Batch Processing Without Cold Starts**: Unlike single-task execution, a running worker continuously pulls tasks from `transcode_queue`. When a user uploads 100 images or multiple video files, a warm worker processes them back-to-back in seconds without restarting the container or control plane churn. +- **Automatic Scale-to-Zero**: When `activeWorkflows === 0` and no new task arrives within 10 consecutive seconds, the worker initiates graceful DBOS shutdown and exits with code `0`. +- The completed Job pod terminates, freeing the node so Cluster Autoscaler can terminate the EC2 instance down to zero. ### 4. Automated Stale-Heartbeat Recovery Sweep diff --git a/eks/shumai-transcode.yaml b/eks/shumai-transcode.yaml index 25f946ba..7a2f8329 100644 --- a/eks/shumai-transcode.yaml +++ b/eks/shumai-transcode.yaml @@ -60,14 +60,13 @@ spec: - bun - run - /app/apps/transcode/src/index.ts - - --once env: - name: POD_NAME valueFrom: fieldRef: fieldPath: metadata.name - - name: SHUMAI_WORKER_ONCE - value: 'true' + - name: SHUMAI_WORKER_IDLE_TIMEOUT_MS + value: '10000' envFrom: - configMapRef: name: shumai-config @@ -91,7 +90,7 @@ spec: triggers: - type: postgresql metadata: - query: "SELECT COUNT(*) FROM dbos.workflow_status WHERE queue_name = 'task_queue_transcode' AND status IN ('ENQUEUED', 'PENDING');" + query: "SELECT COUNT(*) FROM dbos.workflow_status WHERE queue_name = 'transcode_queue' AND status IN ('ENQUEUED', 'PENDING');" targetQueryValue: '1' authenticationRef: name: keda-postgres-auth diff --git a/packages/workflow-core/src/dbos-executor.test.ts b/packages/workflow-core/src/dbos-executor.test.ts index 2fab9f29..d9175d6f 100644 --- a/packages/workflow-core/src/dbos-executor.test.ts +++ b/packages/workflow-core/src/dbos-executor.test.ts @@ -384,13 +384,7 @@ describe('DbosExecutor Tests', () => { }, 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) - }) - + describe('Workflow events and conflict handling', () => { it('should emit workflowStarted and workflowFinished events during execution', async () => { let startedTask: WorkflowTask | null = null let finishedPayload: { taskId: string; success: boolean } | null = null diff --git a/packages/workflow-core/src/dbos-executor.ts b/packages/workflow-core/src/dbos-executor.ts index 0f45885a..83b6f445 100644 --- a/packages/workflow-core/src/dbos-executor.ts +++ b/packages/workflow-core/src/dbos-executor.ts @@ -89,7 +89,6 @@ export class DbosExecutor extends EventEmitter { private inFlightSubmits = new Set>() private executorId?: string private instanceSuffix = Math.random().toString(36).slice(2, 8) - private onceMode = false constructor(listenQueues?: string[], executorId?: string) { super() @@ -101,14 +100,6 @@ export class DbosExecutor extends EventEmitter { } } - setOnceMode(once: boolean): void { - this.onceMode = once - } - - isOnceMode(): boolean { - return this.onceMode - } - isStarted(): boolean { return this.started } @@ -118,7 +109,6 @@ export class DbosExecutor extends EventEmitter { } getTranscodeConcurrencyLimit(): number { - if (this.onceMode) return 1 return getConcurrencyLimit(process.env.CONCURRENCY_TRANSCODE, 1) }