Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Manage subprocesses, add retries and shutdown hooks
Richie McIlroy4e58ed42a1b6
diff --git a/apps/media-server/src/index.ts b/apps/media-server/src/index.tsindex 3d3b4db2d..0bd3b6538 100644--- a/apps/media-server/src/index.ts+++ b/apps/media-server/src/index.ts@@ -1,17 +1,34 @@import app from "./app";+import { abortAllJobs } from "./lib/job-manager";+import { terminateAllSubprocesses } from "./lib/subprocess";const port = Number(process.env.PORT) || 3456;console.log(`[media-server] Starting on port ${port}`);-const shutdown = () => {+let shuttingDown = false;++const shutdown = async () => {+ if (shuttingDown) return;+ shuttingDown = true;console.log("[media-server] Shutting down...");+ const abortedJobs = abortAllJobs();+ if (abortedJobs > 0) {+ console.log(`[media-server] Aborted ${abortedJobs} active jobs`);+ }+ await terminateAllSubprocesses();process.exit(0);};-process.on("SIGINT", shutdown);-process.on("SIGTERM", shutdown);-process.on("SIGHUP", shutdown);+process.on("SIGINT", () => {+ void shutdown();+});+process.on("SIGTERM", () => {+ void shutdown();+});+process.on("SIGHUP", () => {+ void shutdown();+});export default {port,diff --git a/apps/media-server/src/lib/ffmpeg-video.ts b/apps/media-server/src/lib/ffmpeg-video.tsindex baefd7e48..17392a758 100644--- a/apps/media-server/src/lib/ffmpeg-video.ts+++ b/apps/media-server/src/lib/ffmpeg-video.ts@@ -1,11 +1,11 @@import { file, type Subprocess, spawn } from "bun";import type { VideoMetadata } from "./job-manager";+import { registerSubprocess, terminateProcess } from "./subprocess";import { createTempFile, type TempFileHandle } from "./temp-files";const PROCESS_TIMEOUT_MS = 45 * 60 * 1000;const PROCESS_TIMEOUT_PER_SECOND_MS = 20_000;const MAX_PROCESS_TIMEOUT_MS = 2 * 60 * 60 * 1000;-const PROCESS_EXIT_WAIT_MS = 5_000;const THUMBNAIL_TIMEOUT_MS = 60_000;const DOWNLOAD_TIMEOUT_MS = 10 * 60 * 1000;const UPLOAD_TIMEOUT_MS = 10 * 60 * 1000;@@ -66,32 +66,6 @@ export function normalizeVideoInputExtension(: (`.${normalized}` as `.${string}`);}-function killProcess(proc: Subprocess): void {- try {- proc.kill();- } catch {}-}--async function waitForProcessExit(- proc: Pick<Subprocess, "exited">,- timeoutMs = PROCESS_EXIT_WAIT_MS,-): Promise<void> {- await Promise.race([- proc.exited.then(- () => undefined,- () => undefined,- ),- new Promise<void>((resolve) => {- setTimeout(resolve, timeoutMs);- }),- ]);-}--async function terminateProcess(proc: Subprocess): Promise<void> {- killProcess(proc);- await waitForProcessExit(proc);-}-export async function withTimeout<T>(promise: Promise<T>,timeoutMs: number,@@ -144,11 +118,18 @@ async function readStreamWithLimit(let totalBytes = 0;try {- while (totalBytes < maxBytes) {+ while (true) {const { done, value } = await reader.read();if (done) break;- chunks.push(value);- totalBytes += value.length;+ if (totalBytes < maxBytes) {+ const remainingBytes = maxBytes - totalBytes;+ const chunk =+ value.length > remainingBytes+ ? value.slice(0, remainingBytes)+ : value;+ chunks.push(chunk);+ totalBytes += chunk.length;+ }}} finally {reader.releaseLock();@@ -230,8 +211,7 @@ export async function downloadVideoToTemp(throw new Error("No response body");}- const arrayBuffer = await response.arrayBuffer();- await Bun.write(tempFile.path, arrayBuffer);+ await Bun.write(tempFile.path, response);const fileHandle = file(tempFile.path);const fileSize = fileHandle.size;@@ -280,16 +260,18 @@ export async function repairContainer(console.log(`[repairContainer] Running: ${ffmpegArgs.join(" ")}`);- const proc = spawn({- cmd: ffmpegArgs,- stdout: "pipe",- stderr: "pipe",- });+ const proc = registerSubprocess(+ spawn({+ cmd: ffmpegArgs,+ stdout: "pipe",+ stderr: "pipe",+ }),+ );let abortCleanup: (() => void) | undefined;if (abortSignal) {abortCleanup = () => {- killProcess(proc);+ void terminateProcess(proc);};abortSignal.addEventListener("abort", abortCleanup, { once: true });}@@ -537,18 +519,20 @@ export async function processVideo(console.log(`[processVideo] Running FFmpeg: ${ffmpegArgs.join(" ")}`);- const proc = spawn({- cmd: ffmpegArgs,- stdout: "pipe",- stderr: "pipe",- });+ const proc = registerSubprocess(+ spawn({+ cmd: ffmpegArgs,+ stdout: "pipe",+ stderr: "pipe",+ }),+ );const totalDurationUs = metadata.duration * 1_000_000;let abortCleanup: (() => void) | undefined;if (abortSignal) {abortCleanup = () => {- killProcess(proc);+ void terminateProcess(proc);};abortSignal.addEventListener("abort", abortCleanup, { once: true });}@@ -659,11 +643,13 @@ export async function generateThumbnail("pipe:1",];- const proc = spawn({- cmd: ffmpegArgs,- stdout: "pipe",- stderr: "pipe",- });+ const proc = registerSubprocess(+ spawn({+ cmd: ffmpegArgs,+ stdout: "pipe",+ stderr: "pipe",+ }),+ );try {const result = await withTimeout(@@ -708,12 +694,12 @@ export async function generateThumbnail(return output;})(),THUMBNAIL_TIMEOUT_MS,- () => killProcess(proc),+ () => terminateProcess(proc),);return result;} finally {- killProcess(proc);+ await terminateProcess(proc);}}diff --git a/apps/media-server/src/lib/ffmpeg.ts b/apps/media-server/src/lib/ffmpeg.tsindex 1efc94f73..abf7e9f8a 100644--- a/apps/media-server/src/lib/ffmpeg.ts+++ b/apps/media-server/src/lib/ffmpeg.ts@@ -1,4 +1,5 @@import { type Subprocess, spawn } from "bun";+import { registerSubprocess, terminateProcess } from "./subprocess";export interface AudioExtractionOptions {format?: "mp3";@@ -28,21 +29,18 @@ export function canAcceptNewProcess(): boolean {return activeProcesses < MAX_CONCURRENT_PROCESSES;}-function killProcess(proc: Subprocess): void {- try {- proc.kill();- } catch {}-}-async function withTimeout<T>(promise: Promise<T>,timeoutMs: number,- cleanup?: () => void,+ cleanup?: () => void | Promise<void>,): Promise<T> {let timeoutId: ReturnType<typeof setTimeout> | undefined;+ let cleanupPromise: Promise<void> | undefined;const timeoutPromise = new Promise<never>((_, reject) => {timeoutId = setTimeout(() => {- cleanup?.();+ cleanupPromise = Promise.resolve()+ .then(() => cleanup?.())+ .then(() => undefined);reject(new Error(`Operation timed out after ${timeoutMs}ms`));}, timeoutMs);});@@ -52,6 +50,9 @@ async function withTimeout<T>(if (timeoutId) clearTimeout(timeoutId);return result;} catch (err) {+ if (cleanupPromise) {+ await cleanupPromise;+ }if (timeoutId) clearTimeout(timeoutId);throw err;}@@ -80,11 +81,18 @@ async function readStreamWithLimit(let totalBytes = 0;try {- while (totalBytes < maxBytes) {+ while (true) {const { done, value } = await reader.read();if (done) break;- chunks.push(value);- totalBytes += value.length;+ if (totalBytes < maxBytes) {+ const remainingBytes = maxBytes - totalBytes;+ const chunk =+ value.length > remainingBytes+ ? value.slice(0, remainingBytes)+ : value;+ chunks.push(chunk);+ totalBytes += chunk.length;+ }}} finally {reader.releaseLock();@@ -105,11 +113,13 @@ export async function checkHasAudioTrack(videoUrl: string): Promise<boolean> {activeProcesses++;- const proc = spawn({- cmd: ["ffmpeg", "-i", videoUrl, "-hide_banner"],- stdout: "pipe",- stderr: "pipe",- });+ const proc = registerSubprocess(+ spawn({+ cmd: ["ffmpeg", "-i", videoUrl, "-hide_banner"],+ stdout: "pipe",+ stderr: "pipe",+ }),+ );try {const result = await withTimeout(@@ -124,13 +134,13 @@ export async function checkHasAudioTrack(videoUrl: string): Promise<boolean> {return /Stream #\d+:\d+.*Audio:/.test(stderrText);})(),CHECK_TIMEOUT_MS,- () => killProcess(proc),+ () => terminateProcess(proc),);return result;} finally {activeProcesses--;- killProcess(proc);+ await terminateProcess(proc);}}@@ -160,11 +170,13 @@ export async function extractAudio("pipe:1",];- const proc = spawn({- cmd: ffmpegArgs,- stdout: "pipe",- stderr: "pipe",- });+ const proc = registerSubprocess(+ spawn({+ cmd: ffmpegArgs,+ stdout: "pipe",+ stderr: "pipe",+ }),+ );try {const result = await withTimeout(@@ -215,13 +227,13 @@ export async function extractAudio(return output;})(),EXTRACT_TIMEOUT_MS,- () => killProcess(proc),+ () => terminateProcess(proc),);return result;} finally {activeProcesses--;- killProcess(proc);+ await terminateProcess(proc);}}@@ -257,11 +269,13 @@ export function extractAudioStream("pipe:1",];- const proc = spawn({- cmd: ffmpegArgs,- stdout: "pipe",- stderr: "pipe",- });+ const proc = registerSubprocess(+ spawn({+ cmd: ffmpegArgs,+ stdout: "pipe",+ stderr: "pipe",+ }),+ );let timeoutId: ReturnType<typeof setTimeout> | undefined;let cleaned = false;@@ -279,7 +293,7 @@ export function extractAudioStream(reader = null;}activeProcesses--;- killProcess(proc);+ void terminateProcess(proc);};timeoutId = setTimeout(() => {diff --git a/apps/media-server/src/lib/ffprobe.ts b/apps/media-server/src/lib/ffprobe.tsindex e592d94e5..86a5f5247 100644--- a/apps/media-server/src/lib/ffprobe.ts+++ b/apps/media-server/src/lib/ffprobe.ts@@ -1,5 +1,6 @@import { type Subprocess, spawn } from "bun";import type { VideoMetadata } from "./job-manager";+import { registerSubprocess, terminateProcess } from "./subprocess";const PROBE_TIMEOUT_MS = 30_000;const MAX_OUTPUT_BYTES = 1024 * 1024;@@ -15,21 +16,18 @@ export function canAcceptNewProbeProcess(): boolean {return activeProbeProcesses < MAX_CONCURRENT_PROBE_PROCESSES;}-function killProcess(proc: Subprocess): void {- try {- proc.kill();- } catch {}-}-async function withTimeout<T>(promise: Promise<T>,timeoutMs: number,- cleanup?: () => void,+ cleanup?: () => void | Promise<void>,): Promise<T> {let timeoutId: ReturnType<typeof setTimeout> | undefined;+ let cleanupPromise: Promise<void> | undefined;const timeoutPromise = new Promise<never>((_, reject) => {timeoutId = setTimeout(() => {- cleanup?.();+ cleanupPromise = Promise.resolve()+ .then(() => cleanup?.())+ .then(() => undefined);reject(new Error(`Operation timed out after ${timeoutMs}ms`));}, timeoutMs);});@@ -39,6 +37,9 @@ async function withTimeout<T>(if (timeoutId) clearTimeout(timeoutId);return result;} catch (err) {+ if (cleanupPromise) {+ await cleanupPromise;+ }if (timeoutId) clearTimeout(timeoutId);throw err;}@@ -53,11 +54,18 @@ async function readStreamToString(let totalBytes = 0;try {- while (totalBytes < maxBytes) {+ while (true) {const { done, value } = await reader.read();if (done) break;- chunks.push(value);- totalBytes += value.length;+ if (totalBytes < maxBytes) {+ const remainingBytes = maxBytes - totalBytes;+ const chunk =+ value.length > remainingBytes+ ? value.slice(0, remainingBytes)+ : value;+ chunks.push(chunk);+ totalBytes += chunk.length;+ }}} finally {reader.releaseLock();@@ -105,20 +113,22 @@ export async function probeVideo(videoUrl: string): Promise<VideoMetadata> {activeProbeProcesses++;- const proc = spawn({- cmd: [- "ffprobe",- "-v",- "quiet",- "-print_format",- "json",- "-show_format",- "-show_streams",- videoUrl,- ],- stdout: "pipe",- stderr: "pipe",- });+ const proc = registerSubprocess(+ spawn({+ cmd: [+ "ffprobe",+ "-v",+ "quiet",+ "-print_format",+ "json",+ "-show_format",+ "-show_streams",+ videoUrl,+ ],+ stdout: "pipe",+ stderr: "pipe",+ }),+ );try {const result = await withTimeout(@@ -180,13 +190,13 @@ export async function probeVideo(videoUrl: string): Promise<VideoMetadata> {};})(),PROBE_TIMEOUT_MS,- () => killProcess(proc),+ () => terminateProcess(proc),);return result;} finally {activeProbeProcesses--;- killProcess(proc);+ await terminateProcess(proc);}}@@ -197,24 +207,26 @@ export async function probeVideoFile(filePath: string): Promise<VideoMetadata> {activeProbeProcesses++;- const proc = spawn({- cmd: [- "ffprobe",- "-v",- "quiet",- "-print_format",- "json",- "-show_format",- "-show_streams",- "-analyzeduration",- "10000000",- "-probesize",- "10000000",- filePath,- ],- stdout: "pipe",- stderr: "ignore",- });+ const proc = registerSubprocess(+ spawn({+ cmd: [+ "ffprobe",+ "-v",+ "quiet",+ "-print_format",+ "json",+ "-show_format",+ "-show_streams",+ "-analyzeduration",+ "10000000",+ "-probesize",+ "10000000",+ filePath,+ ],+ stdout: "pipe",+ stderr: "ignore",+ }),+ );try {const result = await withTimeout(@@ -266,13 +278,13 @@ export async function probeVideoFile(filePath: string): Promise<VideoMetadata> {};})(),PROBE_TIMEOUT_MS,- () => killProcess(proc),+ () => terminateProcess(proc),);return result;} finally {activeProbeProcesses--;- killProcess(proc);+ await terminateProcess(proc);}}diff --git a/apps/media-server/src/lib/job-manager.ts b/apps/media-server/src/lib/job-manager.tsindex d95ac0dc9..acea2b6ba 100644--- a/apps/media-server/src/lib/job-manager.ts+++ b/apps/media-server/src/lib/job-manager.ts@@ -59,14 +59,22 @@ const jobs = new Map<string, Job>();const JOB_TTL_MS = 60 * 60 * 1000;let activeVideoProcesses = 0;-const MAX_CONCURRENT_VIDEO_PROCESSES = 3;+const maxConcurrentVideoProcesses =+ Number.parseInt(+ process.env.MEDIA_SERVER_MAX_CONCURRENT_VIDEO_PROCESSES ?? "3",+ 10,+ ) || 3;export function getActiveVideoProcessCount(): number {return activeVideoProcesses;}+export function getMaxConcurrentVideoProcesses(): number {+ return maxConcurrentVideoProcesses;+}+export function canAcceptNewVideoProcess(): boolean {- return activeVideoProcesses < MAX_CONCURRENT_VIDEO_PROCESSES;+ return activeVideoProcesses < maxConcurrentVideoProcesses;}export function incrementActiveVideoProcesses(): void {@@ -136,6 +144,7 @@ export function updateJob(export function deleteJob(jobId: string): boolean {const job = jobs.get(jobId);if (job) {+ job.abortController?.abort();job.inputTempFile?.cleanup().catch(() => {});job.outputTempFile?.cleanup().catch(() => {});if (job.process) {@@ -147,6 +156,26 @@ export function deleteJob(jobId: string): boolean {return jobs.delete(jobId);}+export function abortAllJobs(): number {+ let aborted = 0;++ for (const job of jobs.values()) {+ if (+ job.phase !== "complete" &&+ job.phase !== "error" &&+ job.phase !== "cancelled"+ ) {+ job.abortController?.abort();+ job.phase = "cancelled";+ job.message = "Server shutting down";+ job.updatedAt = Date.now();+ aborted++;+ }+ }++ return aborted;+}+export function getAllJobs(): Job[] {return Array.from(jobs.values());}@@ -197,7 +226,7 @@ export async function sendWebhook(job: Job): Promise<void> {}}-setInterval(+const cleanupInterval = setInterval(() => {const cleaned = cleanupExpiredJobs();if (cleaned > 0) {@@ -206,3 +235,5 @@ setInterval(},5 * 60 * 1000,);++cleanupInterval.unref?.();diff --git a/apps/media-server/src/lib/subprocess.ts b/apps/media-server/src/lib/subprocess.tsnew file mode 100644index 000000000..3cbf69f99--- /dev/null+++ b/apps/media-server/src/lib/subprocess.ts@@ -0,0 +1,67 @@+import type { Subprocess } from "bun";++const PROCESS_EXIT_WAIT_MS = 5_000;+const FORCE_KILL_WAIT_MS = 1_000;++const activeSubprocesses = new Map<number, Subprocess>();++export function registerSubprocess<T extends Subprocess>(proc: T): T {+ activeSubprocesses.set(proc.pid, proc);+ return proc;+}++export function unregisterSubprocess(proc: Subprocess): void {+ activeSubprocesses.delete(proc.pid);+}++async function waitForProcessExit(+ proc: Pick<Subprocess, "exited" | "exitCode">,+ timeoutMs: number,+): Promise<boolean> {+ if (proc.exitCode !== null) {+ return true;+ }++ const result = await Promise.race([+ proc.exited.then(+ () => true,+ () => true,+ ),+ new Promise<false>((resolve) => {+ setTimeout(() => resolve(false), timeoutMs);+ }),+ ]);++ return result;+}++export async function terminateProcess(+ proc: Subprocess,+ timeoutMs = PROCESS_EXIT_WAIT_MS,+): Promise<void> {+ if (proc.exitCode !== null) {+ unregisterSubprocess(proc);+ return;+ }++ try {+ proc.kill("SIGTERM");+ } catch {}++ const exited = await waitForProcessExit(proc, timeoutMs);++ if (!exited && proc.exitCode === null) {+ try {+ proc.kill("SIGKILL");+ } catch {}++ await waitForProcessExit(proc, FORCE_KILL_WAIT_MS);+ }++ unregisterSubprocess(proc);+}++export async function terminateAllSubprocesses(): Promise<void> {+ const processes = Array.from(activeSubprocesses.values());+ await Promise.allSettled(processes.map((proc) => terminateProcess(proc)));+}diff --git a/apps/media-server/src/routes/video.ts b/apps/media-server/src/routes/video.tsindex e14e76fe7..00a0b430d 100644--- a/apps/media-server/src/routes/video.ts+++ b/apps/media-server/src/routes/video.ts@@ -26,6 +26,7 @@ import {getAllJobs,getJob,getJobProgress,+ getMaxConcurrentVideoProcesses,incrementActiveVideoProcesses,sendWebhook,updateJob,@@ -74,6 +75,7 @@ video.get("/status", (c) => {const jobs = getAllJobs();return c.json({activeVideoProcesses: getActiveVideoProcessCount(),+ maxConcurrentVideoProcesses: getMaxConcurrentVideoProcesses(),activeProbeProcesses: getActiveProbeProcessCount(),canAcceptNewVideoProcess: canAcceptNewVideoProcess(),canAcceptNewProbeProcess: canAcceptNewProbeProcess(),@@ -230,12 +232,15 @@ video.post("/process", async (c) => {}if (!canAcceptNewVideoProcess()) {+ const activeVideoProcesses = getActiveVideoProcessCount();+ const maxConcurrentVideoProcesses = getMaxConcurrentVideoProcesses();return c.json({error: "Server is busy",code: "SERVER_BUSY",- details:- "Too many concurrent video processing jobs, please retry later",+ details: `Too many concurrent video processing jobs (${activeVideoProcesses}/${maxConcurrentVideoProcesses}), please retry later`,+ activeVideoProcesses,+ maxConcurrentVideoProcesses,},503,);diff --git a/apps/web/workflows/import-loom-video.ts b/apps/web/workflows/import-loom-video.tsindex 47f2c18a8..b3d31c61d 100644--- a/apps/web/workflows/import-loom-video.ts+++ b/apps/web/workflows/import-loom-video.ts@@ -460,6 +460,61 @@ interface MediaServerProcessResult {};}+const MEDIA_SERVER_START_MAX_ATTEMPTS = 6;+const MEDIA_SERVER_START_RETRY_BASE_MS = 2000;++async function waitForRetry(delayMs: number): Promise<void> {+ await new Promise((resolve) => setTimeout(resolve, delayMs));+}++async function startMediaServerProcessJob(+ mediaServerUrl: string,+ body: {+ videoId: string;+ userId: string;+ videoUrl: string;+ outputPresignedUrl: string;+ thumbnailPresignedUrl: string;+ webhookUrl: string;+ },+): Promise<string> {+ for (let attempt = 0; attempt < MEDIA_SERVER_START_MAX_ATTEMPTS; attempt++) {+ const response = await fetch(`${mediaServerUrl}/video/process`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ });++ if (response.ok) {+ const { jobId } = (await response.json()) as { jobId: string };+ return jobId;+ }++ const errorData = (await response.json().catch(() => ({}))) as {+ error?: string;+ code?: string;+ details?: string;+ };+ const errorMessage =+ errorData.error ||+ errorData.details ||+ "Video processing failed to start";+ const shouldRetry =+ response.status === 503 &&+ (errorData.code === "SERVER_BUSY" ||+ errorMessage.includes("Server is busy"));++ if (shouldRetry && attempt < MEDIA_SERVER_START_MAX_ATTEMPTS - 1) {+ await waitForRetry(MEDIA_SERVER_START_RETRY_BASE_MS * 2 ** attempt);+ continue;+ }++ throw new Error(errorMessage);+ }++ throw new Error("Video processing failed to start");+}+async function processVideoOnMediaServer(payload: ImportLoomPayload,): Promise<MediaServerProcessResult> {@@ -505,28 +560,15 @@ async function processVideoOnMediaServer(const webhookUrl = `${webhookBaseUrl}/api/webhooks/media-server/progress`;- const response = await fetch(`${mediaServerUrl}/video/process`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- videoId,- userId,- videoUrl: rawVideoUrl,- outputPresignedUrl,- thumbnailPresignedUrl,- webhookUrl,- }),+ const jobId = await startMediaServerProcessJob(mediaServerUrl, {+ videoId,+ userId,+ videoUrl: rawVideoUrl,+ outputPresignedUrl,+ thumbnailPresignedUrl,+ webhookUrl,});- if (!response.ok) {- const errorData = (await response.json().catch(() => ({}))) as {- error?: string;- };- throw new Error(errorData.error || "Video processing failed to start");- }-- const { jobId } = (await response.json()) as { jobId: string };-return await pollForCompletion(mediaServerUrl, jobId);}diff --git a/apps/web/workflows/process-video.ts b/apps/web/workflows/process-video.tsindex 9dd51c6cc..1e4b91f83 100644--- a/apps/web/workflows/process-video.ts+++ b/apps/web/workflows/process-video.ts@@ -109,6 +109,9 @@ interface MediaServerProcessResult {};}+const MEDIA_SERVER_START_MAX_ATTEMPTS = 6;+const MEDIA_SERVER_START_RETRY_BASE_MS = 2000;+function getInputExtension(rawFileKey: string): string {const parts = rawFileKey.split(".");const extension = parts.at(-1)?.toLowerCase();@@ -120,6 +123,59 @@ function getInputExtension(rawFileKey: string): string {return `.${extension}`;}+async function waitForRetry(delayMs: number): Promise<void> {+ await new Promise((resolve) => setTimeout(resolve, delayMs));+}++async function startMediaServerProcessJob(+ mediaServerUrl: string,+ body: {+ videoId: string;+ userId: string;+ videoUrl: string;+ outputPresignedUrl: string;+ thumbnailPresignedUrl: string;+ webhookUrl: string;+ inputExtension: string;+ },+): Promise<string> {+ for (let attempt = 0; attempt < MEDIA_SERVER_START_MAX_ATTEMPTS; attempt++) {+ const response = await fetch(`${mediaServerUrl}/video/process`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ });++ if (response.ok) {+ const { jobId } = (await response.json()) as { jobId: string };+ return jobId;+ }++ const errorData = (await response.json().catch(() => ({}))) as {+ error?: string;+ code?: string;+ details?: string;+ };+ const errorMessage =+ errorData.error ||+ errorData.details ||+ "Video processing failed to start";+ const shouldRetry =+ response.status === 503 &&+ (errorData.code === "SERVER_BUSY" ||+ errorMessage.includes("Server is busy"));++ if (shouldRetry && attempt < MEDIA_SERVER_START_MAX_ATTEMPTS - 1) {+ await waitForRetry(MEDIA_SERVER_START_RETRY_BASE_MS * 2 ** attempt);+ continue;+ }++ throw new Error(errorMessage);+ }++ throw new Error("Video processing failed to start");+}+async function processVideoOnMediaServer(videoId: string,userId: string,@@ -160,30 +216,16 @@ async function processVideoOnMediaServer(const webhookUrl = `${webhookBaseUrl}/api/webhooks/media-server/progress`;- const response = await fetch(`${mediaServerUrl}/video/process`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- videoId,- userId,- videoUrl: rawVideoUrl,- outputPresignedUrl,- thumbnailPresignedUrl,- webhookUrl,- inputExtension: getInputExtension(rawFileKey),- }),+ const jobId = await startMediaServerProcessJob(mediaServerUrl, {+ videoId,+ userId,+ videoUrl: rawVideoUrl,+ outputPresignedUrl,+ thumbnailPresignedUrl,+ webhookUrl,+ inputExtension: getInputExtension(rawFileKey),});- if (!response.ok) {- const errorData = await response.json().catch(() => ({}));- throw new Error(- (errorData as { error?: string }).error ||- "Video processing failed to start",- );- }-- const { jobId } = (await response.json()) as { jobId: string };-const result = await pollForCompletion(mediaServerUrl, jobId);return result;