-
Notifications
You must be signed in to change notification settings - Fork 0
/
glue.js
1357 lines (1125 loc) · 32.9 KB
/
glue.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
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Glue - Robust Go and Javascript Socket Library
* Copyright (C) 2015 Roland Singer <roland.singer[at]desertbit.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
var glue = function (host, options) {
// Turn on strict mode.
'use strict'
// Include the dependencies.
function Emitter (obj) {
if (obj) return mixin(obj)
}
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin (obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key]
}
return obj
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on = Emitter.prototype.addEventListener = function (
event,
fn
) {
this._callbacks = this._callbacks || {}
;(this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(
fn
)
return this
}
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function (event, fn) {
function on () {
this.off(event, on)
fn.apply(this, arguments)
}
on.fn = fn
this.on(event, on)
return this
}
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (
event,
fn
) {
this._callbacks = this._callbacks || {}
// all
if (arguments.length === 0) {
this._callbacks = {}
return this
}
// specific event
var callbacks = this._callbacks['$' + event]
if (!callbacks) return this
// remove all handlers
if (arguments.length === 1) {
delete this._callbacks['$' + event]
return this
}
// remove specific handler
var cb
for (var i = 0; i < callbacks.length; i++) {
cb = callbacks[i]
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1)
break
}
}
return this
}
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function (event) {
this._callbacks = this._callbacks || {}
var args = [].slice.call(arguments, 1)
var callbacks = this._callbacks['$' + event]
if (callbacks) {
callbacks = callbacks.slice(0)
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args)
}
}
return this
}
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function (event) {
this._callbacks = this._callbacks || {}
return this._callbacks['$' + event] || []
}
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function (event) {
return !!this.listeners(event).length
}
var newWebSocket = function () {
/*
* Variables
*/
var s = {}
var ws
/*
* Socket layer implementation.
*/
s.open = function () {
try {
// Generate the websocket url.
var url
if (host.match('^https://')) {
url = 'wss' + host.substr(5)
} else {
url = 'ws' + host.substr(4)
}
url += options.baseURL + 'ws'
// Open the websocket connection
ws = new WebSocket(url) // eslint-disable-line
// Set the callback handlers
ws.onmessage = function (event) {
s.onMessage(event.data.toString())
}
ws.onerror = function (event) {
var msg = 'the websocket closed the connection with '
if (event.code) {
msg += 'the error code: ' + event.code
} else {
msg += 'an error.'
}
s.onError(msg)
}
ws.onclose = function () {
s.onClose()
}
ws.onopen = function () {
s.onOpen()
}
} catch (e) {
s.onError()
}
}
s.send = function (data) {
// Send the data to the server
ws.send(data)
}
s.reset = function () {
// Close the websocket if defined.
if (ws) {
ws.close()
}
ws = undefined
}
return s
}
var newAjaxSocket = function () {
/*
* Constants
*/
var ajaxHost = host + options.baseURL + 'ajax'
var sendTimeout = 8000
var pollTimeout = 45000
var PollCommands = {
Timeout: 't',
Closed: 'c'
}
var Commands = {
Delimiter: '&',
Init: 'i',
Push: 'u',
Poll: 'o'
}
/*
* Variables
*/
var s = {}
var uid
var pollToken
var pollXhr = false
var sendXhr = false
var poll
/*
* Methods
*/
var stopRequests = function () {
// Set the poll function to a dummy function.
// This will prevent further poll calls.
poll = function () {}
// Kill the ajax requests.
if (pollXhr) {
pollXhr.abort()
}
if (sendXhr) {
sendXhr.abort()
}
}
var postAjax = function (url, timeout, data, success, error) {
// eslint-disable-next-line
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP')
xhr.onload = function () {
success(xhr.response)
}
xhr.onerror = function () {
error()
}
xhr.ontimeout = function () {
error('timeout')
}
xhr.open('POST', url, true)
xhr.responseType = 'text'
xhr.timeout = timeout
xhr.send(data)
return xhr
}
var triggerClosed = function () {
// Stop the ajax requests.
stopRequests()
// Trigger the event.
s.onClose()
}
var triggerError = function (msg) {
// Stop the ajax requests.
stopRequests()
// Create the error message.
if (msg) {
msg = 'the ajax socket closed the connection with the error: ' + msg
} else {
msg = 'the ajax socket closed the connection with an error.'
}
// Trigger the event.
s.onError(msg)
}
var send = function (data, callback) {
sendXhr = postAjax(
ajaxHost,
sendTimeout,
data,
function (data) {
sendXhr = false
if (callback) {
callback(data)
}
},
function (msg) {
sendXhr = false
triggerError(msg)
}
)
}
poll = function () {
var data = Commands.Poll + uid + Commands.Delimiter + pollToken
pollXhr = postAjax(
ajaxHost,
pollTimeout,
data,
function (data) {
pollXhr = false
// Check if this jax request has reached the server's timeout.
if (data === PollCommands.Timeout) {
// Just start the next poll request.
poll()
return
}
// Check if this ajax connection was closed.
if (data === PollCommands.Closed) {
// Trigger the closed event.
triggerClosed()
return
}
// Split the new token from the rest of the data.
var i = data.indexOf(Commands.Delimiter)
if (i < 0) {
triggerError('ajax socket: failed to split poll token from data!')
return
}
// Set the new token and the data variable.
pollToken = data.substring(0, i)
data = data.substr(i + 1)
// Start the next poll request.
poll()
// Call the event.
s.onMessage(data)
},
function (msg) {
pollXhr = false
triggerError(msg)
}
)
}
/*
* Socket layer implementation.
*/
s.open = function () {
// Initialize the ajax socket session
send(Commands.Init, function (data) {
// Get the uid and token string
var i = data.indexOf(Commands.Delimiter)
if (i < 0) {
triggerError(
'ajax socket: failed to split uid and poll token from data!'
)
return
}
// Set the uid and token.
uid = data.substring(0, i)
pollToken = data.substr(i + 1)
// Start the long polling process.
poll()
// Trigger the event.
s.onOpen()
})
}
s.send = function (data) {
// Always prepend the command with the uid to the data.
send(Commands.Push + uid + Commands.Delimiter + data)
}
s.reset = function () {
// Stop the ajax requests.
stopRequests()
}
return s
}
/*
* Constants
*/
var Version = '1.9.1'
var MainChannelName = 'm'
var SocketTypes = {
WebSocket: 'WebSocket',
AjaxSocket: 'AjaxSocket'
}
var Commands = {
Len: 2,
Init: 'in',
Ping: 'pi',
Pong: 'po',
Close: 'cl',
Invalid: 'iv',
DontAutoReconnect: 'dr',
ChannelData: 'cd'
}
var States = {
Disconnected: 'disconnected',
Connecting: 'connecting',
Reconnecting: 'reconnecting',
Connected: 'connected'
}
var DefaultOptions = {
// The base URL is appended to the host string. This value has to match with the server value.
baseURL: '/glue/',
// Force a socket type.
// Values: false, "WebSocket", "AjaxSocket"
forceSocketType: false,
// Kill the connect attempt after the timeout.
connectTimeout: 10000,
// If the connection is idle, ping the server to check if the connection is stil alive.
pingInterval: 35000,
// Reconnect if the server did not response with a pong within the timeout.
pingReconnectTimeout: 5000,
// Whenever to automatically reconnect if the connection was lost.
reconnect: true,
reconnectDelay: 1000,
reconnectDelayMax: 5000,
// To disable set to 0 (endless).
reconnectAttempts: 10,
// Reset the send buffer after the timeout.
resetSendBufferTimeout: 10000
}
/*
* Variables
*/
var emitter = new Emitter()
var bs = false
var mainChannel
var initialConnectedOnce = false // If at least one successful connection was made.
var bsNewFunc // Function to create a new backend socket.
var currentSocketType
var currentState = States.Disconnected
var reconnectCount = 0
var autoReconnectDisabled = false
var connectTimeout = false
var pingTimeout = false
var pingReconnectTimeout = false
var sendBuffer = []
var resetSendBufferTimeout = false
var resetSendBufferTimedOut = false
var isReady = false // If true the socket is initialized and ready.
var beforeReadySendBuffer = [] // Buffer to hold requests for the server while the socket is not ready yet.
var socketID = ''
/*
* Include the dependencies
*/
// Exported helper methods for the dependencies.
var closeSocket
var send
var sendBuffered
var utils = (function () {
/*
* Constants
*/
var Delimiter = '&'
/*
* Variables
*/
var instance = {} // Our public instance object returned by this function.
/*
* Public Methods
*/
// Mimics jQuery's extend method.
// Source: http://stackoverflow.com/questions/11197247/javascript-equivalent-of-jquerys-extend-method
instance.extend = function () {
for (var i = 1; i < arguments.length; i++) {
for (var key in arguments[i]) {
if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
arguments[0][key] = arguments[i][key]
}
}
}
return arguments[0]
}
// Source: http://stackoverflow.com/questions/5999998/how-can-i-check-if-a-javascript-variable-is-function-type.
instance.isFunction = function (v) {
var getType = {}
return v && getType.toString.call(v) === '[object Function]'
}
// unmarshalValues splits two values from a single string.
// This function is chainable to extract multiple values.
// An object with two strings (first, second) is returned.
instance.unmarshalValues = function (data) {
if (!data) {
return false
}
// Find the delimiter position.
var pos = data.indexOf(Delimiter)
// Extract the value length integer of the first value.
var len = parseInt(data.substring(0, pos), 10)
data = data.substring(pos + 1)
// Validate the length.
if (len < 0 || len > data.length) {
return false
}
// Now split the first value from the second.
var firstV = data.substr(0, len)
var secondV = data.substr(len)
// Return an object with both values.
return {
first: firstV,
second: secondV
}
}
// marshalValues joins two values into a single string.
// They can be decoded by the unmarshalValues function.
instance.marshalValues = function (first, second) {
return String(first.length) + Delimiter + first + second
}
return instance
})()
var channel = (function () {
/*
* Variables
*/
var instance = {} // Our public instance object returned by this function.
var channels = {} // Object as key value map.
/*
* Private Methods
*/
var newChannel = function (name) {
// Create the channel object.
var channel = {
// Set to a dummy function.
onMessageFunc: function () {}
}
// Set the channel public instance object.
// This is the value which is returned by the public glue.channel(...) function.
channel.instance = {
// onMessage sets the function which is triggered as soon as a message is received.
onMessage: function (f) {
channel.onMessageFunc = f
},
// send a data string to the channel.
// One optional discard callback can be passed.
// It is called if the data could not be send to the server.
// The data is passed as first argument to the discard callback.
// returns:
// 1 if immediately send,
// 0 if added to the send queue and
// -1 if discarded.
send: function (data, discardCallback) {
// Discard empty data.
if (!data) {
return -1
}
// Call the helper method and send the data to the channel.
return sendBuffered(
Commands.ChannelData,
utils.marshalValues(name, data),
discardCallback
)
}
}
// Return the channel object.
return channel
}
/*
* Public Methods
*/
// Get or create a channel if it does not exists.
instance.get = function (name) {
if (!name) {
return false
}
// Get the channel.
var c = channels[name]
if (c) {
return c.instance
}
// Create a new one, if it does not exists and add it to the map.
c = newChannel(name)
channels[name] = c
return c.instance
}
instance.emitOnMessage = function (name, data) {
if (!name || !data) {
return
}
// Get the channel.
var c = channels[name]
if (!c) {
console.log(
"glue: channel '" +
name +
"': emit onMessage event: channel does not exists"
)
return
}
// Call the channel's on message event.
try {
c.onMessageFunc(data)
} catch (err) {
console.log(
"glue: channel '" +
name +
"': onMessage event call failed: " +
err.message
)
}
}
return instance
})()
// Function variables.
var reconnect, triggerEvent
// Sends the data to the server if a socket connection exists, otherwise it is discarded.
// If the socket is not ready yet, the data is buffered until the socket is ready.
send = function (data) {
if (!bs) {
return
}
// If the socket is not ready yet, buffer the data.
if (!isReady) {
beforeReadySendBuffer.push(data)
return
}
// Send the data.
bs.send(data)
}
// Hint: the isReady flag has to be true before calling this function!
var sendBeforeReadyBufferedData = function () {
// Skip if empty.
if (beforeReadySendBuffer.length === 0) {
return
}
// Send the buffered data.
for (var i = 0; i < beforeReadySendBuffer.length; i++) {
send(beforeReadySendBuffer[i])
}
// Clear the buffer.
beforeReadySendBuffer = []
}
var stopResetSendBufferTimeout = function () {
// Reset the flag.
resetSendBufferTimedOut = false
// Stop the timeout timer if present.
if (resetSendBufferTimeout !== false) {
clearTimeout(resetSendBufferTimeout)
resetSendBufferTimeout = false
}
}
var startResetSendBufferTimeout = function () {
// Skip if already running or if already timed out.
if (resetSendBufferTimeout !== false || resetSendBufferTimedOut) {
return
}
// Start the timeout.
resetSendBufferTimeout = setTimeout(function () {
// Update the flags.
resetSendBufferTimeout = false
resetSendBufferTimedOut = true
// Return if already empty.
if (sendBuffer.length === 0) {
return
}
// Call the discard callbacks if defined.
var buf
for (var i = 0; i < sendBuffer.length; i++) {
buf = sendBuffer[i]
if (buf.discardCallback && utils.isFunction(buf.discardCallback)) {
try {
buf.discardCallback(buf.data)
} catch (err) {
console.log('glue: failed to call discard callback: ' + err.message)
}
}
}
// Trigger the event if any buffered send data is discarded.
triggerEvent('discard_send_buffer')
// Reset the buffer.
sendBuffer = []
}, options.resetSendBufferTimeout)
}
var sendDataFromSendBuffer = function () {
// Stop the reset send buffer tiemout.
stopResetSendBufferTimeout()
// Skip if empty.
if (sendBuffer.length === 0) {
return
}
// Send data, which could not be send...
var buf
for (var i = 0; i < sendBuffer.length; i++) {
buf = sendBuffer[i]
send(buf.cmd + buf.data)
}
// Clear the buffer again.
sendBuffer = []
}
// Send data to the server.
// This is a helper method which handles buffering,
// if the socket is currently not connected.
// One optional discard callback can be passed.
// It is called if the data could not be send to the server.
// The data is passed as first argument to the discard callback.
// returns:
// 1 if immediately send,
// 0 if added to the send queue and
// -1 if discarded.
sendBuffered = function (cmd, data, discardCallback) {
// Be sure, that the data value is an empty
// string if not passed to this method.
if (!data) {
data = ''
}
// Add the data to the send buffer if disconnected.
// They will be buffered for a short timeout to bridge short connection errors.
if (!bs || currentState !== States.Connected) {
// If already timed out, then call the discard callback and return.
if (resetSendBufferTimedOut) {
if (discardCallback && utils.isFunction(discardCallback)) {
discardCallback(data)
}
return -1
}
// Reset the send buffer after a specific timeout.
startResetSendBufferTimeout()
// Append to the buffer.
sendBuffer.push({
cmd: cmd,
data: data,
discardCallback: discardCallback
})
return 0
}
// Send the data with the command to the server.
send(cmd + data)
return 1
}
var stopConnectTimeout = function () {
// Stop the timeout timer if present.
if (connectTimeout !== false) {
clearTimeout(connectTimeout)
connectTimeout = false
}
}
var resetConnectTimeout = function () {
// Stop the timeout.
stopConnectTimeout()
// Start the timeout.
connectTimeout = setTimeout(function () {
// Update the flag.
connectTimeout = false
// Trigger the event.
triggerEvent('connect_timeout')
// Reconnect to the server.
reconnect()
}, options.connectTimeout)
}
var stopPingTimeout = function () {
// Stop the timeout timer if present.
if (pingTimeout !== false) {
clearTimeout(pingTimeout)
pingTimeout = false
}
// Stop the reconnect timeout.
if (pingReconnectTimeout !== false) {
clearTimeout(pingReconnectTimeout)
pingReconnectTimeout = false
}
}
var resetPingTimeout = function () {
// Stop the timeout.
stopPingTimeout()
// Start the timeout.
pingTimeout = setTimeout(function () {
// Update the flag.
pingTimeout = false
// Request a Pong response to check if the connection is still alive.
send(Commands.Ping)
// Start the reconnect timeout.
pingReconnectTimeout = setTimeout(function () {
// Update the flag.
pingReconnectTimeout = false
// Trigger the event.
triggerEvent('timeout')
// Reconnect to the server.
reconnect()
}, options.pingReconnectTimeout)
}, options.pingInterval)
}
var newBackendSocket = function () {
// If at least one successfull connection was made,
// then create a new socket using the last create socket function.
// Otherwise determind which socket layer to use.
if (initialConnectedOnce) {
bs = bsNewFunc()
return
}
// Fallback to the ajax socket layer if there was no successful initial
// connection and more than one reconnection attempt was made.
if (reconnectCount > 1) {
bsNewFunc = newAjaxSocket
bs = bsNewFunc()
currentSocketType = SocketTypes.AjaxSocket
return
}
// Choose the socket layer depending on the browser support.
if (
(!options.forceSocketType && window.WebSocket) ||
options.forceSocketType === SocketTypes.WebSocket
) {
bsNewFunc = newWebSocket
currentSocketType = SocketTypes.WebSocket
} else {
bsNewFunc = newAjaxSocket
currentSocketType = SocketTypes.AjaxSocket
}
// Create the new socket.
bs = bsNewFunc()
}
var initSocket = function (data) {
// Parse the data JSON string to an object.
data = JSON.parse(data)
// Validate.
// Close the socket and log the error on invalid data.
if (!data.socketID) {
closeSocket()
console.log(
'glue: socket initialization failed: invalid initialization data received'
)
return
}
// Set the socket ID.
socketID = data.socketID
// The socket initialization is done.
// ##################################
// Set the ready flag.
isReady = true