-
Notifications
You must be signed in to change notification settings - Fork 7
/
proclaim.py
79 lines (59 loc) · 2.4 KB
/
proclaim.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
class Proclaim(object):
def __init__(self, redis):
self.redis = redis
self.groups = { "all": [] }
def activate_group(self, feature, group):
if group in self.groups:
self.redis.sadd(_group_key(feature), group)
def deactivate_group(self, feature, group):
self.redis.srem(_group_key(feature), group)
def deactivate_all(self, feature):
self.redis.delete(_group_key(feature))
self.redis.delete(_user_key(feature))
self.redis.delete(_percentage_key(feature))
def activate_user(self, feature, user):
self.redis.sadd(_user_key(feature), user.id)
def deactivate_user(self, feature, user):
self.redis.srem(_user_key(feature), user.id)
def define_group(self, group, *users):
self.groups[group] = []
for user in users:
self.groups[group].append(user.id)
def is_active(self, feature, user):
if self._user_in_active_group(feature, user):
return True
if self._user_active(feature, user):
return True
if self._user_within_active_percentage(feature, user):
return True
return False
def activate_percentage(self, feature, percentage):
self.redis.set(_percentage_key(feature), percentage)
def deactivate_percentage(self, feature, percentage):
self.redis.delete(_percentage_key(feature), percentage)
def _user_in_active_group(self, feature, user):
if self.redis.exists(_group_key(feature)):
active_groups = self.redis.smembers(_group_key(feature))
if active_groups:
for grp in active_groups:
if user.id in self.groups[grp]:
return True
return False
def _user_active(self, feature, user):
if self.redis.sismember(_user_key(feature), user.id):
return True
return False
def _user_within_active_percentage(self, feature, user):
if self.redis.exists(_percentage_key(feature)):
percentage = self.redis.get(_percentage_key(feature))
if int(user.id) % 10 < int(percentage) / 10:
return True
return False
def _key(name):
return "feature:%s" % name
def _group_key(name):
return "%s:groups" % (_key(name))
def _user_key(name):
return "%s:users" % (_key(name))
def _percentage_key(name):
return "%s:percentage" % (_key(name))