-
Notifications
You must be signed in to change notification settings - Fork 37
/
ConnectionManager.java
1911 lines (1680 loc) · 71.5 KB
/
ConnectionManager.java
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
package io.ably.lib.transport;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import io.ably.lib.debug.DebugOptions;
import io.ably.lib.debug.DebugOptions.RawProtocolListener;
import io.ably.lib.http.HttpHelpers;
import io.ably.lib.realtime.AblyRealtime;
import io.ably.lib.realtime.Channel;
import io.ably.lib.realtime.CompletionListener;
import io.ably.lib.realtime.Connection;
import io.ably.lib.realtime.ConnectionState;
import io.ably.lib.realtime.ConnectionStateListener;
import io.ably.lib.realtime.ConnectionStateListener.ConnectionStateChange;
import io.ably.lib.rest.Auth;
import io.ably.lib.transport.ITransport.ConnectListener;
import io.ably.lib.transport.ITransport.TransportParams;
import io.ably.lib.transport.NetworkConnectivity.NetworkConnectivityListener;
import io.ably.lib.types.AblyException;
import io.ably.lib.types.ClientOptions;
import io.ably.lib.types.ConnectionDetails;
import io.ably.lib.types.ErrorInfo;
import io.ably.lib.types.ProtocolMessage;
import io.ably.lib.types.ProtocolSerializer;
import io.ably.lib.util.Log;
import io.ably.lib.util.PlatformAgentProvider;
import io.ably.lib.util.TimerUtil;
public class ConnectionManager implements ConnectListener {
final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
final ExecutorCompletionService<Void> executorCompletionService =
new ExecutorCompletionService<>(singleThreadExecutor);
/**************************************************************
* ConnectionManager
*
* This class is responsible for coordinating all actions that
* relate to transports and connection state.
*
* It comprises two principal parts:
* - An action queue, and a thread that performs those actions.
* Actions comprise connection state change requests, plus other
* actions that arise from transport state indications. An
* action Handler thread runs, except during idle times when
* there is no current or pending connection activity, that
* performs queued actions.
*
* - A state machine that represents the current connection state,
* and the possible transitions between states.
**************************************************************/
private static final String TAG = ConnectionManager.class.getName();
private static final String INTERNET_CHECK_URL = "https://internet-up.ably-realtime.com/is-the-internet-up.txt";
private static final String INTERNET_CHECK_OK = "yes";
/***********************************
* default errors
***********************************/
static ErrorInfo REASON_CLOSED = new ErrorInfo("Can't attach when not in an active state", 200, 10000);
static ErrorInfo REASON_DISCONNECTED = new ErrorInfo("Connection temporarily unavailable", 503, 80003);
static ErrorInfo REASON_SUSPENDED = new ErrorInfo("Connection unavailable", 503, 80002);
static ErrorInfo REASON_FAILED = new ErrorInfo("Connection failed", 400, 80000);
static ErrorInfo REASON_REFUSED = new ErrorInfo("Access refused", 401, 40100);
static ErrorInfo REASON_TOO_BIG = new ErrorInfo("Connection closed; message too large", 400, 40000);
/**
* Methods on the channels map owned by the {@link AblyRealtime} instance
* which the {@link ConnectionManager} needs access to.
*/
public interface Channels {
void onMessage(ProtocolMessage msg);
void suspendAll(ErrorInfo error, boolean notifyStateChange);
Iterable<Channel> values();
void transferToChannels(List<QueuedMessage> queuedMessages);
}
/***********************************
* a class encapsulating information
* associated with a currentState change
* request or notification
***********************************/
public static class StateIndication {
final ConnectionState state;
final ErrorInfo reason;
final String fallback;
final String currentHost;
final boolean reattachOnResumeFailure;
StateIndication(ConnectionState state) {
this(state, null);
}
public StateIndication(ConnectionState state, ErrorInfo reason) {
this(state, reason, null, null);
}
StateIndication(ConnectionState state, ErrorInfo reason, String fallback, String currentHost) {
this.state = state;
this.reason = reason;
this.fallback = fallback;
this.currentHost = currentHost;
this.reattachOnResumeFailure = false;
}
StateIndication(ConnectionState state, ErrorInfo reason, String fallback, String currentHost,
boolean reattachOnResumeFailure) {
this.state = state;
this.reason = reason;
this.fallback = fallback;
this.currentHost = currentHost;
this.reattachOnResumeFailure = reattachOnResumeFailure;
}
}
/*************************************
* a class encapsulating state machine
* information for a given state
*************************************/
public abstract class State {
public final ConnectionState state;
public final ErrorInfo defaultErrorInfo;
public final boolean queueEvents;
public final boolean sendEvents;
final boolean terminal;
public final long timeout;
State(ConnectionState state, boolean queueEvents, boolean sendEvents, boolean terminal, long timeout, ErrorInfo defaultErrorInfo) {
this.state = state;
this.queueEvents = queueEvents;
this.sendEvents = sendEvents;
this.terminal = terminal;
this.timeout = timeout;
this.defaultErrorInfo = defaultErrorInfo;
}
/**
* Called on the current state to determine the response to a
* give state change request.
* @param target: the state change request or event
* @return StateIndication result: the determined response to
* the request with the required state transition, if any. A
* null result indicates that there is no resulting transition.
*/
abstract StateIndication validateTransition(StateIndication target);
/**
* Called when the timeout occurs for the current state.
* @return StateIndication result: the determined response to
* the timeout with the required state transition, if any. A
* null result indicates that there is no resulting transition.
*/
StateIndication onTimeout() {
return null;
}
/**
* Perform a transition to this state.
* @param stateIndication: the transition request that triggered this transition
* @param change: the change event corresponding to this transition.
*/
void enact(StateIndication stateIndication, ConnectionStateChange change) {
if(change != null) {
/* if now connected, send queued messages, etc */
if(sendEvents) {
sendQueuedMessages();
} else if(!queueEvents) {
failQueuedMessages(stateIndication.reason);
}
for(final Channel channel : channels.values()) {
enactForChannel(stateIndication, change, channel);
}
}
}
/**
* Perform a transition to this state for a given channel.
* @param stateIndication: the transition request that triggered this transition
* @param change: the change event corresponding to this transition.
* @param channel: the channel
*/
void enactForChannel(StateIndication stateIndication, ConnectionStateChange change, Channel channel) {}
}
/**************************************************
* Initialized: the initial state
**************************************************/
class Initialized extends State {
Initialized() {
super(ConnectionState.initialized, true, false, false, 0, null);
}
@Override
StateIndication validateTransition(StateIndication target) {
/* we can transition to any other state, other than ourselves */
if(target.state == this.state) {
return null;
}
return target;
}
}
/**************************************************
* Connecting: a connection attempt is in progress
**************************************************/
class Connecting extends State {
Connecting() {
super(ConnectionState.connecting, true, false, false, Defaults.TIMEOUT_CONNECT, null);
}
@Override
StateIndication onTimeout() {
return checkSuspended(null);
}
@Override
StateIndication validateTransition(StateIndication target) {
/* we can transition to any other state */
return target;
}
@Override
void enact(StateIndication stateIndication, ConnectionStateChange change) {
super.enact(stateIndication, change);
connectImpl(stateIndication);
}
}
/**************************************************
* Connected: a connection is established
**************************************************/
class Connected extends State {
Connected() {
super(ConnectionState.connected, false, true, false, 0, null);
}
@Override
StateIndication validateTransition(StateIndication target) {
if(target.state == this.state) {
/* RTN24: no currentState change, so no transition, required, but there will be an update event;
* connected is special case because we want to deliver reauth notifications to listeners as an update */
addAction(new UpdateAction(null));
return null;
}
/* we can transition to any other state */
return target;
}
@Override
void enactForChannel(StateIndication stateIndication, ConnectionStateChange change, Channel channel) {
channel.setConnected(stateIndication.reattachOnResumeFailure);
}
}
/**************************************************
* Disconnected: no connection is established, but
* a reconnection attempt will be made on timer
* expiry, anticipating preservation of connection
* state on reconnection
**************************************************/
class Disconnected extends State {
Disconnected() {
super(ConnectionState.disconnected, true, false, false, Defaults.TIMEOUT_DISCONNECT, REASON_DISCONNECTED);
}
@Override
StateIndication validateTransition(StateIndication target) {
/* we can't transition to ourselves */
if(target.state == this.state) {
return null;
}
/* a closing event will transition directly to closed */
if(target.state == ConnectionState.closing) {
return new StateIndication(ConnectionState.closed);
}
/* otherwise, the transition is valid */
return target;
}
@Override
StateIndication onTimeout() {
return new StateIndication(ConnectionState.connecting);
}
@Override
void enactForChannel(StateIndication stateIndication, ConnectionStateChange change, Channel channel) {
/* (RTL3e) If the connection currentState enters the
* DISCONNECTED currentState, it will have no effect on the
* channel states. */
}
@Override
void enact(StateIndication stateIndication, ConnectionStateChange change) {
super.enact(stateIndication, change);
clearTransport();
if(change.previous == ConnectionState.connected) {
setSuspendTime();
/* we were connected, so retry immediately */
if(!suppressRetry) {
requestState(ConnectionState.connecting);
}
}
}
}
/**************************************************
* Suspended: no connection is established. A
* reconnection attempt will be made on timer expiry
* but there will be no continuity of connection
* state on reconnection
**************************************************/
class Suspended extends State {
Suspended() {
super(ConnectionState.suspended, false, false, false, Defaults.connectionStateTtl, REASON_SUSPENDED);
}
@Override
StateIndication validateTransition(StateIndication target) {
/* we can't transition to ourselves */
if(target.state == this.state) {
return null;
}
/* a closing event will transition directly to closed */
if(target.state == ConnectionState.closing) {
return new StateIndication(ConnectionState.closed);
}
/* otherwise, the transition is valid */
return target;
}
@Override
StateIndication onTimeout() {
return new StateIndication(ConnectionState.connecting);
}
@Override
void enactForChannel(StateIndication stateIndication, ConnectionStateChange change, Channel channel) {
/* (RTL3c) If the connection currentState enters the SUSPENDED
* currentState, then an ATTACHING or ATTACHED channel currentState
* will transition to SUSPENDED. */
channel.setSuspended(defaultErrorInfo, true);
}
}
/**************************************************
* Closing: a close sequence is in progress
**************************************************/
class Closing extends State {
Closing() {
super(ConnectionState.closing, false, false, false, Defaults.TIMEOUT_CONNECT, REASON_CLOSED);
}
@Override
StateIndication validateTransition(StateIndication target) {
/* we can't transition to ourselves */
if(target.state == this.state) {
return null;
}
/* any disconnection event will transition directly to closed */
if(target.state == ConnectionState.disconnected || target.state == ConnectionState.suspended) {
return new StateIndication(ConnectionState.closed);
}
/* otherwise, the transition is valid */
return target;
}
@Override
StateIndication onTimeout() {
return new StateIndication(ConnectionState.closed);
}
@Override
void enact(StateIndication stateIndication, ConnectionStateChange change) {
super.enact(stateIndication, change);
boolean closed = closeImpl();
if(closed) {
addAction(new AsynchronousStateChangeAction(ConnectionState.closed));
}
}
}
/**************************************************
* Closed: the connection is closed, and no
* reconnection attempt will be made unless
* explicitly requested
**************************************************/
class Closed extends State {
Closed() {
super(ConnectionState.closed, false, false, true, 0, REASON_CLOSED);
}
@Override
StateIndication validateTransition(StateIndication target) {
/* we only leave the closed state via a connection attempt */
if(target.state == ConnectionState.connecting) {
return target;
}
/* otherwise, the transition is not valid */
return null;
}
@Override
void enactForChannel(StateIndication stateIndication, ConnectionStateChange change, Channel channel) {
/* (RTL3b) If the connection currentState enters the CLOSED
* currentState, then an ATTACHING or ATTACHED channel currentState
* will transition to DETACHED. */
channel.setConnectionClosed(REASON_CLOSED);
}
}
/**************************************************
* Failed: there is no connection, and there has
* been an error, either in options validation or
* as a response to a connection attempt, that
* implies no new connection attempt will succeed.
* No reconnection attempt will be made unless
* explicitly requested
**************************************************/
class Failed extends State {
Failed() {
super(ConnectionState.failed, false, false, true, 0, REASON_FAILED);
}
@Override
StateIndication validateTransition(StateIndication target) {
/* we only leave the failed state via a connection attempt */
if(target.state == ConnectionState.connecting) {
return target;
}
/* otherwise, the transition is not valid */
return null;
}
@Override
void enactForChannel(StateIndication stateIndication, ConnectionStateChange change, Channel channel) {
/* (RTL3a) If the connection currentState enters the FAILED
* currentState, then an ATTACHING or ATTACHED channel currentState
* will transition to FAILED, set the
* Channel#errorReason and emit the error event. */
channel.setConnectionFailed(stateIndication.reason);
}
@Override
void enact(StateIndication stateIndication, ConnectionStateChange change) {
super.enact(stateIndication, change);
clearTransport();
}
}
public ErrorInfo getStateErrorInfo() {
return stateError != null ? stateError : currentState.defaultErrorInfo;
}
public boolean isActive() {
return currentState.queueEvents || currentState.sendEvents;
}
/**
* Listens for connection state changes.
*
* The close() method must be called when the ConnectionWaiter is no longer needed.
*/
private class ConnectionWaiter implements ConnectionStateListener {
private ConnectionStateChange change;
private boolean closed = false;
/**
* Create a ConnectionWaiter as a connection listener.
*/
private ConnectionWaiter() {
connection.on(this);
}
/**
* Wait for a currentState change notification
*/
private synchronized ErrorInfo waitForChange() {
if (closed) {
throw new IllegalStateException("Already closed.");
}
Log.d(TAG, "ConnectionWaiter.waitFor()");
if (change == null) {
try { wait(); } catch(InterruptedException e) {}
}
Log.d(TAG, "ConnectionWaiter.waitFor done: currentState=" + currentState + ")");
ErrorInfo reason = change.reason;
change = null;
return reason;
}
/**
* ConnectionStateListener interface
*/
@Override
public synchronized void onConnectionStateChanged(ConnectionStateChange state) {
change = state;
notify();
}
/**
* Remove this ConnectionWaiter as a connection listener.
*/
private void close() {
// This method is explicitly not synchronized. There may be a case for this in the
// future, however its addition is designed to be lightweight with minimal impact.
if (closed) {
return;
}
closed = true;
connection.off(this);
}
}
/***********************
* Actions
***********************/
/**
* A class that encapsulates actions to perform by the ConnectionManager
*/
private interface Action extends Runnable {}
/**
* An class that performs a state transition
*/
private abstract class StateChangeAction {
protected final ITransport transport;
protected final StateIndication stateIndication;
protected ConnectionStateChange change;
StateChangeAction(ITransport transport, StateIndication stateIndication) {
this.transport = transport;
this.stateIndication = stateIndication;
}
/**
* Make the change to the ConnectionManager currentState represented by this Action
*/
protected void setState() {
change = ConnectionManager.this.setState(transport, stateIndication);
}
protected void enactState() {
if(change != null) {
if(change.current != change.previous) {
/* broadcast currentState change */
connection.onConnectionStateChange(change);
}
/* implement the state change */
states.get(stateIndication.state).enact(stateIndication, change);
if(currentState.terminal) {
clearTransport();
}
}
}
}
/**
* An Action that enacts a state transition, making the ConnectionManager state change
* synchronously. This is for instances such as any transition away from the connected
* state, where the state is updated synchronously with the transport state change.
* This ensures that there is no possibility of an attempt to send on the transport
* after it has indicated that it is not available.
*/
private class SynchronousStateChangeAction extends StateChangeAction implements Action {
SynchronousStateChangeAction(ITransport transport, StateIndication stateIndication) {
super(transport, stateIndication);
setState();
}
@Override
public void run() {
enactState();
}
}
/**
* An Action that enacts a state transition, making the ConnectionManager state change
* asynchronously. This applies to all transitions that are not transitions away from
* the connected state.
*/
private class AsynchronousStateChangeAction extends StateChangeAction implements Action{
AsynchronousStateChangeAction(ConnectionState state) {
super(null, new StateIndication(state, null));
}
AsynchronousStateChangeAction(ITransport transport, StateIndication stateIndication) {
super(transport, stateIndication);
}
@Override
public void run() {
setState();
enactState();
}
}
/**
* An Action that performs an inband reauthorisation
*/
private class ReauthAction implements Action {
@Override
public void run() {
handleReauth();
}
}
/**
* An Action that handles dissemination of update events arising from a
* connected -> connected transition
*/
private class UpdateAction implements Action {
private final ErrorInfo reason;
UpdateAction(ErrorInfo reason) {
this.reason = reason;
}
@Override
public void run() {
connection.emitUpdate(reason);
}
}
/**
* A queue of Actions awaiting processing
*/
private static class ActionQueue extends ArrayDeque<Action> {
public synchronized boolean add(Action action) {
return super.add(action);
}
public synchronized Action poll() {
return super.poll();
}
public synchronized Action peek() {
return super.peek();
}
public synchronized int size() {
return super.size();
}
}
/**
* Append an action to the pending action queue
* @param action: the action
*/
private synchronized void addAction(Action action) {
actionQueue.add(action);
notifyAll();
}
/**
* A handler that runs in a dedicated Thread that processes queued actions
*/
class ActionHandler implements Runnable {
public void run() {
while(true) {
/*
* Until we're committed to exit we:
* - wait for an action or timeout
* - given an action, perform the action asynchronously;
* - if a timeout, perform the timeout state transition
*/
/* Hold the lock until we obtain an action */
synchronized(ConnectionManager.this) {
while(actionQueue.size() == 0) {
/* if we're in a terminal state, then this thread is done */
if(currentState.terminal) {
/* indicate that this thread is committed to die */
handlerThread = null;
stopConnectivityListener();
return;
}
/* wait for an action event or for expiry of the current currentState */
tryWait(currentState.timeout);
/* if during the wait some action was requested, handle it */
Action act = actionQueue.peek();
if (act != null) {
Log.d(TAG, "Wait ended by action: " + act.toString());
break;
}
/* if our currentState wants us to retry on timer expiry, do that */
if (!suppressRetry) {
StateIndication nextState = currentState.onTimeout();
if (nextState != null) {
requestState(nextState);
}
}
}
}
/* perform outstanding actions, without the ConnectionManager locked */
Action deferredAction;
while((deferredAction = actionQueue.poll()) != null) {
try {
deferredAction.run();
} catch(Exception e) {
Log.e(TAG, "Action invocation failed with exception: action = " + deferredAction.toString(), e);
}
}
}
}
}
/***********************
* ConnectionManager
***********************/
public ConnectionManager(final AblyRealtime ably, final Connection connection, final Channels channels, final PlatformAgentProvider platformAgentProvider) throws AblyException {
this.ably = ably;
this.connection = connection;
this.channels = channels;
this.platformAgentProvider = platformAgentProvider;
ClientOptions options = ably.options;
this.hosts = new Hosts(options.realtimeHost, Defaults.HOST_REALTIME, options);
/* debug options */
ITransport.Factory transportFactory = null;
RawProtocolListener protocolListener = null;
if(options instanceof DebugOptions) {
protocolListener = ((DebugOptions) options).protocolListener;
transportFactory = ((DebugOptions) options).transportFactory;
}
this.protocolListener = protocolListener;
this.transportFactory = (transportFactory != null) ? transportFactory : Defaults.TRANSPORT;
/* construct all states */
states.put(ConnectionState.initialized, new Initialized());
states.put(ConnectionState.connecting, new Connecting());
states.put(ConnectionState.connected, new Connected());
states.put(ConnectionState.disconnected, new Disconnected());
states.put(ConnectionState.suspended, new Suspended());
states.put(ConnectionState.closing, new Closing());
states.put(ConnectionState.closed, new Closed());
states.put(ConnectionState.failed, new Failed());
currentState = states.get(ConnectionState.initialized);
setSuspendTime();
}
/*********************
* host management
*********************/
/* This is only here for the benefit of ConnectionManagerTest. */
public String getHost() {
return lastUsedHost;
}
/*********************
* states API
*********************/
public synchronized State getConnectionState() {
return currentState;
}
public synchronized void connect() {
/* connect() is the only action that will bring the ConnectionManager out of a terminal currentState */
if(currentState.terminal || currentState.state == ConnectionState.initialized) {
startup();
}
requestState(ConnectionState.connecting);
}
public void close() {
requestState(ConnectionState.closing);
}
public void requestState(ConnectionState state) {
requestState(new StateIndication(state, null));
}
public void requestState(StateIndication state) {
requestState(null, state);
}
private synchronized void requestState(ITransport transport, StateIndication stateIndication) {
Log.v(TAG, "requestState(): requesting " + stateIndication.state + "; id = " + connection.id);
addAction(new AsynchronousStateChangeAction(transport, stateIndication));
}
private synchronized ConnectionStateChange setState(ITransport transport, StateIndication stateIndication) {
/* check validity of transport */
if (transport != null && transport != this.transport) {
Log.v(TAG, "setState: action received for superseded transport; discarding");
return null;
}
/* check validity of transition */
StateIndication validatedStateIndication = currentState.validateTransition(stateIndication);
if (validatedStateIndication == null) {
Log.v(TAG, "setState(): not transitioning; not a valid transition " + stateIndication.state);
return null;
}
if (stateIndication.state == ConnectionState.suspended || stateIndication.state == ConnectionState.connected) {
this.disconnectedRetryCount = 0;
}
/* update currentState */
ConnectionState newConnectionState = validatedStateIndication.state;
State newState = states.get(newConnectionState);
ErrorInfo reason = validatedStateIndication.reason;
if (reason == null) {
reason = newState.defaultErrorInfo;
}
Log.v(TAG, "setState(): setting " + newState.state + "; reason " + reason);
long retryDelay = newState.timeout;
if (newState.state == ConnectionState.disconnected) {
this.disconnectedRetryCount++;
retryDelay = TimerUtil.getRetryTime((int) newState.timeout, this.disconnectedRetryCount);
}
ConnectionStateChange change = new ConnectionStateChange(currentState.state, newConnectionState, retryDelay, reason);
currentState = newState;
stateError = reason;
return change;
}
/*********************
* ping API
*********************/
public void ping(final CompletionListener listener) {
HeartbeatWaiter waiter = new HeartbeatWaiter(listener);
if(currentState.state != ConnectionState.connected) {
waiter.onError(new ErrorInfo("Unable to ping service; not connected", 40000, 400));
return;
}
synchronized(heartbeatWaiters) {
heartbeatWaiters.add(waiter);
waiter.start();
}
try {
send(new ProtocolMessage(ProtocolMessage.Action.heartbeat), false, null);
} catch (AblyException e) {
waiter.onError(e.errorInfo);
}
}
/**
* A thread that waits for completion of a ping
*/
private class HeartbeatWaiter extends Thread {
private final CompletionListener listener;
HeartbeatWaiter(CompletionListener listener) {
this.listener = listener;
}
private void onSuccess() {
clear();
if(listener != null) {
listener.onSuccess();
}
}
private void onError(ErrorInfo reason) {
clear();
if(listener != null) {
listener.onError(reason);
}
}
private boolean clear() {
boolean pending = heartbeatWaiters.remove(this);
if(pending) {
interrupt();
}
return pending;
}
@Override
public void run() {
boolean pending;
synchronized(heartbeatWaiters) {
try {
heartbeatWaiters.wait(HEARTBEAT_TIMEOUT);
} catch (InterruptedException ie) {
}
pending = clear();
}
if(pending) {
onError(new ErrorInfo("Timed out waiting for heartbeat response", 50000, 500));
} else {
onSuccess();
}
}
}
/***************************************
* auth event handling
***************************************/
/**
* (RTC8) For a realtime client, Auth.authorize instructs the library to
* obtain a token using the provided tokenParams and authOptions and upgrade
* the current connection to use that token; or if not currently connected,
* to connect with the token.
*/
public void onAuthUpdated(final String token, final boolean waitForResponse) throws AblyException {
final ConnectionWaiter waiter = new ConnectionWaiter();
try {
switch(currentState.state) {
case connected:
/* (RTC8a) If the connection is in the CONNECTED currentState and
* auth.authorize is called or Ably requests a re-authentication
* (see RTN22), the client must obtain a new token, then send an
* AUTH ProtocolMessage to Ably with an auth attribute
* containing an AuthDetails object with the token string. */
try {
ProtocolMessage msg = new ProtocolMessage(ProtocolMessage.Action.auth);
msg.auth = new ProtocolMessage.AuthDetails(token);
send(msg, false, null);
} catch (AblyException e) {
/* The send failed. Close the transport; if a subsequent
* reconnect succeeds, it will be with the new token. */
Log.v(TAG, "onAuthUpdated: closing transport after send failure");
transport.close();
}
break;
case connecting:
/* Close the connecting transport. */
Log.v(TAG, "onAuthUpdated: closing connecting transport");
ErrorInfo disconnectError = new ErrorInfo("Aborting incomplete connection with superseded auth params", 503, 80003);
requestState(new StateIndication(ConnectionState.disconnected, disconnectError, null, null));
/* Start a new connection attempt. */
connect();
break;
default:
/* Start a new connection attempt. */
connect();
break;
}
if(!waitForResponse) {
return;
}
/* Wait for a currentState transition into anything other than connecting or
* disconnected. Note that this includes the case that the connection
* was already connected, and the AUTH message prompted the server to
* send another connected message. */
boolean waitingForConnected = true;
while (waitingForConnected) {
final ErrorInfo reason = waiter.waitForChange();
final ConnectionState connectionState = currentState.state;
switch (connectionState) {
case connected:
Log.v(TAG, "onAuthUpdated: got connected");
waitingForConnected = false;
break;
case connecting:
case disconnected:
Log.v(TAG, "onAuthUpdated: " + connectionState);
break;