-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
xpmutex.ts
218 lines (190 loc) · 6.45 KB
/
xpmutex.ts
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import { watch, promises as fs, mkdirSync } from 'fs';
import * as os from 'os';
import * as path from 'path';
export class XpMutexPool {
public static fromDirectory(directory: string) {
mkdirSync(directory, { recursive: true });
return new XpMutexPool(directory);
}
public static fromName(name: string) {
return XpMutexPool.fromDirectory(path.join(os.tmpdir(), name));
}
private readonly waitingResolvers = new Set<() => void>();
private watcher: ReturnType<typeof watch> | undefined;
private constructor(public readonly directory: string) {
this.startWatch();
}
public mutex(name: string) {
return new XpMutex(this, name);
}
/**
* Await an unlock event
*
* (An unlock event is when a file in the directory gets deleted, with a tiny
* random sleep attached to it).
*/
public awaitUnlock(maxWaitMs?: number): Promise<void> {
const wait = new Promise<void>(ok => {
this.waitingResolvers.add(async () => {
await randomSleep(10);
ok();
});
});
if (maxWaitMs) {
return Promise.race([wait, sleep(maxWaitMs)]);
} else {
return wait;
}
}
private startWatch() {
this.watcher = watch(this.directory);
(this.watcher as any).unref(); // @types doesn't know about this but it exists
this.watcher.on('change', async (eventType, fname) => {
// Only trigger on 'deletes'.
// After receiving the event, we check if the file exists.
// - If no: the file was deleted! Huzzah, this counts as a wakeup.
// - If yes: either the file was just created (in which case we don't need to wakeup)
// or the event was due to a delete but someone raced us to it and claimed the
// file already (in which case we also don't need to wake up).
if (eventType === 'rename' && !await fileExists(path.join(this.directory, fname.toString()))) {
this.notifyWaiters();
}
});
this.watcher.on('error', async (e) => {
// eslint-disable-next-line no-console
console.error(e);
await randomSleep(100);
this.startWatch();
});
}
private notifyWaiters() {
for (const promise of this.waitingResolvers) {
promise();
}
this.waitingResolvers.clear();
}
}
/**
* Cross-process mutex
*
* Uses the presence of a file on disk and `fs.watch` to represent the mutex
* and discover unlocks.
*/
export class XpMutex {
private readonly fileName: string;
constructor(private readonly pool: XpMutexPool, public readonly mutexName: string) {
this.fileName = path.join(pool.directory, `${mutexName}.mutex`);
}
/**
* Try to acquire the lock (may fail)
*/
public async tryAcquire(): Promise<ILock | undefined> {
while (true) {
// Acquire lock by being the one to create the file
try {
return await this.writePidFile('wx'); // Fails if the file already exists
} catch (e) {
if (e.code !== 'EEXIST') { throw e; }
}
// File already exists. Read the contents, see if it's an existent PID (if so, the lock is taken)
const ownerPid = await this.readPidFile();
if (ownerPid === undefined) {
// File got deleted just now, maybe we can acquire it again
continue;
}
if (processExists(ownerPid)) {
return undefined;
}
// If not, the lock is stale and will never be released anymore. We may
// delete it and acquire it anyway, but we may be racing someone else trying
// to do the same. Solve this as follows:
// - Try to acquire a lock that gives us permissions to declare the existing lock stale.
// - Sleep a small random period to reduce contention on this operation
await randomSleep(10);
const innerMux = new XpMutex(this.pool, `${this.mutexName}.${ownerPid}`);
const innerLock = await innerMux.tryAcquire();
if (!innerLock) {
return undefined;
}
// We may not release the 'inner lock' we used to acquire the rights to declare the other
// lock stale until we release the actual lock itself. If we did, other contenders might
// see it released while they're still in this fallback block and accidentally steal
// from a new legitimate owner.
return this.writePidFile('w', innerLock); // Force write lock file, attach inner lock as well
}
}
/**
* Acquire the lock, waiting until we can
*/
public async acquire(): Promise<ILock> {
while (true) {
// Start the wait here, so we don't miss the signal if it comes after
// we try but before we sleep.
//
// We also periodically retry anyway since we may have missed the delete
// signal due to unfortunate timing.
const wait = this.pool.awaitUnlock(5000);
const lock = await this.tryAcquire();
if (lock) {
// Ignore the wait (count as handled)
wait.then(() => {}, () => {});
return lock;
}
await wait;
await randomSleep(100);
}
}
private async readPidFile(): Promise<number | undefined> {
const deadLine = Date.now() + 1000;
while (Date.now() < deadLine) {
let contents;
try {
contents = await fs.readFile(this.fileName, { encoding: 'utf-8' });
} catch (e) {
if (e.code === 'ENOENT') { return undefined; }
throw e;
}
// Retry until we've seen the full contents
if (contents.endsWith('.')) { return parseInt(contents.substring(0, contents.length - 1), 10); }
await sleep(10);
}
throw new Error(`${this.fileName} was never completely written`);
}
private async writePidFile(mode: string, additionalLock?: ILock): Promise<ILock> {
const fd = await fs.open(this.fileName, mode); // May fail if the file already exists
await fd.write(`${process.pid}.`); // Period guards against partial reads
await fd.close();
return {
release: async () => {
await fs.unlink(this.fileName);
await additionalLock?.release();
},
};
}
}
export interface ILock {
release(): Promise<void>;
}
async function fileExists(fileName: string) {
try {
await fs.stat(fileName);
return true;
} catch (e) {
if (e.code === 'ENOENT') { return false; }
throw e;
}
}
function processExists(pid: number) {
try {
process.kill(pid, 0);
return true;
} catch (e) {
return false;
}
}
function sleep(ms: number): Promise<void> {
return new Promise(ok => (setTimeout(ok, ms) as any).unref());
}
function randomSleep(ms: number) {
return sleep(Math.floor(Math.random() * ms));
}