|
| 1 | +import json |
| 2 | +import threading |
| 3 | +import copy |
| 4 | + |
| 5 | +from securenative.errors import MissingApiKeyError |
| 6 | +from securenative.http_client import HttpClient |
| 7 | +from securenative.sdk_options import SecureNativeOptions |
| 8 | + |
| 9 | + |
| 10 | +class QueueItem: |
| 11 | + def __init__(self, url, body): |
| 12 | + self.url = url |
| 13 | + self.body = body |
| 14 | + |
| 15 | + |
| 16 | +class EventManager: |
| 17 | + def __init__(self, api_key, options=SecureNativeOptions(), http_client=HttpClient()): |
| 18 | + if api_key is None: |
| 19 | + raise MissingApiKeyError() |
| 20 | + |
| 21 | + self.http_client = http_client |
| 22 | + self.api_key = api_key |
| 23 | + self.options = options |
| 24 | + self.queue = list() |
| 25 | + |
| 26 | + if self.options.auto_send: |
| 27 | + interval_seconds = max(options.interval // 1000, 1) |
| 28 | + threading.Timer(interval_seconds, self.flush).start() |
| 29 | + |
| 30 | + def send_async(self, event, resource_path): |
| 31 | + item = QueueItem( |
| 32 | + self._build_url(resource_path), |
| 33 | + json.dumps(event) |
| 34 | + ) |
| 35 | + |
| 36 | + self.queue.insert(0, item) |
| 37 | + if self._is_queue_full(): |
| 38 | + self.queue = self.queue[:len(self.queue - 1)] |
| 39 | + |
| 40 | + def flush(self): |
| 41 | + queue_copy = copy.copy(self.queue) |
| 42 | + self.queue = list() |
| 43 | + |
| 44 | + for item in queue_copy: |
| 45 | + self.http_client.post(item.url, self.api_key, item.body) |
| 46 | + |
| 47 | + def send_sync(self, event, resources_path): |
| 48 | + return self.http_client.post( |
| 49 | + self._build_url(resources_path), |
| 50 | + self.api_key, |
| 51 | + json.dumps(event) |
| 52 | + ) |
| 53 | + |
| 54 | + def _build_url(self, resource_path): |
| 55 | + return self.options.api_url + "/" + resource_path |
| 56 | + |
| 57 | + def _is_queue_full(self): |
| 58 | + return len(self.queue) > self.options.max_events |
0 commit comments