Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(warehouse_sources): support StreamElements API version v3 (#74155)

Tom Owers1f25a3a5c4af
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/settings.py
index 84a1987b889d..72df319b806e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/settings.py
@@ -4,7 +4,18 @@ from typing import Any, Literal, Optional
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
from products.warehouse_sources.backend.types import IncrementalField
-STREAMELEMENTS_BASE_URL = "https://api.streamelements.com/kappa/v2"
+# Vendor API versions. The label is the base-URL segment (kappa/<version>): v3 serves every
+# endpoint this source reads at the same paths as v2 and only adds a giveaways collection we
+# don't sync, so the version is a pure base-URL switch with identical response shapes.
+STREAMELEMENTS_V2 = "v2"
+STREAMELEMENTS_V3 = "v3"
+SUPPORTED_VERSIONS = (STREAMELEMENTS_V2, STREAMELEMENTS_V3)
+DEFAULT_VERSION = STREAMELEMENTS_V3
+
+
+def streamelements_base_url(api_version: str) -> str:
+ return f"https://api.streamelements.com/kappa/{api_version}"
+
# Documented cap for tips/activities list endpoints (limit must be 1-100).
DEFAULT_PAGE_SIZE = 100
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/source.py
index e9db918f302c..ce2cd07d4a2a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/source.py
@@ -27,8 +27,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
StreamElementsSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.streamelements.settings import (
+ DEFAULT_VERSION,
ENDPOINTS,
INCREMENTAL_FIELDS,
+ SUPPORTED_VERSIONS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.streamelements.streamelements import (
StreamElementsResumeConfig,
@@ -42,8 +44,8 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
class StreamElementsSource(ResumableSource[StreamElementsSourceConfig, StreamElementsResumeConfig]):
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
- supported_versions = ("v2",)
- default_version = "v2"
+ supported_versions = SUPPORTED_VERSIONS
+ default_version = DEFAULT_VERSION
api_docs_url = "https://dev.streamelements.com/"
@property
@@ -112,7 +114,9 @@ Use the channel JWT token from your StreamElements dashboard: open your account
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
- return validate_streamelements_credentials(config.api_token)
+ # Pre-creation calls pass no pin and resolve to default_version (what new rows are
+ # stamped with); a pinned source revalidates under its own kappa/<version> base URL.
+ return validate_streamelements_credentials(config.api_token, self.resolve_api_version(api_version))
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[StreamElementsResumeConfig]:
return ResumableSourceManager[StreamElementsResumeConfig](inputs, StreamElementsResumeConfig)
@@ -129,6 +133,7 @@ Use the channel JWT token from your StreamElements dashboard: open your account
team_id=inputs.team_id,
job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
+ api_version=self.resolve_api_version(inputs.api_version),
should_use_incremental_field=inputs.should_use_incremental_field,
db_incremental_field_last_value=inputs.db_incremental_field_last_value
if inputs.should_use_incremental_field
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/streamelements.py b/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/streamelements.py
index e5d9c6f3bc62..df0bec052a35 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/streamelements.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/streamelements.py
@@ -23,8 +23,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.streamelements.settings import (
- STREAMELEMENTS_BASE_URL,
STREAMELEMENTS_ENDPOINTS,
+ streamelements_base_url,
)
@@ -133,9 +133,9 @@ def _tracked_session(api_token: str) -> requests.Session:
return make_tracked_session(redact_values=(api_token,), capture=False)
-def _client_config(api_token: str) -> ClientConfig:
+def _client_config(api_token: str, api_version: str) -> ClientConfig:
return {
- "base_url": STREAMELEMENTS_BASE_URL,
+ "base_url": streamelements_base_url(api_version),
"headers": {"Accept": "application/json"},
# Channel JWT tokens and OAuth2 access tokens both go in a Bearer Authorization
# header. Framework auth redacts the value from logs.
@@ -144,10 +144,10 @@ def _client_config(api_token: str) -> ClientConfig:
}
-def get_channel_id(api_token: str) -> str:
+def get_channel_id(api_token: str, api_version: str) -> str:
"""Resolve the 24-hex channel id every other endpoint is scoped by."""
response = _tracked_session(api_token).get(
- f"{STREAMELEMENTS_BASE_URL}/channels/me",
+ f"{streamelements_base_url(api_version)}/channels/me",
headers={"Authorization": f"Bearer {api_token}", "Accept": "application/json"},
timeout=30,
)
@@ -158,11 +158,11 @@ def get_channel_id(api_token: str) -> str:
return str(channel_id)
-def validate_credentials(api_token: str) -> tuple[bool, str | None]:
+def validate_credentials(api_token: str, api_version: str) -> tuple[bool, str | None]:
"""Confirm the token is genuine with one cheap probe of GET /channels/me."""
try:
response = _tracked_session(api_token).get(
- f"{STREAMELEMENTS_BASE_URL}/channels/me",
+ f"{streamelements_base_url(api_version)}/channels/me",
headers={"Authorization": f"Bearer {api_token}", "Accept": "application/json"},
timeout=10,
)
@@ -190,6 +190,7 @@ def streamelements_source(
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[StreamElementsResumeConfig],
+ api_version: str,
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
@@ -197,7 +198,7 @@ def streamelements_source(
path = config.path
if "{channel}" in path:
- path = path.format(channel=get_channel_id(api_token))
+ path = path.format(channel=get_channel_id(api_token, api_version))
params: dict[str, Any] = dict(config.params)
use_incremental = should_use_incremental_field and config.supports_incremental
@@ -229,7 +230,7 @@ def streamelements_source(
}
rest_config: RESTAPIConfig = {
- "client": _client_config(api_token),
+ "client": _client_config(api_token, api_version),
"resources": [
{
"name": endpoint,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/tests/test_streamelements.py b/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/tests/test_streamelements.py
index 70cc8332a149..451ca04df090 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/tests/test_streamelements.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/tests/test_streamelements.py
@@ -61,8 +61,10 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,
return snapshots
-def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any):
- return streamelements_source("jwt", endpoint, team_id=1, job_id="j", resumable_source_manager=manager, **kwargs)
+def _source(endpoint: str, manager: mock.MagicMock, *, api_version: str = "v2", **kwargs: Any):
+ return streamelements_source(
+ "jwt", endpoint, team_id=1, job_id="j", resumable_source_manager=manager, api_version=api_version, **kwargs
+ )
def _rows(source_response) -> list[dict[str, Any]]:
@@ -108,7 +110,7 @@ class TestValidateCredentials:
@mock.patch(SESSION_PATCH)
def test_status_mapping(self, mock_session: mock.MagicMock, status_code: int, expected_valid: bool) -> None:
mock_session.return_value.get.return_value = _response({"_id": CHANNEL_ID}, status_code=status_code)
- valid, _ = validate_credentials("jwt")
+ valid, _ = validate_credentials("jwt", "v2")
assert valid is expected_valid
@mock.patch(SESSION_PATCH)
@@ -116,10 +118,18 @@ class TestValidateCredentials:
import requests
mock_session.return_value.get.side_effect = requests.exceptions.ConnectionError("boom")
- valid, message = validate_credentials("jwt")
+ valid, message = validate_credentials("jwt", "v2")
assert valid is False
assert message == "boom"
+ @pytest.mark.parametrize("api_version", ["v2", "v3"])
+ @mock.patch(SESSION_PATCH)
+ def test_probes_channels_me_under_pinned_version(self, mock_session: mock.MagicMock, api_version: str) -> None:
+ mock_session.return_value.get.return_value = _response({"_id": CHANNEL_ID})
+ validate_credentials("jwt", api_version)
+ url = mock_session.return_value.get.call_args.args[0]
+ assert url == f"https://api.streamelements.com/kappa/{api_version}/channels/me"
+
class TestCaptureDisabled:
"""StreamElements payloads carry donor emails and free-text tip/chat messages the name-based
@@ -140,16 +150,35 @@ class TestCaptureDisabled:
@mock.patch(SESSION_PATCH)
def test_get_channel_id_disables_capture(self, mock_session: mock.MagicMock) -> None:
mock_session.return_value.get.return_value = _response({"_id": CHANNEL_ID})
- get_channel_id("jwt")
+ get_channel_id("jwt", "v2")
mock_session.assert_called_once_with(redact_values=("jwt",), capture=False)
@mock.patch(SESSION_PATCH)
def test_validate_credentials_disables_capture(self, mock_session: mock.MagicMock) -> None:
mock_session.return_value.get.return_value = _response({"_id": CHANNEL_ID})
- validate_credentials("jwt")
+ validate_credentials("jwt", "v2")
mock_session.assert_called_once_with(redact_values=("jwt",), capture=False)
+class TestApiVersion:
+ """The version label is the kappa/<version> base-URL segment. Both the channel-id probe and
+ every pipeline request must target the pinned version so a v2-pinned source stays on v2 while
+ new v3 sources hit /kappa/v3."""
+
+ @pytest.mark.parametrize("api_version", ["v2", "v3"])
+ @mock.patch(SESSION_PATCH)
+ def test_pipeline_requests_target_pinned_version(self, MockSession: mock.MagicMock, api_version: str) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response({"docs": [_tip(1)], "total": 1})])
+
+ _rows(_source("tips", _make_manager(), api_version=api_version))
+
+ # get_channel_id probes /channels/me under the pinned version...
+ assert session.get.call_args.args[0] == f"https://api.streamelements.com/kappa/{api_version}/channels/me"
+ # ...and the paginated request builds its URL from the same base.
+ assert snapshots[0]["url"].startswith(f"https://api.streamelements.com/kappa/{api_version}/tips/")
+
+
class TestTips:
@mock.patch(SESSION_PATCH)
def test_paginates_offsets_until_total(self, MockSession: mock.MagicMock) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/tests/test_streamelements_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/tests/test_streamelements_source.py
index e8eb0746737a..07b37805f323 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/tests/test_streamelements_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/tests/test_streamelements_source.py
@@ -101,7 +101,8 @@ class TestStreamElementsSource:
mock_validate.return_value = mock_return
assert self.source.validate_credentials(self.config, self.team_id) == mock_return
- mock_validate.assert_called_once_with(self.config.api_token)
+ # No pin passed -> resolves to default_version (what new rows are stamped with).
+ mock_validate.assert_called_once_with(self.config.api_token, "v3")
def test_get_resumable_source_manager_binds_resume_config(self) -> None:
manager = self.source.get_resumable_source_manager(mock.MagicMock())
@@ -116,6 +117,7 @@ class TestStreamElementsSource:
inputs.schema_name = "tips"
inputs.should_use_incremental_field = True
inputs.db_incremental_field_last_value = 1567780450202
+ inputs.api_version = "v2"
manager = mock.MagicMock()
self.source.source_for_pipeline(self.config, manager, inputs)
@@ -128,6 +130,28 @@ class TestStreamElementsSource:
assert kwargs["should_use_incremental_field"] is True
assert kwargs["db_incremental_field_last_value"] == 1567780450202
+ @pytest.mark.parametrize(
+ "pin, expected",
+ [
+ (None, "v3"), # unpinned rows follow the default
+ ("v2", "v2"), # existing v2 pins keep hitting kappa/v2
+ ("v3", "v3"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.streamelements.source.streamelements_source"
+ )
+ def test_source_for_pipeline_resolves_api_version(
+ self, mock_source: mock.MagicMock, pin: str | None, expected: str
+ ) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "tips"
+ inputs.api_version = pin
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_source.call_args.kwargs["api_version"] == expected
+
@mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.streamelements.source.streamelements_source"
)