diff --git a/server/src/motion.ts b/server/src/motion.ts index 71e2c13..c574673 100644 --- a/server/src/motion.ts +++ b/server/src/motion.ts @@ -182,7 +182,9 @@ export class MotionDetector { }, onStderr: (line) => { const score = parseSceneScore(line); - if (score === undefined || Date.now() - startedAt < 5000) return; + if (score === undefined) return; + det.sup.progress(); + if (Date.now() - startedAt < 5000) return; for (const ev of tracker.feed(Date.now(), score)) this.dispatch(det, ev); }, onExit: () => { @@ -190,6 +192,8 @@ export class MotionDetector { }, minBackoffMs: 5000, maxBackoffMs: 120_000, + // Scene scores arrive twice a second; with -skip_frame nokey they come in bursts per keyframe. + stallMs: 60_000, }), }; this.dets.set(cam.id, det); diff --git a/server/src/proc.ts b/server/src/proc.ts index a332a1f..75c465a 100644 --- a/server/src/proc.ts +++ b/server/src/proc.ts @@ -29,6 +29,12 @@ export type SupervisorOpts = { minBackoffMs?: number; maxBackoffMs?: number; healthyAfterMs?: number; + /** + * Restart the process when it keeps running but `progress()` has not been called for this long. + * ffmpeg can stay alive without producing anything, e.g. after the camera behind go2rtc reconnects + * and the RTP timestamps jump; it never exits, so the exit-based restart alone does not recover it. + */ + stallMs?: number; }; export class Supervisor { @@ -37,6 +43,8 @@ export class Supervisor { private backoff: number; private timer?: ReturnType; private startedAt = 0; + private lastProgress = 0; + private stallTimer?: ReturnType; lastError?: string; restarts = 0; readonly log: Logger; @@ -57,9 +65,33 @@ export class Supervisor { start(): void { if (!this.stopped) return; this.stopped = false; + const stallMs = this.opts.stallMs; + if (stallMs && stallMs > 0) { + clearInterval(this.stallTimer); + this.stallTimer = setInterval(() => this.checkStall(stallMs), Math.min(10_000, Math.max(1000, stallMs / 3))); + } this.spawn(); } + /** Marks that the process produced output, see `stallMs`. */ + progress(): void { + this.lastProgress = Date.now(); + } + + private checkStall(stallMs: number) { + const p = this.proc; + if (!p || p.exitCode !== null || this.stopped) return; + const idle = Date.now() - Math.max(this.lastProgress, this.startedAt); + if (idle < stallMs) return; + this.lastError = `no progress for ${Math.round(idle / 1000)}s`; + this.log.warn(`${this.lastError}, restarting`); + this.lastProgress = Date.now(); + p.kill("SIGINT"); // lets ffmpeg finish the current file; handleExit() schedules the restart + setTimeout(() => { + if (this.proc === p && p.exitCode === null) p.kill("SIGKILL"); + }, 5000); + } + private spawn(): void { if (this.stopped) return; const spec = this.opts.command(); @@ -77,6 +109,7 @@ export class Supervisor { }); this.proc = proc; this.startedAt = Date.now(); + this.lastProgress = this.startedAt; this.opts.onStart?.(); void readLines(proc.stdout, (l) => this.opts.onStdout?.(l)); void readLines(proc.stderr, (l) => { @@ -112,6 +145,8 @@ export class Supervisor { async stop(): Promise { this.stopped = true; clearTimeout(this.timer); + clearInterval(this.stallTimer); + this.stallTimer = undefined; const p = this.proc; this.proc = undefined; if (!p) return; diff --git a/server/src/recorder.ts b/server/src/recorder.ts index f0843f8..7883612 100644 --- a/server/src/recorder.ts +++ b/server/src/recorder.ts @@ -24,7 +24,7 @@ export type RecorderDeps = { getCamera: (cameraId: string) => CameraRecord | undefined; }; -type Entry = { sup: Supervisor; key: string; cam: CameraRecord; lastSegmentAt: number; lastError?: string }; +type Entry = { sup: Supervisor; key: string; cam: CameraRecord; lastSegmentAt: number; lastError?: string; lastSize?: string }; export function buildRecordArgs(o: { ffmpeg: string; @@ -150,6 +150,8 @@ export class Recorder { }, minBackoffMs: 3000, maxBackoffMs: 60_000, + // The segment being written grows continuously; doScan() (every 20 s) reports growth as progress. + stallMs: 90_000, }), }; this.entries.set(cam.id, entry); @@ -176,6 +178,17 @@ export class Recorder { for (const f of readdirSync(join(dir, day))) if (/^\d{6}\.mp4$/.test(f)) files.push(`${day}/${f}`); } files.sort(); + const newest = files[files.length - 1]; + if (entry && newest) { + try { + const st = statSync(join(dir, newest)); + const mark = `${newest}:${st.size}`; + if (mark !== entry.lastSize) { + entry.lastSize = mark; + entry.sup.progress(); + } + } catch {} + } const active = !includeNewest && entry?.sup.running; const finished = active ? files.slice(0, -1) : files; for (const rel of finished) { diff --git a/server/test/proc.test.ts b/server/test/proc.test.ts new file mode 100644 index 0000000..fd48fe4 --- /dev/null +++ b/server/test/proc.test.ts @@ -0,0 +1,52 @@ +import { expect, test } from "bun:test"; +import { Supervisor } from "../src/proc.ts"; + +test("supervisor restarts a process that stops making progress", async () => { + let starts = 0; + const sup = new Supervisor("stall-test", { + command: () => ({ cmd: ["sleep", "30"] }), + onStart: () => { + starts++; + }, + minBackoffMs: 50, + stallMs: 1000, + }); + sup.start(); + await Bun.sleep(2600); + await sup.stop(); + expect(starts).toBeGreaterThanOrEqual(2); + expect(sup.lastError).toContain("no progress"); +}); + +test("progress() keeps a quiet but healthy process running", async () => { + let starts = 0; + const sup = new Supervisor("stall-test-ok", { + command: () => ({ cmd: ["sleep", "30"] }), + onStart: () => { + starts++; + }, + minBackoffMs: 50, + stallMs: 1000, + }); + sup.start(); + const t = setInterval(() => sup.progress(), 200); + await Bun.sleep(2600); + clearInterval(t); + await sup.stop(); + expect(starts).toBe(1); +}); + +test("without stallMs a silent process is left alone", async () => { + let starts = 0; + const sup = new Supervisor("no-stall", { + command: () => ({ cmd: ["sleep", "30"] }), + onStart: () => { + starts++; + }, + minBackoffMs: 50, + }); + sup.start(); + await Bun.sleep(1500); + await sup.stop(); + expect(starts).toBe(1); +});