forked from binary-com/binary-static
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket_base.js
More file actions
296 lines (261 loc) · 10.1 KB
/
socket_base.js
File metadata and controls
296 lines (261 loc) · 10.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
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
const ClientBase = require('./client_base');
const SocketCache = require('./socket_cache');
const getLanguage = require('../language').get;
const State = require('../storage').State;
const cloneObject = require('../utility').cloneObject;
const getPropertyValue = require('../utility').getPropertyValue;
const isEmptyObject = require('../utility').isEmptyObject;
const PromiseClass = require('../utility').PromiseClass;
const getAppId = require('../../config').getAppId;
const getSocketURL = require('../../config').getSocketURL;
/*
* An abstraction layer over native javascript WebSocket,
* which provides additional functionality like
* reopen the closed connection and process the buffered requests
*/
const BinarySocketBase = (() => {
let binary_socket;
let config = {};
let buffered_sends = [];
let req_id = 0;
let wrong_app_id = 0;
let is_available = true;
let is_disconnect_called = false;
const socket_url = `${getSocketURL()}?app_id=${getAppId()}&l=${getLanguage()}`;
const timeouts = {};
const promises = {};
const no_duplicate_requests = [
'authorize',
'get_settings',
'residence_list',
'landing_company',
'payout_currencies',
'asset_index',
];
const sent_requests = {
items : [],
clear : () => { sent_requests.items = []; },
has : msg_type => sent_requests.items.indexOf(msg_type) >= 0,
add : (msg_type) => { if (!sent_requests.has(msg_type)) sent_requests.items.push(msg_type); },
remove: (msg_type) => {
if (sent_requests.has(msg_type)) sent_requests.items.splice(sent_requests.items.indexOf(msg_type, 1));
},
};
const waiting_list = {
items: {},
add : (msg_type, promise_obj) => {
if (!waiting_list.items[msg_type]) {
waiting_list.items[msg_type] = [];
}
waiting_list.items[msg_type].push(promise_obj);
},
resolve: (response) => {
const msg_type = response.msg_type;
const this_promises = waiting_list.items[msg_type];
if (this_promises && this_promises.length) {
this_promises.forEach((pr) => {
if (!waiting_list.another_exists(pr, msg_type)) {
pr.resolve(response);
}
});
waiting_list.items[msg_type] = [];
}
},
another_exists: (pr, msg_type) => (
Object.keys(waiting_list.items)
.some(type => (
type !== msg_type &&
waiting_list.items[type].indexOf(pr) !== -1
))
),
};
const clearTimeouts = () => {
Object.keys(timeouts).forEach((key) => {
clearTimeout(timeouts[key]);
delete timeouts[key];
});
};
const isReady = () => hasReadyState(1);
const isClose = () => !binary_socket || hasReadyState(2, 3);
const hasReadyState = (...states) => binary_socket && states.some(s => binary_socket.readyState === s);
const sendBufferedRequests = () => {
while (buffered_sends.length > 0 && is_available) {
const req_obj = buffered_sends.shift();
send(req_obj.request, req_obj.options);
}
};
const wait = (...msg_types) => {
const promise_obj = new PromiseClass();
let is_resolved = true;
msg_types.forEach((msg_type) => {
const last_response = State.get(['response', msg_type]);
if (!last_response) {
if (msg_type !== 'authorize' || ClientBase.isLoggedIn()) {
waiting_list.add(msg_type, promise_obj);
is_resolved = false;
}
} else if (msg_types.length === 1) {
promise_obj.resolve(last_response);
}
});
if (is_resolved) {
promise_obj.resolve();
}
return promise_obj.promise;
};
/**
* @param {Object} data: request object
* @param {Object} options:
* forced : {boolean} sends the request regardless the same msg_type has been sent before
* msg_type: {string} specify the type of request call
* callback: {function} to call on response of streaming requests
*/
const send = function (data, options = {}) {
const promise_obj = options.promise || new PromiseClass();
if (!data || isEmptyObject(data)) return promise_obj.promise;
const msg_type = options.msg_type || no_duplicate_requests.find(c => c in data);
// Fetch from cache
if (!options.forced) {
const response = SocketCache.get(data, msg_type);
if (response) {
State.set(['response', msg_type], cloneObject(response));
if (isReady() && is_available) { // make the request to keep the cache updated
binary_socket.send(JSON.stringify(data));
}
promise_obj.resolve(response);
return promise_obj.promise;
}
}
// Fetch from state
if (!options.forced && msg_type && no_duplicate_requests.indexOf(msg_type) !== -1) {
const last_response = State.get(['response', msg_type]);
if (last_response) {
promise_obj.resolve(last_response);
return promise_obj.promise;
} else if (sent_requests.has(msg_type)) {
return wait(msg_type).then((response) => {
promise_obj.resolve(response);
return promise_obj.promise;
});
}
}
if (!data.req_id) {
data.req_id = ++req_id;
}
promises[data.req_id] = {
callback: (response) => {
if (typeof options.callback === 'function') {
options.callback(response);
} else {
promise_obj.resolve(response);
}
},
subscribe: !!data.subscribe,
};
if (isReady() && is_available && config.isOnline()) {
is_disconnect_called = false;
if (!getPropertyValue(data, 'passthrough') && !getPropertyValue(data, 'verify_email')) {
data.passthrough = {};
}
binary_socket.send(JSON.stringify(data));
config.wsEvent('send');
if (msg_type && !sent_requests.has(msg_type)) {
sent_requests.add(msg_type);
}
} else if (+data.time !== 1) { // Do not buffer all time requests
buffered_sends.push({ request: data, options: Object.assign(options, { promise: promise_obj }) });
}
return promise_obj.promise;
};
const init = (options) => {
if (wrong_app_id === getAppId()) {
return;
}
if (typeof options === 'object' && config !== options) {
config = options;
buffered_sends = [];
}
clearTimeouts();
config.wsEvent('init');
if (isClose()) {
binary_socket = new WebSocket(socket_url);
State.set('response', {});
}
binary_socket.onopen = () => {
config.wsEvent('open');
if (ClientBase.isLoggedIn()) {
send({ authorize: ClientBase.get('token') }, { forced: true });
} else {
sendBufferedRequests();
}
if (typeof config.onOpen === 'function') {
config.onOpen(isReady());
}
};
binary_socket.onmessage = (msg) => {
config.wsEvent('message');
const response = msg.data ? JSON.parse(msg.data) : undefined;
if (response) {
SocketCache.set(response);
const msg_type = response.msg_type;
// store in State
if (!getPropertyValue(response, ['echo_req', 'subscribe']) || /balance|website_status/.test(msg_type)) {
State.set(['response', msg_type], cloneObject(response));
}
// resolve the send promise
const this_req_id = response.req_id;
const pr = this_req_id ? promises[this_req_id] : null;
if (pr && typeof pr.callback === 'function') {
pr.callback(response);
if (!pr.subscribe) {
delete promises[this_req_id];
}
}
// resolve the wait promise
waiting_list.resolve(response);
if (getPropertyValue(response, ['error', 'code']) === 'InvalidAppID') {
wrong_app_id = getAppId();
}
if (typeof config.onMessage === 'function') {
config.onMessage(response);
}
}
};
binary_socket.onclose = () => {
sent_requests.clear();
clearTimeouts();
config.wsEvent('close');
if (wrong_app_id !== getAppId() && typeof config.onDisconnect === 'function' && !is_disconnect_called) {
config.onDisconnect();
is_disconnect_called = true;
}
};
};
const clear = (msg_type) => {
buffered_sends = [];
if (msg_type) {
State.set(['response', msg_type], undefined);
sent_requests.remove(msg_type);
}
};
const availability = (status) => {
if (typeof status !== 'undefined') {
is_available = !!status;
}
return is_available;
};
return {
init,
wait,
send,
clear,
clearTimeouts,
availability,
hasReadyState,
sendBuffered : sendBufferedRequests,
get : () => binary_socket,
setOnDisconnect : (onDisconnect) => { config.onDisconnect = onDisconnect; },
removeOnDisconnect: () => { delete config.onDisconnect; },
};
})();
module.exports = BinarySocketBase;