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          11x 11x     2146x 2146x 2146x 2146x 2146x 2146x 2146x   2146x       12x 12x       227x 227x 226x 226x 226x       1975x 1975x 57x 57x         1314x 2116x         952x 952x 376x 376x   952x       479x 6x   473x 473x                         473x 473x 473x 473x       437x 437x 98x   437x       859x 819x 819x 450x 4x     446x 446x       364x 386x         448x 448x 447x   446x 446x 446x 446x       110x 110x 109x 109x 109x 31x 31x 14x 14x 14x 14x 14x 4x 4x 3x 3x 3x 3x     10x       109x       243x 243x   242x 242x 242x 242x       90x 90x   89x 89x 90x 90x                     8x 8x   7x 7x 7x 7x 7x       35x 35x   30x 4x             4x 4x 4x 4x                         364x   364x 363x     364x 364x 364x 10x     364x 364x 364x 364x       364x 159x 159x   364x       32x 31x 29x         3x           49x 41x 41x       1690x 1690x 1443x 767x         1690x       1213x 1213x 1169x 18x         1213x       1180x       3x 3x       735x       753x 3x 3x      
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();
    }
}