queue.ts 4.16 KB
import type { Job } from './types';
import type { JobStore } from './jobStore';
import { cancelRun } from './runner';

export interface RunResult {
    resultDir: string | null;
    reportPath: string | null;
    /** True when the run was aborted via `cancel()`. */
    cancelled?: boolean;
}

/** A single run: drives the coderio engine for one job and resolves with paths. */
export type Runner = (
    job: Job,
    onPid: (pid: number) => void,
    onProgress?: (phase: string, percent: 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);
                },
                (phase, percent) => {
                    this.store.update(job.id, { phase, progress: percent });
                    this.onChange(this.store);
                },
            );
            if (result.cancelled) {
                this.store.update(job.id, {
                    status: 'cancelled',
                    finishedAt: new Date().toISOString(),
                    error: '已手动取消',
                });
            } else {
                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);
        }
    }

    /**
     * Abort a job. Queued jobs are dropped from the wait list; running jobs
     * have their child process killed (via `cancelRun`). The job is marked
     * `cancelled` immediately so the UI reflects it without waiting for the
     * child to fully exit. Returns false for unknown or already-terminal jobs.
     */
    cancel(id: string): boolean {
        const job = this.store.get(id);
        if (!job) return false;
        if (job.status !== 'queued' && job.status !== 'running') return false;

        const qi = this.queue.indexOf(id);
        if (qi >= 0) this.queue.splice(qi, 1);
        cancelRun(id);

        this.store.update(id, {
            status: 'cancelled',
            finishedAt: new Date().toISOString(),
            error: '已手动取消',
        });
        this.onChange(this.store);
        return true;
    }

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