All files / src task-queue.ts

100% Statements 160/160
100% Branches 74/74
100% Functions 27/27
100% Lines 142/142

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 294 295 296 297 298 299 300          9x 9x     1333x 1333x 1333x 1333x 1333x 1333x 1333x   9x       6x 6x       193x 193x 192x 192x 192x       1281x 1281x 56x 56x         1116x 1681x         864x 864x 335x 335x   864x       435x 6x   429x 429x                         429x 429x 429x 429x       399x 399x 92x   399x       774x 735x 735x 406x 4x     402x 402x       327x 345x         404x 404x 403x   402x 402x 402x 402x       94x 94x 93x 93x 93x 31x 31x 14x 14x 14x 14x 14x 4x 4x 3x 3x 3x 3x     10x       93x       208x 208x   207x 207x 207x 207x       88x 88x   87x 87x 88x 88x                     8x 8x   7x 7x 7x 7x 7x       35x 35x   30x 4x             4x 4x 4x 4x                         327x   327x 326x     327x 327x 327x 10x     327x 327x 327x 327x       327x 93x 93x   327x       30x 29x 27x         3x           30x 26x 26x       1353x 1353x 1139x 680x         1353x       902x 902x 866x 18x         902x       1029x       3x 3x       561x       480x 2x 2x      
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<number> = 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) window.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);
            /* v8 ignore next -- a queued task always has its type queue, created on enqueue */
            if (q) {
                const idx = q.indexOf(id);
                /* v8 ignore next -- a queued task is always present in its own queue */
                if (idx >= 0) q.splice(idx, 1);
            }
            this.tasks.delete(id);
            this.aborts.delete(id);
            this.notify();
            return;
        }
 
        /* v8 ignore next -- a live task is either QUEUED (handled above) or ACTIVE; terminal states are removed from tasks */
        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 = window.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);
                /* v8 ignore next -- a non-null active id always has a backing task entry */
                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);
                /* v8 ignore next -- a non-null active id always has a backing task entry */
                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);
                /* v8 ignore next -- queued ids always have a backing task entry */
                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();
    }
}