jobStore.ts
3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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);
}
}