jobStore.ts
4.87 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
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;
}
}