forked from aws/aws-sdk-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent_listeners.spec.js
1555 lines (1466 loc) · 55.3 KB
/
event_listeners.spec.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Generated by CoffeeScript 1.12.3
(function() {
var AWS, MockService, helpers;
helpers = require('./helpers');
AWS = helpers.AWS;
MockService = helpers.MockService;
MockServiceFromApi = helpers.MockServiceFromApi;
var FooService = require('./foo-service.fixture').FooService;
describe('AWS.EventListeners', function() {
var completeHandler, config, delays, errorHandler, makeRequest, oldMathRandom, oldSetTimeout, randomValues, retryHandler, service, successHandler, totalWaited;
oldSetTimeout = setTimeout;
oldMathRandom = Math.random;
config = null;
service = null;
totalWaited = null;
delays = [];
successHandler = null;
errorHandler = null;
completeHandler = null;
retryHandler = null;
randomValues = [];
beforeEach(function(done) {
setTimeout = helpers.createSpy('setTimeout');;
setTimeout.andCallFake(function(callback, delay) {
totalWaited += delay;
delays.push(delay);
return callback();
});
totalWaited = 0;
delays = [];
service = new MockService({
maxRetries: 3
});
service.config.credentials = AWS.util.copy(service.config.credentials);
Math.random = helpers.createSpy('random');;
Math.random.andCallFake(function() {
var val;
val = oldMathRandom();
randomValues.push(val);
return val;
});
randomValues = [];
successHandler = helpers.createSpy('success');
errorHandler = helpers.createSpy('error');
completeHandler = helpers.createSpy('complete');
retryHandler = helpers.createSpy('retry');
return done();
});
afterEach(function() {
return setTimeout = oldSetTimeout; Math.random = oldMathRandom;
});
makeRequest = function(callback) {
var request;
request = service.makeRequest('mockMethod', {
foo: 'bar'
});
request.on('retry', retryHandler);
request.on('error', errorHandler);
request.on('success', successHandler);
request.on('complete', completeHandler);
if (callback) {
return request.send(callback);
} else {
return request;
}
};
describe('validate', function() {
it('takes the request object as a parameter', function() {
var request, response;
request = makeRequest();
request.on('validate', function(req) {
expect(req).to.equal(request);
throw 'ERROR';
});
response = request.send(function() {});
return expect(response.error.message).to.equal('ERROR');
});
it('sends error event if credentials are not set', function() {
service.config.credentialProvider = null;
service.config.credentials.accessKeyId = null;
makeRequest(function() {});
expect(errorHandler.calls.length).not.to.equal(0);
return AWS.util.arrayEach(errorHandler.calls, function(call) {
expect(call['arguments'][0]).to.be.instanceOf(Error);
expect(call['arguments'][0].code).to.equal('CredentialsError');
expect(call['arguments'][0].name).to.equal('CredentialsError');
return expect(call['arguments'][0].message).to.match(/Missing credentials/);
});
});
it('sends error event if credentials are not set', function() {
service.config.credentials.accessKeyId = 'akid';
service.config.credentials.secretAccessKey = null;
makeRequest(function() {});
expect(errorHandler.calls.length).not.to.equal(0);
return AWS.util.arrayEach(errorHandler.calls, function(call) {
expect(call['arguments'][0]).to.be.instanceOf(Error);
expect(call['arguments'][0].code).to.equal('CredentialsError');
expect(call['arguments'][0].name).to.equal('CredentialsError');
return expect(call['arguments'][0].message).to.match(/Missing credentials/);
});
});
it('does not validate credentials if request is not signed', function() {
var request;
helpers.mockHttpResponse(200, {}, '');
service.api = new AWS.Model.Api({
metadata: {
endpointPrefix: 'mockservice',
signatureVersion: null
}
});
request = makeRequest();
request.send(function() {});
expect(errorHandler.calls.length).to.equal(0);
return expect(successHandler.calls.length).not.to.equal(0);
});
[null, undefined, ''].forEach(function(region) {
it('sends error event if region is ' + region, function() {
var call, request;
helpers.mockHttpResponse(200, {}, '');
service.config.region = region;
request = makeRequest(function() {});
call = errorHandler.calls[0];
expect(errorHandler.calls.length).not.to.equal(0);
expect(call['arguments'][0]).to.be.instanceOf(Error);
expect(call['arguments'][0].code).to.equal('ConfigError');
return expect(call['arguments'][0].message).to.match(/Missing region in config/);
});
});
[
'has_underscore',
'-starts-with-dash',
'ends-with-dash-',
'-starts-and-ends-with-dash-',
'-',
'c0nt@in$-$ymb01$',
'0123456789012345678901234567890123456789012345678901234567890123', // 64 characters
].forEach(function(region) {
it('sends error event if region is "' + region + '"', function() {
var call, request;
helpers.mockHttpResponse(200, {}, '');
service.config.region = region;
request = makeRequest(function() {});
call = errorHandler.calls[0];
expect(errorHandler.calls.length).not.to.equal(0);
expect(call['arguments'][0]).to.be.instanceOf(Error);
expect(call['arguments'][0].code).to.equal('ConfigError');
return expect(call['arguments'][0].message).to.match(/Invalid region in config/);
});
});
[
'a',
'ab',
'abc',
'contains-dashes-in-the-middle',
'123StartsWithNumbers',
'EndsWithNumbers123',
'123StartsAndEndsWithNumbers000',
'012345678901234567890123456789012345678901234567890123456789012', // 63 characters
].forEach(function(region) {
it('successful region validation if region is "' + region + '"', function() {
helpers.mockHttpResponse(200, {}, '');
service.config.region = region;
makeRequest(function() {});
return expect(errorHandler.calls.length).to.equal(0);
});
});
return it('ignores region validation if service has global endpoint', function() {
helpers.mockHttpResponse(200, {}, '');
service.config.region = null;
service.isGlobalEndpoint = true;
makeRequest(function() {});
expect(errorHandler.calls.length).to.equal(0);
return delete service.isGlobalEndpoint;
});
});
describe('build', function() {
return it('takes the request object as a parameter', function() {
var request, response;
helpers.mockHttpResponse(200, {}, '');
request = makeRequest();
request.on('build', function(req) {
expect(req).to.equal(request);
throw 'ERROR';
});
response = request.send(function() {});
return expect(response.error.message).to.equal('ERROR');
});
});
describe('afterBuild', function() {
var fs, request, sendRequest;
request = null;
fs = null;
sendRequest = function(body, callback) {
request = makeRequest();
request.removeAllListeners('sign');
request.on('build', function(req) {
return req.httpRequest.body = body;
});
if (callback) {
return request.send(callback);
} else {
request.send();
return request;
}
};
describe('add Transfer-Encoding header', function() {
it('when streaming payload is unsigned payload if content length is not available', function(done) {
var oldByteLength = AWS.util.string.byteLength;
helpers.spyOn(AWS.util.string, 'byteLength').andCallFake(function(chunk) {
throw new Error('Cannot determine length of ' + chunk);
});
var service = new FooService();
var req = service.putStream({
Body: 'NoLengthBody'
});
req.runTo('sign', function(err) {
expect(req.httpRequest.headers['Transfer-Encoding']).to.equal('chunked');
expect(!err).to.equal(true);
AWS.util.string.byteLength = oldByteLength;
done();
});
});
});
describe('adds Content-Length header', function() {
var contentLength;
contentLength = function(body) {
return sendRequest(body).httpRequest.headers['Content-Length'];
};
describe('when using unsigned authtype', function() {
it('when payload is a buffer', function() {
var service = new FooService();
var req = service.putStream({
Body: AWS.util.buffer.toBuffer('test')
});
req.runTo('sign', function(err) {
expect(req.httpRequest.headers['Content-Length']).to.equal(4);
expect(!err).to.equal(true);
});
});
it('when payload is a string', function() {
var service = new FooService();
var req = service.putStream({
Body: 'test'
});
req.runTo('sign', function(err) {
expect(req.httpRequest.headers['Content-Length']).to.equal(4);
expect(!err).to.equal(true);
});
});
if (AWS.util.isNode()) {
it('when payload is a file stream', function() {
var service = new FooService();
var req = service.putStream({
Body: require('fs').createReadStream(__filename)
});
req.runTo('sign', function(err) {
expect(req.httpRequest.headers['Content-Length'] > 0).to.equal(true);
expect(!err).to.equal(true);
});
});
it('unless payload is a non-file stream', function() {
var service = new FooService();
var req = service.putStream({
Body: new AWS.util.stream.Readable()
});
req.runTo('sign', function(err) {
expect(typeof req.httpRequest.headers['Content-Length']).to.equal('undefined');
expect(!err).to.equal(true);
});
});
}
});
it('builds Content-Length in the request headers for string content', function() {
return expect(contentLength('FOOBAR')).to.equal(6);
});
it('builds Content-Length for string "0"', function() {
return expect(contentLength('0')).to.equal(1);
});
it('builds Content-Length for utf-8 string body', function() {
return expect(contentLength('tï№')).to.equal(6);
});
it('builds Content-Length for buffer body', function() {
return expect(contentLength(AWS.util.buffer.toBuffer('tï№'))).to.equal(6);
});
describe ('when has requiresLength trait exists', function() {
var oldByteLength = AWS.util.string.byteLength;
var service = new FooService();
beforeEach(function() {
helpers.spyOn(AWS.util.string, 'byteLength').andCallFake(function(chunk) {
throw new Error('Cannot determine length of ' + chunk);
});
});
afterEach(function() {
AWS.util.string.byteLength = oldByteLength;
});
it('throws error when content length is required in payload shape but length is not available', function(done) {
var req = service.putBoundedStream({
Body: 'NoLengthBody'
});
//this event listener will raise error even before setting content length
req.removeListener('afterBuild', AWS.EventListeners.Core.COMPUTE_SHA256);
req.runTo('sign', function(err) {
expect(err.message).to.contain('Cannot determine length of');
done();
});
});
it('throws error when content length is required in unsigned payload shape but length is not available', function(done) {
var req = service.putUnsignedBoundedStream({
Body: 'NoLengthBody'
});
req.runTo('sign', function(err) {
expect(err.message).to.contain('Cannot determine length of');
done();
});
});
});
it('throws error when non-streaming body has no length', function(done) {
var oldByteLength = AWS.util.string.byteLength;
var service = new FooService();
helpers.spyOn(AWS.util.string, 'byteLength').andCallFake(function(chunk) {
throw new Error('Cannot determine length of ' + chunk);
});
var req = service.putNonStream({
Body: 'NoLengthBody'
});
req.runTo('sign', function(err) {
AWS.util.string.byteLength = oldByteLength;
expect(err.message).to.contain('Cannot determine length of');
done();
});
});
if (AWS.util.isNode()) {
it('builds Content-Length for file body', function(done) {
var file;
fs = require('fs');
file = fs.createReadStream(__filename);
return sendRequest(file, function(err) {
return done();
});
});
it('throws an error for non-file body', function(done) {
sendRequest(new AWS.util.stream.Readable(), function(err) {
expect(typeof err).not.to.equal('undefined');
expect(err.message).to.equal('Non-file stream objects are not supported with SigV4');
done();
});
});
}
});
describe('adds Content-MD5 header', function() {
it('when payload is a string', function() {
var service = new FooService();
var req = service.putWithChecksum({
Body: 'test'
});
req.runTo('sign', function(err) {
expect(req.httpRequest.headers['Content-MD5']).to.equal('mi9mZPtVgELD8CntO010Rw==');
expect(!err).to.equal(true);
});
});
it('when using signature v2', function() {
var service = new FooService({ signatureVersion: 's3' });
var req = service.putWithChecksum({
Body: 'test'
});
req.runTo('sign', function(err) {
expect(req.httpRequest.headers['Content-MD5']).to.equal('mi9mZPtVgELD8CntO010Rw==');
expect(!err).to.equal(true);
});
});
it('should be disabled if computeChecksums set to false', function() {
var service = new FooService({
computeChecksums: false
});
var req = service.putWithChecksum({
Body: 'test'
});
req.runTo('sign', function(err) {
expect(req.httpRequest.headers['Content-MD5']).to.equal(undefined);
expect(!err).to.equal(true);
});
});
it('should not calculate checksum if provided', function() {
var service = new FooService({
computeChecksums: false
});
var req = service.putWithChecksum({
Body: 'test'
});
req.on('build', function(req) {
req.httpRequest.headers['Content-MD5'] = '000';
});
req.runTo('sign', function(err) {
expect(req.httpRequest.headers['Content-MD5']).to.equal('000');
expect(!err).to.equal(true);
});
});
});
describe('adds X-Amzn-Trace-Id header', function() {
if (AWS.util.isNode()) {
var originalEnv = process.env;
beforeEach(function() {
process.env = {};
});
afterEach(function() {
process.env = originalEnv;
});
it('when AWS_LAMBDA_FUNCTION_NAME and _X_AMZN_TRACE_ID env exists', function () {
helpers.mockHttpResponse(200, {}, '');
process.env = {
'AWS_LAMBDA_FUNCTION_NAME': 'some-function',
'_X_AMZN_TRACE_ID': 'Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1;lineage=a87bd80c:0,68fd508a:5,c512fbe3:2',
};
var request = sendRequest();
request.send(function (err) {
expect(err).to.equal(null);
expect(request.httpRequest.headers['X-Amzn-Trace-Id']).to.equal('Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1;lineage=a87bd80c:0,68fd508a:5,c512fbe3:2');
});
});
it('should not set trace id header when AWS_LAMBDA_FUNCTION_NAME is not set', function () {
helpers.mockHttpResponse(200, {}, '');
process.env = {
'_X_AMZN_TRACE_ID': 'Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1;lineage=a87bd80c:0,68fd508a:5,c512fbe3:2',
};
var request = sendRequest();
request.send(function (err) {
expect(err).to.equal(null);
expect(request.httpRequest.headers['X-Amzn-Trace-Id']).to.equal(undefined);
});
});
it('should not set trace id header when the header is already set', function () {
helpers.mockHttpResponse(200, {}, '');
process.env = {
'AWS_LAMBDA_FUNCTION_NAME': 'some-function',
'_X_AMZN_TRACE_ID': 'EnvValue'
};
request = makeRequest();
request.on('build', function(req) {
req.httpRequest.headers['X-Amzn-Trace-Id'] = 'OriginalValue';
});
response = request.send(function() {});
expect(request.httpRequest.headers['X-Amzn-Trace-Id']).to.equal('OriginalValue');
});
}
});
});
describe('restart', function() {
var request;
request = null;
return it('constructs a fresh httpRequest object', function() {
var httpRequest;
request = makeRequest();
httpRequest = request.httpRequest;
request.on('build', function() {
var err;
if (!this.threwSimulatedError) {
this.threwSimulatedError = true;
err = new Error('simulated error');
err.retryable = true;
throw err;
}
});
request.build();
return expect(request.httpRequest).not.to.eql(httpRequest);
});
});
describe('sign', function() {
it('takes the request object as a parameter', function() {
var request, response;
helpers.mockHttpResponse(200, {}, '');
request = makeRequest();
request.on('sign', function(req) {
expect(req).to.equal(request);
throw 'ERROR';
});
response = request.send(function() {});
return expect(response.error.message).to.equal('ERROR');
});
return it('uses the signingName from service', function() {
var request, response;
helpers.mockHttpResponse(200, {}, '');
service.getSigningName = function() { return 'SIGNING_NAME';};
helpers.spyOn(AWS.Signers.RequestSigner, 'getVersion').andCallFake(function() {
return function(req, signingName) {
throw signingName;
};
});
request = makeRequest();
response = request.send(function() {});
expect(response.error).to.equal('SIGNING_NAME');
return delete service.api.signingName;
});
});
describe('send', function() {
it('passes httpOptions from config', function() {
var options;
options = {};
helpers.spyOn(AWS.HttpClient, 'getInstance').andReturn({
handleRequest: function(req, opts) {
options = opts;
return new AWS.SequentialExecutor();
}
});
service.config.httpOptions = {
timeout: 15
};
service.config.maxRetries = 0;
makeRequest(function() {});
return expect(options.timeout).to.equal(15);
});
it('signs only once in normal case', function(done) {
var request, signHandler;
signHandler = helpers.createSpy('sign');
helpers.mockHttpResponse(200, {}, ['data']);
request = makeRequest();
request.on('sign', signHandler);
request.build();
request.signedAt = new Date(request.signedAt - 60 * 5 * 1000);
request.send();
expect(signHandler.calls.length).to.equal(1);
return done();
});
return it('resigns if it took more than 10 min to get to send', function(done) {
var request, signHandler;
signHandler = helpers.createSpy('sign');
helpers.mockHttpResponse(200, {}, ['data']);
request = makeRequest();
request.on('sign', signHandler);
request.build();
request.signedAt = new Date(request.signedAt - 60 * 12 * 1000);
request.send();
expect(signHandler.calls.length).to.equal(2);
return done();
});
});
describe('httpHeaders', function() {
return it('applies clock skew offset when correcClockSkew is true', function() {
var offset, request, response, serverDate;
service = new MockService({
maxRetries: 3,
correctClockSkew: true
});
serverDate = new Date(new Date().getTime() - 300000);
helpers.mockHttpResponse(200, {
date: serverDate.toString()
}, '');
helpers.spyOn(service, 'isClockSkewed').andReturn(true);
request = makeRequest();
response = request.send();
offset = Math.abs(service.config.systemClockOffset);
expect(offset > 299000 && offset < 310000).to.equal(true);
});
});
describe('httpData', function() {
beforeEach(function() {
return helpers.mockHttpResponse(200, {}, ['FOO', 'BAR', 'BAZ', 'QUX']);
});
it('emits httpData event on each chunk', function(done) {
var calls, request;
calls = [];
request = makeRequest();
request.on('httpData', function(chunk) {
return calls.push(chunk.toString());
});
request.send();
expect(calls).to.eql(['FOO', 'BAR', 'BAZ', 'QUX']);
return done();
});
it('does not clear default httpData event if another is added', function(done) {
var request, response;
request = makeRequest();
request.on('httpData', function() {});
response = request.send();
expect(response.httpResponse.body.toString()).to.equal('FOOBARBAZQUX');
return done();
});
return it('disables httpData if createUnbufferedStream() is called', function(done) {
var calls, request, stream;
calls = [];
stream = null;
helpers.mockHttpResponse(200, {}, ['data1', 'data2', 'data3']);
request = makeRequest();
request.on('httpData', function(chunk) {
return calls.push(chunk.toString());
});
request.on('httpHeaders', function(statusCode, headers) {
return stream = request.response.httpResponse.createUnbufferedStream();
});
request.send();
expect(calls.length).to.equal(0);
expect(stream).to.exist;
return done();
});
});
if (AWS.util.isNode() && AWS.HttpClient.streamsApiVersion > 1) {
describe('httpDownloadProgress', function() {
beforeEach(function() {
return helpers.mockHttpResponse(200, {
'content-length': 12
}, ['FOO', 'BAR', 'BAZ', 'QUX']);
});
return it('emits httpDownloadProgress for each chunk', function() {
var progress, request;
progress = [];
request = makeRequest();
request.on('httpDownloadProgress', function(p) {
return progress.push(p);
});
request.send();
expect(progress[0]).to.eql({
loaded: 3,
total: 12
});
expect(progress[1]).to.eql({
loaded: 6,
total: 12
});
expect(progress[2]).to.eql({
loaded: 9,
total: 12
});
return expect(progress[3]).to.eql({
loaded: 12,
total: 12
});
});
});
}
describe('httpError', function() {
it('rewrites ENOTFOUND error to include helpful message', function() {
var request;
helpers.mockHttpResponse({
code: 'NetworkingError',
errno: 'ENOTFOUND',
region: 'mock-region',
hostname: 'svc.mock-region.example.com',
retryable: true
});
request = makeRequest();
request.send();
expect(request.response.error.code).to.equal('UnknownEndpoint');
return expect(request.response.error.message).to.contain('This service may not be available in the `mock-region\' region.');
});
if (AWS.util.getSystemErrorName) {
// errno is a number after Node 12
// reference: https://github.com/nodejs/node/pull/28140
it('rewrites ENOTFOUND error to include helpful message when errno is number', function() {
var request;
helpers.mockHttpResponse({
code: 'NetworkingError',
errno: -3008,
region: 'mock-region',
hostname: 'svc.mock-region.example.com',
retryable: true
});
request = makeRequest();
request.send();
expect(request.response.error.code).to.equal('UnknownEndpoint');
return expect(request.response.error.message).to.contain('This service may not be available in the `mock-region\' region.');
});
}
return it('retries ENOTFOUND errors', function() {
var request, response, sendHandler;
helpers.mockHttpResponse({
code: 'NetworkingError',
errno: 'ENOTFOUND',
region: 'mock-region',
hostname: 'svc.mock-region.example.com',
retryable: true
});
service.config.maxRetries = 10;
sendHandler = helpers.createSpy('send');
request = makeRequest();
request.on('send', sendHandler);
response = request.send();
expect(retryHandler.calls.length).not.to.equal(0);
expect(errorHandler.calls.length).not.to.equal(0);
expect(completeHandler.calls.length).not.to.equal(0);
expect(successHandler.calls.length).to.equal(0);
expect(response.retryCount).to.equal(service.config.maxRetries);
return expect(sendHandler.calls.length).to.equal(service.config.maxRetries + 1);
});
});
describe('retry', function() {
it('retries a request with a set maximum retries', function() {
var request, response, sendHandler;
sendHandler = helpers.createSpy('send');
service.config.maxRetries = 10;
helpers.mockHttpResponse({
code: 'NetworkingError',
message: 'Cannot connect'
});
request = makeRequest();
request.on('send', sendHandler);
response = request.send(function() {});
expect(retryHandler.calls.length).not.to.equal(0);
expect(errorHandler.calls.length).not.to.equal(0);
expect(completeHandler.calls.length).not.to.equal(0);
expect(successHandler.calls.length).to.equal(0);
expect(response.retryCount).to.equal(service.config.maxRetries);
return expect(sendHandler.calls.length).to.equal(service.config.maxRetries + 1);
});
it('retries with falloff', function() {
var baseDelays, expectedDelays, i;
helpers.mockHttpResponse({
code: 'NetworkingError',
message: 'Cannot connect'
});
makeRequest(function() {});
baseDelays = [100, 200, 400];
expectedDelays = (function() {
var j, ref, results;
results = [];
for (i = j = 0, ref = service.numRetries() - 1; 0 <= ref ? j <= ref : j >= ref; i = 0 <= ref ? ++j : --j) {
results.push(baseDelays[i] * randomValues[i]);
}
return results;
})();
return expect(delays).to.eql(expectedDelays);
});
it('retries with falloff using custom base', function() {
var baseDelays, expectedDelays, i;
service.config.update({
retryDelayOptions: {
base: 30
}
});
helpers.mockHttpResponse({
code: 'NetworkingError',
message: 'Cannot connect'
});
makeRequest(function() {});
baseDelays = [30, 60, 120];
expectedDelays = (function() {
var j, ref, results;
results = [];
for (i = j = 0, ref = service.numRetries() - 1; 0 <= ref ? j <= ref : j >= ref; i = 0 <= ref ? ++j : --j) {
results.push(baseDelays[i] * randomValues[i]);
}
return results;
})();
return expect(delays).to.eql(expectedDelays);
});
it('retries with falloff using custom backoff', function() {
service.config.update({
retryDelayOptions: {
customBackoff: function(retryCount) {
return 2 * retryCount;
}
}
});
helpers.mockHttpResponse({
code: 'NetworkingError',
message: 'Cannot connect'
});
makeRequest(function() {});
return expect(delays).to.eql([0, 2, 4]);
});
it('retries with falloff using custom backoff instead of base', function() {
service.config.update({
retryDelayOptions: {
base: 100,
customBackoff: function(retryCount) {
return 2 * retryCount;
}
}
});
helpers.mockHttpResponse({
code: 'NetworkingError',
message: 'Cannot connect'
});
makeRequest(function() {});
return expect(delays).to.eql([0, 2, 4]);
});
it('skips retries if custom backoff returns negative delay', function() {
service.config.update({
retryDelayOptions: {
customBackoff: function(retryCount, err) {
if (err.code === 'NetworkingError') {
return -1;
} else {
return 2 * retryCount;
}
}
}
});
helpers.mockHttpResponse({
code: 'NetworkingError',
message: 'Cannot connect'
});
makeRequest(function() {});
return expect(delays).to.eql([]);
});
it('uses retry from error.retryDelay property', function() {
var request, response;
helpers.mockHttpResponse({
code: 'NetworkingError',
message: 'Cannot connect'
});
request = makeRequest();
request.on('retry', function(resp) {
return resp.error.retryDelay = 17;
});
response = request.send(function() {});
return expect(delays).to.eql([17, 17, 17]);
});
it('retries if status code is >= 500', function() {
helpers.mockHttpResponse(500, {}, '');
return makeRequest(function(err) {
expect(err.code).to.equal(500);
expect(err.message).to.equal(null);
expect(err.statusCode).to.equal(500);
expect(err.retryable).to.equal(true);
return expect(this.retryCount).to.equal(service.config.maxRetries);
});
});
it('should not emit error if retried fewer than maxRetries', function() {
var baseDelays, expectedDelays, i, response;
helpers.mockIntermittentFailureResponse(2, 200, {}, 'foo');
response = makeRequest(function() {});
baseDelays = [100, 200];
expectedDelays = (function() {
var j, ref, results;
results = [];
for (i = j = 0, ref = delays.length - 1; 0 <= ref ? j <= ref : j >= ref; i = 0 <= ref ? ++j : --j) {
results.push(baseDelays[i] * randomValues[i]);
}
return results;
})();
expect(totalWaited).to.equal(expectedDelays.reduce(function(a, b) {
return a + b;
}));
expect(response.retryCount).to.be.lessThan(service.config.maxRetries);
expect(response.data).to.equal('foo');
return expect(errorHandler.calls.length).to.equal(0);
});
['ExpiredToken', 'ExpiredTokenException', 'RequestExpired'].forEach(function(name) {
return it('invalidates expired credentials and retries', function() {
var creds, response;
helpers.spyOn(AWS.HttpClient, 'getInstance');
AWS.HttpClient.getInstance.andReturn({
handleRequest: function(req, opts, cb, errCb) {
if (req.headers.Authorization.match('Credential=INVALIDKEY')) {
helpers.mockHttpSuccessfulResponse(403, {}, name, cb);
} else {
helpers.mockHttpSuccessfulResponse(200, {}, 'DATA', cb);
}
return new AWS.SequentialExecutor();
}
});
creds = {
numCalls: 0,
expired: false,
accessKeyId: 'INVALIDKEY',
secretAccessKey: 'INVALIDSECRET',
get: function(cb) {
if (this.expired) {
this.numCalls += 1;
this.expired = false;
this.accessKeyId = 'VALIDKEY' + this.numCalls;
this.secretAccessKey = 'VALIDSECRET' + this.numCalls;
}
return cb();
}
};
service.config.credentials = creds;
response = makeRequest(function() {});
expect(response.retryCount).to.equal(1);
expect(creds.accessKeyId).to.equal('VALIDKEY1');
return expect(creds.secretAccessKey).to.equal('VALIDSECRET1');
});
});
it('retries an expired signature error', function() {
var request, response;
helpers.mockHttpResponse(403, {}, '');
request = makeRequest();
request.on('extractError', function(resp) {
return resp.error = {
code: 'SignatureDoesNotMatch',
message: 'Signature expired: 10 is now earlier than 20',
retryable: false
};
});
response = request.send();
return expect(response.retryCount).to.equal(service.config.maxRetries);
});
['RequestTimeTooSkewed', 'RequestExpired', 'RequestInTheFuture', 'InvalidSignatureException', 'SignatureDoesNotMatch', 'AuthFailure'].forEach(function(code) {
return it('retries clock skew errors', function() {
var request, response;
helpers.mockHttpResponse(400, {}, '');
service = new MockService({
maxRetries: 3,
correctClockSkew: true
});
request = makeRequest();
request.on('extractError', function(resp) {
return resp.error = {
code: code,
message: 'Client clock is skewed'
};
});
response = request.send();
return expect(response.retryCount).to.equal(service.config.maxRetries);
});
});
it('does not apply clock skew correction when correctClockSkew is false', function() {
var request, response;
helpers.mockHttpResponse(400, {}, '');
service = new MockService({
maxRetries: 3,
correctClockSkew: false
});
request = makeRequest();
request.on('extractError', function(resp) {
return resp.error = {
code: 'RequestTimeTooSkewed',
message: 'Client clock is skewed'
};
});
response = request.send();
return expect(response.retryCount).to.equal(0);
});
it('does not retry other signature errors if clock is not skewed', function() {
var request, response;
helpers.mockHttpResponse(403, {}, '');
service = new MockService({
maxRetries: 3,
correctClockSkew: false
});
request = makeRequest();
request.on('extractError', function(resp) {
return resp.error = {
code: 'SignatureDoesNotMatch',
message: 'Invalid signature',
retryable: false
};
});
response = request.send();
return expect(response.retryCount).to.equal(0);
});
[301, 307].forEach(function(code) {
return it('attempts to redirect on ' + code + ' responses', function() {
var response;
helpers.mockHttpResponse(code, {
location: 'http://redirected'
}, '');
service.config.maxRetries = 0;
service.config.maxRedirects = 5;
response = makeRequest(function() {});