-
Notifications
You must be signed in to change notification settings - Fork 36
feat: add odp event manager #403
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
7e135eb
add odp event manager
andrewleap-optimizely 079df46
add event manager config
andrewleap-optimizely 35ca02f
add common data/decoder to odp events
andrewleap-optimizely d91be75
fix tests
andrewleap-optimizely 0eeb1cb
remove unnecessary lock
andrewleap-optimizely e641a46
add warning for shutdown queue
andrewleap-optimizely 847082e
address comments
andrewleap-optimizely 4c78039
remove unnecessary copy
andrewleap-optimizely 53962ec
add flushing interval/wait on config
andrewleap-optimizely f6524c8
add test for odp disabled after odp event
andrewleap-optimizely 0aa1da0
Merge branch 'master' into aleap/add_odp_event_manager
andrewleap-optimizely 3d524e8
cleanup
andrewleap-optimizely 3ed7056
cleanup
andrewleap-optimizely 7e1995c
disable event pre-queueing
andrewleap-optimizely 8988870
address comments
andrewleap-optimizely fa2220d
enforce batch size and add auto retries
andrewleap-optimizely 0318a6d
lower flush interval
andrewleap-optimizely d85ec2c
type fix
andrewleap-optimizely File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,187 @@ | ||
| # Copyright 2019-2022, Optimizely | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from __future__ import annotations | ||
| from threading import Lock, Thread | ||
| from typing import Any, Optional | ||
| import queue | ||
| from queue import Queue | ||
| from sys import version_info | ||
|
|
||
| from optimizely import logger as _logging | ||
| from .odp_event import OdpEvent | ||
| from .odp_config import OdpConfig | ||
| from .zaius_rest_api_manager import ZaiusRestApiManager | ||
| from optimizely.helpers.enums import OdpEventManagerConfig, Errors | ||
|
|
||
|
|
||
| if version_info < (3, 8): | ||
| from typing_extensions import Final | ||
| else: | ||
| from typing import Final # type: ignore | ||
|
|
||
|
|
||
| class Signal: | ||
| '''Used to create unique objects for sending signals to event queue.''' | ||
| pass | ||
|
|
||
|
|
||
| class OdpEventManager: | ||
| """ | ||
| Class that sends batches of ODP events. | ||
|
|
||
| The OdpEventManager maintains a single consumer thread that pulls events off of | ||
| the queue and buffers them before the events are sent to ODP. | ||
| """ | ||
|
|
||
| _SHUTDOWN_SIGNAL: Final = Signal() | ||
| _FLUSH_SIGNAL: Final = Signal() | ||
|
|
||
| def __init__( | ||
| self, | ||
| odp_config: OdpConfig, | ||
| logger: Optional[_logging.Logger] = None, | ||
| api_manager: Optional[ZaiusRestApiManager] = None | ||
|
|
||
| ): | ||
| """ OdpEventManager init method to configure event batching. | ||
|
|
||
| Args: | ||
| odp_config: ODP integration config. | ||
| logger: Optional component which provides a log method to log messages. By default nothing would be logged. | ||
| api_manager: Optional component which sends events to ODP. | ||
| """ | ||
| self.logger = logger or _logging.NoOpLogger() | ||
| self.zaius_manager = api_manager or ZaiusRestApiManager(self.logger) | ||
| self.odp_config = odp_config | ||
| self.event_queue: Queue[OdpEvent | Signal] = Queue(OdpEventManagerConfig.DEFAULT_QUEUE_CAPACITY) | ||
| self.batch_size = OdpEventManagerConfig.DEFAULT_BATCH_SIZE | ||
| self.lock = Lock() | ||
|
|
||
| self._current_batch: list[OdpEvent] = [] | ||
|
|
||
| self.executor = Thread(target=self._run, daemon=True) | ||
|
|
||
| @property | ||
| def is_running(self) -> bool: | ||
| """ Property to check if consumer thread is alive or not. """ | ||
| return self.executor.is_alive() | ||
|
|
||
| def start(self) -> None: | ||
| """ Starts the batch processing thread to batch events. """ | ||
| if self.is_running: | ||
| self.logger.warning('ODP event processor already started.') | ||
| return | ||
|
|
||
| self.executor.start() | ||
|
|
||
| def _run(self) -> None: | ||
| """ Triggered as part of the thread which batches odp events or flushes event_queue and blocks on get | ||
| for flush interval if queue is empty. | ||
| """ | ||
| try: | ||
| while True: | ||
| item = self.event_queue.get() | ||
|
|
||
| if item == self._SHUTDOWN_SIGNAL: | ||
| self.logger.debug('Received ODP event shutdown signal.') | ||
| self.event_queue.task_done() | ||
andrewleap-optimizely marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| break | ||
|
|
||
| if item is self._FLUSH_SIGNAL: | ||
| self.logger.debug('Received ODP event flush signal.') | ||
| self._flush_batch() | ||
| self.event_queue.task_done() | ||
| continue | ||
|
|
||
| if isinstance(item, OdpEvent): | ||
| self._add_to_batch(item) | ||
| self.event_queue.task_done() | ||
|
|
||
| except Exception as exception: | ||
andrewleap-optimizely marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| self.logger.error(f'Uncaught exception processing ODP events. Error: {exception}') | ||
|
|
||
| finally: | ||
| self.logger.info('Exiting ODP event processing loop. Attempting to flush pending events.') | ||
| self._flush_batch() | ||
|
|
||
| def flush(self) -> None: | ||
| """ Adds flush signal to event_queue. """ | ||
|
|
||
| self.event_queue.put(self._FLUSH_SIGNAL) | ||
|
|
||
| def _flush_batch(self) -> None: | ||
| """ Flushes current batch by dispatching event. """ | ||
| batch_len = len(self._current_batch) | ||
| if batch_len == 0: | ||
| self.logger.debug('Nothing to flush.') | ||
andrewleap-optimizely marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| return | ||
|
|
||
| api_key = self.odp_config.get_api_key() | ||
| api_host = self.odp_config.get_api_host() | ||
|
|
||
| if not api_key or not api_host: | ||
| self.logger.debug('ODP event processing has been disabled.') | ||
| return | ||
andrewleap-optimizely marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| self.logger.debug(f'Flushing batch size {batch_len}.') | ||
andrewleap-optimizely marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| should_retry = False | ||
| with self.lock: | ||
| event_batch = list(self._current_batch) | ||
| try: | ||
| should_retry = self.zaius_manager.send_odp_events(api_key, api_host, event_batch) | ||
| except Exception as e: | ||
| self.logger.error(Errors.ODP_EVENT_FAILED.format(f'{event_batch} {e}')) | ||
|
|
||
| if should_retry: | ||
| self.logger.debug('Error dispatching ODP events, scheduled to retry.') | ||
| return | ||
|
|
||
| self._current_batch = [] | ||
|
|
||
| def _add_to_batch(self, odp_event: OdpEvent) -> None: | ||
| """ Method to append received odp event to current batch.""" | ||
|
|
||
| with self.lock: | ||
| self._current_batch.append(odp_event) | ||
| if len(self._current_batch) >= self.batch_size: | ||
andrewleap-optimizely marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| self.logger.debug('Flushing ODP events on batch size.') | ||
| self._flush_batch() | ||
|
|
||
| def stop(self) -> None: | ||
| """ Stops and disposes batch odp event queue.""" | ||
| self.event_queue.put(self._SHUTDOWN_SIGNAL) | ||
| self.logger.warning('Stopping ODP Event Queue.') | ||
|
|
||
| if self.is_running: | ||
| self.executor.join() | ||
|
|
||
| if len(self._current_batch) > 0: | ||
| self.logger.error(Errors.ODP_EVENT_FAILED.format(self._current_batch)) | ||
|
|
||
| if self.is_running: | ||
| self.logger.error('Error stopping ODP event queue.') | ||
|
|
||
| def send_event(self, type: str, action: str, identifiers: dict[str, str], data: dict[str, Any]) -> None: | ||
| event = OdpEvent(type, action, identifiers, data) | ||
andrewleap-optimizely marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| self.dispatch(event) | ||
|
|
||
| def dispatch(self, event: OdpEvent) -> None: | ||
| if not self.odp_config.odp_integrated(): | ||
| self.logger.debug('ODP event processing has been disabled.') | ||
| return | ||
andrewleap-optimizely marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| try: | ||
| self.event_queue.put_nowait(event) | ||
andrewleap-optimizely marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| except queue.Full: | ||
andrewleap-optimizely marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| self.logger.error(Errors.ODP_EVENT_FAILED.format("Queue is full")) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.