OrbiSubs panel: channel list, add/edit modal, live status (phase 1, start/stop off)
This commit is contained in:
@@ -0,0 +1,158 @@
|
||||
'use strict';
|
||||
// status.js — estado real de cada canal: lo que dice systemd de sus instancias
|
||||
// orbisubs-*@<slug> y lo que escriben los procesos en /var/log/orbisubs (las
|
||||
// métricas por segmento de orbisubs.py, orbisubs_tr.py y orbisubs_srt.py).
|
||||
// Solo lee: no arranca ni para nada.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { execFile } = require('child_process');
|
||||
|
||||
const LOG_DIR = process.env.LOG_DIR || '/var/log/orbisubs';
|
||||
const HLS_DIR = process.env.HLS_DIR || '/var/www/hls';
|
||||
const STALE_S = 60; // métricas más viejas que esto: el proceso no está produciendo
|
||||
|
||||
function sh(cmd, args, timeout = 5000) {
|
||||
return new Promise(resolve => {
|
||||
execFile(cmd, args, { timeout, maxBuffer: 4 << 20 }, (err, stdout) => resolve(err && !stdout ? '' : String(stdout)));
|
||||
});
|
||||
}
|
||||
|
||||
// Instancias systemd que forman el canal, según su configuración.
|
||||
function unitsOf(ch) {
|
||||
const u = ['ingest', 'asr'];
|
||||
if (ch.cfg.tr && ch.cfg.tr.langs && ch.cfg.tr.langs.length) u.push('tr');
|
||||
if (ch.cfg.srt && ch.cfg.srt.enabled) u.push('srt');
|
||||
return u.map(k => ({ key: k, unit: `orbisubs-${k}@${ch.slug}.service` }));
|
||||
}
|
||||
|
||||
// Un solo `systemctl show` para todas las unidades de todos los canales.
|
||||
async function systemdState(units) {
|
||||
if (!units.length) return {};
|
||||
const out = await sh('systemctl', ['show', '--no-pager', '-p', 'Id,LoadState,ActiveState,SubState,NRestarts,Result,UnitFileState', ...units]);
|
||||
const res = {};
|
||||
for (const block of out.split(/\n\s*\n/)) {
|
||||
const o = {};
|
||||
for (const line of block.split('\n')) {
|
||||
const i = line.indexOf('=');
|
||||
if (i > 0) o[line.slice(0, i)] = line.slice(i + 1);
|
||||
}
|
||||
if (o.Id) res[o.Id] = { load: o.LoadState, active: o.ActiveState, sub: o.SubState, restarts: Number(o.NRestarts || 0), result: o.Result, file: o.UnitFileState };
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
// Últimas líneas JSON de un .jsonl, leyendo solo la cola del archivo.
|
||||
function tailJsonl(file, maxBytes = 256 * 1024) {
|
||||
let fd;
|
||||
try {
|
||||
fd = fs.openSync(file, 'r');
|
||||
const st = fs.fstatSync(fd);
|
||||
const len = Math.min(st.size, maxBytes);
|
||||
const buf = Buffer.alloc(len);
|
||||
fs.readSync(fd, buf, 0, len, st.size - len);
|
||||
const lines = buf.toString('utf8').split('\n');
|
||||
if (st.size > len) lines.shift(); // la primera puede venir cortada
|
||||
const rows = [];
|
||||
for (const l of lines) { if (l.trim()) { try { rows.push(JSON.parse(l)); } catch { /* línea a medias */ } } }
|
||||
return { rows, mtime: st.mtimeMs };
|
||||
} catch { return { rows: [], mtime: 0 }; }
|
||||
finally { if (fd !== undefined) fs.closeSync(fd); }
|
||||
}
|
||||
|
||||
const median = a => {
|
||||
if (!a.length) return null;
|
||||
const s = [...a].sort((x, y) => x - y), m = s.length >> 1;
|
||||
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
||||
};
|
||||
const round = (v, d = 2) => (v == null ? null : Math.round(v * 10 ** d) / 10 ** d);
|
||||
|
||||
function metrics(ch, { last = 1 } = {}) {
|
||||
const now = Date.now();
|
||||
const asr = tailJsonl(path.join(LOG_DIR, `${ch.slug}.jsonl`));
|
||||
const segs = asr.rows.filter(r => r.seq != null && r.dur != null);
|
||||
const lastSeg = segs[segs.length - 1];
|
||||
const fresh = asr.mtime && now - asr.mtime < STALE_S * 1000;
|
||||
const m = {
|
||||
fresh: !!fresh,
|
||||
age_s: asr.mtime ? Math.round((now - asr.mtime) / 1000) : null,
|
||||
delay_s: fresh && lastSeg ? lastSeg.channel_extra_s : null,
|
||||
held_segments: fresh && lastSeg ? lastSeg.held_segments : null,
|
||||
pending_s: fresh && lastSeg ? lastSeg.pending_s : null,
|
||||
last: {},
|
||||
recent: {},
|
||||
};
|
||||
const conTexto = segs.filter(r => r.text);
|
||||
if (conTexto.length) m.last[ch.cfg.asr.lang] = conTexto[conTexto.length - 1].text.replace(/ \| /g, ' ');
|
||||
m.recent[ch.cfg.asr.lang] = conTexto.slice(-last).map(r => ({ seq: r.seq, text: r.text.replace(/ \| /g, ' ') }));
|
||||
// Pedidos al motor de reconocimiento (gpu02 :8004): los últimos 100 segmentos.
|
||||
const asrT = segs.slice(-100).map(r => r.http_s ?? r.asr_s).filter(v => typeof v === 'number');
|
||||
m.asr = { n: asrT.length, median_s: round(median(asrT)) };
|
||||
|
||||
if (ch.cfg.tr.langs.length) {
|
||||
const tr = tailJsonl(path.join(LOG_DIR, `${ch.slug}-en.jsonl`));
|
||||
const frases = tr.rows.filter(r => 'en' in r);
|
||||
const lags = tr.rows.filter(r => r.en_lag_vs_es_s != null).slice(-100).map(r => r.en_lag_vs_es_s);
|
||||
const okT = frases.slice(-100).map(r => r.qwen_s).filter(v => typeof v === 'number');
|
||||
const conEn = frases.filter(r => r.en);
|
||||
if (conEn.length) m.last.en = conEn[conEn.length - 1].en;
|
||||
m.recent.en = conEn.slice(-last).map(r => ({ text: r.en, es: r.es }));
|
||||
m.tr = { n: okT.length, median_s: round(median(okT)), lag_median_s: round(median(lags)), fresh: !!(tr.mtime && now - tr.mtime < STALE_S * 1000) };
|
||||
}
|
||||
|
||||
if (ch.cfg.srt.enabled) {
|
||||
const s = tailJsonl(path.join(LOG_DIR, `${ch.slug}-srt.jsonl`), 64 * 1024);
|
||||
const r = s.rows[s.rows.length - 1];
|
||||
if (r) {
|
||||
const pick = k => (r[k] ? { cues: r[k].cues, tarde: r[k].tarde, perdidos: r[k].perdidos, tarde_max_s: r[k].tarde_max_s ?? null } : null);
|
||||
m.srt = {
|
||||
fresh: !!(s.mtime && now - s.mtime < STALE_S * 1000),
|
||||
delay_s: r.retraso_fijo_s, send_lag_s: r.atraso_envio_s,
|
||||
es608: pick('es608'), en608: pick('en608'), es708: pick('es708'), en708: pick('en708'),
|
||||
};
|
||||
}
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
// Fallas de los pedidos a gpu02 en la última hora, contadas en el journal
|
||||
// (orbisubs.py escribe asr_error y orbisubs_tr.py translate_error).
|
||||
async function failures(ch) {
|
||||
const count = async (unit, word) => {
|
||||
const out = await sh('journalctl', ['-u', unit, '--since', '-1h', '-o', 'cat', '--no-pager', '-q'], 8000);
|
||||
return out.split('\n').filter(l => l.includes(`"${word}"`)).length;
|
||||
};
|
||||
const r = { asr_errors_1h: await count(`orbisubs-asr@${ch.slug}.service`, 'asr_error') };
|
||||
if (ch.cfg.tr.langs.length) r.tr_errors_1h = await count(`orbisubs-tr@${ch.slug}.service`, 'translate_error');
|
||||
return r;
|
||||
}
|
||||
|
||||
// Resume las unidades en un estado del canal: corriendo, parado, error, arrancando.
|
||||
function summarize(ch, sd) {
|
||||
const units = unitsOf(ch).map(u => ({ ...u, ...(sd[u.unit] || { load: 'not-found', active: 'inactive' }) }));
|
||||
const act = units.map(u => u.active);
|
||||
let state;
|
||||
if (act.every(a => a === 'active')) state = 'running';
|
||||
else if (act.some(a => a === 'failed')) state = 'error';
|
||||
else if (act.every(a => a === 'inactive')) state = 'stopped';
|
||||
else if (act.some(a => a === 'activating' || a === 'reloading')) state = 'connecting';
|
||||
else state = 'error'; // a medias: algunas andan y otras no
|
||||
const notes = units.filter(u => u.active !== 'active' && state !== 'stopped').map(u => `${u.key}: ${u.active}${u.result && u.result !== 'success' ? ` (${u.result})` : ''}`);
|
||||
return { state, units, notes, managed: units.some(u => u.load === 'loaded') };
|
||||
}
|
||||
|
||||
async function all(channels) {
|
||||
const sd = await systemdState(channels.flatMap(ch => unitsOf(ch).map(u => u.unit)));
|
||||
const res = {};
|
||||
for (const ch of channels) {
|
||||
const s = summarize(ch, sd);
|
||||
const m = metrics(ch);
|
||||
// Corriendo según systemd pero sin producir subtítulos: se muestra como error.
|
||||
if (s.state === 'running' && !m.fresh && m.age_s !== null && m.age_s > STALE_S * 2) {
|
||||
s.state = 'error'; s.notes.push(`sin subtítulos nuevos hace ${m.age_s} s`);
|
||||
}
|
||||
res[ch.id] = { ...s, metrics: m };
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
module.exports = { all, metrics, failures, unitsOf, systemdState, summarize, LOG_DIR, HLS_DIR };
|
||||
@@ -0,0 +1,195 @@
|
||||
'use strict';
|
||||
// validate.js — normaliza y valida la configuración de un canal. Lo usa la API
|
||||
// (la que manda) y lo replica a mano el modal (defense in depth, como en v1:
|
||||
// la regla crítica se chequea en cada camino por el que puede entrar).
|
||||
//
|
||||
// Puertos: cada salida SRT listener reserva su puerto y el siguiente (la 078 usa
|
||||
// SRT_PORT para clientes y SRT_PORT_TEST = +1 para el HLS de prueba interno).
|
||||
|
||||
const SLUG_RE = /^[a-z0-9][a-z0-9-]{0,30}$/;
|
||||
// Puertos del CT que no puede tomar ningún canal (ssh, smtp local, nginx, este panel).
|
||||
const RESERVED = new Set([22, 25, 80, 443, Number(process.env.PORT) || 4700]);
|
||||
const CC608 = ['CC1', 'CC2', 'CC3', 'CC4'];
|
||||
const LANGS = ['es', 'en', 'pt'];
|
||||
|
||||
class ValidationError extends Error {
|
||||
constructor(msg, field) { super(msg); this.field = field; this.status = 400; }
|
||||
}
|
||||
const bad = (msg, field) => { throw new ValidationError(msg, field); };
|
||||
|
||||
const str = v => (v == null ? '' : String(v).trim());
|
||||
function int(v, field, min, max, label, { optional = false } = {}) {
|
||||
if (v === '' || v == null) {
|
||||
if (optional) return null;
|
||||
bad(`Falta ${label}`, field);
|
||||
}
|
||||
const n = Number(v);
|
||||
if (!Number.isInteger(n) || n < min || n > max) bad(`${label}: tiene que ser un entero entre ${min} y ${max}`, field);
|
||||
return n;
|
||||
}
|
||||
function num(v, field, min, max, label) {
|
||||
const n = Number(v);
|
||||
if (v === '' || v == null || !Number.isFinite(n) || n < min || n > max) bad(`${label}: tiene que ser un número entre ${min} y ${max}`, field);
|
||||
return n;
|
||||
}
|
||||
function httpUrl(v, field, label) {
|
||||
const s = str(v);
|
||||
let u;
|
||||
try { u = new URL(s); } catch { bad(`${label}: URL mal armada`, field); }
|
||||
if (!/^https?:$/.test(u.protocol)) bad(`${label}: tiene que empezar con http:// o https://`, field);
|
||||
return s.replace(/\/+$/, '');
|
||||
}
|
||||
function host(v, field, label) {
|
||||
const s = str(v);
|
||||
if (!/^[A-Za-z0-9.-]{1,253}$/.test(s) && !/^\[[0-9a-fA-F:]+\]$/.test(s)) bad(`${label}: host mal armado`, field);
|
||||
return s;
|
||||
}
|
||||
function passphrase(v, field) {
|
||||
const s = str(v);
|
||||
if (s && (s.length < 10 || s.length > 79)) bad('La passphrase SRT tiene que tener entre 10 y 79 caracteres', field);
|
||||
return s;
|
||||
}
|
||||
|
||||
function input(i = {}) {
|
||||
const kind = str(i.kind);
|
||||
if (kind === 'srt') {
|
||||
const mode = str(i.mode) === 'listener' ? 'listener' : 'caller';
|
||||
const out = {
|
||||
kind, mode,
|
||||
host: mode === 'caller' ? host(i.host, 'in_host', 'Entrada SRT') : (str(i.host) || '0.0.0.0'),
|
||||
port: int(i.port, 'in_port', 1, 65535, 'Puerto de la entrada'),
|
||||
latency_ms: int(i.latency_ms === '' || i.latency_ms == null ? 200 : i.latency_ms, 'in_latency', 20, 8000, 'Latency de la entrada (ms)'),
|
||||
streamid: str(i.streamid),
|
||||
passphrase: passphrase(i.passphrase, 'in_passphrase'),
|
||||
};
|
||||
if (out.streamid.length > 512 || /[\s&]/.test(out.streamid)) bad('streamid: sin espacios ni &, hasta 512 caracteres', 'in_streamid');
|
||||
if (mode === 'listener' && RESERVED.has(out.port)) bad(`El puerto ${out.port} lo usa el sistema`, 'in_port');
|
||||
return Object.assign(out, avPick(i));
|
||||
}
|
||||
if (kind === 'udp') {
|
||||
const s = str(i.url);
|
||||
const m = /^udp:\/\/(@?)([0-9.]+|[A-Za-z0-9.-]+)?:(\d{1,5})(\?.*)?$/.exec(s);
|
||||
if (!m || Number(m[3]) < 1 || Number(m[3]) > 65535) bad('Entrada UDP: tiene que ser udp://ip:puerto (o udp://@239.x.x.x:puerto)', 'in_url');
|
||||
return Object.assign({ kind, url: s }, avPick(i));
|
||||
}
|
||||
if (kind === 'hls') {
|
||||
const url = httpUrl(i.url, 'in_url', 'Entrada HLS');
|
||||
if (!/\.m3u8/i.test(url)) bad('Entrada HLS: la URL tiene que apuntar a una lista .m3u8', 'in_url');
|
||||
return Object.assign({ kind, url }, avPick(i));
|
||||
}
|
||||
bad('Tipo de entrada desconocido (SRT, UDP o HLS)', 'in_kind');
|
||||
}
|
||||
// Programa y PID de audio: opcionales, para fuentes con más de un servicio o audio.
|
||||
function avPick(i) {
|
||||
return {
|
||||
program: int(i.program, 'in_program', 1, 65535, 'Programa', { optional: true }),
|
||||
audio_pid: int(i.audio_pid, 'in_audio_pid', 16, 8190, 'PID de audio', { optional: true }),
|
||||
};
|
||||
}
|
||||
|
||||
// Toma el JSON que manda el modal (o la API) y devuelve el canal normalizado.
|
||||
function channel(body = {}) {
|
||||
const name = str(body.name);
|
||||
if (!name || name.length > 80) bad('Falta el nombre (hasta 80 caracteres)', 'name');
|
||||
const slug = str(body.slug).toLowerCase();
|
||||
if (!SLUG_RE.test(slug)) bad('Id corto: minúsculas, números y guiones, hasta 31, empezando con letra o número', 'slug');
|
||||
// <slug>-cc es la carpeta del HLS de prueba de la salida SRT (078): no puede ser otro canal.
|
||||
if (/-cc$/.test(slug)) bad('El id corto no puede terminar en "-cc" (lo usa la prueba de la salida SRT)', 'slug');
|
||||
|
||||
const c = body.cfg || body;
|
||||
const asr = c.asr || {};
|
||||
const tr = c.tr || {};
|
||||
const hls = c.hls || {};
|
||||
const srt = c.srt || {};
|
||||
|
||||
const cfg = {
|
||||
input: input(c.input),
|
||||
asr: {
|
||||
lang: LANGS.includes(str(asr.lang)) ? str(asr.lang) : 'es',
|
||||
url: httpUrl(asr.url || 'http://192.168.2.10:8004', 'asr_url', 'URL del motor de reconocimiento'),
|
||||
prompt: str(asr.prompt).slice(0, 500),
|
||||
},
|
||||
tr: {
|
||||
langs: [...new Set((Array.isArray(tr.langs) ? tr.langs : []).map(str))].filter(l => l === 'en'),
|
||||
url: httpUrl(tr.url || 'http://192.168.2.10:8001', 'tr_url', 'URL del LLM'),
|
||||
model: str(tr.model) || 'qwen2.5-7b-instruct',
|
||||
},
|
||||
hls: {
|
||||
enabled: hls.enabled !== false,
|
||||
seg_s: int(hls.seg_s ?? 6, 'hls_seg', 2, 10, 'Largo de segmento HLS (s)'),
|
||||
list_size: int(hls.list_size ?? 10, 'hls_list', 3, 30, 'Segmentos en la lista'),
|
||||
},
|
||||
srt: { enabled: !!srt.enabled },
|
||||
};
|
||||
if (cfg.tr.langs.length && cfg.asr.lang === 'en') bad('El audio ya es inglés: no hace falta traducir a inglés', 'tr_langs');
|
||||
|
||||
if (cfg.srt.enabled) {
|
||||
const mode = str(srt.mode) === 'caller' ? 'caller' : 'listener';
|
||||
Object.assign(cfg.srt, {
|
||||
mode,
|
||||
host: mode === 'caller' ? host(srt.host, 'srt_host', 'Destino de la salida SRT') : '',
|
||||
port: int(srt.port, 'srt_port', 1024, 65534, 'Puerto de la salida SRT'),
|
||||
latency_ms: int(srt.latency_ms === '' || srt.latency_ms == null ? 200 : srt.latency_ms, 'srt_latency', 20, 8000, 'Latency de la salida (ms)'),
|
||||
passphrase: passphrase(srt.passphrase, 'srt_passphrase'),
|
||||
delay_s: num(srt.delay_s ?? 24, 'srt_delay', 5, 60, 'Retraso fijo del video (s)'),
|
||||
cc608: {}, cc708: {},
|
||||
});
|
||||
// Qué idioma va en cada canal 608 y servicio 708. Vacío = ese idioma no va.
|
||||
const langsOut = [cfg.asr.lang, ...cfg.tr.langs];
|
||||
const used608 = new Set(), used708 = new Set();
|
||||
for (const l of langsOut) {
|
||||
const v608 = str((srt.cc608 || {})[l]);
|
||||
if (v608) {
|
||||
if (!CC608.includes(v608)) bad(`608 de ${l}: CC1 a CC4`, 'srt_cc608');
|
||||
if (used608.has(v608)) bad(`${v608} está repetido entre idiomas`, 'srt_cc608');
|
||||
used608.add(v608); cfg.srt.cc608[l] = v608;
|
||||
}
|
||||
const v708 = (srt.cc708 || {})[l];
|
||||
if (v708 !== '' && v708 != null) {
|
||||
const n = int(v708, 'srt_cc708', 1, 6, `Servicio 708 de ${l}`);
|
||||
if (used708.has(n)) bad(`El servicio 708 ${n} está repetido entre idiomas`, 'srt_cc708');
|
||||
used708.add(n); cfg.srt.cc708[l] = n;
|
||||
}
|
||||
}
|
||||
if (mode === 'listener' && (RESERVED.has(cfg.srt.port) || RESERVED.has(cfg.srt.port + 1))) {
|
||||
bad(`El puerto ${cfg.srt.port} (o el siguiente) lo usa el sistema`, 'srt_port');
|
||||
}
|
||||
}
|
||||
if (!cfg.hls.enabled && !cfg.srt.enabled) bad('El canal necesita al menos una salida (HLS o SRT)', 'hls_enabled');
|
||||
|
||||
return { name, slug, enabled: body.enabled !== false, cfg };
|
||||
}
|
||||
|
||||
// Puertos UDP que el canal toma en este CT (listeners SRT de entrada y salida).
|
||||
function portsOf(cfg) {
|
||||
const out = [];
|
||||
if (cfg.input && cfg.input.kind === 'srt' && cfg.input.mode === 'listener') out.push({ port: cfg.input.port, what: 'entrada SRT' });
|
||||
if (cfg.srt && cfg.srt.enabled && cfg.srt.mode === 'listener') {
|
||||
out.push({ port: cfg.srt.port, what: 'salida SRT' }, { port: cfg.srt.port + 1, what: 'prueba interna de la salida SRT' });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Choque de puertos o de id contra los otros canales (others = filas de la base).
|
||||
function conflicts(ch, others) {
|
||||
for (const o of others) {
|
||||
if (o.slug === ch.slug) bad(`Ya hay un canal con el id corto "${ch.slug}"`, 'slug');
|
||||
}
|
||||
const mine = portsOf(ch.cfg);
|
||||
const seen = new Map();
|
||||
for (const p of mine) {
|
||||
if (seen.has(p.port)) bad(`El puerto ${p.port} se usa dos veces en este canal (${seen.get(p.port)} y ${p.what})`, p.what.includes('entrada') ? 'in_port' : 'srt_port');
|
||||
seen.set(p.port, p.what);
|
||||
}
|
||||
for (const o of others) {
|
||||
for (const q of portsOf(o.cfg)) {
|
||||
for (const p of mine) {
|
||||
if (p.port === q.port) {
|
||||
bad(`El puerto ${p.port} (${p.what}) ya lo usa el canal "${o.name}" (${q.what})`, p.what.includes('entrada') ? 'in_port' : 'srt_port');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { channel, conflicts, portsOf, ValidationError, SLUG_RE };
|
||||
Reference in New Issue
Block a user