-
Notifications
You must be signed in to change notification settings - Fork 392
/
Copy pathtest-utils.js
1340 lines (1144 loc) · 63.1 KB
/
test-utils.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
'use strict';
const sinon = require('sinon');
const expect = require('expect.js');
var awsV3Mock = require('aws-sdk-client-mock');
const {
CreateAliasCommand, DeleteAliasCommand, DeleteFunctionCommand, GetAliasCommand,
GetFunctionConfigurationCommand, InvokeCommand, LambdaClient, PublishVersionCommand,
UpdateFunctionConfigurationCommand, UpdateAliasCommand, ResourceNotFoundException,
} = require('@aws-sdk/client-lambda');
const { GetObjectCommand, S3Client } = require('@aws-sdk/client-s3');
process.env.sfCosts = `{"us-gov-west-1": 0.00003,"eu-north-1": 0.000025,
"eu-central-1": 0.000025,"us-east-1": 0.000025,"ap-northeast-1": 0.000025,
"ap-northeast-2": 0.0000271,"eu-south-1": 0.00002625,"af-south-1": 0.00002975,
"us-west-1": 0.0000279,"eu-west-3": 0.0000297,"ap-southeast-2": 0.000025,
"ap-east-1": 0.0000275,"eu-west-2": 0.000025,"me-south-1": 0.0000275,
"us-east-2": 0.000025,"ap-south-1": 0.0000285,"ap-southeast-1": 0.000025,
"us-gov-east-1": 0.00003,"ca-central-1": 0.000025,"eu-west-1": 0.000025,
"us-west-2": 0.000025,"sa-east-1": 0.0000375}`;
process.env.baseCosts = '{"x86_64": {"ap-east-1":2.9e-9,"af-south-1":2.8e-9,"me-south-1":2.6e-9,"eu-south-1":2.4e-9,"default":2.1e-9}, "arm64": {"default":1.7e-9}}';
process.env.AWS_REGION = 'af-south-1';
const utils = require('../../lambda/utils');
const { consoleLogStub: consoleLogSetupStub } = require('../setup.spec');
const sandBox = sinon.createSandbox();
// AWS SDK mocks
const lambdaMock = awsV3Mock.mockClient(LambdaClient);
lambdaMock.reset();
lambdaMock.on(GetAliasCommand).resolves({});
lambdaMock.on(GetFunctionConfigurationCommand).resolves({
MemorySize: 1024,
State: 'Active',
LastUpdateStatus: 'Successful',
Architectures: ['x86_64'],
Description: 'Sample Description',
});
lambdaMock.on(UpdateFunctionConfigurationCommand).resolves({});
lambdaMock.on(PublishVersionCommand).resolves({});
lambdaMock.on(DeleteFunctionCommand).resolves({});
lambdaMock.on(CreateAliasCommand).resolves({});
lambdaMock.on(DeleteAliasCommand).resolves({});
lambdaMock.on(InvokeCommand).resolves({});
lambdaMock.on(UpdateAliasCommand).resolves({});
const s3Mock = awsV3Mock.mockClient(S3Client);
s3Mock.reset();
s3Mock.on(GetObjectCommand).resolves({
Body: {
transformToString: async(encoding) => {
return '{"Value": "OK"}';
},
},
});
// utility to create a UInt8Array from a string
const toByteArray = (inputString) => {
const textEncoder = new TextEncoder();
return textEncoder.encode(inputString);
};
describe('Lambda Utils', () => {
// I'm dynamically generating tests for all these utilities
const lambdaUtilities = [
utils.getLambdaAlias,
utils.setLambdaPower,
utils.publishLambdaVersion,
utils.deleteLambdaVersion,
utils.createLambdaAlias,
utils.updateLambdaAlias,
utils.deleteLambdaAlias,
utils.invokeLambda,
utils.invokeLambdaWithProcessors,
utils.waitForFunctionUpdate,
];
// just returns the utility name for convenience
function _fname(func) {
const keys = Object.keys(utils);
for (let name of keys) {
if (utils[name] === func) {
return name;
}
}
throw new Error('Export not found! ' + func);
}
// this is mainly for coverage (it's not doing much, just making sure the code runs)
lambdaUtilities.forEach(func => {
describe(_fname(func), () => {
it('should return a promise', () => {
const result = func('arn:aws:lambda:us-east-1:XXX:function:YYY', 'test', 'test');
expect(result).to.be.an('object');
});
// TODO add more tests!
});
});
afterEach('Global mock utilities afterEach', () => {
// restore everything to its natural order
sandBox.restore();
});
describe('stepFunctionsBaseCost', () => {
it('should return expected step base cost', () => {
process.env.sfCosts = '{"us-gov-west-1": 0.00003, "default": 0.000025}';
process.env.AWS_REGION = 'us-gov-west-1';
const result = utils.stepFunctionsBaseCost();
expect(result).to.be.equal(0.00003);
});
it('should return default step base cost', () => {
process.env.sfCosts = '{"us-gov-west-1": 0.00003, "default": 0.000025}';
process.env.AWS_REGION = 'af-south-1';
const result = utils.stepFunctionsBaseCost();
expect(result).to.be.equal(0.000025);
});
});
describe('stepFunctionsCost', () => {
it('should return expected step total cost', () => {
process.env.sfCosts = '{"us-gov-west-1": 0.00003, "default": 0.000025}';
process.env.AWS_REGION = 'us-gov-west-1';
const nPower = 10;
const expectedCost = 0.00108;
const result = utils.stepFunctionsCost(nPower, false, 10);
expect(result).to.be.equal(expectedCost);
});
it('should return expected step total cost when onlyColdStarts=true', () => {
process.env.sfCosts = '{"us-gov-west-1": 0.00003, "default": 0.000025}';
process.env.AWS_REGION = 'us-gov-west-1';
const nPower = 10;
const expectedCost = 0.00648;
const result = utils.stepFunctionsCost(nPower, true, 10);
expect(result).to.be.equal(expectedCost);
});
});
describe('getLambdaPower', () => {
it('should return the power value and description', async() => {
lambdaMock.on(GetFunctionConfigurationCommand).resolves({
MemorySize: 1024,
State: 'Active',
LastUpdateStatus: 'Successful',
Architectures: ['x86_64'],
Description: 'Sample Description', // this is null if no vars are set
});
const value = await utils.getLambdaPower('arn:aws:lambda:us-east-1:XXX:function:YYY');
expect(value.power).to.be(1024);
expect(value.description).to.be('Sample Description');
});
it('should return the power value and description, even if empty', async() => {
lambdaMock.on(GetFunctionConfigurationCommand).resolves({
MemorySize: 1024,
State: 'Active',
LastUpdateStatus: 'Successful',
Architectures: ['x86_64'],
Description: '', // this is null if no vars are set
});
const value = await utils.getLambdaPower('arn:aws:lambda:us-east-1:XXX:function:YYY');
expect(value.power).to.be(1024);
expect(value.description).to.be('');
});
});
describe('verifyAliasExistance', () => {
it('should return true if the alias exists', async() => {
sandBox.stub(utils, 'getLambdaAlias')
.callsFake(async() => {
return { FunctionVersion: '1' };
});
const aliasExists = await utils.verifyAliasExistance('arnOK', 'aliasName');
expect(aliasExists).to.be(true);
});
it('should return false if the alias does not exists', async() => {
sandBox.stub(utils, 'getLambdaAlias')
.callsFake(async() => {
const error = new ResourceNotFoundException('alias is not defined');
throw error;
});
const aliasExists = await utils.verifyAliasExistance('arnOK', 'aliasName');
expect(aliasExists).to.be(false);
});
});
describe('waitForFunctionUpdate', () => {
it('should return if LastUpdateStatus is successful', async() => {
// TODO: remove waitFor mock and test this properly
await utils.waitForFunctionUpdate('arn:aws:lambda:us-east-1:XXX:function:YYY');
});
});
describe('waitForAliasActive', () => {
it('should return if Status is Active', async() => {
// TODO: remove waitFor mock and test this properly
await utils.waitForAliasActive('arn:aws:lambda:us-east-1:XXX:function:YYY', 'aliasName');
});
});
const textLog =
'START RequestId: 55bc566d-1e2c-11e7-93e6-6705ceb4c1cc Version: $LATEST\n' +
'END RequestId: 55bc566d-1e2c-11e7-93e6-6705ceb4c1cc\n' +
'REPORT RequestId: 55bc566d-1e2c-11e7-93e6-6705ceb4c1cc\tDuration: 469.40 ms\tBilled Duration: 500 ms\tMemory Size: 1024 MB\tMax Memory Used: 21 MB\tInit Duration: 100.99 ms'
;
const textLogSnapStart =
'START RequestId: 55bc566d-1e2c-11e7-93e6-6705ceb4c1cc Version: $LATEST\n' +
'END RequestId: 55bc566d-1e2c-11e7-93e6-6705ceb4c1cc\n' +
'REPORT RequestId: 55bc566d-1e2c-11e7-93e6-6705ceb4c1cc\tDuration: 469.40 ms\tBilled Duration: 500 ms\tMemory Size: 1024 MB\tMax Memory Used: 21 MB\tRestore Duration: 474.16 ms\tBilled Restore Duration: 75 ms'
;
// JSON logs contain multiple objects, seperated by a newline
const jsonLog =
'{"timestamp":"2024-02-09T08:42:44.078Z","level":"INFO","requestId":"d661f7cf-9208-46b9-85b0-213b04a91065","message":"Just some logs here =)"}\n' +
'{"time":"2024-02-09T08:42:44.078Z","type":"platform.start","record":{"requestId":"d661f7cf-9208-46b9-85b0-213b04a91065","version":"8"}}\n' +
'{"time":"2024-02-09T08:42:44.079Z","type":"platform.runtimeDone","record":{"requestId":"d661f7cf-9208-46b9-85b0-213b04a91065","status":"success","spans":[{"name":"responseLatency","start":"2024-02-09T08:42:44.078Z","durationMs":0.677},{"name":"responseDuration","start":"2024-02-09T08:42:44.079Z","durationMs":0.035},{"name":"runtimeOverhead","start":"2024-02-09T08:42:44.079Z","durationMs":0.211}],"metrics":{"durationMs":1.056,"producedBytes":50}}}\n' +
'{"time":"2024-02-09T08:42:44.080Z","type":"platform.report","record":{"requestId":"d661f7cf-9208-46b9-85b0-213b04a91065","status":"success","metrics":{"durationMs":1.317,"billedDurationMs":2,"memorySizeMB":1024,"maxMemoryUsedMB":68,"initDurationMs": 10}}}'
;
const jsonLogSnapStart =
'{"timestamp":"2024-02-09T08:42:44.078Z","level":"INFO","requestId":"d661f7cf-9208-46b9-85b0-213b04a91065","message":"Just some logs here =)"}\n' +
'{"time":"2024-02-09T08:42:44.078Z","type":"platform.start","record":{"requestId":"d661f7cf-9208-46b9-85b0-213b04a91065","version":"8"}}\n' +
'{"time":"2024-02-09T08:42:44.079Z","type":"platform.runtimeDone","record":{"requestId":"d661f7cf-9208-46b9-85b0-213b04a91065","status":"success","spans":[{"name":"responseLatency","start":"2024-02-09T08:42:44.078Z","durationMs":0.677},{"name":"responseDuration","start":"2024-02-09T08:42:44.079Z","durationMs":0.035},{"name":"runtimeOverhead","start":"2024-02-09T08:42:44.079Z","durationMs":0.211}],"metrics":{"durationMs":1.056,"producedBytes":50}}}\n' +
'{"time":"2024-02-09T08:42:44.080Z","type":"platform.report","record":{"requestId":"d661f7cf-9208-46b9-85b0-213b04a91065","status":"success","metrics":{"durationMs": 147.156,"billedDurationMs": 201, "memorySizeMB": 512,"maxMemoryUsedMB": 91,"restoreDurationMs": 500.795,"billedRestoreDurationMs": 53 }}}'
;
const jsonMixedLog =
'{"timestamp":"2024-02-09T08:42:44.078Z","level":"INFO","requestId":"d661f7cf-9208-46b9-85b0-213b04a91065","message":"Just some logs here =)"}\n' +
'[AWS Parameters and Secrets Lambda Extension] 2024/04/11 02:14:17 PARAMETERS_SECRETS_EXTENSION_LOG_LEVEL is info. Log level set to info.' +
'{"time":"2024-02-09T08:42:44.078Z","type":"platform.start","record":{"requestId":"d661f7cf-9208-46b9-85b0-213b04a91065","version":"8"}}\n' +
'{"time":"2024-02-09T08:42:44.079Z","type":"platform.runtimeDone","record":{"requestId":"d661f7cf-9208-46b9-85b0-213b04a91065","status":"success","spans":[{"name":"responseLatency","start":"2024-02-09T08:42:44.078Z","durationMs":0.677},{"name":"responseDuration","start":"2024-02-09T08:42:44.079Z","durationMs":0.035},{"name":"runtimeOverhead","start":"2024-02-09T08:42:44.079Z","durationMs":0.211}],"metrics":{"durationMs":1.056,"producedBytes":50}}}\n' +
'{"time":"2024-02-09T08:42:44.080Z","type":"platform.report","record":{"requestId":"d661f7cf-9208-46b9-85b0-213b04a91065","status":"success","metrics":{"durationMs":1.317,"billedDurationMs":4,"memorySizeMB":1024,"maxMemoryUsedMB":68,"initDurationMs": 20}}}'
;
const jsonMixedLogWithInvalidJSON =
'{"timestamp":"2024-02-09T08:42:44.078Z","level":"INFO","requestId":"d661f7cf-9208-46b9-85b0-213b04a91065","message":"Just some logs here =)"\n' + // missing } here
'[AWS Parameters and Secrets Lambda Extension] 2024/04/11 02:14:17 PARAMETERS_SECRETS_EXTENSION_LOG_LEVEL is info. Log level set to info.' +
'{"time":"2024-02-09T08:42:44.078Z","type":"platform.start","record":{"requestId":"d661f7cf-9208-46b9-85b0-213b04a91065","version":"8"}}\n' +
'{"time":"2024-02-09T08:42:44.079Z","type":"platform.runtimeDone","record":{"requestId":"d661f7cf-9208-46b9-85b0-213b04a91065","status":"success","spans":[{"name":"responseLatency","start":"2024-02-09T08:42:44.078Z","durationMs":0.677},{"name":"responseDuration","start":"2024-02-09T08:42:44.079Z","durationMs":0.035},{"name":"runtimeOverhead","start":"2024-02-09T08:42:44.079Z","durationMs":0.211}],"metrics":{"durationMs":1.056,"producedBytes":50}}}\n' +
'{"time":"2024-02-09T08:42:44.080Z","type":"platform.report","record":{"requestId":"d661f7cf-9208-46b9-85b0-213b04a91065","status":"success","metrics":{"durationMs":1.317,"billedDurationMs":8,"memorySizeMB":1024,"maxMemoryUsedMB":68,"initDurationMs": 30}}}'
;
const invalidJSONLog = '{"timestamp":"2024-02-09T08:42:44.078Z","level":"INFO","requestId":"d661f7cf-9208-46b9-85b0-213b04a91065","message":"Just some logs here =)"}';
describe('extractDuration', () => {
it('should extract the duration from a Lambda log (text format)', () => {
expect(utils.extractDuration(textLog)).to.be(469.4);
});
it('should retrieve the Init Duration from a Lambda log (text format)', () => {
expect(utils.extractDuration(textLog, utils.DURATIONS.initDurationMs)).to.be(100.99);
});
it('should retrieve the Billed Duration from a Lambda log (text format)', () => {
expect(utils.extractDuration(textLog, utils.DURATIONS.billedDurationMs)).to.be(500);
});
it('should retrieve the Restore Duration from a SnapStart Lambda log (text format)', () => {
expect(utils.extractDuration(textLogSnapStart, utils.DURATIONS.restoreDurationMs)).to.be(474.16);
});
it('should retrieve the Billed Restore Duration from a SnapStart Lambda log (text format)', () => {
expect(utils.extractDuration(textLogSnapStart, utils.DURATIONS.billedRestoreDurationMs)).to.be(75);
});
it('should return 0 if duration is not found', () => {
expect(utils.extractDuration('hello world')).to.be(0);
const partialLog = 'START RequestId: 55bc566d-1e2c-11e7-93e6-6705ceb4c1cc Version: $LATEST\n';
expect(utils.extractDuration(partialLog)).to.be(0);
});
it('should return 0 if Init Duration is not found', () => {
expect(utils.extractDuration('hello world', utils.DURATIONS.initDurationMs)).to.be(0);
const partialLog = 'START RequestId: 55bc566d-1e2c-11e7-93e6-6705ceb4c1cc Version: $LATEST\n';
expect(utils.extractDuration(partialLog, utils.DURATIONS.initDurationMs)).to.be(0);
});
it('should return 0 if Restore Duration is not found', () => {
expect(utils.extractDuration('hello world', utils.DURATIONS.restoreDurationMs)).to.be(0);
const partialLog = 'START RequestId: 55bc566d-1e2c-11e7-93e6-6705ceb4c1cc Version: $LATEST\n';
expect(utils.extractDuration(partialLog, utils.DURATIONS.restoreDurationMs)).to.be(0);
});
it('should return 0 if Billed Duration is not found', () => {
expect(utils.extractDuration('hello world', utils.DURATIONS.billedDurationMs)).to.be(0);
const partialLog = 'START RequestId: 55bc566d-1e2c-11e7-93e6-6705ceb4c1cc Version: $LATEST\n';
expect(utils.extractDuration(partialLog, utils.DURATIONS.billedDurationMs)).to.be(0);
});
it('should return 0 if Billed Restore Duration is not found', () => {
expect(utils.extractDuration('hello world', utils.DURATIONS.billedRestoreDurationMs)).to.be(0);
const partialLog = 'START RequestId: 55bc566d-1e2c-11e7-93e6-6705ceb4c1cc Version: $LATEST\n';
expect(utils.extractDuration(partialLog, utils.DURATIONS.billedRestoreDurationMs)).to.be(0);
});
it('should extract the duration from a Lambda log (json format)', () => {
expect(utils.extractDuration(jsonLog, utils.DURATIONS.durationMs)).to.be(1.317);
});
it('should extract the Init duration from a Lambda log (json format)', () => {
expect(utils.extractDuration(jsonLog, utils.DURATIONS.initDurationMs)).to.be(10);
});
it('should extract the Restore duration from a Lambda log (json format)', () => {
expect(utils.extractDuration(jsonLogSnapStart, utils.DURATIONS.restoreDurationMs)).to.be(500.795);
});
it('should extract the Billed Restore duration from a Lambda log (json format)', () => {
expect(utils.extractDuration(jsonLogSnapStart, utils.DURATIONS.billedRestoreDurationMs)).to.be(53);
});
it('should extract the duration from a Lambda log (json text mixed format)', () => {
expect(utils.extractDuration(jsonMixedLog)).to.be(1.317);
});
it('should extract the duration from a Lambda log (json text mixed format with invalid JSON)', () => {
expect(utils.extractDuration(jsonMixedLogWithInvalidJSON)).to.be(1.317);
});
it('should explode if invalid json format document is provided', () => {
expect(() => utils.extractDuration(invalidJSONLog)).to.throwError();
});
});
describe('computePrice', () => {
const minCost = 2.1e-9; // $ per ms
const minRAM = 128; // MB
const value = 1024; // MB
const averageDuration = 300; // ms
it('should return the average price', () => {
const avgPrice = utils.computePrice(minCost, minRAM, value, averageDuration);
expect(avgPrice).to.be.a('number');
expect(avgPrice).to.be(minCost * (value / minRAM) * averageDuration);
});
});
describe('parseLogAndExtractDurations', () => {
const results = [
// Duration 1ms
{ StatusCode: 200, LogResult: 'U1RBUlQgUmVxdWVzdElkOiA0NzlmYjUxYy0xZTM4LTExZTctOTljYS02N2JmMTYzNjA4ZWQgVmVyc2lvbjogOTkKMjAxNy0wNC0xMFQyMTo1NDozMi42ODNaCTQ3OWZiNTFj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WU3LTk5Y2EtNjdiZjE2MzYwOGVkClJFUE9SVCBSZXF1ZXN0SWQ6IDQ3OWZiNTFjLTFlMzgtMTFlNy05OWNhLTY3YmYxNjM2MDhlZAlEdXJhdGlvbjogMy4wIG1zCUJpbGxlZCBEdXJhdGlvbjogMyBtcyAJTWVtb3J5IFNpemU6IDEyOCBNQglNYXggTWVtb3J5IFVzZWQ6IDE1IE1C', Payload: 'null' },
];
it('should return the list of durations', () => {
const durations = utils.parseLogAndExtractDurations(results);
expect(durations).to.be.a('array');
expect(durations.length).to.be(5);
expect(durations).to.eql([1, 1, 2, 3, 3]);
});
it('should return empty list if empty results', () => {
const durations = utils.parseLogAndExtractDurations([]);
expect(durations).to.be.an('array');
expect(durations.length).to.be(0);
});
it('should not explode if missing logs', () => {
const durations = utils.parseLogAndExtractDurations([
{ StatusCode: 200, Payload: 'null' },
]);
expect(durations).to.be.an('array');
expect(durations).to.eql([0]);
});
it('should give duration as initDuration + duration', () => {
const resultWithInitDuration =
{
StatusCode: 200,
// Duration: 469.40 ms Init Duration: 100.99 ms
LogResult: Buffer.from(textLog).toString('base64'),
};
const durations = utils.parseLogAndExtractDurations([resultWithInitDuration]);
expect(durations).to.be.a('array');
expect(durations.length).to.be(1);
expect(durations).to.eql([570.39]);
});
it('should give duration as restoreDuration + duration (for SnapStart)', () => {
const resultWithInitDuration =
{
StatusCode: 200,
// Duration: 469.40 ms - Restore Duration: 474.16 ms
LogResult: Buffer.from(textLogSnapStart).toString('base64'),
};
const durations = utils.parseLogAndExtractDurations([resultWithInitDuration]);
expect(durations).to.be.a('array');
expect(durations.length).to.be(1);
expect(durations).to.eql([943.56]);
});
});
describe('parseLogAndExtractBilledDurations', () => {
const results = [
// Billed Duration 1ms
{ StatusCode: 200, LogResult: 'U1RBUlQgUmVxdWVzdElkOiA0NzlmYjUxYy0xZTM4LTExZTctOTljYS02N2JmMTYzNjA4ZWQgVmVyc2lvbjogOTkKMjAxNy0wNC0xMFQyMTo1NDozMi42ODNa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ZDogNDc5ZmI1MWMtMWUzOC0xMWU3LTk5Y2EtNjdiZjE2MzYwOGVkClJFUE9SVCBSZXF1ZXN0SWQ6IDQ3OWZiNTFjLTFlMzgtMTFlNy05OWNhLTY3YmYxNjM2MDhlZAlEdXJhdGlvbjogMy4wIG1zCUJpbGxlZCBEdXJhdGlvbjogMyBtcyAJTWVtb3J5IFNpemU6IDEyOCBNQglNYXggTWVtb3J5IFVzZWQ6IDE1IE1C', Payload: 'null' },
];
it('should return the list of billed durations', () => {
const durations = utils.parseLogAndExtractBilledDurations(results);
expect(durations).to.be.a('array');
expect(durations.length).to.be(5);
expect(durations).to.eql([1, 1, 2, 3, 3]);
});
it('should return empty list if empty results', () => {
const durations = utils.parseLogAndExtractBilledDurations([]);
expect(durations).to.be.an('array');
expect(durations.length).to.be(0);
});
it('should not explode if missing logs', () => {
const durations = utils.parseLogAndExtractBilledDurations([
{ StatusCode: 200, Payload: 'null' },
]);
expect(durations).to.be.an('array');
expect(durations).to.eql([0]);
});
it('should give duration as billedDuration + restoreDuration (for SnapStart)', () => {
const resultWithInitDuration =
{
StatusCode: 200,
// Billed Duration: 500 ms Billed Restore Duration: 75 ms
LogResult: Buffer.from(textLogSnapStart).toString('base64'),
};
const durations = utils.parseLogAndExtractBilledDurations([resultWithInitDuration]);
expect(durations).to.be.a('array');
expect(durations.length).to.be(1);
expect(durations).to.eql([575]);
});
});
describe('computeAverageDuration', () => {
const durations = [
// keep 5 values because it's the minimum length
// `num` can't be smaller than 5, unless it's a dryrun
1, 2, 3, 4, 2000,
];
it('should return the average duration', () => {
const duration = utils.computeAverageDuration(durations, 0.2);
expect(duration).to.be(3);
});
it('should return the average duration custom trimming', () => {
const duration = utils.computeAverageDuration(durations, 0.4);
expect(duration).to.be(3);
});
it('should return the average duration with no trimmed value', () => {
const duration = utils.computeAverageDuration(durations, 0);
expect(duration).to.be(402);
});
it('should return the average duration even if not enough results to discard', () => {
const duration = utils.computeAverageDuration([1], 0.4);
expect(duration).to.be(1);
});
it('should return 0 if empty results', () => {
const duration = utils.computeAverageDuration([], 0.2);
expect(duration).to.be(0);
});
});
describe('computeTotalCost', () => {
const minCost = 2.1e-9; // $ per ms
const minRAM = 128; // MB
const value = 1024; // MB
const durations = [
100, 150, 200, 300, 400,
];
// sum all
const totDuration = durations.reduce((a, b) => a + b, 0);
it('should return the total cost', () => {
const duration = utils.computeTotalCost(minCost, minRAM, value, durations);
expect(duration).to.be(minCost * (value / minRAM) * totDuration);
});
it('should return 0 if empty durations', () => {
const duration = utils.computeTotalCost(minCost, minRAM, value, []);
expect(duration).to.be(0);
});
});
describe('base64decode', () => {
it('should convert a string to base64', () => {
expect(utils.base64decode('aGVsbG8gd29ybGQ=')).to.be('hello world');
expect(utils.base64decode('bG9yZW0gaXBzdW0=')).to.be('lorem ipsum');
});
it('should explode with non-string arguments', () => {
expect(() => utils.base64decode(null)).to.throwError();
expect(() => utils.base64decode(undefined)).to.throwError();
expect(() => utils.base64decode(10)).to.throwError();
});
});
describe('range', () => {
it('should generate a list of size N', () => {
expect(utils.range(1)).to.be.an('array');
expect(utils.range(0)).to.have.length(0);
expect(utils.range(5)).to.have.length(5);
expect(utils.range(50)).to.have.length(50);
expect(utils.range(500)).to.have.length(500);
});
it('should explode when called with invalid arguments', () => {
[-1, -2, -Infinity, Infinity, null, undefined].forEach(val => {
expect(() => utils.range(val)).to.throwError();
});
});
});
describe('lambdaClientFromARN', () => {
it('should return the region name', () => {
const arn = 'arn:aws:lambda:us-east-1:XXX:function:YYY';
expect(utils.regionFromARN(arn)).to.be('us-east-1');
});
[undefined, null, 0, 10, '', 'arn:aws', {}].forEach(arn => {
it('should explode when called with "' + arn + '"', () => {
expect(() => utils.lambdaClientFromARN(arn)).to.throwError();
});
});
});
describe('buildVisualizationURL', () => {
const stats = [
{ power: 1, duration: 2, cost: 3 },
{ power: 2, duration: 2, cost: 2 },
{ power: 3, duration: 1, cost: 2 },
];
const prefix = 'https://prefix/';
it('should return the visualization URL based on stats', () => {
const URL = utils.buildVisualizationURL(stats, prefix);
expect(URL).to.be.a('string');
expect(URL).to.contain('prefix');
expect(URL).to.contain('#');
expect(URL).to.contain(';');
expect(URL).to.contain('AQACAAMA'); // powers
expect(URL).to.contain('AAAAQAAAAEAAAIA'); // times
expect(URL).to.contain('AABAQAAAAEAAAABA'); // costs
});
it('should include the CNY currency if region is cn-north-1', () => {
process.env.AWS_REGION = 'cn-north-1';
const URL = utils.buildVisualizationURL(stats, prefix);
expect(URL).to.contain('?currency=CNY');
});
it('should include the CNY currency if region is cn-north-1', () => {
process.env.AWS_REGION = 'cn-northwest-1';
const URL = utils.buildVisualizationURL(stats, prefix);
expect(URL).to.contain('?currency=CNY');
});
});
describe('allPowerValues', () => {
it('should return a list of integers between 128 and 3008', () => {
const values = utils.allPowerValues();
expect(values).to.be.an('array');
values.forEach((val) => {
expect(val).to.be.a('number');
expect(val).to.be.greaterThan(127);
expect(val).to.be.lessThan(3009);
});
});
it('should return a list of integers at intervals of 64', () => {
const values = utils.allPowerValues();
let val1, val2;
for (let i = 0; i < values.length - 1; i++) {
val1 = values[i];
val2 = values[i + 1];
expect(val2 - val1).to.be(64);
}
});
});
describe('baseCostForRegion', () => {
const prices = {
'ap-east-1': 0.0000002865,
'af-south-1': 0.0000002763,
'me-south-1': 0.0000002583,
default: 0.0000002083,
};
it('should return ap-east-1 base price', () => {
expect(utils.baseCostForRegion(prices, 'ap-east-1')).to.be(0.0000002865);
});
it('should return default base price', () => {
expect(utils.baseCostForRegion(prices, 'eu-west-1')).to.be(0.0000002083);
});
});
describe('lambdaBaseCost', () => {
it('should return x86 base prices', () => {
expect(utils.lambdaBaseCost('eu-west-1', 'x86_64')).to.be(2.1e-9);
});
it('should return default base price', () => {
expect(utils.lambdaBaseCost('eu-west-1', 'arm64')).to.be(1.7e-9);
});
it('should explode if invalid architecture', () => {
expect(() => utils.lambdaBaseCost('eu-west-1', 'invalid_arch')).to.throwError();
});
});
describe('getLambdaConfig', () => {
it('should return a string representing the arch type', async() => {
const ARN = 'arn:aws:lambda:eu-west-1:XXX:function:name';
const alias = 'aliasName';
const { architecture } = await utils.getLambdaConfig(ARN, alias);
expect(architecture).to.be('x86_64');
});
it('should return arm64 when Graviton is supported', async() => {
lambdaMock.on(GetFunctionConfigurationCommand).resolves({ MemorySize: 1024, State: 'Active', LastUpdateStatus: 'Successful', Architectures: ['arm64'] });
const ARN = 'arn:aws:lambda:eu-west-1:XXX:function:name';
const alias = 'aliasName';
const { architecture } = await utils.getLambdaConfig(ARN, alias);
expect(architecture).to.be('arm64');
});
it('should always return x86_64 when Graviton is not supported', async() => {
lambdaMock.on(GetFunctionConfigurationCommand).resolves({ MemorySize: 1024, State: 'Active', LastUpdateStatus: 'Successful' });
const ARN = 'arn:aws:lambda:eu-west-1:XXX:function:name';
const alias = 'aliasName';
const { architecture } = await utils.getLambdaConfig(ARN, alias);
expect(architecture).to.be('x86_64');
});
it('should return isPending true when function/alias state is Pending', async() => {
lambdaMock.on(GetFunctionConfigurationCommand).resolves({ MemorySize: 1024, State: 'Pending', LastUpdateStatus: 'Successful' });
const ARN = 'arn:aws:lambda:eu-west-1:XXX:function:name';
const alias = 'aliasName';
const { isPending } = await utils.getLambdaConfig(ARN, alias);
expect(isPending).to.be(true);
});
it('should return isPending false when function/alias state is not Pending', async() => {
lambdaMock.on(GetFunctionConfigurationCommand).resolves({ MemorySize: 1024, State: 'Active', LastUpdateStatus: 'Successful' });
const ARN = 'arn:aws:lambda:eu-west-1:XXX:function:name';
const alias = 'aliasName';
const { isPending } = await utils.getLambdaConfig(ARN, alias);
expect(isPending).to.be(false);
});
it('should return isPending false when function/alias state is missing', async() => {
lambdaMock.on(GetFunctionConfigurationCommand).resolves({ MemorySize: 1024, LastUpdateStatus: 'Successful' });
const ARN = 'arn:aws:lambda:eu-west-1:XXX:function:name';
const alias = 'aliasName';
const { isPending } = await utils.getLambdaConfig(ARN, alias);
expect(isPending).to.be(false);
});
});
describe('invokeLambdaProcessor', () => {
var invokeLambdaCounter;
beforeEach('mock API call', () => {
invokeLambdaCounter = 0;
});
it('should invoke the processing function without an alias', async() => {
const ARN = 'arn:aws:lambda:eu-west-1:XXX:function:name';
const data = await utils.invokeLambdaProcessor(ARN, '{}');
expect(data).to.be(undefined); // mocked API call
});
it('should invoke the processing function', async() => {
sandBox.stub(utils, 'invokeLambda')
.callsFake(async() => {
invokeLambdaCounter++;
return {
Payload: '{"OK": "OK"}',
};
});
const data = await utils.invokeLambdaProcessor('arnOK', {});
expect(invokeLambdaCounter).to.be(1);
expect(data).to.be('{"OK": "OK"}');
});
const invokeLambdaProcessorReturningUnhandledError = async({ disablePayloadLogs, isPayloadInErrorMessage }) => {
const payload = { keyOne: 'value-one' };
sandBox.stub(utils, 'invokeLambda')
.callsFake(async() => {
invokeLambdaCounter++;
return {
Payload: toByteArray('{"errorMessage": "Exception raised during execution.", ' +
'"errorType": "Exception", "requestId": "c9e545c9-373c-402b-827f-e1c19af39e99", ' +
'"stackTrace": ["File \\"/var/task/lambda_function.py\\", line 9, in lambda_handler, raise Exception(\\"Exception raised during execution.\\")"]}'),
FunctionError: 'Unhandled',
};
});
try {
const data = await utils.invokeLambdaProcessor('arnOK', payload, 'Pre', disablePayloadLogs);
expect(data).to.be(null);
} catch (ex) {
expect(ex.message).to.contain('failed');
expect(ex.message.includes('with payload')).to.be(isPayloadInErrorMessage);
}
expect(invokeLambdaCounter).to.be(1);
};
it('should explode if processor fails and share payload in error when disablePayloadLogs is undefined', async() => invokeLambdaProcessorReturningUnhandledError({
disablePayloadLogs: undefined,
isPayloadInErrorMessage: true,
}));
it('should explode if processor fails and share payload in error when disablePayloadLogs is false', async() => invokeLambdaProcessorReturningUnhandledError({
disablePayloadLogs: false,
isPayloadInErrorMessage: true,
}));
it('should explode if processor fails and not share payload in error when disablePayloadLogs is true', async() => invokeLambdaProcessorReturningUnhandledError({
disablePayloadLogs: true,
isPayloadInErrorMessage: false,
}));
});
const isJsonString = (str) => {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
};
describe('handleLambdaInvocationError', () => {
const invokeLambdaForInvocationErrorAndAssertOnErrorMessage = async({disablePayloadLogs, isPayloadInErrorMessage}) => {
const errorMessage = 'Encountered invocation error';
const originalErrorMessage = 'Exception raised during execution.';
const originalErrorType = 'Exception';
const originalStackTrace = '["File \\"/var/task/lambda_function.py\\", line 9, in lambda_handler, raise Exception(\\"Exception raised during execution.\\")"]';
const invocationResults = {
Payload: toByteArray(`{"errorMessage": "${originalErrorMessage}", ` +
`"errorType": "${originalErrorType}", "requestId": "c9e545c9-373c-402b-827f-e1c19af39e99", ` +
`"stackTrace": ${originalStackTrace}}`),
FunctionError: 'Unhandled',
};
const actualPayload = 'TEST_PAYLOAD';
try {
utils.handleLambdaInvocationError(errorMessage, invocationResults, actualPayload, disablePayloadLogs);
} catch (error) {
expect(error.message).to.contain(errorMessage);
expect(error.message).to.contain(originalErrorMessage);
expect(error.message).to.contain(originalErrorType);
expect(error.message).to.contain(originalStackTrace);
expect(error.message.includes(actualPayload)).to.be(isPayloadInErrorMessage);
}
};
it('should NOT contain not payload in error message if display payload logging is disabled', async() => invokeLambdaForInvocationErrorAndAssertOnErrorMessage({
disablePayloadLogs: true,
isPayloadInErrorMessage: false,
}));
it('should contain payload in error message if display payload logging is NOT disabled', async() => invokeLambdaForInvocationErrorAndAssertOnErrorMessage({
disablePayloadLogs: false,
isPayloadInErrorMessage: true,
}));
it('should contain payload in error message if disablePayloadLogs is undefined', async() => invokeLambdaForInvocationErrorAndAssertOnErrorMessage({
disablePayloadLogs: undefined,
isPayloadInErrorMessage: true,
}));
});
describe('convertPayload', () => {
it('should JSON-encode strings, if not JSON strings already', async() => {
const strings = [
'test',
'',
' ',
];
strings.forEach(s => {
expect(utils.convertPayload(s)).to.be('"' + s + '"');
expect(isJsonString(utils.convertPayload(s))).to.be(true);
});
});
it('should return already a JSON-encoded string as is', async() => {
const strings = [
'{"test": true}',
'[]',
'true',
'null',
];
strings.forEach(s => {
expect(utils.convertPayload(s)).to.be(s);
expect(isJsonString(utils.convertPayload(s))).to.be(true);
});
});
it('should return undefined when undefined is given', async() => {
expect(utils.convertPayload()).to.be(undefined);
expect(utils.convertPayload(undefined)).to.be(undefined);
});
it('should convert everything else to string', async() => {
expect(utils.convertPayload(null)).to.be('null');
expect(utils.convertPayload({})).to.be('{}');
expect(utils.convertPayload({ test: true })).to.be('{"test":true}');
expect(utils.convertPayload([])).to.be('[]');
expect(utils.convertPayload([1, 2, 3])).to.be('[1,2,3]');
expect(utils.convertPayload(['ok', {}])).to.be('["ok",{}]');
});
});
describe('generatePayloads', () => {
it('should generate a list of the same payload, if not weighted', async() => {
const payload = { test: true };
const output = utils.generatePayloads(10, payload);
expect(output.length).to.be(10);
output.forEach(p => {
expect(p).to.be('{"test":true}');
expect(isJsonString(p)).to.be(true);
});
});
it('should generate a list of encoded JSON strings, if not weighted', async() => {
const payload = 'just a string';
const output = utils.generatePayloads(10, payload);
expect(output.length).to.be(10);
output.forEach(p => {
expect(p).to.be('"just a string"');
expect(isJsonString(p)).to.be(true);
});
});
it('should return input array as output if not weighted', async() => {
let payloads = [
[],
[{}],
[1, 2, 3],
[{ weight: 1 }],
[{ payload: {}, weight: 1 }, { payload: {}}],
[{ payload: {} }],
];
payloads.forEach(payload => {
let output = utils.generatePayloads(10, payload);
expect(output.length).to.be(10);
expect(output.every(p => p === JSON.stringify(payload))).to.be(true);
});
});
it('should explode if num < count(payloads)', async() => {
const weightedPayload = [ // 6 weighted payloads
{ weight: 1, payload: {} },
{ weight: 1, payload: { test: 1 } },
{ weight: 1, payload: { test: 2 } },
{ weight: 1, payload: { ok: 1 } },
{ weight: 1, payload: { ok: 2 } },
{ weight: 1, payload: { ok: 3 } },
];
expect(() => utils.generatePayloads(5, weightedPayload)).to.throwError();
});
it('should return weighted payloads (100/2)', async() => {
const weightedPayload = [
{ payload: { test: 'A' }, weight: 1 },
{ payload: { test: 'B' }, weight: 1 },
];
const counters = {
A: 0, B: 0,
};
const output = utils.generatePayloads(100, weightedPayload);
expect(output.length).to.be(100);
output.forEach(payload => {
counters[JSON.parse(payload).test] += 1;
});
expect(counters.A).to.be(50);
expect(counters.B).to.be(50);
});
it('should return weighted payloads (100/3)', async() => {
const weightedPayload = [
{ payload: { test: 'A' }, weight: 1 },
{ payload: { test: 'B' }, weight: 1 },
{ payload: { test: 'C' }, weight: 1 },
];
const counters = {
A: 0, B: 0, C: 0,
};
const output = utils.generatePayloads(100, weightedPayload);
expect(output.length).to.be(100);
output.forEach(payload => {
expect(payload).to.be.a('string');
counters[JSON.parse(payload).test] += 1;
});
expect(counters.A).to.be(33);
expect(counters.B).to.be(33);
expect(counters.C).to.be(34); // the last payload will fill the missing gap
});
it('should return weighted payloads (20/3)', async() => {
const weightedPayload = [
{ payload: { test: 'A' }, weight: 1 },
{ payload: { test: 'B' }, weight: 1 },
{ payload: { test: 'C' }, weight: 1 },
];
const counters = {
A: 0, B: 0, C: 0,
};
const output = utils.generatePayloads(20, weightedPayload);
expect(output.length).to.be(20);
output.forEach(payload => {
expect(payload).to.be.a('string');
counters[JSON.parse(payload).test] += 1;
});
expect(counters.A).to.be(6);
expect(counters.B).to.be(6);
expect(counters.C).to.be(8); // the last payload will fill the missing gap
});
it('should return weighted payloads (10/1)', async() => {
const weightedPayload = [
{ payload: { test: 'A' }, weight: 1 },
];
const counters = {
A: 0,
};
const output = utils.generatePayloads(10, weightedPayload);
expect(output.length).to.be(10);
output.forEach(payload => {
expect(payload).to.be.a('string');
counters[JSON.parse(payload).test] += 1;
});
expect(counters.A).to.be(10);
});
it('should return weighted payloads (23/4)', async() => {
const weightedPayload = [
{ payload: { test: 'A' }, weight: 1 },
{ payload: { test: 'B' }, weight: 1 },
{ payload: { test: 'C' }, weight: 1 },
{ payload: { test: 'D' }, weight: 1 },
];
const counters = {
A: 0, B: 0, C: 0, D: 0,
};
const output = utils.generatePayloads(23, weightedPayload);
expect(output.length).to.be(23);
output.forEach(payload => {