-
Notifications
You must be signed in to change notification settings - Fork 217
/
index.js
260 lines (226 loc) · 7.1 KB
/
index.js
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
'use strict';
const EventEmitter = require('events').EventEmitter;
const { getUserAgent } = require('..');
const MAX_RECONNECT_ATTEMPTS = 5;
const RECONNECT_INTERVAL_MS = 50;
const WS_CLOSE_NORMAL = 1000;
const toplevel = global.window || global;
const WebSocket = toplevel.WebSocket ? toplevel.WebSocket : require('ws');
/**
* Publish events to the Insights gateway.
* @extends EventEmitter
* @emits InsightsPublisher#connected
* @emits InsightsPublisher#disconnected
* @emits InsightsPublisher#reconnecting
*/
class InsightsPublisher extends EventEmitter {
/**
* @param {string} token - Insights gateway token
* @param {string} sdkName - Name of the SDK using the {@link InsightsPublisher}
* @param {string} sdkVersion - Version of the SDK using the {@link InsightsPublisher}
* @param {string} environment - One of 'dev', 'stage' or 'prod'
* @param {string} realm - Region identifier
* @param {InsightsPublisherOptions} options - Override default behavior
*/
constructor(token, sdkName, sdkVersion, environment, realm, options) {
super();
options = Object.assign({
gateway: `${createGateway(environment, realm)}/v1/VideoEvents`,
maxReconnectAttempts: MAX_RECONNECT_ATTEMPTS,
reconnectIntervalMs: RECONNECT_INTERVAL_MS,
userAgent: getUserAgent(),
WebSocket
}, options);
Object.defineProperties(this, {
_connectTimestamp: {
value: 0,
writable: true
},
_eventQueue: {
value: []
},
_reconnectAttemptsLeft: {
value: options.maxReconnectAttempts,
writable: true
},
_ws: {
value: null,
writable: true
},
_WebSocket: {
value: options.WebSocket
}
});
const self = this;
this.on('disconnected', function maybeReconnect(error) {
self._session = null;
if (error && self._reconnectAttemptsLeft > 0) {
self.emit('reconnecting');
reconnect(self, token, sdkName, sdkVersion, options);
return;
}
self.removeListener('disconnected', maybeReconnect);
});
connect(this, token, sdkName, sdkVersion, options);
}
/**
* Publish an event to the Insights gateway.
* @private
* @param {*} event
*/
_publish(event) {
event.session = this._session;
this._ws.send(JSON.stringify(event));
}
/**
* Disconnect from the Insights gateway.
* @returns {boolean} true if called when connecting/open, false if not
*/
disconnect() {
if (this._ws.readyState === this._WebSocket.CLOSING || this._ws.readyState === this._WebSocket.CLOSED) {
return false;
}
try {
this._ws.close();
} catch (error) {
// Do nothing.
}
this.emit('disconnected');
return true;
}
/**
* Publish (or queue, if not connected) an event to the Insights gateway.
* @param {string} groupName - Event group name
* @param {string} eventName - Event name
* @param {object} payload - Event payload
* @returns {boolean} true if queued or published, false if disconnect() called
*/
publish(groupName, eventName, payload) {
if (this._ws.readyState === this._WebSocket.CLOSING || this._ws.readyState === this._WebSocket.CLOSED) {
return false;
}
const publishOrEnqueue = typeof this._session === 'string'
? this._publish.bind(this)
: this._eventQueue.push.bind(this._eventQueue);
publishOrEnqueue({
group: groupName,
name: eventName,
payload,
timestamp: Date.now(),
type: 'event',
version: 1
});
return true;
}
}
/**
* Start connecting to the Insights gateway.
* @private
* @param {InsightsPublisher} publisher
* @param {string} name
* @param {string} token
* @param {string} sdkName
* @param {string} sdkVersion
* @param {InsightsPublisherOptions} options
*/
function connect(publisher, token, sdkName, sdkVersion, options) {
publisher._connectTimestamp = Date.now();
publisher._reconnectAttemptsLeft--;
publisher._ws = new options.WebSocket(options.gateway);
const ws = publisher._ws;
ws.addEventListener('close', event => {
if (event.code === WS_CLOSE_NORMAL) {
publisher.emit('disconnected');
return;
}
publisher.emit('disconnected', new Error(`WebSocket Error ${event.code}: ${event.reason}`));
});
ws.addEventListener('message', message => {
handleConnectResponse(publisher, JSON.parse(message.data), options);
});
ws.addEventListener('open', () => {
const connectRequest = {
type: 'connect',
token,
version: 1
};
connectRequest.publisher = {
name: sdkName,
sdkVersion,
userAgent: options.userAgent
};
ws.send(JSON.stringify(connectRequest));
});
}
/**
* Create the Insights Websocket gateway URL.
* @param {string} environment
* @param {string} realm
* @returns {string}
*/
function createGateway(environment, realm) {
return environment === 'prod' ? `wss://sdkgw.${realm}.twilio.com`
: `wss://sdkgw.${environment}-${realm}.twilio.com`;
}
/**
* Handle connect response from the Insights gateway.
* @param {InsightsPublisher} publisher
* @param {*} response
* @param {InsightsPublisherOptions} options
*/
function handleConnectResponse(publisher, response, options) {
switch (response.type) {
case 'connected':
publisher._session = response.session;
publisher._reconnectAttemptsLeft = options.maxReconnectAttempts;
publisher._eventQueue.splice(0).forEach(publisher._publish, publisher);
publisher.emit('connected');
break;
case 'error':
publisher._ws.close();
publisher.emit('disconnected', new Error(response.message));
break;
}
}
/**
* Start re-connecting to the Insights gateway with an appropriate delay based
* on InsightsPublisherOptions#reconnectIntervalMs.
* @private
* @param {InsightsPublisher} publisher
* @param {string} token
* @param {string} sdkName
* @param {string} sdkVersion
* @param {InsightsPublisherOptions} options
*/
function reconnect(publisher, token, sdkName, sdkVersion, options) {
const connectInterval = Date.now() - publisher._connectTimestamp;
const timeToWait = options.reconnectIntervalMs - connectInterval;
if (timeToWait > 0) {
setTimeout(() => {
connect(publisher, token, sdkName, sdkVersion, options);
}, timeToWait);
return;
}
connect(publisher, token, sdkName, sdkVersion, options);
}
/**
* The {@link InsightsPublisher} is connected to the gateway.
* @event InsightsPublisher#connected
*/
/**
* The {@link InsightsPublisher} is disconnected from the gateway.
* @event InsightsPublisher#disconnected
* @param {Error} [error] - Optional error if disconnected unintentionally
*/
/**
* The {@link InsightsPublisher} is re-connecting to the gateway.
* @event InsightsPublisher#reconnecting
*/
/**
* {@link InsightsPublisher} options.
* @typedef {object} InsightsPublisherOptions
* @property {string} [gateway=sdkgw.{environment}-{realm}.twilio.com] - Insights WebSocket gateway url
* @property {number} [maxReconnectAttempts=5] - Max re-connect attempts
* @property {number} [reconnectIntervalMs=50] - Re-connect interval in ms
*/
module.exports = InsightsPublisher;