Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add job heartbeat and extend max lifetime

Richie McIlroy0a16319af53b
diff --git a/apps/media-server/src/__tests__/lib/job-manager.test.ts b/apps/media-server/src/__tests__/lib/job-manager.test.ts
new file mode 100644
index 000000000..c138649fd
--- /dev/null
+++ b/apps/media-server/src/__tests__/lib/job-manager.test.ts
@@ -0,0 +1,83 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import {
+ cleanupExpiredJobs,
+ createJob,
+ deleteJob,
+ getJob,
+ touchJob,
+} from "../../lib/job-manager";
+
+const createdJobs: string[] = [];
+
+function createTrackedJob(jobId: string) {
+ createdJobs.push(jobId);
+ return createJob(jobId, "video-id", "user-id");
+}
+
+afterEach(() => {
+ for (const jobId of createdJobs.splice(0)) {
+ deleteJob(jobId);
+ }
+});
+
+describe("job cleanup", () => {
+ test("keeps a processing job alive after a heartbeat", () => {
+ const job = createTrackedJob("job-heartbeat");
+ const now = Date.now();
+ job.phase = "processing";
+ job.createdAt = now - 20 * 60 * 1000;
+ job.updatedAt = now - 16 * 60 * 1000;
+
+ touchJob(job.jobId);
+
+ const cleaned = cleanupExpiredJobs();
+ const currentJob = getJob(job.jobId);
+
+ expect(cleaned).toBe(0);
+ expect(currentJob?.phase).toBe("processing");
+ });
+
+ test("marks an untouched stale processing job as error", () => {
+ const job = createTrackedJob("job-stale");
+ const now = Date.now();
+ job.phase = "processing";
+ job.createdAt = now - 20 * 60 * 1000;
+ job.updatedAt = now - 16 * 60 * 1000;
+
+ const cleaned = cleanupExpiredJobs();
+ const currentJob = getJob(job.jobId);
+
+ expect(cleaned).toBe(1);
+ expect(currentJob?.phase).toBe("error");
+ expect(currentJob?.error).toContain("Job stale");
+ });
+
+ test("allows active jobs below the one-hour lifetime cap", () => {
+ const job = createTrackedJob("job-below-lifetime");
+ const now = Date.now();
+ job.phase = "processing";
+ job.createdAt = now - 50 * 60 * 1000;
+ job.updatedAt = now;
+
+ const cleaned = cleanupExpiredJobs();
+ const currentJob = getJob(job.jobId);
+
+ expect(cleaned).toBe(0);
+ expect(currentJob?.phase).toBe("processing");
+ });
+
+ test("marks active jobs past the one-hour lifetime cap as error", () => {
+ const job = createTrackedJob("job-past-lifetime");
+ const now = Date.now();
+ job.phase = "processing";
+ job.createdAt = now - 61 * 60 * 1000;
+ job.updatedAt = now;
+
+ const cleaned = cleanupExpiredJobs();
+ const currentJob = getJob(job.jobId);
+
+ expect(cleaned).toBe(1);
+ expect(currentJob?.phase).toBe("error");
+ expect(currentJob?.error).toContain("maximum lifetime of 60 minutes");
+ });
+});
diff --git a/apps/media-server/src/lib/job-manager.ts b/apps/media-server/src/lib/job-manager.ts
index e5dd7a703..bce6f11ce 100644
--- a/apps/media-server/src/lib/job-manager.ts
+++ b/apps/media-server/src/lib/job-manager.ts
@@ -60,7 +60,7 @@ export interface Job {
const jobs = new Map<string, Job>();
const JOB_TTL_MS = 60 * 60 * 1000;
const STALE_JOB_MS = 15 * 60 * 1000;
-const MAX_JOB_LIFETIME_MS = 45 * 60 * 1000;
+const MAX_JOB_LIFETIME_MS = 60 * 60 * 1000;
const WEBHOOK_MAX_ATTEMPTS = 3;
const WEBHOOK_RETRY_BASE_MS = 500;
const WEBHOOK_TIMEOUT_MS = 5000;
@@ -232,6 +232,14 @@ export function updateJob(
return job;
}
+export function touchJob(jobId: string): Job | undefined {
+ const job = jobs.get(jobId);
+ if (!job) return undefined;
+
+ job.updatedAt = Date.now();
+ return job;
+}
+
export function deleteJob(jobId: string): boolean {
const job = jobs.get(jobId);
if (job) {
diff --git a/apps/media-server/src/routes/video.ts b/apps/media-server/src/routes/video.ts
index bb3d7c5af..a3354bd8b 100644
--- a/apps/media-server/src/routes/video.ts
+++ b/apps/media-server/src/routes/video.ts
@@ -31,12 +31,14 @@ import {
getMaxConcurrentVideoProcesses,
getSystemResources,
sendWebhook,
+ touchJob,
updateJob,
} from "../lib/job-manager";
import type { TempFileHandle } from "../lib/temp-files";
import { cleanupStaleTempFiles } from "../lib/temp-files";
const video = new Hono();
+const PROCESSING_HEARTBEAT_MS = 60 * 1000;
const probeSchema = z.object({
videoUrl: z.string().url(),
@@ -142,6 +144,33 @@ async function createVideoDownloadResponse(
});
}
+async function withJobHeartbeat<T>(
+ jobId: string,
+ operation: () => Promise<T>,
+): Promise<T> {
+ const interval = setInterval(() => {
+ const job = getJob(jobId);
+ if (
+ !job ||
+ job.phase === "complete" ||
+ job.phase === "error" ||
+ job.phase === "cancelled"
+ ) {
+ clearInterval(interval);
+ return;
+ }
+
+ touchJob(jobId);
+ }, PROCESSING_HEARTBEAT_MS);
+ interval.unref?.();
+
+ try {
+ return await operation();
+ } finally {
+ clearInterval(interval);
+ }
+}
+
video.get("/status", (c) => {
const jobs = getAllJobs();
const resources = getSystemResources();
@@ -583,27 +612,7 @@ async function processWithResilientRetry(
}
};
- try {
- const outputFile = await processVideo(
- inputPath,
- metadata,
- processOptions,
- onProgress,
- abortSignal,
- );
- return { outputFile, lastResortRepairFile: null };
- } catch (firstError) {
- if (!isWebm) throw firstError;
-
- console.warn(
- `[processWithResilientRetry] First transcode attempt failed: ${firstError instanceof Error ? firstError.message : String(firstError)}`,
- );
-
- updateJob(jobId, {
- progress: 10,
- message: "Retrying with error recovery...",
- });
-
+ return await withJobHeartbeat(jobId, async () => {
try {
const outputFile = await processVideo(
inputPath,
@@ -611,55 +620,77 @@ async function processWithResilientRetry(
processOptions,
onProgress,
abortSignal,
- RESILIENT_FLAGS,
);
return { outputFile, lastResortRepairFile: null };
- } catch (retryError) {
+ } catch (firstError) {
+ if (!isWebm) throw firstError;
+
console.warn(
- `[processWithResilientRetry] Resilient retry also failed: ${retryError instanceof Error ? retryError.message : String(retryError)}`,
+ `[processWithResilientRetry] First transcode attempt failed: ${firstError instanceof Error ? firstError.message : String(firstError)}`,
);
- }
- console.log(
- "[processWithResilientRetry] Attempting last-resort container repair and transcode...",
- );
+ updateJob(jobId, {
+ progress: 10,
+ message: "Retrying with error recovery...",
+ });
- updateJob(jobId, {
- progress: 10,
- message: "Attempting full repair...",
- });
+ try {
+ const outputFile = await processVideo(
+ inputPath,
+ metadata,
+ processOptions,
+ onProgress,
+ abortSignal,
+ RESILIENT_FLAGS,
+ );
+ return { outputFile, lastResortRepairFile: null };
+ } catch (retryError) {
+ console.warn(
+ `[processWithResilientRetry] Resilient retry also failed: ${retryError instanceof Error ? retryError.message : String(retryError)}`,
+ );
+ }
- let lastResortRepairFile: TempFileHandle | null = null;
- try {
- lastResortRepairFile = await repairContainer(
- originalInputPath,
- abortSignal,
+ console.log(
+ "[processWithResilientRetry] Attempting last-resort container repair and transcode...",
);
- let repairedMetadata: VideoMetadata;
+ updateJob(jobId, {
+ progress: 10,
+ message: "Attempting full repair...",
+ });
+
+ let lastResortRepairFile: TempFileHandle | null = null;
try {
- repairedMetadata = await probeVideoFile(lastResortRepairFile.path);
- } catch {
- repairedMetadata = metadata;
- }
+ lastResortRepairFile = await repairContainer(
+ originalInputPath,
+ abortSignal,
+ );
- const outputFile = await processVideo(
- lastResortRepairFile.path,
- repairedMetadata,
- processOptions,
- onProgress,
- abortSignal,
- RESILIENT_FLAGS,
- );
- return { outputFile, lastResortRepairFile };
- } catch (lastResortError) {
- console.error(
- `[processWithResilientRetry] Last-resort repair+transcode failed: ${lastResortError instanceof Error ? lastResortError.message : String(lastResortError)}`,
- );
- await lastResortRepairFile?.cleanup();
- throw lastResortError;
+ let repairedMetadata: VideoMetadata;
+ try {
+ repairedMetadata = await probeVideoFile(lastResortRepairFile.path);
+ } catch {
+ repairedMetadata = metadata;
+ }
+
+ const outputFile = await processVideo(
+ lastResortRepairFile.path,
+ repairedMetadata,
+ processOptions,
+ onProgress,
+ abortSignal,
+ RESILIENT_FLAGS,
+ );
+ return { outputFile, lastResortRepairFile };
+ } catch (lastResortError) {
+ console.error(
+ `[processWithResilientRetry] Last-resort repair+transcode failed: ${lastResortError instanceof Error ? lastResortError.message : String(lastResortError)}`,
+ );
+ await lastResortRepairFile?.cleanup();
+ throw lastResortError;
+ }
}
- }
+ });
}
async function processVideoAsync(