jobStore.ts 4.87 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);
    }

    /**
     * Remove a single job. Caller is responsible for aborting a still-active
     * run (kill the child process) before calling this, so we don't leak a
     * detached vite/engine subprocess.
     */
    delete(id: string): boolean {
        if (!this.jobs.has(id)) return false;
        this.jobs.delete(id);
        if (this.db) {
            this.db.prepare('DELETE FROM jobs WHERE id = ?').run(id);
        } else if (this.jsonFallback) {
            this.writeJson();
        }
        return true;
    }

    /** Remove every job. Returns how many were removed. */
    clear(): number {
        const n = this.jobs.size;
        this.jobs.clear();
        if (this.db) {
            this.db.prepare('DELETE FROM jobs').run();
        } else if (this.jsonFallback) {
            this.writeJson();
        }
        return n;
    }

    private writeJson(): void {
        if (!this.jsonFallback) return;
        fs.writeFileSync(this.jsonFallback, JSON.stringify([...this.jobs.values()], null, 2));
    }

    /** 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);
    }

    /**
     * On startup, any job left in `running`/`queued` from a previous process is
     * an orphan (its child process no longer exists). Mark them cancelled so the
     * UI never shows a permanently stuck "生成中" and the concurrency slot frees.
     * Returns the number of jobs reconciled.
     */
    reconcileOnStartup(): number {
        const orphans = [...this.jobs.values()].filter(
            (j) => j.status === 'running' || j.status === 'queued',
        );
        for (const j of orphans) {
            this.jobs.set(j.id, {
                ...j,
                status: 'cancelled',
                finishedAt: new Date().toISOString(),
                error: '服务重启,任务已中止',
            });
        }
        if (orphans.length) {
            this.persist(orphans.map((j) => this.jobs.get(j.id)!));
        }
        return orphans.length;
    }
}