-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathclient_spec.rb
1408 lines (1200 loc) · 58.2 KB
/
client_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 'webrick'
describe Ably::Rest::Client do
vary_by_protocol do
let(:default_options) { { environment: environment, protocol: protocol, log_retries_as_info: true } }
let(:client_options) { default_options }
let(:client) { Ably::Rest::Client.new(client_options) }
http_defaults = Ably::Rest::Client::HTTP_DEFAULTS
def encode64(text)
Base64.urlsafe_encode64(text)
end
context '#initialize' do
let(:client_id) { random_str }
let(:token_request) { client.auth.create_token_request({}, key_name: key_name, key_secret: key_secret, client_id: client_id) }
context 'with only an API key' do
let(:client) { Ably::Rest::Client.new(client_options.merge(key: api_key)) }
it 'uses basic authentication' do
expect(client.auth).to be_using_basic_auth
end
end
context 'with an invalid API key' do
let(:client) { Ably::Rest::Client.new(client_options.merge(key: 'app.key:secret', log_level: :fatal)) }
it 'logs an entry with a help href url matching the code #TI5' do
begin
client.channels.get('foo').publish('test')
raise 'Expected Ably::Exceptions::ResourceMissing'
rescue Ably::Exceptions::ResourceMissing => err
expect err.to_s.match(%r{https://help.ably.io/error/40400})
end
end
end
context 'with an explicit string :token' do
let(:client) { Ably::Rest::Client.new(client_options.merge(token: random_str)) }
it 'uses token authentication' do
expect(client.auth).to be_using_token_auth
end
end
context 'with :use_token_auth set to true' do
let(:client) { Ably::Rest::Client.new(client_options.merge(key: api_key, use_token_auth: true)) }
it 'uses token authentication' do
expect(client.auth).to be_using_token_auth
end
end
context 'with a non string :client_id' do
let(:client) { Ably::Rest::Client.new(client_options.merge(key: api_key, client_id: 1)) }
it 'raises an ArgumentError' do
expect { client.auth }.to raise_error ArgumentError, /client_id.*String/
end
end
context 'with an invalid wildcard "*" :client_id' do
it 'raises an exception' do
expect { Ably::Rest::Client.new(client_options.merge(key: api_key, client_id: '*')) }.to raise_error ArgumentError
end
end
context 'with an :auth_callback lambda' do
let(:client) { Ably::Rest::Client.new(client_options.merge(auth_callback: lambda { |token_params| token_request })) }
it 'calls the auth lambda to get a new token' do
expect { client.channel('channel_name').publish('event', 'message') }.to change { client.auth.current_token_details }
expect(client.auth.current_token_details.client_id).to eql(client_id)
end
it 'uses token authentication' do
expect(client.auth).to be_using_token_auth
end
end
context 'with :default_token_params' do
let(:client) do
Ably::Rest::Client.new(client_options.merge(
default_token_params: { client_id: 'bob' },
use_token_auth: true,
key: api_key
))
end
it 'overides the default token params (#TO3j11)' do
client.auth.authorize
expect(client.auth.client_id).to eql('bob')
end
end
context 'with an :auth_callback lambda (clientId provided in library options instead of as a token_request param)' do
let(:client) { Ably::Rest::Client.new(client_options.merge(client_id: client_id, auth_callback: lambda { |token_params| token_request })) }
let(:token_request) { client.auth.create_token_request({}, key_name: key_name, key_secret: key_secret) }
it 'correctly sets the clientId on the token' do
expect { client.channel('channel_name').publish('event', 'message') }.to change { client.auth.current_token_details }
expect(client.auth.current_token_details.client_id).to eql(client_id)
end
end
context 'with an auth URL' do
let(:client_options) { default_options.merge(key: api_key, auth_url: token_request_url, auth_method: :get) }
let(:token_request_url) { 'http://get.token.request.com/' }
it 'uses token authentication' do
expect(client.auth).to be_using_token_auth
end
context 'before any REST request' do
before do
expect(client.auth).to receive(:token_request_from_auth_url).with(token_request_url, hash_including(:auth_method => :get), anything).once do
client.auth.create_token_request(client_id: client_id)
end
end
it 'sends an HTTP request to the provided auth URL to get a new token' do
expect { client.channel('channel_name').publish('event', 'message') }.to change { client.auth.current_token_details }
expect(client.auth.current_token_details.client_id).to eql(client_id)
end
end
end
context 'auth headers', webmock: true do
let(:channel_name) { random_str }
let(:history_params) { { 'direction' => 'backwards', 'limit' => 100 } }
let(:history_querystring) { history_params.map { |k, v| "#{k}=#{v}" }.join("&") }
context 'with basic auth', webmock: true do
let(:client_options) { default_options.merge(key: api_key, client_id: client_id) }
let!(:get_message_history_stub) do
stub_request(:get, "https://#{environment}-#{Ably::Rest::Client::DOMAIN}/channels/#{channel_name}/messages?#{history_querystring}")
.with(headers: { 'X-Ably-ClientId' => encode64(client_id) })
.to_return(body: [], headers: { 'Content-Type' => 'application/json' })
end
it 'sends the API key in authentication part of the secure URL (the Authorization: Basic header is not used with the Faraday HTTP library by default)' do
client.channel(channel_name).history history_params
expect(get_message_history_stub).to have_been_requested
end
end
context 'with token auth', webmock: true do
let(:token_string) { random_str }
let(:client_options) { default_options.merge(token: token_string) }
let!(:get_message_history_stub) do
stub_request(:get, "#{http_protocol}://#{environment}-#{Ably::Rest::Client::DOMAIN}/channels/#{channel_name}/messages?#{history_querystring}").
with(headers: { 'Authorization' => "Bearer #{encode64(token_string)}" }).
to_return(body: [], headers: { 'Content-Type' => 'application/json' })
end
context 'without specifying protocol' do
let(:http_protocol) { 'https' }
it 'sends the token string over HTTPS in the Authorization Bearer header with Base64 encoding' do
client.channel(channel_name).history history_params
expect(get_message_history_stub).to have_been_requested
end
end
context 'when setting constructor ClientOption :tls to false' do
let(:client_options) { default_options.merge(token: token_string, tls: false) }
let(:http_protocol) { 'http' }
it 'sends the token string over HTTP in the Authorization Bearer header with Base64 encoding' do
client.channel(channel_name).history history_params
expect(get_message_history_stub).to have_been_requested
end
end
end
end
end
context 'using tokens' do
let(:client) do
Ably::Rest::Client.new(client_options.merge(auth_callback: lambda do |token_params|
@request_index ||= 0
@request_index += 1
send("token_request_#{@request_index > 2 ? 'next' : @request_index}")
end))
end
let(:client_id) { random_str }
let(:client_id_2) { client_id }
let(:token_request_1) { client.auth.create_token_request({}, token_request_options.merge(client_id: client_id)) }
let(:token_request_2) { client.auth.create_token_request({}, token_request_options.merge(client_id: client_id_2)) }
# If token expires against whilst runnig tests in a slower CI environment then use this token
let(:token_request_next) { client.auth.create_token_request({}, token_request_options.merge(client_id: random_str)) }
context 'when expired' do
before do
# Ensure tokens issued expire immediately after issue
stub_const 'Ably::Auth::TOKEN_DEFAULTS', Ably::Auth::TOKEN_DEFAULTS.merge(renew_token_buffer: 0)
end
let(:token_request_options) { { key_name: key_name, key_secret: key_secret, token_params: { ttl: Ably::Models::TokenDetails::TOKEN_EXPIRY_BUFFER } } }
it 'creates a new token automatically when the old token expires' do
expect { client.channel('channel_name').publish('event', 'message') }.to change { client.auth.current_token_details }
expect(client.auth.current_token_details.client_id).to eql(token_request_1.client_id)
sleep 1
expect { client.channel('channel_name').publish('event', 'message') }.to change { client.auth.current_token_details }
expect(client.auth.current_token_details.client_id).to eql(token_request_2.client_id)
end
context 'with a different client_id in the subsequent token' do
let(:client_id_2) { random_str }
it 'fails to authenticate and raises an exception' do
client.channel('channel_name').publish('event', 'message')
sleep 1
expect { client.channel('channel_name').publish('event', 'message') }.to raise_error(Ably::Exceptions::IncompatibleClientId)
end
end
end
context 'when token has not expired' do
let(:token_request_options) { { key_name: key_name, key_secret: key_secret, ttl: 3600 } }
it 'reuses the existing token for every request' do
expect { client.channel('channel_name').publish('event', 'message') }.to change { client.auth.current_token_details }
expect(client.auth.current_token_details.client_id).to eql(token_request_1.client_id)
sleep 1
expect { client.channel('channel_name').publish('event', 'message') }.to_not change { client.auth.current_token_details }
expect(client.auth.current_token_details.client_id).to eql(token_request_1.client_id)
end
end
end
context 'connection transport' do
context 'defaults' do
let(:client_options) { default_options.merge(key: api_key, environment: 'production') }
context 'for default host' do
it "is configured to timeout connection opening in #{http_defaults.fetch(:open_timeout)} seconds" do
expect(client.connection.options.open_timeout).to eql(http_defaults.fetch(:open_timeout))
end
it "is configured to timeout connection requests in #{http_defaults.fetch(:request_timeout)} seconds" do
expect(client.connection.options.timeout).to eql(http_defaults.fetch(:request_timeout))
end
end
context 'for the fallback hosts' do
it "is configured to timeout connection opening in #{http_defaults.fetch(:open_timeout)} seconds" do
expect(client.fallback_connection.options.open_timeout).to eql(http_defaults.fetch(:open_timeout))
end
it "is configured to timeout connection requests in #{http_defaults.fetch(:request_timeout)} seconds" do
expect(client.fallback_connection.options.timeout).to eql(http_defaults.fetch(:request_timeout))
end
end
end
context 'with custom http_open_timeout and http_request_timeout options' do
let(:http_open_timeout) { 999 }
let(:http_request_timeout) { 666 }
let(:client_options) { default_options.merge(key: api_key, http_open_timeout: http_open_timeout, http_request_timeout: http_request_timeout, environment: 'production') }
context 'for default host' do
it 'is configured to use custom open timeout' do
expect(client.connection.options.open_timeout).to eql(http_open_timeout)
end
it 'is configured to use custom request timeout' do
expect(client.connection.options.timeout).to eql(http_request_timeout)
end
end
context 'for the fallback hosts' do
it "is configured to timeout connection opening in #{http_defaults.fetch(:open_timeout)} seconds" do
expect(client.fallback_connection.options.open_timeout).to eql(http_open_timeout)
end
it "is configured to timeout connection requests in #{http_defaults.fetch(:request_timeout)} seconds" do
expect(client.fallback_connection.options.timeout).to eql(http_request_timeout)
end
end
end
end
context 'fallback hosts', :webmock do
let(:path) { '/channels/test/publish' }
let(:publish_block) { lambda { client.channel('test').publish('event', 'data') } }
context 'configured' do
let(:client_options) { default_options.merge(key: api_key, environment: 'production') }
it 'should make connection attempts to a.ably-realtime.com, b.ably-realtime.com, c.ably-realtime.com, d.ably-realtime.com, e.ably-realtime.com (#RSC15a)' do
hosts = []
5.times do
hosts << client.fallback_connection.host
end
expect(hosts).to match_array(%w(a.ably-realtime.com b.ably-realtime.com c.ably-realtime.com d.ably-realtime.com e.ably-realtime.com))
end
end
context 'when environment is NOT production (#RSC15b)' do
context 'and custom fallback hosts are empty' do
let(:client_options) { default_options.merge(environment: 'sandbox', key: api_key, fallback_hosts: []) }
let!(:default_host_request_stub) do
stub_request(:post, "https://#{environment}-#{Ably::Rest::Client::DOMAIN}#{path}").to_return do
raise Faraday::TimeoutError.new('timeout error message')
end
end
it 'does not retry failed requests with fallback hosts when there is a connection error' do
expect { publish_block.call }.to raise_error Ably::Exceptions::ConnectionTimeout
end
end
context 'and no custom fallback hosts are provided' do
let(:client_options) { default_options.merge(environment: 'sandbox', key: api_key) }
it 'should make connection attempts to sandbox-a-fallback.ably-realtime.com, sandbox-b-fallback.ably-realtime.com, sandbox-c-fallback.ably-realtime.com, sandbox-d-fallback.ably-realtime.com, sandbox-e-fallback.ably-realtime.com (#RSC15a)' do
hosts = []
5.times do
hosts << client.fallback_connection.host
end
expect(hosts).to match_array(%w(a b c d e).map { |id| "sandbox-#{id}-fallback.ably-realtime.com" })
end
end
end
context 'when environment is production' do
let(:custom_hosts) { %w(a.ably-realtime.com b.ably-realtime.com) }
let(:max_retry_count) { 2 }
let(:max_retry_duration) { 0.5 }
let(:fallback_block) { proc { raise Faraday::SSLError.new('ssl error message') } }
let(:client_options) do
default_options.merge(
environment: nil,
key: api_key,
http_max_retry_duration: max_retry_duration,
http_max_retry_count: max_retry_count,
log_level: :error
)
end
before do
stub_const 'Ably::FALLBACK_HOSTS', custom_hosts
end
let!(:first_fallback_request_stub) do
stub_request(:post, "https://#{custom_hosts[0]}#{path}").to_return(&fallback_block)
end
let!(:second_fallback_request_stub) do
stub_request(:post, "https://#{custom_hosts[1]}#{path}").to_return(&fallback_block)
end
context 'and connection times out' do
let!(:default_host_request_stub) do
stub_request(:post, "https://#{Ably::Rest::Client::DOMAIN}#{path}").to_return do
raise Faraday::TimeoutError.new('timeout error message')
end
end
it "tries fallback hosts #{http_defaults.fetch(:max_retry_count)} times (#RSC15b, #RSC15b)" do
expect { publish_block.call }.to raise_error Ably::Exceptions::ConnectionError, /ssl error message/
expect(default_host_request_stub).to have_been_requested
expect(first_fallback_request_stub).to have_been_requested
expect(second_fallback_request_stub).to have_been_requested
end
context "and the total request time exeeds #{http_defaults.fetch(:max_retry_duration)} seconds" do
let!(:default_host_request_stub) do
stub_request(:post, "https://#{Ably::Rest::Client::DOMAIN}#{path}").to_return do
sleep max_retry_duration * 1.5
raise Faraday::TimeoutError.new('timeout error message')
end
end
it 'makes no further attempts to any fallback hosts' do
expect { publish_block.call }.to raise_error Ably::Exceptions::ConnectionTimeout
expect(default_host_request_stub).to have_been_requested
expect(first_fallback_request_stub).to_not have_been_requested
expect(second_fallback_request_stub).to_not have_been_requested
end
end
end
context 'and connection fails' do
let!(:default_host_request_stub) do
stub_request(:post, "https://#{Ably::Rest::Client::DOMAIN}#{path}").to_return do
raise Faraday::ConnectionFailed.new('connection failure error message')
end
end
it "tries fallback hosts #{http_defaults.fetch(:max_retry_count)} times" do
expect { publish_block.call }.to raise_error Ably::Exceptions::ConnectionError, /ssl error message/
expect(default_host_request_stub).to have_been_requested
expect(first_fallback_request_stub).to have_been_requested
expect(second_fallback_request_stub).to have_been_requested
end
end
context 'and first request to primary endpoint fails' do
let(:client_options) do
default_options.merge(
environment: nil,
key: api_key,
http_max_retry_duration: max_retry_duration,
http_max_retry_count: max_retry_count,
log_level: :error
)
end
let(:requests) { [] }
let!(:default_host_request_stub) do
stub_request(:post, "https://#{Ably::Rest::Client::DOMAIN}#{path}").to_return do
requests << true
if requests.count == 1
raise Faraday::ConnectionFailed.new('connection failure error message')
else
{
headers: { 'Content-Type' => 'application/json' },
status: 200,
body: {}.to_json
}
end
end
end
it "tries a fallback host, and for the next request tries the primary endpoint again (#RSC15e)" do
expect { publish_block.call }.to raise_error Ably::Exceptions::ConnectionError, /ssl error message/
expect(default_host_request_stub).to have_been_requested
expect(first_fallback_request_stub).to have_been_requested
expect(requests.count).to eql(1)
publish_block.call
expect(requests.count).to eql(2)
end
end
context 'and basic authentication fails' do
let(:status) { 401 }
let!(:default_host_request_stub) do
stub_request(:post, "https://#{Ably::Rest::Client::DOMAIN}#{path}").to_return(
headers: { 'Content-Type' => 'application/json' },
status: status,
body: {
"error" => {
"statusCode" => 401,
"code" => 40101,
"message" => "Invalid credentials"
}
}.to_json
)
end
it 'does not attempt the fallback hosts as this is an authentication failure' do
expect { publish_block.call }.to raise_error(Ably::Exceptions::UnauthorizedRequest)
expect(default_host_request_stub).to have_been_requested
expect(first_fallback_request_stub).to_not have_been_requested
expect(second_fallback_request_stub).to_not have_been_requested
end
end
context 'and server returns a 50x error' do
let(:status) { 502 }
let(:fallback_block) do
proc do
{
headers: { 'Content-Type' => 'text/html' },
status: status
}
end
end
let!(:default_host_request_stub) do
stub_request(:post, "https://#{Ably::Rest::Client::DOMAIN}#{path}").to_return(&fallback_block)
end
it 'attempts the fallback hosts as this is an authentication failure (#RSC15d)' do
expect { publish_block.call }.to raise_error(Ably::Exceptions::ServerError)
expect(default_host_request_stub).to have_been_requested
expect(first_fallback_request_stub).to have_been_requested
expect(second_fallback_request_stub).to have_been_requested
end
end
end
context 'when environment is production and server returns a 50x error' do
let(:custom_hosts) { %w(A.foo.com B.foo.com) }
let(:max_retry_count) { 2 }
let(:max_retry_duration) { 0.5 }
let(:fallback_block) { proc { raise Faraday::SSLError.new('ssl error message') } }
let(:production_options) do
default_options.merge(
environment: nil,
key: api_key,
http_max_retry_duration: max_retry_duration,
http_max_retry_count: max_retry_count
)
end
let(:status) { 502 }
let(:fallback_block) do
proc do
{
headers: { 'Content-Type' => 'text/html' },
status: status
}
end
end
let!(:default_host_request_stub) do
stub_request(:post, "https://#{Ably::Rest::Client::DOMAIN}#{path}").to_return(&fallback_block)
end
context 'with custom fallback hosts provided' do
let!(:first_fallback_request_stub) do
stub_request(:post, "https://#{custom_hosts[0]}#{path}").to_return(&fallback_block)
end
let!(:second_fallback_request_stub) do
stub_request(:post, "https://#{custom_hosts[1]}#{path}").to_return(&fallback_block)
end
let(:client_options) {
production_options.merge(fallback_hosts: custom_hosts, log_level: :error)
}
it 'attempts the fallback hosts as this is an authentication failure (#RSC15b, #RSC15a, #TO3k6)' do
expect { publish_block.call }.to raise_error(Ably::Exceptions::ServerError)
expect(default_host_request_stub).to have_been_requested
expect(first_fallback_request_stub).to have_been_requested
expect(second_fallback_request_stub).to have_been_requested
end
end
context 'with an empty array of fallback hosts provided (#RSC15b, #RSC15a, #TO3k6)' do
let(:client_options) {
production_options.merge(fallback_hosts: [])
}
it 'does not attempt the fallback hosts as this is an authentication failure' do
expect { publish_block.call }.to raise_error(Ably::Exceptions::ServerError)
expect(default_host_request_stub).to have_been_requested
end
end
context 'using a local web-server', webmock: false do
let(:primary_host) { 'local-rest.ably.io' }
let(:fallbacks) { ['local.ably.io', 'localhost'] }
let(:port) { rand(10000) + 2000 }
let(:channel_name) { 'foo' }
let(:request_timeout) { 3 }
after do
@web_server.shutdown
end
context 'and timing out the primary host' do
before do
@web_server = WEBrick::HTTPServer.new(:Port => port, :SSLEnable => false, :AccessLog => [], Logger: WEBrick::Log.new("/dev/null"))
request_handler = lambda do |result_body|
lambda do |req, res|
host = req.header["host"].first
if host.include?(primary_host)
@primary_host_request_count ||= 0
@primary_host_request_count += 1
sleep request_timeout + 0.5
else
@fallback_request_count ||= 0
@fallback_request_count += 1
@fallback_hosts_tried ||= []
@fallback_hosts_tried.push(host)
if @fallback_request_count <= fail_fallback_request_count
sleep request_timeout + 0.5
else
res.status = 200
res['Content-Type'] = 'application/json'
res.body = result_body
end
end
end
end
@web_server.mount_proc "/time", &request_handler.call('[1000000000000]')
@web_server.mount_proc "/channels/#{channel_name}/publish", &request_handler.call('{}')
Thread.new do
@web_server.start
end
end
context 'POST with request timeout less than max_retry_duration' do
let(:client_options) do
default_options.merge(
rest_host: primary_host,
fallback_hosts: fallbacks,
token: 'fake.token',
port: port,
tls: false,
http_request_timeout: request_timeout,
http_max_retry_duration: request_timeout * 2.5,
log_level: :error
)
end
let(:fail_fallback_request_count) { 1 }
it 'tries the primary host, then both fallback hosts (#RSC15d)' do
client.channel(channel_name).publish('event', 'data')
expect(@primary_host_request_count).to eql(1)
expect(@fallback_request_count).to eql(2)
expect(@fallback_hosts_tried.uniq.length).to eql(2)
end
end
context 'GET with request timeout less than max_retry_duration' do
let(:client_options) do
default_options.merge(
rest_host: primary_host,
fallback_hosts: fallbacks,
token: 'fake.token',
port: port,
tls: false,
http_request_timeout: request_timeout,
http_max_retry_duration: request_timeout * 2.5,
log_level: :error
)
end
let(:fail_fallback_request_count) { 1 }
it 'tries the primary host, then both fallback hosts (#RSC15d)' do
client.time
expect(@primary_host_request_count).to eql(1)
expect(@fallback_request_count).to eql(2)
expect(@fallback_hosts_tried.uniq.length).to eql(2)
end
end
context 'POST with request timeout more than max_retry_duration' do
let(:client_options) do
default_options.merge(
rest_host: primary_host,
fallback_hosts: fallbacks,
token: 'fake.token',
port: port,
tls: false,
http_request_timeout: request_timeout,
http_max_retry_duration: request_timeout / 2,
log_level: :error
)
end
let(:fail_fallback_request_count) { 0 }
it 'does not try any fallback hosts (#RSC15d)' do
expect { client.channel(channel_name).publish('event', 'data') }.to raise_error Ably::Exceptions::ConnectionTimeout
expect(@primary_host_request_count).to eql(1)
expect(@fallback_request_count).to be_nil
end
end
context 'GET with request timeout more than max_retry_duration' do
let(:client_options) do
default_options.merge(
rest_host: primary_host,
fallback_hosts: fallbacks,
token: 'fake.token',
port: port,
tls: false,
http_request_timeout: request_timeout,
http_max_retry_duration: request_timeout / 2,
log_level: :error
)
end
let(:fail_fallback_request_count) { 0 }
it 'does not try any fallback hosts (#RSC15d)' do
expect { client.time }.to raise_error Ably::Exceptions::ConnectionTimeout
expect(@primary_host_request_count).to eql(1)
expect(@fallback_request_count).to be_nil
end
end
end
context 'and failing the primary host' do
before do
@web_server = WEBrick::HTTPServer.new(:Port => port, :SSLEnable => false, :AccessLog => [], Logger: WEBrick::Log.new("/dev/null"))
@web_server.mount_proc "/channels/#{channel_name}/publish" do |req, res|
if req.header["host"].first.include?(primary_host)
@primary_host_requested = true
res.status = 500
else
@fallback_request_count ||= 0
@fallback_request_count += 1
if @fallback_request_count <= fail_fallback_request_count
res.status = 500
else
res.status = 200
res['Content-Type'] = 'application/json'
res.body = '{}'
end
end
end
Thread.new do
@web_server.start
end
end
let(:client_options) do
default_options.merge(
rest_host: primary_host,
fallback_hosts: fallbacks,
token: 'fake.token',
port: port,
tls: false,
log_level: :error
)
end
let(:fail_fallback_request_count) { 1 }
it 'tries one of the fallback hosts' do
client.channel(channel_name).publish('event', 'data')
expect(@primary_host_requested).to be_truthy
expect(@fallback_request_count).to eql(2)
end
end
context 'to fail the primary host, allow a fallback to succeed, then later trigger a fallback to the primary host (#RSC15f)' do
before do
@request_count = 0
@primary_host_request_count = 0
@web_server = WEBrick::HTTPServer.new(:Port => port, :SSLEnable => false, :AccessLog => [], Logger: WEBrick::Log.new("/dev/null"))
@web_server.mount_proc "/channels/#{channel_name}/publish" do |req, res|
@request_count += 1
if req.header["host"].first.include?(primary_host)
@primary_host_request_count += 1
# Fail all requests to the primary host so that a fallback is used
# Except request 6 which should suceed and clear the fallback host preference
if @request_count == 6
res.status = 200
res['Content-Type'] = 'application/json'
res.body = '{}'
else
res.status = 500
end
else
# Fail the second request (first failed fallback of first request)
# Fail the third request on the previously succeeded fallback host to trigger an attempt on the primary host
if [2, 5].include?(@request_count)
res.status = 500
else
res.status = 200
res['Content-Type'] = 'application/json'
res.body = '{}'
end
end
end
Thread.new do
@web_server.start
end
end
let(:client_options) do
default_options.merge(
rest_host: primary_host,
fallback_hosts: fallbacks,
token: 'fake.token',
port: port,
tls: false,
log_level: :error
).merge(additional_client_options)
end
let (:additional_client_options) { {} }
it 'succeeds and remembers fallback host preferences across requests' do
# Send a request, expect primary endpoint to fail, one fallback to fail, second fallback to succeed
client.channel(channel_name).publish('event', 'data')
expect(@request_count).to eql(3)
expect(fallbacks).to include(client.using_preferred_fallback_host?)
successfull_fallback = client.using_preferred_fallback_host?
expect(@primary_host_request_count).to eql(1)
# Send another request, which should go straight to the fallback as it succeeded previously
client.channel(channel_name).publish('event', 'data')
expect(@request_count).to eql(4)
expect(successfull_fallback).to eql(client.using_preferred_fallback_host?)
expect(@primary_host_request_count).to eql(1)
# A subsequent request should fail to the fallback, go the primary host and succeed
client.channel(channel_name).publish('event', 'data')
expect(@request_count).to eql(6)
expect(client.using_preferred_fallback_host?).to be_falsey
expect(@primary_host_request_count).to eql(2)
# A subsequent request will fail on the primary endpoint, and we expect the fallback to be used again
client.channel(channel_name).publish('event', 'data')
expect(@request_count).to eql(8)
expect(fallbacks).to include(client.using_preferred_fallback_host?)
successfull_fallback = client.using_preferred_fallback_host?
expect(@primary_host_request_count).to eql(3)
# Send another request, which should go straight to the fallback as it succeeded previously
client.channel(channel_name).publish('event', 'data')
expect(@request_count).to eql(9)
expect(successfull_fallback).to eql(client.using_preferred_fallback_host?)
expect(@primary_host_request_count).to eql(3)
end
context 'with custom :fallback_retry_timeout' do
let (:additional_client_options) { { fallback_retry_timeout: 5 } }
it 'stops using the preferred fallback after this time' do
# Send a request, expect primary endpoint to fail, one fallback to fail, second fallback to succeed
client.channel(channel_name).publish('event', 'data')
expect(@request_count).to eql(3)
expect(fallbacks).to include(client.using_preferred_fallback_host?)
expect(@primary_host_request_count).to eql(1)
# Wait for the preferred fallback cache to expire
sleep 5
# Send another request, which should go straight to the primary host again as fallback host is expired
client.channel(channel_name).publish('event', 'data')
expect(@primary_host_request_count).to eql(2)
end
end
end
end
end
context 'when environment is not production and server returns a 50x error' do
let(:env) { 'custom-env' }
let(:default_fallbacks) { %w(a b c d e).map { |id| "#{env}-#{id}-fallback.ably-realtime.com" } }
let(:custom_hosts) { %w(A.foo.com B.foo.com) }
let(:max_retry_count) { 2 }
let(:max_retry_duration) { 0.5 }
let(:fallback_block) { proc { raise Faraday::SSLError.new('ssl error message') } }
let(:production_options) do
default_options.merge(
environment: env,
key: api_key,
http_max_retry_duration: max_retry_duration,
http_max_retry_count: max_retry_count,
log_level: :fatal,
)
end
let(:status) { 502 }
let(:fallback_block) do
proc do
{
headers: { 'Content-Type' => 'text/html' },
status: status
}
end
end
let!(:default_host_request_stub) do
stub_request(:post, "https://#{env}-#{Ably::Rest::Client::DOMAIN}#{path}").to_return(&fallback_block)
end
context 'with no fallback hosts provided (#TBC, see https://github.com/ably/wiki/issues/361)' do
let(:client_options) {
production_options.merge(log_level: :fatal)
}
it 'uses the default fallback hosts for that environment as this is not an authentication failure' do
fallbacks_called_count = 0
default_fallbacks.each do |host|
counting_fallback_proc = proc do
fallbacks_called_count += 1
fallback_block.call
end
stub_request(:post, "https://#{host}#{path}").to_return(&counting_fallback_proc)
end
expect { publish_block.call }.to raise_error(Ably::Exceptions::ServerError)
expect(default_host_request_stub).to have_been_requested
expect(fallbacks_called_count).to be >= 2
end
end
context 'with custom fallback hosts provided (#RSC15b, #TO3k6)' do
let!(:first_fallback_request_stub) do
stub_request(:post, "https://#{custom_hosts[0]}#{path}").to_return(&fallback_block)
end
let!(:second_fallback_request_stub) do
stub_request(:post, "https://#{custom_hosts[1]}#{path}").to_return(&fallback_block)
end
let(:client_options) {
production_options.merge(fallback_hosts: custom_hosts, log_level: :fatal)
}
it 'attempts the fallback hosts as this is not an authentication failure' do
expect { publish_block.call }.to raise_error(Ably::Exceptions::ServerError)
expect(default_host_request_stub).to have_been_requested
expect(first_fallback_request_stub).to have_been_requested
expect(second_fallback_request_stub).to have_been_requested
end
end
context 'with an empty array of fallback hosts provided (#RSC15b, #TO3k6)' do
let(:client_options) {
production_options.merge(fallback_hosts: [], log_level: :fatal)
}
it 'does not attempt the fallback hosts as this is an authentication failure' do
expect { publish_block.call }.to raise_error(Ably::Exceptions::ServerError)
expect(default_host_request_stub).to have_been_requested
end
end
context 'with fallback_hosts_use_default: true (#RSC15b, #TO3k7)' do
let(:custom_hosts) { Ably::FALLBACK_HOSTS[0...2] }
before do
stub_const 'Ably::FALLBACK_HOSTS', custom_hosts
end
let!(:first_fallback_request_stub) do
stub_request(:post, "https://#{Ably::FALLBACK_HOSTS[0]}#{path}").to_return(&fallback_block)
end
let!(:second_fallback_request_stub) do
stub_request(:post, "https://#{Ably::FALLBACK_HOSTS[1]}#{path}").to_return(&fallback_block)
end
let(:client_options) {
production_options.merge(fallback_hosts: custom_hosts, log_level: :fatal)
}
it 'attempts the default fallback hosts as this is an authentication failure' do
expect { publish_block.call }.to raise_error(Ably::Exceptions::ServerError)
expect(default_host_request_stub).to have_been_requested
expect(first_fallback_request_stub).to have_been_requested
expect(second_fallback_request_stub).to have_been_requested
end
end
end
end
context 'with a custom host' do
let(:custom_host) { 'host.does.not.exist' }
let(:client_options) { default_options.merge(key: api_key, rest_host: custom_host) }
let(:capability) { { :foo => ["publish"] } }
context 'that does not exist' do
it 'fails immediately and raises a Faraday Error' do
expect { client.channel('test').publish('event', 'data') }.to raise_error Ably::Exceptions::ConnectionError
end
context 'fallback hosts', :webmock do
let(:path) { '/channels/test/publish' }
let!(:custom_host_request_stub) do
stub_request(:post, "https://#{custom_host}#{path}").to_return do
raise Faraday::ConnectionFailed.new('connection failure error message')
end
end
before do
Ably::FALLBACK_HOSTS.each do |host|
stub_request(:post, "https://#{host}#{path}").to_return do
raise 'Fallbacks should not be used with custom hosts'
end
end
end
specify 'are never used' do
expect { client.channel('test').publish('event', 'data') }.to raise_error Ably::Exceptions::ConnectionError
expect(custom_host_request_stub).to have_been_requested
end
end
end
context 'that times out', :webmock do
let(:path) { '/keys/app_id.key_name/requestToken' }
let!(:custom_host_request_stub) do
stub_request(:post, "https://#{custom_host}#{path}").to_return do
raise Faraday::TimeoutError.new('timeout error message')
end
end
it 'fails immediately and raises a Faraday Error' do
expect { client.auth.request_token }.to raise_error Ably::Exceptions::ConnectionTimeout
end
context 'fallback hosts' do
before do
Ably::FALLBACK_HOSTS.each do |host|
stub_request(:post, "https://#{host}#{path}").to_return do
raise 'Fallbacks should not be used with custom hosts'