OrbiSubs panel: catch async route errors; take busy before the first await

Revisión externa 2.1, 2.2 y 2.4: asyncHandler + errorHandler (500 y log) en vez de tumbar el panel con un rechazo. PUT, DELETE y start marcan el canal ocupado antes de esperar a systemd. Puerto SRT del modal hasta 55000, como el servidor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JAUCv2ADyD2NSg4ub9YPr1
This commit is contained in:
guy
2026-11-22 14:12:04 -03:00
parent e8261ab458
commit d600150088
5 changed files with 168 additions and 66 deletions
+16
View File
@@ -0,0 +1,16 @@
'use strict';
// http.js — rutas async y manejador de errores del panel.
//
// Express 4 no captura el rechazo de un handler async: con Node 22 una promesa rechazada
// sin catch tira abajo el proceso, o sea el panel entero, por ejemplo si falla
// systemctl o la base en medio de un pedido (revisión externa, 2.1). asyncHandler pasa el
// error a next() y errorHandler responde 500 y lo loguea.
const asyncHandler = fn => (req, res, next) => Promise.resolve().then(() => fn(req, res, next)).catch(next);
function errorHandler(err, req, res, next) { // eslint-disable-line no-unused-vars
console.error('[orbisubs-panel]', req.method, req.originalUrl, err);
if (res.headersSent) return;
res.status(err.status || 500).json({ error: err.status ? err.message : 'Error interno' });
}
module.exports = { asyncHandler, errorHandler };
+1 -1
View File
@@ -299,7 +299,7 @@
<label class="srt-on srt-caller"><span data-i18n>Destino (host)</span> <input name="srt_host" placeholder="10.100.101.211"></label> <label class="srt-on srt-caller"><span data-i18n>Destino (host)</span> <input name="srt_host" placeholder="10.100.101.211"></label>
</div> </div>
<div class="grid-3 srt-on"> <div class="grid-3 srt-on">
<label><span data-i18n>Puerto</span> <input name="srt_port" type="number" min="1024" max="65534" placeholder="9002"> <label><span data-i18n>Puerto</span> <input name="srt_port" type="number" min="1024" max="55000" placeholder="9002">
<span class="field-hint" data-i18n>Hasta 55000. En listener toma también el siguiente (prueba interna).</span> <span class="field-hint" data-i18n>Hasta 55000. En listener toma también el siguiente (prueba interna).</span>
</label> </label>
<label>Latency (ms) <input name="srt_latency" type="number" min="20" max="8000" step="10" value="200"></label> <label>Latency (ms) <input name="srt_latency" type="number" min="20" max="8000" step="10" value="200"></label>
+70 -61
View File
@@ -9,6 +9,7 @@ const alarmas = require('../engine/alarmas');
const apply = require('../engine/apply'); const apply = require('../engine/apply');
const P = require('../engine/posicion'); const P = require('../engine/posicion');
const { asyncHandler: ah } = require('../http');
// Como máximo 2 canales andando a la vez: el reconocimiento y la traducción van a // Como máximo 2 canales andando a la vez: el reconocimiento y la traducción van a
// gpu02, que es compartido (076-agregado: ~1 s de whisper por segmento de 6 s). // gpu02, que es compartido (076-agregado: ~1 s de whisper por segmento de 6 s).
@@ -24,11 +25,11 @@ function fail(res, e) {
throw e; throw e;
} }
router.get('/', async (req, res) => { router.get('/', ah(async (req, res) => {
const chs = allChannels(); const chs = allChannels();
const st = await status.all(chs); const st = await status.all(chs);
res.json({ control: true, max_running: MAX_RUNNING, channels: chs.map(c => ({ ...c, status: st[c.id], busy: busy.has(c.id), alarms: alarmas.activas(c.slug) })) }); res.json({ control: true, max_running: MAX_RUNNING, channels: chs.map(c => ({ ...c, status: st[c.id], busy: busy.has(c.id), alarms: alarmas.activas(c.slug) })) });
}); }));
// Una operación a la vez por canal, y como mucho 5 arranques en 10 min (el mismo // Una operación a la vez por canal, y como mucho 5 arranques en 10 min (el mismo
// throttle que las unidades systemd; caso TVR-hls de v1: 15k restarts por un loop). // throttle que las unidades systemd; caso TVR-hls de v1: 15k restarts por un loop).
@@ -86,14 +87,14 @@ router.get('/:id/frame', (req, res) => {
}); });
// Lo que muestra "Ver canal": últimos subtítulos por idioma y números. // Lo que muestra "Ver canal": últimos subtítulos por idioma y números.
router.get('/:id/view', async (req, res) => { router.get('/:id/view', ah(async (req, res) => {
const ch = getChannel(req.params.id); const ch = getChannel(req.params.id);
if (!ch) return res.status(404).json({ error: 'Canal inexistente' }); if (!ch) return res.status(404).json({ error: 'Canal inexistente' });
const st = (await status.all([ch]))[ch.id]; const st = (await status.all([ch]))[ch.id];
st.metrics = status.metrics(ch, { last: 8 }); st.metrics = status.metrics(ch, { last: 8 });
res.json({ channel: ch, status: st, failures: await status.failures(ch), res.json({ channel: ch, status: st, failures: await status.failures(ch),
alarms: alarmas.activas(ch.slug), alarm_history: alarmas.historial(ch.slug) }); alarms: alarmas.activas(ch.slug), alarm_history: alarmas.historial(ch.slug) });
}); }));
router.post('/', (req, res) => { router.post('/', (req, res) => {
let ch; let ch;
@@ -106,7 +107,7 @@ router.post('/', (req, res) => {
res.status(201).json(getChannel(r.lastInsertRowid)); res.status(201).json(getChannel(r.lastInsertRowid));
}); });
router.put('/:id', async (req, res) => { router.put('/:id', ah(async (req, res) => {
const old = getChannel(req.params.id); const old = getChannel(req.params.id);
if (!old) return res.status(404).json({ error: 'Canal inexistente' }); if (!old) return res.status(404).json({ error: 'Canal inexistente' });
let ch; let ch;
@@ -114,37 +115,39 @@ router.put('/:id', async (req, res) => {
ch = V.channel(req.body); ch = V.channel(req.body);
V.conflicts(ch, allChannels().filter(o => o.id !== old.id)); V.conflicts(ch, allChannels().filter(o => o.id !== old.id));
} catch (e) { return fail(res, e); } } catch (e) { return fail(res, e); }
// Renombrar el id corto con el canal andando dejaría instancias huérfanas con el nombre viejo. // Ocupado se toma antes del primer await: si no, un start/stop/delete que entra mientras
if (ch.slug !== old.slug) { // se mira systemd encontraba el canal libre (revisión externa, 2.2).
const st = (await status.all([old]))[old.id];
if (st.units.some(u => u.active === 'active' || u.active === 'activating')) {
return res.status(409).json({ error: 'Detén el canal antes de cambiarle el id corto', field: 'slug' });
}
}
if (busy.has(old.id)) return res.status(409).json({ error: 'El canal está ocupado con otra operación' }); if (busy.has(old.id)) return res.status(409).json({ error: 'El canal está ocupado con otra operación' });
const save = c => db.prepare("UPDATE channels SET slug = ?, name = ?, enabled = ?, cfg = ?, updated_at = datetime('now') WHERE id = ?") busy.add(old.id);
.run(c.slug, c.name, c.enabled ? 1 : 0, JSON.stringify(c.cfg), old.id); try {
save(ch); // Renombrar el id corto con el canal andando dejaría instancias huérfanas con el nombre viejo.
// Solo cambió la posición del subtítulo (082): se reescribe el .pos.json, que los procesos if (ch.slug !== old.slug) {
// releen en cada segmento. No se reinicia nada ni se corta el video. const st = (await status.all([old]))[old.id];
// Solo nombre, id corto y configuración: la fila de la base trae además id y fechas. if (st.units.some(u => u.active === 'active' || u.active === 'activating')) {
const sinPos = c => JSON.stringify({ name: c.name, slug: c.slug, cfg: { ...c.cfg, pos: undefined } }); return res.status(409).json({ error: 'Detén el canal antes de cambiarle el id corto', field: 'slug' });
// Un .env de antes de la 082 no les pasa --pos-file a los procesos: esa vez se reinicia. }
let conPos = false; }
try { conPos = fs.readFileSync(`${process.env.ORBISUBS_ETC || '/etc/orbisubs'}/${old.slug}.env`, 'utf8').includes('--pos-file'); } catch { /* sin .env */ } const save = c => db.prepare("UPDATE channels SET slug = ?, name = ?, enabled = ?, cfg = ?, updated_at = datetime('now') WHERE id = ?")
if (conPos && sinPos(ch) === sinPos(old) && JSON.stringify(ch.cfg.pos) !== JSON.stringify(old.cfg.pos) && await isUp(old)) { .run(c.slug, c.name, c.enabled ? 1 : 0, JSON.stringify(c.cfg), old.id);
apply.writePos(ch); save(ch);
const seg = ch.cfg.hls.seg_s || 6; // Solo cambió la posición del subtítulo (082): se reescribe el .pos.json, que los procesos
const en_s = Math.round(seg + (apply.holdBack(ch).hb || seg * 3) + 3); // releen en cada segmento. No se reinicia nada ni se corta el video.
event('info', `Posición del subtítulo de ${ch.name}: ${P.NOMBRE[ch.cfg.pos.modo]} (${ch.cfg.pos.pct} %)`, { channel: ch.slug, username: req.user.username }); // Solo nombre, id corto y configuración: la fila de la base trae además id y fechas.
return res.json({ ...getChannel(old.id), applied: 'pos', applied_in_s: en_s }); const sinPos = c => JSON.stringify({ name: c.name, slug: c.slug, cfg: { ...c.cfg, pos: undefined } });
} // Un .env de antes de la 082 no les pasa --pos-file a los procesos: esa vez se reinicia.
// Andando: se aplica ya. Si no arranca con lo nuevo, vuelve todo (servicios y base) let conPos = false;
// a lo anterior, para no dejar el canal a medias. try { conPos = fs.readFileSync(`${process.env.ORBISUBS_ETC || '/etc/orbisubs'}/${old.slug}.env`, 'utf8').includes('--pos-file'); } catch { /* sin .env */ }
if (await isUp(old)) { if (conPos && sinPos(ch) === sinPos(old) && JSON.stringify(ch.cfg.pos) !== JSON.stringify(old.cfg.pos) && await isUp(old)) {
if (throttled(old.id)) { save(old); return res.status(429).json({ error: 'Demasiados reinicios de este canal: espera unos minutos' }); } apply.writePos(ch);
busy.add(old.id); const seg = ch.cfg.hls.seg_s || 6;
try { const en_s = Math.round(seg + (apply.holdBack(ch).hb || seg * 3) + 3);
event('info', `Posición del subtítulo de ${ch.name}: ${P.NOMBRE[ch.cfg.pos.modo]} (${ch.cfg.pos.pct} %)`, { channel: ch.slug, username: req.user.username });
return res.json({ ...getChannel(old.id), applied: 'pos', applied_in_s: en_s });
}
// Andando: se aplica ya. Si no arranca con lo nuevo, vuelve todo (servicios y base)
// a lo anterior, para no dejar el canal a medias.
if (await isUp(old)) {
if (throttled(old.id)) { save(old); return res.status(429).json({ error: 'Demasiados reinicios de este canal: espera unos minutos' }); }
const r = await apply.start({ ...ch, id: old.id }, { prevCh: old }); const r = await apply.start({ ...ch, id: old.id }, { prevCh: old });
if (!r.ok) { if (!r.ok) {
save(old); save(old);
@@ -152,38 +155,44 @@ router.put('/:id', async (req, res) => {
return res.status(409).json({ error: `No arrancó con la configuración nueva: ${r.errors.join(' · ')}` }); return res.status(409).json({ error: `No arrancó con la configuración nueva: ${r.errors.join(' · ')}` });
} }
for (const w of r.warnings || []) event('warn', `${ch.name}: ${w}`, { channel: ch.slug, username: req.user.username }); for (const w of r.warnings || []) event('warn', `${ch.name}: ${w}`, { channel: ch.slug, username: req.user.username });
} finally { busy.delete(old.id); } event('info', `Canal editado y reiniciado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
event('info', `Canal editado y reiniciado: ${ch.name}`, { channel: ch.slug, username: req.user.username }); } else {
} else { event('info', `Canal editado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
event('info', `Canal editado: ${ch.name}`, { channel: ch.slug, username: req.user.username }); }
} res.json(getChannel(old.id));
res.json(getChannel(old.id)); } finally { busy.delete(old.id); }
}); }));
router.delete('/:id', async (req, res) => { router.delete('/:id', ah(async (req, res) => {
const ch = getChannel(req.params.id); const ch = getChannel(req.params.id);
if (!ch) return res.status(404).json({ error: 'Canal inexistente' }); if (!ch) return res.status(404).json({ error: 'Canal inexistente' });
const st = (await status.all([ch]))[ch.id]; // Borrar mientras arranca (start en curso) dejaba las unidades andando sin canal (2.2).
if (st.units.some(u => u.active === 'active' || u.active === 'activating')) { if (busy.has(ch.id)) return res.status(409).json({ error: 'El canal está ocupado con otra operación' });
return res.status(409).json({ error: 'El canal está andando: detenlo antes de borrarlo' }); busy.add(ch.id);
} try {
db.prepare('DELETE FROM channels WHERE id = ?').run(ch.id); const st = (await status.all([ch]))[ch.id];
apply.removeEnv(ch.slug); if (st.units.some(u => u.active === 'active' || u.active === 'activating')) {
event('warn', `Canal borrado: ${ch.name}`, { channel: ch.slug, username: req.user.username }); return res.status(409).json({ error: 'El canal está andando: detenlo antes de borrarlo' });
res.json({ ok: true }); }
}); db.prepare('DELETE FROM channels WHERE id = ?').run(ch.id);
apply.removeEnv(ch.slug);
event('warn', `Canal borrado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
res.json({ ok: true });
} finally { busy.delete(ch.id); }
}));
router.post('/:id/start', async (req, res) => { router.post('/:id/start', ah(async (req, res) => {
const ch = getChannel(req.params.id); const ch = getChannel(req.params.id);
if (!ch) return res.status(404).json({ error: 'Canal inexistente' }); if (!ch) return res.status(404).json({ error: 'Canal inexistente' });
if (busy.has(ch.id)) return res.status(409).json({ error: 'El canal está ocupado con otra operación' }); if (busy.has(ch.id)) return res.status(409).json({ error: 'El canal está ocupado con otra operación' });
const others = await runningOthers(ch); // Ocupado antes del primer await (2.2), como en PUT y DELETE.
if (others.length >= MAX_RUNNING) {
return res.status(409).json({ error: `Ya hay ${others.length} canales andando (${others.join(', ')}): el máximo es ${MAX_RUNNING} por gpu02` });
}
if (throttled(ch.id)) return res.status(429).json({ error: 'Demasiados reinicios de este canal: espera unos minutos' });
busy.add(ch.id); busy.add(ch.id);
try { try {
const others = await runningOthers(ch);
if (others.length >= MAX_RUNNING) {
return res.status(409).json({ error: `Ya hay ${others.length} canales andando (${others.join(', ')}): el máximo es ${MAX_RUNNING} por gpu02` });
}
if (throttled(ch.id)) return res.status(429).json({ error: 'Demasiados reinicios de este canal: espera unos minutos' });
const r = await apply.start(ch); const r = await apply.start(ch);
if (!r.ok) { if (!r.ok) {
event('error', `No arrancó ${ch.name}: ${r.errors.join(' · ')}`, { channel: ch.slug, username: req.user.username }); event('error', `No arrancó ${ch.name}: ${r.errors.join(' · ')}`, { channel: ch.slug, username: req.user.username });
@@ -193,9 +202,9 @@ router.post('/:id/start', async (req, res) => {
event('info', `Canal iniciado: ${ch.name}`, { channel: ch.slug, username: req.user.username }); event('info', `Canal iniciado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
res.json({ ok: true }); res.json({ ok: true });
} finally { busy.delete(ch.id); } } finally { busy.delete(ch.id); }
}); }));
router.post('/:id/stop', async (req, res) => { router.post('/:id/stop', ah(async (req, res) => {
const ch = getChannel(req.params.id); const ch = getChannel(req.params.id);
if (!ch) return res.status(404).json({ error: 'Canal inexistente' }); if (!ch) return res.status(404).json({ error: 'Canal inexistente' });
if (busy.has(ch.id)) return res.status(409).json({ error: 'El canal está ocupado con otra operación' }); if (busy.has(ch.id)) return res.status(409).json({ error: 'El canal está ocupado con otra operación' });
@@ -203,7 +212,7 @@ router.post('/:id/stop', async (req, res) => {
try { await apply.stop(ch); } finally { busy.delete(ch.id); } try { await apply.stop(ch); } finally { busy.delete(ch.id); }
event('info', `Canal parado: ${ch.name}`, { channel: ch.slug, username: req.user.username }); event('info', `Canal parado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
res.json({ ok: true }); res.json({ ok: true });
}); }));
// Base nueva: T13 (el canal de la 076-078, configurado a mano) entra como un canal // Base nueva: T13 (el canal de la 076-078, configurado a mano) entra como un canal
// más, con lo que dice su /etc/orbisubs/t13.env. Solo se lee. // más, con lo que dice su /etc/orbisubs/t13.env. Solo se lee.
+1 -4
View File
@@ -55,10 +55,7 @@ app.get('/api/events', (req, res) => {
app.use(express.static(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'public')));
app.get('*', (req, res, next) => (req.path.startsWith('/api') ? next() : res.sendFile(path.join(__dirname, 'public', 'index.html')))); app.get('*', (req, res, next) => (req.path.startsWith('/api') ? next() : res.sendFile(path.join(__dirname, 'public', 'index.html'))));
app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars app.use(require('./http').errorHandler);
console.error('[orbisubs-panel]', err);
res.status(err.status || 500).json({ error: err.status ? err.message : 'Error interno' });
});
app.listen(PORT, () => console.log(`[orbisubs-panel] escuchando en :${PORT}`)); app.listen(PORT, () => console.log(`[orbisubs-panel] escuchando en :${PORT}`));
+80
View File
@@ -0,0 +1,80 @@
'use strict';
// Rutas de canales (revisión externa, 2.1 y 2.2).
const test = require('node:test');
const assert = require('node:assert');
const fs = require('fs');
const os = require('os');
const path = require('path');
const http = require('http');
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'orbisubs-rutas-'));
process.env.ORBISUBS_ETC = path.join(process.env.DATA_DIR, 'etc');
process.env.LOG_DIR = path.join(process.env.DATA_DIR, 'log');
const express = require('express');
const status = require('../src/engine/status');
const { db } = require('../src/db');
const { errorHandler } = require('../src/http');
const router = require('../src/routes/channels');
function servidor() {
const app = express();
app.use(express.json());
app.use((req, res, next) => { req.user = { username: 'test' }; next(); });
app.use('/api/channels', router);
app.use(errorHandler);
return new Promise(r => { const s = app.listen(0, '127.0.0.1', () => r(s)); });
}
function pedir(s, method, url) {
return new Promise((resolve, reject) => {
const req = http.request({ host: '127.0.0.1', port: s.address().port, method, path: url }, res => {
let b = '';
res.on('data', d => { b += d; });
res.on('end', () => resolve({ status: res.statusCode, body: b ? JSON.parse(b) : null }));
});
req.on('error', reject);
req.end();
});
}
const cfg = {
input: { kind: 'udp', url: 'udp://@239.1.1.1:1234' }, asr: { lang: 'es', url: 'http://127.0.0.1:1' },
tr: { langs: [] }, hls: { enabled: true, seg_s: 6, list_size: 10 }, srt: { enabled: false },
};
test('2.1: un rechazo en una ruta async responde 500 y el panel sigue andando', async t => {
const s = await servidor();
const orig = status.all;
t.after(() => { status.all = orig; s.close(); });
const errores = [];
const ce = console.error;
console.error = (...a) => errores.push(a.join(' '));
try {
status.all = async () => { throw new Error('systemctl colgado'); };
const r = await pedir(s, 'GET', '/api/channels');
assert.strictEqual(r.status, 500);
assert.strictEqual(r.body.error, 'Error interno');
assert.ok(errores.some(e => e.includes('systemctl colgado')), 'se loguea');
status.all = orig;
// Sigue vivo: el pedido siguiente anda.
status.all = async chs => Object.fromEntries(chs.map(c => [c.id, { state: 'stopped', units: [], notes: [] }]));
assert.strictEqual((await pedir(s, 'GET', '/api/channels')).status, 200);
} finally { console.error = ce; }
});
test('2.2: dos DELETE a la vez: el segundo encuentra el canal ocupado', async t => {
const s = await servidor();
const orig = status.all;
t.after(() => { status.all = orig; s.close(); });
const id = db.prepare('INSERT INTO channels (slug, name, enabled, cfg) VALUES (?, ?, 1, ?)').run('borrame', 'Borrame', JSON.stringify(cfg)).lastInsertRowid;
let soltar;
const espera = new Promise(r => { soltar = r; });
status.all = async chs => { await espera; return Object.fromEntries(chs.map(c => [c.id, { state: 'stopped', units: [], notes: [] }])); };
const primero = pedir(s, 'DELETE', `/api/channels/${id}`);
await new Promise(r => setTimeout(r, 50));
const segundo = await pedir(s, 'DELETE', `/api/channels/${id}`);
assert.strictEqual(segundo.status, 409);
assert.match(segundo.body.error, /ocupado/);
soltar();
assert.strictEqual((await primero).status, 200);
assert.strictEqual(db.prepare('SELECT 1 FROM channels WHERE id = ?').get(id), undefined);
});