-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
web-locks.js
201 lines (176 loc) Β· 4.36 KB
/
web-locks.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
'use strict';
const { EventEmitter } = require('events');
const threads = require('worker_threads');
const { isMainThread, parentPort } = threads;
const isWorkerThread = !isMainThread;
const LOCKED = 0;
const UNLOCKED = 1;
let locks = null; // LockManager instance
class Lock {
constructor(name, mode = 'exclusive', buffer = null) {
this.name = name;
this.mode = mode; // 'exclusive' or 'shared'
this.queue = [];
this.owner = false;
this.trying = false;
this.buffer = buffer ? buffer : new SharedArrayBuffer(4);
this.flag = new Int32Array(this.buffer, 0, 1);
if (!buffer) Atomics.store(this.flag, 0, UNLOCKED);
}
enter(handler) {
return new Promise((resolve, reject) => {
this.queue.push({ handler, resolve, reject });
this.trying = true;
setTimeout(() => {
this.tryEnter();
}, 0);
});
}
tryEnter() {
if (this.queue.length === 0) return;
const prev = Atomics.exchange(this.flag, 0, LOCKED);
if (prev === LOCKED) return;
this.owner = true;
this.trying = false;
const { handler, resolve, reject } = this.queue.shift();
handler(this)
.then(() => {
this.leave();
resolve();
})
.catch((error) => {
this.leave();
reject(error);
});
}
leave() {
if (!this.owner) return;
Atomics.store(this.flag, 0, UNLOCKED);
this.owner = false;
const message = { webLocks: true, kind: 'leave', name: this.name };
locks.send(message);
this.tryEnter();
}
}
class LockManagerSnapshot {
constructor(resources) {
const held = [];
const pending = [];
this.held = held;
this.pending = pending;
for (const lock of resources) {
if (lock.queue.length > 0) {
pending.push(...lock.queue);
}
if (lock.owner) {
held.push(lock);
}
}
}
}
class LockManager {
constructor() {
this.collection = new Map();
this.workers = new Set();
if (isWorkerThread) {
parentPort.on('message', (message) => {
this.receive(message);
});
}
}
async request(name, options, handler) {
if (typeof options === 'function') {
handler = options;
options = {};
}
const { mode = 'exclusive', signal = null } = options;
let lock = this.collection.get(name);
if (!lock) {
lock = new Lock(name, mode);
this.collection.set(name, lock);
const { buffer } = lock;
const message = { webLocks: true, kind: 'create', name, mode, buffer };
locks.send(message);
}
const finished = lock.enter(handler);
let aborted = null;
if (signal) {
aborted = new Promise((resolve, reject) => {
signal.on('abort', reject);
});
await Promise.race([finished, aborted]);
} else {
await finished;
}
setTimeout(() => {
lock.tryEnter();
}, 0);
return undefined;
}
query() {
const snapshot = new LockManagerSnapshot();
return Promise.resolve(snapshot);
}
attach(worker) {
this.workers.add(worker);
worker.on('message', (message) => {
for (const peer of this.workers) {
if (peer !== worker) {
peer.postMessage(message);
}
}
this.receive(message);
});
}
send(message) {
if (isWorkerThread) {
parentPort.postMessage(message);
return;
}
for (const worker of this.workers) {
worker.postMessage(message);
}
}
receive(message) {
if (!message.webLocks) return;
const { kind, name, mode, buffer } = message;
if (kind === 'create') {
const lock = new Lock(name, mode, buffer);
this.collection.set(name, lock);
return;
}
if (kind === 'leave') {
for (const lock of this.collection.values()) {
if (lock.name === name && lock.trying) {
lock.tryEnter();
}
}
}
}
}
class AbortError extends Error {
constructor(message) {
super(message);
this.name = 'AbortError';
}
}
class AbortSignal extends EventEmitter {
constructor() {
super();
this.aborted = false;
this.on('abort', () => {
this.aborted = true;
});
}
}
class AbortController {
constructor() {
this.signal = new AbortSignal();
}
abort() {
const error = new AbortError('The request was aborted');
this.signal.emit('abort', error);
}
}
locks = new LockManager();
module.exports = { locks, AbortController };