forked from ably/ably-ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection_spec.rb
1883 lines (1641 loc) · 71.8 KB
/
connection_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'
require 'ostruct'
describe Ably::Realtime::Connection, :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) { auto_close Ably::Realtime::Client.new(client_options) }
before(:example) do
EventMachine.add_shutdown_hook do
connection.off # minimise side effects of callbacks from finished test calling stop_reactor
end
end
context 'intialization' do
it 'connects automatically' do
connection.on(:connected) do
expect(connection.state).to eq(:connected)
stop_reactor
end
end
context 'current_host' do
it 'is available immediately after the client is instanced' do
expect(connection.current_host.to_s).to match(/\.ably\.io$/)
stop_reactor
end
end
context 'with :auto_connect option set to false' do
let(:client) do
auto_close Ably::Realtime::Client.new(default_options.merge(auto_connect: false))
end
it 'does not connect automatically' do
EventMachine.add_timer(1) do
expect(connection).to be_initialized
stop_reactor
end
client
end
it 'connects when method #connect is called' do
connection.connect do
expect(connection).to be_connected
stop_reactor
end
end
end
context 'with token auth' do
before do
# Reduce token expiry buffer to zero so that a token expired? predicate is exact
# Normally there is a buffer so that a token expiring soon is considered expired
@original_token_expiry_buffer = Ably::Models::TokenDetails::TOKEN_EXPIRY_BUFFER
stub_const 'Ably::Models::TokenDetails::TOKEN_EXPIRY_BUFFER', 0
end
let(:original_token_expiry_buffer) { @original_token_expiry_buffer }
context 'for renewable tokens' do
context 'that are valid for the duration of the test' do
context 'with valid pre authorized token expiring in the future' do
let(:client_options) { default_options.merge(use_token_auth: true) }
it 'uses the existing token created by Auth' do
client.auth.authorize(ttl: 300)
expect(client.auth).to_not receive(:request_token)
connection.once(:connected) do
stop_reactor
end
end
end
context 'with implicit authorisation' do
let(:client_options) { default_options.merge(client_id: 'force_token_auth') }
it 'uses the token created by the implicit authorisation' do
expect(client.rest_client.auth).to receive(:request_token).once.and_call_original
connection.once(:connected) do
stop_reactor
end
end
end
end
context 'that expire' do
let(:client_options) { default_options.merge(log_level: :error) }
before do
expect(client.rest_client.time.to_f).to be_within(2).of(Time.now.to_i), "Local clock is out of sync with Ably"
end
before do
# Ensure tokens issued expire immediately after issue
@original_renew_token_buffer = Ably::Auth::TOKEN_DEFAULTS.fetch(:renew_token_buffer)
stub_const 'Ably::Auth::TOKEN_DEFAULTS', Ably::Auth::TOKEN_DEFAULTS.merge(renew_token_buffer: 0)
end
let(:original_renew_token_buffer) { @original_renew_token_buffer }
context 'opening a new connection' do
context 'with almost expired tokens' do
before do
# Authorize synchronously to ensure token has been issued
client.auth.authorize_sync(ttl: ttl)
end
let(:ttl) { 2 }
it 'renews token every time after it expires' do
started_at = Time.now.to_f
connected_times = 0
disconnected_times = 0
connection.on(:connected) do
connected_times += 1
end
connection.on(:disconnected) do
disconnected_times += 1
if disconnected_times == 3
expect(connected_times).to eql(3)
expect(Time.now.to_f - started_at).to be > ttl * 3
expect(Time.now.to_f - started_at).to be < (ttl * 2) * 3
stop_reactor
end
end
end
end
context 'with immediately expired token' do
let(:ttl) { 0.001 }
let(:auth_requests) { [] }
let(:token_callback) do
lambda do |token_params|
auth_requests << Time.now
Ably::Rest::Client.new(default_options).auth.request_token(ttl: ttl).token
end
end
let(:client_options) { default_options.merge(auth_callback: token_callback) }
it 'renews the token on connect, and makes one immediate subsequent attempt to obtain a new token (#RSA4b)' do
started_at = Time.now.to_f
connection.once(:disconnected) do
connection.once(:disconnected) do |connection_state_change|
expect(connection_state_change.reason.code).to eql(40142) # token expired
expect(Time.now.to_f - started_at).to be < 1000
expect(auth_requests.count).to eql(2)
stop_reactor
end
end
end
context 'when disconnected_retry_timeout is 0.5 seconds' do
let(:client_options) { default_options.merge(disconnected_retry_timeout: 0.5, auth_callback: token_callback) }
it 'renews the token on connect, and continues to attempt renew based on the retry schedule' do
disconnect_count = 0
first_disconnected_at = nil
connection.on(:disconnected) do |connection_state_change|
first_disconnected_at ||= begin
Time.now.to_f
end
expect(connection_state_change.reason.code).to eql(40142) # token expired
if disconnect_count == 4 # 3 attempts to reconnect after initial
# First disconnect reattempts immediately as part of connect sequence
# Second disconnect reattempt immediately as part of disconnected retry sequence
# Following two take 0.5 second each
# Not convinced two immediate retries is necessary, but not worth engineering effort to fix given
# it's only one extra retry
expect(Time.now.to_f - first_disconnected_at).to be > 2 * 0.5
expect(Time.now.to_f - first_disconnected_at).to be < 9 # allow 1.5 seconds for each authentication cycle
stop_reactor
end
disconnect_count += 1
end
end
end
context 'using implicit token auth' do
let(:client_options) { default_options.merge(use_token_auth: true, default_token_params: { ttl: ttl }) }
before do
stub_const 'Ably::Models::TokenDetails::TOKEN_EXPIRY_BUFFER', -10 # ensure client lib thinks token is still valid
end
it 'uses the primary host for subsequent connection and auth requests' do
connection.once(:disconnected) do
expect(client.rest_client.connection).to receive(:post).
with(/requestToken$/, anything).
exactly(:twice). # it retries an expired token request immediately
and_call_original
expect(client.rest_client).to_not receive(:fallback_connection)
expect(client).to_not receive(:fallback_endpoint)
# Connection will go into :disconnected, then back to
# :connecting, then :disconnected again
connection.once(:disconnected) do
connection.once(:disconnected) do
stop_reactor
end
end
end
end
end
end
end
context 'when connected with a valid non-expired token' do
context 'that then expires following the connection being opened' do
let(:ttl) { 5 }
let(:channel_name) { random_str }
let(:channel) { client.channel(channel_name) }
let(:client_options) { default_options.merge(use_token_auth: true, default_token_params: { ttl: ttl }) }
context 'the server' do
it 'disconnects the client, and the client automatically renews the token and then reconnects', em_timeout: 15 do
connection.once(:connected) do
original_token = client.auth.current_token_details
expect(original_token).to_not be_expired
started_at = Time.now
connection.once(:disconnected) do |connection_state_change|
expect(connection_state_change.reason.code).to eq(40142) # Token expired
# Token has expired, so now ensure it is not used again
stub_const 'Ably::Models::TokenDetails::TOKEN_EXPIRY_BUFFER', original_token_expiry_buffer
stub_const 'Ably::Auth::TOKEN_DEFAULTS', Ably::Auth::TOKEN_DEFAULTS.merge(renew_token_buffer: original_renew_token_buffer)
connection.once(:connected) do
expect(client.auth.current_token_details).to_not be_expired
expect(Time.now - started_at >= ttl)
expect(original_token).to be_expired
stop_reactor
end
end
end
connection.unsafe_once(:failed) { |error| fail error.inspect }
channel.attach
end
end
context 'connection state' do
let(:publish_count) { 10 }
let(:ttl) { 4 }
let(:auth_requests) { [] }
let(:token_callback) do
lambda do |token_params|
sleep 2
auth_requests << Time.now
Ably::Rest::Client.new(default_options).auth.request_token(ttl: ttl).token
end
end
let(:client_options) { default_options.merge(auth_callback: token_callback) }
let(:publishing_client) { auto_close Ably::Realtime::Client.new(default_options) }
let(:publishing_channel) { publishing_client.channels.get(channel_name) }
let(:messages_received) { [] }
def publish_and_check_disconnect(options = {})
iteration = options.fetch(:iteration) { 1 }
total_expected = publish_count * iteration
publish_count.times.each { |index| publishing_channel.publish('event', (total_expected - publish_count + index).to_s) }
channel.subscribe('event') do |message|
messages_received << message.data.to_i
if messages_received.count == total_expected
expect(messages_received).to match(total_expected.times.to_a)
expect(auth_requests.count).to eql(iteration + 1)
EventMachine.add_timer(1) do
channel.unsubscribe 'event'
yield
end
end
end
end
it 'retains messages published when disconnected three times during authentication', em_timeout: 30 do
publishing_channel.attach do
channel.attach do
connection.once(:disconnected) do
publish_and_check_disconnect(iteration: 1) do
connection.once(:disconnected) do
publish_and_check_disconnect(iteration: 2) do
connection.once(:disconnected) do
publish_and_check_disconnect(iteration: 3) do
stop_reactor
end
end
end
end
end
end
end
end
end
end
context 'and subsequent token is invalid' do
let(:ttl) { 2 }
let(:token_callback) do
lambda do |token_params|
if @token_issued
"#{app_id}.invalid-token-invalid-token-invalid-token"
else
@token_issued = true
Ably::Rest::Client.new(default_options).auth.request_token(ttl: ttl).token
end
end
end
let(:client_options) { default_options.merge(auth_callback: token_callback, log_level: :none) }
it 'transitions the connection to the failed state' do
connection.once(:disconnected) do
connection.once(:failed) do
expect(connection.error_reason.code).to eql(40101)
stop_reactor
end
end
end
end
end
end
end
end
context 'for non-renewable tokens' do
context 'that are expired' do
before do
stub_const 'Ably::Auth::TOKEN_DEFAULTS', Ably::Auth::TOKEN_DEFAULTS.merge(renew_token_buffer: 0)
end
let!(:expired_token_details) do
# Request a token synchronously
token_client = auto_close Ably::Realtime::Client.new(default_options)
token_client.auth.request_token_sync(ttl: ttl)
end
context 'opening a new connection' do
let(:client_options) { default_options.merge(key: nil, token: expired_token_details.token, log_level: :none) }
let(:ttl) { 0.01 }
it 'transitions state to failed (#RSA4a)', em_timeout: 10 do
EventMachine.add_timer(1) do # wait for token to expire
expect(expired_token_details).to be_expired
connection.once(:connected) { raise 'Connection should never connect as token has expired' }
connection.once(:failed) do
expect(client.connection.error_reason.code).to eql(40142)
stop_reactor
end
end
end
end
context 'when connected' do
let(:client_options) { default_options.merge(key: nil, token: expired_token_details.token, log_level: :none) }
let(:ttl) { 4 }
it 'transitions state to failed (#RSA4a)' do
connection.once(:connected) do
connection.once(:failed) do
expect(client.connection.error_reason.code).to eql(40142)
stop_reactor
end
end
end
end
end
end
context 'with opaque token string that contain an implicit client_id' do
let(:client_options) { default_options.merge(token: token_string, key: nil) }
let(:rest_auth_client) { Ably::Rest::Client.new(default_options.merge(key: api_key)) }
let(:token_string) { rest_auth_client.auth.request_token(client_id: client_id).token }
context 'string' do
let(:client_id) { random_str }
it 'sets the Client#client_id and Auth#client_id once CONNECTED' do
expect(client.client_id).to be_nil
client.connection.once(:connected) do
expect(client.client_id).to eql(client_id)
stop_reactor
end
end
context 'that is incompatible with the current client client_id' do
let(:client_id) { random_str }
let(:client_options) { default_options.merge(client_id: 'incompatible', token: token_string, key: nil, log_level: :none) }
it 'fails the connection' do
expect(client.client_id).to eql('incompatible')
client.connection.once(:failed) do
expect(client.client_id).to eql('incompatible')
expect(client.connection.error_reason.code).to eql(40101) # Invalid clientId for credentials
stop_reactor
end
end
end
end
context 'wildcard' do
let(:client_id) { '*' }
it 'configures the Client#client_id and Auth#client_id with a wildcard once CONNECTED' do
expect(client.client_id).to be_nil
client.connection.once(:connected) do
expect(client.client_id).to eql('*')
stop_reactor
end
end
end
end
end
end
context 'initialization state changes' do
let(:phases) { [:connecting, :connected] }
let(:events_emitted) { [] }
let(:test_expectation) do
lambda do
expect(events_emitted).to eq(phases)
stop_reactor
end
end
def expect_ordered_phases
phases.each do |phase|
connection.on(phase) do
events_emitted << phase
test_expectation.call if events_emitted.length == phases.length
end
end
end
context 'with implicit #connect' do
it 'are emitted in order' do
expect_ordered_phases
end
end
context 'with explicit #connect' do
it 'are emitted in order' do
expect_ordered_phases
connection.connect
end
end
end
context '#connect' do
it 'returns a SafeDeferrable that catches exceptions in callbacks and logs them' do
expect(connection.connect).to be_a(Ably::Util::SafeDeferrable)
stop_reactor
end
it 'calls the Deferrable callback on success' do
connection.connect.callback do
expect(connection.state).to eq(:connected)
stop_reactor
end
end
it 'calls the provided block on success even if state changes to disconnected first' do
been_disconnected = false
connection.once(:disconnected) do
been_disconnected = true
end
connection.once(:connecting) do
close_if_transport_available = lambda do
EventMachine.add_timer(0.001) do
if connection.transport
connection.transport.close_connection_after_writing
else
close_if_transport_available.call
end
end
end
close_if_transport_available.call
end
connection.connect do
expect(connection.state).to eq(:connected)
expect(been_disconnected).to be_truthy
stop_reactor
end
end
context 'with invalid auth details' do
let(:client_options) { default_options.merge(key: 'this.is:invalid', log_level: :none) }
it 'calls the Deferrable errback only once on connection failure' do
errback_called = false
connection.connect.errback do
expect(connection.state).to eq(:failed)
raise 'Errback already called' if errback_called
errback_called = true
connection.connect.errback do
EventMachine.add_timer(0.5) { stop_reactor }
end
end
end
end
context 'when already connected' do
it 'does nothing and no further state changes are emitted' do
connection.once(:connected) do
connection.once_state_changed { raise 'State should not have changed' }
3.times { connection.connect }
EventMachine.add_timer(1) do
expect(connection).to be_connected
connection.off
stop_reactor
end
end
end
end
describe 'connection#id' do
it 'is null before connecting' do
expect(connection.id).to be_nil
stop_reactor
end
end
describe 'connection#key' do
it 'is null before connecting' do
expect(connection.key).to be_nil
stop_reactor
end
end
describe 'once connected' do
let(:client2) { auto_close Ably::Realtime::Client.new(client_options) }
let(:connection2) { client2.connection }
describe 'connection#id' do
it 'is a string' do
connection.connect do
expect(connection.id).to be_a(String)
stop_reactor
end
end
it 'is unique from the connection#key' do
connection.connect do
expect(connection.id).to_not eql(connection.key)
stop_reactor
end
end
it 'is unique for every connection' do
when_all(connection.connect, connection2.connect) do
expect(connection.id).to_not eql(connection2.id)
stop_reactor
end
end
end
describe 'connection#key' do
it 'is a string' do
connection.connect do
expect(connection.key).to be_a(String)
stop_reactor
end
end
it 'is unique from the connection#id' do
connection.connect do
expect(connection.key).to_not eql(connection.id)
stop_reactor
end
end
it 'is unique for every connection' do
when_all(connection.connect, connection2.connect) do
expect(connection.key).to_not eql(connection2.key)
stop_reactor
end
end
end
end
context 'following a previous connection being opened and closed' do
it 'reconnects and is provided with a new connection ID and connection key from the server' do
connection.connect do
connection_id = connection.id
connection_key = connection.key
connection.close do
connection.connect do
expect(connection.id).to_not eql(connection_id)
expect(connection.key).to_not eql(connection_key)
stop_reactor
end
end
end
end
end
context 'when closing' do
it 'fails the deferrable before the connection is closed' do
connection.connect do
connection.once(:closing) do
connection.connect.errback do |error|
expect(error).to be_a(Ably::Exceptions::InvalidStateChange)
stop_reactor
end
end
connection.close
end
end
end
end
describe '#serial connection serial' do
let(:channel) { client.channel(random_str) }
it 'is set to -1 when a new connection is opened' do
connection.connect do
expect(connection.serial).to eql(-1)
stop_reactor
end
end
context 'when a message is sent but the ACK has not yet been received' do
it 'the sent message msgSerial is 0 but the connection serial remains at -1' do
channel.attach do
connection.__outgoing_protocol_msgbus__.subscribe(:protocol_message) do |protocol_message|
if protocol_message.action == :message
connection.__outgoing_protocol_msgbus__.unsubscribe
expect(protocol_message['msgSerial']).to eql(0)
expect(connection.serial).to eql(-1)
stop_reactor
end
end
channel.publish('event', 'data')
end
end
end
it 'is set to 0 when a message is received back' do
channel.publish('event', 'data')
channel.subscribe do
expect(connection.serial).to eql(0)
stop_reactor
end
end
it 'is set to 1 when the second message is received' do
channel.attach do
messages = []
channel.subscribe do |message|
messages << message
if messages.length == 2
expect(connection.serial).to eql(1)
stop_reactor
end
end
channel.publish('event', 'data') do
channel.publish('event', 'data')
end
end
end
end
describe '#msgSerial' do
context 'when messages are queued for publish before a connection is established' do
let(:batches) { 6 }
let(:messages_per_batch) { 10 }
let(:publishing_client) { auto_close Ably::Realtime::Client.new(default_options) }
let(:channel_name) { random_str }
let(:publishing_channel) { publishing_client.channels.get(channel_name) }
let(:receiving_channel) { client.channels.get(channel_name) }
it 'the msgSerial is always incrementing (and not reset when the new connection is established) ensuring messages are never de-duped by the realtime service' do
messages = []
receiving_channel.attach do
receiving_channel.subscribe('event') do |message|
messages << message
stop_reactor if messages.count == batches * messages_per_batch
end
batches.times do |batch|
EventMachine.add_timer(batch.to_f / batches.to_f) do
messages_per_batch.times { |index| publishing_channel.publish('event') }
end
end
end
end
end
end
context '#close' do
it 'returns a SafeDeferrable that catches exceptions in callbacks and logs them' do
connection.connect do
expect(connection.close).to be_a(Ably::Util::SafeDeferrable)
stop_reactor
end
end
it 'calls the Deferrable callback on success' do
connection.connect do
connection.close.callback do
expect(connection).to be_a(Ably::Realtime::Connection)
expect(connection.state).to eq(:closed)
stop_reactor
end
end
end
context 'when already closed' do
it 'does nothing and no further state changes are emitted' do
connection.once(:connected) do
connection.close do
connection.once_state_changed { raise 'State should not have changed' }
3.times { connection.close }
EventMachine.add_timer(1) do
expect(connection).to be_closed
connection.off
stop_reactor
end
end
end
end
end
context 'when connection state is' do
let(:events) { Hash.new }
def log_connection_changes
connection.on(:closing) { events[:closing_emitted] = true }
connection.__incoming_protocol_msgbus__.subscribe(:protocol_message) do |protocol_message|
events[:closed_message_from_server_received] = true if protocol_message.action == :closed
end
end
context ':initialized' do
it 'changes the connection state to :closing and then immediately :closed without sending a ProtocolMessage CLOSE' do
connection.on(:closed) do
expect(connection.state).to eq(:closed)
EventMachine.add_timer(1) do # allow for all subscribers on incoming message bes
expect(events[:closed_message_from_server_received]).to_not eql(true)
expect(events[:closing_emitted]).to eql(true)
stop_reactor
end
end
log_connection_changes
connection.close
end
end
context ':connected' do
it 'changes the connection state to :closing and waits for the server to confirm connection is :closed with a ProtocolMessage' do
connection.on(:connected) do
connection.on(:closed) do
EventMachine.add_timer(1) do # allow for all subscribers on incoming message bus
expect(events[:closed_message_from_server_received]).to eql(true)
expect(events[:closing_emitted]).to eql(true)
stop_reactor
end
end
log_connection_changes
connection.close
end
end
context 'with an unresponsive connection' do
let(:custom_timeout) { 2 }
let(:client_options) { default_options.merge(realtime_request_timeout: custom_timeout) }
before do
connection.on(:connected) do
# Prevent all incoming & outgoing ProtocolMessages from being processed by the client library
connection.__outgoing_protocol_msgbus__.unsubscribe
connection.__incoming_protocol_msgbus__.unsubscribe
end
end
it 'force closes the connection when a :closed ProtocolMessage response is not received' do
connection.on(:connected) do
close_requested_at = Time.now
connection.on(:closed) do
expect(Time.now - close_requested_at).to be >= custom_timeout
expect(connection.state).to eq(:closed)
expect(events[:closed_message_from_server_received]).to_not eql(true)
expect(events[:closing_emitted]).to eql(true)
stop_reactor
end
log_connection_changes
EventMachine.next_tick { connection.close }
end
end
end
end
end
end
context '#ping' do
it 'echoes a heart beat (#RTN13a)' do
connection.on(:connected) do
connection.ping do |time_elapsed|
expect(time_elapsed).to be > 0
expect(time_elapsed).to be < 3
stop_reactor
end
end
end
it 'sends a unique ID in each protocol message (#RTN13e)' do
connection.on(:connected) do
heartbeat_ids = []
pings_complete = []
connection.__outgoing_protocol_msgbus__.subscribe(:protocol_message) do |protocol_message|
if protocol_message.action == :heartbeat
heartbeat_ids << protocol_message.id
end
end
ping_block = lambda do |time|
pings_complete << true
if pings_complete.length == 3
expect(heartbeat_ids.uniq.length).to eql(3)
stop_reactor
end
end
connection.ping(&ping_block)
connection.ping(&ping_block)
connection.ping(&ping_block)
end
end
it 'waits until the connection becomes CONNECTED when in the CONNETING state' do
connection.once(:connecting) do
connection.ping do |time_elapsed|
expect(connection.state).to eq(:connected)
stop_reactor
end
end
end
context 'with incompatible states' do
let(:client_options) { default_options.merge(log_level: :none) }
context 'when not connected' do
it 'fails the deferrable (#RTN13b)' do
connection.ping.errback do |error|
expect(error.message).to match(/Cannot send a ping when.*initialized/i)
stop_reactor
end
end
end
context 'when suspended' do
it 'fails the deferrable (#RTN13b)' do
connection.once(:connected) do
connection.transition_state_machine! :suspended
connection.ping.errback do |error|
expect(error.message).to match(/Cannot send a ping when.*suspended/i)
stop_reactor
end
end
end
end
context 'when failed' do
it 'fails the deferrable (#RTN13b)' do
connection.once(:connected) do
connection.transition_state_machine! :failed
connection.ping.errback do |error|
expect(error.message).to match(/Cannot send a ping when.*failed/i)
stop_reactor
end
end
end
end
context 'when closed' do
it 'fails the deferrable (#RTN13b)' do
connection.once(:connected) do
connection.close
connection.once(:closed) do
connection.ping.errback do |error|
expect(error.message).to match(/Cannot send a ping when.*closed/i)
stop_reactor
end
end
end
end
end
context 'when it becomes closed' do
it 'fails the deferrable (#RTN13b)' do
connection.once(:connected) do
connection.ping.errback do |error|
expect(error.message).to match(/Ping failed as connection has changed state to.*closing/i)
stop_reactor
end
connection.close
end
end
end
end
context 'with a success block that raises an exception' do
it 'catches the exception and logs the error' do
connection.on(:connected) do
expect(connection.logger).to receive(:error) do |*args, &block|
expect(args.concat([block ? block.call : nil]).join(',')).to match(/Forced exception/)
stop_reactor
end
connection.ping { raise 'Forced exception' }
end
end
end
context 'when ping times out' do
let(:client_options) { default_options.merge(log_level: :error) }
it 'fails the deferrable logs a warning (#RTN13a, #RTN13c)' do
message_logged = false
connection.once(:connected) do
allow(connection).to receive(:defaults).and_return(connection.defaults.merge(realtime_request_timeout: 0.0001))
expect(connection.logger).to receive(:warn) do |*args, &block|
expect(block.call).to match(/Ping timed out/)
message_logged = true
end
connection.ping.errback do |error|
EventMachine.add_timer(0.1) do
expect(error.message).to match(/Ping timed out/)
expect(error.code).to eql(50003)
expect(message_logged).to be_truthy
stop_reactor
end
end
end
end
it 'yields to the block with a nil value' do
connection.once(:connected) do
allow(connection).to receive(:defaults).and_return(connection.defaults.merge(realtime_request_timeout: 0.0001))
connection.ping do |time_elapsed|
expect(time_elapsed).to be_nil
stop_reactor
end
end
end
end
end
context 'Heartbeats (#RTN23)' do
context 'heartbeat interval' do
context 'when reduced artificially' do
let(:protocol_message_attributes) do
{
action: Ably::Models::ProtocolMessage::ACTION.Connected.to_i,
connection_serial: 55,
connection_details: {
max_idle_interval: 2 * 1000
}
}
end
let(:client_options) { default_options.merge(realtime_request_timeout: 3) }
let(:expected_heartbeat_interval) { 5 }
it 'is the sum of the max_idle_interval and realtime_request_timeout (#RTN23a)' do
connection.once(:connected) do
connection.__incoming_protocol_msgbus__.publish :protocol_message, Ably::Models::ProtocolMessage.new(protocol_message_attributes)
EventMachine.next_tick do
expect(connection.heartbeat_interval).to eql(expected_heartbeat_interval)
stop_reactor
end
end
end
it 'disconnects the transport if no heartbeat received since connected (#RTN23a)' do
connection.once(:connected) do
connection.__incoming_protocol_msgbus__.publish :protocol_message, Ably::Models::ProtocolMessage.new(protocol_message_attributes)
last_received_at = Time.now
connection.once(:disconnected) do
expect(Time.now.to_i - last_received_at.to_i).to be_within(2).of(expected_heartbeat_interval)
stop_reactor