queue.ts
2.75 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
import type { Job } from './types';
import type { JobStore } from './jobStore';
export interface RunResult {
resultDir: string;
reportPath: string | null;
}
/** A single run: drives the coderio engine for one job and resolves with paths. */
export type Runner = (
job: Job,
onPid: (pid: number) => void,
) => Promise<RunResult>;
/**
* Concurrency-limited job queue. Generation is heavy (LLM quota, Playwright),
* so we cap how many run at once. Jobs submitted beyond the limit are queued
* (FIFO) and picked up as slots free up. `onChange` is invoked after every
* state transition so the server can broadcast fresh state over SSE.
*/
export class JobQueue {
private queue: string[] = [];
private active = new Set<string>();
constructor(
private readonly store: JobStore,
private readonly runner: Runner,
private readonly maxConcurrent: number,
private readonly onChange: (store: JobStore) => void,
) {}
submit(job: Job): void {
this.store.create(job);
this.queue.push(job.id);
void this.pump();
this.onChange(this.store);
}
private async pump(): Promise<void> {
while (this.active.size < this.maxConcurrent && this.queue.length > 0) {
const id = this.queue.shift()!;
const job = this.store.get(id);
if (!job) continue;
this.active.add(id);
this.store.update(id, { status: 'running', startedAt: new Date().toISOString() });
this.onChange(this.store);
void this.runOne(job);
}
}
private async runOne(job: Job): Promise<void> {
try {
const result = await this.runner(job, (pid) => {
this.store.update(job.id, { pid });
this.onChange(this.store);
});
this.store.update(job.id, {
status: 'done',
finishedAt: new Date().toISOString(),
resultDir: result.resultDir,
reportPath: result.reportPath,
});
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
this.store.update(job.id, {
status: 'error',
finishedAt: new Date().toISOString(),
error: message,
});
} finally {
this.active.delete(job.id);
void this.pump();
this.onChange(this.store);
}
}
/** 1-based position in the wait queue, or 0 if not queued. */
position(id: string): number {
const i = this.queue.indexOf(id);
return i >= 0 ? i + 1 : 0;
}
pendingCount(): number {
return this.queue.length;
}
activeCount(): number {
return this.active.size;
}
}