queue.ts 2.75 KB
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;
    }
}