ravendb
Version:
RavenDB client for Node.js
68 lines • 2.13 kB
JavaScript
import { AsyncTimeout } from "./PromiseUtil.js";
import { getError } from "../Exceptions/index.js";
class SemaphoreAcquisition {
_acquired;
_disposed = false;
_timeout;
_sem;
_promise;
get promise() {
return this._promise;
}
_isTimedOut() {
return this._timeout && this._timeout.timedOut;
}
constructor(sem, semOpts) {
const contextName = semOpts ? semOpts.contextName : "";
if (semOpts && semOpts.timeout != null) {
const timedOutOpName = contextName ? `WAIT_FOR_SEM_${contextName}` : null;
this._timeout = new AsyncTimeout(semOpts.timeout, timedOutOpName);
}
this._acquired = false;
this._sem = sem;
this._initialize();
}
_initialize() {
const sem = this._sem;
const semAcquired = new Promise((resolve, reject) => {
sem.take(() => {
if (this._disposed || this._isTimedOut()) {
// when we finally got here after timeout or disposal
// need to release it anyway
sem.leave();
reject(getError("InvalidOperationException", "Semaphore acquire timed out or was disposed."));
return;
}
this._acquired = true;
resolve();
});
});
let resultPromise = semAcquired;
if (this._timeout) {
resultPromise = Promise.race([
semAcquired,
this._timeout.promise
])
.then(() => this._timeout.cancel());
}
this._promise = resultPromise;
}
dispose() {
if (this._disposed) {
return;
}
this._disposed = true;
if (this._timeout) {
this._timeout.cancel();
}
if (!this._acquired) {
return;
}
this._sem.leave();
this._acquired = false;
}
}
export function acquireSemaphore(sem, semOpts) {
return new SemaphoreAcquisition(sem, semOpts);
}
//# sourceMappingURL=SemaphoreUtil.js.map