|
| 1 | +import hashlib |
| 2 | + |
| 3 | + |
| 4 | +class BaseDialup(object): |
| 5 | + """BaseDialup class to provide an interface for all dialup classes""" |
| 6 | + |
| 7 | + def __init__(self, region_config, **kwargs): |
| 8 | + self.region_config = region_config |
| 9 | + |
| 10 | + def is_enabled(self): |
| 11 | + """ |
| 12 | + Returns a bool on whether this dialup is enabled or not |
| 13 | + """ |
| 14 | + raise NotImplementedError |
| 15 | + |
| 16 | + def __str__(self): |
| 17 | + return self.__class__.__name__ |
| 18 | + |
| 19 | + |
| 20 | +class DisabledDialup(BaseDialup): |
| 21 | + """ |
| 22 | + A dialup that is never enabled |
| 23 | + """ |
| 24 | + |
| 25 | + def __init__(self, region_config, **kwargs): |
| 26 | + super(DisabledDialup, self).__init__(region_config) |
| 27 | + |
| 28 | + def is_enabled(self): |
| 29 | + return False |
| 30 | + |
| 31 | + |
| 32 | +class ToggleDialup(BaseDialup): |
| 33 | + """ |
| 34 | + A simple toggle Dialup |
| 35 | + Example of region_config: { "type": "toggle", "enabled": True } |
| 36 | + """ |
| 37 | + |
| 38 | + def __init__(self, region_config, **kwargs): |
| 39 | + super(ToggleDialup, self).__init__(region_config) |
| 40 | + self.region_config = region_config |
| 41 | + |
| 42 | + def is_enabled(self): |
| 43 | + return self.region_config.get("enabled", False) |
| 44 | + |
| 45 | + |
| 46 | +class SimpleAccountPercentileDialup(BaseDialup): |
| 47 | + """ |
| 48 | + Simple account percentile dialup, enabling X% of |
| 49 | + Example of region_config: { "type": "account-percentile", "enabled-%": 20 } |
| 50 | + """ |
| 51 | + |
| 52 | + def __init__(self, region_config, account_id, feature_name, **kwargs): |
| 53 | + super(SimpleAccountPercentileDialup, self).__init__(region_config) |
| 54 | + self.account_id = account_id |
| 55 | + self.feature_name = feature_name |
| 56 | + |
| 57 | + def _get_account_percentile(self): |
| 58 | + """ |
| 59 | + Get account percentile based on sha256 hash of account ID and feature_name |
| 60 | +
|
| 61 | + :returns: integer n, where 0 <= n < 100 |
| 62 | + """ |
| 63 | + m = hashlib.sha256() |
| 64 | + m.update(self.account_id.encode()) |
| 65 | + m.update(self.feature_name.encode()) |
| 66 | + return int(m.hexdigest(), 16) % 100 |
| 67 | + |
| 68 | + def is_enabled(self): |
| 69 | + """ |
| 70 | + Enable when account_percentile falls within target_percentile |
| 71 | + Meaning only (target_percentile)% of accounts will be enabled |
| 72 | + """ |
| 73 | + target_percentile = self.region_config.get("enabled-%", 0) |
| 74 | + return self._get_account_percentile() < target_percentile |
0 commit comments