Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 12
feat: support-evaluation-tracking-api#196
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
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
3070147
feat/add-pipeline-analytics-processor-for-batching-events
Zaimwa9 cc1c293
feat/wire-analytics-pipeline-to-flag-evaluation
Zaimwa9 f6a84cf
feat/add-trackevent-and-pipeline-config-in-clients
Zaimwa9 f8cdca5
feat: log-runtime-error
Zaimwa9 f00647c
feat: extracted-resolve-trait-values
Zaimwa9 cd5ab91
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 9add012
feat: linter
Zaimwa9 226bb62
Merge branch 'feat/support-evaluation-tracking-api' of github.com:Fla…
Zaimwa9 b31dac4
feat: trimmed-tests
Zaimwa9 aacf9f0
feat: renamed-max-buffer-to-max-buffer-items
Zaimwa9 b91349f
feat: remove-redundant-has-attr-check-in-del
Zaimwa9 55df6eb
feat: added-docstring-for-PipelineAnalyticsProcessor
Zaimwa9 7743a37
feat: use-at-exit-to-flush-analytics-on-process-exit
Zaimwa9 b38039f
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
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 |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| from flagsmith import webhooks | ||
| from flagsmith.analytics import PipelineAnalyticsConfig | ||
| from flagsmith.flagsmith import Flagsmith | ||
| from flagsmith.version import __version__ | ||
| __all__ = ("Flagsmith", "webhooks", "__version__") | ||
| __all__ = ("Flagsmith", "PipelineAnalyticsConfig", "webhooks", "__version__") |
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 |
|---|---|---|
| @@ -1,9 +1,18 @@ | ||
| import atexit | ||
| import json | ||
| import logging | ||
| import threading | ||
| import time | ||
| import typing | ||
| from dataclasses import dataclass | ||
| from datetime import datetime | ||
| from requests_futures.sessions import FuturesSession # type: ignore | ||
| from flagsmith.version import __version__ | ||
| logger = logging.getLogger(__name__) | ||
| ANALYTICS_ENDPOINT: typing.Final[str] = "analytics/flags/" | ||
| # Used to control how often we send data(in seconds) | ||
| @@ -60,3 +69,161 @@ def track_feature(self, feature_name: str) -> None: | ||
| self.analytics_data[feature_name] = self.analytics_data.get(feature_name, 0) + 1 | ||
| if (datetime.now() - self._last_flushed).seconds > ANALYTICS_TIMER: | ||
| self.flush() | ||
| @dataclass | ||
| class PipelineAnalyticsConfig: | ||
| analytics_server_url: str | ||
| max_buffer_items: int = 1000 | ||
| flush_interval_seconds: float = 10.0 | ||
| class PipelineAnalyticsProcessor: | ||
khvn26 marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| """ | ||
| Buffered analytics processor that sends per-evaluation and custom events | ||
| to the Flagsmith pipeline analytics endpoint in batches. | ||
| Evaluation events are deduplicated within each flush window. Events are | ||
| flushed periodically via a background timer or when the buffer is full. | ||
| """ | ||
| def __init__( | ||
| self, | ||
| config: PipelineAnalyticsConfig, | ||
| environment_key: str, | ||
| ) -> None: | ||
| url = config.analytics_server_url | ||
| if not url.endswith("/"): | ||
| url = f"{url}/" | ||
| self._batch_endpoint = f"{url}v1/analytics/batch" | ||
| self._environment_key = environment_key | ||
| self._max_buffer = config.max_buffer_items | ||
| self._flush_interval_seconds = config.flush_interval_seconds | ||
| self._buffer: typing.List[typing.Dict[str, typing.Any]] = [] | ||
| self._dedup_keys: typing.Dict[str, str] = {} | ||
| self._lock = threading.Lock() | ||
| self._timer: typing.Optional[threading.Timer] = None | ||
| def record_evaluation_event( | ||
| self, | ||
| flag_key: str, | ||
| enabled: bool, | ||
| value: typing.Any, | ||
| identity_identifier: typing.Optional[str] = None, | ||
| traits: typing.Optional[typing.Dict[str, typing.Any]] = None, | ||
| ) -> None: | ||
| fingerprint = f"{identity_identifier or 'none'}|{enabled}|{value}" | ||
| should_flush = False | ||
| with self._lock: | ||
| if self._dedup_keys.get(flag_key) == fingerprint: | ||
| return | ||
| self._dedup_keys[flag_key] = fingerprint | ||
| self._buffer.append( | ||
| { | ||
| "event_id": flag_key, | ||
| "event_type": "flag_evaluation", | ||
| "evaluated_at": int(time.time() * 1000), | ||
| "identity_identifier": identity_identifier, | ||
| "enabled": enabled, | ||
| "value": value, | ||
| "traits": dict(traits) if traits else None, | ||
| "metadata": {"sdk_version": __version__}, | ||
| } | ||
| ) | ||
| if len(self._buffer) >= self._max_buffer: | ||
| should_flush = True | ||
| if should_flush: | ||
| self.flush() | ||
| def record_custom_event( | ||
| self, | ||
| event_name: str, | ||
| identity_identifier: typing.Optional[str] = None, | ||
| traits: typing.Optional[typing.Dict[str, typing.Any]] = None, | ||
| metadata: typing.Optional[typing.Dict[str, typing.Any]] = None, | ||
| ) -> None: | ||
| should_flush = False | ||
| with self._lock: | ||
| self._buffer.append( | ||
| { | ||
| "event_id": event_name, | ||
| "event_type": "custom_event", | ||
| "evaluated_at": int(time.time() * 1000), | ||
| "identity_identifier": identity_identifier, | ||
| "enabled": None, | ||
| "value": None, | ||
| "traits": dict(traits) if traits else None, | ||
| "metadata": {**(metadata or {}), "sdk_version": __version__}, | ||
| } | ||
| ) | ||
| if len(self._buffer) >= self._max_buffer: | ||
| should_flush = True | ||
| if should_flush: | ||
| self.flush() | ||
| def flush(self) -> None: | ||
| with self._lock: | ||
| if not self._buffer: | ||
| return | ||
| events = self._buffer | ||
| self._buffer = [] | ||
| self._dedup_keys.clear() | ||
| payload = json.dumps( | ||
| {"events": events, "environment_key": self._environment_key} | ||
| ) | ||
| try: | ||
| future = session.post( | ||
| self._batch_endpoint, | ||
| data=payload, | ||
| timeout=3, | ||
| headers={ | ||
| "Content-Type": "application/json; charset=utf-8", | ||
| "X-Environment-Key": self._environment_key, | ||
| "Flagsmith-SDK-User-Agent": f"flagsmith-python-client/{__version__}", | ||
| }, | ||
| ) | ||
| except RuntimeError: | ||
| logger.debug("Skipping flush: thread pool already shut down") | ||
| return | ||
| future.add_done_callback(lambda f: self._handle_flush_result(f, events)) | ||
| def _handle_flush_result( | ||
| self, | ||
| future: typing.Any, | ||
| events: typing.List[typing.Dict[str, typing.Any]], | ||
| ) -> None: | ||
| try: | ||
| response = future.result() | ||
| response.raise_for_status() | ||
| except Exception: | ||
| logger.warning( | ||
| "Failed to flush pipeline analytics, re-queuing events", exc_info=True | ||
| ) | ||
| with self._lock: | ||
| self._buffer = events + self._buffer | ||
| self._buffer = self._buffer[: self._max_buffer] | ||
| def start(self) -> None: | ||
| self._schedule_flush() | ||
| atexit.register(self.stop) | ||
| def stop(self) -> None: | ||
| atexit.unregister(self.stop) | ||
| if self._timer is not None: | ||
| self._timer.cancel() | ||
| self.flush() | ||
| def _schedule_flush(self) -> None: | ||
| self._timer = threading.Timer(self._flush_interval_seconds, self._timer_flush) | ||
| self._timer.daemon = True | ||
| self._timer.start() | ||
| def _timer_flush(self) -> None: | ||
| self.flush() | ||
| self._schedule_flush() | ||
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
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
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.