diff --git a/panel/src/http.js b/panel/src/http.js
new file mode 100644
index 0000000..e7e3ffc
--- /dev/null
+++ b/panel/src/http.js
@@ -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 };
diff --git a/panel/src/public/index.html b/panel/src/public/index.html
index a3cc91d..4091d25 100644
--- a/panel/src/public/index.html
+++ b/panel/src/public/index.html
@@ -299,7 +299,7 @@
Destino (host)
- Puerto
+ Puerto
Hasta 55000. En listener toma también el siguiente (prueba interna).
Latency (ms)
diff --git a/panel/src/routes/channels.js b/panel/src/routes/channels.js
index 83ce607..c8319b8 100644
--- a/panel/src/routes/channels.js
+++ b/panel/src/routes/channels.js
@@ -9,6 +9,7 @@ const alarmas = require('../engine/alarmas');
const apply = require('../engine/apply');
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
// 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;
}
-router.get('/', async (req, res) => {
+router.get('/', ah(async (req, res) => {
const chs = allChannels();
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) })) });
-});
+}));
// 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).
@@ -86,14 +87,14 @@ router.get('/:id/frame', (req, res) => {
});
// 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);
if (!ch) return res.status(404).json({ error: 'Canal inexistente' });
const st = (await status.all([ch]))[ch.id];
st.metrics = status.metrics(ch, { last: 8 });
res.json({ channel: ch, status: st, failures: await status.failures(ch),
alarms: alarmas.activas(ch.slug), alarm_history: alarmas.historial(ch.slug) });
-});
+}));
router.post('/', (req, res) => {
let ch;
@@ -106,7 +107,7 @@ router.post('/', (req, res) => {
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);
if (!old) return res.status(404).json({ error: 'Canal inexistente' });
let ch;
@@ -114,37 +115,39 @@ router.put('/:id', async (req, res) => {
ch = V.channel(req.body);
V.conflicts(ch, allChannels().filter(o => o.id !== old.id));
} catch (e) { return fail(res, e); }
- // Renombrar el id corto con el canal andando dejaría instancias huérfanas con el nombre viejo.
- if (ch.slug !== old.slug) {
- 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' });
- }
- }
+ // Ocupado se toma antes del primer await: si no, un start/stop/delete que entra mientras
+ // se mira systemd encontraba el canal libre (revisión externa, 2.2).
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 = ?")
- .run(c.slug, c.name, c.enabled ? 1 : 0, JSON.stringify(c.cfg), old.id);
- save(ch);
- // Solo cambió la posición del subtítulo (082): se reescribe el .pos.json, que los procesos
- // releen en cada segmento. No se reinicia nada ni se corta el video.
- // Solo nombre, id corto y configuración: la fila de la base trae además id y fechas.
- 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.
- let conPos = false;
- try { conPos = fs.readFileSync(`${process.env.ORBISUBS_ETC || '/etc/orbisubs'}/${old.slug}.env`, 'utf8').includes('--pos-file'); } catch { /* sin .env */ }
- if (conPos && sinPos(ch) === sinPos(old) && JSON.stringify(ch.cfg.pos) !== JSON.stringify(old.cfg.pos) && await isUp(old)) {
- apply.writePos(ch);
- const seg = ch.cfg.hls.seg_s || 6;
- 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' }); }
- busy.add(old.id);
- try {
+ busy.add(old.id);
+ try {
+ // Renombrar el id corto con el canal andando dejaría instancias huérfanas con el nombre viejo.
+ if (ch.slug !== old.slug) {
+ 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' });
+ }
+ }
+ const save = c => db.prepare("UPDATE channels SET slug = ?, name = ?, enabled = ?, cfg = ?, updated_at = datetime('now') WHERE id = ?")
+ .run(c.slug, c.name, c.enabled ? 1 : 0, JSON.stringify(c.cfg), old.id);
+ save(ch);
+ // Solo cambió la posición del subtítulo (082): se reescribe el .pos.json, que los procesos
+ // releen en cada segmento. No se reinicia nada ni se corta el video.
+ // Solo nombre, id corto y configuración: la fila de la base trae además id y fechas.
+ 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.
+ let conPos = false;
+ try { conPos = fs.readFileSync(`${process.env.ORBISUBS_ETC || '/etc/orbisubs'}/${old.slug}.env`, 'utf8').includes('--pos-file'); } catch { /* sin .env */ }
+ if (conPos && sinPos(ch) === sinPos(old) && JSON.stringify(ch.cfg.pos) !== JSON.stringify(old.cfg.pos) && await isUp(old)) {
+ apply.writePos(ch);
+ const seg = ch.cfg.hls.seg_s || 6;
+ 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 });
if (!r.ok) {
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(' · ')}` });
}
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 });
- } else {
- event('info', `Canal editado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
- }
- res.json(getChannel(old.id));
-});
+ event('info', `Canal editado y reiniciado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
+ } else {
+ event('info', `Canal editado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
+ }
+ 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);
if (!ch) return res.status(404).json({ error: 'Canal inexistente' });
- const st = (await status.all([ch]))[ch.id];
- if (st.units.some(u => u.active === 'active' || u.active === 'activating')) {
- return res.status(409).json({ error: 'El canal está andando: detenlo antes de borrarlo' });
- }
- 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 });
-});
+ // Borrar mientras arranca (start en curso) dejaba las unidades andando sin canal (2.2).
+ if (busy.has(ch.id)) return res.status(409).json({ error: 'El canal está ocupado con otra operación' });
+ busy.add(ch.id);
+ try {
+ const st = (await status.all([ch]))[ch.id];
+ if (st.units.some(u => u.active === 'active' || u.active === 'activating')) {
+ return res.status(409).json({ error: 'El canal está andando: detenlo antes de borrarlo' });
+ }
+ 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);
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' });
- 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' });
+ // Ocupado antes del primer await (2.2), como en PUT y DELETE.
busy.add(ch.id);
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);
if (!r.ok) {
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 });
res.json({ ok: true });
} 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);
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' });
@@ -203,7 +212,7 @@ router.post('/:id/stop', async (req, res) => {
try { await apply.stop(ch); } finally { busy.delete(ch.id); }
event('info', `Canal parado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
res.json({ ok: true });
-});
+}));
// 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.
diff --git a/panel/src/server.js b/panel/src/server.js
index 05146e8..6e205a0 100644
--- a/panel/src/server.js
+++ b/panel/src/server.js
@@ -55,10 +55,7 @@ app.get('/api/events', (req, res) => {
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.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
- console.error('[orbisubs-panel]', err);
- res.status(err.status || 500).json({ error: err.status ? err.message : 'Error interno' });
-});
+app.use(require('./http').errorHandler);
app.listen(PORT, () => console.log(`[orbisubs-panel] escuchando en :${PORT}`));
diff --git a/panel/test/rutas.test.js b/panel/test/rutas.test.js
new file mode 100644
index 0000000..5c1ddd4
--- /dev/null
+++ b/panel/test/rutas.test.js
@@ -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);
+});