-
Notifications
You must be signed in to change notification settings - Fork 36
feat(eventProcessor): Add EventProcessor and BatchEventProcessor #203
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 all commits
Commits
Show all changes
69 commits
Select commit
Hold shift + click to select a range
232f0a0
feat: Add event_batch datamodels.
2320939
fix: unit test fixes.
fbb5a68
Merge branch 'master' into epmodels
mnoman09 c162465
feat: add event_factory and user_event_factory for event processing.
633b095
Removed third party dependency
msohailhussain 8a5f531
Merge branch 'master' into sohail/pr-189
mnoman09 35fcd82
Merge remote-tracking branch 'origin/sohail/pr-189' into sohail/pr-193
mnoman09 d7201cb
Removed HasAttr
mnoman09 c829fca
Merge branch 'master' into sohail/pr-189
mnoman09 1d858b7
feat(eventProcessor): Adds EventProcessor and BatchEventProcessor
mnoman09 c3c9d46
Addressed feedback. Restructured classes.
msohailhussain a2eeb85
Merge branch 'sohail/pr-189' into sohail/pr-193
mnoman09 a045291
update: structural changes.
f70a1c9
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
mnoman09 faff070
update: add check for integer values and insert logs for default values.
mnoman09 c931956
replaced comma with as
mnoman09 2dea7fe
conditions reordered
mnoman09 23ab6ce
fix: addressed more feedback
6474e98
update: removed print statements.
mnoman09 1184568
merged PR 189
mnoman09 592a306
fix: use VisitorAttribute class to create visitor attributes list.
c4a412a
fix: fix log_event payload.
2a3374c
removed commented code
mnoman09 ce44c11
fix linter error.
mnoman09 00efd1b
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
mnoman09 54333d7
update: log_event params.
mnoman09 d2f7126
fix: update module names according to structural changes.
3fd5788
fix: update module names according to structural changes.
ebe833c
Merge branch 'mnoman/AddBatchEP' of github.com:optimizely/python-sdk …
d4f2c66
Merge branch 'master' into sohail/pr-189
rashidsp 80b0963
fix: addressed minor feedback.
071460a
fix: addressed minor feedback.
900d96d
Merge branch 'sohail/pr-189' of github.com:optimizely/python-sdk into…
8cd8547
Merge branch 'sohail/pr-189' into sohail/pr-193
b730bfd
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
e628e0f
fix: addressed review comments.
mariamjamal94 855c73f
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
mariamjamal94 c18e359
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
mariamjamal94 56408dc
Merge branches 'mnoman/AddBatchEP' and 'mnoman/AddBatchEP' of github.…
mariamjamal94 f851754
fix: addresses review comments.
mariamjamal94 8f7be2b
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
mariamjamal94 1486fa4
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
mariamjamal94 b9d5fd9
Merge branch 'mnoman/AddBatchEP' of github.com:optimizely/python-sdk …
mariamjamal94 65a752b
fix: addresses review comment.
mariamjamal94 ab192a0
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
mariamjamal94 641d09a
update: allow float values for intervals.
mariamjamal94 8998580
fix: updated docstring for LogEvent.
mariamjamal94 a89a5bf
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
mariamjamal94 cfb2d74
fix: restore config_manager and remove unnecessary warnings from tox.…
mariamjamal94 751ee64
fix: remove closeable and introduce stop method.
mariamjamal94 c3d5b07
Merge branch 'master' into sohail/pr-193
mariamjamal94 b5d461b
Merge branch 'master' into sohail/pr-193
aliabbasrizvi ca208a6
Merge remote-tracking branch 'remotes/main_origin/master' into mnoman…
mariamjamal94 2c33344
update: update documentation and set default time interval unit to sec.
mariamjamal94 67e0424
fix: compare times directly in seconds.
mariamjamal94 477bbd5
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
oakbani e299dce
update: update sleeping time to 5sec.
mariamjamal94 758ffc2
Merge branch 'mnoman/AddBatchEP' of github.com:optimizely/python-sdk …
mariamjamal94 304ac00
update: update sleeping time to 5 sec.
mariamjamal94 5ef24de
fix: address import order issues.
mariamjamal94 1edb7c2
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
mariamjamal94 443b7aa
update: add documentation.
mariamjamal94 1d5aeca
Merge branch 'master' into sohail/pr-193
oakbani b3883d6
Merge remote-tracking branch 'remotes/origin/sohail/pr-193' into mnom…
oakbani 655a859
Merge branch 'mnoman/AddBatchEP' of github.com:optimizely/python-sdk …
oakbani 86e4b7f
Merge branch 'master' into mnoman/AddBatchEP
msohailhussain 65fb6fa
fix: address review comments.
mariamjamal94 01a8ea1
Merge branch 'mnoman/AddBatchEP' of github.com:optimizely/python-sdk …
mariamjamal94 498db55
update: add docstring.
mariamjamal94 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,269 @@ | ||
# Copyright 2019 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. | ||
|
||
import abc | ||
import threading | ||
import time | ||
|
||
from datetime import timedelta | ||
from six.moves import queue | ||
|
||
from optimizely import logger as _logging | ||
from optimizely.event_dispatcher import EventDispatcher as default_event_dispatcher | ||
from optimizely.helpers import validator | ||
from .event_factory import EventFactory | ||
from .user_event import UserEvent | ||
|
||
ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()}) | ||
|
||
|
||
class BaseEventProcessor(ABC): | ||
""" Class encapsulating event processing. Override with your own implementation. """ | ||
|
||
@abc.abstractmethod | ||
def process(user_event): | ||
aliabbasrizvi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" Method to provide intermediary processing stage within event production. | ||
Args: | ||
user_event: UserEvent instance that needs to be processed and dispatched. | ||
""" | ||
pass | ||
|
||
|
||
class BatchEventProcessor(BaseEventProcessor): | ||
""" | ||
BatchEventProcessor is an implementation of the BaseEventProcessor that batches events. | ||
The BatchEventProcessor maintains a single consumer thread that pulls events off of | ||
the blocking queue and buffers them for either a configured batch size or for a | ||
maximum duration before the resulting LogEvent is sent to the EventDispatcher. | ||
""" | ||
|
||
_DEFAULT_QUEUE_CAPACITY = 1000 | ||
_DEFAULT_BATCH_SIZE = 10 | ||
_DEFAULT_FLUSH_INTERVAL = timedelta(seconds=30) | ||
_DEFAULT_TIMEOUT_INTERVAL = timedelta(seconds=5) | ||
_SHUTDOWN_SIGNAL = object() | ||
_FLUSH_SIGNAL = object() | ||
LOCK = threading.Lock() | ||
|
||
def __init__(self, | ||
event_dispatcher, | ||
logger, | ||
start_on_init=False, | ||
event_queue=None, | ||
batch_size=None, | ||
flush_interval=None, | ||
timeout_interval=None): | ||
""" BatchEventProcessor init method to configure event batching. | ||
Args: | ||
event_dispatcher: Provides a dispatch_event method which if given a URL and params sends a request to it. | ||
logger: Provides a log method to log messages. By default nothing would be logged. | ||
start_on_init: Optional boolean param which starts the consumer thread if set to True. | ||
aliabbasrizvi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
Default value is False. | ||
event_queue: Optional component which accumulates the events until dispacthed. | ||
batch_size: Optional param which defines the upper limit on the number of events in event_queue after which | ||
the event_queue will be flushed. | ||
flush_interval: Optional floating point number representing time interval in seconds after which event_queue will | ||
be flushed. | ||
timeout_interval: Optional floating point number representing time interval in seconds before joining the consumer | ||
thread. | ||
""" | ||
self.event_dispatcher = event_dispatcher or default_event_dispatcher | ||
self.logger = _logging.adapt_logger(logger or _logging.NoOpLogger()) | ||
self.event_queue = event_queue or queue.Queue(maxsize=self._DEFAULT_QUEUE_CAPACITY) | ||
self.batch_size = batch_size if self._validate_intantiation_props(batch_size, 'batch_size') \ | ||
else self._DEFAULT_BATCH_SIZE | ||
self.flush_interval = timedelta(seconds=flush_interval) \ | ||
if self._validate_intantiation_props(flush_interval, 'flush_interval') \ | ||
else self._DEFAULT_FLUSH_INTERVAL | ||
self.timeout_interval = timedelta(seconds=timeout_interval) \ | ||
if self._validate_intantiation_props(timeout_interval, 'timeout_interval') \ | ||
else self._DEFAULT_TIMEOUT_INTERVAL | ||
self._current_batch = list() | ||
|
||
if start_on_init is True: | ||
self.start() | ||
|
||
@property | ||
def is_running(self): | ||
""" Property to check if consumer thread is alive or not. """ | ||
return self.executor.isAlive() | ||
|
||
def _validate_intantiation_props(self, prop, prop_name): | ||
aliabbasrizvi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" Method to determine if instantiation properties like batch_size, flush_interval | ||
and timeout_interval are valid. | ||
|
||
Args: | ||
prop: Property value that needs to be validated. | ||
prop_name: Property name. | ||
|
||
Returns: | ||
False if property value is None or less than 1 or not a finite number. | ||
False if property name is batch_size and value is a floating point number. | ||
True otherwise. | ||
""" | ||
if (prop_name == 'batch_size' and not isinstance(prop, int)) or prop is None or prop < 1 or \ | ||
not validator.is_finite_number(prop): | ||
self.logger.info('Using default value for {}.'.format(prop_name)) | ||
return False | ||
|
||
return True | ||
|
||
def _get_time(self, _time=None): | ||
aliabbasrizvi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" Method to return rounded off time as integer in seconds. If _time is None, uses current time. | ||
|
||
Args: | ||
_time: time in seconds that needs to be rounded off. | ||
|
||
Returns: | ||
Integer time in seconds. | ||
""" | ||
if _time is None: | ||
return int(round(time.time())) | ||
|
||
return int(round(_time)) | ||
|
||
def start(self): | ||
aliabbasrizvi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" Starts the batch processing thread to batch events. """ | ||
if hasattr(self, 'executor') and self.is_running: | ||
self.logger.warning('BatchEventProcessor already started.') | ||
return | ||
|
||
self.flushing_interval_deadline = self._get_time() + self._get_time(self.flush_interval.total_seconds()) | ||
self.executor = threading.Thread(target=self._run) | ||
self.executor.setDaemon(True) | ||
self.executor.start() | ||
|
||
def _run(self): | ||
""" Triggered as part of the thread which batches events or flushes event_queue and sleeps | ||
periodically if queue is empty. | ||
""" | ||
try: | ||
while True: | ||
if self._get_time() > self.flushing_interval_deadline: | ||
self._flush_queue() | ||
|
||
try: | ||
item = self.event_queue.get(True, 0.05) | ||
|
||
except queue.Empty: | ||
time.sleep(0.05) | ||
continue | ||
|
||
if item == self._SHUTDOWN_SIGNAL: | ||
self.logger.debug('Received shutdown signal.') | ||
break | ||
|
||
if item == self._FLUSH_SIGNAL: | ||
self.logger.debug('Received flush signal.') | ||
self._flush_queue() | ||
continue | ||
|
||
if isinstance(item, UserEvent): | ||
self._add_to_batch(item) | ||
|
||
except Exception as exception: | ||
self.logger.error('Uncaught exception processing buffer. Error: ' + str(exception)) | ||
|
||
finally: | ||
self.logger.info('Exiting processing loop. Attempting to flush pending events.') | ||
self._flush_queue() | ||
|
||
def flush(self): | ||
""" Adds flush signal to event_queue. """ | ||
|
||
self.event_queue.put(self._FLUSH_SIGNAL) | ||
|
||
def _flush_queue(self): | ||
""" Flushes event_queue by dispatching events. """ | ||
|
||
if len(self._current_batch) == 0: | ||
return | ||
|
||
with self.LOCK: | ||
to_process_batch = list(self._current_batch) | ||
self._current_batch = list() | ||
|
||
log_event = EventFactory.create_log_event(to_process_batch, self.logger) | ||
|
||
try: | ||
self.event_dispatcher.dispatch_event(log_event) | ||
except Exception as e: | ||
self.logger.error('Error dispatching event: ' + str(log_event) + ' ' + str(e)) | ||
|
||
def process(self, user_event): | ||
aliabbasrizvi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" Method to process the user_event by putting it in event_queue. | ||
Args: | ||
user_event: UserEvent Instance. | ||
""" | ||
if not isinstance(user_event, UserEvent): | ||
self.logger.error('Provided event is in an invalid format.') | ||
return | ||
|
||
self.logger.debug('Received user_event: ' + str(user_event)) | ||
|
||
try: | ||
self.event_queue.put_nowait(user_event) | ||
except queue.Full: | ||
self.logger.debug('Payload not accepted by the queue. Current size: {}'.format(str(self.event_queue.qsize()))) | ||
|
||
def _add_to_batch(self, user_event): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit. This needs docstring. |
||
""" Method to append received user event to current batch. | ||
Args: | ||
user_event: UserEvent Instance. | ||
""" | ||
if self._should_split(user_event): | ||
self._flush_queue() | ||
self._current_batch = list() | ||
|
||
# Reset the deadline if starting a new batch. | ||
if len(self._current_batch) == 0: | ||
self.flushing_interval_deadline = self._get_time() + \ | ||
self._get_time(self.flush_interval.total_seconds()) | ||
|
||
with self.LOCK: | ||
self._current_batch.append(user_event) | ||
if len(self._current_batch) >= self.batch_size: | ||
self._flush_queue() | ||
|
||
def _should_split(self, user_event): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit. This needs docstring. |
||
""" Method to check if current event batch should split into two. | ||
Args: | ||
user_event: UserEvent Instance. | ||
Return Value: | ||
- True, if revision number and project_id of last event in current batch do not match received event's | ||
revision number and project id respectively. | ||
- False, otherwise. | ||
""" | ||
if len(self._current_batch) == 0: | ||
return False | ||
|
||
current_context = self._current_batch[-1].event_context | ||
new_context = user_event.event_context | ||
|
||
if current_context.revision != new_context.revision: | ||
return True | ||
|
||
if current_context.project_id != new_context.project_id: | ||
return True | ||
|
||
return False | ||
|
||
def stop(self): | ||
""" Stops and disposes batch event processor. """ | ||
self.event_queue.put(self._SHUTDOWN_SIGNAL) | ||
self.logger.warning('Stopping Scheduler.') | ||
|
||
self.executor.join(self.timeout_interval.total_seconds()) | ||
|
||
if self.is_running: | ||
self.logger.error('Timeout exceeded while attempting to close for ' + str(self.timeout_interval) + ' ms.') |
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.