All files lock_object.ts

100% Statements 15/15
100% Branches 4/4
100% Functions 5/5
100% Lines 14/14

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        65x 65x     29x 21x 21x     8x       29x   8x 8x   21x         29x 29x 29x   29x        
// SPDX-FileCopyrightText: 2025 Anaconda, Inc
// SPDX-License-Identifier: Apache-2.0
 
export class Lock {
    private _locked = false;
    private _waiting: (() => void)[] = [];
 
    private async acquire(): Promise<void> {
        if (!this._locked) {
            this._locked = true;
            return;
        }
        // Wait until released
        await new Promise<void>((resolve) => this._waiting.push(resolve));
    }
 
    private release(): void {
        if (this._waiting.length > 0) {
            // Give the lock to the next waiter
            const next = this._waiting.shift()!;
            next();
        } else {
            this._locked = false;
        }
    }
 
    public async runExclusive<T>(fn: () => Promise<T> | T): Promise<T> {
        await this.acquire();
        try {
            return await fn();
        } finally {
            this.release();
        }
    }
}