SPB Git

Repository Public

jobs.ts 1.9 KB 28 lines typescript

1import { all, get, now, run, tx } from "./db";23export type JobType = "sync" | "epg" | "vod" | "library" | "sources";4export interface Job { id: number; type: JobType; status: "queued" | "running" | "done" | "failed"; requested_at: number; started_at: number | null; finished_at: number | null; result: string | null; error: string | null; trigger: string }56/** Queue a job unless one of the same type is already queued or running. Returns the job id either way. */7export function enqueue(type: JobType, trigger: "manual" | "schedule" | "startup"): number {8  return tx(() => {9    const cur = get<{ id: number }>("SELECT id FROM jobs WHERE type = ? AND status IN ('queued','running') ORDER BY id LIMIT 1", type);10    if (cur) return cur.id;11    return Number(run("INSERT INTO jobs(type, requested_at, trigger) VALUES(?,?,?)", type, now(), trigger).lastInsertRowid);12  });13}14/** Takes the oldest queued job among `types`. Long catalogue imports run in their own loop so they never delay a sync. */15export function claim(types: JobType[]): Job | undefined {16  return tx(() => {17    const j = get<Job>(`SELECT * FROM jobs WHERE status = 'queued' AND type IN (${types.map(() => "?").join(",")}) ORDER BY id LIMIT 1`, ...types);18    if (j) run("UPDATE jobs SET status = 'running', started_at = ? WHERE id = ?", now(), j.id);19    return j;20  });21}22export function finish(id: number, result: unknown, error?: string) {23  run("UPDATE jobs SET status = ?, finished_at = ?, result = ?, error = ? WHERE id = ?", error ? "failed" : "done", now(), result ? JSON.stringify(result) : null, error ?? null, id);24  run("DELETE FROM jobs WHERE id < (SELECT MAX(id) FROM jobs) - 200");25}26export const recentJobs = (limit = 30) => all<Job>("SELECT * FROM jobs ORDER BY id DESC LIMIT ?", limit);27export const lastDone = (type: JobType) => get<Job>("SELECT * FROM jobs WHERE type = ? AND status = 'done' ORDER BY id DESC LIMIT 1", type);28
Files main
Menu

Theme