UNPKG

@apiratorjs/locking

Version:

A lightweight library providing both local and distributed locking primitives (mutexes, semaphores, and read-write locks) for managing concurrency in Node.js.

93 lines 3.13 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.InMemoryDistributedReadWriteLock = void 0; const read_write_lock_1 = require("../read-write-lock"); const in_memory_distributed_registry_1 = require("./in-memory-distributed-registry"); const errors_1 = require("../errors"); class InMemoryDistributedReadWriteLock { constructor(props, _registry = in_memory_distributed_registry_1.inMemoryDistributedRWLockRegistry, _type = "rwlock") { this._registry = _registry; this._type = _type; this._isDestroyed = false; this.implementation = "in-memory"; this.name = `${_type}:${props.name}`; if (!this._registry.has(this.name)) { this._registry.set(this.name, new read_write_lock_1.ReadWriteLock({ maxReaders: props.maxReaders })); } } get isDestroyed() { return this._isDestroyed; } async maxReaders() { return this.getRWLockOrException().maxReaders(); } async activeReaders() { return this.getRWLockOrException().activeReaders(); } async withReadLock(...args) { let callback; let params; if (args.length === 1) { callback = args[0]; } else { params = args[0]; callback = args[1]; } const rwLock = this.getRWLockOrException(); if (params) { return rwLock.withReadLock(params, callback); } else { return rwLock.withReadLock(callback); } } async withWriteLock(...args) { let callback; let params; if (args.length === 1) { callback = args[0]; } else { params = args[0]; callback = args[1]; } const rwLock = this.getRWLockOrException(); if (params) { return rwLock.withWriteLock(params, callback); } else { return rwLock.withWriteLock(callback); } } async destroy(message) { const rwLock = this.getRWLockOrException(); this._isDestroyed = true; this._registry.delete(this.name); await rwLock.cancelAll(message ?? "ReadWriteLock destroyed"); } async acquireRead(params) { return this.getRWLockOrException().acquireRead(params); } async acquireWrite(params) { return this.getRWLockOrException().acquireWrite(params); } async cancelAll(errMessage) { return this.getRWLockOrException().cancelAll(errMessage); } async isReadLocked() { return this.getRWLockOrException().isReadLocked(); } async isWriteLocked() { return this.getRWLockOrException().isWriteLocked(); } getRWLockOrException() { const rwLock = this._registry.get(this.name); if (!rwLock) { throw new errors_1.LockNotFoundError(`${this._type} '${this.name}' does not exist`); } return rwLock; } } exports.InMemoryDistributedReadWriteLock = InMemoryDistributedReadWriteLock; //# sourceMappingURL=in-memory-distributed-read-write-lock.js.map