-
Notifications
You must be signed in to change notification settings - Fork 12
/
growthbook.py
1664 lines (1418 loc) · 57 KB
/
growthbook.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
This is the Python client library for GrowthBook, the open-source
feature flagging and A/B testing platform.
More info at https://www.growthbook.io
"""
import re
import sys
import json
from abc import ABC, abstractmethod
import logging
from typing import Optional, Any, Set, Tuple, List, Dict
# Only require typing_extensions if using Python 3.7 or earlier
if sys.version_info >= (3, 8):
from typing import TypedDict
else:
from typing_extensions import TypedDict
from urllib.parse import urlparse, parse_qs
from base64 import b64decode
from time import time
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from urllib3 import PoolManager
logger = logging.getLogger("growthbook")
def fnv1a32(str: str) -> int:
hval = 0x811C9DC5
prime = 0x01000193
uint32_max = 2 ** 32
for s in str:
hval = hval ^ ord(s)
hval = (hval * prime) % uint32_max
return hval
def gbhash(seed: str, value: str, version: int) -> Optional[float]:
if version == 2:
n = fnv1a32(str(fnv1a32(seed + value)))
return (n % 10000) / 10000
if version == 1:
n = fnv1a32(value + seed)
return (n % 1000) / 1000
return None
def inRange(n: float, range: Tuple[float, float]) -> bool:
return range[0] <= n < range[1]
def inNamespace(userId: str, namespace: Tuple[str, float, float]) -> bool:
n = gbhash("__" + namespace[0], userId, 1)
if n is None:
return False
return namespace[1] <= n < namespace[2]
def getEqualWeights(numVariations: int) -> List[float]:
if numVariations < 1:
return []
return [1 / numVariations for _ in range(numVariations)]
def getBucketRanges(
numVariations: int, coverage: float = 1, weights: List[float] = None
) -> List[Tuple[float, float]]:
if coverage < 0:
coverage = 0
if coverage > 1:
coverage = 1
if weights is None:
weights = getEqualWeights(numVariations)
if len(weights) != numVariations:
weights = getEqualWeights(numVariations)
if sum(weights) < 0.99 or sum(weights) > 1.01:
weights = getEqualWeights(numVariations)
cumulative: float = 0
ranges = []
for w in weights:
start = cumulative
cumulative += w
ranges.append((start, start + coverage * w))
return ranges
def chooseVariation(n: float, ranges: List[Tuple[float, float]]) -> int:
for i, r in enumerate(ranges):
if inRange(n, r):
return i
return -1
def getQueryStringOverride(id: str, url: str, numVariations: int) -> Optional[int]:
res = urlparse(url)
if not res.query:
return None
qs = parse_qs(res.query)
if id not in qs:
return None
variation = qs[id][0]
if variation is None or not variation.isdigit():
return None
varId = int(variation)
if varId < 0 or varId >= numVariations:
return None
return varId
def decrypt(encrypted_str: str, key_str: str) -> str:
iv_str, ct_str = encrypted_str.split(".", 2)
key = b64decode(key_str)
iv = b64decode(iv_str)
ct = b64decode(ct_str)
cipher = Cipher(algorithms.AES128(key), modes.CBC(iv))
decryptor = cipher.decryptor()
decrypted = decryptor.update(ct) + decryptor.finalize()
unpadder = padding.PKCS7(128).unpadder()
bytestring = unpadder.update(decrypted) + unpadder.finalize()
return bytestring.decode("utf-8")
def paddedVersionString(input) -> str:
# If input is a number, convert to a string
if type(input) is int or type(input) is float:
input = str(input)
if not input or type(input) is not str:
input = "0"
# Remove build info and leading `v` if any
input = re.sub(r"(^v|\+.*$)", "", input)
# Split version into parts (both core version numbers and pre-release tags)
# "v1.2.3-rc.1+build123" -> ["1","2","3","rc","1"]
parts = re.split(r"[-.]", input)
# If it's SemVer without a pre-release, add `~` to the end
# ["1","0","0"] -> ["1","0","0","~"]
# "~" is the largest ASCII character, so this will make "1.0.0" greater than "1.0.0-beta" for example
if len(parts) == 3:
parts.append("~")
# Left pad each numeric part with spaces so string comparisons will work ("9">"10", but " 9"<"10")
# Then, join back together into a single string
return "-".join([v.rjust(5, " ") if re.match(r"^[0-9]+$", v) else v for v in parts])
def isIn(conditionValue, attributeValue) -> bool:
if type(attributeValue) is list:
return bool(set(conditionValue) & set(attributeValue))
return attributeValue in conditionValue
def evalCondition(attributes: dict, condition: dict) -> bool:
if "$or" in condition:
return evalOr(attributes, condition["$or"])
if "$nor" in condition:
return not evalOr(attributes, condition["$nor"])
if "$and" in condition:
return evalAnd(attributes, condition["$and"])
if "$not" in condition:
return not evalCondition(attributes, condition["$not"])
for key, value in condition.items():
if not evalConditionValue(value, getPath(attributes, key)):
return False
return True
def evalOr(attributes, conditions) -> bool:
if len(conditions) == 0:
return True
for condition in conditions:
if evalCondition(attributes, condition):
return True
return False
def evalAnd(attributes, conditions) -> bool:
for condition in conditions:
if not evalCondition(attributes, condition):
return False
return True
def isOperatorObject(obj) -> bool:
for key in obj.keys():
if key[0] != "$":
return False
return True
def getType(attributeValue) -> str:
t = type(attributeValue)
if attributeValue is None:
return "null"
if t is int or t is float:
return "number"
if t is str:
return "string"
if t is list or t is set:
return "array"
if t is dict:
return "object"
if t is bool:
return "boolean"
return "unknown"
def getPath(attributes, path):
current = attributes
for segment in path.split("."):
if type(current) is dict and segment in current:
current = current[segment]
else:
return None
return current
def evalConditionValue(conditionValue, attributeValue) -> bool:
if type(conditionValue) is dict and isOperatorObject(conditionValue):
for key, value in conditionValue.items():
if not evalOperatorCondition(key, attributeValue, value):
return False
return True
return conditionValue == attributeValue
def elemMatch(condition, attributeValue) -> bool:
if not type(attributeValue) is list:
return False
for item in attributeValue:
if isOperatorObject(condition):
if evalConditionValue(condition, item):
return True
else:
if evalCondition(item, condition):
return True
return False
def compare(val1, val2) -> int:
if (type(val1) is int or type(val1) is float) and not (type(val2) is int or type(val2) is float):
if (val2 is None):
val2 = 0
else:
val2 = float(val2)
if (type(val2) is int or type(val2) is float) and not (type(val1) is int or type(val1) is float):
if (val1 is None):
val1 = 0
else:
val1 = float(val1)
if val1 > val2:
return 1
if val1 < val2:
return -1
return 0
def evalOperatorCondition(operator, attributeValue, conditionValue) -> bool:
if operator == "$eq":
try:
return compare(attributeValue, conditionValue) == 0
except Exception:
return False
elif operator == "$ne":
try:
return compare(attributeValue, conditionValue) != 0
except Exception:
return False
elif operator == "$lt":
try:
return compare(attributeValue, conditionValue) < 0
except Exception:
return False
elif operator == "$lte":
try:
return compare(attributeValue, conditionValue) <= 0
except Exception:
return False
elif operator == "$gt":
try:
return compare(attributeValue, conditionValue) > 0
except Exception:
return False
elif operator == "$gte":
try:
return compare(attributeValue, conditionValue) >= 0
except Exception:
return False
elif operator == "$veq":
return paddedVersionString(attributeValue) == paddedVersionString(conditionValue)
elif operator == "$vne":
return paddedVersionString(attributeValue) != paddedVersionString(conditionValue)
elif operator == "$vlt":
return paddedVersionString(attributeValue) < paddedVersionString(conditionValue)
elif operator == "$vlte":
return paddedVersionString(attributeValue) <= paddedVersionString(conditionValue)
elif operator == "$vgt":
return paddedVersionString(attributeValue) > paddedVersionString(conditionValue)
elif operator == "$vgte":
return paddedVersionString(attributeValue) >= paddedVersionString(conditionValue)
elif operator == "$regex":
try:
r = re.compile(conditionValue)
return bool(r.search(attributeValue))
except Exception:
return False
elif operator == "$in":
if not type(conditionValue) is list:
return False
return isIn(conditionValue, attributeValue)
elif operator == "$nin":
if not type(conditionValue) is list:
return False
return not isIn(conditionValue, attributeValue)
elif operator == "$elemMatch":
return elemMatch(conditionValue, attributeValue)
elif operator == "$size":
if not (type(attributeValue) is list):
return False
return evalConditionValue(conditionValue, len(attributeValue))
elif operator == "$all":
if not (type(attributeValue) is list):
return False
for cond in conditionValue:
passing = False
for attr in attributeValue:
if evalConditionValue(cond, attr):
passing = True
if not passing:
return False
return True
elif operator == "$exists":
if not conditionValue:
return attributeValue is None
return attributeValue is not None
elif operator == "$type":
return getType(attributeValue) == conditionValue
elif operator == "$not":
return not evalConditionValue(conditionValue, attributeValue)
return False
class VariationMeta(TypedDict):
key: str
name: str
passthrough: bool
class Filter(TypedDict):
seed: str
ranges: List[Tuple[float, float]]
hashVersion: int
attribute: str
class Experiment(object):
def __init__(
self,
key: str,
variations: list,
weights: List[float] = None,
active: bool = True,
status: str = "running",
coverage: int = None,
condition: dict = None,
namespace: Tuple[str, float, float] = None,
url: str = "",
include=None,
groups: list = None,
force: int = None,
hashAttribute: str = "id",
fallbackAttribute: str = None,
hashVersion: int = None,
ranges: List[Tuple[float, float]] = None,
meta: List[VariationMeta] = None,
filters: List[Filter] = None,
seed: str = None,
name: str = None,
phase: str = None,
disableStickyBucketing: bool = False,
bucketVersion: int = None,
minBucketVersion: int = None,
parentConditions: List[dict] = None,
) -> None:
self.key = key
self.variations = variations
self.weights = weights
self.active = active
self.coverage = coverage
self.condition = condition
self.namespace = namespace
self.force = force
self.hashAttribute = hashAttribute
self.hashVersion = hashVersion or 1
self.ranges = ranges
self.meta = meta
self.filters = filters
self.seed = seed
self.name = name
self.phase = phase
self.disableStickyBucketing = disableStickyBucketing
self.bucketVersion = bucketVersion or 0
self.minBucketVersion = minBucketVersion or 0
self.parentConditions = parentConditions
self.fallbackAttribute = None
if not self.disableStickyBucketing:
self.fallbackAttribute = fallbackAttribute
# Deprecated properties
self.status = status
self.url = url
self.include = include
self.groups = groups
def to_dict(self):
obj = {
"key": self.key,
"variations": self.variations,
"weights": self.weights,
"active": self.active,
"coverage": self.coverage or 1,
"condition": self.condition,
"namespace": self.namespace,
"force": self.force,
"hashAttribute": self.hashAttribute,
"hashVersion": self.hashVersion,
"ranges": self.ranges,
"meta": self.meta,
"filters": self.filters,
"seed": self.seed,
"name": self.name,
"phase": self.phase,
}
if self.fallbackAttribute:
obj["fallbackAttribute"] = self.fallbackAttribute
if self.disableStickyBucketing:
obj["disableStickyBucketing"] = True
if self.bucketVersion:
obj["bucketVersion"] = self.bucketVersion
if self.minBucketVersion:
obj["minBucketVersion"] = self.minBucketVersion
if self.parentConditions:
obj["parentConditions"] = self.parentConditions
return obj
def update(self, data: dict) -> None:
weights = data.get("weights", None)
status = data.get("status", None)
coverage = data.get("coverage", None)
url = data.get("url", None)
groups = data.get("groups", None)
force = data.get("force", None)
if weights is not None:
self.weights = weights
if status is not None:
self.status = status
if coverage is not None:
self.coverage = coverage
if url is not None:
self.url = url
if groups is not None:
self.groups = groups
if force is not None:
self.force = force
class Result(object):
def __init__(
self,
variationId: int,
inExperiment: bool,
value,
hashUsed: bool,
hashAttribute: str,
hashValue: str,
featureId: Optional[str],
meta: VariationMeta = None,
bucket: float = None,
stickyBucketUsed: bool = False,
) -> None:
self.variationId = variationId
self.inExperiment = inExperiment
self.value = value
self.hashUsed = hashUsed
self.hashAttribute = hashAttribute
self.hashValue = hashValue
self.featureId = featureId or None
self.bucket = bucket
self.stickyBucketUsed = stickyBucketUsed
self.key = str(variationId)
self.name = ""
self.passthrough = False
if meta:
if "name" in meta:
self.name = meta["name"]
if "key" in meta:
self.key = meta["key"]
if "passthrough" in meta:
self.passthrough = meta["passthrough"]
def to_dict(self) -> dict:
obj = {
"featureId": self.featureId,
"variationId": self.variationId,
"inExperiment": self.inExperiment,
"value": self.value,
"hashUsed": self.hashUsed,
"hashAttribute": self.hashAttribute,
"hashValue": self.hashValue,
"key": self.key,
"stickyBucketUsed": self.stickyBucketUsed,
}
if self.bucket is not None:
obj["bucket"] = self.bucket
if self.name:
obj["name"] = self.name
if self.passthrough:
obj["passthrough"] = True
return obj
class Feature(object):
def __init__(self, defaultValue=None, rules: list = []) -> None:
self.defaultValue = defaultValue
self.rules: List[FeatureRule] = []
for rule in rules:
if isinstance(rule, FeatureRule):
self.rules.append(rule)
else:
self.rules.append(FeatureRule(
id=rule.get("id", None),
key=rule.get("key", ""),
variations=rule.get("variations", None),
weights=rule.get("weights", None),
coverage=rule.get("coverage", None),
condition=rule.get("condition", None),
namespace=rule.get("namespace", None),
force=rule.get("force", None),
hashAttribute=rule.get("hashAttribute", "id"),
fallbackAttribute=rule.get("fallbackAttribute", None),
hashVersion=rule.get("hashVersion", None),
range=rule.get("range", None),
ranges=rule.get("ranges", None),
meta=rule.get("meta", None),
filters=rule.get("filters", None),
seed=rule.get("seed", None),
name=rule.get("name", None),
phase=rule.get("phase", None),
disableStickyBucketing=rule.get("disableStickyBucketing", False),
bucketVersion=rule.get("bucketVersion", None),
minBucketVersion=rule.get("minBucketVersion", None),
parentConditions=rule.get("parentConditions", None),
))
def to_dict(self) -> dict:
return {
"defaultValue": self.defaultValue,
"rules": [rule.to_dict() for rule in self.rules],
}
class FeatureRule(object):
def __init__(
self,
id: str = None,
key: str = "",
variations: list = None,
weights: List[float] = None,
coverage: int = None,
condition: dict = None,
namespace: Tuple[str, float, float] = None,
force=None,
hashAttribute: str = "id",
fallbackAttribute: str = None,
hashVersion: int = None,
range: Tuple[float, float] = None,
ranges: List[Tuple[float, float]] = None,
meta: List[VariationMeta] = None,
filters: List[Filter] = None,
seed: str = None,
name: str = None,
phase: str = None,
disableStickyBucketing: bool = False,
bucketVersion: int = None,
minBucketVersion: int = None,
parentConditions: List[dict] = None,
) -> None:
if disableStickyBucketing:
fallbackAttribute = None
self.id = id
self.key = key
self.variations = variations
self.weights = weights
self.coverage = coverage
self.condition = condition
self.namespace = namespace
self.force = force
self.hashAttribute = hashAttribute
self.fallbackAttribute = fallbackAttribute
self.hashVersion = hashVersion or 1
self.range = range
self.ranges = ranges
self.meta = meta
self.filters = filters
self.seed = seed
self.name = name
self.phase = phase
self.disableStickyBucketing = disableStickyBucketing
self.bucketVersion = bucketVersion or 0
self.minBucketVersion = minBucketVersion or 0
self.parentConditions = parentConditions
def to_dict(self) -> dict:
data: Dict[str, Any] = {}
if self.id:
data["id"] = self.id
if self.key:
data["key"] = self.key
if self.variations is not None:
data["variations"] = self.variations
if self.weights is not None:
data["weights"] = self.weights
if self.coverage and self.coverage != 1:
data["coverage"] = self.coverage
if self.condition is not None:
data["condition"] = self.condition
if self.namespace is not None:
data["namespace"] = self.namespace
if self.force is not None:
data["force"] = self.force
if self.hashAttribute != "id":
data["hashAttribute"] = self.hashAttribute
if self.hashVersion:
data["hashVersion"] = self.hashVersion
if self.range is not None:
data["range"] = self.range
if self.ranges is not None:
data["ranges"] = self.ranges
if self.meta is not None:
data["meta"] = self.meta
if self.filters is not None:
data["filters"] = self.filters
if self.seed is not None:
data["seed"] = self.seed
if self.name is not None:
data["name"] = self.name
if self.phase is not None:
data["phase"] = self.phase
if self.fallbackAttribute:
data["fallbackAttribute"] = self.fallbackAttribute
if self.disableStickyBucketing:
data["disableStickyBucketing"] = True
if self.bucketVersion:
data["bucketVersion"] = self.bucketVersion
if self.minBucketVersion:
data["minBucketVersion"] = self.minBucketVersion
if self.parentConditions:
data["parentConditions"] = self.parentConditions
return data
class FeatureResult(object):
def __init__(
self,
value,
source: str,
experiment: Experiment = None,
experimentResult: Result = None,
ruleId: str = None,
) -> None:
self.value = value
self.source = source
self.ruleId = ruleId
self.experiment = experiment
self.experimentResult = experimentResult
self.on = bool(value)
self.off = not bool(value)
def to_dict(self) -> dict:
data = {
"value": self.value,
"source": self.source,
"on": self.on,
"off": self.off,
}
if self.ruleId:
data["ruleId"] = self.ruleId
if self.experiment:
data["experiment"] = self.experiment.to_dict()
if self.experimentResult:
data["experimentResult"] = self.experimentResult.to_dict()
return data
class AbstractFeatureCache(ABC):
@abstractmethod
def get(self, key: str) -> Optional[Dict]:
pass
@abstractmethod
def set(self, key: str, value: Dict, ttl: int) -> None:
pass
def clear(self) -> None:
pass
class CacheEntry(object):
def __init__(self, value: Dict, ttl: int) -> None:
self.value = value
self.ttl = ttl
self.expires = time() + ttl
def update(self, value: Dict):
self.value = value
self.expires = time() + self.ttl
class InMemoryFeatureCache(AbstractFeatureCache):
def __init__(self) -> None:
self.cache: Dict[str, CacheEntry] = {}
def get(self, key: str) -> Optional[Dict]:
if key in self.cache:
entry = self.cache[key]
if entry.expires >= time():
return entry.value
return None
def set(self, key: str, value: Dict, ttl: int) -> None:
if key in self.cache:
self.cache[key].update(value)
self.cache[key] = CacheEntry(value, ttl)
def clear(self) -> None:
self.cache.clear()
class AbstractStickyBucketService(ABC):
@abstractmethod
def get_assignments(self, attributeName: str, attributeValue: str) -> Optional[Dict]:
pass
@abstractmethod
def save_assignments(self, doc: Dict) -> None:
pass
def get_key(self, attributeName: str, attributeValue: str) -> str:
return f"{attributeName}||{attributeValue}"
# By default, just loop through all attributes and call get_assignments
# Override this method in subclasses to perform a multi-query instead
def get_all_assignments(self, attributes: Dict[str, str]) -> Dict[str, Dict]:
docs = {}
for attributeName, attributeValue in attributes.items():
doc = self.get_assignments(attributeName, attributeValue)
if doc:
docs[self.get_key(attributeName, attributeValue)] = doc
return docs
class InMemoryStickyBucketService(AbstractStickyBucketService):
def __init__(self) -> None:
self.docs: Dict[str, Dict] = {}
def get_assignments(self, attributeName: str, attributeValue: str) -> Optional[Dict]:
return self.docs.get(self.get_key(attributeName, attributeValue), None)
def save_assignments(self, doc: Dict) -> None:
self.docs[self.get_key(doc["attributeName"], doc["attributeValue"])] = doc
def destroy(self) -> None:
self.docs.clear()
class FeatureRepository(object):
def __init__(self) -> None:
self.cache: AbstractFeatureCache = InMemoryFeatureCache()
self.http: Optional[PoolManager] = None
def set_cache(self, cache: AbstractFeatureCache) -> None:
self.cache = cache
def clear_cache(self):
self.cache.clear()
# Loads features with an in-memory cache in front
def load_features(
self, api_host: str, client_key: str, decryption_key: str = "", ttl: int = 60
) -> Optional[Dict]:
key = api_host + "::" + client_key
cached = self.cache.get(key)
if not cached:
res = self._fetch_features(api_host, client_key, decryption_key)
if res is not None:
self.cache.set(key, res, ttl)
logger.debug("Fetched features from API, stored in cache")
return res
return cached
# Perform the GET request (separate method for easy mocking)
def _get(self, url: str):
self.http = self.http or PoolManager()
return self.http.request("GET", url)
def _fetch_and_decode(self, api_host: str, client_key: str) -> Optional[Dict]:
try:
r = self._get(self._get_features_url(api_host, client_key))
if r.status >= 400:
logger.warning(
"Failed to fetch features, received status code %d", r.status
)
return None
decoded = json.loads(r.data.decode("utf-8"))
return decoded
except Exception:
logger.warning("Failed to decode feature JSON from GrowthBook API")
return None
# Fetch features from the GrowthBook API
def _fetch_features(
self, api_host: str, client_key: str, decryption_key: str = ""
) -> Optional[Dict]:
decoded = self._fetch_and_decode(api_host, client_key)
if not decoded:
return None
if "encryptedFeatures" in decoded:
if not decryption_key:
raise ValueError("Must specify decryption_key")
try:
decrypted = decrypt(decoded["encryptedFeatures"], decryption_key)
return json.loads(decrypted)
except Exception:
logger.warning(
"Failed to decrypt features from GrowthBook API response"
)
return None
elif "features" in decoded:
return decoded["features"]
else:
logger.warning("GrowthBook API response missing features")
return None
@staticmethod
def _get_features_url(api_host: str, client_key: str) -> str:
api_host = (api_host or "https://cdn.growthbook.io").rstrip("/")
return api_host + "/api/features/" + client_key
# Singleton instance
feature_repo = FeatureRepository()
class GrowthBook(object):
def __init__(
self,
enabled: bool = True,
attributes: dict = {},
url: str = "",
features: dict = {},
qa_mode: bool = False,
on_experiment_viewed=None,
api_host: str = "",
client_key: str = "",
decryption_key: str = "",
cache_ttl: int = 60,
forced_variations: dict = {},
sticky_bucket_service: AbstractStickyBucketService = None,
sticky_bucket_identifier_attributes: List[str] = None,
# Deprecated args
trackingCallback=None,
qaMode: bool = False,
user: dict = {},
groups: dict = {},
overrides: dict = {},
forcedVariations: dict = {},
):
self._enabled = enabled
self._attributes = attributes
self._url = url
self._features: Dict[str, Feature] = {}
self._api_host = api_host
self._client_key = client_key
self._decryption_key = decryption_key
self._cache_ttl = cache_ttl
self.sticky_bucket_identifier_attributes = sticky_bucket_identifier_attributes
self.sticky_bucket_service = sticky_bucket_service
self._sticky_bucket_assignment_docs: dict = {}
self._using_derived_sticky_bucket_attributes = not sticky_bucket_identifier_attributes
self._sticky_bucket_attributes: Optional[dict] = None
self._qaMode = qa_mode or qaMode
self._trackingCallback = on_experiment_viewed or trackingCallback
# Deprecated args
self._user = user
self._groups = groups
self._overrides = overrides
self._forcedVariations = forced_variations or forcedVariations
self._tracked: Dict[str, Any] = {}
self._assigned: Dict[str, Any] = {}
self._subscriptions: Set[Any] = set()
if features:
self.setFeatures(features)
def load_features(self) -> None:
if not self._client_key:
raise ValueError("Must specify `client_key` to refresh features")
features = feature_repo.load_features(
self._api_host, self._client_key, self._decryption_key, self._cache_ttl
)
if features is not None:
self.setFeatures(features)
# @deprecated, use set_features
def setFeatures(self, features: dict) -> None:
return self.set_features(features)
def set_features(self, features: dict) -> None:
self._features = {}
for key, feature in features.items():
if isinstance(feature, Feature):
self._features[key] = feature
else:
self._features[key] = Feature(
rules=feature.get("rules", []),
defaultValue=feature.get("defaultValue", None),
)
self.refresh_sticky_buckets()
# @deprecated, use get_features
def getFeatures(self) -> Dict[str, Feature]:
return self.get_features()
def get_features(self) -> Dict[str, Feature]:
return self._features
# @deprecated, use set_attributes
def setAttributes(self, attributes: dict) -> None:
return self.set_attributes(attributes)
def set_attributes(self, attributes: dict) -> None:
self._attributes = attributes
self.refresh_sticky_buckets()
# @deprecated, use get_attributes
def getAttributes(self) -> dict:
return self.get_attributes()
def get_attributes(self) -> dict:
return self._attributes
def destroy(self) -> None:
self._subscriptions.clear()
self._tracked.clear()
self._assigned.clear()
self._trackingCallback = None
self._forcedVariations.clear()
self._overrides.clear()
self._groups.clear()
self._attributes.clear()
self._features.clear()
# @deprecated, use is_on
def isOn(self, key: str) -> bool: