Repository navigation
Expand file tree
/
Copy pathrealtime.ts
More file actions
111 lines (110 loc) · 3.23 KB
/
Copy pathrealtime.ts
File metadata and controls
111 lines (110 loc) · 3.23 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
type Message = { type: string; room?: string; [key: string]: any };
class Realtime {
socket: WebSocket | null = null;
private listeners = new Set<(message: Message) => void>();
private timer: ReturnType<typeof setTimeout> | undefined;
private refs = 0;
private retry = 0;
private sessionExpired = false;
private connectionFailed = false;
retain() {
if (++this.refs === 1) {
this.retry = 0;
this.sessionExpired = false;
this.connectionFailed = !navigator.onLine;
window.addEventListener("offline", this.offline);
window.addEventListener("online", this.online);
this.connect();
}
return () => {
if (--this.refs === 0) {
clearTimeout(this.timer);
this.closeSocket();
window.removeEventListener("offline", this.offline);
window.removeEventListener("online", this.online);
}
};
}
subscribe(fn: (message: Message) => void) {
this.listeners.add(fn);
return () => {
this.listeners.delete(fn);
};
}
private emit(m: Message) {
this.listeners.forEach((fn) => fn(m));
}
get connected() {
return navigator.onLine && this.socket?.readyState === WebSocket.OPEN;
}
get unavailable() {
return !navigator.onLine || this.connectionFailed;
}
send(m: Message) {
if (!this.connected) return false;
this.socket!.send(JSON.stringify(m));
return true;
}
private closeSocket() {
const ws = this.socket;
this.socket = null;
ws?.close();
}
private offline = () => {
clearTimeout(this.timer);
this.connectionFailed = true;
this.closeSocket();
this.emit({ type: "disconnected" });
};
private online = () => {
clearTimeout(this.timer);
this.retry = 0;
this.connect();
};
private connect() {
if (!this.refs || this.socket || this.sessionExpired || !navigator.onLine)
return;
const ws = new WebSocket(
`${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}/api/v1/ws`,
);
this.socket = ws;
ws.onmessage = (e) => {
if (this.socket !== ws) return;
try {
const m = JSON.parse(e.data);
if (m.type === "ready") {
this.retry = 0;
this.connectionFailed = false;
this.emit({ type: "connected" });
} else this.emit(m);
} catch {
this.emit({ type: "connection.error" });
}
};
ws.onclose = (e) => {
if (this.socket !== ws) return;
this.socket = null;
this.sessionExpired = e.code === 4401;
this.connectionFailed = !this.sessionExpired && e.code !== 4403;
this.emit({ type: "disconnected", code: e.code });
if (this.sessionExpired) {
window.dispatchEvent(new Event("session-expired"));
return;
}
if (this.refs && navigator.onLine && !this.socket)
this.timer = setTimeout(
() => this.connect(),
Math.min(15000, 1000 * 2 ** this.retry++) + Math.random() * 300,
);
};
ws.onerror = () => ws.close();
}
}
export const realtime = new Realtime();
export const toBase64 = (bytes: Uint8Array) => {
let s = "";
for (const b of bytes) s += String.fromCharCode(b);
return btoa(s);
};
export const fromBase64 = (s: string) =>
Uint8Array.from(atob(s), (c) => c.charCodeAt(0));