All files / src task-queue.ts

100% Statements 242/242
100% Branches 96/96
100% Functions 27/27
100% Lines 242/242

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 2941x         1x 1x   1x 1131x 1131x 1131x 1131x 1131x 1131x 1131x   1131x     1131x 5x 5x 5x   1131x 179x 179x 178x 178x 178x 179x   1131x 1045x 1045x 53x 53x 53x 1045x   1131x 1067x 1603x 1603x 1067x   1131x 830x 830x 319x 319x 319x 830x 830x   1131x 418x 6x 6x 412x 412x 412x 412x 412x 412x 412x 412x 412x 412x 412x 412x 412x 412x 412x 412x 412x 412x 418x   1131x 383x 383x 92x 92x 383x 383x   1131x 743x 706x 743x 743x 4x 4x   386x 386x 743x   1131x 313x 331x 331x 313x   1131x 388x 388x 387x   386x 386x 386x 386x 388x   1131x 85x 85x 84x 85x 85x 30x 30x 14x 14x 14x 14x 14x 4x 4x 3x 3x 3x 3x 3x 14x 10x 10x 14x 30x 84x 85x   1131x 198x 198x   197x 197x 197x 197x 198x   1131x 83x 83x   82x 83x 83x 83x 83x                 1131x 8x 8x   7x 8x 7x 7x 7x 8x   1131x 36x 36x   36x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   27x 27x 27x 27x 27x 27x 36x   1131x 313x   313x 313x 313x   313x 313x 313x 10x 10x   313x 313x 313x 313x 313x   1131x 313x 97x 97x 313x 313x 313x   1131x 28x 27x 26x 26x 26x 27x 2x 28x       1131x 29x 25x 29x 29x   1131x 1810x 1810x 1671x 959x 959x 959x 1671x 1810x 1810x   1131x 1379x 1379x 1411x 19x 19x 19x 1411x 1379x 1379x   1131x 1493x 1493x   1131x 3x 3x 3x   1131x 511x 511x   1131x 381x 2x 2x 381x 1131x  
import type { TaskEntry, TaskType } from "./types";
import { BACKGROUND_TASK_TYPES, TASK_QUEUE, TASK_STATUS } from "./types";
 
export type TaskChangeListener = () => void;
 
const RATE_SAMPLE_FLOOR_MS = 500;
export const FLASH_WINDOW_MS = 2000;
 
export class TaskQueue {
    private tasks: Map<string, TaskEntry> = new Map();
    private queues: Map<TaskType, string[]> = new Map();
    private activeIds: Map<TaskType, string | null> = new Map();
    private aborts: Map<string, AbortController> = new Map();
    private history: TaskEntry[] = [];
    private listeners: TaskChangeListener[] = [];
    private flashTimers: Set<ReturnType<typeof setTimeout>> = new Set();
 
    static readonly MAX_HISTORY = 50;
 
    /** Clear pending flash-clear timers — call from plugin unload to avoid zombie notifies. */
    dispose(): void {
        for (const handle of this.flashTimers) clearTimeout(handle);
        this.flashTimers.clear();
    }
 
    registerAbort(id: string, controller: AbortController): void {
        const task = this.tasks.get(id);
        if (!task) return;
        this.aborts.set(id, controller);
        task.canCancel = true;
        this.notify();
    }
 
    onChange(listener: TaskChangeListener): () => void {
        this.listeners.push(listener);
        return () => {
            const idx = this.listeners.indexOf(listener);
            if (idx >= 0) this.listeners.splice(idx, 1);
        };
    }
 
    private notify(): void {
        for (const listener of this.listeners) {
            listener();
        }
    }
 
    private typeQueue(type: TaskType): string[] {
        let q = this.queues.get(type);
        if (!q) {
            q = [];
            this.queues.set(type, q);
        }
        return q;
    }
 
    enqueue(name: string, type: TaskType, retry?: () => void | Promise<void>): string | null {
        if (this.typeQueue(type).length >= TASK_QUEUE.MAX_QUEUED_PER_TYPE) {
            return null;
        }
        const id = `${type}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
        const task: TaskEntry = {
            id,
            name,
            type,
            status: TASK_STATUS.QUEUED,
            progress: 0,
            detail: "",
            startedAt: Date.now(),
            completedAt: null,
            error: null,
            canCancel: true,
            retry,
        };
        this.tasks.set(id, task);
        this.typeQueue(type).push(id);
        this.processType(type);
        return id;
    }
 
    private backgroundActiveCount(): number {
        let count = 0;
        for (const [type, id] of this.activeIds) {
            if (id && BACKGROUND_TASK_TYPES.has(type)) count++;
        }
        return count;
    }
 
    private processType(type: TaskType): void {
        if (this.activeIds.get(type)) return;
        const q = this.queues.get(type);
        if (!q || q.length === 0) return;
        if (BACKGROUND_TASK_TYPES.has(type) && this.backgroundActiveCount() >= TASK_QUEUE.MAX_CONCURRENT_BACKGROUND) {
            return;
        }
 
        const nextId = q.shift()!;
        this.activate(nextId);
    }
 
    private processAll(): void {
        for (const type of this.queues.keys()) {
            this.processType(type);
        }
    }
 
    activate(id: string): void {
        const task = this.tasks.get(id);
        if (!task) return;
        if (task.status !== TASK_STATUS.QUEUED) return;
 
        task.status = TASK_STATUS.ACTIVE;
        task.canCancel = this.aborts.has(id);
        this.activeIds.set(task.type, id);
        this.notify();
    }
 
    update(id: string, progress: number, detail?: string, bytes?: { current?: number; total?: number }): void {
        const task = this.tasks.get(id);
        if (!task) return;
        task.progress = progress;
        if (detail !== undefined) task.detail = detail;
        if (bytes) {
            if (bytes.total !== undefined) task.bytesTotal = bytes.total;
            if (bytes.current !== undefined) {
                const now = Date.now();
                const prevBytes = task.bytesCurrent;
                const prevAt = task.lastRateAt;
                task.bytesCurrent = bytes.current;
                if (prevBytes !== undefined && prevAt !== undefined) {
                    const elapsedMs = now - prevAt;
                    if (elapsedMs >= RATE_SAMPLE_FLOOR_MS) {
                        const deltaBytes = bytes.current - prevBytes;
                        const rate = (deltaBytes / elapsedMs) * 1000;
                        task.rateBps = rate > 0 ? rate : 0;
                        task.lastRateAt = now;
                    }
                } else {
                    task.lastRateAt = now;
                }
            }
        }
        this.notify();
    }
 
    complete(id: string): void {
        const task = this.tasks.get(id);
        if (!task) return;
 
        task.status = TASK_STATUS.DONE;
        task.progress = 100;
        task.completedAt = Date.now();
        this.moveToHistory(id);
    }
 
    fail(id: string, error?: string): void {
        const task = this.tasks.get(id);
        if (!task) return;
 
        task.status = TASK_STATUS.FAILED;
        task.error = error ?? null;
        task.completedAt = Date.now();
        this.moveToHistory(id);
    }
 
    /**
     * Neutral terminal state: the server told us it is already handling this work
     * (e.g. a concurrent /api/add for the same source). The task isn't done — the
     * original request is still running — and it isn't failed either, so Retry
     * would just collide again. Park it in history with a `waiting` status and
     * no retry affordance.
     */
    markWaiting(id: string, detail?: string): void {
        const task = this.tasks.get(id);
        if (!task) return;
 
        task.status = TASK_STATUS.WAITING;
        if (detail !== undefined) task.detail = detail;
        task.completedAt = Date.now();
        task.retry = undefined;
        this.moveToHistory(id);
    }
 
    cancel(id: string): void {
        const task = this.tasks.get(id);
        if (!task) return;
 
        if (task.status === TASK_STATUS.QUEUED) {
            const q = this.queues.get(task.type);
            if (q) {
                const idx = q.indexOf(id);
                if (idx >= 0) q.splice(idx, 1);
            }
            this.tasks.delete(id);
            this.aborts.delete(id);
            this.notify();
            return;
        }
 
        if (task.status === TASK_STATUS.ACTIVE) {
            this.aborts.get(id)?.abort();
            task.status = TASK_STATUS.CANCELLED;
            task.completedAt = Date.now();
            this.moveToHistory(id);
        }
    }
 
    private moveToHistory(id: string): void {
        const task = this.tasks.get(id)!;
 
        if (this.activeIds.get(task.type) === id) {
            this.activeIds.set(task.type, null);
        }
 
        this.aborts.delete(id);
        this.history.unshift(task);
        if (this.history.length > TaskQueue.MAX_HISTORY) {
            this.history.pop();
        }
 
        this.tasks.delete(id);
        this.notify();
        this.scheduleFlashClear();
        this.processAll();
    }
 
    private scheduleFlashClear(): void {
        const handle = setTimeout(() => {
            this.flashTimers.delete(handle);
            this.notify();
        }, FLASH_WINDOW_MS);
        this.flashTimers.add(handle);
    }
 
    get active(): TaskEntry | null {
        for (const id of this.activeIds.values()) {
            if (id) {
                const task = this.tasks.get(id);
                if (task) return task;
            }
        }
        return null;
    }
 
    /** Returns all currently active tasks across all types. */
    /** Returns true if a task of the given type is active or queued. */
    hasPending(type: TaskType): boolean {
        if (this.activeIds.get(type)) return true;
        const q = this.queues.get(type);
        return q !== undefined && q.length > 0;
    }
 
    get activeAll(): TaskEntry[] {
        const result: TaskEntry[] = [];
        for (const id of this.activeIds.values()) {
            if (id) {
                const task = this.tasks.get(id);
                if (task) result.push(task);
            }
        }
        return result;
    }
 
    get queued(): TaskEntry[] {
        const result: TaskEntry[] = [];
        for (const q of this.queues.values()) {
            for (const id of q) {
                const task = this.tasks.get(id);
                if (task) result.push(task);
            }
        }
        return result;
    }
 
    get completed(): TaskEntry[] {
        return [...this.history];
    }
 
    clearHistory(): void {
        this.history = [];
        this.notify();
    }
 
    toJSON(): { history: TaskEntry[] } {
        return { history: [...this.history] };
    }
 
    loadFromJSON(data: { history?: TaskEntry[] } | undefined): void {
        if (!data || !Array.isArray(data.history)) return;
        this.history = data.history.slice(0, TaskQueue.MAX_HISTORY);
        this.notify();
    }
}