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:
@@ -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 };
|
||||
@@ -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>
|
||||
</div>
|
||||
<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>
|
||||
</label>
|
||||
<label>Latency (ms) <input name="srt_latency" type="number" min="20" max="8000" step="10" value="200"></label>
|
||||
|
||||
@@ -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,6 +115,11 @@ 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); }
|
||||
// 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' });
|
||||
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];
|
||||
@@ -121,7 +127,6 @@ router.put('/:id', async (req, res) => {
|
||||
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' });
|
||||
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);
|
||||
@@ -143,8 +148,6 @@ router.put('/:id', async (req, res) => {
|
||||
// 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 {
|
||||
const r = await apply.start({ ...ch, id: old.id }, { prevCh: old });
|
||||
if (!r.ok) {
|
||||
save(old);
|
||||
@@ -152,17 +155,21 @@ 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));
|
||||
});
|
||||
} 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' });
|
||||
// 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' });
|
||||
@@ -171,19 +178,21 @@ router.delete('/:id', async (req, res) => {
|
||||
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' });
|
||||
// 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' });
|
||||
busy.add(ch.id);
|
||||
try {
|
||||
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.
|
||||
|
||||
+1
-4
@@ -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}`));
|
||||
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
Reference in New Issue
Block a user