-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathconnection_failures_spec.rb
1718 lines (1448 loc) · 69.5 KB
/
connection_failures_spec.rb
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
# encoding: utf-8
require 'spec_helper'
describe Ably::Realtime::Connection, 'failures', :event_machine do
let(:connection) { client.connection }
vary_by_protocol do
let(:default_options) do
{ key: api_key, environment: environment, protocol: protocol }
end
let(:client_options) { default_options }
let(:client) do
auto_close Ably::Realtime::Client.new(client_options)
end
let(:rest_client) do
Ably::Rest::Client.new(default_options)
end
context 'authentication failure' do
let(:client_options) do
default_options.merge(key: invalid_key, log_level: :none)
end
context 'when API key is invalid' do
context 'with invalid app part of the key' do
let(:invalid_key) { 'not_an_app.invalid_key_name:invalid_key_value' }
it 'enters the failed state and returns a not found error' do
connection.on(:failed) do |connection_state_change|
error = connection_state_change.reason
expect(connection.state).to eq(:failed)
# TODO: Check error type is an InvalidToken exception
expect(error.status).to eq(404)
expect(error.code).to eq(40400) # not found
stop_reactor
end
end
end
context 'with invalid key name part of the key' do
let(:invalid_key) { "#{app_id}.invalid_key_name:invalid_key_value" }
it 'enters the failed state and returns an authorization error' do
connection.on(:failed) do |connection_state_change|
error = connection_state_change.reason
expect(connection.state).to eq(:failed)
# TODO: Check error type is a TokenNotFound exception
expect(error.status).to eq(401)
expect(error.code).to eq(40400) # not found
stop_reactor
end
end
end
end
context 'with auth_url' do
context 'opening a new connection' do
context 'request fails due to network failure' do
let(:client_options) { default_options.reject { |k, v| k == :key }.merge(auth_url: "http://#{random_str}.domain.will.never.resolve.to/path", log_level: :fatal) }
specify 'the connection moves to the disconnected state and tries again, returning again to the disconnected state (#RSA4c, #RSA4c1, #RSA4c2)' do
states = Hash.new { |hash, key| hash[key] = [] }
connection.once(:connected) { raise "Connection can never move to connected because of auth failures" }
connection.on do |connection_state|
states[connection_state.current.to_sym] << Time.now
if states[:disconnected].count == 2 && connection_state.current == :disconnected
expect(connection.error_reason).to be_a(Ably::Exceptions::ConnectionError)
expect(connection.error_reason.message).to match(/auth_url/)
EventMachine.add_timer(2) do
expect(states.keys).to include(:connecting, :disconnected)
expect(states[:connecting].count).to eql(2)
expect(states[:connected].count).to eql(0)
stop_reactor
end
end
end
end
end
context 'request fails due to invalid content', :webmock do
let(:auth_endpoint) { "http://#{random_str}.domain.will.never.resolve.to/authenticate" }
let(:client_options) { default_options.reject { |k, v| k == :key }.merge(auth_url: auth_endpoint, log_level: :fatal) }
before do
stub_request(:get, auth_endpoint).
to_return(:status => 200, :body => "", :headers => { "Content-type" => "text/html" })
end
specify 'the connection moves to the disconnected state and tries again, returning again to the disconnected state (#RSA4c, #RSA4c1, #RSA4c2)' do
states = Hash.new { |hash, key| hash[key] = [] }
connection.once(:connected) { raise "Connection can never move to connected because of auth failures" }
connection.on do |connection_state|
states[connection_state.current.to_sym] << Time.now
if states[:disconnected].count == 2 && connection_state.current == :disconnected
expect(connection.error_reason).to be_a(Ably::Exceptions::ConnectionError)
expect(connection.error_reason.message).to match(/auth_url/)
expect(connection.error_reason.message).to match(/Content Type.*not supported/)
EventMachine.add_timer(2) do
expect(states.keys).to include(:connecting, :disconnected)
expect(states[:connecting].count).to eql(2)
expect(states[:connected].count).to eql(0)
stop_reactor
end
end
end
end
end
context 'request fails due to slow response and subsequent timeout', :webmock, em_timeout: (Ably::Rest::Client::HTTP_DEFAULTS.fetch(:request_timeout) + 5) * 2 do
let(:auth_url) { "http://#{random_str}.domain.will.be.stubbed/path" }
let(:client_options) { default_options.reject { |k, v| k == :key }.merge(auth_url: auth_url, log_level: :fatal) }
# Timeout +5 seconds, beyond default allowed timeout
before do
stub_request(:get, auth_url).
to_return do |request|
sleep Ably::Rest::Client::HTTP_DEFAULTS.fetch(:request_timeout) + 5
{ status: [500, "Internal Server Error"] }
end
end
specify 'the connection moves to the disconnected state and tries again, returning again to the disconnected state (#RSA4c, #RSA4c1, #RSA4c2)' do
states = Hash.new { |hash, key| hash[key] = [] }
connection.once(:connected) { raise "Connection can never move to connected because of auth failures" }
connection.on do |connection_state|
states[connection_state.current.to_sym] << Time.now
if states[:disconnected].count == 2 && connection_state.current == :disconnected
expect(connection.error_reason).to be_a(Ably::Exceptions::ConnectionError)
expect(connection.error_reason.message).to match(/auth_url/)
EventMachine.add_timer(2) do
expect(states.keys).to include(:connecting, :disconnected)
expect(states[:connecting].count).to eql(2)
expect(states[:connected].count).to eql(0)
stop_reactor
end
end
end
end
end
context 'request fails once due to slow response but succeeds the second time' do
let(:auth_url) { "http://#{random_str}.domain.will.be.stubbed/path" }
let(:client_options) { default_options.reject { |k, v| k == :key }.merge(auth_url: auth_url, log_level: :fatal) }
# Timeout +5 seconds, beyond default allowed timeout
before do
token_response = Ably::Rest::Client.new(default_options).auth.request_token
WebMock.enable!
stub_request(:get, auth_url).
to_return do |request|
sleep Ably::Rest::Client::HTTP_DEFAULTS.fetch(:request_timeout)
{ status: [500, "Internal Server Error"] }
end.then.
to_return(:status => 201, :body => token_response.to_json, :headers => { 'Content-Type' => 'application/json' })
stub_request(:get, 'https://internet-up.ably-realtime.com/is-the-internet-up.txt')
.with(
headers: {
'Accept-Encoding' => 'gzip, compressed',
'Connection' => 'close',
'Host' => 'internet-up.ably-realtime.com',
'User-Agent' => 'EventMachine HttpClient'
}
).to_return(status: 200, body: 'yes\n', headers: { 'Content-Type' => 'text/plain' })
end
specify 'the connection moves to the disconnected state and tries again, returning again to the disconnected state (#RSA4c, #RSA4c1, #RSA4c2)' do
states = Hash.new { |hash, key| hash[key] = [] }
connection.once(:connected) do
expect(states[:disconnected].count).to eql(1)
expect(states[:connecting].count).to eql(2)
stop_reactor
end
connection.on do |connection_state|
states[connection_state.current.to_sym] << Time.now
end
end
end
end
context 'existing CONNECTED connection' do
context 'authorize request failure leaves connection in existing condition' do
let(:auth_options) { { auth_url: "http://#{random_str}.domain.will.never.resolve.to/path" } }
let(:client_options) { default_options.merge(use_token_auth: true, log_level: :fatal) }
specify 'the connection remains in the CONNECTED state and authorize fails (#RSA4c, #RSA4c1, #RSA4c3)' do
connection.once(:connected) do
connection.on { raise "State should not change and should stay connected" }
client.auth.authorize(nil, auth_options).tap do |deferrable|
deferrable.callback { raise "Authorize should not succeed" }
deferrable.errback do |err|
expect(err).to be_a(Ably::Exceptions::ConnectionError)
expect(err.message).to match(/auth_url/)
EventMachine.add_timer(1) do
expect(connection).to be_connected
connection.off
stop_reactor
end
end
end
end
end
end
end
end
context 'with auth_callback' do
context 'opening a new connection' do
context 'when callback fails due to an exception' do
let(:client_options) { default_options.reject { |k, v| k == :key }.merge(auth_callback: lambda { |token_params| raise "Cannot issue token" }, log_level: :fatal) }
it 'the connection moves to the disconnected state and tries again, returning again to the disconnected state (#RSA4c, #RSA4c1, #RSA4c2)' do
states = Hash.new { |hash, key| hash[key] = [] }
connection.once(:connected) { raise "Connection can never move to connected because of auth failures" }
connection.on do |connection_state|
states[connection_state.current.to_sym] << Time.now
if states[:disconnected].count == 2 && connection_state.current == :disconnected
expect(connection.error_reason).to be_a(Ably::Exceptions::ConnectionError)
expect(connection.error_reason.message).to match(/auth_callback/)
EventMachine.add_timer(2) do
expect(states.keys).to include(:connecting, :disconnected)
expect(states[:connecting].count).to eql(2)
expect(states[:connected].count).to eql(0)
stop_reactor
end
end
end
end
end
context 'existing CONNECTED connection' do
context 'when callback fails due to the request taking longer than realtime_request_timeout' do
let(:request_timeout) { 3 }
let(:client_options) { default_options.merge(
realtime_request_timeout: request_timeout,
use_token_auth: true,
log_level: :fatal)
}
let(:auth_options) { { auth_callback: lambda { |token_params| sleep 10 }, } }
it 'the authorization request fails as configured in the realtime_request_timeout (#RSA4c, #RSA4c1, #RSA4c3)' do
connection.once(:connected) do
connection.on { raise "State should not change and should stay connected" }
client.auth.authorize(nil, auth_options).tap do |deferrable|
deferrable.callback { raise "Authorize should not succeed" }
deferrable.errback do |err|
expect(err).to be_a(Ably::Exceptions::ConnectionError)
expect(err.message).to match(/auth_callback/)
EventMachine.add_timer(1) do
expect(connection).to be_connected
connection.off
stop_reactor
end
end
end
end
end
end
end
end
end
end
context 'automatic connection retry' do
context 'with invalid WebSocket host' do
let(:retry_every_for_tests) { 0.2 }
let(:max_time_in_state_for_tests) { 0.6 }
let(:client_failure_options) do
default_options.merge(
log_level: :none,
disconnected_retry_timeout: retry_every_for_tests,
suspended_retry_timeout: retry_every_for_tests,
max_connection_state_ttl: max_time_in_state_for_tests
)
end
# retry immediately after failure, then one retry every :retry_every_for_tests
let(:expected_retry_attempts) { 1 + (max_time_in_state_for_tests / retry_every_for_tests).round }
let(:state_changes) { Hash.new { |hash, key| hash[key] = 0 } }
let(:timer) { Hash.new }
let(:client_options) do
client_failure_options.merge(realtime_host: 'non.existent.host')
end
def count_state_changes
EventMachine.next_tick do
%w(connecting disconnected failed suspended).each do |state|
connection.on(state.to_sym) { state_changes[state.to_sym] += 1 }
end
end
end
def start_timer
timer[:start] = Time.now
end
def time_passed
Time.now.to_f - timer[:start].to_f
end
context 'when disconnected' do
it 'enters the suspended state after multiple attempts to connect' do
connection.on(:failed) { raise 'Connection should not have reached :failed state yet' }
count_state_changes && start_timer
connection.once(:suspended) do
expect(connection.state).to eq(:suspended)
expect(state_changes[:connecting]).to eql(expected_retry_attempts + 1) # allow for initial connecting attempt
expect(state_changes[:disconnected]).to eql(expected_retry_attempts)
expect(time_passed).to be > max_time_in_state_for_tests
stop_reactor
end
end
context 'for the first time' do
let(:client_options) do
default_options.merge(realtime_host: 'non.existent.host', disconnected_retry_timeout: 2, log_level: :error)
end
it 'reattempts connection immediately and then waits disconnected_retry_timeout for a subsequent attempt' do
expect(connection.defaults[:disconnected_retry_timeout]).to eql(2)
connection.once(:disconnected) do
started_at = Time.now.to_f
connection.once(:disconnected) do
expect(Time.now.to_f - started_at).to be < 1
started_at = Time.now.to_f
connection.once(:disconnected) do
expect(Time.now.to_f - started_at).to be > 2
stop_reactor
end
end
end
end
end
describe '#close' do
it 'transitions connection state to :closed' do
connection.on(:connected) { raise 'Connection should not have reached :connected state' }
connection.on(:failed) { raise 'Connection should not have reached :failed state yet' }
connection.once(:disconnected) do
expect(connection.state).to eq(:disconnected)
connection.on(:closed) do
expect(connection.state).to eq(:closed)
stop_reactor
end
connection.close
end
end
end
end
context 'when connection state is :suspended' do
it 'stays in the suspended state after any number of reconnection attempts' do
connection.on(:connected) { raise 'Connection should not have reached :connected state' }
connection.once(:suspended) do
count_state_changes && start_timer
EventMachine.add_timer((retry_every_for_tests + 0.1) * 10) do
expect(connection.state).to eq(:suspended)
expect(state_changes[:connecting]).to be >= 10
expect(state_changes[:suspended]).to be >= 10
expect(state_changes[:disconnected]).to eql(0)
stop_reactor
end
end
end
context 'for the first time' do
let(:client_options) do
default_options.merge(suspended_retry_timeout: 2, max_connection_state_ttl: 0, log_level: :error)
end
it 'waits suspended_retry_timeout before attempting to reconnect' do
expect(client.connection.defaults[:suspended_retry_timeout]).to eql(2)
connection.once(:connected) do
connection.transition_state_machine :suspended
allow(connection).to receive(:current_host).and_return('does.not.exist.com')
started_at = Time.now.to_f
connection.once(:connecting) do
expect(Time.now.to_f - started_at).to be > 1.75
started_at = Time.now.to_f
connection.once(:connecting) do
expect(Time.now.to_f - started_at).to be > 1.75
connection.once(:suspended) do
stop_reactor
end
end
end
end
end
end
describe '#close' do
it 'transitions connection state to :closed' do
connection.on(:connected) { raise 'Connection should not have reached :connected state' }
connection.once(:suspended) do
expect(connection.state).to eq(:suspended)
connection.on(:closed) do
expect(connection.state).to eq(:closed)
stop_reactor
end
connection.close
end
end
end
end
context 'when connection state is :failed' do
describe '#close' do
it 'will not transition state to :close and fails with an InvalidStateChange exception' do
connection.on(:connected) { raise 'Connection should not have reached :connected state' }
connection.once(:suspended) do
connection.transition_state_machine :failed
end
connection.once(:failed) do
expect(connection.state).to eq(:failed)
connection.close.errback do |error|
expect(error).to be_a(Ably::Exceptions::InvalidStateChange)
expect(error.message).to match(/Unable to transition from failed => closing/)
stop_reactor
end
end
end
end
end
context '#error_reason' do
[:disconnected, :suspended, :failed].each do |state|
it "contains the error when state is #{state}" do
connection.on(state) do |connection_state_change|
error = connection_state_change.reason
expect(connection.error_reason).to eq(error)
expect(connection.error_reason.code).to eql(80000)
stop_reactor
end
connection.once(:suspended) do |connection_state_change|
connection.transition_state_machine :failed, reason: connection_state_change.reason
end
end
end
it 'is reset to nil when :connected' do
connection.once(:disconnected) do |error|
# stub the host so that the connection connects
allow(connection).to receive(:determine_host).and_yield(TestApp.instance.realtime_host)
connection.once(:connected) do
expect(connection.error_reason).to be_nil
stop_reactor
end
end
end
it 'is reset to nil when :closed' do
connection.once(:disconnected) do |error|
connection.close do
expect(connection.error_reason).to be_nil
stop_reactor
end
end
end
end
end
describe '#connect' do
let(:timeout) { 1.5 }
let(:client_options) do
default_options.merge(
log_level: :none,
realtime_request_timeout: timeout,
)
end
before do
connection.on(:connected) { raise "Connection should not open in this test as CONNECTED ProtocolMessage is never received" }
connection.once(:connecting) do
# don't process any incoming ProtocolMessages so the connection never opens
connection.__incoming_protocol_msgbus__.unsubscribe
end
end
context 'connection opening times out' do
it 'attempts to reconnect' do
started_at = Time.now
connection.once(:disconnected) do
expect(Time.now.to_f - started_at.to_f).to be > timeout
connection.once(:connecting) do
stop_reactor
end
end
connection.connect
end
context 'when retry intervals are stubbed to attempt reconnection quickly' do
let(:client_options) do
default_options.merge(
log_level: :error,
disconnected_retry_timeout: 0.1,
suspended_retry_timeout: 0.1,
max_connection_state_ttl: 0.2,
realtime_host: 'non.existent.host'
)
end
it 'never calls the provided success block', em_timeout: 10 do
connection.connect do
raise 'success block should not have been called'
end
connection.once(:suspended) do
connection.once(:suspended) do
stop_reactor
end
end
end
end
end
end
end
context 'connection resume' do
let(:channel_name) { random_str }
let(:channel) { client.channel(channel_name) }
let(:publishing_client) do
auto_close Ably::Realtime::Client.new(client_options)
end
let(:publishing_client_channel) { publishing_client.channel(channel_name) }
let(:client_options) { default_options.merge(log_level: :none) }
def fail_if_suspended_or_failed
connection.on(:suspended) { raise 'Connection should not have reached :suspended state' }
connection.on(:failed) { raise 'Connection should not have reached :failed state' }
end
context 'when DISCONNECTED ProtocolMessage received from the server' do
it 'reconnects automatically and immediately (#RTN15a)' do
fail_if_suspended_or_failed
connection.once(:connected) do
connection.once(:disconnected) do
disconnected_at = Time.now.to_f
connection.once(:connecting) do
expect(Time.now.to_f).to be_within(0.25).of(disconnected_at)
connection.once(:connected) do
state_history = connection.state_history.map { |transition| transition[:state].to_sym }
expect(state_history).to eql([:connecting, :connected, :disconnected, :connecting, :connected])
stop_reactor
end
end
end
protocol_message = Ably::Models::ProtocolMessage.new(action: Ably::Models::ProtocolMessage::ACTION.Disconnected.to_i)
connection.__incoming_protocol_msgbus__.publish :protocol_message, protocol_message
end
end
context 'when protocolMessage contains token error' do
context "library does not have a means to renew the token (#RTN15h1)" do
let(:auth_url) { 'https://echo.ably.io/createJWT' }
let(:token) { Faraday.get("#{auth_url}?keyName=#{key_name}&keySecret=#{key_secret}").body }
let(:client_options) { default_options.merge(token: token, log_level: :none) }
let(:error_message) { 'error_message' }
it 'moves connection state to failed' do
connection.on(:failed) do |connection_state_change|
expect(connection.error_reason.message).to eq(error_message)
stop_reactor
end
connection.on(:connected) do
protocol_message = Ably::Models::ProtocolMessage.new(action: Ably::Models::ProtocolMessage::ACTION.Disconnected.to_i, error: { code: 40140, message: error_message })
connection.__incoming_protocol_msgbus__.publish :protocol_message, protocol_message
end
connection.connect
end
end
context "library have a means to renew the token (#RTN15h2)" do
let(:client_options) { default_options.merge(log_level: :none) }
let(:error_message) { 'error_message' }
def send_disconnect_message
protocol_message = Ably::Models::ProtocolMessage.new(action: Ably::Models::ProtocolMessage::ACTION.Disconnected.to_i, error: { code: 40140, message: error_message })
connection.__incoming_protocol_msgbus__.publish :protocol_message, protocol_message
end
it 'attempts to reconnect' do
connection.on(:failed) do |connection_state_change|
raise "Connection shouldn't be failed"
end
connection.on(:connected) do
connection.once(:connecting) do
connection.once(:disconnected) do
expect(connection.error_reason.message).to eq(error_message)
stop_reactor
end
send_disconnect_message
end
send_disconnect_message
end
connection.connect
end
end
end
context 'connection state freshness is monitored' do
it 'resumes connections when disconnected within the connection_state_ttl period (#RTN15g)' do
connection.once(:connected) do
connection_id = connection.id
reconnected_with_resume = false
# Make sure the next connect has the resume param
allow(EventMachine).to receive(:connect).and_wrap_original do |original, *args, &block|
url = args[4]
uri = URI.parse(url)
expect(CGI::parse(uri.query)['resume'][0]).to_not be_empty
reconnected_with_resume = true
original.call(*args, &block)
end
connection.once(:disconnected) do
disconnected_at = Time.now
connection.once(:connecting) do
expect(Time.now.to_f - disconnected_at.to_f).to be < connection.connection_state_ttl
connection.once(:connected) do |state_change|
expect(connection.id).to eql(connection_id)
expect(reconnected_with_resume).to be_truthy
stop_reactor
end
end
end
connection.transport.unbind
end
end
context 'when connection_state_ttl period has passed since being disconnected' do
let(:client_options) do
default_options.merge(
disconnected_retry_timeout: 4,
suspended_retry_timeout: 8,
max_connection_state_ttl: 2,
)
end
it 'clears the local connection state and uses a new connection when the connection_state_ttl period has passed (#RTN15g)' do
connection.once(:connected) do
connection_id = connection.id
resumed_with_clean_connection = false
connection.once(:disconnected) do
disconnected_at = Time.now
connection.once(:connecting) do
connection.once(:disconnected) do
# Make sure the next connect does not have the resume param
allow(EventMachine).to receive(:connect).and_wrap_original do |original, *args, &block|
url = args[4]
uri = URI.parse(url)
expect(CGI::parse(uri.query)['resume']).to be_empty
resumed_with_clean_connection = true
original.call(*args, &block)
end
allow(connection.details).to receive(:max_idle_interval).and_return(0)
connection.__incoming_protocol_msgbus__.plugin_listeners
connection.once(:connecting) do
expect(Time.now.to_f - disconnected_at.to_f).to be > connection.connection_state_ttl
connection.once(:connected) do |state_change|
expect(connection.id).to_not eql(connection_id)
expect(resumed_with_clean_connection).to be_truthy
stop_reactor
end
end
end
# Disconnect the transport and trigger a new disconnected state
wait_until(lambda { connection.transport }) do
connection.transport.unbind
end
end
connection.__incoming_protocol_msgbus__.unplug_listeners
end
connection.transport.unbind
end
end
end
context 'when connection_state_ttl period has passed since last activity on the connection' do
let(:client_options) do
default_options.merge(
max_connection_state_ttl: 2,
)
end
it 'does not clear the local connection state when the connection_state_ttl period has passed since last activity, but the idle timeout has not passed (#RTN15g1, #RTN15g2)' do
expect(connection.connection_state_ttl).to eql(client_options.fetch(:max_connection_state_ttl))
connection.once(:connected) do
connection_id = connection.id
resumed_connection = false
connection.once(:disconnected) do
allow(connection).to receive(:time_since_connection_confirmed_alive?).and_return(connection.connection_state_ttl + 1)
# Make sure the next connect does not have the resume param
allow(EventMachine).to receive(:connect).and_wrap_original do |original, *args, &block|
url = args[4]
uri = URI.parse(url)
expect(CGI::parse(uri.query)['resume']).to_not be_empty
resumed_connection = true
original.call(*args, &block)
end
connection.once(:connecting) do
connection.once(:connected) do |state_change|
expect(connection.id).to eql(connection_id)
expect(resumed_connection).to be_truthy
stop_reactor
end
end
end
connection.transport.unbind
end
end
it 'clears the local connection state and uses a new connection when the connection_state_ttl + max_idle_interval period has passed since last activity (#RTN15g1, #RTN15g2)' do
expect(connection.connection_state_ttl).to eql(client_options.fetch(:max_connection_state_ttl))
connection.once(:connected) do
connection_id = connection.id
resumed_with_clean_connection = false
connection.once(:disconnected) do
pseudo_time_passed = connection.connection_state_ttl + connection.details.max_idle_interval + 1
allow(connection).to receive(:time_since_connection_confirmed_alive?).and_return(pseudo_time_passed)
# Make sure the next connect does not have the resume param
allow(EventMachine).to receive(:connect).and_wrap_original do |original, *args, &block|
url = args[4]
uri = URI.parse(url)
expect(CGI::parse(uri.query)['resume']).to be_empty
resumed_with_clean_connection = true
original.call(*args, &block)
end
connection.once(:connecting) do
connection.once(:connected) do |state_change|
expect(connection.id).to_not eql(connection_id)
expect(resumed_with_clean_connection).to be_truthy
stop_reactor
end
end
end
connection.transport.unbind
end
end
it 'still reattaches the channels automatically following a new connection being established (#RTN15g2)' do
connection.once(:connected) do
connection_id = connection.id
resumed_with_clean_connection = false
channel_emitted_an_attached = false
channel.attach do
channel.once(:attached) do
channel_emitted_an_attached = true
end
connection.once(:disconnected) do
pseudo_time_passed = connection.connection_state_ttl + connection.details.max_idle_interval + 1
allow(connection).to receive(:time_since_connection_confirmed_alive?).and_return(pseudo_time_passed)
# Make sure the next connect does not have the resume param
allow(EventMachine).to receive(:connect).and_wrap_original do |original, *args, &block|
url = args[4]
uri = URI.parse(url)
expect(CGI::parse(uri.query)['resume']).to be_empty
resumed_with_clean_connection = true
original.call(*args, &block)
end
connection.once(:connecting) do
connection.once(:connected) do |state_change|
expect(connection.id).to_not eql(connection_id)
expect(resumed_with_clean_connection).to be_truthy
wait_until(lambda { channel.attached? }) do
expect(channel_emitted_an_attached).to be_truthy
stop_reactor
end
end
end
end
connection.transport.unbind
end
end
end
end
end
context 'and subsequently fails to reconnect' do
let(:retry_every) { 1.5 }
let(:client_options) do
default_options.merge(
log_level: :none,
disconnected_retry_timeout: retry_every,
suspended_retry_timeout: retry_every,
max_connection_state_ttl: 60
)
end
it "retries every #{Ably::Realtime::Connection::DEFAULTS.fetch(:disconnected_retry_timeout)} seconds" do
fail_if_suspended_or_failed
stubbed_first_attempt = false
connection.once(:connected) do
connection.once(:disconnected) do
connection.once(:connecting) do
connection.once(:disconnected) do
disconnected_at = Time.now.to_f
connection.once(:connecting) do
expect(Time.now.to_f - disconnected_at).to be > retry_every
state_history = connection.state_history.map { |transition| transition[:state].to_sym }
expect(state_history).to eql([:connecting, :connected, :disconnected, :connecting, :disconnected, :connecting])
# allow one more recoonect when reactor stopped
expect(connection.manager).to receive(:reconnect_transport)
stop_reactor
end
end
# When reconnect called simply open the transport and close immediately
expect(connection.manager).to receive(:reconnect_transport) do
next if stubbed_first_attempt
connection.manager.setup_transport do
EventMachine.next_tick do
connection.transport.unbind
stubbed_first_attempt = true
end
end
end
end
end
protocol_message = Ably::Models::ProtocolMessage.new(action: Ably::Models::ProtocolMessage::ACTION.Disconnected.to_i)
connection.__incoming_protocol_msgbus__.publish :protocol_message, protocol_message
end
end
end
end
context 'when websocket transport is abruptly disconnected' do
it 'reconnects automatically' do
fail_if_suspended_or_failed
connection.once(:connected) do
connection.once(:disconnected) do
connection.once(:connected) do
state_history = connection.state_history.map { |transition| transition[:state].to_sym }
expect(state_history).to eql([:connecting, :connected, :disconnected, :connecting, :connected])
stop_reactor
end
end
connection.transport.close_connection_after_writing
end
end
context 'hosts used' do
it 'reconnects with the default host' do
fail_if_suspended_or_failed
connection.once(:connected) do
connection.once(:disconnected) do
hosts = []
expect(connection).to receive(:create_transport).once.and_wrap_original do |original_method, *args, &block|
hosts << args[0]
original_method.call(*args, &block)
end
connection.once(:connected) do
host = "#{"#{environment}-" if environment && environment.to_s != 'production'}#{Ably::Realtime::Client::DOMAIN}"
expect(hosts.first).to eql(host)
expect(hosts.length).to eql(1)
stop_reactor
end
end
connection.transport.close_connection_after_writing
end
end
end
end
context 'after successfully reconnecting and resuming' do
it 'retains connection_id and updates the connection_key (#RTN15e, #RTN16d)' do
connection.once(:connected) do
previous_connection_id = connection.id
connection.transport.close_connection_after_writing
expect(connection).to receive(:configure_new).with(previous_connection_id, anything).and_call_original
connection.once(:connected) do
expect(connection.key).to_not be_nil
expect(connection.id).to eql(previous_connection_id)
stop_reactor
end
end
end
it 'includes the error received in the connection state change from Ably but leaves the channels attached' do
channel.attach do
connection.transport.close_connection_after_writing
connection.once(:connecting) do
connection.__incoming_protocol_msgbus__.unsubscribe
connection.__incoming_protocol_msgbus__.subscribe(:protocol_message) do |protocol_message|
allow(protocol_message).to receive(:error).and_return(Ably::Exceptions::Standard.new('Injected error'))
end
# Create a new message dispatcher that subscribes to ProtocolMessages after the previous subscription allowing us
# to modify the ProtocolMessage
Ably::Realtime::Client::IncomingMessageDispatcher.new(client, connection)
end
connection.once(:connected) do |connection_state_change|
EM.add_timer(0.5) do
expect(connection_state_change.reason).to be_a(Ably::Exceptions::Standard)
expect(connection_state_change.reason.message).to match(/Injected error/)
expect(connection.error_reason).to be_a(Ably::Exceptions::Standard)
expect(channel).to be_attached
stop_reactor
end
end
end
end
it 'retains channel subscription state' do
channel.subscribe('event') do |message|
expect(message.data).to eql('message')
stop_reactor
end
channel.attach do
publishing_client_channel.attach do
connection.transport.close_connection_after_writing
connection.once(:connected) do
publishing_client_channel.publish 'event', 'message'
end
end