: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add Ably source (#73178)
Tom Owers814e42ffcfef
diff --git a/frontend/public/services/ably.png b/frontend/public/services/ably.pngindex 57813a734073..63e06f6ae6c2 100644Binary files a/frontend/public/services/ably.png and b/frontend/public/services/ably.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 1c2b8ffab495..869335baf190 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -44,6 +44,7 @@ the row lists both.| Source | Comm method | Primary library | Tracked transport || -------------------------------- | --------------------------- | --------------------------------------------------------------- | --------------------------- |+| ably | HTTP | requests + `rest_source.RESTClient` | ✅ || adroll | HTTP | requests | ✅ || agilecrm | HTTP | requests | ✅ || aha | HTTP | requests | ✅ |@@ -678,7 +679,6 @@ doesn't conflict with concurrent PRs.- \*\*Migrate- \*\*Switch- ab_tasty-- ably- abnormal_security- acast- acculynxdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/ably.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/ably.pynew file mode 100644index 000000000000..1aa8c74d5007--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/ably.py@@ -0,0 +1,180 @@+import time+import dataclasses+from datetime import UTC, datetime+from typing import Any, Optional++from requests.exceptions import RequestException++from products.warehouse_sources.backend.temporal.data_imports.sources.ably.settings import BASE_URL, MAX_LIMIT+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.typing import (+ Endpoint,+ EndpointResource,+ IncrementalConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+++class AblyResumeConfig:+ next_url: str+++def split_api_key(api_key: str) -> tuple[str, str]:+ """Ably app API keys are `{app-id}.{key-id}:{key-secret}` — Basic auth splits on the+ first colon (https://ably.com/docs/api/rest-api#authentication)."""+ username, _, password = api_key.partition(":")+ return username, password+++def _add_interval_start(row: dict[str, Any]) -> dict[str, Any]:+ """Ably's `intervalId` is a granularity-dependent string, e.g. `2024-01-15:14:05` for+ `unit=minute`, `2024-01-15:14` for `unit=hour`/`day`/`month`. Derive real columns from it:+ `interval_start` (ISO datetime, for partitioning/display) and `interval_start_ms` (Unix ms,+ the same unit Ably's `start`/`end` stats params use — so it doubles as the incremental+ cursor fed straight back into the next sync's `start` param, no reformatting needed)."""+ parsed = _parse_interval_start(row.get("intervalId"))+ row["interval_start"] = parsed.isoformat() if parsed else None+ row["interval_start_ms"] = int(parsed.timestamp() * 1000) if parsed else None+ return row+++def _parse_interval_start(interval_id: Optional[str]) -> Optional[datetime]:+ if not interval_id:+ return None++ parts = interval_id.split(":")+ date_part = parts[0]++ try:+ year, month, day = (int(component) for component in date_part.split("-"))+ hour = int(parts[1]) if len(parts) > 1 else 0+ minute = int(parts[2]) if len(parts) > 2 else 0+ return datetime(year, month, day, hour, minute, tzinfo=UTC)+ except (ValueError, IndexError):+ # Unexpected intervalId shape — leave the incremental/partition columns unset rather+ # than raising, so a single malformed bucket doesn't fail the whole sync.+ return None+++def get_resource(unit: str, should_use_incremental_field: bool) -> EndpointResource:+ endpoint: Endpoint = {+ "path": "/stats",+ "paginator": "header_link",+ "params": {+ "unit": unit,+ "direction": "forwards",+ "limit": MAX_LIMIT,+ },+ "data_selector_required": True,+ }++ if should_use_incremental_field:+ incremental_config: IncrementalConfig = {+ "start_param": "start",+ "end_param": "end",+ "initial_value": "0",+ # Ably has no open-ended "everything since X" mode — every request needs an+ # explicit end. Bound it to "now" at request-build time (this function runs+ # fresh each sync) rather than relying on the vendor's own end-of-window default.+ "end_value": str(int(time.time() * 1000)),+ }+ endpoint["incremental"] = incremental_config++ return {+ "name": "Stats",+ "table_name": "stats",+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ }+ if should_use_incremental_field+ else "replace",+ "endpoint": endpoint,+ "table_format": "delta",+ "data_map": _add_interval_start,+ }+++def ably_source(+ api_key: str,+ unit: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[AblyResumeConfig],+ db_incremental_field_last_value: Optional[Any],+ should_use_incremental_field: bool = False,+):+ username, password = split_api_key(api_key)++ config: RESTAPIConfig = {+ "client": {+ "base_url": BASE_URL,+ "auth": {+ "type": "http_basic",+ "username": username,+ "password": password,+ },+ # Pin every request to BASE_URL's host and refuse redirects: the Basic auth header+ # carries the Ably key, so a spoofed `Link: rel="next"` target or a cross-origin 3xx+ # must not carry that credential off-host (SSRF). `allowed_hosts=[]` means "same host+ # as base_url only" and also pins paginator and resume URLs.+ "allowed_hosts": [],+ "allow_redirects": False,+ "paginator": "header_link",+ },+ "resource_defaults": {+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ }+ if should_use_incremental_field+ else "replace",+ },+ "resources": [get_resource(unit, should_use_incremental_field)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"next_url": resume_config.next_url}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state and state.get("next_url"):+ resumable_source_manager.save_state(AblyResumeConfig(next_url=str(state["next_url"])))++ return rest_api_resource(+ config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ username, password = split_api_key(api_key)+ if not password:+ return False, "Ably API key is malformed — expected the format `{app-id}.{key-id}:{key-secret}`."++ session = make_tracked_session(redact_values=(password, api_key))+ try:+ response = session.get(+ f"{BASE_URL}/stats",+ params={"limit": 1},+ auth=(username, password),+ )+ except RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code in (401, 403):+ return False, "Ably authentication failed. Please check your API key."+ return False, f"Ably returned an unexpected status code ({response.status_code})."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/canonical_descriptions.pynew file mode 100644index 000000000000..074e2678e1cb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/canonical_descriptions.py@@ -0,0 +1,37 @@+"""Canonical, documentation-sourced descriptions for Ably endpoints and columns.++Sourced from the official Ably REST API reference (https://ably.com/docs/api/rest-api#stats and+https://ably.com/docs/metadata-stats/stats). Keyed by the resource names in `settings.py`+`ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced Ably table. Columns absent+here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Stats": {+ "description": "Aggregated usage statistics for an Ably app over a fixed time interval — "+ "message/connection/channel volumes and API request counts, at the selected granularity.",+ "docs_url": "https://ably.com/docs/metadata-stats/stats",+ "columns": {+ "intervalId": "Identifier of the time interval, formatted according to `unit` "+ "(e.g. `2024-01-15:14` for an hourly bucket).",+ "unit": "Granularity of the interval: minute, hour, day, or month.",+ "interval_start": "UTC start of the interval, derived from `intervalId` and `unit`.",+ "schema": "URI of the JSON schema describing this stats record's shape.",+ "appId": "Identifier of the Ably app the stats belong to.",+ "inProgress": "Interval start time if these stats are for the current, still-accumulating interval.",+ "all": "Aggregate message statistics (count and data size) across all channels and protocols.",+ "inbound": "Breakdown of messages published into the app, by protocol (realtime/rest/webhook) and message type.",+ "outbound": "Breakdown of messages delivered from the app, by protocol and message type.",+ "persisted": "Count and size of messages persisted for the history API.",+ "connections": "Peak, minimum, mean, opened, and refused connection counts for the interval.",+ "channels": "Peak, minimum, mean, and opened channel counts for the interval.",+ "apiRequests": "Count of REST API requests made against the app, broken down as succeeded/failed/refused.",+ "tokenRequests": "Count of token requests made against the app, broken down as succeeded/failed/refused.",+ "pushNotifications": "Count of push notifications sent, broken down by outcome (succeeded/failed/invalid).",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/settings.pynew file mode 100644index 000000000000..a787a3fc9482--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/settings.py@@ -0,0 +1,38 @@+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++ENDPOINTS = ("Stats",)++PRIMARY_KEYS: dict[str, list[str]] = {+ # `intervalId` is unique within a single granularity (`unit`), but the source only ever+ # syncs one selected unit at a time — `unit` is included defensively in case that changes.+ "Stats": ["unit", "intervalId"],+}++# `interval_start_ms` (Unix ms) is derived from `intervalId` (see `_add_interval_start` in+# ably.py) — Ably's own `intervalId` is a granularity-dependent string ("2024-01-15:14:05" for+# minute, "2024-01-15:14" for hour, etc), not directly usable as the `start`/`end` stats params,+# which take Unix ms. Using the same unit here means the watermark from one sync feeds straight+# back into the next sync's `start` param with no reformatting.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ "Stats": [+ {+ "label": "Interval start",+ "type": IncrementalFieldType.DateTime,+ "field": "interval_start_ms",+ "field_type": IncrementalFieldType.Integer,+ },+ ],+}++# `interval_start` (ISO datetime string, also derived from `intervalId`) is used for partitioning+# instead of `interval_start_ms` — partitioning wants an actual datetime-typed column.+PARTITION_KEY = "interval_start"++# https://ably.com/docs/api/rest-api#stats+STATS_UNITS = ("minute", "hour", "day", "month")+DEFAULT_STATS_UNIT = "hour"++# Ably caps /stats page size at 1000 (default 100).+MAX_LIMIT = 1000++BASE_URL = "https://main.realtime.ably.net"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/source.pyindex 6be01b143cff..8fd66bbbc43e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/source.py@@ -1,30 +1,145 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-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.ably.ably import (+ AblyResumeConfig,+ ably_source,+ validate_credentials as validate_ably_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.ably.settings import (+ DEFAULT_STATS_UNIT,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ PARTITION_KEY,+ PRIMARY_KEYS,+ STATS_UNITS,+)+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.ably import AblySourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AblySource(SimpleSource[AblySourceConfig]):+class AblySource(ResumableSource[AblySourceConfig, AblyResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://ably.com/docs/api/rest-api"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ABLY+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Ably authentication failed. Please check your API key.",+ "403 Client Error": "Ably authentication failed. Please check your API key.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.ably.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: AblySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self, config: AblySourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None+ ) -> tuple[bool, str | None]:+ return validate_ably_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AblyResumeConfig]:+ return ResumableSourceManager[AblyResumeConfig](inputs, AblyResumeConfig)++ def source_for_pipeline(+ self,+ config: AblySourceConfig,+ resumable_source_manager: ResumableSourceManager[AblyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ resource = ably_source(+ api_key=config.api_key,+ unit=config.unit,+ 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,+ )+ return SourceResponse(+ name=resource.name,+ items=lambda: resource,+ primary_keys=PRIMARY_KEYS.get(inputs.schema_name, ["id"]),+ column_hints=resource.column_hints,+ partition_mode="datetime",+ partition_keys=[PARTITION_KEY],+ sort_mode="asc",+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.ABLY,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,+ keywords=["realtime", "pubsub", "messaging"],label="Ably",+ caption="Enter your Ably app API key, created in the [Ably dashboard](https://ably.com/dashboard). "+ "The key must include both the key ID and secret (`app-id.key-id:key-secret`).",+ docsUrl="https://posthog.com/docs/cdp/sources/ably",iconPath="/static/services/ably.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="xVLyHw.XXXXXX:1234567890abcdef1234567890abcdef12345678",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="unit",+ label="Stats granularity",+ required=True,+ defaultValue=DEFAULT_STATS_UNIT,+ options=[SourceFieldSelectConfigOption(label=unit.title(), value=unit) for unit in STATS_UNITS],+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably.pynew file mode 100644index 000000000000..2c3ebc54d0ed--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably.py@@ -0,0 +1,299 @@+import json+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++from requests import Response+from requests.exceptions import ConnectionError as RequestsConnectionError++from products.warehouse_sources.backend.temporal.data_imports.sources.ably.ably import (+ AblyResumeConfig,+ _add_interval_start,+ _parse_interval_start,+ ably_source,+ get_resource,+ split_api_key,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+++class TestSplitApiKey:+ @pytest.mark.parametrize(+ ("api_key", "expected_username", "expected_password"),+ [+ ("app123.key456:secretvalue", "app123.key456", "secretvalue"),+ # A key secret could itself contain a colon; only the first colon is the split point.+ ("app123.key456:secret:with:colons", "app123.key456", "secret:with:colons"),+ ],+ )+ def test_splits_on_first_colon(self, api_key: str, expected_username: str, expected_password: str) -> None:+ username, password = split_api_key(api_key)+ assert username == expected_username+ assert password == expected_password++ def test_missing_colon_yields_empty_password(self) -> None:+ username, password = split_api_key("no-colon-here")+ assert username == "no-colon-here"+ assert password == ""+++class TestParseIntervalStart:+ @pytest.mark.parametrize(+ ("interval_id", "expected_iso"),+ [+ ("2024-01-15:14:05", "2024-01-15T14:05:00+00:00"),+ ("2024-01-15:14", "2024-01-15T14:00:00+00:00"),+ ("2024-01-15", "2024-01-15T00:00:00+00:00"),+ ],+ )+ def test_parses_known_granularities(self, interval_id: str, expected_iso: str) -> None:+ parsed = _parse_interval_start(interval_id)+ assert parsed is not None+ assert parsed.isoformat() == expected_iso++ @pytest.mark.parametrize("interval_id", [None, "", "not-a-date", "2024/01/15"])+ def test_returns_none_for_malformed_or_missing(self, interval_id: str | None) -> None:+ assert _parse_interval_start(interval_id) is None+++class TestAddIntervalStart:+ def test_adds_parsed_fields(self) -> None:+ row = {"intervalId": "2024-01-15:14", "unit": "hour"}+ result = _add_interval_start(row)+ assert result["interval_start"] == "2024-01-15T14:00:00+00:00"+ # Unix ms — the same unit Ably's start/end stats params take.+ assert result["interval_start_ms"] == 1705327200000++ def test_missing_interval_id_sets_none_rather_than_raising(self) -> None:+ row: dict[str, Any] = {"unit": "hour"}+ result = _add_interval_start(row)+ assert result["interval_start"] is None+ assert result["interval_start_ms"] is None+++class TestGetResource:+ def test_full_refresh_has_no_incremental_params(self) -> None:+ resource = get_resource("hour", should_use_incremental_field=False)+ endpoint = resource["endpoint"]+ assert isinstance(endpoint, dict)+ assert "incremental" not in endpoint+ assert resource["write_disposition"] == "replace"+ params = endpoint["params"]+ assert isinstance(params, dict)+ assert params["unit"] == "hour"+ assert params["direction"] == "forwards"++ def test_incremental_sets_start_and_end_params(self) -> None:+ resource = get_resource("day", should_use_incremental_field=True)+ endpoint = resource["endpoint"]+ assert isinstance(endpoint, dict)+ incremental = endpoint["incremental"]+ assert incremental is not None+ assert incremental["start_param"] == "start"+ assert incremental["end_param"] == "end"+ assert incremental["initial_value"] == "0"+ # end_value is bound to "now" at build time — assert it's a plausible ms-epoch, not a fixed literal.+ end_value = incremental["end_value"]+ assert end_value is not None and int(end_value) > 1_700_000_000_000+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}+++def _make_http_response(body: list[dict[str, Any]], *, next_url: str | None = None, status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ if next_url:+ resp.headers["Link"] = f'<{next_url}>; rel="next"'+ return resp+++class TestAblySourceResumeBehavior:+ """End-to-end resume/pagination behaviour of ``ably_source`` via ``rest_api_resource``."""++ def _drive(+ self, manager: MagicMock, responses: list[Response], should_use_incremental_field: bool = False+ ) -> tuple[list[str], list[list[dict[str, Any]]]]:+ sent_urls: list[str] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_urls.append(request.url)+ return next(response_iter)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ resource = ably_source(+ api_key="app.key:secret",+ unit="hour",+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ db_incremental_field_last_value=None,+ should_use_incremental_field=should_use_incremental_field,+ )+ pages = list(resource)+ return sent_urls, pages++ def test_fresh_run_follows_link_header_and_saves_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ next_url = "https://main.realtime.ably.net/stats?start=abc&series=1"+ responses = [+ _make_http_response([{"intervalId": "2024-01-15:14", "unit": "hour"}], next_url=next_url),+ _make_http_response([{"intervalId": "2024-01-15:15", "unit": "hour"}]),+ ]+ sent_urls, pages = self._drive(manager, responses)++ assert sent_urls == ["https://main.realtime.ably.net/stats", next_url]++ flattened = [row for page in pages for row in page]+ assert flattened[0]["interval_start"] == "2024-01-15T14:00:00+00:00"+ assert flattened[1]["interval_start"] == "2024-01-15T15:00:00+00:00"++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [AblyResumeConfig(next_url=next_url)]++ def test_terminal_single_page_does_not_save_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response([{"intervalId": "2024-01-15:14", "unit": "hour"}])]+ self._drive(manager, responses)++ manager.save_state.assert_not_called()++ def test_resume_seeds_paginator_with_saved_next_url(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ resumed_url = "https://main.realtime.ably.net/stats?start=resumed"+ manager.load_state.return_value = AblyResumeConfig(next_url=resumed_url)++ responses = [_make_http_response([{"intervalId": "2024-01-15:16", "unit": "hour"}])]+ sent_urls, _ = self._drive(manager, responses)++ assert sent_urls == [resumed_url]+ manager.load_state.assert_called_once()++ def test_does_not_load_state_when_cannot_resume(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response([{"intervalId": "2024-01-15:14", "unit": "hour"}])]+ self._drive(manager, responses)++ manager.load_state.assert_not_called()+++def _make_redirect_response(location: str, status_code: int = 302) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp.headers["Location"] = location+ resp._content = b""+ return resp+++class TestAblyHostPinningAndRedirects:+ """`allowed_hosts=[]` + `allow_redirects=False` keep the Basic-auth credential from+ following a spoofed ``Link: rel="next"`` target or a cross-origin redirect off Ably's host."""++ def _drive(self, sent_urls: list[str], responses: list[Response]) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_urls.append(request.url)+ return next(response_iter)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ resource = ably_source(+ api_key="app.key:secret",+ unit="hour",+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ db_incremental_field_last_value=None,+ )+ list(resource)++ def test_off_origin_next_link_is_rejected_before_sending(self) -> None:+ # A spoofed `Link: rel="next"` pointing off Ably's host must be refused before the+ # request (carrying the Basic-auth key) leaves the process.+ evil_url = "https://evil.example.com/stats?start=abc"+ sent_urls: list[str] = []+ responses = [_make_http_response([{"intervalId": "2024-01-15:14", "unit": "hour"}], next_url=evil_url)]++ with pytest.raises(ValueError, match="disallowed host"):+ self._drive(sent_urls, responses)++ # Only the legitimate first page was ever sent; the off-origin URL was never contacted.+ assert sent_urls == ["https://main.realtime.ably.net/stats"]++ def test_cross_origin_redirect_is_not_followed(self) -> None:+ sent_urls: list[str] = []+ responses = [_make_redirect_response("https://evil.example.com/stats")]++ with pytest.raises(ValueError, match="[Rr]edirect"):+ self._drive(sent_urls, responses)++ # The redirect target was never fetched: send ran once for the base host and stopped.+ assert sent_urls == ["https://main.realtime.ably.net/stats"]+++class TestValidateCredentials:+ def test_malformed_key_fails_without_a_request(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.ably.ably.make_tracked_session"+ ) as mock_make_session:+ ok, error = validate_credentials("no-colon-here")++ assert ok is False+ assert error is not None and "malformed" in error.lower()+ mock_make_session.assert_not_called()++ @pytest.mark.parametrize(+ ("status_code", "expect_ok"),+ [+ (200, True),+ (401, False),+ (403, False),+ (500, False),+ ],+ )+ def test_status_code_mapping(self, status_code: int, expect_ok: bool) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.ably.ably.make_tracked_session"+ ) as mock_make_session:+ mock_make_session.return_value.get.return_value = MagicMock(status_code=status_code)+ ok, error = validate_credentials("app.key:secret")++ assert ok is expect_ok+ if not expect_ok:+ assert error is not None++ def test_network_error_is_reported_not_raised(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.ably.ably.make_tracked_session"+ ) as mock_make_session:+ mock_make_session.return_value.get.side_effect = RequestsConnectionError("boom")+ ok, error = validate_credentials("app.key:secret")++ assert ok is False+ assert error == "boom"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably_source.pynew file mode 100644index 000000000000..1774c9aa0ec9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably_source.py@@ -0,0 +1,150 @@+import pytest+from unittest.mock import MagicMock, patch++from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.ably.ably import AblyResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.ably.source import AblySource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.ably import AblySourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestAblySource:+ def setup_method(self):+ self.source = AblySource()+ self.team_id = 123++ def _field(self, name: str):+ return next(f for f in self.source.get_source_config.fields if f.name == name)++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.ABLY++ def test_api_key_field_is_secret_password(self):+ field = self._field("api_key")+ assert isinstance(field, SourceFieldInputConfig)+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_unit_field_defaults_to_hour(self):+ field = self._field("unit")+ assert isinstance(field, SourceFieldSelectConfig)+ assert field.defaultValue == "hour"+ assert {option.value for option in field.options} == {"minute", "hour", "day", "month"}++ def test_get_schemas_returns_stats_with_incremental_field(self):+ config = AblySourceConfig(api_key="app.key:secret", unit="hour")+ schemas = self.source.get_schemas(config, self.team_id)++ assert [schema.name for schema in schemas] == ["Stats"]+ stats = schemas[0]+ assert stats.supports_incremental is True+ assert [f["field"] for f in stats.incremental_fields] == ["interval_start_ms"]++ def test_get_schemas_names_filter(self):+ config = AblySourceConfig(api_key="app.key:secret", unit="hour")+ schemas = self.source.get_schemas(config, self.team_id, names=["Stats"])+ assert [schema.name for schema in schemas] == ["Stats"]++ empty = self.source.get_schemas(config, self.team_id, names=["Missing"])+ assert empty == []++ @pytest.mark.parametrize(+ ("status_code", "expected"),+ [+ (200, (True, None)),+ (401, (False, "Ably authentication failed. Please check your API key.")),+ (403, (False, "Ably authentication failed. Please check your API key.")),+ ],+ )+ def test_validate_credentials(self, status_code, expected):+ config = AblySourceConfig(api_key="app.key:secret", unit="hour")+ mock_response = MagicMock(status_code=status_code)+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.ably.ably.make_tracked_session"+ ) as mock_make_session:+ mock_make_session.return_value.get.return_value = mock_response+ assert self.source.validate_credentials(config, self.team_id) == expected++ def test_validate_credentials_rejects_malformed_key(self):+ config = AblySourceConfig(api_key="no-colon-here", unit="hour")+ ok, error = self.source.validate_credentials(config, self.team_id)+ assert ok is False+ assert error is not None and "malformed" in error.lower()++ def test_get_resumable_source_manager_binds_ably_resume_config(self):+ inputs = MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is AblyResumeConfig++ def test_source_for_pipeline_plumbs_config_and_returns_expected_response_shape(self):+ config = AblySourceConfig(api_key="app.key:secret", unit="day")+ inputs = MagicMock(+ team_id=self.team_id,+ job_id="job-1",+ schema_name="Stats",+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000000,+ )+ manager = MagicMock(spec=ResumableSourceManager)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.ably.source.ably_source"+ ) as mock_ably_source:+ mock_resource = MagicMock(name="Stats", column_hints={"interval_start": "timestamp"})+ mock_resource.name = "Stats"+ mock_ably_source.return_value = mock_resource++ response = self.source.source_for_pipeline(config, manager, inputs)++ mock_ably_source.assert_called_once_with(+ api_key="app.key:secret",+ unit="day",+ team_id=self.team_id,+ job_id="job-1",+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000000,+ )++ assert response.name == "Stats"+ assert response.primary_keys == ["unit", "intervalId"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["interval_start"]+ assert response.sort_mode == "asc"++ def test_source_for_pipeline_ignores_last_value_on_full_refresh(self):+ config = AblySourceConfig(api_key="app.key:secret", unit="hour")+ inputs = MagicMock(+ team_id=self.team_id,+ job_id="job-1",+ schema_name="Stats",+ should_use_incremental_field=False,+ db_incremental_field_last_value=1700000000000,+ )+ manager = MagicMock(spec=ResumableSourceManager)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.ably.source.ably_source"+ ) as mock_ably_source:+ mock_resource = MagicMock(name="Stats", column_hints=None)+ mock_resource.name = "Stats"+ mock_ably_source.return_value = mock_resource++ self.source.source_for_pipeline(config, manager, inputs)++ assert mock_ably_source.call_args.kwargs["db_incremental_field_last_value"] is None++ @pytest.mark.parametrize(+ "error_message",+ [+ "401 Client Error: Unauthorized for url: https://main.realtime.ably.net/stats",+ "403 Client Error: Forbidden for url: https://main.realtime.ably.net/stats",+ ],+ )+ def test_non_retryable_errors(self, error_message):+ non_retryable = self.source.get_non_retryable_errors()+ assert any(pattern in error_message for pattern in non_retryable)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/ably.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/ably.pyindex 958e72b73566..8ea7eace44c0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/ably.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/ably.py@@ -1,9 +1,12 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config@config.configclass AblySourceConfig(config.Config):- pass+ api_key: str+ unit: Literal["minute", "hour", "day", "month"] = config.value(default="hour")