-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathbasesocket.ts
More file actions
149 lines (124 loc) · 3.76 KB
/
Copy pathbasesocket.ts
File metadata and controls
149 lines (124 loc) · 3.76 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
import { BaseCollection, EventSpewer, Timers } from 'detritus-utils';
import {
SocketCloseCodes,
SocketEventsBase,
} from './constants';
export enum DependencyTypes {
UWS = 'uws',
WS = 'ws',
}
export const WebsocketDependency: {
module: any,
type: null | DependencyTypes,
} = {
module: null,
type: null,
};
[
DependencyTypes.WS,
DependencyTypes.UWS,
].forEach((dependency) => {
try {
WebsocketDependency.module = require(dependency);
WebsocketDependency.type = dependency;
} catch(e) {}
});
export class BaseSocket extends EventSpewer {
readonly pings = new BaseCollection<string, {
reject: Function,
resolve: Function,
}>();
socket: any;
constructor(url: string) {
super();
if (WebsocketDependency.module === null) {
throw new Error(`Missing a WebSocket Dependency, pick one: ${JSON.stringify(Object.values(DependencyTypes))}`)
}
this.socket = new WebsocketDependency.module(url);
this.socket.on(SocketEventsBase.CLOSE, this.onClose.bind(this));
this.socket.on(SocketEventsBase.PONG, this.onPong.bind(this));
this.socket.on(SocketEventsBase.ERROR, this.emit.bind(this, SocketEventsBase.ERROR));
this.socket.on(SocketEventsBase.MESSAGE, this.emit.bind(this, SocketEventsBase.MESSAGE));
this.socket.on(SocketEventsBase.OPEN, this.emit.bind(this, SocketEventsBase.OPEN));
this.socket.on(SocketEventsBase.PING, this.emit.bind(this, SocketEventsBase.PING));
}
get closed(): boolean {
return this.socket.readyState === this.socket.CLOSED;
}
get closing(): boolean {
return this.socket.readyState === this.socket.CLOSING;
}
get connected(): boolean {
return this.socket.readyState === this.socket.OPEN;
}
get connecting(): boolean {
return this.socket.readyState === this.socket.CONNECTING;
}
get using(): DependencyTypes {
if (!WebsocketDependency.type) {
throw new Error(`Missing a WebSocket Dependency, pick one: ${JSON.stringify(Object.values(DependencyTypes))}`);
}
return WebsocketDependency.type;
}
send(data: any, callback?: Function): void {
if (this.connected) {
this.socket.send(data, {}, callback);
}
}
close(code: number = SocketCloseCodes.NORMAL, reason: string = ''): void {
if (this.connected) {
this.socket.close(code, reason);
}
}
onClose(code: number, message: string): void {
for (const [nonce, {reject}] of this.pings) {
reject(new Error('Socket has closed.'));
this.pings.delete(nonce);
}
this.pings.clear();
this.socket.removeAllListeners();
this.emit(SocketEventsBase.CLOSE, code, message);
this.removeAllListeners();
}
onPong(data: any): void {
try {
const { nonce }: { nonce: string } = JSON.parse(String(data));
const ping = this.pings.get(nonce);
if (ping) {
ping.resolve();
this.pings.delete(nonce);
}
} catch(e) {
// malformed ping?
}
this.emit(SocketEventsBase.PONG, data);
}
async ping(
timeout: number = 1000,
): Promise<number> {
if (!this.connected) {
throw new Error('Socket isn\'t connected.');
}
const nonce = `${Date.now()}.${Math.random().toString(36)}`;
return new Promise((resolve, reject) => {
const expire = new Timers.Timeout();
if (timeout) {
expire.start(timeout, () => {
this.pings.delete(nonce);
reject(new Error(`Pong took longer than ${timeout}ms.`));
});
}
const now = Date.now();
new Promise((res, rej) => {
this.pings.set(nonce, {resolve: res, reject: rej});
this.socket.ping(JSON.stringify({nonce}));
}).then(() => {
expire.stop();
resolve(Math.round(Date.now() - now));
});
});
}
terminate() {
return this.socket.terminate();
}
}