Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion server/src/motion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,14 +182,18 @@ 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: () => {
for (const ev of tracker.flush()) this.dispatch(det, ev);
},
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);
Expand Down
35 changes: 35 additions & 0 deletions server/src/proc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -37,6 +43,8 @@ export class Supervisor {
private backoff: number;
private timer?: ReturnType<typeof setTimeout>;
private startedAt = 0;
private lastProgress = 0;
private stallTimer?: ReturnType<typeof setInterval>;
lastError?: string;
restarts = 0;
readonly log: Logger;
Expand All @@ -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();
Expand All @@ -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) => {
Expand Down Expand Up @@ -112,6 +145,8 @@ export class Supervisor {
async stop(): Promise<void> {
this.stopped = true;
clearTimeout(this.timer);
clearInterval(this.stallTimer);
this.stallTimer = undefined;
const p = this.proc;
this.proc = undefined;
if (!p) return;
Expand Down
15 changes: 14 additions & 1 deletion server/src/recorder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand All @@ -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) {
Expand Down
52 changes: 52 additions & 0 deletions server/test/proc.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});