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(data-warehouse): implement streamelements import source (#72656)

Tom Owers8ae2c6a9f89b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index bd0eefec3ec3..b6a6d00e4e40 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -526,6 +526,7 @@ the row lists both.
| statuspage | HTTP | requests | ✅ |
| stigg | HTTP | requests | ✅ |
| stockdata | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| streamelements | HTTP | requests | ✅ |
| stripe | HTTP (vendor SDK) + Webhook | stripe (StripeClient + RequestsClient) + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| stytch | HTTP | requests | ✅ |
| sumo_logic | HTTP | requests | ✅ |
@@ -954,7 +955,6 @@ doesn't conflict with concurrent PRs.
- spotify_ads
- statsig
- strava
-- streamelements
- streamlabs
- sumsub
- superwall
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/streamelements.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/streamelements.py
index fd6275bc02aa..56bbaa15bc2e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/streamelements.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/streamelements.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class StreamElementsSourceConfig(config.Config):
- pass
+ api_token: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/canonical_descriptions.py
new file mode 100644
index 000000000000..a44251b20d08
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/canonical_descriptions.py
@@ -0,0 +1,130 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://dev.streamelements.com/"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "tips": {
+ "description": "A tip (donation) received on the channel's tipping page, including the donor, amount, currency and payment provider.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "_id": "Unique identifier of the tip.",
+ "channel": "Identifier of the StreamElements channel that received the tip.",
+ "donation": "Donation details: the donor's username and email, the message, the amount and the currency.",
+ "provider": "Payment provider the tip was processed through (e.g. paypal, stripe).",
+ "status": "Processing status of the tip (e.g. success).",
+ "approved": "Moderation state of the tip (e.g. allowed).",
+ "deleted": "Whether the tip has been deleted.",
+ "transactionId": "Identifier of the payment transaction at the provider.",
+ "createdAt": "When the tip was received.",
+ "updatedAt": "When the tip was last updated.",
+ },
+ },
+ "activities": {
+ "description": "An event from the channel's activity feed: follows, tips, hosts, cheers, raids, subscriptions, sponsorships, super chats, loyalty redemptions and merch orders.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "_id": "Unique identifier of the activity.",
+ "channel": "Identifier of the StreamElements channel the activity belongs to.",
+ "type": "Activity type: follow, tip, host, cheer, raid, subscriber, sponsor, superchat, redemption or merch.",
+ "provider": "Streaming platform the activity originated from (e.g. twitch, youtube).",
+ "data": "Type-specific payload, such as the username, amount, message and subscription tier.",
+ "createdAt": "When the activity happened.",
+ },
+ },
+ "store_redemptions": {
+ "description": "A redemption of a loyalty store item, including the redeemer and any input they provided.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "_id": "Unique identifier of the redemption.",
+ "channel": "Identifier of the StreamElements channel the redemption belongs to.",
+ "item": "The store item that was redeemed.",
+ "redeemer": "The user who redeemed the item.",
+ "input": "Answers the redeemer provided for the item's input prompts.",
+ "createdAt": "When the item was redeemed.",
+ "updatedAt": "When the redemption was last updated.",
+ },
+ },
+ "store_items": {
+ "description": "An item in the channel's loyalty store that viewers can redeem with loyalty points.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "_id": "Unique identifier of the store item.",
+ "channel": "Identifier of the StreamElements channel the item belongs to.",
+ "name": "Display name of the item.",
+ "description": "Description of the item shown in the store.",
+ "cost": "Loyalty point cost to redeem the item.",
+ "quantity": "Stock configuration for the item.",
+ "enabled": "Whether the item is currently available in the store.",
+ "createdAt": "When the item was created.",
+ "updatedAt": "When the item was last updated.",
+ },
+ },
+ "points_leaderboard": {
+ "description": "The channel's current loyalty points leaderboard, one row per viewer with their spendable points balance.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "username": "Viewer's username on the streaming platform.",
+ "points": "Viewer's current spendable loyalty points balance.",
+ },
+ },
+ "points_alltime_leaderboard": {
+ "description": "The channel's all-time loyalty points leaderboard, one row per viewer with the total points they have ever earned.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "username": "Viewer's username on the streaming platform.",
+ "points": "Total loyalty points the viewer has earned all-time.",
+ },
+ },
+ "bot_commands": {
+ "description": "A custom chatbot command configured for the channel.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "_id": "Unique identifier of the command.",
+ "channel": "Identifier of the StreamElements channel the command belongs to.",
+ "command": "The chat keyword that triggers the command.",
+ "reply": "The bot's response text.",
+ "aliases": "Alternative keywords that trigger the command.",
+ "accessLevel": "Minimum user level allowed to use the command.",
+ "cooldown": "Per-user and global cooldowns in seconds.",
+ "cost": "Loyalty point cost to use the command.",
+ "enabled": "Whether the command is enabled.",
+ "createdAt": "When the command was created.",
+ "updatedAt": "When the command was last updated.",
+ },
+ },
+ "bot_timers": {
+ "description": "A chatbot timer that posts a message on an interval while the channel is live or offline.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "_id": "Unique identifier of the timer.",
+ "channel": "Identifier of the StreamElements channel the timer belongs to.",
+ "name": "Display name of the timer.",
+ "message": "Message the bot posts when the timer fires.",
+ "chatLines": "Minimum chat lines required between two firings.",
+ "online": "Enabled state and interval in minutes while the stream is live.",
+ "offline": "Enabled state and interval in minutes while the stream is offline.",
+ "enabled": "Whether the timer is enabled.",
+ "createdAt": "When the timer was created.",
+ "updatedAt": "When the timer was last updated.",
+ },
+ },
+ "channel": {
+ "description": "Details of the StreamElements channel the connected token belongs to.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "_id": "Unique identifier of the channel.",
+ "username": "Channel's username on the streaming platform.",
+ "displayName": "Channel's display name.",
+ "provider": "Streaming platform the channel is linked to (e.g. twitch, youtube).",
+ "providerId": "Channel's identifier on the streaming platform.",
+ "email": "Email address associated with the StreamElements account.",
+ "isPartner": "Whether the channel is a platform partner.",
+ "broadcasterType": "Broadcaster tier on the streaming platform.",
+ "country": "Country the channel is registered in.",
+ "createdAt": "When the StreamElements account was created.",
+ "updatedAt": "When the channel details were last updated.",
+ },
+ },
+}
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
new file mode 100644
index 000000000000..84a1987b889d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/settings.py
@@ -0,0 +1,144 @@
+from dataclasses import dataclass, field
+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"
+
+# Documented cap for tips/activities list endpoints (limit must be 1-100).
+DEFAULT_PAGE_SIZE = 100
+# Points leaderboards accept bigger pages: verified live that limit=1000 returns rows while
+# larger values silently return an empty list.
+LEADERBOARD_PAGE_SIZE = 1000
+
+# The activity feed only returns events whose type is listed, so ask for every documented type.
+ACTIVITY_TYPES = [
+ "follow",
+ "tip",
+ "host",
+ "cheer",
+ "raid",
+ "subscriber",
+ "sponsor",
+ "superchat",
+ "redemption",
+ "merch",
+]
+
+# How an endpoint is fetched. Routed on in `streamelements.py:streamelements_source`.
+# "offset" -> limit/offset pagination, optionally unwrapping a body key via data_selector
+# "activities" -> GET /activities/{channel}, paged by walking the `before` datetime bound down
+# "single" -> whole result in one un-paginated response
+EndpointKind = Literal["offset", "activities", "single"]
+
+
+@dataclass
+class StreamElementsEndpointConfig:
+ name: str
+ # "{channel}" is replaced with the channel id resolved from GET /channels/me.
+ path: str
+ kind: EndpointKind
+ primary_keys: list[str] = field(default_factory=lambda: ["_id"])
+ # Body key the row list is wrapped under (e.g. {"docs": [...]}); None for bare-array bodies.
+ data_selector: Optional[str] = None
+ # jsonpath of the grand-total count in wrapped responses, used to stop offset pagination.
+ total_path: Optional[str] = None
+ # False only for endpoints returning a single object rather than a list of rows.
+ returns_list: bool = True
+ # Stable (never-changing) datetime field used for datetime partitioning.
+ partition_key: Optional[str] = None
+ page_size: int = DEFAULT_PAGE_SIZE
+ # Static query params sent on every request.
+ params: dict[str, Any] = field(default_factory=dict)
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+
+ @property
+ def supports_incremental(self) -> bool:
+ return len(self.incremental_fields) > 0
+
+
+STREAMELEMENTS_ENDPOINTS: dict[str, StreamElementsEndpointConfig] = {
+ "tips": StreamElementsEndpointConfig(
+ name="tips",
+ path="/tips/{channel}",
+ kind="offset",
+ data_selector="docs",
+ total_path="total",
+ partition_key="createdAt",
+ # createdAt ascending is a documented sort value, keeping offset pages stable while
+ # new tips arrive mid-sync and letting the incremental watermark advance per batch.
+ params={"sort": "createdAt"},
+ incremental_fields=[incremental_field("createdAt")],
+ ),
+ "activities": StreamElementsEndpointConfig(
+ name="activities",
+ path="/activities/{channel}",
+ kind="activities",
+ partition_key="createdAt",
+ # The bounds and origin are required even when defaults would do; origin is any
+ # caller-chosen identifier.
+ params={
+ "types": ACTIVITY_TYPES,
+ "mincheer": 0,
+ "minhost": 0,
+ "minsub": 0,
+ "mintip": 0,
+ "origin": "posthog",
+ },
+ incremental_fields=[incremental_field("createdAt")],
+ ),
+ "store_redemptions": StreamElementsEndpointConfig(
+ name="store_redemptions",
+ path="/store/{channel}/redemptions",
+ kind="offset",
+ data_selector="docs",
+ total_path="total",
+ partition_key="createdAt",
+ ),
+ "store_items": StreamElementsEndpointConfig(
+ name="store_items",
+ path="/store/{channel}/items",
+ kind="offset",
+ ),
+ "points_leaderboard": StreamElementsEndpointConfig(
+ name="points_leaderboard",
+ path="/points/{channel}/top",
+ kind="offset",
+ data_selector="users",
+ total_path="_total",
+ primary_keys=["username"],
+ page_size=LEADERBOARD_PAGE_SIZE,
+ ),
+ "points_alltime_leaderboard": StreamElementsEndpointConfig(
+ name="points_alltime_leaderboard",
+ path="/points/{channel}/alltime",
+ kind="offset",
+ data_selector="users",
+ total_path="_total",
+ primary_keys=["username"],
+ page_size=LEADERBOARD_PAGE_SIZE,
+ ),
+ "bot_commands": StreamElementsEndpointConfig(
+ name="bot_commands",
+ path="/bot/commands/{channel}",
+ kind="single",
+ ),
+ "bot_timers": StreamElementsEndpointConfig(
+ name="bot_timers",
+ path="/bot/timers/{channel}",
+ kind="single",
+ ),
+ "channel": StreamElementsEndpointConfig(
+ name="channel",
+ path="/channels/me",
+ kind="single",
+ returns_list=False,
+ ),
+}
+
+ENDPOINTS = tuple(STREAMELEMENTS_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in STREAMELEMENTS_ENDPOINTS.items()
+}
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 5c0ad53aa9b6..181da6ba1d99 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
@@ -1,21 +1,51 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.streamelements import (
StreamElementsSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.streamelements.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.streamelements.streamelements import (
+ StreamElementsResumeConfig,
+ streamelements_source,
+ validate_credentials as validate_streamelements_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class StreamElementsSource(SimpleSource[StreamElementsSourceConfig]):
+class StreamElementsSource(ResumableSource[StreamElementsSourceConfig, StreamElementsResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
+ supported_versions = ("v2",)
+ default_version = "v2"
+ api_docs_url = "https://dev.streamelements.com/"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.STREAMELEMENTS
@@ -25,9 +55,77 @@ class StreamElementsSource(SimpleSource[StreamElementsSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.STREAM_ELEMENTS,
category=DataWarehouseSourceCategory.COMMUNICATION,
- keywords=["twitch", "streaming"],
+ keywords=["twitch", "streaming", "tips", "donations"],
label="StreamElements",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Sync tips, activity feed events, loyalty points, store redemptions and chatbot settings from StreamElements into the PostHog Data warehouse.
+
+Use the channel JWT token from your StreamElements dashboard: open your account page, enable **Show secrets** under **Channels**, then copy the JWT token. An OAuth2 access token also works if it has the `channel:read`, `tips:read`, `activities:read`, `loyalty:read` and `store:read` scopes.
+""",
iconPath="/static/services/streamelements.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/streamelements",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="JWT token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.streamelements.com": "Your StreamElements token is invalid or expired. Copy a fresh JWT token from the StreamElements dashboard and reconnect.",
+ "403 Client Error: Forbidden for url: https://api.streamelements.com": "Your StreamElements token does not have access to this resource. Check the token scopes and try again.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.streamelements.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: StreamElementsSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Merge only: resume re-fetches the last checkpointed page and the activities window
+ # walk overlaps page boundaries by design, so append mode would duplicate rows.
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=ENDPOINTS)
+
+ def validate_credentials(
+ self, config: StreamElementsSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_streamelements_credentials(config.api_token)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[StreamElementsResumeConfig]:
+ return ResumableSourceManager[StreamElementsResumeConfig](inputs, StreamElementsResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: StreamElementsSourceConfig,
+ resumable_source_manager: ResumableSourceManager[StreamElementsResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return streamelements_source(
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ 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
+ else None,
)
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
new file mode 100644
index 000000000000..e5d9c6f3bc62
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/streamelements.py
@@ -0,0 +1,282 @@
+import dataclasses
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+import requests
+from dateutil import parser as dateutil_parser
+from requests import Request, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
+ OffsetPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+)
+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,
+)
+
+
+class StreamElementsResumeConfig:
+ # Paginator snapshot: {"offset": int} for offset endpoints, {"before": int} for activities.
+ paginator_state: dict[str, Any]
+
+
+def _to_epoch_ms(value: Any) -> Optional[int]:
+ """Convert an incremental cursor value (datetime/date/epoch/ISO string) to epoch
+ milliseconds for StreamElements' after/before datetime filters."""
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return round(dt.timestamp() * 1000)
+ if isinstance(value, date):
+ return round(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp() * 1000)
+ if isinstance(value, str):
+ try:
+ return int(value)
+ except ValueError:
+ pass
+ try:
+ return _to_epoch_ms(dateutil_parser.parse(value))
+ except (ValueError, OverflowError):
+ return None
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
+
+
+class StreamElementsActivitiesPaginator(BasePaginator):
+ """Datetime-window paginator for GET /activities/{channel}.
+
+ The activity feed has no offset or cursor pagination and no sort param: each request
+ returns up to ``limit`` of the newest events inside the ``after``/``before`` window. We
+ page by walking the ``before`` bound down to just past the oldest event of each page
+ (+1ms so events sharing that millisecond aren't skipped at the page boundary; the
+ resulting overlap dedupes on the ``_id`` merge key). ``after`` stays fixed, so on
+ incremental syncs the server bounds the walk at the watermark.
+ """
+
+ def __init__(self, page_size: int, initial_before_ms: int) -> None:
+ super().__init__()
+ self._page_size = page_size
+ self._next_before_ms = initial_before_ms
+
+ def init_request(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ request.params["limit"] = self._page_size
+ request.params["before"] = self._next_before_ms
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ if not data or len(data) < self._page_size:
+ self._has_next_page = False
+ return
+
+ created_values = [
+ _to_epoch_ms(item.get("createdAt")) for item in data if isinstance(item, dict) and item.get("createdAt")
+ ]
+ timestamps = [value for value in created_values if value is not None]
+ if not timestamps:
+ # A full page without parseable createdAt values means the response shape changed;
+ # stop rather than loop on the same window forever.
+ self._has_next_page = False
+ return
+
+ next_before = min(timestamps) + 1
+ if next_before >= self._next_before_ms:
+ # Force progress when a whole page shares the millisecond just below the current
+ # bound; any events beyond page_size in that same millisecond are skipped.
+ next_before = self._next_before_ms - 1
+ self._next_before_ms = next_before
+ self._has_next_page = True
+
+ def update_request(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ request.params["limit"] = self._page_size
+ request.params["before"] = self._next_before_ms
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ return {"before": self._next_before_ms} if self._has_next_page else None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ before = state.get("before")
+ if before is not None:
+ self._next_before_ms = int(before)
+ self._has_next_page = True
+
+ def __str__(self) -> str:
+ return f"StreamElementsActivitiesPaginator(before={self._next_before_ms})"
+
+
+def _tracked_session(api_token: str) -> requests.Session:
+ """Build the session every StreamElements request runs on.
+
+ ``capture=False``: responses carry donor email addresses, tip and chat message text,
+ activity payloads and redemption input — free-text the name-based scrubbers can't
+ recognise, so their bodies must stay out of HTTP sample capture (still metered and logged).
+ """
+ return make_tracked_session(redact_values=(api_token,), capture=False)
+
+
+def _client_config(api_token: str) -> ClientConfig:
+ return {
+ "base_url": STREAMELEMENTS_BASE_URL,
+ "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.
+ "auth": {"type": "bearer", "token": api_token},
+ "session": _tracked_session(api_token),
+ }
+
+
+def get_channel_id(api_token: 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",
+ headers={"Authorization": f"Bearer {api_token}", "Accept": "application/json"},
+ timeout=30,
+ )
+ response.raise_for_status()
+ channel_id = response.json().get("_id")
+ if not channel_id:
+ raise ValueError("StreamElements did not return a channel id for this token")
+ return str(channel_id)
+
+
+def validate_credentials(api_token: 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",
+ headers={"Authorization": f"Bearer {api_token}", "Accept": "application/json"},
+ timeout=10,
+ )
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+ if response.status_code in (401, 403):
+ return (
+ False,
+ "Invalid StreamElements token. Copy the JWT token from your StreamElements dashboard and try again.",
+ )
+ if not response.ok:
+ return False, f"StreamElements API error: {response.status_code} {response.text}"
+
+ return True, None
+
+
+def _now_ms() -> int:
+ return round(datetime.now(tz=UTC).timestamp() * 1000)
+
+
+def streamelements_source(
+ api_token: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[StreamElementsResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = STREAMELEMENTS_ENDPOINTS[endpoint]
+
+ path = config.path
+ if "{channel}" in path:
+ path = path.format(channel=get_channel_id(api_token))
+
+ params: dict[str, Any] = dict(config.params)
+ use_incremental = should_use_incremental_field and config.supports_incremental
+ if use_incremental:
+ # after accepts epoch milliseconds; on the first sync the watermark is None and the
+ # param is dropped, fetching from the beginning of history.
+ params["after"] = {
+ "type": "incremental",
+ "cursor_path": "createdAt",
+ "convert": _to_epoch_ms,
+ }
+
+ paginator: BasePaginator
+ if config.kind == "offset":
+ paginator = OffsetPaginator(limit=config.page_size, total_path=config.total_path)
+ elif config.kind == "activities":
+ paginator = StreamElementsActivitiesPaginator(page_size=config.page_size, initial_before_ms=_now_ms())
+ else:
+ paginator = SinglePagePaginator()
+
+ endpoint_config: Endpoint = {
+ "path": path,
+ "params": params,
+ "paginator": paginator,
+ "data_selector": config.data_selector,
+ # Fail loud when the response shape changes instead of silently syncing 0 rows —
+ # except for single-object endpoints, whose dict body intentionally becomes one row.
+ "data_selector_required": config.returns_list,
+ }
+
+ rest_config: RESTAPIConfig = {
+ "client": _client_config(api_token),
+ "resources": [
+ {
+ "name": endpoint,
+ "table_name": endpoint,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if use_incremental else "replace",
+ "endpoint": endpoint_config,
+ "table_format": "delta",
+ }
+ ],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if config.kind != "single" and resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None:
+ initial_paginator_state = resume.paginator_state
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Persist only while a next page remains. Both paginators snapshot the NEXT page to
+ # fetch and the hook runs after the current page is yielded, so a crash between pages
+ # never skips rows.
+ if state:
+ resumable_source_manager.save_state(StreamElementsResumeConfig(paginator_state=state))
+
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value if use_incremental else None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=config.primary_keys,
+ # Tips request sort=createdAt (documented ascending sort). Activities have no sort
+ # param and arrive newest-first inside each window, so with sort_mode="desc" the
+ # pipeline only commits the cursor watermark once a sync fully completes; the `after`
+ # server filter (not row ordering) is what bounds each incremental fetch. Live
+ # ordering semantics were not verified against the API as no test credentials were
+ # available.
+ sort_mode="desc" if config.kind == "activities" else "asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
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
new file mode 100644
index 000000000000..70cc8332a149
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/tests/test_streamelements.py
@@ -0,0 +1,368 @@
+import json
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.streamelements.settings import (
+ ENDPOINTS,
+ STREAMELEMENTS_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.streamelements.streamelements import (
+ StreamElementsResumeConfig,
+ _to_epoch_ms,
+ get_channel_id,
+ streamelements_source,
+ validate_credentials,
+)
+
+# Every StreamElements request — the pipeline client session, channel resolution and the
+# credential probe — runs on a session built by the shared _tracked_session factory, which
+# calls make_tracked_session in the streamelements module. Patch that one symbol.
+SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.streamelements.streamelements.make_tracked_session"
+
+CHANNEL_ID = "5b2e2007760aeb7729487dab"
+
+
+def _response(payload: Any, status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(payload).encode()
+ return resp
+
+
+def _make_manager(resume_state: StreamElementsResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+ """Wire a mock session and capture each request's url + params AT SEND TIME.
+
+ ``request.params`` is a single dict mutated in place across pages, so inspecting it after the
+ run shows only the final state — snapshot a copy when each request is prepared instead.
+ Channel resolution goes through ``.get``; the pipeline goes through ``.prepare_request``/``.send``.
+ """
+ session.headers = {}
+ session.get.return_value = _response({"_id": CHANNEL_ID})
+ snapshots: list[dict[str, Any]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ snapshots.append({"url": request.url, "params": dict(request.params or {})})
+ return mock.MagicMock()
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ 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 _rows(source_response) -> list[dict[str, Any]]:
+ return [row for page in source_response.items() for row in page]
+
+
+def _tip(i: int, created_at: str = "2024-01-01T00:00:00.000Z") -> dict[str, Any]:
+ return {"_id": f"tip{i}", "createdAt": created_at, "donation": {"amount": i}}
+
+
+def _activity(i: int, created_at: str) -> dict[str, Any]:
+ return {"_id": f"act{i}", "type": "follow", "createdAt": created_at}
+
+
+class TestToEpochMs:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (None, None),
+ (datetime(2019, 9, 6, 15, 54, 10, 202000, tzinfo=UTC), 1567785250202),
+ (datetime(2019, 9, 6, 15, 54, 10, 202000), 1567785250202),
+ (date(2019, 9, 6), 1567728000000),
+ (1567785250202, 1567785250202),
+ ("1567785250202", 1567785250202),
+ ("2019-09-06T15:54:10.202Z", 1567785250202),
+ ("nope", None),
+ ],
+ )
+ def test_to_epoch_ms(self, value: Any, expected: Any) -> None:
+ assert _to_epoch_ms(value) == expected
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected_valid",
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ (500, False),
+ ],
+ )
+ @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")
+ assert valid is expected_valid
+
+ @mock.patch(SESSION_PATCH)
+ def test_request_exception_returns_error(self, mock_session: mock.MagicMock) -> None:
+ import requests
+
+ mock_session.return_value.get.side_effect = requests.exceptions.ConnectionError("boom")
+ valid, message = validate_credentials("jwt")
+ assert valid is False
+ assert message == "boom"
+
+
+class TestCaptureDisabled:
+ """StreamElements payloads carry donor emails and free-text tip/chat messages the name-based
+ scrubbers can't recognise, so every session must be built with capture=False. These lock that
+ in for the pipeline client session and both direct probe paths."""
+
+ @mock.patch(SESSION_PATCH)
+ def test_pipeline_session_disables_capture(self, mock_session: mock.MagicMock) -> None:
+ session = mock_session.return_value
+ _wire(session, [_response({"docs": [_tip(1)], "total": 1})])
+ _rows(_source("tips", _make_manager()))
+
+ assert mock_session.call_args_list # sanity: the pipeline built at least one session
+ for call in mock_session.call_args_list:
+ assert call.kwargs.get("capture") is False
+ assert call.kwargs.get("redact_values") == ("jwt",)
+
+ @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")
+ 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")
+ mock_session.assert_called_once_with(redact_values=("jwt",), capture=False)
+
+
+class TestTips:
+ @mock.patch(SESSION_PATCH)
+ def test_paginates_offsets_until_total(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response({"docs": [_tip(i) for i in range(100)], "total": 150}),
+ _response({"docs": [_tip(100 + i) for i in range(50)], "total": 150}),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source("tips", manager))
+
+ assert session.send.call_count == 2
+ assert len(rows) == 150
+ assert snapshots[0]["url"].endswith(f"/tips/{CHANNEL_ID}")
+ assert snapshots[0]["params"]["offset"] == 0
+ assert snapshots[0]["params"]["limit"] == 100
+ assert snapshots[0]["params"]["sort"] == "createdAt"
+ assert snapshots[1]["params"]["offset"] == 100
+ # The next offset is checkpointed after each yielded page; the final page saves nothing.
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0] == StreamElementsResumeConfig(paginator_state={"offset": 100})
+
+ @mock.patch(SESSION_PATCH)
+ def test_resumes_from_saved_offset(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response({"docs": [_tip(1)], "total": 301})])
+
+ _rows(_source("tips", _make_manager(StreamElementsResumeConfig(paginator_state={"offset": 300}))))
+ assert snapshots[0]["params"]["offset"] == 300
+
+ @mock.patch(SESSION_PATCH)
+ def test_incremental_adds_after_filter(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response({"docs": [_tip(1)], "total": 1})])
+
+ _rows(
+ _source(
+ "tips",
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2019, 9, 6, 15, 54, 10, 202000, tzinfo=UTC),
+ )
+ )
+ assert snapshots[0]["params"]["after"] == 1567785250202
+
+ @mock.patch(SESSION_PATCH)
+ def test_full_refresh_omits_after_filter(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response({"docs": [_tip(1)], "total": 1})])
+
+ _rows(_source("tips", _make_manager(), should_use_incremental_field=False))
+ assert "after" not in snapshots[0]["params"]
+
+ @mock.patch(SESSION_PATCH)
+ def test_unexpected_body_shape_fails_loud(self, MockSession: mock.MagicMock) -> None:
+ # A bare array where {"docs": [...]} is expected must raise, not silently sync 0 rows.
+ session = MockSession.return_value
+ _wire(session, [_response([_tip(1)])])
+
+ with pytest.raises(ValueError, match="data_selector"):
+ _rows(_source("tips", _make_manager()))
+
+
+class TestActivities:
+ @mock.patch(SESSION_PATCH)
+ def test_walks_before_bound_down_until_short_page(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ # Newest-first pages; the oldest event of page one is at 2024-01-02T00:00:00Z.
+ page_one = [_activity(i, "2024-01-03T00:00:00.000Z") for i in range(99)] + [
+ _activity(99, "2024-01-02T00:00:00.000Z")
+ ]
+ page_two = [_activity(100, "2024-01-01T00:00:00.000Z")]
+ snapshots = _wire(session, [_response(page_one), _response(page_two)])
+
+ manager = _make_manager()
+ rows = _rows(_source("activities", manager))
+
+ assert session.send.call_count == 2
+ assert len(rows) == 101
+ assert snapshots[0]["url"].endswith(f"/activities/{CHANNEL_ID}")
+ assert snapshots[0]["params"]["limit"] == 100
+ # Page two's upper bound moves to just past page one's oldest event so events sharing
+ # that millisecond aren't skipped.
+ oldest_ms = 1704153600000 # 2024-01-02T00:00:00Z
+ assert snapshots[1]["params"]["before"] == oldest_ms + 1
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0] == StreamElementsResumeConfig(
+ paginator_state={"before": oldest_ms + 1}
+ )
+
+ @mock.patch(SESSION_PATCH)
+ def test_resumes_from_saved_before_bound(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response([_activity(1, "2024-01-01T00:00:00.000Z")])])
+
+ _rows(
+ _source("activities", _make_manager(StreamElementsResumeConfig(paginator_state={"before": 1704153600000})))
+ )
+ assert snapshots[0]["params"]["before"] == 1704153600000
+
+ @mock.patch(SESSION_PATCH)
+ def test_incremental_keeps_after_filter_on_every_page(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ page_one = [_activity(i, "2024-01-02T00:00:00.000Z") for i in range(100)]
+ page_two = [_activity(100, "2024-01-01T00:00:00.000Z")]
+ snapshots = _wire(session, [_response(page_one), _response(page_two)])
+
+ _rows(
+ _source(
+ "activities",
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2023-12-01T00:00:00.000Z",
+ )
+ )
+ watermark_ms = 1701388800000 # 2023-12-01T00:00:00Z
+ assert snapshots[0]["params"]["after"] == watermark_ms
+ assert snapshots[1]["params"]["after"] == watermark_ms
+
+ @mock.patch(SESSION_PATCH)
+ def test_full_page_of_identical_timestamps_still_progresses(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ same_ms = "2024-01-02T00:00:00.000Z"
+ snapshots = _wire(
+ session,
+ [
+ _response([_activity(i, same_ms) for i in range(100)]),
+ _response([_activity(200, same_ms)]),
+ ],
+ )
+
+ _rows(
+ _source("activities", _make_manager(StreamElementsResumeConfig(paginator_state={"before": 1704153600001})))
+ )
+ # before must strictly decrease even when a whole page shares the bound's millisecond,
+ # otherwise pagination loops on the same window forever.
+ assert snapshots[1]["params"]["before"] < snapshots[0]["params"]["before"]
+
+
+class TestSinglePageEndpoints:
+ @mock.patch(SESSION_PATCH)
+ def test_bot_commands_returns_bare_array(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response([{"_id": "c1", "command": "test"}])])
+
+ rows = _rows(_source("bot_commands", _make_manager()))
+
+ assert session.send.call_count == 1
+ assert snapshots[0]["url"].endswith(f"/bot/commands/{CHANNEL_ID}")
+ assert [row["_id"] for row in rows] == ["c1"]
+
+ @mock.patch(SESSION_PATCH)
+ def test_channel_yields_single_row_without_channel_resolution(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response({"_id": CHANNEL_ID, "username": "streamer"})])
+
+ rows = _rows(_source("channel", _make_manager()))
+
+ # /channels/me needs no channel id in the path, so get_channel_id (which probes via .get)
+ # is never invoked — the row comes straight from the pipeline .send path.
+ session.get.assert_not_called()
+ assert snapshots[0]["url"].endswith("/channels/me")
+ assert rows == [{"_id": CHANNEL_ID, "username": "streamer"}]
+
+
+class TestLeaderboards:
+ @mock.patch(SESSION_PATCH)
+ def test_points_leaderboard_unwraps_users_with_big_pages(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [_response({"_total": 2, "users": [{"username": "a", "points": 2}, {"username": "b", "points": 1}]})],
+ )
+
+ rows = _rows(_source("points_leaderboard", _make_manager()))
+
+ assert snapshots[0]["url"].endswith(f"/points/{CHANNEL_ID}/top")
+ assert snapshots[0]["params"]["limit"] == 1000
+ assert [row["username"] for row in rows] == ["a", "b"]
+
+
+class TestStreamElementsSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ @mock.patch(SESSION_PATCH)
+ def test_response_metadata_per_endpoint(self, mock_session: mock.MagicMock, endpoint: str) -> None:
+ mock_session.return_value.get.return_value = _response({"_id": CHANNEL_ID})
+ config = STREAMELEMENTS_ENDPOINTS[endpoint]
+ response = _source(endpoint, _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ @mock.patch(SESSION_PATCH)
+ def test_activities_use_desc_sort_mode(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _response({"_id": CHANNEL_ID})
+ assert _source("activities", _make_manager()).sort_mode == "desc"
+
+ @mock.patch(SESSION_PATCH)
+ def test_tips_use_asc_sort_mode(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _response({"_id": CHANNEL_ID})
+ assert _source("tips", _make_manager()).sort_mode == "asc"
+
+ @pytest.mark.parametrize("config", list(STREAMELEMENTS_ENDPOINTS.values()))
+ def test_partition_keys_are_stable_creation_fields(self, config: Any) -> None:
+ if config.partition_key:
+ assert config.partition_key == "createdAt"
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
new file mode 100644
index 000000000000..e8eb0746737a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/streamelements/tests/test_streamelements_source.py
@@ -0,0 +1,142 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.streamelements import (
+ StreamElementsSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.streamelements.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.streamelements.source import StreamElementsSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.streamelements.streamelements import (
+ StreamElementsResumeConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestStreamElementsSource:
+ def setup_method(self) -> None:
+ self.source = StreamElementsSource()
+ self.team_id = 123
+ self.config = StreamElementsSourceConfig(api_token="jwt-token")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.STREAMELEMENTS
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "StreamElements"
+ assert config.label == "StreamElements"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert not config.unreleasedSource
+ assert config.iconPath == "/static/services/streamelements.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_token"]
+
+ def test_api_token_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ token_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig))
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.secret is True
+ assert token_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.streamelements.com/kappa/v2/channels/me",
+ "403 Client Error: Forbidden for url: https://api.streamelements.com/kappa/v2/tips/abc",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.streamelements.com/kappa/v2/tips/abc",
+ ],
+ )
+ def test_non_retryable_errors_ignore_unrelated(self, other_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ incremental = {schema.name for schema in schemas if schema.supports_incremental}
+ # Only tips and activities expose StreamElements' server-side `after` datetime filter.
+ assert incremental == {"tips", "activities"}
+ assert all(schema.supports_append is False for schema in schemas)
+
+ def test_incremental_schemas_advertise_created_at(self) -> None:
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas["tips"].incremental_fields == INCREMENTAL_FIELDS["tips"]
+ assert schemas["points_leaderboard"].incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["tips"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "tips"
+
+ @pytest.mark.parametrize(
+ "mock_return",
+ [
+ (True, None),
+ (False, "Invalid StreamElements token"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.streamelements.source.validate_streamelements_credentials"
+ )
+ def test_validate_credentials(self, mock_validate: mock.MagicMock, mock_return: tuple[bool, str | None]) -> None:
+ 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)
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is StreamElementsResumeConfig
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.streamelements.source.streamelements_source"
+ )
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "tips"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1567780450202
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_token"] == "jwt-token"
+ assert kwargs["endpoint"] == "tips"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1567780450202
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.streamelements.source.streamelements_source"
+ )
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "store_items"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = 1567780450202
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None