feat(transcode): support idle-timeout auto-drain for KEDA scaled jobs

This commit is contained in:
yiling
2026-10-19 09:23:17 +08:00
parent a16a1515d7
commit 8e3522eab6
7 changed files with 61 additions and 56 deletions
+1 -1
View File
@@ -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
+40 -18
View File
@@ -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()
})
}
+3 -3
View File
@@ -141,8 +141,8 @@ graph TD
Server -->|Direct Uploads / Stream Proxies| Storage[(S3 / Garage Storage)]
KEDA[KEDA ScaledJob<br/>PostgreSQL Trigger<br/>min: 0, max: 10] -.->|Monitors Queue| DB
KEDA -->|Spawns 1 Job per task| Job1[Job: shumai-transcode-1<br/>--once mode]
KEDA -->|Spawns 1 Job per task| JobN[Job: shumai-transcode-N<br/>--once mode]
KEDA -->|Spawns Jobs for queue| Job1[Job: shumai-transcode-1<br/>Auto-drain worker]
KEDA -->|Spawns Jobs for queue| JobN[Job: shumai-transcode-N<br/>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
+13 -13
View File
@@ -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
+3 -4
View File
@@ -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
@@ -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
@@ -89,7 +89,6 @@ export class DbosExecutor extends EventEmitter {
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()
@@ -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)
}