-
Notifications
You must be signed in to change notification settings - Fork 69
feat(capture): add capture_mode config scaffolding (capture v1, 1/6) #701
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
Draft
eli-r-ph
wants to merge
2
commits into
main
Choose a base branch
from
capture-v1/01-config
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.
+227
β2
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| import logging | ||
| import os | ||
| from enum import Enum | ||
| from typing import Optional, Union | ||
|
|
||
| log = logging.getLogger("posthog") | ||
|
|
||
| CAPTURE_MODE_ENV_VAR = "POSTHOG_CAPTURE_MODE" | ||
|
|
||
|
|
||
| class CaptureMode(str, Enum): | ||
| """Selects the capture wire protocol used for event ingestion. | ||
|
|
||
| ``V0`` is the legacy ``POST /batch/`` endpoint and the default, so upgrading | ||
| is transparent to existing callers. ``V1`` opts into | ||
| ``POST /i/v1/analytics/events`` (Bearer auth, per-event results, partial | ||
| retry). Inheriting from ``str`` keeps the members directly comparable to and | ||
| serializable as their ``"v0"`` / ``"v1"`` values. | ||
| """ | ||
|
|
||
| V0 = "v0" | ||
| V1 = "v1" | ||
|
|
||
|
|
||
| # Accepted spellings for both the explicit kwarg and the env var. Aliases mirror | ||
| # the posthog-go naming (``legacy`` / ``analytics_v1``) so the two SDKs are | ||
| # configured with the same vocabulary. | ||
| _ALIASES: dict[str, CaptureMode] = { | ||
| "v0": CaptureMode.V0, | ||
| "legacy": CaptureMode.V0, | ||
| "v1": CaptureMode.V1, | ||
| "analytics_v1": CaptureMode.V1, | ||
| } | ||
|
|
||
|
|
||
| def _coerce_explicit(value: Union[CaptureMode, str]) -> CaptureMode: | ||
| """Normalize an explicitly-supplied capture mode to a ``CaptureMode``. | ||
|
|
||
| Accepts a ``CaptureMode`` or one of the string aliases. An explicit but | ||
| unrecognized value is a programming error, so it raises ``ValueError`` rather | ||
| than silently defaulting (unlike the env var, which is operator-supplied and | ||
| defaults defensively). | ||
| """ | ||
| if isinstance(value, CaptureMode): | ||
| return value | ||
| if isinstance(value, str): | ||
| resolved = _ALIASES.get(value.strip().lower()) | ||
| if resolved is not None: | ||
| return resolved | ||
| raise ValueError( | ||
| f"invalid capture_mode {value!r}; expected a CaptureMode or one of " | ||
| f"{sorted(_ALIASES)}" | ||
| ) | ||
|
|
||
|
|
||
| def resolve_capture_mode( | ||
| capture_mode: Optional[Union[CaptureMode, str]] = None, | ||
| ) -> CaptureMode: | ||
| """Resolve the effective capture mode. | ||
|
|
||
| Precedence: explicit ``capture_mode`` argument > ``POSTHOG_CAPTURE_MODE`` env | ||
| var > ``CaptureMode.V0``. An unrecognized env value logs a warning and falls | ||
| back to ``V0`` so a typo never silently flips the wire protocol. | ||
| """ | ||
| if capture_mode is not None: | ||
| return _coerce_explicit(capture_mode) | ||
|
|
||
| raw = os.environ.get(CAPTURE_MODE_ENV_VAR) | ||
| if raw is None or raw.strip() == "": | ||
| return CaptureMode.V0 | ||
|
|
||
| resolved = _ALIASES.get(raw.strip().lower()) | ||
| if resolved is None: | ||
| log.warning( | ||
| "Unrecognized %s=%r; falling back to %s. Expected one of %s.", | ||
| CAPTURE_MODE_ENV_VAR, | ||
| raw, | ||
| CaptureMode.V0.value, | ||
| sorted(_ALIASES), | ||
| ) | ||
| return CaptureMode.V0 | ||
| return resolved |
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,109 @@ | ||
| import os | ||
| import unittest | ||
| from unittest import mock | ||
|
|
||
| from parameterized import parameterized | ||
|
|
||
| from posthog.capture_mode import ( | ||
| CAPTURE_MODE_ENV_VAR, | ||
| CaptureMode, | ||
| resolve_capture_mode, | ||
| ) | ||
| from posthog.client import Client | ||
| from posthog.consumer import Consumer | ||
| from posthog.test.logging_helpers import capture_message_only_logs | ||
| from posthog.test.test_utils import TEST_API_KEY | ||
|
|
||
|
|
||
| class TestResolveCaptureMode(unittest.TestCase): | ||
| def test_defaults_to_v0_with_no_kwarg_and_no_env(self) -> None: | ||
| with mock.patch.dict(os.environ, {}, clear=False): | ||
| os.environ.pop(CAPTURE_MODE_ENV_VAR, None) | ||
| self.assertIs(resolve_capture_mode(None), CaptureMode.V0) | ||
|
|
||
| @parameterized.expand( | ||
| [ | ||
| # (name, kwarg, expected, opposite_env): the env always names the | ||
| # mode the kwarg must override, so every row proves the kwarg wins. | ||
| ("enum_v0", CaptureMode.V0, CaptureMode.V0, "v1"), | ||
| ("enum_v1", CaptureMode.V1, CaptureMode.V1, "v0"), | ||
| ("str_v0", "v0", CaptureMode.V0, "v1"), | ||
| ("str_v1", "v1", CaptureMode.V1, "v0"), | ||
| ("str_legacy_alias", "legacy", CaptureMode.V0, "v1"), | ||
| ("str_analytics_v1_alias", "analytics_v1", CaptureMode.V1, "v0"), | ||
| ("str_upper_and_padded", " V1 ", CaptureMode.V1, "v0"), | ||
| ] | ||
| ) | ||
| def test_explicit_kwarg_takes_precedence_and_coerces( | ||
| self, _name, kwarg, expected, opposite_env | ||
| ) -> None: | ||
| with mock.patch.dict(os.environ, {CAPTURE_MODE_ENV_VAR: opposite_env}): | ||
| self.assertIs(resolve_capture_mode(kwarg), expected) | ||
|
|
||
| def test_invalid_kwarg_raises_even_with_valid_env(self) -> None: | ||
| # The kwarg path is consulted before the env, so an invalid kwarg raises | ||
| # rather than silently falling back to a valid env value. | ||
| with mock.patch.dict(os.environ, {CAPTURE_MODE_ENV_VAR: "v1"}): | ||
| with self.assertRaises(ValueError): | ||
| resolve_capture_mode("bogus") | ||
|
|
||
| @parameterized.expand( | ||
| [ | ||
| ("v0", "v0", CaptureMode.V0), | ||
| ("legacy", "legacy", CaptureMode.V0), | ||
| ("v1", "v1", CaptureMode.V1), | ||
| ("analytics_v1", "analytics_v1", CaptureMode.V1), | ||
| ("uppercase", "V1", CaptureMode.V1), | ||
| ("padded", " v1 ", CaptureMode.V1), | ||
| ] | ||
| ) | ||
| def test_env_var_resolution(self, _name, env_value, expected) -> None: | ||
| with mock.patch.dict(os.environ, {CAPTURE_MODE_ENV_VAR: env_value}): | ||
| self.assertIs(resolve_capture_mode(None), expected) | ||
|
|
||
| @parameterized.expand([("empty", ""), ("whitespace", " ")]) | ||
| def test_blank_env_var_defaults_to_v0(self, _name, env_value) -> None: | ||
| with mock.patch.dict(os.environ, {CAPTURE_MODE_ENV_VAR: env_value}): | ||
| self.assertIs(resolve_capture_mode(None), CaptureMode.V0) | ||
|
|
||
| def test_unrecognized_env_var_warns_and_defaults_to_v0(self) -> None: | ||
| with mock.patch.dict(os.environ, {CAPTURE_MODE_ENV_VAR: "bogus"}): | ||
| with capture_message_only_logs() as stream: | ||
| self.assertIs(resolve_capture_mode(None), CaptureMode.V0) | ||
| self.assertIn("bogus", stream.getvalue()) | ||
|
|
||
| @parameterized.expand([("bad_str", "bogus"), ("wrong_type", 1)]) | ||
| def test_invalid_explicit_kwarg_raises(self, _name, value) -> None: | ||
| with self.assertRaises(ValueError): | ||
| resolve_capture_mode(value) | ||
|
|
||
|
|
||
| class TestCaptureModePlumbing(unittest.TestCase): | ||
| def test_client_resolves_and_stores_default_v0(self) -> None: | ||
| with mock.patch.dict(os.environ, {}, clear=False): | ||
| os.environ.pop(CAPTURE_MODE_ENV_VAR, None) | ||
| client = Client(TEST_API_KEY, sync_mode=True) | ||
| self.assertIs(client.capture_mode, CaptureMode.V0) | ||
|
|
||
| @parameterized.expand( | ||
| [ | ||
| ("enum_v1", CaptureMode.V1, CaptureMode.V1), | ||
| ("str_v1", "v1", CaptureMode.V1), | ||
| ("enum_v0", CaptureMode.V0, CaptureMode.V0), | ||
| ] | ||
| ) | ||
| def test_client_kwarg_sets_mode(self, _name, kwarg, expected) -> None: | ||
| client = Client(TEST_API_KEY, sync_mode=True, capture_mode=kwarg) | ||
| self.assertIs(client.capture_mode, expected) | ||
|
|
||
| def test_client_propagates_mode_to_consumers(self) -> None: | ||
| # Async (non-sync) client builds Consumer threads; assert each carries | ||
| # the resolved mode. | ||
| client = Client(TEST_API_KEY, capture_mode=CaptureMode.V1, send=False, thread=2) | ||
| self.assertEqual(len(client.consumers), 2) | ||
| for consumer in client.consumers: | ||
| self.assertIs(consumer.capture_mode, CaptureMode.V1) | ||
|
|
||
| def test_consumer_defaults_to_v0(self) -> None: | ||
| consumer = Consumer(None, TEST_API_KEY) | ||
| self.assertIs(consumer.capture_mode, CaptureMode.V0) | ||
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.