dragonflight/services/mam-api/src/routes/schedules.js

158 lines
6 KiB
JavaScript
Raw Normal View History

// Recorder scheduler — CRUD for upcoming + historic recording windows.
//
// The actual start/stop transitions happen in src/scheduler.js; this route
// just owns the recorder_schedules rows.
import express from 'express';
import pool from '../db/pool.js';
chore: 1.2 ship-prep sweep — close 38 issues Frontend / UX / a11y - Sidebar collapse/expand toggle with localStorage persistence (#142) - Settings sections wrap inputs in <form> with Enter-to-submit + native validation; password autocomplete=new-password (#141, #138) - Asset thumbnails get descriptive alt text (#140) - Production deploy now precompiles JSX via esbuild and loads the production React UMD instead of dev builds + in-browser Babel (#139, #122) - Search wrapper gets role=search; global search input gets aria-label, role=combobox, aria-controls/aria-expanded/aria-activedescendant wiring (#137, #135) - Dashboard and Library no longer share the same nav icon (#136) - Sidebar collapses off-canvas with a topbar menu button below 768 px; mobile default is collapsed (#134) - --text-3 bumped to #8B92A0 for WCAG AA contrast on --bg-0 (#133) - Schedule and Library routes were rendering empty inside the .main flex container — switched to flex:1 + min-height:0 (#131, #132, editor + asset detail get the same fix) - Jobs nav badge now polls /jobs?status=active every 10 s and reflects the live count (#130, #113) - aria-label sweep on every icon-only button (#126) - Premiere panel release list moved to window.PREMIERE_RELEASES in data.jsx; Editor + Settings read from the same source (#125) - Typo setPgMclips → setPgmClips (#124) - Stray console.error / console.warn calls gated behind window.DF_LOG.{warn,error} (#123) - Hardcoded /api/v1 paths route through window.ZAMPP_API_PREFIX (#115) - Schedule rows no longer crash on null recorder_id (#117) - EditorKeyboard guards against document.activeElement === null (#116) - Unmount-safe timers for PasswordResetModal, Containers, Editor (#111) - Player seek clamps below totalMs, server-side range clamping + uncached 416 on EOF, client-side EOF-stall watchdog (#143) - Duration badge overlap fix on narrow asset cards (#52) Backend / security / reliability - GET /recorders fixed N+1: single LATERAL JOIN for live_asset_id; Docker inspects bounded to actually-recording rows (#121) - Upload disk-storage (multer.diskStorage) streams parts to S3 instead of buffering 500 MB in RAM (#120) - /assets list clamps limit to MAX_LIMIT=500 to prevent OOM (#119) - SDK upload archive listing + post-extract sanitize block zip-slip / tar-slip and symlink escapes (#118) - Migrations track applied state in schema_migrations, run in a transaction, and exit non-zero on failure (#107) - node-agent BMD_COUNT override uses BMD_DEVICE_PREFIX; filesystem detection wins (#109, #127) - GPU_COUNT override now merges with nvidia-smi enrichment (#108) - /cluster/heartbeat requires a node-bound token or admin user; tokens carry bound_hostname (#106) - /recorders/:id/start error responses no longer echo the Docker create payload — env vars stay out of client responses (#105) - /recorders/probe restricts schemes (srt/rtmp/rtsp/udp/rtp), blocks private + loopback hosts for non-admins, denies common service ports (#104) - Scheduler tick guarded by a Postgres advisory lock; pending/running rows claimed via UPDATE...RETURNING + FOR UPDATE SKIP LOCKED to survive multi-node deploys (#103) - UUID validateUuid('id') param middleware on every /:id route (#102) - Error handler scrubs Postgres error messages and 5xx detail (#101) - Graceful SIGTERM/SIGINT shutdown — stops scheduler, drains the HTTP server, ends the pool, 25 s force-exit watchdog (#100) - AMPP sync moved from fire-and-forget to a persisted retry queue (ampp_sync_status / attempts / next_attempt_at + scheduler retry loop with exponential backoff) (#77) Migrations - 019: api_tokens.bound_hostname (#106) - 020: assets.ampp_sync_status + retry bookkeeping (#77) Other - Defer #92 Growing-files per-upload toggle, #80 Audio tab, #57 Dashboard redesign, #56 Editor SPA polish phase 3, #114 S3 migration tool to v1.3
2026-05-26 22:06:14 -04:00
import { validateUuid } from '../middleware/errors.js';
const router = express.Router();
chore: 1.2 ship-prep sweep — close 38 issues Frontend / UX / a11y - Sidebar collapse/expand toggle with localStorage persistence (#142) - Settings sections wrap inputs in <form> with Enter-to-submit + native validation; password autocomplete=new-password (#141, #138) - Asset thumbnails get descriptive alt text (#140) - Production deploy now precompiles JSX via esbuild and loads the production React UMD instead of dev builds + in-browser Babel (#139, #122) - Search wrapper gets role=search; global search input gets aria-label, role=combobox, aria-controls/aria-expanded/aria-activedescendant wiring (#137, #135) - Dashboard and Library no longer share the same nav icon (#136) - Sidebar collapses off-canvas with a topbar menu button below 768 px; mobile default is collapsed (#134) - --text-3 bumped to #8B92A0 for WCAG AA contrast on --bg-0 (#133) - Schedule and Library routes were rendering empty inside the .main flex container — switched to flex:1 + min-height:0 (#131, #132, editor + asset detail get the same fix) - Jobs nav badge now polls /jobs?status=active every 10 s and reflects the live count (#130, #113) - aria-label sweep on every icon-only button (#126) - Premiere panel release list moved to window.PREMIERE_RELEASES in data.jsx; Editor + Settings read from the same source (#125) - Typo setPgMclips → setPgmClips (#124) - Stray console.error / console.warn calls gated behind window.DF_LOG.{warn,error} (#123) - Hardcoded /api/v1 paths route through window.ZAMPP_API_PREFIX (#115) - Schedule rows no longer crash on null recorder_id (#117) - EditorKeyboard guards against document.activeElement === null (#116) - Unmount-safe timers for PasswordResetModal, Containers, Editor (#111) - Player seek clamps below totalMs, server-side range clamping + uncached 416 on EOF, client-side EOF-stall watchdog (#143) - Duration badge overlap fix on narrow asset cards (#52) Backend / security / reliability - GET /recorders fixed N+1: single LATERAL JOIN for live_asset_id; Docker inspects bounded to actually-recording rows (#121) - Upload disk-storage (multer.diskStorage) streams parts to S3 instead of buffering 500 MB in RAM (#120) - /assets list clamps limit to MAX_LIMIT=500 to prevent OOM (#119) - SDK upload archive listing + post-extract sanitize block zip-slip / tar-slip and symlink escapes (#118) - Migrations track applied state in schema_migrations, run in a transaction, and exit non-zero on failure (#107) - node-agent BMD_COUNT override uses BMD_DEVICE_PREFIX; filesystem detection wins (#109, #127) - GPU_COUNT override now merges with nvidia-smi enrichment (#108) - /cluster/heartbeat requires a node-bound token or admin user; tokens carry bound_hostname (#106) - /recorders/:id/start error responses no longer echo the Docker create payload — env vars stay out of client responses (#105) - /recorders/probe restricts schemes (srt/rtmp/rtsp/udp/rtp), blocks private + loopback hosts for non-admins, denies common service ports (#104) - Scheduler tick guarded by a Postgres advisory lock; pending/running rows claimed via UPDATE...RETURNING + FOR UPDATE SKIP LOCKED to survive multi-node deploys (#103) - UUID validateUuid('id') param middleware on every /:id route (#102) - Error handler scrubs Postgres error messages and 5xx detail (#101) - Graceful SIGTERM/SIGINT shutdown — stops scheduler, drains the HTTP server, ends the pool, 25 s force-exit watchdog (#100) - AMPP sync moved from fire-and-forget to a persisted retry queue (ampp_sync_status / attempts / next_attempt_at + scheduler retry loop with exponential backoff) (#77) Migrations - 019: api_tokens.bound_hostname (#106) - 020: assets.ampp_sync_status + retry bookkeeping (#77) Other - Defer #92 Growing-files per-upload toggle, #80 Audio tab, #57 Dashboard redesign, #56 Editor SPA polish phase 3, #114 S3 migration tool to v1.3
2026-05-26 22:06:14 -04:00
router.param('id', (req, res, next) => validateUuid('id')(req, res, next));
const ALLOWED_RECURRENCE = new Set(['none', 'daily', 'weekly']);
const TERMINAL = new Set(['completed', 'failed', 'cancelled']);
function rowToJson(r) {
return {
id: r.id,
name: r.name,
recorder_id: r.recorder_id,
recorder_name: r.recorder_name || null,
start_at: r.start_at,
end_at: r.end_at,
recurrence: r.recurrence,
status: r.status,
last_asset_id: r.last_asset_id,
error_message: r.error_message,
created_at: r.created_at,
updated_at: r.updated_at,
};
}
const ALLOWED_STATUS_FILTER = new Set(['all', 'upcoming', 'past']);
// GET /api/v1/schedules?status=upcoming|past|all
router.get('/', async (req, res, next) => {
try {
const status = (req.query.status || 'all').toLowerCase();
if (!ALLOWED_STATUS_FILTER.has(status)) {
return res.status(400).json({ error: `status must be one of: ${[...ALLOWED_STATUS_FILTER].join(', ')}` });
}
let where = 'TRUE';
if (status === 'upcoming') where = `(s.status IN ('pending','running') OR s.end_at >= NOW() - INTERVAL '1 hour')`;
else if (status === 'past') where = `s.status IN ('completed','failed','cancelled') AND s.end_at < NOW()`;
const result = await pool.query(
`SELECT s.*, r.name AS recorder_name
FROM recorder_schedules s
LEFT JOIN recorders r ON r.id = s.recorder_id
WHERE ${where}
ORDER BY s.start_at ASC
LIMIT 200`
);
res.json({ schedules: result.rows.map(rowToJson) });
} catch (err) { next(err); }
});
// POST /api/v1/schedules
router.post('/', async (req, res, next) => {
try {
const { name, recorder_id, start_at, end_at, recurrence } = req.body || {};
if (!name || !recorder_id || !start_at || !end_at) {
return res.status(400).json({ error: 'name, recorder_id, start_at and end_at are required' });
}
const rec = (recurrence || 'none').toLowerCase();
if (!ALLOWED_RECURRENCE.has(rec)) {
return res.status(400).json({ error: `recurrence must be one of: ${[...ALLOWED_RECURRENCE].join(', ')}` });
}
if (new Date(end_at) <= new Date(start_at)) {
return res.status(400).json({ error: 'end_at must be after start_at' });
}
// Make sure the recorder exists before binding to it.
const rExists = await pool.query('SELECT id FROM recorders WHERE id = $1', [recorder_id]);
if (rExists.rows.length === 0) {
return res.status(400).json({ error: 'Unknown recorder_id' });
}
const ins = await pool.query(
`INSERT INTO recorder_schedules (name, recorder_id, start_at, end_at, recurrence, status)
VALUES ($1, $2, $3, $4, $5, 'pending')
RETURNING *`,
[name.trim(), recorder_id, start_at, end_at, rec]
);
res.status(201).json(rowToJson(ins.rows[0]));
} catch (err) { next(err); }
});
// PUT /api/v1/schedules/:id — edit a not-yet-started schedule
router.put('/:id', async (req, res, next) => {
try {
const { id } = req.params;
const current = await pool.query('SELECT * FROM recorder_schedules WHERE id = $1', [id]);
if (current.rows.length === 0) return res.status(404).json({ error: 'Schedule not found' });
if (current.rows[0].status === 'running') {
return res.status(400).json({ error: 'Cannot edit a running schedule; cancel it first' });
}
const fields = ['name','start_at','end_at','recurrence'];
const updates = [];
const values = [];
let i = 1;
for (const f of fields) {
if (req.body[f] !== undefined) {
if (f === 'recurrence' && !ALLOWED_RECURRENCE.has(String(req.body[f]).toLowerCase())) {
return res.status(400).json({ error: 'invalid recurrence' });
}
updates.push(`${f} = $${i++}`);
values.push(req.body[f]);
}
}
if (updates.length === 0) return res.json(rowToJson(current.rows[0]));
updates.push('updated_at = NOW()');
values.push(id);
const result = await pool.query(
`UPDATE recorder_schedules SET ${updates.join(', ')} WHERE id = $${i} RETURNING *`,
values
);
res.json(rowToJson(result.rows[0]));
} catch (err) { next(err); }
});
// POST /api/v1/schedules/:id/cancel — cancel a pending or running schedule
router.post('/:id/cancel', async (req, res, next) => {
try {
const { id } = req.params;
const cur = await pool.query('SELECT * FROM recorder_schedules WHERE id = $1', [id]);
if (cur.rows.length === 0) return res.status(404).json({ error: 'Schedule not found' });
if (TERMINAL.has(cur.rows[0].status)) {
return res.status(400).json({ error: `Schedule is already ${cur.rows[0].status}` });
}
// Just mark as cancelled — the tick loop will stop the recorder if it's
// currently running and the schedule has just been cancelled.
const result = await pool.query(
`UPDATE recorder_schedules SET status = 'cancelled', updated_at = NOW()
WHERE id = $1 RETURNING *`,
[id]
);
res.json(rowToJson(result.rows[0]));
} catch (err) { next(err); }
});
// DELETE /api/v1/schedules/:id — hard delete (terminal schedules only)
router.delete('/:id', async (req, res, next) => {
try {
const { id } = req.params;
const cur = await pool.query('SELECT status FROM recorder_schedules WHERE id = $1', [id]);
if (cur.rows.length === 0) return res.status(404).json({ error: 'Schedule not found' });
if (!TERMINAL.has(cur.rows[0].status) && cur.rows[0].status !== 'pending') {
return res.status(400).json({ error: 'Cancel a running schedule before deleting' });
}
await pool.query('DELETE FROM recorder_schedules WHERE id = $1', [id]);
res.json({ message: 'Schedule deleted' });
} catch (err) { next(err); }
});
export default router;