-
Notifications
You must be signed in to change notification settings - Fork 35
/
MutexService.js
70 lines (58 loc) · 1.79 KB
/
MutexService.js
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class AcquireTimeoutError extends Error {
}
class MutexService {
constructor() {
this.queue = [];
this.locked = false;
}
async acquire(callback, timeLimitMS = 500) {
let timeoutHandle;
const lockHandler = {}
const timeoutPromise = new Promise((resolve, reject) => {
lockHandler.resolve = resolve
lockHandler.reject = reject
timeoutHandle = setTimeout(
() => reject(new AcquireTimeoutError('MutexService timeout reached')),
timeLimitMS
);
});
const asyncPromise = new Promise((resolve, reject) => {
if (this.locked) {
lockHandler.resolve = resolve
lockHandler.reject = reject
this.queue.push(lockHandler);
} else {
this.locked = true;
resolve();
}
});
await Promise.race([asyncPromise, timeoutPromise]).then(async () => {
clearTimeout(timeoutHandle);
try {
if (callback[Symbol.toStringTag] === 'AsyncFunction') {
await callback()
return
}
callback()
} finally {
this.release()
}
}).catch(e => {
let index = this.queue.indexOf(lockHandler);
if (index !== -1) {
this.queue.splice(index, 1);
}
throw e
})
}
release() {
if (this.queue.length > 0) {
const queueItem = this.queue.shift();
queueItem.resolve();
} else {
this.locked = false;
}
}
}
module.exports.MutexService = MutexService
module.exports.AcquireTimeoutError = AcquireTimeoutError