jobStore.ts 3 KB
import { DatabaseSync } from 'node:sqlite';
import path from 'node:path';
import fs from 'node:fs';
import type { Job } from './types';

/**
 * Job persistence. Primary backend is SQLite (Node's built-in `node:sqlite`,
 * zero external dependencies). If SQLite is unavailable for any reason we fall
 * back to a JSON file so the service still runs. Either way, jobs survive a
 * server restart (unlike the old single in-memory `currentJob`).
 */
export class JobStore {
    private db: DatabaseSync | null = null;
    private jsonFallback: string | null = null;
    private jobs = new Map<string, Job>();

    constructor(dataDir: string) {
        fs.mkdirSync(dataDir, { recursive: true });
        const dbPath = path.join(dataDir, 'jobs.db');
        try {
            this.db = new DatabaseSync(dbPath);
            this.db.exec(
                'CREATE TABLE IF NOT EXISTS jobs (id TEXT PRIMARY KEY, payload TEXT NOT NULL, updated_at INTEGER NOT NULL)',
            );
            const rows = this.db.prepare('SELECT payload FROM jobs').all() as Array<{ payload: string }>;
            for (const r of rows) {
                try {
                    const j = JSON.parse(r.payload) as Job;
                    this.jobs.set(j.id, j);
                } catch {
                    /* skip corrupt row */
                }
            }
        } catch (e) {
            console.warn(
                '[jobStore] SQLite 不可用,回退到 JSON 文件存储:',
                e instanceof Error ? e.message : String(e),
            );
            this.db = null;
            this.jsonFallback = path.join(dataDir, 'jobs.json');
            if (fs.existsSync(this.jsonFallback)) {
                try {
                    const arr = JSON.parse(fs.readFileSync(this.jsonFallback, 'utf8')) as Job[];
                    for (const j of arr) this.jobs.set(j.id, j);
                } catch {
                    /* ignore */
                }
            }
        }
    }

    private persist(jobs: Job[]): void {
        if (this.db) {
            const stmt = this.db.prepare('INSERT OR REPLACE INTO jobs (id, payload, updated_at) VALUES (?, ?, ?)');
            for (const j of jobs) stmt.run(j.id, JSON.stringify(j), Date.now());
        } else if (this.jsonFallback) {
            fs.writeFileSync(this.jsonFallback, JSON.stringify([...this.jobs.values()], null, 2));
        }
    }

    create(job: Job): void {
        this.jobs.set(job.id, job);
        this.persist([job]);
    }

    update(id: string, patch: Partial<Job>): Job | null {
        const cur = this.jobs.get(id);
        if (!cur) return null;
        const next = { ...cur, ...patch };
        this.jobs.set(id, next);
        this.persist([next]);
        return next;
    }

    get(id: string): Job | undefined {
        return this.jobs.get(id);
    }

    /** Most-recent-first list (for the history view). */
    list(limit = 50): Job[] {
        return [...this.jobs.values()]
            .sort((a, b) => b.createdAt.localeCompare(a.createdAt))
            .slice(0, limit);
    }
}