添加Watchdog

This commit is contained in:
CN-JS-HuiBai
2026-04-04 12:54:02 +08:00
parent c607af6fac
commit 4391eea04d

View File

@@ -679,9 +679,26 @@ app.get('/api/hls/playlist.m3u8', async (req, res) => {
res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Cache-Control', 'no-cache');
res.send(m3u8); res.send(m3u8);
}); });
const hlsProcesses = new Map(); const hlsProcesses = new Map();
// Watchdog: Kill HLS transcoding if the frontend stops requesting segments
setInterval(() => {
const now = Date.now();
for (const [key, processInfo] of hlsProcesses.entries()) {
if (processInfo.lastActive && now - processInfo.lastActive > 30000) {
try {
if (processInfo.command) {
processInfo.command.kill('SIGKILL');
}
} catch (e) {
console.warn(`Failed to kill inactive HLS process for ${key}:`, e);
}
hlsProcesses.delete(key);
console.log(`[Watchdog] Terminated inactive HLS transcode for ${key}`);
}
}
}, 10000);
app.get('/api/hls/segment.ts', async (req, res) => { app.get('/api/hls/segment.ts', async (req, res) => {
const bucket = req.query.bucket; const bucket = req.query.bucket;
const key = req.query.key; const key = req.query.key;
@@ -702,6 +719,10 @@ app.get('/api/hls/segment.ts', async (req, res) => {
const targetSegPath = path.join(hlsDir, `segment_${seg}.ts`); const targetSegPath = path.join(hlsDir, `segment_${seg}.ts`);
let currentProcess = hlsProcesses.get(progressKey); let currentProcess = hlsProcesses.get(progressKey);
if (currentProcess) {
currentProcess.lastActive = Date.now();
}
const checkIsCachedAndCompleted = () => { const checkIsCachedAndCompleted = () => {
if (!fs.existsSync(targetSegPath)) return false; if (!fs.existsSync(targetSegPath)) return false;
const m3u8Path = path.join(hlsDir, `temp.m3u8`); const m3u8Path = path.join(hlsDir, `temp.m3u8`);
@@ -799,7 +820,7 @@ app.get('/api/hls/segment.ts', async (req, res) => {
}); });
ffmpegCommand.run(); ffmpegCommand.run();
currentProcess = { command: ffmpegCommand, currentSeg: seg }; currentProcess = { command: ffmpegCommand, currentSeg: seg, lastActive: Date.now() };
hlsProcesses.set(progressKey, currentProcess); hlsProcesses.set(progressKey, currentProcess);
} }
@@ -807,8 +828,10 @@ app.get('/api/hls/segment.ts', async (req, res) => {
if (!ready) { if (!ready) {
return res.status(500).send('Segment generation timeout'); return res.status(500).send('Segment generation timeout');
} }
if (currentProcess) {
if (currentProcess) currentProcess.currentSeg = Math.max(currentProcess.currentSeg, seg); currentProcess.currentSeg = Math.max(currentProcess.currentSeg, seg);
currentProcess.lastActive = Date.now();
}
res.setHeader('Content-Type', 'video/MP2T'); res.setHeader('Content-Type', 'video/MP2T');
res.sendFile(targetSegPath); res.sendFile(targetSegPath);