All files / packages/coordination/src mutex.ts

100% Statements 15/15
100% Branches 2/2
100% Functions 4/4
100% Lines 15/15

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        10x   10x               18x       39x       15x 15x 15x 15x       4x 4x       4x 2x 2x   2x 2x      
import { loggers } from '@ydbjs/debug'
 
import { Lease, Semaphore } from './semaphore.js'
 
let dbg = loggers.coordination.extend('mutex')
 
let mutexCapacity = 2n ** 64n - 1n
 
export type Lock = Lease
 
export class Mutex {
	#semaphore: Semaphore
 
	constructor(semaphore: Semaphore) {
		this.#semaphore = semaphore
	}
 
	get name(): string {
		return this.#semaphore.name
	}
 
	async lock(signal?: AbortSignal): Promise<Lock> {
		dbg.log('waiting to acquire lock on %s', this.name)
		let lease = await this.#semaphore.acquire({ count: mutexCapacity, ephemeral: true }, signal)
		dbg.log('lock acquired on %s', this.name)
		return lease
	}
 
	async tryLock(signal?: AbortSignal): Promise<Lock | null> {
		dbg.log('trying to acquire lock on %s without waiting', this.name)
		let lease = await this.#semaphore.tryAcquire(
			{ count: mutexCapacity, ephemeral: true },
			signal
		)
		if (!lease) {
			dbg.log('%s is already locked, skipping', this.name)
			return null
		}
		dbg.log('lock acquired on %s', this.name)
		return lease
	}
}