-
Notifications
You must be signed in to change notification settings - Fork 39
/
WebSocketHandler.ts
195 lines (162 loc) · 4.74 KB
/
WebSocketHandler.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
import http from 'http';
import ws from 'ws';
import { formatError } from '../../Utils';
import Service from '../../service/Service';
import Controller from '../Controller';
enum Operation {
// TODO: unsubscribe
Subscribe = 'subscribe',
Update = 'update',
}
enum SubscriptionChannel {
SwapUpdate = 'swap.update',
}
type WsRequest = {
op: Operation;
};
type WsSubscribeRequest = WsRequest & {
channel: SubscriptionChannel;
args: string[];
};
type WsResponse = {
event: Operation;
};
type WsErrorResponse = {
error: string;
};
class WebSocketHandler {
private static readonly pingIntervalMs = 15_000;
private readonly ws: ws.Server;
private pingInterval?: NodeJS.Timer;
private readonly swapToSockets = new Map<string, ws[]>();
private readonly socketToSwaps = new Map<ws, string[]>();
constructor(
private readonly service: Service,
private readonly controller: Controller,
) {
this.ws = new ws.Server({
noServer: true,
});
this.listenConnections();
this.listenSwapUpdates();
}
public register = (server: http.Server) => {
server.on('upgrade', (request, socket, head) => {
this.ws.handleUpgrade(request, socket, head, (ws) => {
this.ws.emit('connection', ws, request);
});
});
this.pingInterval = setInterval(() => {
this.ws.clients.forEach((ws) => ws.ping());
}, WebSocketHandler.pingIntervalMs);
};
public close = () => {
this.ws.close();
clearInterval(this.pingInterval);
};
private listenConnections = () => {
this.ws.on('connection', (socket) => {
socket.on('message', (msg) => this.handleMessage(socket, msg));
socket.on('close', () => {
const ids = this.socketToSwaps.get(socket);
if (ids === undefined) {
return;
}
this.socketToSwaps.delete(socket);
for (const id of ids) {
const sockets = this.swapToSockets
.get(id)
?.filter((s) => s !== socket);
if (sockets === undefined || sockets.length === 0) {
this.swapToSockets.delete(id);
continue;
}
this.swapToSockets.set(id, sockets);
}
});
});
};
private handleMessage = (socket: ws, message: ws.RawData) => {
try {
const data = JSON.parse(message.toString('utf-8')) as WsRequest;
switch (data.op) {
case Operation.Subscribe:
this.handleSubscribe(socket, data);
break;
default:
this.sendToSocket(socket, { error: 'unknown operation' });
break;
}
} catch (e) {
this.sendToSocket(socket, {
error: `could not parse message: ${formatError(e)}`,
});
}
};
private handleSubscribe = (socket: ws, data: WsRequest) => {
const subscribeData = data as WsSubscribeRequest;
switch (subscribeData.channel) {
case SubscriptionChannel.SwapUpdate: {
const existingIds = this.socketToSwaps.get(socket) || [];
this.socketToSwaps.set(
socket,
existingIds.concat(
subscribeData.args.filter((id) => !existingIds.includes(id)),
),
);
for (const id of subscribeData.args) {
const existingSockets = this.swapToSockets.get(id) || [];
if (existingSockets.includes(socket)) {
continue;
}
this.swapToSockets.set(id, existingSockets.concat(socket));
}
break;
}
default:
this.sendToSocket(socket, { error: 'unknown channel' });
return;
}
this.sendToSocket(socket, {
event: Operation.Subscribe,
channel: subscribeData.channel,
args: subscribeData.args,
});
if (subscribeData.channel === SubscriptionChannel.SwapUpdate) {
const args = subscribeData.args
.map((id) => [id, this.controller.pendingSwapInfos.get(id)])
.filter(([, data]) => data !== undefined);
this.sendToSocket(socket, {
event: Operation.Update,
channel: SubscriptionChannel.SwapUpdate,
args: args,
});
}
};
private listenSwapUpdates = () => {
this.service.eventHandler.on('swap.update', ({ id, status }) => {
const sockets = this.swapToSockets.get(id);
if (sockets === undefined) {
return;
}
for (const socket of sockets) {
this.sendToSocket(socket, {
event: Operation.Update,
channel: SubscriptionChannel.SwapUpdate,
args: [[id, status]],
});
}
});
};
private sendToSocket = <T extends WsResponse>(
socket: ws,
msg: T | WsErrorResponse,
) => {
if (socket.readyState !== socket.OPEN) {
return;
}
socket.send(JSON.stringify(msg));
};
}
export default WebSocketHandler;
export { Operation, SubscriptionChannel };