All files / src operation-queue.ts

92.3% Statements 48/52
88.23% Branches 15/17
100% Functions 4/4
92.3% Lines 48/52

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 761x           1x 9x 9x   9x 9x 9x             9x 26x 26x 26x 26x     26x 26x   26x   2x         2x 2x 26x   24x 24x   26x 1x 25x 1x 24x   26x   26x 26x 26x 26x 25x 25x 26x 26x 1x 1x 26x   26x 26x 26x 26x   26x 26x   9x 1x 1x 9x  
import { Logger } from "./logger";
 
/**
 * Serializes asynchronous operations to prevent race conditions.
 * Operations are executed one at a time in FIFO order.
 */
export class OperationQueue {
    private queue: Promise<void> = Promise.resolve();
    private readonly contextName?: string;
 
    constructor(contextName?: string) {
        this.contextName = contextName;
    }
 
    public enqueue<T>(operation: () => Promise<T>): Promise<T>;
    public enqueue<T>(
        operationName: string,
        operation: () => Promise<T>
    ): Promise<T>;
    public enqueue<T>(
        operationOrName: string | (() => Promise<T>),
        operation?: () => Promise<T>
    ): Promise<T> {
        const logger = Logger.getInstance();
 
        // Resolve the operation function and name based on call signature
        let operationFn: () => Promise<T>;
        let operationName: string | undefined;
 
        if (typeof operationOrName === "string") {
            // Named signature: enqueue("name", operation)
            if (!operation) {
                throw new Error(
                    `Operation function required when using named signature: ${operationOrName}`
                );
            }
            operationName = operationOrName;
            operationFn = operation;
        } else {
            // Anonymous signature: enqueue(operation)
            operationFn = operationOrName;
        }
 
        const logPrefix = this.contextName
            ? `[${this.contextName}${operationName ? `::${operationName}` : ""}]`
            : operationName
              ? `[${operationName}]`
              : "[Operation]";
 
        logger.debug(`${logPrefix} Enqueued`);
 
        const newOperation = this.queue
            .then(async () => {
                logger.debug(`${logPrefix} Executing`);
                const result = await operationFn();
                logger.debug(`${logPrefix} Completed`);
                return result;
            })
            .catch((error) => {
                logger.error(`${logPrefix} Failed:`, error);
                throw error;
            });
 
        this.queue = newOperation.then(
            () => {},
            () => {}
        );
 
        return newOperation;
    }
 
    public async flush(): Promise<void> {
        await this.queue;
    }
}