SPB Git

Repository Public

index.ts 6.2 KB 98 lines typescript

1import { bumpCatalog, closeDb, db, get, getNum, getSetting, log, now, run, setSetting } from "@/server/db";2import { dueStreams, runBatch } from "@/server/checker";3import { refreshEpg } from "@/server/epg";4import { claim, enqueue, finish, lastDone } from "@/server/jobs";5import { ensureBuiltinSources, syncCatalog } from "@/server/sync";6import { importVod } from "@/server/vod";7import { scanLibrary } from "@/server/library";8import { ensureBuiltinVod, expireTitles, refreshSources } from "@/server/engine";9import { sample as relaySample } from "@/server/relay/health";1011// Background worker: catalogue synchronisation and guide refresh (queued jobs + schedule) and the continuous, rate-limited12// availability monitor. It talks to the web process only through the SQLite database.13let stopping = false, scanning = false;14const sleep = (ms: number) => new Promise<void>((r) => { setTimeout(r, ms); });1516async function jobLoop(types: Parameters<typeof claim>[0]) {17  while (!stopping) {18    const job = claim(types);19    if (!job) { await sleep(2000); continue; }20    log("info", "worker", `Tâche ${job.type} #${job.id} démarrée (${job.trigger})`);21    try {22      const result = job.type === "sync" ? await syncCatalog() : job.type === "epg" ? await refreshEpg() : job.type === "vod" ? await importVod(() => stopping) : job.type === "sources" ? await refreshSources() : await scanLibrary();23      const failed = job.type === "sync" && (result as Awaited<ReturnType<typeof syncCatalog>>).sources.every((s) => !s.ok);24      finish(job.id, result, failed ? "Aucune source n'a pu être synchronisée" : undefined);25      if (job.type === "epg") {26        // A guide file that could not be fetched is asked again within the hour rather than at the next full interval.27        const failed = (result as Awaited<ReturnType<typeof refreshEpg>>).sources.some((s) => !s.ok);28        setSetting("last_epg_at", String(failed ? now() - getNum("epg_interval_hours") * 3600_000 + 3600_000 : now()));29      }30      if (job.type === "vod") setSetting("last_vod_at", String(now()));31      if (job.type === "sources") setSetting("last_sources_at", String(now()));32      if (job.type === "library") setSetting("last_library_at", String(now()));33      // A fresh catalogue changes the guide list: refresh the guide right after the first import.34      if (job.type === "sync" && !failed && !lastDone("epg") && getSetting("epg_enabled") === "1") enqueue("epg", "schedule");35    } catch (e) {36      finish(job.id, null, (e as Error).message);37      log("error", "worker", `Tâche ${job.type} #${job.id} en échec`, { error: (e as Error).message });38    }39  }40}4142async function scheduleLoop() {43  while (!stopping) {44    try {45      setSetting("worker_heartbeat", String(now()));46      const lastSync = Number(getSetting("last_sync_at") ?? 0);47      if (now() - lastSync > getNum("sync_interval_hours") * 3600_000) enqueue("sync", lastSync ? "schedule" : "startup");48      const lastEpg = Number(getSetting("last_epg_at") ?? 0);49      if (lastSync && getSetting("epg_enabled") === "1" && now() - lastEpg > getNum("epg_interval_hours") * 3600_000) enqueue("epg", "schedule");50      // Films and series: weekly by default (the sources change slowly). Library: a light scan every few minutes picks up new files.51      if (lastSync && now() - Number(getSetting("last_vod_at") ?? 0) > getNum("vod_interval_hours") * 3600_000) enqueue("vod", "schedule");52      if (!scanning && now() - Number(getSetting("last_library_at") ?? 0) > getNum("library_interval_minutes") * 60_000 && get("SELECT 1 FROM library_dirs WHERE enabled = 1")) {53        // Not queued as a job: it runs often and usually finds nothing; it only writes to the journal when something changed.54        scanning = true; setSetting("last_library_at", String(now()));55        scanLibrary().catch((e) => log("error", "library", "Analyse planifiée en échec", { error: (e as Error).message })).finally(() => { scanning = false; });56      }57      // ARTE (rotating rights), NASA and the sources you added: every day.58      if (lastSync && now() - Number(getSetting("last_sources_at") ?? 0) > getNum("sources_interval_hours") * 3600_000) enqueue("sources", "schedule");59      expireTitles();60      run("DELETE FROM logs WHERE at < ?", now() - 30 * 86400_000);61    } catch (e) { log("error", "worker", "Planificateur", { error: (e as Error).message }); }62    await sleep(30_000);63  }64}6566async function checkLoop() {67  await sleep(5000);68  while (!stopping) {69    if (getSetting("check_enabled") !== "1") { await sleep(30_000); continue; }70    const batch = dueStreams(400);71    if (!batch.length) { await sleep(60_000); continue; }72    const t0 = now();73    const r = await runBatch(batch, { concurrency: getNum("check_concurrency"), hostDelayMs: getNum("check_host_delay_ms"), timeoutMs: getNum("check_timeout_ms"), shouldStop: () => stopping || getSetting("check_enabled") !== "1" });74    setSetting("last_check_batch", JSON.stringify({ at: now(), tested: r.up + r.down, up: r.up, down: r.down, ms: now() - t0 }));75    bumpCatalog();76    log("info", "check", `Lot vérifié : ${r.up} disponibles, ${r.down} indisponibles`, { ms: now() - t0 });77  }78}7980// Relay engine: real measurements every five seconds, silent sessions closed, frozen sources reconnected.81async function relayLoop() {82  await sleep(3000);83  while (!stopping) {84    try { await relaySample(); } catch (e) { log("error", "relay", "Surveillance du relais", { error: (e as Error).message }); }85    await sleep(5000);86  }87}8889async function main() {90  db(); ensureBuiltinSources(); ensureBuiltinVod();91  const stale = run("UPDATE jobs SET status = 'failed', finished_at = ?, error = 'Interrompue par un redémarrage du worker' WHERE status = 'running'", now());92  log("info", "worker", `Worker démarré${stale.changes ? ` (${stale.changes} tâche(s) interrompue(s))` : ""}`);93  for (const sig of ["SIGINT", "SIGTERM"] as const) process.on(sig, () => { if (stopping) process.exit(0); stopping = true; log("info", "worker", "Arrêt demandé"); setTimeout(() => { closeDb(); process.exit(0); }, 12_000).unref(); });94  await Promise.all([jobLoop(["sync", "epg", "library"]), jobLoop(["vod", "sources"]), scheduleLoop(), checkLoop(), relayLoop()]);95  closeDb();96}97main().catch((e) => { console.error(e); process.exit(1); });98
Files main
Menu

Theme