nanoflags 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +40 -20
- data/LICENSE +202 -202
- data/NOTICE +4 -4
- data/README.md +206 -152
- data/lib/nanoflags/client.rb +1225 -869
- data/lib/nanoflags/engine/js.rb +531 -531
- data/lib/nanoflags/engine/json.rb +200 -200
- data/lib/nanoflags/engine.rb +407 -407
- data/lib/nanoflags/evaluation_detail.rb +91 -87
- data/lib/nanoflags/http.rb +126 -119
- data/lib/nanoflags/keys.rb +14 -14
- data/lib/nanoflags/session.rb +137 -0
- data/lib/nanoflags/store.rb +59 -59
- data/lib/nanoflags/verify.rb +180 -180
- data/lib/nanoflags/version.rb +6 -6
- data/lib/nanoflags/websocket.rb +411 -0
- data/lib/nanoflags.rb +12 -10
- metadata +9 -6
data/lib/nanoflags/client.rb
CHANGED
|
@@ -1,869 +1,1225 @@
|
|
|
1
|
-
# frozen_string_literal: true
|
|
2
|
-
|
|
3
|
-
require "json"
|
|
4
|
-
require "monitor"
|
|
5
|
-
require "time"
|
|
6
|
-
|
|
7
|
-
module NanoFlags
|
|
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
|
-
def
|
|
229
|
-
|
|
230
|
-
# The
|
|
231
|
-
def
|
|
232
|
-
|
|
233
|
-
#
|
|
234
|
-
#
|
|
235
|
-
def
|
|
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
|
-
return if
|
|
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
|
-
end
|
|
435
|
-
|
|
436
|
-
def
|
|
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
|
-
end
|
|
494
|
-
|
|
495
|
-
def
|
|
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
|
-
if
|
|
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
|
-
end
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
def
|
|
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
|
-
unless
|
|
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
|
-
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "monitor"
|
|
5
|
+
require "time"
|
|
6
|
+
|
|
7
|
+
module NanoFlags
|
|
8
|
+
# WebSocket subprotocol of the edge's live socket (+/v1/live+).
|
|
9
|
+
LIVE_PROTOCOL = "nanoflags.v1"
|
|
10
|
+
# Close code of the live socket for a deleted environment: the client keeps its last bundle and stops reconnecting.
|
|
11
|
+
CLOSE_ENVIRONMENT_DELETED = 4004
|
|
12
|
+
|
|
13
|
+
# The NanoFlags client for Ruby servers (Rails, Puma, Sidekiq, Rack, plain scripts).
|
|
14
|
+
#
|
|
15
|
+
# Flags are evaluated locally and synchronously against an in-memory bundle; a variation call never performs I/O
|
|
16
|
+
# and never raises. The network is used in background threads only: to load the bundle (`/v1/bundle`, with ETag
|
|
17
|
+
# revalidation), to receive new revisions as soon as they are published (pushed over the live WebSocket `/v1/live`;
|
|
18
|
+
# while no socket can be opened, server-sent events on `/v1/stream`; polling as the safety net), and to send sampled
|
|
19
|
+
# telemetry plus the periodic service report (`/v1/events`). Test sessions ({#session}) are resolved on demand.
|
|
20
|
+
#
|
|
21
|
+
# Create one client per process and share it between threads. It is fork-safe: after a fork (Puma and Unicorn
|
|
22
|
+
# workers, Passenger, Resque, Sidekiq Swarm) the child keeps the configuration it inherited and restarts the
|
|
23
|
+
# background threads on its first call (a child that never evaluates a flag never opens a connection). Events
|
|
24
|
+
# queued before the fork are sent by the parent only.
|
|
25
|
+
#
|
|
26
|
+
# FLAGS = NanoFlags::Client.new(ENV.fetch("NANOFLAGS_SDK_KEY"), service: "checkout-api")
|
|
27
|
+
# FLAGS.wait_until_ready(5)
|
|
28
|
+
# FLAGS.bool_variation("new-checkout", false, { key: current_user.id, plan: current_user.plan })
|
|
29
|
+
class Client
|
|
30
|
+
STATUS_NOT_READY = "not-ready"
|
|
31
|
+
STATUS_READY = "ready"
|
|
32
|
+
STATUS_STALE = "stale"
|
|
33
|
+
|
|
34
|
+
MAX_QUEUE = 500
|
|
35
|
+
MAX_BATCH = 50
|
|
36
|
+
MAX_EVENT_VALUE_CHARS = 1024
|
|
37
|
+
KEYS_REFETCH = 60.0
|
|
38
|
+
LIVE_CONNECT_TIMEOUT = 10.0
|
|
39
|
+
LIVE_PING = 30.0
|
|
40
|
+
LIVE_PONG_TIMEOUT = 10.0
|
|
41
|
+
LIVE_MAX_BACKOFF = 300.0
|
|
42
|
+
# A healthy socket is replaced after about this long, so the edge validates the key again (it drops sockets older
|
|
43
|
+
# than 2 h).
|
|
44
|
+
LIVE_ROTATE = 50 * 60.0
|
|
45
|
+
LIVE_STABLE = 30.0
|
|
46
|
+
MAX_SESSIONS = 1000
|
|
47
|
+
SESSION_MISS_TTL = 15.0
|
|
48
|
+
SESSION_ERROR_TTL = 3.0
|
|
49
|
+
ACCEPT_BOOL = ->(v) { v == true || v == false }
|
|
50
|
+
ACCEPT_STRING = ->(v) { v.is_a?(String) }
|
|
51
|
+
ACCEPT_NUMBER = ->(v) { v.is_a?(Float) && v.finite? }
|
|
52
|
+
ACCEPT_ANY = ->(v) { !v.equal?(Engine::UNDEFINED) }
|
|
53
|
+
|
|
54
|
+
REGISTRY = ObjectSpace::WeakMap.new
|
|
55
|
+
REGISTRY_LOCK = Mutex.new
|
|
56
|
+
private_constant :REGISTRY, :REGISTRY_LOCK
|
|
57
|
+
|
|
58
|
+
attr_reader :base_url, :service
|
|
59
|
+
|
|
60
|
+
# @param sdk_key [String] `nf_srv_…` (server view) or `nf_pub_…` (client-exposed flags only)
|
|
61
|
+
# @param base_url [String] the edge; signatures are verified by default on the hosted edge
|
|
62
|
+
# @param service [String, nil] the name shown in "which revision is each service running"
|
|
63
|
+
# @param poll_interval [Numeric] seconds between polls while no live socket is open (0 disables polling)
|
|
64
|
+
# @param streaming [Boolean] receive new revisions without polling (live WebSocket, else server-sent events);
|
|
65
|
+
# false: polling only
|
|
66
|
+
# @param live [Boolean] false skips the live WebSocket and uses server-sent events + polling
|
|
67
|
+
# @param live_poll_interval [Numeric] seconds between safety polls while the live socket is healthy
|
|
68
|
+
# @param live_url [String, nil] WebSocket URL of /v1/live when it is not +base_url+ with ws(s):// (advanced)
|
|
69
|
+
# @param bootstrap [Hash, String, nil] a bundle (Hash or JSON text) to use until the edge answers
|
|
70
|
+
# @param cache_path [String, nil] keep the last good bundle in this file (restored, and verified again, on start)
|
|
71
|
+
# @param store [#get, #set, nil] custom persistence; overrides +cache_path+
|
|
72
|
+
# @param events [Hash, false, nil] telemetry: false disables it; a Hash with :sample_rate (0.1), :flush_interval
|
|
73
|
+
# (10 s), :report_interval (60 s), :redact (a callable receiving the context Hash)
|
|
74
|
+
# @param verify [Hash, Boolean, nil] signature verification: nil (default) on for the hosted edge; false off;
|
|
75
|
+
# true on with keys from the edge's /v1/keys; a Hash with :public_keys (JWKs), :require, :fetch_keys
|
|
76
|
+
# @param on_change [#call, nil] called with an {UpdateEvent} whenever a new configuration is adopted
|
|
77
|
+
# @param on_error [#call, nil] called with an {Error} for background failures
|
|
78
|
+
# @param logger [Logger, nil] debug output of the background activity
|
|
79
|
+
# @param start [Boolean] false defers the background work until {#start}
|
|
80
|
+
# @param http [#call, nil] the transport (see {HTTP::NetHttp})
|
|
81
|
+
def initialize(sdk_key, base_url: OFFICIAL_EDGE_URL, service: nil, poll_interval: 30, streaming: true, live: true,
|
|
82
|
+
live_poll_interval: 300, live_url: nil, bootstrap: nil, cache_path: nil, store: nil, events: nil,
|
|
83
|
+
verify: nil, on_change: nil, on_error: nil, logger: nil, start: true, http: nil, request_timeout: 10,
|
|
84
|
+
stream_read_timeout: 90, random: nil)
|
|
85
|
+
@sdk_key = sdk_key.to_s
|
|
86
|
+
@base_url = base_url.to_s.sub(%r{/+\z}, "")
|
|
87
|
+
@service = service.to_s.empty? ? "unknown" : service.to_s
|
|
88
|
+
@poll_interval = poll_interval.to_f
|
|
89
|
+
@streaming = streaming
|
|
90
|
+
@live_enabled = live
|
|
91
|
+
@live_poll_interval = live_poll_interval.to_f
|
|
92
|
+
@live_url = live_url&.to_s
|
|
93
|
+
@request_timeout = request_timeout.to_f
|
|
94
|
+
@stream_read_timeout = stream_read_timeout.to_f
|
|
95
|
+
@http = http || HTTP::NetHttp.new
|
|
96
|
+
@logger = logger
|
|
97
|
+
@random = random || -> { rand }
|
|
98
|
+
@id = format("%08x", Engine.murmur3("#{@base_url}|#{@sdk_key}"))
|
|
99
|
+
@browser_key = @sdk_key.start_with?("nf_pub_")
|
|
100
|
+
@store = store || (cache_path ? Store::File.new(cache_path) : nil)
|
|
101
|
+
@pending_errors = []
|
|
102
|
+
|
|
103
|
+
ev = events.is_a?(Hash) ? events.transform_keys(&:to_sym) : {}
|
|
104
|
+
@events_enabled = events != false
|
|
105
|
+
@sample_rate = Float(ev.fetch(:sample_rate, 0.1)).clamp(0.0, 1.0)
|
|
106
|
+
@flush_interval = Float(ev.fetch(:flush_interval, 10.0))
|
|
107
|
+
@report_interval = Float(ev.fetch(:report_interval, 60.0))
|
|
108
|
+
@redact = ev[:redact]
|
|
109
|
+
|
|
110
|
+
setup_verifier(verify)
|
|
111
|
+
@fetched_keys = []
|
|
112
|
+
@keys_fetched_at = nil
|
|
113
|
+
|
|
114
|
+
@listeners = { change: [], error: [], status: [] }
|
|
115
|
+
@listeners[:change] << on_change if on_change
|
|
116
|
+
@listeners[:error] << on_error if on_error
|
|
117
|
+
|
|
118
|
+
@bundle = nil
|
|
119
|
+
@etag = nil
|
|
120
|
+
@checksum = nil
|
|
121
|
+
@sig = nil
|
|
122
|
+
@raw = nil
|
|
123
|
+
@status = STATUS_NOT_READY
|
|
124
|
+
@last_error = nil
|
|
125
|
+
@pinned_env = nil
|
|
126
|
+
@failures = 0
|
|
127
|
+
@closed = false
|
|
128
|
+
@started = false
|
|
129
|
+
@ready = false
|
|
130
|
+
@stream_open = false
|
|
131
|
+
@live_open = false
|
|
132
|
+
@live_socket = nil
|
|
133
|
+
@live_revision = 0
|
|
134
|
+
@environment_deleted = false
|
|
135
|
+
@sessions = {}
|
|
136
|
+
@session_locks = {}
|
|
137
|
+
@queue = []
|
|
138
|
+
@last_report = monotonic
|
|
139
|
+
@attrs = {}
|
|
140
|
+
@attrs_for = nil
|
|
141
|
+
init_concurrency
|
|
142
|
+
|
|
143
|
+
if @sdk_key.strip.empty?
|
|
144
|
+
@pending_errors << Error.new("An SDK key is required.", :config)
|
|
145
|
+
end
|
|
146
|
+
@pending_errors << Error.new("The base URL must be an http(s) URL, got #{base_url.inspect}.", :config) unless @base_url.match?(%r{\Ahttps?://}i)
|
|
147
|
+
adopt_bootstrap(bootstrap) unless bootstrap.nil?
|
|
148
|
+
REGISTRY_LOCK.synchronize { REGISTRY[self] = true }
|
|
149
|
+
Client.install_exit_hook
|
|
150
|
+
self.start if start
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
# ------------------------------------------------------------------ lifecycle
|
|
154
|
+
|
|
155
|
+
# Starts the background threads (done by the constructor unless +start: false+).
|
|
156
|
+
def start
|
|
157
|
+
check_fork
|
|
158
|
+
@mutex.synchronize do
|
|
159
|
+
return self if @started || @closed
|
|
160
|
+
|
|
161
|
+
@started = true
|
|
162
|
+
end
|
|
163
|
+
pending = @pending_errors
|
|
164
|
+
@pending_errors = []
|
|
165
|
+
pending.each { |e| emit_error(e) }
|
|
166
|
+
if pending.any? { |e| e.code == :config && e.message.start_with?("An SDK key", "The base URL") }
|
|
167
|
+
mark_ready
|
|
168
|
+
return self
|
|
169
|
+
end
|
|
170
|
+
spawn("nanoflags-poll") { main_loop }
|
|
171
|
+
self
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
# Stops the background threads after a best-effort final telemetry flush (at most 2 seconds). Evaluations keep
|
|
175
|
+
# working on the last configuration. Idempotent.
|
|
176
|
+
def close
|
|
177
|
+
return if @closed
|
|
178
|
+
|
|
179
|
+
flush(timeout: 2) if @started && Process.pid == @pid
|
|
180
|
+
@mutex.synchronize do
|
|
181
|
+
@closed = true
|
|
182
|
+
@cv.broadcast
|
|
183
|
+
@sleep_cv.broadcast
|
|
184
|
+
end
|
|
185
|
+
close_stream
|
|
186
|
+
drop_live
|
|
187
|
+
mark_ready
|
|
188
|
+
@threads.each { |t| t.join(2) unless t == Thread.current }
|
|
189
|
+
nil
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
def closed? = @closed
|
|
193
|
+
|
|
194
|
+
# Blocks until the first load attempt has finished (or a configuration was adopted); returns whether a
|
|
195
|
+
# configuration is in use. +timeout+ in seconds (nil: no limit).
|
|
196
|
+
def wait_until_ready(timeout = nil)
|
|
197
|
+
check_fork
|
|
198
|
+
deadline = timeout && (monotonic + timeout)
|
|
199
|
+
@mutex.synchronize do
|
|
200
|
+
until @ready
|
|
201
|
+
left = deadline && (deadline - monotonic)
|
|
202
|
+
break if left && left <= 0
|
|
203
|
+
|
|
204
|
+
@ready_cv.wait(left)
|
|
205
|
+
end
|
|
206
|
+
end
|
|
207
|
+
!@bundle.nil?
|
|
208
|
+
end
|
|
209
|
+
|
|
210
|
+
# "not-ready", "ready" (known to be current) or "stale" (in use, not known to be current).
|
|
211
|
+
def status = @status
|
|
212
|
+
|
|
213
|
+
# The revision in use, or nil.
|
|
214
|
+
def revision = @bundle && @bundle["revision"].to_i
|
|
215
|
+
|
|
216
|
+
# True when a configuration is in use (ready or stale).
|
|
217
|
+
def initialized? = !@bundle.nil?
|
|
218
|
+
|
|
219
|
+
# :live while the live socket is open, :stream while the event stream is connected, otherwise :poll.
|
|
220
|
+
def transport
|
|
221
|
+
return :poll if Process.pid != @pid # a forked child has none of the parent's connections
|
|
222
|
+
return :live if @live_open
|
|
223
|
+
|
|
224
|
+
@stream_open ? :stream : :poll
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
# The last background error, if any.
|
|
228
|
+
def last_error = @last_error
|
|
229
|
+
|
|
230
|
+
# The bundle in use as JSON text (the signed bytes when it was signed), or nil.
|
|
231
|
+
def bundle_json = @raw || (@bundle && Engine::Js.stringify(@bundle))
|
|
232
|
+
|
|
233
|
+
# Registers a listener: +:change+ ({UpdateEvent}), +:error+ ({Error}) or +:status+ (a status string). Returns a
|
|
234
|
+
# lambda that removes it. Listeners run on a background thread; exceptions they raise are swallowed.
|
|
235
|
+
def on(event, callable = nil, &block)
|
|
236
|
+
fn = callable || block
|
|
237
|
+
list = @listeners.fetch(event.to_sym) { raise ArgumentError, "unknown event #{event.inspect}" }
|
|
238
|
+
list << fn
|
|
239
|
+
-> { list.delete(fn) }
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
def on_change(callable = nil, &block) = on(:change, callable, &block)
|
|
243
|
+
def on_error(callable = nil, &block) = on(:error, callable, &block)
|
|
244
|
+
|
|
245
|
+
# Revalidates now (blocking) and returns whether a configuration is in use. Errors are reported, never raised.
|
|
246
|
+
def refresh
|
|
247
|
+
check_fork
|
|
248
|
+
sync
|
|
249
|
+
initialized?
|
|
250
|
+
end
|
|
251
|
+
|
|
252
|
+
# ------------------------------------------------------------------ evaluation
|
|
253
|
+
|
|
254
|
+
# The boolean value of +key+ for +context+; +default+ when the flag is unknown, not a boolean, or nothing is loaded.
|
|
255
|
+
def bool_variation(key, default, context = nil) = run(key, default, context, ACCEPT_BOOL).value
|
|
256
|
+
def string_variation(key, default, context = nil) = run(key, default, context, ACCEPT_STRING).value
|
|
257
|
+
# A number flag; whole numbers are returned as Integer.
|
|
258
|
+
def number_variation(key, default, context = nil) = run(key, default, context, ACCEPT_NUMBER).value
|
|
259
|
+
# A JSON flag as plain Ruby data (Hash with String keys, Array, …); any served value is accepted.
|
|
260
|
+
def json_variation(key, default, context = nil) = run(key, default, context, ACCEPT_ANY).value
|
|
261
|
+
|
|
262
|
+
def bool_variation_detail(key, default, context = nil) = run(key, default, context, ACCEPT_BOOL)
|
|
263
|
+
def string_variation_detail(key, default, context = nil) = run(key, default, context, ACCEPT_STRING)
|
|
264
|
+
def number_variation_detail(key, default, context = nil) = run(key, default, context, ACCEPT_NUMBER)
|
|
265
|
+
def json_variation_detail(key, default, context = nil) = run(key, default, context, ACCEPT_ANY)
|
|
266
|
+
|
|
267
|
+
# The full engine result ({EvaluationDetail}) without any type check.
|
|
268
|
+
def evaluate(key, default, context = nil) = run(key, default, context, nil)
|
|
269
|
+
|
|
270
|
+
# Every flag of the configuration in use evaluated for +context+ ({} when nothing is loaded). Not sampled into
|
|
271
|
+
# telemetry.
|
|
272
|
+
def all_flags(context = nil)
|
|
273
|
+
all_flags_detail(context).transform_values(&:value)
|
|
274
|
+
end
|
|
275
|
+
|
|
276
|
+
def all_flags_detail(context = nil)
|
|
277
|
+
b = @bundle
|
|
278
|
+
return {} if b.nil?
|
|
279
|
+
|
|
280
|
+
ctx = to_context(context)
|
|
281
|
+
out = {}
|
|
282
|
+
b["flags"].each_key do |k|
|
|
283
|
+
r = Engine.evaluate(b, k, ctx, nil)
|
|
284
|
+
out[k] = EvaluationDetail.from_result(r, nil) unless r.reason == "flag_not_found"
|
|
285
|
+
end
|
|
286
|
+
out
|
|
287
|
+
rescue StandardError
|
|
288
|
+
{}
|
|
289
|
+
end
|
|
290
|
+
|
|
291
|
+
# ------------------------------------------------------------------ test sessions
|
|
292
|
+
|
|
293
|
+
# Resolves a test session (+GET /v1/session+, once per token and service, cached until the session expires) and
|
|
294
|
+
# returns a {SessionEvaluator} scoped to it. Pass the incoming +x-nanoflags-session+ header value. Blocks on the
|
|
295
|
+
# first call per token; never raises. Unknown tokens are remembered for 15 s, failed lookups for 3 s. Without an
|
|
296
|
+
# active session the evaluator behaves exactly like the client.
|
|
297
|
+
#
|
|
298
|
+
# +service+ is sent as +X-NanoFlags-Service+ (default: the client's +service+); a session may be limited to
|
|
299
|
+
# certain services.
|
|
300
|
+
def session(token, service: nil)
|
|
301
|
+
check_fork
|
|
302
|
+
return SessionEvaluator.new(self, nil) if !NanoFlags.session_token?(token) || @closed || !@base_url.match?(%r{\Ahttps?://}i)
|
|
303
|
+
|
|
304
|
+
name = service.to_s.empty? ? (@service == "unknown" ? nil : @service) : service.to_s
|
|
305
|
+
key = "#{name}\n#{token}"
|
|
306
|
+
if (hit = cached_session(key))
|
|
307
|
+
return SessionEvaluator.new(self, hit[0])
|
|
308
|
+
end
|
|
309
|
+
|
|
310
|
+
# One lookup per token at a time: concurrent requests of the same session wait for it instead of repeating it.
|
|
311
|
+
lock = @sessions_mutex.synchronize { @session_locks[key] ||= Mutex.new }
|
|
312
|
+
lock.synchronize do
|
|
313
|
+
if (hit = cached_session(key))
|
|
314
|
+
return SessionEvaluator.new(self, hit[0])
|
|
315
|
+
end
|
|
316
|
+
|
|
317
|
+
state, failed = fetch_session(token, name)
|
|
318
|
+
until_ts = state ? state.expires_at_ts : Time.now.to_f + (failed ? SESSION_ERROR_TTL : SESSION_MISS_TTL)
|
|
319
|
+
@sessions_mutex.synchronize do
|
|
320
|
+
if @sessions.size >= MAX_SESSIONS
|
|
321
|
+
now = Time.now.to_f
|
|
322
|
+
@sessions.delete_if { |_, v| now >= v[1] }
|
|
323
|
+
@sessions.delete(@sessions.first[0]) while @sessions.size >= MAX_SESSIONS # oldest first
|
|
324
|
+
end
|
|
325
|
+
@sessions[key] = [state, until_ts]
|
|
326
|
+
@session_locks.delete(key)
|
|
327
|
+
end
|
|
328
|
+
SessionEvaluator.new(self, state)
|
|
329
|
+
end
|
|
330
|
+
rescue StandardError
|
|
331
|
+
SessionEvaluator.new(self, nil)
|
|
332
|
+
end
|
|
333
|
+
|
|
334
|
+
# ------------------------------------------------------------------ fork safety
|
|
335
|
+
|
|
336
|
+
# @api private
|
|
337
|
+
def self.install_exit_hook
|
|
338
|
+
REGISTRY_LOCK.synchronize do
|
|
339
|
+
return if @exit_hook
|
|
340
|
+
|
|
341
|
+
@exit_hook = true
|
|
342
|
+
at_exit { each_client { |c| c.close unless c.closed? } }
|
|
343
|
+
end
|
|
344
|
+
end
|
|
345
|
+
|
|
346
|
+
# @api private
|
|
347
|
+
def self.each_client(&block)
|
|
348
|
+
clients = REGISTRY_LOCK.synchronize { REGISTRY.keys }
|
|
349
|
+
clients.each(&block)
|
|
350
|
+
end
|
|
351
|
+
|
|
352
|
+
# Restarts the background threads of every client in a forked child now (for example from Puma's
|
|
353
|
+
# +on_worker_boot+). Optional: a client notices the fork on its first call in the child and restarts then.
|
|
354
|
+
def self.after_fork
|
|
355
|
+
each_client { |c| c.send(:check_fork) }
|
|
356
|
+
end
|
|
357
|
+
|
|
358
|
+
private
|
|
359
|
+
|
|
360
|
+
def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
361
|
+
|
|
362
|
+
def init_concurrency
|
|
363
|
+
@pid = Process.pid
|
|
364
|
+
@mutex = Monitor.new
|
|
365
|
+
@cv = @mutex.new_cond # wakes the poll loop (sync requested, close)
|
|
366
|
+
@sleep_cv = @mutex.new_cond # wakes the other loops (close)
|
|
367
|
+
@ready_cv = @mutex.new_cond
|
|
368
|
+
@sessions_mutex = Mutex.new
|
|
369
|
+
@rescheduled = false
|
|
370
|
+
@sync_mutex = Mutex.new
|
|
371
|
+
@keys_mutex = Mutex.new
|
|
372
|
+
@queue_mutex = Mutex.new
|
|
373
|
+
@threads = []
|
|
374
|
+
@sync_requested = false
|
|
375
|
+
@stream_closer = nil
|
|
376
|
+
@stream_thread = nil
|
|
377
|
+
@stream_active = false
|
|
378
|
+
@stream_gen = 0
|
|
379
|
+
end
|
|
380
|
+
|
|
381
|
+
# A fork keeps the configuration but not the threads: restart them in the child, and drop the parent's queued
|
|
382
|
+
# events (the parent sends those).
|
|
383
|
+
def check_fork
|
|
384
|
+
return if Process.pid == @pid
|
|
385
|
+
|
|
386
|
+
FORK_LOCK.synchronize do
|
|
387
|
+
return if Process.pid == @pid
|
|
388
|
+
|
|
389
|
+
was_started = @started
|
|
390
|
+
init_concurrency
|
|
391
|
+
@queue = []
|
|
392
|
+
@stream_open = false
|
|
393
|
+
# The parent's socket is the parent's: never write to it (not even a close frame) from the child.
|
|
394
|
+
@live_open = false
|
|
395
|
+
@live_socket = nil
|
|
396
|
+
@session_locks = {}
|
|
397
|
+
@started = false
|
|
398
|
+
@last_report = monotonic
|
|
399
|
+
start if was_started && !@closed
|
|
400
|
+
end
|
|
401
|
+
end
|
|
402
|
+
|
|
403
|
+
FORK_LOCK = Mutex.new
|
|
404
|
+
|
|
405
|
+
def spawn(name, &block)
|
|
406
|
+
t = Thread.new do
|
|
407
|
+
Thread.current.name = name
|
|
408
|
+
Thread.current.report_on_exception = false
|
|
409
|
+
block.call
|
|
410
|
+
rescue StandardError => e
|
|
411
|
+
log { "#{name} stopped: #{e.class}: #{e.message}" }
|
|
412
|
+
end
|
|
413
|
+
@threads << t
|
|
414
|
+
t
|
|
415
|
+
end
|
|
416
|
+
|
|
417
|
+
def log
|
|
418
|
+
@logger&.debug("nanoflags") { yield }
|
|
419
|
+
end
|
|
420
|
+
|
|
421
|
+
def mark_ready
|
|
422
|
+
@mutex.synchronize do
|
|
423
|
+
@ready = true
|
|
424
|
+
@ready_cv.broadcast
|
|
425
|
+
end
|
|
426
|
+
end
|
|
427
|
+
|
|
428
|
+
def fire(event, arg)
|
|
429
|
+
@listeners[event].dup.each do |fn|
|
|
430
|
+
fn.call(arg)
|
|
431
|
+
rescue StandardError => e
|
|
432
|
+
log { "#{event} listener raised #{e.class}: #{e.message}" }
|
|
433
|
+
end
|
|
434
|
+
end
|
|
435
|
+
|
|
436
|
+
def emit_error(e)
|
|
437
|
+
@last_error = e
|
|
438
|
+
log { "#{e.code}: #{e.message}" }
|
|
439
|
+
fire(:error, e)
|
|
440
|
+
end
|
|
441
|
+
|
|
442
|
+
def set_status(status)
|
|
443
|
+
changed = @mutex.synchronize do
|
|
444
|
+
old = @status
|
|
445
|
+
@status = status
|
|
446
|
+
old != status
|
|
447
|
+
end
|
|
448
|
+
fire(:status, status) if changed
|
|
449
|
+
end
|
|
450
|
+
|
|
451
|
+
def setup_verifier(verify)
|
|
452
|
+
official = @base_url == OFFICIAL_EDGE_URL
|
|
453
|
+
official_keys = -> { Signature.import_keys(OFFICIAL_SIGNING_KEYS) }
|
|
454
|
+
@verifier =
|
|
455
|
+
case verify
|
|
456
|
+
when false then nil
|
|
457
|
+
when nil then official ? { base: official_keys.(), require: true, refetch: true } : nil
|
|
458
|
+
when true then official ? { base: official_keys.(), require: true, refetch: true } : { base: [], require: true, refetch: true }
|
|
459
|
+
when Hash
|
|
460
|
+
v = verify.transform_keys(&:to_sym)
|
|
461
|
+
req = v.key?(:require) ? v[:require] : official
|
|
462
|
+
keys = v[:public_keys]
|
|
463
|
+
if keys.is_a?(Array) && !keys.empty?
|
|
464
|
+
unless keys.all? { |k| Signature.public_ed25519_jwk?(k.is_a?(Hash) ? k.transform_keys(&:to_s) : k) }
|
|
465
|
+
@pending_errors << Error.new("`verify[:public_keys]` must contain public Ed25519 JWKs only. Other entries (including private keys) were ignored.", :config)
|
|
466
|
+
end
|
|
467
|
+
{ base: Signature.import_keys(keys), require: req, refetch: v.fetch(:fetch_keys, false) }
|
|
468
|
+
elsif v[:fetch_keys] || !official
|
|
469
|
+
{ base: [], require: req, refetch: true }
|
|
470
|
+
else
|
|
471
|
+
{ base: official_keys.(), require: req, refetch: true }
|
|
472
|
+
end
|
|
473
|
+
else raise ArgumentError, "verify must be nil, true, false or a Hash"
|
|
474
|
+
end
|
|
475
|
+
end
|
|
476
|
+
|
|
477
|
+
def adopt_bootstrap(bootstrap)
|
|
478
|
+
b = bootstrap.is_a?(String) ? Engine::Json.parse(bootstrap) : Engine::Js.from_ruby(bootstrap)
|
|
479
|
+
if !Engine.bundle?(b)
|
|
480
|
+
@pending_errors << Error.new("The bootstrap bundle is invalid and was ignored.", :invalid_bundle)
|
|
481
|
+
elsif !Engine.supports_engine?(b.fetch("engine", Engine::UNDEFINED))
|
|
482
|
+
@pending_errors << engine_error(b)
|
|
483
|
+
else
|
|
484
|
+
adopt(b, etag: nil, checksum: nil, sig: nil, raw: nil, status: STATUS_READY, source: :bootstrap, transport: :poll)
|
|
485
|
+
end
|
|
486
|
+
rescue Engine::InvalidJsonError
|
|
487
|
+
@pending_errors << Error.new("The bootstrap bundle is invalid and was ignored.", :invalid_bundle)
|
|
488
|
+
end
|
|
489
|
+
|
|
490
|
+
def engine_error(b)
|
|
491
|
+
Error.new("Bundle r#{Engine::Js.to_str(b.fetch("revision", Engine::UNDEFINED))} needs evaluation engine #{Engine::Js.stringify(b.fetch("engine", Engine::UNDEFINED)) || "undefined"}; " \
|
|
492
|
+
"this SDK supports up to #{Engine::VERSION}. Upgrade the nanoflags gem. The configuration in use is unchanged.", :engine)
|
|
493
|
+
end
|
|
494
|
+
|
|
495
|
+
def adopt(bundle, etag:, checksum:, sig:, raw:, status:, source:, transport:, latency_ms: nil)
|
|
496
|
+
event = nil
|
|
497
|
+
@mutex.synchronize do
|
|
498
|
+
prev = @bundle
|
|
499
|
+
prev_rev = prev && prev["revision"].to_i
|
|
500
|
+
is_new = prev.nil? || prev_rev != bundle["revision"].to_i || @checksum != checksum
|
|
501
|
+
@bundle = bundle # one assignment: every evaluation sees one consistent revision
|
|
502
|
+
@etag = etag
|
|
503
|
+
@checksum = checksum
|
|
504
|
+
@sig = sig
|
|
505
|
+
@raw = raw
|
|
506
|
+
event = UpdateEvent.new(revision: bundle["revision"].to_i, previous_revision: prev_rev, checksum: checksum, source: source, transport: transport, latency_ms: latency_ms) if is_new
|
|
507
|
+
end
|
|
508
|
+
set_status(status)
|
|
509
|
+
mark_ready
|
|
510
|
+
fire(:change, event) if event
|
|
511
|
+
end
|
|
512
|
+
|
|
513
|
+
# ------------------------------------------------------------------ evaluation internals
|
|
514
|
+
|
|
515
|
+
def to_context(context)
|
|
516
|
+
return {} if context.nil?
|
|
517
|
+
|
|
518
|
+
v = Engine::Js.from_ruby(context)
|
|
519
|
+
v.is_a?(Hash) ? v : {}
|
|
520
|
+
end
|
|
521
|
+
|
|
522
|
+
# +scope+: a live test session ({SessionState}) or nil for the configuration in use.
|
|
523
|
+
def run(key, default, context, accepts, scope = nil)
|
|
524
|
+
check_fork
|
|
525
|
+
if scope
|
|
526
|
+
b = scope.bundle
|
|
527
|
+
ctx = scope.context.merge(to_context(context))
|
|
528
|
+
else
|
|
529
|
+
b = @bundle
|
|
530
|
+
ctx = to_context(context)
|
|
531
|
+
end
|
|
532
|
+
fallback = Engine::Js.from_ruby(default)
|
|
533
|
+
r = Engine.evaluate(b, key.to_s, ctx, fallback)
|
|
534
|
+
if accepts && r.reason != "flag_not_found" && r.reason != "error" && !accepts.(r.value)
|
|
535
|
+
error = "Flag \"#{key}\" has a #{Engine::Js.type_name(r.value)} value, which does not match the requested type."
|
|
536
|
+
r = Engine::Result.new(key.to_s, fallback, "error", r.revision, nil, Engine::UNDEFINED, nil, nil,
|
|
537
|
+
r.trace + [Engine::TraceStep.new("result", "Returned the fallback", error)], error)
|
|
538
|
+
end
|
|
539
|
+
record(r, scope ? nil : context, ctx, b, scope&.id)
|
|
540
|
+
EvaluationDetail.from_result(r, default)
|
|
541
|
+
rescue StandardError => e
|
|
542
|
+
EvaluationDetail.new(flag_key: key.to_s, value: default, reason: "error", revision: 0, error: e.message)
|
|
543
|
+
end
|
|
544
|
+
|
|
545
|
+
# ------------------------------------------------------------------ background loop
|
|
546
|
+
|
|
547
|
+
def main_loop
|
|
548
|
+
restore
|
|
549
|
+
sync
|
|
550
|
+
mark_ready # even without a bundle: callers must not hang; they check `status`
|
|
551
|
+
return if @closed
|
|
552
|
+
|
|
553
|
+
spawn("nanoflags-events") { events_loop } if @events_enabled && @flush_interval.positive?
|
|
554
|
+
if @streaming
|
|
555
|
+
if live_wanted?
|
|
556
|
+
spawn("nanoflags-socket") { live_loop }
|
|
557
|
+
else
|
|
558
|
+
start_stream
|
|
559
|
+
end
|
|
560
|
+
end
|
|
561
|
+
loop do
|
|
562
|
+
due = @mutex.synchronize do
|
|
563
|
+
return if @closed
|
|
564
|
+
|
|
565
|
+
unless @sync_requested || @rescheduled
|
|
566
|
+
if @poll_interval.positive?
|
|
567
|
+
@cv.wait(next_delay)
|
|
568
|
+
else
|
|
569
|
+
@cv.wait
|
|
570
|
+
end
|
|
571
|
+
end
|
|
572
|
+
return if @closed
|
|
573
|
+
|
|
574
|
+
# Rescheduled (the live socket opened or closed): wait again with the new interval, without a request.
|
|
575
|
+
if @rescheduled && !@sync_requested
|
|
576
|
+
@rescheduled = false
|
|
577
|
+
next false
|
|
578
|
+
end
|
|
579
|
+
@rescheduled = false
|
|
580
|
+
@sync_requested = false
|
|
581
|
+
true
|
|
582
|
+
end
|
|
583
|
+
sync if due
|
|
584
|
+
end
|
|
585
|
+
end
|
|
586
|
+
|
|
587
|
+
# Restarts the poll wait (its interval depends on whether the live socket is open).
|
|
588
|
+
def reschedule
|
|
589
|
+
@mutex.synchronize do
|
|
590
|
+
@rescheduled = true
|
|
591
|
+
@cv.broadcast
|
|
592
|
+
end
|
|
593
|
+
end
|
|
594
|
+
|
|
595
|
+
def request_sync
|
|
596
|
+
@mutex.synchronize do
|
|
597
|
+
@sync_requested = true
|
|
598
|
+
@cv.broadcast
|
|
599
|
+
end
|
|
600
|
+
end
|
|
601
|
+
|
|
602
|
+
def next_delay
|
|
603
|
+
jitter = 0.8 + (0.4 * @random.call)
|
|
604
|
+
interval = @live_open ? [@poll_interval, @live_poll_interval].max : @poll_interval
|
|
605
|
+
base = @failures.positive? ? [@poll_interval, 2.0**[@failures - 1, 10].min].min : interval
|
|
606
|
+
[0.25, base * jitter].max
|
|
607
|
+
end
|
|
608
|
+
|
|
609
|
+
def headers(extra = nil)
|
|
610
|
+
h = { "Authorization" => "Bearer #{@sdk_key}", "User-Agent" => "nanoflags-ruby/#{VERSION}" }
|
|
611
|
+
extra ? h.merge(extra) : h
|
|
612
|
+
end
|
|
613
|
+
|
|
614
|
+
def request(method, path, extra_headers = nil, body = nil, timeout = @request_timeout)
|
|
615
|
+
@http.call(method, "#{@base_url}#{path}", headers(extra_headers), body, timeout)
|
|
616
|
+
end
|
|
617
|
+
|
|
618
|
+
def sync
|
|
619
|
+
@sync_mutex.synchronize { sync_once unless @closed }
|
|
620
|
+
end
|
|
621
|
+
|
|
622
|
+
def sync_once
|
|
623
|
+
transport = @stream_triggered ? :stream : :poll
|
|
624
|
+
@stream_triggered = false
|
|
625
|
+
begin
|
|
626
|
+
res = begin
|
|
627
|
+
request("GET", "/v1/bundle", @etag ? { "If-None-Match" => @etag } : nil)
|
|
628
|
+
rescue StandardError => e
|
|
629
|
+
raise Error.new("Could not reach the NanoFlags edge: #{e.message}", :network)
|
|
630
|
+
end
|
|
631
|
+
return if @closed
|
|
632
|
+
|
|
633
|
+
served_stale = res.header("X-NanoFlags-Stale") == "true"
|
|
634
|
+
if res.status == 304 && @bundle
|
|
635
|
+
@failures = 0
|
|
636
|
+
set_status(served_stale ? STATUS_STALE : STATUS_READY)
|
|
637
|
+
return
|
|
638
|
+
end
|
|
639
|
+
raise Error.new("The SDK key was rejected (unknown or revoked).", :unauthorized, res.status) if [401, 403].include?(res.status)
|
|
640
|
+
raise Error.new("Bundle request failed with HTTP #{res.status}.", :http, res.status) unless res.ok?
|
|
641
|
+
|
|
642
|
+
body = begin
|
|
643
|
+
Engine::Json.parse(res.body)
|
|
644
|
+
rescue Engine::InvalidJsonError
|
|
645
|
+
nil
|
|
646
|
+
end
|
|
647
|
+
raise Error.new("The edge returned an invalid bundle.", :invalid_bundle) unless body.is_a?(Hash) && Engine.bundle?(body["bundle"])
|
|
648
|
+
|
|
649
|
+
bundle = body["bundle"]
|
|
650
|
+
sig, raw = check_signature(res, body, bundle)
|
|
651
|
+
return if @closed
|
|
652
|
+
raise engine_error(bundle) unless Engine.supports_engine?(bundle.fetch("engine", Engine::UNDEFINED))
|
|
653
|
+
|
|
654
|
+
@failures = 0
|
|
655
|
+
cur = @bundle
|
|
656
|
+
# The edge is serving its last-known-good copy: never go backwards because of it.
|
|
657
|
+
if served_stale && cur && cur["revision"] >= bundle["revision"]
|
|
658
|
+
set_status(STATUS_STALE)
|
|
659
|
+
return
|
|
660
|
+
end
|
|
661
|
+
checksum = body["checksum"].is_a?(String) ? body["checksum"] : nil
|
|
662
|
+
# A revision pushed while this request was under way (or that the edge's cache does not point at yet) wins.
|
|
663
|
+
return if cur && bundle["revision"].to_i < @live_revision && cur["revision"].to_i >= @live_revision
|
|
664
|
+
|
|
665
|
+
@pinned_env = sig.environment_id if sig
|
|
666
|
+
adopt(bundle, etag: res.header("ETag"), checksum: checksum, sig: sig, raw: raw,
|
|
667
|
+
status: served_stale ? STATUS_STALE : STATUS_READY, source: :network, transport: transport)
|
|
668
|
+
persist
|
|
669
|
+
rescue Error => e
|
|
670
|
+
return if @closed
|
|
671
|
+
|
|
672
|
+
if e.code == :engine
|
|
673
|
+
emit_error(e)
|
|
674
|
+
return
|
|
675
|
+
end
|
|
676
|
+
@failures += 1
|
|
677
|
+
if e.code == :signature
|
|
678
|
+
emit_error(e) # same bundle, same status; polling retries with backoff
|
|
679
|
+
return
|
|
680
|
+
end
|
|
681
|
+
drop_live if e.code == :unauthorized
|
|
682
|
+
set_status(STATUS_STALE) if @bundle
|
|
683
|
+
emit_error(e)
|
|
684
|
+
end
|
|
685
|
+
end
|
|
686
|
+
|
|
687
|
+
# Verifies a /v1/bundle response (when verification is on); returns [signature info or nil, bundle text to keep].
|
|
688
|
+
def check_signature(res, body, bundle)
|
|
689
|
+
raw = Signature.raw_member(res.body, "bundle")
|
|
690
|
+
return [nil, raw] unless @verifier
|
|
691
|
+
|
|
692
|
+
rev = bundle["revision"].to_i
|
|
693
|
+
reject = ->(why) { Error.new("Bundle r#{rev} was rejected: #{why} The configuration in use is unchanged.", :signature) }
|
|
694
|
+
unless res.header("X-NanoFlags-Signed") == "true"
|
|
695
|
+
raise reject.("it is not signed (the edge is still distributing it) and unsigned bundles are refused; fetching again shortly.") if @verifier[:require]
|
|
696
|
+
|
|
697
|
+
return [nil, raw]
|
|
698
|
+
end
|
|
699
|
+
signature = res.header("X-NanoFlags-Signature")
|
|
700
|
+
env_id = res.header("X-NanoFlags-Environment-Id")
|
|
701
|
+
kid = res.header("X-NanoFlags-Key-Id")
|
|
702
|
+
checksum = body["checksum"]
|
|
703
|
+
raise reject.("the signature headers are incomplete.") if signature.to_s.empty? || env_id.to_s.empty? || !checksum.is_a?(String)
|
|
704
|
+
raise reject.("the signed revision does not match the bundle.") if body["revision"].is_a?(Float) && body["revision"].to_i != rev
|
|
705
|
+
raise reject.("it was signed for a different environment.") if @pinned_env && @pinned_env != env_id
|
|
706
|
+
|
|
707
|
+
info = Signature::Info.new(signature, kid.to_s.empty? ? nil : kid, env_id, rev, checksum)
|
|
708
|
+
keys = begin
|
|
709
|
+
load_keys(info.kid)
|
|
710
|
+
rescue StandardError => e
|
|
711
|
+
raise reject.("the signing keys could not be loaded (#{e.message}).")
|
|
712
|
+
end
|
|
713
|
+
# The edge embeds the stored bundle text byte-for-byte; re-serialisation is the fallback.
|
|
714
|
+
return [info, raw] if raw && Signature.verify(keys, info, raw)
|
|
715
|
+
|
|
716
|
+
again = Engine::Js.stringify(bundle)
|
|
717
|
+
return [info, again] if again && again != raw && Signature.verify(keys, info, again)
|
|
718
|
+
|
|
719
|
+
raise reject.("its signature does not verify.")
|
|
720
|
+
end
|
|
721
|
+
|
|
722
|
+
# The pinned or embedded keys plus those of /v1/keys; an unknown key id reloads /v1/keys (at most once a minute).
|
|
723
|
+
def load_keys(kid)
|
|
724
|
+
v = @verifier
|
|
725
|
+
return [] unless v
|
|
726
|
+
return v[:base] unless v[:refetch]
|
|
727
|
+
|
|
728
|
+
@keys_mutex.synchronize do
|
|
729
|
+
known = v[:base] + @fetched_keys
|
|
730
|
+
return known if !known.empty? && (kid.nil? || known.any? { |k| k.kid == kid })
|
|
731
|
+
return known if @keys_fetched_at && monotonic - @keys_fetched_at < KEYS_REFETCH
|
|
732
|
+
|
|
733
|
+
begin
|
|
734
|
+
# Public endpoint: the SDK key is deliberately not sent.
|
|
735
|
+
res = @http.call("GET", "#{@base_url}/v1/keys", { "User-Agent" => "nanoflags-ruby/#{VERSION}" }, nil, @request_timeout)
|
|
736
|
+
raise Error.new("Signing keys request failed with HTTP #{res.status}.", :signature, res.status) unless res.status == 200
|
|
737
|
+
|
|
738
|
+
parsed = JSON.parse(res.body)
|
|
739
|
+
keys = Signature.import_keys(parsed.is_a?(Hash) && parsed["keys"].is_a?(Array) ? parsed["keys"] : [])
|
|
740
|
+
raise Error.new("The edge returned no usable signing keys.", :signature) if keys.empty?
|
|
741
|
+
|
|
742
|
+
@fetched_keys = keys
|
|
743
|
+
rescue StandardError
|
|
744
|
+
raise if v[:base].empty?
|
|
745
|
+
ensure
|
|
746
|
+
@keys_fetched_at = monotonic
|
|
747
|
+
end
|
|
748
|
+
v[:base] + @fetched_keys
|
|
749
|
+
end
|
|
750
|
+
end
|
|
751
|
+
|
|
752
|
+
# ------------------------------------------------------------------ persistence
|
|
753
|
+
|
|
754
|
+
def persist
|
|
755
|
+
return unless @store
|
|
756
|
+
|
|
757
|
+
payload = @mutex.synchronize do
|
|
758
|
+
p = { "v" => 1, "id" => @id, "etag" => @etag, "checksum" => @checksum, "savedAt" => Time.now.utc.iso8601(3), "bundle" => Engine::Js.stringify(@bundle) }
|
|
759
|
+
if @sig
|
|
760
|
+
p["sig"] = @sig.to_h
|
|
761
|
+
p["raw"] = @raw if @raw
|
|
762
|
+
end
|
|
763
|
+
p
|
|
764
|
+
end
|
|
765
|
+
# "bundle" is JSON text inside the document, so the persisted bytes survive any re-encoding by the store.
|
|
766
|
+
@store.set(JSON.generate(payload))
|
|
767
|
+
rescue StandardError => e
|
|
768
|
+
emit_error(Error.new("Could not persist the bundle: #{e.message}", :store))
|
|
769
|
+
end
|
|
770
|
+
|
|
771
|
+
def restore
|
|
772
|
+
return unless @store
|
|
773
|
+
|
|
774
|
+
text = @store.get
|
|
775
|
+
return if text.nil? || text.empty? || @closed
|
|
776
|
+
|
|
777
|
+
p = JSON.parse(text)
|
|
778
|
+
return unless p.is_a?(Hash) && p["v"] == 1 && p["id"] == @id && p["bundle"].is_a?(String)
|
|
779
|
+
|
|
780
|
+
restored = Engine::Json.parse(p["bundle"])
|
|
781
|
+
return unless Engine.bundle?(restored)
|
|
782
|
+
return emit_error(engine_error(restored)) unless Engine.supports_engine?(restored.fetch("engine", Engine::UNDEFINED))
|
|
783
|
+
return if @bundle && @bundle["revision"] >= restored["revision"]
|
|
784
|
+
|
|
785
|
+
sig = nil
|
|
786
|
+
raw = nil
|
|
787
|
+
if @verifier
|
|
788
|
+
# The store is outside the trust boundary: a signed copy must verify again; with `require` an unsigned copy
|
|
789
|
+
# is not used at all.
|
|
790
|
+
s = Signature::Info.from_h(p["sig"])
|
|
791
|
+
if s && s.revision == restored["revision"].to_i
|
|
792
|
+
raw = p["raw"].is_a?(String) ? p["raw"] : p["bundle"]
|
|
793
|
+
ok = begin
|
|
794
|
+
Signature.verify(load_keys(s.kid), s, raw) && (parsed = Engine::Json.parse(raw)) && Engine.bundle?(parsed) && parsed["revision"].to_i == s.revision
|
|
795
|
+
rescue StandardError
|
|
796
|
+
false
|
|
797
|
+
end
|
|
798
|
+
return emit_error(Error.new("The persisted bundle failed signature verification and was ignored.", :signature)) unless ok
|
|
799
|
+
|
|
800
|
+
restored = parsed
|
|
801
|
+
sig = s
|
|
802
|
+
@pinned_env ||= s.environment_id
|
|
803
|
+
elsif @verifier[:require]
|
|
804
|
+
return
|
|
805
|
+
end
|
|
806
|
+
end
|
|
807
|
+
# Usable but not known to be current: stale until the edge confirms it.
|
|
808
|
+
adopt(restored, etag: p["etag"], checksum: p["checksum"], sig: sig, raw: raw, status: STATUS_STALE, source: :store, transport: :poll)
|
|
809
|
+
rescue StandardError => e
|
|
810
|
+
emit_error(Error.new("Could not read the persisted bundle: #{e.message}", :store))
|
|
811
|
+
end
|
|
812
|
+
|
|
813
|
+
# ------------------------------------------------------------------ test sessions (internals)
|
|
814
|
+
|
|
815
|
+
# @api private
|
|
816
|
+
SessionState = Struct.new(:id, :bundle, :context, :expires_at, :expires_at_ts)
|
|
817
|
+
|
|
818
|
+
def cached_session(key)
|
|
819
|
+
@sessions_mutex.synchronize do
|
|
820
|
+
hit = @sessions[key]
|
|
821
|
+
return nil unless hit
|
|
822
|
+
return hit if Time.now.to_f < hit[1]
|
|
823
|
+
|
|
824
|
+
@sessions.delete(key)
|
|
825
|
+
nil
|
|
826
|
+
end
|
|
827
|
+
end
|
|
828
|
+
|
|
829
|
+
# [state or nil, failed]. nil without failure: no such session (unknown, expired, revoked, service not permitted).
|
|
830
|
+
def fetch_session(token, service)
|
|
831
|
+
extra = { "X-NanoFlags-Session" => token, "Cache-Control" => "no-store", "Accept" => "application/json" }
|
|
832
|
+
extra["X-NanoFlags-Service"] = service if service
|
|
833
|
+
res = begin
|
|
834
|
+
request("GET", "/v1/session", extra)
|
|
835
|
+
rescue StandardError => e
|
|
836
|
+
raise Error.new("Could not load the test session: #{e.message}", :session)
|
|
837
|
+
end
|
|
838
|
+
return [nil, false] if res.status == 404
|
|
839
|
+
raise Error.new("Session request failed with HTTP #{res.status}.", [401, 403].include?(res.status) ? :unauthorized : :session, res.status) unless res.ok?
|
|
840
|
+
|
|
841
|
+
body = begin
|
|
842
|
+
Engine::Json.parse(res.body)
|
|
843
|
+
rescue Engine::InvalidJsonError
|
|
844
|
+
nil
|
|
845
|
+
end
|
|
846
|
+
expires_ts = begin
|
|
847
|
+
body.is_a?(Hash) && body["expires_at"].is_a?(String) ? Time.iso8601(body["expires_at"]).to_f : nil
|
|
848
|
+
rescue ArgumentError
|
|
849
|
+
nil
|
|
850
|
+
end
|
|
851
|
+
raise Error.new("The edge returned an invalid session.", :session) unless body.is_a?(Hash) && body["id"].is_a?(String) && Engine.bundle?(body["bundle"]) && expires_ts
|
|
852
|
+
|
|
853
|
+
bundle = body["bundle"]
|
|
854
|
+
raise engine_error(bundle) unless Engine.supports_engine?(bundle.fetch("engine", Engine::UNDEFINED))
|
|
855
|
+
return [nil, false] if expires_ts <= Time.now.to_f
|
|
856
|
+
|
|
857
|
+
context = body["context"].is_a?(Hash) ? body["context"] : {}
|
|
858
|
+
[SessionState.new(body["id"], bundle, context, Time.at(expires_ts).utc.iso8601(3), expires_ts), false]
|
|
859
|
+
rescue StandardError => e
|
|
860
|
+
emit_error(e.is_a?(Error) ? e : Error.new("Could not load the test session: #{e.message}", :session)) unless @closed
|
|
861
|
+
[nil, true]
|
|
862
|
+
end
|
|
863
|
+
|
|
864
|
+
# ------------------------------------------------------------------ live WebSocket (/v1/live)
|
|
865
|
+
|
|
866
|
+
def live_url
|
|
867
|
+
return @live_url if @live_url && !@live_url.empty?
|
|
868
|
+
|
|
869
|
+
if @base_url.match?(%r{\Ahttps://}i) then "wss://#{@base_url.sub(%r{\Ahttps://}i, "")}/v1/live"
|
|
870
|
+
elsif @base_url.match?(%r{\Ahttp://}i) then "ws://#{@base_url.sub(%r{\Ahttp://}i, "")}/v1/live"
|
|
871
|
+
end
|
|
872
|
+
end
|
|
873
|
+
|
|
874
|
+
def live_wanted?
|
|
875
|
+
@streaming && @live_enabled && !live_url.nil? && @http.respond_to?(:websocket)
|
|
876
|
+
end
|
|
877
|
+
|
|
878
|
+
# Closes the current socket (for a rejected key); the loop reconnects with backoff.
|
|
879
|
+
def drop_live
|
|
880
|
+
ws = @live_socket
|
|
881
|
+
ws&.close(1000, "bye")
|
|
882
|
+
rescue StandardError
|
|
883
|
+
nil
|
|
884
|
+
end
|
|
885
|
+
|
|
886
|
+
# Keeps one live socket open, reconnecting with jittered exponential backoff (1 s · 2ⁿ, at most 5 min, × 0.5–1.5).
|
|
887
|
+
# While no socket can be opened, server-sent events + polling take over.
|
|
888
|
+
def live_loop
|
|
889
|
+
attempt = 0
|
|
890
|
+
current = -> { !@closed && !@environment_deleted && Process.pid == @pid }
|
|
891
|
+
while current.()
|
|
892
|
+
opened = false
|
|
893
|
+
opened_at = 0.0
|
|
894
|
+
rotating = false
|
|
895
|
+
close_code = nil
|
|
896
|
+
ws = nil
|
|
897
|
+
begin
|
|
898
|
+
ws = @http.websocket(live_url, headers, protocols: [LIVE_PROTOCOL], open_timeout: LIVE_CONNECT_TIMEOUT)
|
|
899
|
+
opened = true
|
|
900
|
+
opened_at = monotonic
|
|
901
|
+
rotating = live_session(ws, opened_at)
|
|
902
|
+
rescue WebSocket::Closed => e
|
|
903
|
+
close_code = e.code
|
|
904
|
+
log { "live socket closed: #{e.message}" }
|
|
905
|
+
rescue StandardError => e
|
|
906
|
+
log { "live socket failed: #{e.class}: #{e.message}" }
|
|
907
|
+
ensure
|
|
908
|
+
@live_open = false
|
|
909
|
+
@live_socket = nil
|
|
910
|
+
begin
|
|
911
|
+
ws&.close(1000, rotating ? "rotate" : "bye")
|
|
912
|
+
rescue StandardError
|
|
913
|
+
nil
|
|
914
|
+
end
|
|
915
|
+
end
|
|
916
|
+
return if @closed || Process.pid != @pid
|
|
917
|
+
|
|
918
|
+
if close_code == CLOSE_ENVIRONMENT_DELETED
|
|
919
|
+
# Keep evaluating the last bundle; it can no longer be updated. No socket, no stream; the regular poll stays
|
|
920
|
+
# (it reports the key as rejected, and recovers if the environment turns out to exist after all).
|
|
921
|
+
@environment_deleted = true
|
|
922
|
+
close_stream
|
|
923
|
+
set_status(STATUS_STALE) if @bundle
|
|
924
|
+
emit_error(Error.new("The environment of this SDK key was deleted. The last configuration stays in use; it will not be updated.", :environment_deleted))
|
|
925
|
+
reschedule
|
|
926
|
+
return
|
|
927
|
+
end
|
|
928
|
+
next if rotating # planned replacement: no fallback, no backoff
|
|
929
|
+
|
|
930
|
+
attempt = opened && monotonic - opened_at > LIVE_STABLE ? 1 : attempt + 1
|
|
931
|
+
if opened
|
|
932
|
+
reschedule # back to the normal poll interval
|
|
933
|
+
else
|
|
934
|
+
start_stream # SSE + polling take over until a socket opens again
|
|
935
|
+
end
|
|
936
|
+
wait = [LIVE_MAX_BACKOFF, 2.0**[attempt - 1, 10].min].min * (0.5 + @random.call)
|
|
937
|
+
@mutex.synchronize { @sleep_cv.wait(wait) unless @closed }
|
|
938
|
+
end
|
|
939
|
+
end
|
|
940
|
+
|
|
941
|
+
# Serves one open socket until it closes, dies or is due for rotation. Returns true for a rotation; raises
|
|
942
|
+
# {WebSocket::Closed} when the edge closed it.
|
|
943
|
+
def live_session(ws, opened_at)
|
|
944
|
+
@live_socket = ws
|
|
945
|
+
@live_open = true
|
|
946
|
+
close_stream # SSE is not used while the socket is healthy
|
|
947
|
+
reschedule # the poll becomes a safety net
|
|
948
|
+
rotate_at = opened_at + (LIVE_ROTATE * (0.9 + (0.2 * @random.call)))
|
|
949
|
+
next_ping = opened_at + (LIVE_PING * (0.9 + (0.2 * @random.call)))
|
|
950
|
+
pong_deadline = nil
|
|
951
|
+
until @closed || Process.pid != @pid
|
|
952
|
+
now = monotonic
|
|
953
|
+
return true if now >= rotate_at
|
|
954
|
+
return false if pong_deadline && now >= pong_deadline # silence after a ping: the connection is dead
|
|
955
|
+
|
|
956
|
+
if now >= next_ping
|
|
957
|
+
ws.send_text("ping") # the edge answers "pong" without waking anything up
|
|
958
|
+
pong_deadline ||= now + LIVE_PONG_TIMEOUT
|
|
959
|
+
next_ping = now + (LIVE_PING * (0.9 + (0.2 * @random.call)))
|
|
960
|
+
end
|
|
961
|
+
wait = [next_ping, rotate_at, pong_deadline || rotate_at].min - monotonic
|
|
962
|
+
msg = ws.recv([0.05, wait].max)
|
|
963
|
+
next if msg.nil?
|
|
964
|
+
|
|
965
|
+
pong_deadline = nil
|
|
966
|
+
next if msg == "pong"
|
|
967
|
+
|
|
968
|
+
m = begin
|
|
969
|
+
JSON.parse(msg)
|
|
970
|
+
rescue JSON::ParserError
|
|
971
|
+
nil
|
|
972
|
+
end
|
|
973
|
+
apply_push(m) if m.is_a?(Hash)
|
|
974
|
+
end
|
|
975
|
+
false
|
|
976
|
+
end
|
|
977
|
+
|
|
978
|
+
# Applies one +rev+ / +hello+ message. A message that cannot be trusted changes nothing.
|
|
979
|
+
def apply_push(m)
|
|
980
|
+
return if @closed || !%w[rev hello].include?(m["t"])
|
|
981
|
+
|
|
982
|
+
revision = m["revision"]
|
|
983
|
+
text = m["bundle"]
|
|
984
|
+
revision = revision.to_i if revision.is_a?(Float) && revision.finite? && revision == revision.floor
|
|
985
|
+
return unless revision.is_a?(Integer) && revision >= 1 && text.is_a?(String) # revision 0 / no bundle: nothing published yet
|
|
986
|
+
|
|
987
|
+
cur = @bundle
|
|
988
|
+
return if cur && revision < cur["revision"].to_i # never backwards
|
|
989
|
+
|
|
990
|
+
checksum = m["checksum"].is_a?(String) ? m["checksum"] : nil
|
|
991
|
+
info = nil
|
|
992
|
+
if @verifier
|
|
993
|
+
reject = lambda do |why|
|
|
994
|
+
emit_error(Error.new("Pushed bundle r#{revision} was rejected: #{why} The configuration in use is unchanged.", :signature))
|
|
995
|
+
request_sync # the regular (verified) request path says what is really current
|
|
996
|
+
end
|
|
997
|
+
signature = m["signature"]
|
|
998
|
+
env_id = m["environmentId"]
|
|
999
|
+
return reject.("it carries no complete signature.") unless signature.is_a?(String) && !signature.empty? && env_id.is_a?(String) && !env_id.empty? && checksum
|
|
1000
|
+
return reject.("it was signed for a different environment.") if @pinned_env && @pinned_env != env_id
|
|
1001
|
+
|
|
1002
|
+
kid = m["kid"].is_a?(String) && !m["kid"].empty? ? m["kid"] : nil
|
|
1003
|
+
info = Signature::Info.new(signature, kid, env_id, revision, checksum)
|
|
1004
|
+
ok = begin
|
|
1005
|
+
Signature.verify(load_keys(kid), info, text)
|
|
1006
|
+
rescue StandardError
|
|
1007
|
+
false
|
|
1008
|
+
end
|
|
1009
|
+
return if @closed
|
|
1010
|
+
return reject.("its signature does not verify.") unless ok
|
|
1011
|
+
end
|
|
1012
|
+
parsed = begin
|
|
1013
|
+
Engine::Json.parse(text)
|
|
1014
|
+
rescue Engine::InvalidJsonError
|
|
1015
|
+
nil
|
|
1016
|
+
end
|
|
1017
|
+
unless Engine.bundle?(parsed) && parsed["revision"].is_a?(Float) && parsed["revision"] == revision.to_f
|
|
1018
|
+
return emit_error(Error.new("The edge pushed an invalid bundle; it was ignored.", :invalid_bundle))
|
|
1019
|
+
end
|
|
1020
|
+
return emit_error(engine_error(parsed)) unless Engine.supports_engine?(parsed.fetch("engine", Engine::UNDEFINED))
|
|
1021
|
+
|
|
1022
|
+
confirm = false
|
|
1023
|
+
proceed = @mutex.synchronize do
|
|
1024
|
+
cur = @bundle
|
|
1025
|
+
next false if cur && revision < cur["revision"].to_i
|
|
1026
|
+
|
|
1027
|
+
@failures = 0
|
|
1028
|
+
if cur && revision == cur["revision"].to_i
|
|
1029
|
+
# Already in use: the push only confirms that it is current.
|
|
1030
|
+
confirm = @checksum.nil? || @checksum == checksum
|
|
1031
|
+
next false
|
|
1032
|
+
end
|
|
1033
|
+
@pinned_env = info.environment_id if info
|
|
1034
|
+
@live_revision = revision
|
|
1035
|
+
true
|
|
1036
|
+
end
|
|
1037
|
+
set_status(STATUS_READY) if confirm
|
|
1038
|
+
return unless proceed
|
|
1039
|
+
|
|
1040
|
+
committed = m["committedAt"]
|
|
1041
|
+
latency = committed.is_a?(Numeric) && committed.to_f.finite? ? (Time.now.to_f * 1000) - committed : nil
|
|
1042
|
+
adopt(parsed,
|
|
1043
|
+
# What /v1/bundle would send as ETag for this revision, so the safety poll gets a 304.
|
|
1044
|
+
etag: checksum ? %("#{checksum}-#{@browser_key ? "client" : "server"}") : nil,
|
|
1045
|
+
checksum: checksum, sig: info, raw: text,
|
|
1046
|
+
status: STATUS_READY, source: :network, transport: :live, latency_ms: latency)
|
|
1047
|
+
persist
|
|
1048
|
+
end
|
|
1049
|
+
|
|
1050
|
+
# ------------------------------------------------------------------ event stream (SSE)
|
|
1051
|
+
|
|
1052
|
+
def start_stream
|
|
1053
|
+
gen = @mutex.synchronize do
|
|
1054
|
+
return if @closed || !@streaming || @stream_active || @environment_deleted
|
|
1055
|
+
|
|
1056
|
+
@stream_active = true
|
|
1057
|
+
@stream_gen += 1
|
|
1058
|
+
end
|
|
1059
|
+
@stream_thread = spawn("nanoflags-stream") { stream_loop(gen) }
|
|
1060
|
+
end
|
|
1061
|
+
|
|
1062
|
+
def close_stream
|
|
1063
|
+
closer, thread = @mutex.synchronize do
|
|
1064
|
+
@stream_gen += 1
|
|
1065
|
+
@stream_active = false
|
|
1066
|
+
[@stream_closer, @stream_thread]
|
|
1067
|
+
end
|
|
1068
|
+
begin
|
|
1069
|
+
closer&.call
|
|
1070
|
+
rescue StandardError
|
|
1071
|
+
nil
|
|
1072
|
+
end
|
|
1073
|
+
# A read blocked inside OpenSSL does not always notice the socket closing under it: the thread only reads.
|
|
1074
|
+
thread.kill if thread && thread != Thread.current && !thread.join(0.2)
|
|
1075
|
+
nil
|
|
1076
|
+
end
|
|
1077
|
+
|
|
1078
|
+
def stream_loop(gen)
|
|
1079
|
+
attempt = 0
|
|
1080
|
+
current = -> { !@closed && gen == @stream_gen && Process.pid == @pid }
|
|
1081
|
+
while current.()
|
|
1082
|
+
started = monotonic
|
|
1083
|
+
stop = false
|
|
1084
|
+
begin
|
|
1085
|
+
status = @http.stream("#{@base_url}/v1/stream", headers("Accept" => "text/event-stream"),
|
|
1086
|
+
open_timeout: @request_timeout, read_timeout: @stream_read_timeout,
|
|
1087
|
+
on_open: ->(closer) { @stream_closer = closer }) do |event, data|
|
|
1088
|
+
next :stop unless current.()
|
|
1089
|
+
|
|
1090
|
+
@stream_open = true
|
|
1091
|
+
case event
|
|
1092
|
+
when "revision" then on_revision(data)
|
|
1093
|
+
when "revoked"
|
|
1094
|
+
stop = true
|
|
1095
|
+
request_sync
|
|
1096
|
+
next :stop
|
|
1097
|
+
end
|
|
1098
|
+
nil
|
|
1099
|
+
end
|
|
1100
|
+
stop = true if [401, 403].include?(status) # polling keeps reporting the error
|
|
1101
|
+
rescue StandardError => e
|
|
1102
|
+
log { "stream failed: #{e.class}: #{e.message}" }
|
|
1103
|
+
ensure
|
|
1104
|
+
@stream_open = false
|
|
1105
|
+
@stream_closer = nil
|
|
1106
|
+
end
|
|
1107
|
+
return unless current.()
|
|
1108
|
+
|
|
1109
|
+
if stop
|
|
1110
|
+
@mutex.synchronize { @stream_active = false if gen == @stream_gen }
|
|
1111
|
+
return
|
|
1112
|
+
end
|
|
1113
|
+
attempt = monotonic - started > 30 ? 0 : attempt + 1
|
|
1114
|
+
wait = [30.0, 2.0**[attempt, 5].min].min * (0.5 + @random.call)
|
|
1115
|
+
@mutex.synchronize { @sleep_cv.wait(wait) unless @closed }
|
|
1116
|
+
end
|
|
1117
|
+
end
|
|
1118
|
+
|
|
1119
|
+
def on_revision(data)
|
|
1120
|
+
m = JSON.parse(data)
|
|
1121
|
+
return unless m.is_a?(Hash)
|
|
1122
|
+
|
|
1123
|
+
b = @bundle
|
|
1124
|
+
return unless b.nil? || m["revision"] != b["revision"].to_i || m["checksum"] != @checksum || @status != STATUS_READY
|
|
1125
|
+
|
|
1126
|
+
@stream_triggered = true
|
|
1127
|
+
request_sync
|
|
1128
|
+
rescue JSON::ParserError
|
|
1129
|
+
nil
|
|
1130
|
+
end
|
|
1131
|
+
|
|
1132
|
+
# ------------------------------------------------------------------ telemetry
|
|
1133
|
+
|
|
1134
|
+
def attrs_used_by(bundle, flag_key)
|
|
1135
|
+
return [] if bundle.nil?
|
|
1136
|
+
|
|
1137
|
+
unless @attrs_for.equal?(bundle)
|
|
1138
|
+
@attrs = {}
|
|
1139
|
+
@attrs_for = bundle
|
|
1140
|
+
end
|
|
1141
|
+
@attrs[flag_key] ||= Engine.attributes_used_by(bundle, flag_key)
|
|
1142
|
+
end
|
|
1143
|
+
|
|
1144
|
+
def record(r, user_context, ctx, bundle, session_id = nil)
|
|
1145
|
+
return if !@events_enabled || @closed || @sample_rate <= 0 || @random.call >= @sample_rate
|
|
1146
|
+
|
|
1147
|
+
context =
|
|
1148
|
+
if @redact
|
|
1149
|
+
c = Engine::Js.from_ruby(@redact.call(user_context.is_a?(Hash) ? user_context.dup : Engine::Js.to_ruby(ctx)))
|
|
1150
|
+
c.is_a?(Hash) ? c : {}
|
|
1151
|
+
else
|
|
1152
|
+
# No attribute values: only the names the flag's rules use that are present, with the value's type.
|
|
1153
|
+
attrs_used_by(bundle, r.flag_key).each_with_object({}) do |name, h|
|
|
1154
|
+
v = ctx.fetch(name, Engine::UNDEFINED)
|
|
1155
|
+
h[name] = Engine::Js.type_name(v) unless v.equal?(Engine::UNDEFINED)
|
|
1156
|
+
end
|
|
1157
|
+
end
|
|
1158
|
+
rev = Engine::Js.to_number(r.revision)
|
|
1159
|
+
ev = { "flagKey" => truncate(r.flag_key, 63), "value" => event_value(r.value), "reason" => r.reason }
|
|
1160
|
+
ev["ruleIndex"] = r.rule_index.to_f unless r.rule_index.nil?
|
|
1161
|
+
ev["revision"] = rev.finite? ? rev.to_i.to_f : 0.0
|
|
1162
|
+
ev["context"] = context
|
|
1163
|
+
ev["at"] = Time.now.utc.strftime("%Y-%m-%dT%H:%M:%S.%LZ")
|
|
1164
|
+
ev["sessionId"] = session_id unless session_id.nil?
|
|
1165
|
+
ev["sampleRate"] = @sample_rate
|
|
1166
|
+
text = Engine::Js.stringify(ev)
|
|
1167
|
+
@queue_mutex.synchronize { @queue << text if @queue.length < MAX_QUEUE } # bounded: drop instead of growing
|
|
1168
|
+
rescue StandardError
|
|
1169
|
+
nil # telemetry must never affect evaluation
|
|
1170
|
+
end
|
|
1171
|
+
|
|
1172
|
+
def event_value(v)
|
|
1173
|
+
return truncate(v, MAX_EVENT_VALUE_CHARS) if v.is_a?(String)
|
|
1174
|
+
|
|
1175
|
+
text = Engine::Js.stringify(v)
|
|
1176
|
+
return nil if text.nil? || ((v.is_a?(Array) || v.is_a?(Hash)) && Engine::Js.utf16_length(text) > MAX_EVENT_VALUE_CHARS)
|
|
1177
|
+
|
|
1178
|
+
v
|
|
1179
|
+
end
|
|
1180
|
+
|
|
1181
|
+
def truncate(s, n)
|
|
1182
|
+
return s if s.bytesize <= n || Engine::Js.utf16_length(s) <= n
|
|
1183
|
+
|
|
1184
|
+
Engine::Js.units_to_string(Engine::Js.to_units(s).first(n))
|
|
1185
|
+
end
|
|
1186
|
+
|
|
1187
|
+
public
|
|
1188
|
+
|
|
1189
|
+
# Sends queued telemetry and the service report now (blocking, best effort, never raises).
|
|
1190
|
+
def flush(timeout: @request_timeout)
|
|
1191
|
+
return unless @events_enabled
|
|
1192
|
+
|
|
1193
|
+
batch = @queue_mutex.synchronize { @queue.shift(MAX_BATCH) }
|
|
1194
|
+
@last_report = monotonic
|
|
1195
|
+
rev = revision || 0
|
|
1196
|
+
body = %({"service":#{Engine::Js.quote(truncate(@service, 60))},"sdk":"ruby/#{VERSION}","revision":#{[rev, 0].max},"events":[#{batch.join(",")}]})
|
|
1197
|
+
request("POST", "/v1/events", { "Content-Type" => "application/json" }, body, timeout)
|
|
1198
|
+
nil
|
|
1199
|
+
rescue StandardError
|
|
1200
|
+
nil # dropped on failure, by design: telemetry is never retried
|
|
1201
|
+
end
|
|
1202
|
+
|
|
1203
|
+
def inspect
|
|
1204
|
+
"#<NanoFlags::Client base_url=#{@base_url.inspect} status=#{@status.inspect} revision=#{revision.inspect} transport=#{transport.inspect}>"
|
|
1205
|
+
end
|
|
1206
|
+
|
|
1207
|
+
private
|
|
1208
|
+
|
|
1209
|
+
def events_loop
|
|
1210
|
+
loop do
|
|
1211
|
+
@mutex.synchronize do
|
|
1212
|
+
return if @closed
|
|
1213
|
+
|
|
1214
|
+
@sleep_cv.wait(@flush_interval)
|
|
1215
|
+
return if @closed
|
|
1216
|
+
end
|
|
1217
|
+
empty = @queue_mutex.synchronize { @queue.empty? }
|
|
1218
|
+
# Nothing queued: the service report alone goes out once per report interval.
|
|
1219
|
+
next if empty && monotonic - @last_report < @report_interval
|
|
1220
|
+
|
|
1221
|
+
flush
|
|
1222
|
+
end
|
|
1223
|
+
end
|
|
1224
|
+
end
|
|
1225
|
+
end
|