-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathnode_redis.spec.js
More file actions
761 lines (625 loc) · 42.5 KB
/
node_redis.spec.js
File metadata and controls
761 lines (625 loc) · 42.5 KB
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
/* eslint-disable no-console */
import osFunction from 'os';
import * as ipFunction from '../../utils/ip';
import tape from 'tape';
import sinon from 'sinon';
import RedisServer from 'redis-server';
import RedisClient from 'ioredis';
import { exec } from 'child_process';
import { SplitFactory } from '../../';
import { merge } from '@splitsoftware/splitio-commons/src/utils/lang';
import { KeyBuilderSS } from '@splitsoftware/splitio-commons/src/storages/KeyBuilderSS';
import { validatePrefix } from '@splitsoftware/splitio-commons/src/storages/KeyBuilder';
import { settingsFactory } from '../../settings/node';
import { nearlyEqual } from '../testUtils';
import { version } from '../../../package.json';
import { OPTIMIZED, NONE, DEBUG } from '@splitsoftware/splitio-commons/src/utils/constants';
import { truncateTimeFrame } from '@splitsoftware/splitio-commons/src/utils/time';
const IP_VALUE = ipFunction.address();
const HOSTNAME_VALUE = osFunction.hostname();
const NA = 'NA';
const redisPort = '6385';
const TOTAL_RAW_IMPRESSIONS = 17;
const TOTAL_EVENTS = 2;
const DEDUPED_IMPRESSIONS = 3;
const config = {
core: {
authorizationKey: 'SOME SDK KEY' // in consumer mode, SDK key is only used to track and log warning regarding duplicated SDK instances
},
mode: 'consumer',
storage: {
type: 'REDIS',
prefix: 'REDIS_NODE_UT',
options: {
url: `redis://localhost:${redisPort}/0`
}
},
sync: {
impressionsMode: 'DEBUG'
},
startup: {
readyTimeout: 36000 // 10hs
}
};
const expectedConfig = '{"color":"brown"}';
const timeFrame = Date.now();
const expectedImpressionCount = [
`UT_IN_SEGMENT::${truncateTimeFrame(timeFrame)}`, '2',
`UT_NOT_IN_SEGMENT::${truncateTimeFrame(timeFrame)}`, '2',
`UT_SET_MATCHER::${truncateTimeFrame(timeFrame)}`, '2',
`UT_NOT_SET_MATCHER::${truncateTimeFrame(timeFrame)}`, '3',
`always-o.n-with-config::${truncateTimeFrame(timeFrame)}`, '1',
`always-on::${truncateTimeFrame(timeFrame)}`, '1',
`hierarchical_splits_testing_on::${truncateTimeFrame(timeFrame)}`, '1',
`hierarchical_splits_testing_off::${truncateTimeFrame(timeFrame)}`, '1',
`hierarchical_splits_testing_on_negated::${truncateTimeFrame(timeFrame)}`, '1',
];
const expectedSplitName = 'hierarchical_splits_testing_on';
const expectedSplitView = { name: 'hierarchical_splits_testing_on', trafficType: 'user', killed: false, changeNumber: 1487277320548, treatments: ['on', 'off'], configs: {}, sets: [], defaultTreatment: 'off', impressionsDisabled: false };
const MOCKS = {
'': 'redis-commands',
'flag_sets': 'redis-commands-flag-sets'
};
/**
* Initialize redis server and run a cli bash command to load redis with data to do the proper tests
*/
const initializeRedisServer = (mock = '') => {
// Simply pass the port that you want a Redis server to listen on.
const server = new RedisServer(redisPort);
const mockFileName = MOCKS[mock];
const promise = new Promise((resolve, reject) => {
server
.open()
.then(() => {
exec(`cat ./src/__tests__/mocks/${mockFileName}.txt | redis-cli -p ${redisPort}`, err => {
if (err) {
reject(server);
// Node.js couldn't execute the command
return;
}
resolve(server);
});
});
});
return promise;
};
tape('Node.js Redis', function (t) {
t.test('Regular usage - DEBUG strategy', assert => {
initializeRedisServer()
.then(async (server) => {
const sdk = SplitFactory(config);
const client = sdk.client();
const manager = sdk.manager();
/** Evaluation, track and manager methods before SDK_READY */
client.getTreatment('UT_Segment_member', 'UT_IN_SEGMENT').then(result => assert.equal(result, 'control', 'Evaluations using Redis storage should be control until connection is stablished.'));
client.getTreatment('other', 'UT_IN_SEGMENT').then(result => assert.equal(result, 'control', 'Evaluations using Redis storage should be control until connection is stablished.'));
manager.names().then((result) => assert.deepEqual(result, [], 'manager `names` method returns an empty list of split names if called before SDK_READY or Redis operation fail'));
manager.split(expectedSplitName).then((result) => assert.deepEqual(result, null, 'manager `split` method returns a null split view if called before SDK_READY or Redis operation fail'));
manager.splits().then((result) => assert.deepEqual(result, [], 'manager `splits` method returns an empty list of split views if called before SDK_READY or Redis operation fail'));
client.track('nicolas@split.io', 'user', 'before.ready', 18).then((result) => assert.true(result, 'Redis adapter queue "rpush" operations until it is ready.'));
await client.ready();
/** Evaluation, track and manager methods on SDK_READY */
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_IN_SEGMENT', undefined, { properties: { /* empty properties are ignored */ } }), 'on', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_IN_SEGMENT', undefined, { properties: { some: 'value1' } }), 'on', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('other', 'UT_IN_SEGMENT'), 'off', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_NOT_IN_SEGMENT'), 'off', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('other', 'UT_NOT_IN_SEGMENT'), 'on', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_SET_MATCHER', {
permissions: ['admin']
}), 'on', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_SET_MATCHER', {
permissions: ['not_matching']
}), 'off', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_NOT_SET_MATCHER', {
permissions: ['create']
}), 'off', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_NOT_SET_MATCHER', {
permissions: ['not_matching']
}), 'on', 'Evaluations using Redis storage should be correct.');
assert.deepEqual(await client.getTreatmentWithConfig('UT_Segment_member', 'UT_NOT_SET_MATCHER', {
permissions: ['not_matching']
}), {
treatment: 'on',
config: null
}, 'Evaluations using Redis storage should be correct, including configs.');
assert.deepEqual(await client.getTreatmentWithConfig('UT_Segment_member', 'always-o.n-with-config'), {
treatment: 'o.n',
config: expectedConfig
}, 'Evaluations using Redis storage should be correct, including configs.');
assert.equal(await client.getTreatment('UT_Segment_member', 'always-on'), 'on', 'Evaluations using Redis storage should be correct.');
// Below feature flags were added manually to the redis_mock.json file.
// They are all_keys (always evaluate to on) which depend from always-on split. the _on/off is what treatment they are expecting there.
assert.equal(await client.getTreatment('UT_Segment_member', 'hierarchical_splits_testing_on'), 'on', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'hierarchical_splits_testing_off'), 'off', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'hierarchical_splits_testing_on_negated'), 'off', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('other_key', 'always-on-impressions-disabled-true'), 'on', 'Evaluations using Redis storage should be correct.');
assert.equal(typeof client.track().then, 'function', 'Track calls should always return a promise on Redis mode, even when parameters are incorrect.');
assert.true(await client.track('nicolas@split.io', 'user', 'test.redis.event', 18), 'If the event was successfully queued the promise will resolve to true');
assert.false(await client.track(), 'If the event was NOT successfully queued the promise will resolve to false');
// Manager methods
const splitNames = await manager.names();
assert.equal(splitNames.length, 26, 'manager `names` method returns the list of split names asynchronously');
assert.equal(splitNames.indexOf(expectedSplitName) > -1, true, 'list of split names should contain expected splits');
assert.deepEqual(await manager.split(expectedSplitName), expectedSplitView, 'manager `split` method returns the split view of the given split name asynchronously');
const splitViews = await manager.splits();
assert.equal(splitViews.length, 26, 'manager `splits` method returns the list of split views asynchronously');
assert.deepEqual(splitViews.find(splitView => splitView.name === expectedSplitName), expectedSplitView, 'manager `split` method returns the split view of the given split name asynchronously');
await client.ready(); // promise already resolved
await client.destroy();
// Validate Impression Counts and Unique Keys for 'always-on-impressions-disabled-true'
exec(`echo "HGETALL ${config.storage.prefix}.SPLITIO.impressions.count" | redis-cli -p ${redisPort}`, async (error, stdout) => {
const trackedImpressionCounts = stdout.split('\n').filter(line => line !== '');
assert.deepEqual(trackedImpressionCounts, [`always-on-impressions-disabled-true::${truncateTimeFrame(timeFrame)}`, '1',], 'Tracked impression counts should be stored in Redis TODO');
exec(`echo "LRANGE ${config.storage.prefix}.SPLITIO.uniquekeys 0 20" | redis-cli -p ${redisPort}`, async (error, stdout) => {
const storedUniqueKeys = stdout.split('\n').filter(line => line !== '').map(JSON.parse);
assert.deepEqual(storedUniqueKeys, [{ 'f': 'always-on-impressions-disabled-true', 'ks': ['other_key'] }], 'Unique keys should be stored in Redis TODO');
// Validate stored impressions and events
exec(`echo "LLEN ${config.storage.prefix}.SPLITIO.impressions \n LLEN ${config.storage.prefix}.SPLITIO.events" | redis-cli -p ${redisPort}`, (error, stdout) => {
if (error) assert.fail('Redis server should be reachable');
const trackedImpressionsAndEvents = stdout.split('\n').filter(line => line !== '').map(line => parseInt(line));
assert.deepEqual(trackedImpressionsAndEvents, [TOTAL_RAW_IMPRESSIONS, TOTAL_EVENTS], 'Tracked impressions and events should be stored in Redis');
// Validate stored telemetry
exec(`echo "HLEN ${config.storage.prefix}.SPLITIO.telemetry.latencies \n HLEN ${config.storage.prefix}.SPLITIO.telemetry.exceptions \n HGET ${config.storage.prefix}.SPLITIO.telemetry.init 'nodejs-${version}/${HOSTNAME_VALUE}/${IP_VALUE}'" | redis-cli -p ${redisPort}`, (error, stdout) => {
if (error) assert.fail('Redis server should be reachable');
const [latencies, exceptions, configValue] = stdout.split('\n').filter(line => line !== '').map(JSON.parse);
assert.true(latencies > 0, 'There are stored latencies');
assert.true(exceptions === 0, 'There aren\'t stored exceptions');
assert.deepEqual(configValue, { oM: 1, st: 'redis', aF: 1, rF: 0 }, 'There is stored telemetry config');
// close server connection
server.close().then(assert.end);
});
});
});
});
});
});
t.test('Regular usage - OPTIMIZED strategy', assert => {
config.sync.impressionsMode = OPTIMIZED;
initializeRedisServer()
.then(async (server) => {
assert.equal(config.sync.impressionsMode, OPTIMIZED, 'impressionsMode should be OPTIMIZED');
const sdk = SplitFactory(config);
const client = sdk.client();
await client.ready();
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_IN_SEGMENT'), 'on', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('other', 'UT_IN_SEGMENT'), 'off', 'Evaluations using Redis storage should be correct.');
// this should be deduped
assert.equal(await client.getTreatment('other', 'UT_IN_SEGMENT'), 'off', 'Evaluations using Redis storage should be correct.');
// this should be deduped
assert.equal(await client.getTreatment('other', 'UT_IN_SEGMENT', undefined, { properties: { /* empty properties are ignored */ } }), 'off', 'Evaluations using Redis storage should be correct.');
// this should not be deduped because of properties
assert.equal(await client.getTreatment('other', 'UT_IN_SEGMENT', undefined, { properties: { some: 'value1' } }), 'off', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_NOT_IN_SEGMENT'), 'off', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('other', 'UT_NOT_IN_SEGMENT'), 'on', 'Evaluations using Redis storage should be correct.');
// this should be deduped
assert.equal(await client.getTreatment('other', 'UT_NOT_IN_SEGMENT'), 'on', 'Evaluations using Redis storage should be correct.');
// this should be deduped
assert.equal(await client.getTreatment('other', 'UT_NOT_IN_SEGMENT'), 'on', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_SET_MATCHER', {
permissions: ['admin']
}), 'on', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_SET_MATCHER', {
permissions: ['not_matching']
}), 'off', 'Evaluations using Redis storage should be correct.');
// this should be deduped
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_SET_MATCHER', {
permissions: ['not_matching']
}), 'off', 'Evaluations using Redis storage should be correct.');
// this should be deduped
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_SET_MATCHER', {
permissions: ['not_matching']
}), 'off', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_NOT_SET_MATCHER', {
permissions: ['create']
}), 'off', 'Evaluations using Redis storage should be correct.');
// this should be deduped
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_NOT_SET_MATCHER', {
permissions: ['create']
}), 'off', 'Evaluations using Redis storage should be correct.');
// this should be deduped
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_NOT_SET_MATCHER', {
permissions: ['create']
}), 'off', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_NOT_SET_MATCHER', {
permissions: ['not_matching']
}), 'on', 'Evaluations using Redis storage should be correct.');
// this should be deduped
assert.deepEqual(await client.getTreatmentWithConfig('UT_Segment_member', 'UT_NOT_SET_MATCHER', {
permissions: ['not_matching']
}), {
treatment: 'on',
config: null
}, 'Evaluations using Redis storage should be correct, including configs.');
assert.deepEqual(await client.getTreatmentWithConfig('UT_Segment_member', 'always-o.n-with-config'), {
treatment: 'o.n',
config: expectedConfig
}, 'Evaluations using Redis storage should be correct, including configs.');
// this should be deduped
assert.deepEqual(await client.getTreatmentWithConfig('UT_Segment_member', 'always-o.n-with-config'), {
treatment: 'o.n',
config: expectedConfig
}, 'Evaluations using Redis storage should be correct, including configs.');
assert.equal(await client.getTreatment('UT_Segment_member', 'always-on'), 'on', 'Evaluations using Redis storage should be correct.');
// this should be deduped
assert.equal(await client.getTreatment('UT_Segment_member', 'always-on'), 'on', 'Evaluations using Redis storage should be correct.');
// Below feature flags were added manually to the redis_mock.json file.
// They are all_keys (always evaluate to on) which depend from always-on split. the _on/off is what treatment they are expecting there.
assert.equal(await client.getTreatment('UT_Segment_member', 'hierarchical_splits_testing_on'), 'on', 'Evaluations using Redis storage should be correct.');
// this should be deduped
assert.equal(await client.getTreatment('UT_Segment_member', 'hierarchical_splits_testing_on'), 'on', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'hierarchical_splits_testing_off'), 'off', 'Evaluations using Redis storage should be correct.');
// this should be deduped
assert.equal(await client.getTreatment('UT_Segment_member', 'hierarchical_splits_testing_off'), 'off', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'hierarchical_splits_testing_on_negated'), 'off', 'Evaluations using Redis storage should be correct.');
// this should be deduped
assert.equal(await client.getTreatment('UT_Segment_member', 'hierarchical_splits_testing_on_negated'), 'off', 'Evaluations using Redis storage should be correct.');
assert.equal(typeof client.track('nicolas@split.io', 'user', 'test.redis.event', 18).then, 'function', 'Track calls should always return a promise on Redis mode.');
assert.equal(typeof client.track().then, 'function', 'Track calls should always return a promise on Redis mode, even when parameters are incorrect.');
assert.true(await client.track('nicolas@split.io', 'user', 'test.redis.event', 18), 'If the event was successfully queued the promise will resolve to true');
assert.false(await client.track(), 'If the event was NOT successfully queued the promise will resolve to false');
await client.ready(); // promise already resolved
await client.destroy();
exec(`echo "HGETALL ${config.storage.prefix}.SPLITIO.impressions.count" | redis-cli -p ${redisPort}`, async (error, stdout) => {
const trackedImpressionCounts = stdout.split('\n').filter(line => line !== '');
assert.deepEqual(trackedImpressionCounts, expectedImpressionCount, 'Tracked impression counts should be stored in Redis');
// Validate stored impressions and events
exec(`echo "LLEN ${config.storage.prefix}.SPLITIO.impressions \n LLEN ${config.storage.prefix}.SPLITIO.events" | redis-cli -p ${redisPort}`, (error, stdout) => {
if (error) assert.fail('Redis server should be reachable');
const trackedImpressionsAndEvents = stdout.split('\n').filter(line => line !== '').map(line => parseInt(line));
assert.deepEqual(trackedImpressionsAndEvents, [TOTAL_RAW_IMPRESSIONS - DEDUPED_IMPRESSIONS, TOTAL_EVENTS], 'Tracked impressions and events should be stored in Redis');
// Validate stored telemetry
exec(`echo "HLEN ${config.storage.prefix}.SPLITIO.telemetry.latencies \n HLEN ${config.storage.prefix}.SPLITIO.telemetry.exceptions \n HGET ${config.storage.prefix}.SPLITIO.telemetry.init 'nodejs-${version}/${HOSTNAME_VALUE}/${IP_VALUE}'" | redis-cli -p ${redisPort}`, (error, stdout) => {
if (error) assert.fail('Redis server should be reachable');
const [latencies, exceptions, configValue] = stdout.split('\n').filter(line => line !== '').map(JSON.parse);
assert.true(latencies > 0, 'There are stored latencies');
assert.true(exceptions === 0, 'There aren\'t stored exceptions');
assert.deepEqual(configValue, { oM: 1, st: 'redis', aF: 1, rF: 0 }, 'There is stored telemetry config');
// close server connection
server.close().then(assert.end);
});
});
});
});
});
t.test('Regular usage - NONE strategy', assert => {
config.sync.impressionsMode = NONE;
initializeRedisServer()
.then(async (server) => {
const expectedUniqueKeys = [
{ 'f': 'UT_IN_SEGMENT', 'ks': ['UT_Segment_member', 'other'] },
{ 'f': 'UT_NOT_IN_SEGMENT', 'ks': ['UT_Segment_member', 'other'] },
{ 'f': 'UT_SET_MATCHER', 'ks': ['UT_Segment_member'] },
{ 'f': 'UT_NOT_SET_MATCHER', 'ks': ['UT_Segment_member'] },
{ 'f': 'always-o.n-with-config', 'ks': ['UT_Segment_member'] },
{ 'f': 'always-on', 'ks': ['UT_Segment_member'] },
{ 'f': 'hierarchical_splits_testing_on', 'ks': ['UT_Segment_member'] },
{ 'f': 'hierarchical_splits_testing_off', 'ks': ['UT_Segment_member'] },
{ 'f': 'hierarchical_splits_testing_on_negated', 'ks': ['UT_Segment_member'] },
];
assert.equal(config.sync.impressionsMode, NONE, 'impressionsMode should be NONE');
const sdk = SplitFactory(config);
const client = sdk.client();
await client.ready();
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_IN_SEGMENT'), 'on', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('other', 'UT_IN_SEGMENT'), 'off', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_NOT_IN_SEGMENT'), 'off', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('other', 'UT_NOT_IN_SEGMENT'), 'on', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_SET_MATCHER', {
permissions: ['admin']
}), 'on', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_SET_MATCHER', {
permissions: ['not_matching']
}), 'off', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_NOT_SET_MATCHER', {
permissions: ['create']
}), 'off', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_NOT_SET_MATCHER', {
permissions: ['not_matching']
}), 'on', 'Evaluations using Redis storage should be correct.');
assert.deepEqual(await client.getTreatmentWithConfig('UT_Segment_member', 'UT_NOT_SET_MATCHER', {
permissions: ['not_matching']
}), {
treatment: 'on',
config: null
}, 'Evaluations using Redis storage should be correct, including configs.');
assert.deepEqual(await client.getTreatmentWithConfig('UT_Segment_member', 'always-o.n-with-config'), {
treatment: 'o.n',
config: expectedConfig
}, 'Evaluations using Redis storage should be correct, including configs.');
assert.equal(await client.getTreatment('UT_Segment_member', 'always-on'), 'on', 'Evaluations using Redis storage should be correct.');
// Below feature flags were added manually to the redis_mock.json file.
// They are all_keys (always evaluate to on) which depend from always-on split. the _on/off is what treatment they are expecting there.
assert.equal(await client.getTreatment('UT_Segment_member', 'hierarchical_splits_testing_on'), 'on', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'hierarchical_splits_testing_off'), 'off', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('UT_Segment_member', 'hierarchical_splits_testing_on_negated'), 'off', 'Evaluations using Redis storage should be correct.');
assert.equal(typeof client.track('nicolas@split.io', 'user', 'test.redis.event', 18).then, 'function', 'Track calls should always return a promise on Redis mode.');
assert.equal(typeof client.track().then, 'function', 'Track calls should always return a promise on Redis mode, even when parameters are incorrect.');
assert.true(await client.track('nicolas@split.io', 'user', 'test.redis.event', 18), 'If the event was successfully queued the promise will resolve to true');
assert.false(await client.track(), 'If the event was NOT successfully queued the promise will resolve to false');
await client.ready(); // promise already resolved
await client.destroy();
// Validate Impression Counts
exec(`echo "HGETALL ${config.storage.prefix}.SPLITIO.impressions.count" | redis-cli -p ${redisPort}`, async (error, stdout) => {
const trackedImpressionCounts = stdout.split('\n').filter(line => line !== '');
assert.deepEqual(trackedImpressionCounts, expectedImpressionCount, 'Tracked impression counts should be stored in Redis');
// Validate unique Keys
exec(`echo "LRANGE ${config.storage.prefix}.SPLITIO.uniquekeys 0 20" | redis-cli -p ${redisPort}`, async (error, stdout) => {
const storedUniqueKeys = stdout.split('\n').filter(line => line !== '').map(JSON.parse);
assert.deepEqual(storedUniqueKeys, expectedUniqueKeys, 'Unique keys should be stored in Redis');
// Validate stored impressions and events
exec(`echo "LLEN ${config.storage.prefix}.SPLITIO.impressions \n LLEN ${config.storage.prefix}.SPLITIO.events" | redis-cli -p ${redisPort}`, (error, stdout) => {
if (error) assert.fail('Redis server should be reachable');
const trackedImpressionsAndEvents = stdout.split('\n').filter(line => line !== '').map(line => parseInt(line));
assert.deepEqual(trackedImpressionsAndEvents, [0, TOTAL_EVENTS], 'No impressions are stored in Redis in NONE impressions mode');
// Validate stored telemetry
exec(`echo "HLEN ${config.storage.prefix}.SPLITIO.telemetry.latencies \n HLEN ${config.storage.prefix}.SPLITIO.telemetry.exceptions \n HGET ${config.storage.prefix}.SPLITIO.telemetry.init 'nodejs-${version}/${HOSTNAME_VALUE}/${IP_VALUE}'" | redis-cli -p ${redisPort}`, (error, stdout) => {
if (error) assert.fail('Redis server should be reachable');
const [latencies, exceptions, configValue] = stdout.split('\n').filter(line => line !== '').map(JSON.parse);
assert.true(latencies > 0, 'There are stored latencies');
assert.true(exceptions === 0, 'There aren\'t stored exceptions');
assert.deepEqual(configValue, { oM: 1, st: 'redis', aF: 1, rF: 0 }, 'There is stored telemetry config');
config.sync.impressionsMode = DEBUG;
// close server connection
server.close().then(assert.end);
});
});
});
});
});
});
t.test('Connection timeout and then ready', assert => {
const readyTimeout = 0.1; // 100 millis
const configWithShortTimeout = { ...config, startup: { readyTimeout } };
const sdk = SplitFactory(configWithShortTimeout);
const client = sdk.client();
const start = Date.now();
let readyTimestamp;
let redisServer;
assert.plan(18);
client.getTreatment('UT_Segment_member', 'always-on').then(treatment => {
assert.equal(treatment, 'control', 'Evaluations using Redis storage should be control until Redis connection is stablished.');
});
client.track('nicolas@split.io', 'user', 'test.redis.event', 18).then(result => {
assert.true(result, 'If the event was successfully queued the promise will resolve to true once Redis connection is stablished');
});
// SDK_READY_TIMED_OUT event must be emitted after 100 millis
client.on(client.Event.SDK_READY_TIMED_OUT, () => {
const delay = Date.now() - start;
assert.true(nearlyEqual(delay, readyTimeout * 1000), 'SDK_READY_TIMED_OUT event must be emitted after 100 millis');
});
// Also, ready promise must be rejected after 100 millis
client.ready().catch(() => {
const delay = Date.now() - start;
assert.true(nearlyEqual(delay, readyTimeout * 1000), 'Ready promise must be rejected after 100 millis');
// Initialize server to emit SDK_READY.
// We want to validate SDK readiness behavior here, so `initializeRedisServer` is not called because loading Redis with
// data takes a time, and the SDK will be ready but might evaluate with or without data, resulting in tests flakiness.
redisServer = new RedisServer(redisPort);
redisServer.open().then(async () => {
readyTimestamp = Date.now();
try {
await client.ready();
assert.fail('Ready promise keeps being rejected until SDK_READY is emitted');
} catch (error) {
assert.pass('Ready promise keeps being rejected until SDK_READY is emitted');
}
});
});
// subscribe to SDK_READY event to assert regular usage
client.on(client.Event.SDK_READY, async () => {
await client.ready();
const delay = Date.now() - readyTimestamp;
assert.true(nearlyEqual(delay, 0), 'SDK_READY event is emitted and Ready promise resolved soon once Redis server is connected');
// some asserts to test regular usage
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_IN_SEGMENT'), 'on', 'Evaluations using Redis storage should be correct.');
assert.equal(await client.getTreatment('other', 'UT_IN_SEGMENT'), 'off', 'Evaluations using Redis storage should be correct.');
assert.true(await client.track('nicolas@split.io', 'user', 'test.redis.event', 18), 'If the event was successfully queued the promise will resolve to true');
assert.false(await client.track(), 'If the event was NOT successfully queued the promise will resolve to false');
await client.destroy();
assert.pass();
});
// create a new factory with a very short readyTimedout config to emit SDK_READY_TIMED_OUT even with the Redis server on
client.on(client.Event.SDK_READY, async () => {
const configWithVeryShortTimeout = {
...config,
startup: { readyTimeout: 0.001 },
core: { authorizationKey: 'aaa4sb69bjv7d4d027f7ukkitd53ek6a9ai9' }
};
const sdk2 = SplitFactory(configWithVeryShortTimeout);
const client2 = sdk2.client();
client2.on(client2.Event.SDK_READY_TIMED_OUT, () => {
assert.pass('SDK_READY_TIMED_OUT event must be emitted');
});
client2.on(client2.Event.SDK_READY, async () => {
assert.pass('SDK_READY event must be emitted');
// some asserts to test regular usage
assert.equal(await client2.getTreatment('UT_Segment_member', 'UT_IN_SEGMENT'), 'on', 'Evaluations using Redis storage should be correct.');
assert.equal(await client2.getTreatment('other', 'UT_IN_SEGMENT'), 'off', 'Evaluations using Redis storage should be correct.');
assert.true(await client2.track('nicolas@split.io', 'user', 'test.redis.event', 18), 'If the event was successfully queued the promise will resolve to true');
assert.false(await client2.track(), 'If the event was NOT successfully queued the promise will resolve to false');
await client2.destroy();
// close server connection
redisServer.close().then(() => {
assert.pass();
assert.end();
});
});
});
});
t.test('Connection error', assert => {
initializeRedisServer()
.then((server) => {
const sdk = SplitFactory(config);
const client = sdk.client();
client.once(client.Event.SDK_READY_TIMED_OUT, assert.fail);
client.ready().then(assert.pass).catch(assert.fail);
const start = Date.now();
client.once(client.Event.SDK_READY, async () => { // Use SDK_READY event.
// ready promise is resolved
await client.ready();
const delay = Date.now() - start;
assert.true(nearlyEqual(delay, 0), 'Ready promise is resolved once SDK_READY is emitted, and it is emitted almost immediately after the SDK is created');
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_NOT_SET_MATCHER', {
permissions: ['create']
}), 'off', 'Control assertion - Everything working as expected.');
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_NOT_SET_MATCHER', {
permissions: ['not_matching']
}), 'on', 'Control assertion - Everything working as expected.');
assert.equal(await client.getTreatment('UT_Segment_member', 'always-on'), 'on', 'Control assertion - Everything working as expected.');
assert.true(await client.track('nicolas@split.io', 'user', 'test.redis.event', 18), 'Control assertion - Everything working as expected.');
assert.notEqual(await client.track(), 'Control assertion - Everything working as expected.');
// close server connection
server.close().then(() => {
// we need to add a delay before doing a getTreatment
setTimeout(async () => {
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_NOT_SET_MATCHER', {
permissions: ['create']
}), 'control', 'In the event of a Redis error like a disconnection, getTreatments should not hang but resolve to "control".');
assert.equal(await client.getTreatment('UT_Segment_member', 'UT_NOT_SET_MATCHER', {
permissions: ['not_matching']
}), 'control', 'In the event of a Redis error like a disconnection, getTreatments should not hang but resolve to "control".');
assert.equal(await client.getTreatment('UT_Segment_member', 'always-on'), 'control', 'In the event of a Redis error like a disconnection, getTreatments should not hang but resolve to "control".');
assert.false(await client.track('nicolas@split.io', 'user', 'test.redis.event', 18), 'In the event of a Redis error like a disconnection, track should resolve to false.');
await client.destroy();
assert.end();
}, 1000);
});
});
});
});
t.test('Calling destroy with pending operations', assert => {
initializeRedisServer()
.then(async (server) => {
const sdk = SplitFactory({
...config,
debug: 'WARN' // we want to see the error/warning logs calling the actual log method (if there's any)
});
const client = sdk.client();
try {
await client.ready(); // Validate ready promise.
} catch (e) {
assert.fail(e);
}
process.on('unhandledRejection', assert.fail);
process.on('uncaughtException', assert.fail);
sinon.spy(console, 'log');
await client.getTreatment('Tito_the_skeleton', 'always-on');
client.destroy();
setTimeout(() => {
process.off('unhandledRejection', assert.fail);
process.off('uncaughtException', assert.fail);
assert.pass('Check unhandledRejection or uncaughtException detected. None is expected');
assert.false(console.log.calledWithMatch('threw or exceeded configured timeout of 5000ms setting. Message: Error: Stream isn\'t writeable and enableOfflineQueue options is false'), 'No error should have been triggered from Redis.');
console.log.restore();
// close server connection and wrap up.
server.close().then(assert.end);
}, 2000);
});
});
t.test('Check IP and Hostname in Redis', assert => {
initializeRedisServer()
.then(async (server) => {
const configs = [
config,
merge({}, config, { core: { IPAddressesEnabled: true } }),
merge({}, config, { core: { IPAddressesEnabled: false } })
];
for (let config of configs) {
// Redis client and keys required to check Redis store.
const setting = settingsFactory(config);
const connection = new RedisClient(setting.storage.options.url);
const keys = new KeyBuilderSS(validatePrefix(setting.storage.prefix), { s: 'js_someversion', i: 'some_ip', n: 'some_hostname' });
const eventKey = keys.buildEventsKey();
const impressionsKey = keys.buildImpressionsKey();
// Clean up list of events and impressions.
connection.del(eventKey);
connection.del(impressionsKey);
// Init Split client for current config
const sdk = SplitFactory(config);
const client = sdk.client();
await client.ready();
// Perform client actions to store a single event and impression objects into Redis
await client.getTreatment('UT_Segment_member', 'UT_IN_SEGMENT');
await client.track('nicolas@split.io', 'user', 'test.redis.event', 18);
// Assert if the impression object was stored properly
let redisImpressions = await connection.lrange(impressionsKey, 0, -1);
assert.equal(redisImpressions.length, 1, 'After getting a treatment, we should have one impression on Redis.');
const parsedImpression = JSON.parse(redisImpressions[0]);
assert.equal(parsedImpression.m.i, setting.core.IPAddressesEnabled ? IP_VALUE : NA, `If IPAddressesEnabled is true, the property .m.i of the impression object must be equal to the machine ip, or "${NA}" otherwise.`);
assert.equal(parsedImpression.m.n, setting.core.IPAddressesEnabled ? HOSTNAME_VALUE : NA, `If IPAddressesEnabled is true, the property .m.n of the impression object must be equal to the machine hostname, or "${NA}" otherwise.`);
// Assert if the event object was stored properly
let redisEvents = await connection.lrange(eventKey, 0, -1);
assert.equal(redisEvents.length, 1, 'After tracking an event, we should have one event on Redis.');
const parsedEvent = JSON.parse(redisEvents[0]);
assert.equal(parsedEvent.m.i, setting.core.IPAddressesEnabled ? IP_VALUE : NA, `If IPAddressesEnabled is true, the property .m.i of the event object must be equal to the machine ip, or "${NA}" otherwise.`);
assert.equal(parsedEvent.m.n, setting.core.IPAddressesEnabled ? HOSTNAME_VALUE : NA, `If IPAddressesEnabled is true, the property .m.n of the event object must be equal to the machine hostname, or "${NA}" otherwise.`);
// Deallocate Split and Redis clients
await client.destroy();
await connection.quit();
}
// close server connection
server.close().then(assert.end);
});
});
t.test('Getting treatments with flag sets', assert => {
initializeRedisServer('flag_sets')
.then(async (server) => {
const sdk = SplitFactory(config);
const client = sdk.client();
client.getTreatmentsWithConfigByFlagSets('other', ['set_one']).then(result => assert.deepEqual(result, {}, 'Flag sets evaluations using Redis storage should be empty until connection is ready.'));
await client.ready();
assert.deepEqual(
await client.getTreatmentsByFlagSet('nico@test', 'set_one'),
{ 'always-on': 'on', 'always-off': 'off' },
'Evaluations using Redis storage should be correct for a set.'
);
assert.deepEqual(
await client.getTreatmentsWithConfigByFlagSet('nico@test', 'set_one'),
{ 'always-on': { treatment: 'on', config: null }, 'always-off': { treatment: 'off', config: null } },
'Evaluations with configs using Redis storage should be correct for a set.'
);
assert.deepEqual(
await client.getTreatmentsByFlagSet('nico@test', 'set_two'),
{ 'always-off': 'off', 'nico_not': 'off' },
'Evaluations using Redis storage should be correct for a set.'
);
assert.deepEqual(
await client.getTreatmentsByFlagSet('nico@test', 'set_invalid'),
{},
'Evaluations using Redis storage should properly handle all invalid sets.'
);
assert.deepEqual(
await client.getTreatmentsByFlagSets('nico@test', ['set_two', 'set_one']),
{ 'always-on': 'on', 'always-off': 'off', 'nico_not': 'off' },
'Evaluations using Redis storage should be correct for multiple sets.'
);
assert.deepEqual(
await client.getTreatmentsWithConfigByFlagSets('nico@test', ['set_two', 'set_one']),
{ 'always-on': { treatment: 'on', config: null }, 'always-off': { treatment: 'off', config: null }, 'nico_not': { treatment: 'off', config: '{"text":"Gallardiola"}' } },
'Evaluations with configs using Redis storage should be correct for multiple sets.'
);
assert.deepEqual(
await client.getTreatmentsByFlagSets('nico@test', [243, null, 'set_two', 'set_one', 'invalid_set']),
{ 'always-on': 'on', 'always-off': 'off', 'nico_not': 'off' },
'Evaluations using Redis storage should be correct for multiple sets, discarding invalids.'
);
assert.deepEqual(
await client.getTreatmentsByFlagSets('nico@test', [243, null, 'invalid_set']),
{},
'Evaluations using Redis storage should properly handle all invalid sets.'
);
await client.ready(); // promise already resolved
await client.destroy();
// Validate stored telemetry
exec(`echo "HLEN ${config.storage.prefix}.SPLITIO.telemetry.latencies \n HKEYS ${config.storage.prefix}.SPLITIO.telemetry.latencies" | redis-cli -p ${redisPort}`, (error, stdout) => {
if (error) assert.fail('Redis server should be reachable');
const [latenciesCount, ...latenciesForFlagSets] = stdout.split('\n').filter(line => line !== '');
assert.true(parseInt(latenciesCount) > 0, 'There are stored latencies');
assert.true(latenciesForFlagSets.some(s => s.match(`nodejs-${version}/${HOSTNAME_VALUE}/${IP_VALUE}/treatmentsByFlagSet/`), 'The latency entry for treatmentsByFlagSet should be there.'));
assert.true(latenciesForFlagSets.some(s => s.match(`nodejs-${version}/${HOSTNAME_VALUE}/${IP_VALUE}/treatmentsByFlagSets/`), 'The latency entry for treatmentsByFlagSets should be there.'));
// close server connection
server.close().then(assert.end);
});
});
});
});