X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils%2FAsyncLock.ts;h=fe984cebdef97d8043d0f29f6fb9ba99ec502f3c;hb=ab7a96fac9432c4759e0bb69a12bb481b1570e02;hp=6b16b0f8a491622a91c8eed844ba5f30bc70b02f;hpb=5983297441ae1af1d5a6e9ecc38ba04f8777724b;p=e-mobility-charging-stations-simulator.git diff --git a/src/utils/AsyncLock.ts b/src/utils/AsyncLock.ts index 6b16b0f8..fe984ceb 100644 --- a/src/utils/AsyncLock.ts +++ b/src/utils/AsyncLock.ts @@ -1,6 +1,8 @@ // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. -import { Queue } from 'mnemonist'; +import Queue from 'mnemonist/queue.js'; + +import { Constants } from './Constants'; export enum AsyncLockType { configuration = 'configuration', @@ -19,25 +21,33 @@ export class AsyncLock { this.resolveQueue = new Queue(); } - public static async acquire(type: AsyncLockType): Promise { + public static async runExclusive(type: AsyncLockType, fn: () => T | Promise): Promise { + return AsyncLock.acquire(type) + .then(fn) + .finally(() => { + AsyncLock.release(type).catch(Constants.EMPTY_FUNCTION); + }); + } + + private static async acquire(type: AsyncLockType): Promise { const asyncLock = AsyncLock.getAsyncLock(type); if (!asyncLock.acquired) { asyncLock.acquired = true; return; } - return new Promise((resolve) => { + return new Promise((resolve) => { asyncLock.resolveQueue.enqueue(resolve); }); } - public static async release(type: AsyncLockType): Promise { + private static async release(type: AsyncLockType): Promise { const asyncLock = AsyncLock.getAsyncLock(type); if (asyncLock.resolveQueue.size === 0 && asyncLock.acquired) { asyncLock.acquired = false; return; } - const queuedResolve = asyncLock.resolveQueue.dequeue(); - return new Promise((resolve) => { + const queuedResolve = asyncLock.resolveQueue.dequeue()!; + return new Promise((resolve) => { queuedResolve(); resolve(); }); @@ -47,6 +57,6 @@ export class AsyncLock { if (!AsyncLock.asyncLocks.has(type)) { AsyncLock.asyncLocks.set(type, new AsyncLock()); } - return AsyncLock.asyncLocks.get(type); + return AsyncLock.asyncLocks.get(type)!; } }