Repository navigation
feat(gateway): optional PostHog signup, identify and activation tracking (SEL-555) #245
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
Open
PetrefiedThunder
wants to merge
9
commits into
main
Choose a base branch
from
hermes/posthog-product-tracking
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+975
−7
Open
Changes from 7 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
85ba83f
feat(gateway): optional PostHog signup, identify and activation tracking
PetrefiedThunder 19e9500
fix(analytics): Settings-backed PostHog config, atomic per-account ac…
PetrefiedThunder 95c4299
fix(analytics): real two-key race test, unbounded-safe root resolutio…
PetrefiedThunder e9a75b8
Merge origin/main into hermes/posthog-product-tracking; renumber migr…
PetrefiedThunder a20b18d
Merge remote-tracking branch 'origin/main' into hermes/posthog-produc…
PetrefiedThunder 22fe3ba
fix(analytics): require HTTPS PostHog host; document migration 055 modes
PetrefiedThunder ffb8680
Merge remote-tracking branch 'origin/main' into hermes/posthog-produc…
PetrefiedThunder 505b203
merge: bring origin/main into hermes/posthog-product-tracking
PetrefiedThunder 70b43f6
Merge branch 'main' into hermes/posthog-product-tracking
PetrefiedThunder 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
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,161 @@ | ||
| """Fail-safe, non-blocking PostHog product tracking. | ||
|
|
||
| Tracking is off unless ``POSTHOG_API_KEY`` is set (process env or ``.env`` via | ||
| Settings). When it | ||
| is unset every function here is a no-op: no client, no network, no task. | ||
|
|
||
| Events go to PostHog's public ``/capture/`` endpoint over httpx (already a | ||
| gateway dependency), so no PostHog SDK is installed. Each send is scheduled as | ||
| a background task with a short timeout, and every exception is caught and | ||
| logged at debug level without the API key, so tracking can never fail or slow | ||
| a request. | ||
|
|
||
| The distinct id is the account's root (sponsor) wallet id. Only | ||
| :func:`identify` sends personal data: the ``email`` person property. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import logging | ||
| import os | ||
| from typing import Any | ||
|
|
||
| import httpx | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| DEFAULT_HOST = "https://us.i.posthog.com" | ||
| SEND_TIMEOUT_SECONDS = 2.0 | ||
|
|
||
| EVENT_SIGNUP = "signup" | ||
| EVENT_ACTIVATION = "activation" | ||
|
|
||
| # In-flight sends are capped; beyond this, new events are dropped so a slow or | ||
| # down PostHog can never pile up unbounded tasks. | ||
| MAX_PENDING = 256 | ||
|
|
||
| _pending: set[asyncio.Task[None]] = set() | ||
| _client: httpx.AsyncClient | None = None | ||
|
|
||
|
|
||
| def _config() -> tuple[str, str] | None: | ||
| """(api_key, host) from process env first, then Settings (``.env``).""" | ||
| from app.core.config import get_settings | ||
|
|
||
| settings = get_settings() | ||
| api_key = os.environ.get("POSTHOG_API_KEY", "").strip() | ||
| if not api_key: | ||
| api_key = settings.POSTHOG_API_KEY.get_secret_value().strip() | ||
| if not api_key: | ||
| return None | ||
| host = ( | ||
| os.environ.get("POSTHOG_HOST", "").strip() | ||
| or settings.POSTHOG_HOST.strip() | ||
| or DEFAULT_HOST | ||
| ) | ||
| if not host.lower().startswith("https://"): | ||
| # The identify payload carries the sponsor email; never send it in | ||
| # cleartext. A non-HTTPS host leaves tracking off. | ||
| return None | ||
| return api_key, host.rstrip("/") | ||
|
|
||
|
|
||
| def _get_client() -> httpx.AsyncClient: | ||
| global _client | ||
| if _client is None or _client.is_closed: | ||
| _client = httpx.AsyncClient(timeout=SEND_TIMEOUT_SECONDS) | ||
| return _client | ||
|
|
||
|
|
||
| def is_enabled() -> bool: | ||
| return _config() is not None | ||
|
|
||
|
|
||
| async def _post(host: str, payload: dict[str, Any]) -> None: | ||
| response = await _get_client().post(f"{host}/capture/", json=payload) | ||
| response.raise_for_status() | ||
|
|
||
|
|
||
| async def _send(host: str, payload: dict[str, Any]) -> None: | ||
| try: | ||
| await _post(host, payload) | ||
| except Exception as exc: # noqa: BLE001 - tracking must never raise | ||
| logger.debug( | ||
| "product_analytics_send_failed event=%s error=%s", | ||
| payload.get("event"), | ||
| type(exc).__name__, | ||
| ) | ||
|
|
||
|
|
||
| def _enqueue(event: str, distinct_id: str, properties: dict[str, Any]) -> None: | ||
| try: | ||
| config = _config() | ||
| if config is None or not distinct_id: | ||
| return | ||
| if len(_pending) >= MAX_PENDING: | ||
| logger.debug("product_analytics_dropped event=%s reason=backlog", event) | ||
| return | ||
| api_key, host = config | ||
| payload = { | ||
| "api_key": api_key, | ||
| "event": event, | ||
| "distinct_id": distinct_id, | ||
| "properties": {**properties, "$lib": "agent-middleware-gateway"}, | ||
| } | ||
| try: | ||
| loop = asyncio.get_running_loop() | ||
| except RuntimeError: | ||
| return # no event loop (sync caller): drop rather than block | ||
| task = loop.create_task(_send(host, payload)) | ||
| _pending.add(task) | ||
| task.add_done_callback(_pending.discard) | ||
| except Exception as exc: # noqa: BLE001 - tracking must never raise | ||
| logger.debug( | ||
| "product_analytics_enqueue_failed event=%s error=%s", | ||
| event, | ||
| type(exc).__name__, | ||
| ) | ||
|
|
||
|
|
||
| def identify(distinct_id: str, *, email: str | None) -> None: | ||
| """Attach the email person property to the account.""" | ||
| props: dict[str, Any] = {} | ||
| if email: | ||
| props["$set"] = {"email": email} | ||
| _enqueue("$identify", distinct_id, props) | ||
|
|
||
|
|
||
| def capture(event: str, distinct_id: str, **properties: Any) -> None: | ||
| _enqueue(event, distinct_id, properties) | ||
|
|
||
|
|
||
| def track_signup(distinct_id: str, *, method: str, email: str | None = None) -> None: | ||
| """identify (with email when known) then a ``signup`` event.""" | ||
| identify(distinct_id, email=email) | ||
| capture(EVENT_SIGNUP, distinct_id, method=method) | ||
|
|
||
|
|
||
| def track_activation(distinct_id: str, *, key_id: str, wallet_id: str) -> None: | ||
| capture(EVENT_ACTIVATION, distinct_id, key_id=key_id, wallet_id=wallet_id) | ||
|
|
||
|
|
||
| async def drain_pending() -> None: | ||
| """Await in-flight sends (tests and graceful shutdown).""" | ||
| if _pending: | ||
| await asyncio.gather(*list(_pending), return_exceptions=True) | ||
|
|
||
|
|
||
| async def shutdown() -> None: | ||
| """Drain in-flight sends and close the shared client (app shutdown).""" | ||
| global _client | ||
| try: | ||
| await asyncio.wait_for(drain_pending(), timeout=SEND_TIMEOUT_SECONDS + 1) | ||
| except Exception as exc: # noqa: BLE001 - shutdown must not raise | ||
| logger.debug("product_analytics_drain_failed error=%s", type(exc).__name__) | ||
| client, _client = _client, None | ||
| if client is not None: | ||
| try: | ||
| await client.aclose() | ||
| except Exception as exc: # noqa: BLE001 | ||
| logger.debug("product_analytics_close_failed error=%s", type(exc).__name__) |
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
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.
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.