|
| 1 | +import abc |
| 2 | +import threading |
| 3 | +import logging |
| 4 | +from splitio.engine.filters.bloom_filter import BloomFilter |
| 5 | + |
| 6 | +_LOGGER = logging.getLogger(__name__) |
| 7 | + |
| 8 | +class BaseUniqueKeysTracker(object, metaclass=abc.ABCMeta): |
| 9 | + """Unique Keys Tracker interface.""" |
| 10 | + |
| 11 | + @abc.abstractmethod |
| 12 | + def track(self, key, feature_name): |
| 13 | + """ |
| 14 | + Return a boolean flag |
| 15 | +
|
| 16 | + """ |
| 17 | + pass |
| 18 | + |
| 19 | + @abc.abstractmethod |
| 20 | + def start(self): |
| 21 | + """ |
| 22 | + No return value |
| 23 | +
|
| 24 | + """ |
| 25 | + pass |
| 26 | + |
| 27 | + @abc.abstractmethod |
| 28 | + def stop(self): |
| 29 | + """ |
| 30 | + No return value |
| 31 | +
|
| 32 | + """ |
| 33 | + pass |
| 34 | + |
| 35 | +class UniqueKeysTracker(BaseUniqueKeysTracker): |
| 36 | + """Unique Keys Tracker class.""" |
| 37 | + |
| 38 | + def __init__(self, cache_size=30000, max_bulk_size=5000, task_refresh_rate = 24): |
| 39 | + self._cache_size = cache_size |
| 40 | + self._max_bulk_size = max_bulk_size |
| 41 | + self._task_refresh_rate = task_refresh_rate |
| 42 | + self._filter = BloomFilter(cache_size) |
| 43 | + self._lock = threading.RLock() |
| 44 | + self._cache = {} |
| 45 | + # TODO: initialize impressions sender adapter and task referesh rate in next PR |
| 46 | + |
| 47 | + def track(self, key, feature_name): |
| 48 | + """ |
| 49 | + Return a boolean flag |
| 50 | +
|
| 51 | + """ |
| 52 | + if self._filter.contains(feature_name+key): |
| 53 | + return False |
| 54 | + |
| 55 | + with self._lock: |
| 56 | + self._add_or_update(feature_name, key) |
| 57 | + self._filter.add(feature_name+key) |
| 58 | + |
| 59 | + if len(self._cache[feature_name]) == self._cache_size: |
| 60 | + _LOGGER.warn("MTK Cache size for Split [%s] has reach maximum unique keys [%d], flushing data now.", feature_name, self._cache_size) |
| 61 | +# TODO: Flush the data and reset split cache in next PR |
| 62 | + if self._get_dict_size() >= self._max_bulk_size: |
| 63 | + _LOGGER.info("Bulk MTK cache size has reach maximum, flushing data now.") |
| 64 | +# TODO: Flush the data and reset split cache in next PR |
| 65 | + |
| 66 | + return True |
| 67 | + |
| 68 | + def _get_dict_size(self): |
| 69 | + total_size = 0 |
| 70 | + for key in self._cache: |
| 71 | + total_size = total_size + len(self._cache[key]) |
| 72 | + return total_size |
| 73 | + |
| 74 | + def _add_or_update(self, feature_name, key): |
| 75 | + if feature_name not in self._cache: |
| 76 | + self._cache[feature_name] = set() |
| 77 | + self._cache[feature_name].add(key) |
| 78 | + |
| 79 | + def start(self): |
| 80 | + """ |
| 81 | + TODO: Add start posting impressions job in next PR |
| 82 | +
|
| 83 | + """ |
| 84 | + |
| 85 | + def stop(self): |
| 86 | + """ |
| 87 | + TODO: Add stop posting impressions job in next PR |
| 88 | +
|
| 89 | + """ |
0 commit comments