-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathconnectionmanager.js
1538 lines (1365 loc) · 66.2 KB
/
connectionmanager.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
var ConnectionManager = (function() {
var haveWebStorage = !!(typeof(WebStorage) !== 'undefined' && WebStorage.get);
var haveSessionStorage = !!(typeof(WebStorage) !== 'undefined' && WebStorage.getSession);
var actions = ProtocolMessage.Action;
var PendingMessage = Protocol.PendingMessage;
var noop = function() {};
var transportPreferenceOrder = Defaults.transportPreferenceOrder;
var optimalTransport = transportPreferenceOrder[transportPreferenceOrder.length - 1];
var transportPreferenceName = 'ably-transport-preference';
var sessionRecoveryName = 'ably-connection-recovery';
function getSessionRecoverData() {
return haveSessionStorage && WebStorage.getSession(sessionRecoveryName);
}
function setSessionRecoverData(value) {
return haveSessionStorage && WebStorage.setSession(sessionRecoveryName, value);
}
function clearSessionRecoverData() {
return haveSessionStorage && WebStorage.removeSession(sessionRecoveryName);
}
function betterTransportThan(a, b) {
return Utils.arrIndexOf(transportPreferenceOrder, a.shortName) >
Utils.arrIndexOf(transportPreferenceOrder, b.shortName);
}
function TransportParams(options, host, mode, connectionKey, connectionSerial) {
this.options = options;
this.host = host;
this.mode = mode;
this.connectionKey = connectionKey;
this.connectionSerial = connectionSerial;
this.format = options.useBinaryProtocol ? 'msgpack' : 'json';
}
TransportParams.prototype.getConnectParams = function(authParams) {
var params = authParams ? Utils.copy(authParams) : {};
var options = this.options;
switch(this.mode) {
case 'upgrade':
params.upgrade = this.connectionKey;
break;
case 'resume':
params.resume = this.connectionKey;
if(this.connectionSerial !== undefined)
params.connection_serial = this.connectionSerial;
break;
case 'recover':
var match = options.recover.split(':');
if(match) {
params.recover = match[0];
params.connection_serial = match[1];
}
break;
default:
}
if(options.clientId !== undefined)
params.clientId = options.clientId;
if(options.echoMessages === false)
params.echo = 'false';
if(this.format !== undefined)
params.format = this.format;
if(this.stream !== undefined)
params.stream = this.stream;
if(this.heartbeats !== undefined)
params.heartbeats = this.heartbeats;
params.v = Defaults.apiVersion;
params.lib = Defaults.libstring;
if(options.transportParams !== undefined) {
Utils.mixin(params, options.transportParams);
}
return params;
};
/* public constructor */
function ConnectionManager(realtime, options) {
EventEmitter.call(this);
this.realtime = realtime;
this.options = options;
var timeouts = options.timeouts;
var self = this;
/* connectingTimeout: leave preferenceConnectTimeout (~6s) to try the
* preference transport, then realtimeRequestTimeout (~10s) to establish
* the base transport in case that fails */
var connectingTimeout = timeouts.preferenceConnectTimeout + timeouts.realtimeRequestTimeout;
this.states = {
initialized: {state: 'initialized', terminal: false, queueEvents: true, sendEvents: false, failState: 'disconnected'},
connecting: {state: 'connecting', terminal: false, queueEvents: true, sendEvents: false, retryDelay: connectingTimeout, failState: 'disconnected'},
connected: {state: 'connected', terminal: false, queueEvents: false, sendEvents: true, failState: 'disconnected'},
synchronizing: {state: 'connected', terminal: false, queueEvents: true, sendEvents: false, forceQueueEvents: true, failState: 'disconnected'},
disconnected: {state: 'disconnected', terminal: false, queueEvents: true, sendEvents: false, retryDelay: timeouts.disconnectedRetryTimeout, failState: 'disconnected'},
suspended: {state: 'suspended', terminal: false, queueEvents: false, sendEvents: false, retryDelay: timeouts.suspendedRetryTimeout, failState: 'suspended'},
closing: {state: 'closing', terminal: false, queueEvents: false, sendEvents: false, retryDelay: timeouts.realtimeRequestTimeout, failState: 'closed'},
closed: {state: 'closed', terminal: true, queueEvents: false, sendEvents: false, failState: 'closed'},
failed: {state: 'failed', terminal: true, queueEvents: false, sendEvents: false, failState: 'failed'}
};
this.state = this.states.initialized;
this.errorReason = null;
this.queuedMessages = new MessageQueue();
this.msgSerial = 0;
this.connectionId = undefined;
this.connectionKey = undefined;
this.connectionSerial = undefined;
this.connectionStateTtl = timeouts.connectionStateTtl;
this.maxIdleInterval = null;
this.transports = Utils.intersect((options.transports || Defaults.defaultTransports), ConnectionManager.supportedTransports);
/* baseTransports selects the leftmost transport in the Defaults.baseTransportOrder list
* that's both requested and supported. Normally this will be xhr_polling;
* if xhr isn't supported it will be jsonp. If the user has forced a
* transport, it'll just be that one. */
this.baseTransport = Utils.intersect(Defaults.baseTransportOrder, this.transports)[0];
this.upgradeTransports = Utils.intersect(this.transports, Defaults.upgradeTransports);
/* Map of hosts to an array of transports to not be tried for that host */
this.transportHostBlacklist = {};
this.transportPreference = null;
this.httpHosts = Defaults.getHosts(options);
this.activeProtocol = null;
this.proposedTransports = [];
this.pendingTransports = [];
this.host = null;
this.lastAutoReconnectAttempt = null;
this.lastActivity = null;
this.mostRecentMsgId = null;
Logger.logAction(Logger.LOG_MINOR, 'Realtime.ConnectionManager()', 'started');
Logger.logAction(Logger.LOG_MICRO, 'Realtime.ConnectionManager()', 'requested transports = [' + (options.transports || Defaults.defaultTransports) + ']');
Logger.logAction(Logger.LOG_MICRO, 'Realtime.ConnectionManager()', 'available transports = [' + this.transports + ']');
Logger.logAction(Logger.LOG_MICRO, 'Realtime.ConnectionManager()', 'http hosts = [' + this.httpHosts + ']');
if(!this.transports.length) {
var msg = 'no requested transports available';
Logger.logAction(Logger.LOG_ERROR, 'realtime.ConnectionManager()', msg);
throw new Error(msg);
}
var addEventListener = Platform.addEventListener;
if(addEventListener) {
/* intercept close event in browser to persist connection id if requested */
if(haveSessionStorage && typeof options.recover === 'function') {
/* Usually can't use bind as not supported in IE8, but IE doesn't support sessionStorage, so... */
addEventListener('beforeunload', this.persistConnection.bind(this));
}
if(options.closeOnUnload === true) {
addEventListener('beforeunload', function() { self.requestState({state: 'closing'}); });
}
/* Listen for online and offline events */
addEventListener('online', function() {
if(self.state == self.states.disconnected || self.state == self.states.suspended) {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager caught browser ‘online’ event', 'reattempting connection');
self.requestState({state: 'connecting'});
}
});
addEventListener('offline', function() {
if(self.state == self.states.connected) {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager caught browser ‘offline’ event', 'disconnecting active transport');
// Not sufficient to just go to the 'disconnected' state, want to
// force all transports to reattempt the connection. Will immediately
// retry.
self.disconnectAllTransports();
}
});
}
}
Utils.inherits(ConnectionManager, EventEmitter);
/*********************
* transport management
*********************/
ConnectionManager.supportedTransports = {};
ConnectionManager.prototype.getTransportParams = function(callback) {
var self = this;
function decideMode(modeCb) {
if(self.connectionKey) {
modeCb('resume');
return;
}
if(typeof self.options.recover === 'string') {
modeCb('recover');
return;
}
var recoverFn = self.options.recover,
lastSessionData = getSessionRecoverData();
if(lastSessionData && typeof(recoverFn) === 'function') {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.getTransportParams()', 'Calling clientOptions-provided recover function with last session data');
recoverFn(lastSessionData, function(shouldRecover) {
if(shouldRecover) {
self.options.recover = lastSessionData.recoveryKey;
modeCb('recover');
} else {
modeCb('clean');
}
});
return;
}
modeCb('clean');
}
decideMode(function(mode) {
if(mode === 'recover') {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.getTransportParams()', 'Transport recovery mode = recover; recoveryKey = ' + self.options.recover);
var match = self.options.recover.split(':');
if(match && match[2]) {
self.msgSerial = match[2];
}
} else {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.getTransportParams()', 'Transport recovery mode = ' + mode + (mode == 'clean' ? '' : '; connectionKey = ' + self.connectionKey + '; connectionSerial = ' + self.connectionSerial));
}
callback(new TransportParams(self.options, null, mode, self.connectionKey, self.connectionSerial));
});
};
/**
* Attempt to connect using a given transport
* @param transportParams
* @param candidate, the transport to try
* @param callback
*/
ConnectionManager.prototype.tryATransport = function(transportParams, candidate, callback) {
var self = this, host = transportParams.host;
Logger.logAction(Logger.LOG_MICRO, 'ConnectionManager.tryATransport()', 'trying ' + candidate);
if((host in this.transportHostBlacklist) && Utils.arrIn(this.transportHostBlacklist[host], candidate)) {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.tryATransport()', candidate + ' transport is blacklisted for host ' + transportParams.host);
return;
}
(ConnectionManager.supportedTransports[candidate]).tryConnect(this, this.realtime.auth, transportParams, function(wrappedErr, transport) {
var state = self.state;
if(state == self.states.closing || state == self.states.closed || state == self.states.failed) {
if(transport) {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.tryATransport()', 'connection ' + state.state + ' while we were attempting the transport; closing ' + transport);
transport.close();
}
callback(true);
return;
}
if(wrappedErr) {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.tryATransport()', 'transport ' + candidate + ' ' + wrappedErr.event + ', err: ' + wrappedErr.error.toString());
/* Comet transport onconnect token errors can be dealt with here.
* Websocket ones only happen after the transport claims to be viable,
* so are dealt with as non-onconnect token errors */
if(Auth.isTokenErr(wrappedErr.error)) {
/* re-get a token and try again */
self.realtime.auth._forceNewToken(null, null, function(err) {
if(err) {
self.actOnErrorFromAuthorize(err);
return;
}
self.tryATransport(transportParams, candidate, callback);
});
} else if(wrappedErr.event === 'failed') {
/* Error that's fatal to the connection */
self.notifyState({state: 'failed', error: wrappedErr.error});
callback(true);
} else if(wrappedErr.event === 'disconnected') {
/* Error with that transport only */
callback(false);
}
return;
}
Logger.logAction(Logger.LOG_MICRO, 'ConnectionManager.chooseTransportForHost()', 'viable transport ' + candidate + '; setting pending');
self.setTransportPending(transport, transportParams);
callback(null, transport);
});
};
/**
* Called when a transport is indicated to be viable, and the connectionmanager
* expects to activate this transport as soon as it is connected.
* @param host
* @param transportParams
*/
ConnectionManager.prototype.setTransportPending = function(transport, transportParams) {
var mode = transportParams.mode;
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.setTransportPending()', 'transport = ' + transport + '; mode = ' + mode);
Utils.arrDeleteValue(this.proposedTransports, transport);
this.pendingTransports.push(transport);
var self = this;
transport.once('connected', function(error, connectionKey, connectionSerial, connectionId, connectionDetails) {
if(mode == 'upgrade' && self.activeProtocol) {
/* if ws and xhrs are connecting in parallel, delay xhrs activation to let ws go ahead */
if(transport.shortName !== optimalTransport && Utils.arrIn(self.getUpgradePossibilities(), optimalTransport)) {
setTimeout(function() {
self.scheduleTransportActivation(error, transport, connectionKey, connectionSerial, connectionId, connectionDetails);
}, self.options.timeouts.parallelUpgradeDelay);
} else {
self.scheduleTransportActivation(error, transport, connectionKey, connectionSerial, connectionId, connectionDetails);
}
} else {
self.activateTransport(error, transport, connectionKey, connectionSerial, connectionId, connectionDetails);
/* allow connectImpl to start the upgrade process if needed, but allow
* other event handlers, including activating the transport, to run first */
Utils.nextTick(function() {
self.connectImpl(transportParams);
});
}
if(mode === 'recover' && self.options.recover) {
/* After a successful recovery, we unpersist, as a recovery key cannot
* be used more than once */
self.options.recover = null;
self.unpersistConnection();
}
});
transport.on(['disconnected', 'closed', 'failed'], function(error) {
self.deactivateTransport(transport, this.event, error);
});
this.emit('transport.pending', transport);
};
/**
* Called when an upgrade transport is connected,
* to schedule the activation of that transport.
* @param transport, the transport instance
* @param connectionKey
*/
ConnectionManager.prototype.scheduleTransportActivation = function(error, transport, connectionKey, connectionSerial, connectionId, connectionDetails) {
var self = this,
currentTransport = this.activeProtocol && this.activeProtocol.getTransport(),
abandon = function() {
transport.disconnect();
Utils.arrDeleteValue(self.pendingTransports, transport);
};
if(this.state !== this.states.connected && this.state !== this.states.connecting) {
/* This is most likely to happen for the delayed xhrs, when xhrs and ws are scheduled in parallel*/
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.scheduleTransportActivation()', 'Current connection state (' + this.state.state + (this.state === this.states.synchronizing ? ', but with an upgrade already in progress' : '') + ') is not valid to upgrade in; abandoning upgrade to ' + transport.shortName);
abandon();
return;
}
if(currentTransport && !betterTransportThan(transport, currentTransport)) {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.scheduleTransportActivation()', 'Proposed transport ' + transport.shortName + ' is no better than current active transport ' + currentTransport.shortName + ' - abandoning upgrade');
abandon();
return;
}
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.scheduleTransportActivation()', 'Scheduling transport upgrade; transport = ' + transport);
this.realtime.channels.onceNopending(function(err) {
var oldProtocol;
if(err) {
Logger.logAction(Logger.LOG_ERROR, 'ConnectionManager.scheduleTransportActivation()', 'Unable to activate transport; transport = ' + transport + '; err = ' + err);
return;
}
if(!transport.isConnected) {
/* This is only possible if the xhr streaming transport was disconnected during the parallelUpgradeDelay */
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.scheduleTransportActivation()', 'Proposed transport ' + transport.shortName + 'is no longer connected; abandoning upgrade');
abandon();
return;
}
if(self.state === self.states.connected) {
Logger.logAction(Logger.LOG_MICRO, 'ConnectionManager.scheduleTransportActivation()', 'Currently connected, so temporarily pausing events until the upgrade is complete');
self.state = self.states.synchronizing;
oldProtocol = self.activeProtocol;
} else if(self.state !== self.states.connecting) {
/* Note: upgrading from the connecting state is valid if the old active
* transport was deactivated after the upgrade transport first connected;
* see logic in deactivateTransport */
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.scheduleTransportActivation()', 'Current connection state (' + self.state.state + (self.state === self.states.synchronizing ? ', but with an upgrade already in progress' : '') + ') is not valid to upgrade in; abandoning upgrade to ' + transport.shortName);
abandon();
return;
}
/* If the connectionId has changed, the upgrade hasn't worked. But as
* it's still an upgrade, realtime still expects a sync - it just needs to
* be a sync with the new connectionSerial (which will be -1). (And it
* needs to be set in the library, which is done by activateTransport). */
var connectionReset = connectionId !== self.connectionId,
newConnectionSerial = connectionReset ? connectionSerial : self.connectionSerial;
if(connectionReset) {
Logger.logAction(Logger.LOG_ERROR, 'ConnectionManager.scheduleTransportActivation()', 'Upgrade resulted in new connectionId; resetting library connectionSerial from ' + self.connectionSerial + ' to ' + newConnectionSerial + '; upgrade error was ' + error);
}
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.scheduleTransportActivation()', 'Syncing transport; transport = ' + transport);
self.sync(transport, function(syncErr, newConnectionSerial, connectionId) {
/* If there's been some problem with syncing (and the connection hasn't
* closed or something in the meantime), we have a problem -- we can't
* just fall back on the old transport, as we don't know whether
* realtime got the sync -- if it did, the old transport is no longer
* valid. To be safe, we disconnect both and start again from scratch. */
if(syncErr) {
if(self.state === self.states.synchronizing) {
Logger.logAction(Logger.LOG_ERROR, 'ConnectionManager.scheduleTransportActivation()', 'Unexpected error attempting to sync transport; transport = ' + transport + '; err = ' + syncErr);
self.disconnectAllTransports();
}
return;
}
var finishUpgrade = function() {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.scheduleTransportActivation()', 'Activating transport; transport = ' + transport);
self.activateTransport(error, transport, connectionKey, newConnectionSerial, connectionId, connectionDetails);
/* Restore pre-sync state. If state has changed in the meantime,
* don't touch it -- since the websocket transport waits a tick before
* disposing itself, it's possible for it to have happily synced
* without err while, unknown to it, the connection has closed in the
* meantime and the ws transport is scheduled for death */
if(self.state === self.states.synchronizing) {
Logger.logAction(Logger.LOG_MICRO, 'ConnectionManager.scheduleTransportActivation()', 'Pre-upgrade protocol idle, sending queued messages on upgraded transport; transport = ' + transport);
self.state = self.states.connected;
} else {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.scheduleTransportActivation()', 'Pre-upgrade protocol idle, but state is now ' + self.state.state + ', so leaving unchanged');
}
if(self.state.sendEvents) {
self.sendQueuedMessages();
}
};
/* Wait until sync is done and old transport is idle before activating new transport. This
* guarantees that messages arrive at realtime in the same order they are sent.
*
* If a message times out on the old transport, since it's still the active transport the
* message will be requeued. deactivateTransport will see the pending transport and notify
* the `connecting` state without starting a new connection, so the new transport can take
* over once deactivateTransport clears the old protocol's queue.
*
* If there is no old protocol, that meant that we weren't in the connected state at the
* beginning of the sync - likely the base transport died just before the sync. So can just
* finish the upgrade. If we're actually in closing/failed rather than connecting, that's
* fine, activatetransport will deal with that. */
if(oldProtocol) {
/* Most of the time this will be already true: the new-transport sync will have given
* enough time for in-flight messages on the old transport to complete. */
oldProtocol.onceIdle(finishUpgrade);
} else {
finishUpgrade();
}
});
});
};
/**
* Called when a transport is connected, and the connectionmanager decides that
* it will now be the active transport. Returns whether or not it activated
* the transport (if the connection is closing/closed it will choose not to).
* @param transport the transport instance
* @param connectionKey the key of the new active connection
* @param connectionSerial the current connectionSerial
* @param connectionId the id of the new active connection
*/
ConnectionManager.prototype.activateTransport = function(error, transport, connectionKey, connectionSerial, connectionId, connectionDetails) {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.activateTransport()', 'transport = ' + transport);
if(error) {
Logger.logAction(Logger.LOG_ERROR, 'ConnectionManager.activateTransport()', 'error = ' + error);
}
if(connectionKey)
Logger.logAction(Logger.LOG_MICRO, 'ConnectionManager.activateTransport()', 'connectionKey = ' + connectionKey);
if(connectionSerial !== undefined)
Logger.logAction(Logger.LOG_MICRO, 'ConnectionManager.activateTransport()', 'connectionSerial = ' + connectionSerial);
if(connectionId)
Logger.logAction(Logger.LOG_MICRO, 'ConnectionManager.activateTransport()', 'connectionId = ' + connectionId);
if(connectionDetails)
Logger.logAction(Logger.LOG_MICRO, 'ConnectionManager.activateTransport()', 'connectionDetails = ' + JSON.stringify(connectionDetails));
this.persistTransportPreference(transport);
/* if the connectionmanager moved to the closing/closed state before this
* connection event, then we won't activate this transport */
var existingState = this.state,
connectedState = this.states.connected.state;
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.activateTransport()', 'current state = ' + existingState.state);
if(existingState.state == this.states.closing.state || existingState.state == this.states.closed.state || existingState.state == this.states.failed.state) {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.activateTransport()', 'Disconnecting transport and abandoning');
transport.disconnect();
return false;
}
/* remove this transport from pending transports */
Utils.arrDeleteValue(this.pendingTransports, transport);
/* if the transport is not connected (eg because it failed during a
* scheduleTransportActivation#onceNoPending wait) then don't activate it */
if(!transport.isConnected) {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.activateTransport()', 'Declining to activate transport ' + transport + ' since it appears to no longer be connected');
return false;
}
/* the given transport is connected; this will immediately
* take over as the active transport */
var existingActiveProtocol = this.activeProtocol;
this.activeProtocol = new Protocol(transport);
this.host = transport.params.host;
if(connectionKey && this.connectionKey != connectionKey) {
this.setConnection(connectionId, connectionKey, connectionSerial);
}
/* Rebroadcast any new connectionDetails from the active transport, which
* can come at any time (eg following a reauth), and emit an RTN24 UPDATE
* event. (Listener added on nextTick because we're in a transport.on('connected')
* callback at the moment; if we add it now we'll be adding it to the end
* of the listeners array and it'll be called immediately) */
this.onConnectionDetailsUpdate(connectionDetails, transport);
var self = this;
Utils.nextTick(function() {
transport.on('connected', function(connectedErr, _connectionKey, _connectionSerial, _connectionId, connectionDetails) {
self.onConnectionDetailsUpdate(connectionDetails, transport);
self.emit('update', new ConnectionStateChange(connectedState, connectedState, null, connectedErr));
});
})
/* If previously not connected, notify the state change (including any
* error). */
if(existingState.state === this.states.connected.state) {
if(error) {
/* if upgrading without error, leave any existing errorReason alone */
this.errorReason = this.realtime.connection.errorReason = error;
/* Only bother emitting an upgrade if there's an error; otherwise it's
* just a transport upgrade, so auth details won't have changed */
this.emit('update', new ConnectionStateChange(connectedState, connectedState, null, error));
}
} else {
this.notifyState({state: 'connected', error: error});
this.errorReason = this.realtime.connection.errorReason = error || null;
}
/* Send after the connection state update, as Channels hooks into this to
* resend attaches on a new transport if necessary */
this.emit('transport.active', transport, connectionKey, transport.params);
/* Gracefully terminate existing protocol */
if(existingActiveProtocol) {
if(existingActiveProtocol.messageQueue.count() > 0) {
/* We could just requeue pending messages on the new transport, but
* actually this should never happen: transports should only take over
* from other active transports when upgrading, and upgrading waits for
* the old transport to be idle. So log an error. */
Logger.logAction(Logger.LOG_ERROR, 'ConnectionManager.activateTransport()', 'Previous active protocol (for transport ' + existingActiveProtocol.transport.shortName + ', new one is ' + transport.shortName + ') finishing with ' + existingActiveProtocol.messageQueue.count() + ' messages still pending');
}
existingActiveProtocol.finish();
}
/* Terminate any other pending transport(s), and
* abort any not-yet-pending transport attempts */
Utils.safeArrForEach(this.pendingTransports, function(transport) {
transport.disconnect();
});
Utils.safeArrForEach(this.proposedTransports, function(transport) {
transport.dispose();
});
return true;
};
/**
* Called when a transport is no longer the active transport. This can occur
* in any transport connection state.
* @param transport
*/
ConnectionManager.prototype.deactivateTransport = function(transport, state, error) {
var currentProtocol = this.activeProtocol,
wasActive = currentProtocol && currentProtocol.getTransport() === transport,
wasPending = Utils.arrDeleteValue(this.pendingTransports, transport),
wasProposed = Utils.arrDeleteValue(this.proposedTransports, transport),
noTransportsScheduledForActivation = this.noTransportsScheduledForActivation();
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.deactivateTransport()', 'transport = ' + transport);
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.deactivateTransport()', 'state = ' + state + (wasActive ? '; was active' : wasPending ? '; was pending' : wasProposed ? '; was proposed' : '') + (noTransportsScheduledForActivation ? '' : '; another transport is scheduled for activation'));
if(error && error.message)
Logger.logAction(Logger.LOG_MICRO, 'ConnectionManager.deactivateTransport()', 'reason = ' + error.message);
if(wasActive) {
Logger.logAction(Logger.LOG_MICRO, 'ConnectionManager.deactivateTransport()', 'Getting, clearing, and requeuing ' + this.activeProtocol.messageQueue.count() + ' pending messages');
this.queuePendingMessages(currentProtocol.getPendingMessages());
/* Clear any messages we requeue to allow the protocol to become idle.
* In case of an upgrade, this will trigger an immediate activation of
* the upgrade transport, so delay a tick so this transport can finish
* deactivating */
Utils.nextTick(function() {
currentProtocol.clearPendingMessages();
});
this.activeProtocol = this.host = null;
}
this.emit('transport.inactive', transport);
/* this transport state change is a state change for the connectionmanager if
* - the transport was the active transport and there are no transports
* which are connected and scheduled for activation, just waiting for the
* active transport to finish what its doing; or
* - the transport was the active transport and the error was fatal (so
* unhealable by another transport); or
* - there is no active transport, and this is the last remaining
* pending transport (so we were in the connecting state)
*/
if((wasActive && noTransportsScheduledForActivation) ||
(wasActive && (state === 'failed') || (state === 'closed')) ||
(currentProtocol === null && wasPending && this.pendingTransports.length === 0)) {
/* TODO remove below line once realtime sends token errors as DISCONNECTEDs */
if(state === 'failed' && Auth.isTokenErr(error)) { state = 'disconnected' }
this.notifyState({state: state, error: error});
} else if(wasActive && (state === 'disconnected')) {
/* If we were active but there is another transport scheduled for
* activation, go into to the connecting state until that transport
* activates and sets us back to connected. (manually starting the
* transition timers in case that never happens) */
Logger.logAction(Logger.LOG_MICRO, 'ConnectionManager.deactivateTransport()', 'wasActive but another transport is connected and scheduled for activation, so going into the connecting state until it activates');
this.startSuspendTimer();
this.startTransitionTimer(this.states.connecting);
this.notifyState({state: 'connecting', error: error});
}
};
/* Helper that returns true if there are no transports which are pending,
* have been connected, and are just waiting for onceNoPending to fire before
* being activated */
ConnectionManager.prototype.noTransportsScheduledForActivation = function() {
return Utils.isEmpty(this.pendingTransports) ||
this.pendingTransports.every(function(transport) {
return !transport.isConnected;
});
};
/**
* Called when activating a new transport, to ensure message delivery
* on the new transport synchronises with the messages already received
*/
ConnectionManager.prototype.sync = function(transport, callback) {
var timeout = setTimeout(function () {
transport.off('sync');
callback(new ErrorInfo('Timeout waiting for sync response', 50000, 500));
}, this.options.timeouts.realtimeRequestTimeout);
/* send sync request */
var syncMessage = ProtocolMessage.fromValues({
action: actions.SYNC,
connectionKey: this.connectionKey,
connectionSerial: this.connectionSerial
});
transport.send(syncMessage);
transport.once('sync', function(connectionSerial, connectionId) {
clearTimeout(timeout);
callback(null, connectionSerial, connectionId);
});
};
ConnectionManager.prototype.setConnection = function(connectionId, connectionKey, connectionSerial) {
/* if connectionKey changes but connectionId stays the same, then just a
* transport change on the same connection. If connectionId changes, we're
* on a new connection, with implications for msgSerial and channel state */
var self = this;
connectionSerial = (connectionSerial === undefined) ? -1 : connectionSerial;
/* If no previous connectionId, don't reset the msgSerial as it may have been set by recover data */
if(this.connectionId && (this.connectionId !== connectionId)) {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.setConnection()', 'Resetting msgSerial');
this.msgSerial = 0;
}
/* but do need to reattach channels, for channels that were previously in
* the attached state even though the connection mode was 'clean' due to a
* freshness check - see /~https://github.com/ably/ably-js/issues/394 */
if(this.connectionId !== connectionId) {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.setConnection()', 'New connectionId; reattaching any attached channels');
/* Wait till next tick before reattaching channels, so that connection
* state will be updated and so that it will be applied after
* Channels#onTransportUpdate, else channels will not have an ATTACHED
* sent twice (once from this and once from that). */
Utils.nextTick(function() {
self.realtime.channels.reattach();
});
} else {
/* don't allow the connectionSerial in the CONNECTED to lower the stored
* connectionSerial, because messages can arrive on the upgrade transport
* (validly incrementing the stored connectionSerial) after it's been
* synced but before it gets activated */
connectionSerial = (this.connectionSerial === undefined) ? connectionSerial : Math.max(connectionSerial, this.connectionSerial);
}
this.realtime.connection.id = this.connectionId = connectionId;
this.realtime.connection.key = this.connectionKey = connectionKey;
this.realtime.connection.serial = this.connectionSerial = connectionSerial;
this.realtime.connection.recoveryKey = connectionKey + ':' + this.connectionSerial + ':' + this.msgSerial;
};
ConnectionManager.prototype.clearConnection = function() {
this.realtime.connection.id = this.connectionId = undefined;
this.realtime.connection.key = this.connectionKey = undefined;
this.realtime.connection.serial = this.connectionSerial = undefined;
this.realtime.connection.recoveryKey = null;
this.msgSerial = 0;
this.unpersistConnection();
};
ConnectionManager.prototype.checkConnectionStateFreshness = function() {
if(!this.lastActivity || !this.connectionId) { return; }
var sinceLast = Utils.now() - this.lastActivity;
if(sinceLast > this.connectionStateTtl + this.maxIdleInterval) {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.checkConnectionStateFreshness()', 'Last known activity from realtime was ' + sinceLast + 'ms ago; discarding connection state');
this.clearConnection();
this.states.connecting.failState = 'suspended';
this.states.connecting.queueEvents = false;
}
};
/**
* Called when the connectionmanager wants to persist transport
* state for later recovery. Only applicable in the browser context.
*/
ConnectionManager.prototype.persistConnection = function() {
if(haveSessionStorage && this.connectionKey && this.connectionSerial !== undefined) {
setSessionRecoverData({
recoveryKey: this.connectionKey + ':' + this.connectionSerial + ':' + this.msgSerial,
disconnectedAt: Utils.now(),
location: window.location,
clientId: this.realtime.auth.clientId
}, this.connectionStateTtl);
}
};
/**
* Called when the connectionmanager wants to persist transport
* state for later recovery. Only applicable in the browser context.
*/
ConnectionManager.prototype.unpersistConnection = function() {
clearSessionRecoverData();
};
/*********************
* state management
*********************/
ConnectionManager.prototype.getStateError = function() {
return ConnectionError[this.state.state];
};
ConnectionManager.prototype.activeState = function() {
return this.state.queueEvents || this.state.sendEvents;
};
ConnectionManager.prototype.enactStateChange = function(stateChange) {
var logLevel = stateChange.current === 'failed' ? Logger.LOG_ERROR : Logger.LOG_MAJOR;
Logger.logAction(logLevel, 'Connection state', stateChange.current + (stateChange.reason ? ('; reason: ' + stateChange.reason.message + ', code: ' + stateChange.reason.code) : ''));
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.enactStateChange', 'setting new state: ' + stateChange.current + '; reason = ' + (stateChange.reason && stateChange.reason.message));
var newState = this.state = this.states[stateChange.current];
if(stateChange.reason) {
this.errorReason = stateChange.reason;
this.realtime.connection.errorReason = stateChange.reason;
}
if(newState.terminal || newState.state === 'suspended') {
/* suspended is nonterminal, but once in the suspended state, realtime
* will have discarded our connection state, so futher connection
* attempts should start from scratch */
this.clearConnection();
}
this.emit('connectionstate', stateChange);
};
/****************************************
* ConnectionManager connection lifecycle
****************************************/
ConnectionManager.prototype.startTransitionTimer = function(transitionState) {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.startTransitionTimer()', 'transitionState: ' + transitionState.state);
if(this.transitionTimer) {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.startTransitionTimer()', 'clearing already-running timer');
clearTimeout(this.transitionTimer);
}
var self = this;
this.transitionTimer = setTimeout(function() {
if(self.transitionTimer) {
self.transitionTimer = null;
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager ' + transitionState.state + ' timer expired', 'requesting new state: ' + transitionState.failState);
self.notifyState({state: transitionState.failState});
}
}, transitionState.retryDelay);
};
ConnectionManager.prototype.cancelTransitionTimer = function() {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.cancelTransitionTimer()', '');
if(this.transitionTimer) {
clearTimeout(this.transitionTimer);
this.transitionTimer = null;
}
};
ConnectionManager.prototype.startSuspendTimer = function() {
var self = this;
if(this.suspendTimer)
return;
this.suspendTimer = setTimeout(function() {
if(self.suspendTimer) {
self.suspendTimer = null;
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager suspend timer expired', 'requesting new state: suspended');
self.states.connecting.failState = 'suspended';
self.states.connecting.queueEvents = false;
self.notifyState({state: 'suspended'});
}
}, this.connectionStateTtl);
};
ConnectionManager.prototype.checkSuspendTimer = function(state) {
if(state !== 'disconnected' && state !== 'suspended' && state !== 'connecting')
this.cancelSuspendTimer();
};
ConnectionManager.prototype.cancelSuspendTimer = function() {
this.states.connecting.failState = 'disconnected';
this.states.connecting.queueEvents = true;
if(this.suspendTimer) {
clearTimeout(this.suspendTimer);
this.suspendTimer = null;
}
};
ConnectionManager.prototype.startRetryTimer = function(interval) {
var self = this;
this.retryTimer = setTimeout(function() {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager retry timer expired', 'retrying');
self.retryTimer = null;
self.requestState({state: 'connecting'});
}, interval);
};
ConnectionManager.prototype.cancelRetryTimer = function() {
if(this.retryTimer) {
clearTimeout(this.retryTimer);
this.retryTimer = null;
}
};
ConnectionManager.prototype.notifyState = function(indicated) {
var state = indicated.state,
self = this;
/* We retry immediately if:
* - something disconnects us while we're connected, or
* - a viable (but not yet active) transport fails due to a token error (so
* this.errorReason will be set, and startConnect will do a forced authorize) */
var retryImmediately = (state === 'disconnected' &&
(this.state === this.states.connected ||
this.state === this.states.synchronizing ||
(this.state === this.states.connecting &&
indicated.error && Auth.isTokenErr(indicated.error))));
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.notifyState()', 'new state: ' + state + (retryImmediately ? '; will retry connection immediately' : ''));
/* do nothing if we're already in the indicated state */
if(state == this.state.state)
return;
/* kill timers (possibly excepting suspend timer depending on the notified
* state), as these are superseded by this notification */
this.cancelTransitionTimer();
this.cancelRetryTimer();
this.checkSuspendTimer(indicated.state);
/* do nothing if we're unable to move from the current state */
if(this.state.terminal)
return;
/* process new state */
var newState = this.states[indicated.state],
change = new ConnectionStateChange(this.state.state, newState.state, newState.retryDelay, (indicated.error || ConnectionError[newState.state]));
if(retryImmediately) {
var autoReconnect = function() {
if(self.state === self.states.disconnected) {
self.lastAutoReconnectAttempt = Utils.now();
self.requestState({state: 'connecting'});
}
};
var sinceLast = this.lastAutoReconnectAttempt && (Utils.now() - this.lastAutoReconnectAttempt + 1);
if(sinceLast && (sinceLast < 1000)) {
Logger.logAction(Logger.LOG_MICRO, 'ConnectionManager.notifyState()', 'Last reconnect attempt was only ' + sinceLast + 'ms ago, waiting another ' + (1000 - sinceLast) + 'ms before trying again');
setTimeout(autoReconnect, 1000 - sinceLast);
} else {
Utils.nextTick(autoReconnect);
}
} else if(state === 'disconnected' || state === 'suspended') {
this.startRetryTimer(newState.retryDelay);
}
/* If going into disconnect/suspended (and not retrying immediately), or a
* terminal state, ensure there are no orphaned transports hanging around. */
if((state === 'disconnected' && !retryImmediately) ||
(state === 'suspended') ||
newState.terminal) {
/* Wait till the next tick so the connection state change is enacted,
* so aborting transports doesn't trigger redundant state changes */
Utils.nextTick(function() {
self.disconnectAllTransports();
});
}
if(state == 'connected' && !this.activeProtocol) {
Logger.logAction(Logger.LOG_ERROR, 'ConnectionManager.notifyState()', 'Broken invariant: attempted to go into connected state, but there is no active protocol');
}
/* implement the change and notify */
this.enactStateChange(change);
if(this.state.sendEvents) {
this.sendQueuedMessages();
} else if(!this.state.queueEvents) {
this.realtime.channels.propogateConnectionInterruption(state, change.reason);
this.failQueuedMessages(change.reason); // RTN7c
}
};
ConnectionManager.prototype.requestState = function(request) {
var state = request.state, self = this;
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.requestState()', 'requested state: ' + state + '; current state: ' + this.state.state);
if(state == this.state.state)
return; /* silently do nothing */
/* kill running timers, as this request supersedes them */
this.cancelTransitionTimer();
this.cancelRetryTimer();
/* for suspend timer check rather than cancel -- eg requesting a connecting
* state should not reset the suspend timer */
this.checkSuspendTimer(state);
if(state == 'connecting' && this.state.state == 'connected') return;
if(state == 'closing' && this.state.state == 'closed') return;
var newState = this.states[state],
change = new ConnectionStateChange(this.state.state, newState.state, null, (request.error || ConnectionError[newState.state]));
this.enactStateChange(change);
if(state == 'connecting') {
Utils.nextTick(function() { self.startConnect(); });
}
if(state == 'closing') {
this.closeImpl();
}
};
ConnectionManager.prototype.startConnect = function() {
if(this.state !== this.states.connecting) {
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.startConnect()', 'Must be in connecting state to connect, but was ' + this.state.state);
return;
}
var auth = this.realtime.auth,
self = this;
var connect = function() {
self.checkConnectionStateFreshness();
self.getTransportParams(function(transportParams) {
self.connectImpl(transportParams);
});
};
Logger.logAction(Logger.LOG_MINOR, 'ConnectionManager.startConnect()', 'starting connection');
this.startSuspendTimer();
this.startTransitionTimer(this.states.connecting);
if(auth.method === 'basic') {
connect();
} else {
var authCb = function(err) {
if(err) {
self.actOnErrorFromAuthorize(err);
} else {
connect();
}
};
if(this.errorReason && Auth.isTokenErr(this.errorReason)) {
/* Force a refetch of a new token */
auth._forceNewToken(null, null, authCb);
} else {
auth._ensureValidAuthCredentials(authCb);
}
}
};
/**
* There are three stages in connecting:
* - preference: if there is a cached transport preference, we try to connect
* on that. If that fails or times out we abort the attempt, remove the
* preference and fall back to base. If it succeeds, we try upgrading it if
* needed (will only be in the case where the preference is xhrs and the
* browser supports ws).
* - base: we try to connect with the best transport that we think will
* never fail for this browser (usually this is xhr_polling; for very old
* browsers will be jsonp, for node will be comet). If it doesn't work, we
* try fallback hosts.
* - upgrade: given a connected transport, we see if there are any better