-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWaitHandleClient.ts
91 lines (71 loc) · 2.22 KB
/
WaitHandleClient.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
import { WebSocket } from 'ws';
interface WaitHandleIncomingMessage {
action: 'released';
id: string;
}
interface WaitHandleOutgoingMessage {
action: 'wait' | 'release';
id: string;
}
export class WaitHandleClient {
private socketConnection: WebSocket;
private resolveCollection: Map<string, (() => void)[]>;
constructor(url: string) {
this.socketConnection = new WebSocket(url);
this.resolveCollection = new Map();
this.socketConnection.on('open', () => {
this.socketConnection.on('message', (data: Buffer | Buffer[]) => {
const incomingMessage = JSON.parse(
data.toString()
) as WaitHandleIncomingMessage;
if (incomingMessage.action === 'released') {
const { id } = incomingMessage;
if (!this.resolveCollection.has(id)) {
return;
}
const resolves = this.resolveCollection.get(id)!;
for (const resolve of resolves) {
resolve();
}
this.resolveCollection.delete(id);
}
});
});
}
private async waitForConnection() {
if (this.socketConnection.readyState === WebSocket.OPEN) {
return;
}
await new Promise<void>((resolve, _reject) => {
// typescript doesn't let me to pass only the resolve
// because it doesn't accept event arg
this.socketConnection.addEventListener('open', () => resolve());
});
}
public async wait(id: string): Promise<void> {
await this.waitForConnection();
return new Promise((resolve, _reject) => {
const outgoingMessage = {
action: 'wait',
id,
} as WaitHandleOutgoingMessage;
this.socketConnection.send(JSON.stringify(outgoingMessage));
if (this.resolveCollection.has(id)) {
this.resolveCollection.get(id)!.push(resolve);
} else {
this.resolveCollection.set(id, [resolve]);
}
});
}
public async release(id: string): Promise<void> {
await this.waitForConnection();
return new Promise((resolve, _reject) => {
const outgoingMessage = {
action: 'release',
id,
} as WaitHandleOutgoingMessage;
this.socketConnection.send(JSON.stringify(outgoingMessage));
resolve();
});
}
}