diff --git a/CHANGELOG.md b/CHANGELOG.md index be00c7a..d0b795d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ * **api:** add native server batch overloads and align with client specs v0.13.0 +### Changed + +* deprecate the `environment` argument; the API key selects the environment and `environment` is no longer sent + ## [0.2.0](https://github.com/altertable-ai/altertable-python/compare/altertable-v0.1.0...altertable-v0.2.0) (2026-03-09) diff --git a/README.md b/README.md index a73fc30..c8dc931 100644 --- a/README.md +++ b/README.md @@ -48,13 +48,20 @@ not impose a client-side batch-size limit. ```python client.track([ - {"event": "button_clicked", "distinct_id": "user_123", "environment": "production"}, - {"event": "checkout_started", "distinct_id": "user_123", "environment": "production"}, + {"event": "button_clicked", "distinct_id": "user_123"}, + {"event": "checkout_started", "distinct_id": "user_123"}, ]) ``` Pass arrays to `identify` and `alias` for the same pass-through behavior. +### Environment + +The API key selects the Product Analytics environment. The `environment` +argument is deprecated and ignored, and `environment` fields in options and +batches are never sent. Replace unbound legacy API keys with environment-bound +keys before upgrading. + ### Audience measurement With an environment-bound API key, pass `mode="audience"` to send events without diff --git a/src/altertable/client.py b/src/altertable/client.py index a80bbe6..1df1a73 100644 --- a/src/altertable/client.py +++ b/src/altertable/client.py @@ -4,6 +4,9 @@ TrackingMode = Literal["product", "audience"] +def _without_environment(payload: Dict[str, Any]) -> Dict[str, Any]: + return {key: value for key, value in payload.items() if key != "environment"} + class AltertableError(Exception): pass @@ -19,15 +22,15 @@ def __init__(self, message: str, cause: Exception): self.cause = cause class Altertable: - def __init__(self, api_key: str, server_url: str = "https://api.altertable.ai", environment: str = "production", timeout: int = 10000, *, mode: TrackingMode = "product"): + def __init__(self, api_key: str, server_url: str = "https://api.altertable.ai", environment: Optional[str] = None, timeout: int = 10000, *, mode: TrackingMode = "product"): """ Initialize the Altertable client. :param api_key: API key used to authenticate with the Altertable API. :param server_url: Base URL of the Altertable API server. - :param environment: Environment name (for example, "production" or "staging"). + :param environment: Ignored; kept so existing calls keep working. The API key determines the environment. :param mode: Collection mode, fixed for this client. Audience mode sends events - without identity or environment fields and ignores identify and alias. + without identity fields and ignores identify and alias. :param timeout: Request timeout in milliseconds. This value is converted to seconds before being passed to the underlying `requests` session. """ @@ -36,7 +39,6 @@ def __init__(self, api_key: str, server_url: str = "https://api.altertable.ai", self._mode: TrackingMode = mode self.api_key = api_key self.server_url = server_url.rstrip("/") - self.environment = environment self.timeout = timeout / 1000.0 self.session = requests.Session() self.session.headers.update({"X-API-Key": self.api_key, "Content-Type": "application/json"}) @@ -51,7 +53,7 @@ def _ignore_identity(self) -> bool: def _apply_mode(self, payload: Dict[str, Any]) -> Dict[str, Any]: # The client owns the mode: raw batches and options cannot select another - # mode or restore identity and environment fields. + # mode or restore identity fields. if self._mode == "product": return {key: value for key, value in payload.items() if key != "mode"} return { @@ -69,6 +71,8 @@ def _get_timestamp(self, timestamp: Optional[Union[str, int]] = None) -> str: return timestamp def _post(self, endpoint: str, payload: Union[Dict[str, Any], List[Dict[str, Any]]]): + # The API key selects the environment, so the deprecated field is never sent. + payload = [_without_environment(record) for record in payload] if isinstance(payload, list) else _without_environment(payload) try: response = self.session.post(f"{self.server_url}{endpoint}", json=payload, timeout=self.timeout) if not response.ok: @@ -91,7 +95,6 @@ def track(self, event: Union[str, List[Dict[str, Any]]], distinct_id: Optional[s payload = { "timestamp": self._get_timestamp(options.get("timestamp")), "event": event, - "environment": options.get("environment", self.environment), "distinct_id": distinct_id, "properties": options.get("properties", {}) } @@ -111,7 +114,6 @@ def identify(self, distinct_id: Union[str, List[Dict[str, Any]]], options: Optio options = options or {} payload = { "timestamp": self._get_timestamp(options.get("timestamp")), - "environment": options.get("environment", self.environment), "distinct_id": distinct_id, } if "traits" in options: @@ -134,7 +136,6 @@ def alias(self, distinct_id: Union[str, List[Dict[str, Any]]], new_user_id: Opti options = options or {} payload = { "timestamp": self._get_timestamp(options.get("timestamp")), - "environment": options.get("environment", self.environment), "distinct_id": distinct_id, "new_user_id": new_user_id, } diff --git a/tests/test_altertable.py b/tests/test_altertable.py index a681598..6cbcff7 100644 --- a/tests/test_altertable.py +++ b/tests/test_altertable.py @@ -1,3 +1,4 @@ +import copy import os import pytest from unittest.mock import Mock @@ -32,7 +33,35 @@ def test_alias(client): ) assert response.get("ok") is True -def test_track_overload_passes_all_payloads_through_without_chunking(): +def test_environment_is_ignored_and_never_sent_from_product_requests(): + client = Altertable("test_pk_abc123", MOCK_BASE_URL, "staging") + response = Mock(ok=True) + response.json.return_value = {"ok": True} + client.session.post = Mock(return_value=response) + + track_options = { + "environment": "event-env", + "properties": {"environment": "business-value"}, + } + identify_options = { + "environment": "identify-env", + "traits": {"environment": "trait-business-value"}, + } + original_track_options = copy.deepcopy(track_options) + original_identify_options = copy.deepcopy(identify_options) + client.track("tracked", "user-1", track_options) + client.identify("user-1", identify_options) + client.alias("user-1", "user-2", {"environment": "alias-env"}) + + payloads = [call.kwargs["json"] for call in client.session.post.call_args_list] + assert all("environment" not in payload for payload in payloads) + assert payloads[0]["properties"]["environment"] == "business-value" + assert payloads[1]["traits"]["environment"] == "trait-business-value" + assert track_options == original_track_options + assert identify_options == original_identify_options + + +def test_raw_batches_strip_environment_without_mutating_caller_payloads(): client = Altertable("test_pk_abc123", server_url=MOCK_BASE_URL) response = Mock(ok=True) response.json.return_value = {"ok": True} @@ -42,12 +71,17 @@ def test_track_overload_passes_all_payloads_through_without_chunking(): for index in range(101) ] + original = [payload.copy() for payload in payloads] assert client.track(payloads) == {"ok": True} client.session.post.assert_called_once() - assert client.session.post.call_args.kwargs["json"] == payloads + assert client.session.post.call_args.kwargs["json"] == [ + {"event": f"event-{index}", "distinct_id": f"user-{index}"} + for index in range(101) + ] + assert payloads == original @pytest.mark.parametrize("method_name, endpoint", [("identify", "/identify"), ("alias", "/alias")]) -def test_other_batch_overloads_pass_payloads_through(method_name, endpoint): +def test_identity_batches_strip_environment_without_mutating_caller(method_name, endpoint): client = Altertable("test_pk_abc123", server_url=MOCK_BASE_URL) response = Mock(ok=True) response.json.return_value = {"ok": True} @@ -56,7 +90,8 @@ def test_other_batch_overloads_pass_payloads_through(method_name, endpoint): assert getattr(client, method_name)(payloads) == {"ok": True} assert client.session.post.call_args.args[0] == f"{MOCK_BASE_URL}{endpoint}" - assert client.session.post.call_args.kwargs["json"] == payloads + assert client.session.post.call_args.kwargs["json"] == [{"distinct_id": "user-1"}] + assert payloads == [{"distinct_id": "user-1", "environment": "test"}] def test_authentication_error(): client = Altertable("wrong_api_key", server_url=MOCK_BASE_URL)