-
Notifications
You must be signed in to change notification settings - Fork 414
Expand file tree
/
Copy pathWsStreamClient.ts
More file actions
196 lines (175 loc) · 5.1 KB
/
Copy pathWsStreamClient.ts
File metadata and controls
196 lines (175 loc) · 5.1 KB
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
import IsomorphicWebSocket from "isomorphic-ws";
import { FrameMeta, StreamServerFrame, StreamStatus, Unsubscribe, WebSocketCtor, WebSocketLike } from "./types";
const DEFAULT_RECONNECT_BASE_MS = 500;
const DEFAULT_RECONNECT_MAX_MS = 10_000;
export type ChannelFrame = { data: unknown } & FrameMeta;
type ChannelListener = (frame: ChannelFrame) => void;
function resolveWebSocketCtor(injected?: WebSocketCtor): WebSocketCtor {
return injected ?? (IsomorphicWebSocket as unknown as WebSocketCtor);
}
export class WsStreamClient {
status: StreamStatus = "closed";
private ws?: WebSocketLike;
private readonly url: string;
private readonly WebSocketImpl: WebSocketCtor;
private readonly reconnectBaseMs: number;
private readonly reconnectMaxMs: number;
private readonly listeners = new Map<string, Set<ChannelListener>>();
private readonly statusListeners = new Set<(status: StreamStatus) => void>();
private reconnectDelay: number;
private reconnectTimer?: ReturnType<typeof setTimeout>;
private closedByUser = false;
constructor(params: {
url: string;
webSocketImpl?: WebSocketCtor;
reconnectBaseMs?: number;
reconnectMaxMs?: number;
}) {
this.url = params.url;
this.WebSocketImpl = resolveWebSocketCtor(params.webSocketImpl);
this.reconnectBaseMs = params.reconnectBaseMs ?? DEFAULT_RECONNECT_BASE_MS;
this.reconnectMaxMs = params.reconnectMaxMs ?? DEFAULT_RECONNECT_MAX_MS;
this.reconnectDelay = this.reconnectBaseMs;
}
subscribe(channel: string, listener: ChannelListener): Unsubscribe {
let set = this.listeners.get(channel);
if (!set) {
set = new Set();
this.listeners.set(channel, set);
}
set.add(listener);
this.ensureConnected();
if (this.status === "live") {
this.sendOp("subscribe", [channel]);
}
return () => {
const current = this.listeners.get(channel);
if (!current) {
return;
}
current.delete(listener);
if (current.size === 0) {
this.listeners.delete(channel);
if (this.status === "live") {
this.sendOp("unsubscribe", [channel]);
}
}
if (this.listeners.size === 0) {
this.close();
}
};
}
addStatusListener(listener: (status: StreamStatus) => void): Unsubscribe {
this.statusListeners.add(listener);
return () => {
this.statusListeners.delete(listener);
};
}
private ensureConnected() {
if (this.ws || this.reconnectTimer) {
return;
}
this.closedByUser = false;
this.connect();
}
private connect() {
this.setStatus(this.status === "closed" ? "connecting" : "reconnecting");
let ws: WebSocketLike;
try {
ws = new this.WebSocketImpl(this.url);
} catch {
this.scheduleReconnect();
return;
}
this.ws = ws;
ws.onopen = () => {
this.reconnectDelay = this.reconnectBaseMs;
this.setStatus("live");
const channels = [...this.listeners.keys()];
if (channels.length) {
this.sendOp("subscribe", channels);
}
};
ws.onmessage = (ev) => this.onMessage(ev.data);
ws.onclose = () => this.onClose();
ws.onerror = () => {
// a close event always follows; reconnection is handled there
};
}
private onMessage(raw: unknown) {
const text = typeof raw === "string" ? raw : String(raw);
let frame: StreamServerFrame;
try {
frame = JSON.parse(text);
} catch {
return;
}
if ("op" in frame || frame.type !== "snapshot") {
return;
}
if (frame.data === undefined) {
return;
}
const set = this.listeners.get(frame.ch);
if (!set) {
return;
}
const payload: ChannelFrame = {
data: frame.data,
serverTs: frame.serverTs,
originTs: frame.originTs,
receivedAt: Date.now(),
byteLength: text.length,
};
for (const listener of set) {
listener(payload);
}
}
private onClose() {
this.ws = undefined;
if (this.closedByUser || this.listeners.size === 0) {
this.setStatus("closed");
return;
}
this.scheduleReconnect();
}
private scheduleReconnect() {
this.setStatus("reconnecting");
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = undefined;
this.connect();
}, this.reconnectDelay);
this.reconnectDelay = Math.min(this.reconnectDelay * 2, this.reconnectMaxMs);
}
private sendOp(op: "subscribe" | "unsubscribe", channels: string[]) {
try {
this.ws?.send(JSON.stringify({ op, channels }));
} catch {
// socket raced into a non-open state; resubscribe runs on reconnect
}
}
private setStatus(status: StreamStatus) {
if (this.status === status) {
return;
}
this.status = status;
for (const listener of this.statusListeners) {
listener(status);
}
}
close() {
this.closedByUser = true;
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = undefined;
}
this.listeners.clear();
try {
this.ws?.close();
} catch {
// already closing
}
this.ws = undefined;
this.setStatus("closed");
}
}