: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): implement shortio import source (#68589)
Tom Owersdd804d0d95e5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 51c05a824b8a..f24441049698 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -310,6 +310,7 @@ the row lists both.| shipstation | HTTP | requests | ✅ || shopify | HTTP | requests | ✅ || shortcut | HTTP | requests | ✅ |+| shortio | HTTP | requests | ✅ || simplecast | HTTP | requests | ✅ || simplesat | HTTP | requests | ✅ || slack | HTTP | requests + `rest_source.RESTClient` | ✅ |diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 9adb045cbb39..7bbb719feecf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -3016,7 +3016,7 @@ class ShortcutSourceConfig(config.Config):@config.configclass ShortioSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shortio/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shortio/canonical_descriptions.pynew file mode 100644index 000000000000..e37ac603eec8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shortio/canonical_descriptions.py@@ -0,0 +1,30 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Short.io API docs (https://developers.short.io/reference/apidomainsget).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "domains": {+ "description": "A branded short-link domain configured in your Short.io account.",+ "docs_url": "https://developers.short.io/reference/apidomainsget",+ "columns": {+ "id": "The unique ID of the domain.",+ "hostname": "The domain's hostname (e.g. 'example.short.gy').",+ "unicodeHostname": "The Unicode (IDN) form of the hostname.",+ "state": "The domain's setup state (e.g. 'configured', 'not_configured').",+ "TeamId": "The ID of the team that owns the domain.",+ "provider": "The DNS/hosting provider backing the domain.",+ "setupType": "How the domain was set up (e.g. 'dns', 'subdomain').",+ "cloaking": "Whether link cloaking (iframe masking) is enabled for the domain.",+ "hasFavicon": "Whether a custom favicon is configured for the domain.",+ "httpsLinks": "Whether generated links use HTTPS.",+ "redirect404": "The URL that 404s on this domain redirect to.",+ "hideReferer": "Whether the HTTP referer is hidden on redirects.",+ "caseSensitive": "Whether link paths on this domain are case sensitive.",+ "exportEnabled": "Whether click-data export is enabled for the domain.",+ "createdAt": "When the domain was created.",+ "updatedAt": "When the domain was last modified.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shortio/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shortio/settings.pynew file mode 100644index 000000000000..58e1f271cf41--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shortio/settings.py@@ -0,0 +1,22 @@+from dataclasses import dataclass, field+++@dataclass+class ShortioEndpointConfig:+ name: str+ path: str+ # Short.io domain IDs are globally unique within an account, so `id` is a safe primary key.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+++# Top-level Short.io list endpoints. Only `domains` is synced in this version: it lists directly+# without a parent id. Links and click statistics are per-domain (fan-out) and are intentionally+# left out of v1. All endpoints are full refresh only — the domain list exposes no server-side+# ordered timestamp filter, so there is no incremental cursor to advance.+SHORTIO_ENDPOINTS: dict[str, ShortioEndpointConfig] = {+ "domains": ShortioEndpointConfig(name="domains", path="/api/domains"),+}++ENDPOINTS = tuple(SHORTIO_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shortio/shortio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shortio/shortio.pynew file mode 100644index 000000000000..9abe657e2ec9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shortio/shortio.py@@ -0,0 +1,115 @@+from collections.abc import Iterator+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++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.shortio.settings import SHORTIO_ENDPOINTS++SHORTIO_BASE_URL = "https://api.short.io"+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint used to confirm an API key is genuine. The key is account-wide, so one probe+# validates access to the domain list.+DEFAULT_PROBE_PATH = "/api/domains"+++class ShortioRetryableError(Exception):+ pass+++def _headers(api_key: str) -> dict[str, str]:+ # Short.io expects the raw secret API key in the Authorization header — no `Bearer` prefix.+ return {"Authorization": api_key, "Accept": "application/json"}+++@retry(+ retry=retry_if_exception_type((ShortioRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_all(+ session: requests.Session,+ path: str,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ response = session.get(f"{SHORTIO_BASE_URL}{path}", timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise ShortioRetryableError(f"Short.io API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"Short.io API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ data = response.json()+ # The domains endpoint returns a bare JSON array of domain records. A non-list 200 means the+ # schema changed under us — retrying can't fix that, so fail fast with a clear message.+ if not isinstance(data, list):+ raise ValueError(+ f"Short.io returned an unexpected payload for {path}: expected list, got {type(data).__name__}"+ )+ return data+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ config = SHORTIO_ENDPOINTS[endpoint]+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))++ # The domain list has no pagination, so a single request returns the whole collection.+ rows = _fetch_all(session, config.path, logger)+ if rows:+ yield rows+++def shortio_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+) -> SourceResponse:+ config = SHORTIO_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(api_key=api_key, endpoint=endpoint, logger=logger),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )+++def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the API key.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))+ try:+ response = session.get(f"{SHORTIO_BASE_URL}{path}", timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Short.io: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Short.io returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ status, message = check_access(api_key)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Short.io API key"+ return False, message or "Could not validate Short.io API key"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shortio/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shortio/source.pyindex 3e19620ed1d1..e8e2c35a899f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shortio/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shortio/source.py@@ -1,19 +1,40 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)+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, SimpleSource+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.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ShortioSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.shortio.settings import (+ ENDPOINTS,+ SHORTIO_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.shortio.shortio import (+ shortio_source,+ validate_credentials as _validate_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass ShortioSource(SimpleSource[ShortioSourceConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SHORTIO@@ -24,7 +45,79 @@ class ShortioSource(SimpleSource[ShortioSourceConfig]):name=SchemaExternalDataSourceType.SHORTIO,category=DataWarehouseSourceCategory.ADVERTISING,label="Shortio",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Short.io API key to pull your branded-link domains into the PostHog Data warehouse.++Create an API key under **Integrations & API** in your [Short.io dashboard](https://app.short.io/settings/integrations/api-key). Paste the secret key value.++This version syncs your top-level list of **domains** only. Per-domain links and click statistics are not synced yet.+""",iconPath="/static/services/shortio.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/shortio",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.shortio.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.short.io": "Your Short.io API key is invalid or has been revoked. Generate a new key under Integrations & API, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.short.io": "Your Short.io API key does not have access to this data. Check the key's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: ShortioSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Full refresh only — the domain list exposes no reliably ordered server-side timestamp+ # filter, so there is no incremental cursor to advance.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: ShortioSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The API key is account-wide, so a single probe validates access to the domain list.+ return _validate_credentials(config.api_key)++ def source_for_pipeline(self, config: ShortioSourceConfig, inputs: SourceInputs) -> SourceResponse:+ if inputs.schema_name not in SHORTIO_ENDPOINTS:+ raise ValueError(f"Unknown Short.io schema '{inputs.schema_name}'")++ return shortio_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shortio/tests/test_shortio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shortio/tests/test_shortio.pynew file mode 100644index 000000000000..1bd0987b6170--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shortio/tests/test_shortio.py@@ -0,0 +1,181 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.shortio import shortio+from products.warehouse_sources.backend.temporal.data_imports.sources.shortio.settings import (+ ENDPOINTS,+ SHORTIO_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.shortio.shortio import (+ ShortioRetryableError,+ check_access,+ get_rows,+ shortio_source,+ validate_credentials,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_all_unwrapped = shortio._fetch_all.__wrapped__ # type: ignore[attr-defined]+++class TestGetRows:+ @staticmethod+ def _collect(monkeypatch: Any, rows: list[dict], endpoint: str = "domains") -> list[dict]:+ def fake_fetch(session: Any, path: str, logger: Any) -> list[dict]:+ return rows++ monkeypatch.setattr(shortio, "_fetch_all", fake_fetch)+ monkeypatch.setattr(shortio, "make_tracked_session", lambda **kwargs: MagicMock())++ collected: list[dict] = []+ for batch in get_rows(api_key="sk-key", endpoint=endpoint, logger=MagicMock()):+ collected.extend(batch)+ return collected++ def test_yields_all_rows_in_a_single_batch(self, monkeypatch: Any) -> None:+ rows = self._collect(monkeypatch, [{"id": 1}, {"id": 2}])+ assert rows == [{"id": 1}, {"id": 2}]++ def test_empty_response_yields_nothing(self, monkeypatch: Any) -> None:+ assert self._collect(monkeypatch, []) == []+++class TestFetchAll:+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body if body is not None else []+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(ShortioRetryableError):+ _fetch_all_unwrapped(session, "/api/domains", MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_all_unwrapped(session, "/api/domains", MagicMock())++ def test_success_returns_list_body(self) -> None:+ body = [{"id": 1}]+ session = self._session_returning(200, body)+ assert _fetch_all_unwrapped(session, "/api/domains", MagicMock()) == body++ def test_non_list_body_fails_fast(self) -> None:+ # A non-list 200 means the schema changed under us — it must not be retried.+ session = self._session_returning(200, {"error": "nope"})+ with pytest.raises(ValueError):+ _fetch_all_unwrapped(session, "/api/domains", MagicMock())+++class TestCheckAccess:+ @staticmethod+ def _configure_session(mock_make_session: MagicMock, response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ mock_make_session.return_value = session+ return session++ @parameterized.expand(+ [+ ("ok", 200, True, 200, None),+ ("unauthorized", 401, False, 401, None),+ ("forbidden", 403, False, 403, None),+ ("server_error", 500, False, 500, "Short.io returned HTTP 500"),+ ]+ )+ @patch.object(shortio, "make_tracked_session")+ def test_status_mapping(+ self,+ _name: str,+ status: int,+ ok: bool,+ expected_status: int,+ expected_message: str | None,+ mock_make_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ self._configure_session(mock_make_session, response)+ assert check_access("sk-key") == (expected_status, expected_message)++ @patch.object(shortio, "make_tracked_session")+ def test_connection_error_maps_to_zero(self, mock_make_session: MagicMock) -> None:+ self._configure_session(mock_make_session, requests.ConnectionError("boom"))+ status, message = check_access("sk-key")+ assert status == 0+ assert message is not None and "boom" in message++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid Short.io API key"),+ ("forbidden", 403, False, "Invalid Short.io API key"),+ ("server_error", 500, False, "Short.io returned HTTP 500"),+ ]+ )+ @patch.object(shortio, "make_tracked_session")+ def test_validate_credentials(+ self,+ _name: str,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ mock_make_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ self._configure_session(mock_make_session, response)+ assert validate_credentials("sk-key") == (expected_valid, expected_message)++ @patch.object(shortio, "make_tracked_session")+ def test_api_key_sent_raw_in_authorization_header(self, mock_make_session: MagicMock) -> None:+ # Short.io uses the raw secret key in Authorization — no 'Bearer' prefix.+ captured: dict[str, Any] = {}++ def fake_make_session(**kwargs: Any) -> MagicMock:+ captured.update(kwargs)+ session = MagicMock()+ response = MagicMock()+ response.status_code = 200+ response.ok = True+ session.get.return_value = response+ return session++ mock_make_session.side_effect = fake_make_session+ check_access("sk-key")+ assert captured["headers"]["Authorization"] == "sk-key"+++class TestShortioSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = shortio_source(api_key="sk-key", endpoint=endpoint, logger=MagicMock())+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # The domain list carries no stable creation timestamp guarantee, so we don't partition.+ assert response.partition_mode is None++ def test_every_endpoint_uses_id_primary_key(self) -> None:+ assert all(config.primary_keys == ["id"] for config in SHORTIO_ENDPOINTS.values())+ assert set(SHORTIO_ENDPOINTS) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shortio/tests/test_shortio_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shortio/tests/test_shortio_source.pynew file mode 100644index 000000000000..2411733591ee--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shortio/tests/test_shortio_source.py@@ -0,0 +1,155 @@+import pytest+from unittest import mock++import structlog+from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ShortioSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.shortio.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.shortio.source import ShortioSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(schema_name: str = "domains") -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-id",+ source_id="source-id",+ team_id=123,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job-id",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )+++class TestShortioSource:+ def setup_method(self) -> None:+ self.source = ShortioSource()+ self.team_id = 123+ self.config = ShortioSourceConfig(api_key="sk-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.SHORTIO++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Shortio"+ assert config.label == "Shortio"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source is visible — it must not carry the scaffolding flag.+ assert not config.unreleasedSource+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/shortio"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_connection_host_fields(self) -> None:+ # The only field is the secret API key; the base URL is hardcoded, so there is no non-secret+ # field an editor could retarget to reuse a preserved key against another account.+ assert self.source.connection_host_fields == []++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["domains"])+ assert len(schemas) == 1+ assert schemas[0].name == "domains"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions) == set(ENDPOINTS)++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://api.short.io/api/domains",),+ ("403 Client Error: Forbidden for url: https://api.short.io/api/domains",),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("500 Server Error: Internal Server Error for url: https://api.short.io/api/domains",),+ ("429 Client Error: Too Many Requests for url: https://api.short.io/api/domains",),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid Short.io API key"),+ ("forbidden", 403, False, "Invalid Short.io API key"),+ ("server_error", 500, False, "Short.io returned HTTP 500"),+ ("connection_error", 0, False, "Could not connect to Short.io: boom"),+ ]+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.shortio.shortio.check_access")+ def test_validate_credentials(+ self,+ _name: str,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ mock_check: mock.MagicMock,+ ) -> None:+ message = (+ "Short.io returned HTTP 500"+ if status == 500+ else ("Could not connect to Short.io: boom" if status == 0 else None)+ )+ mock_check.return_value = (status, message)+ is_valid, returned = self.source.validate_credentials(self.config, self.team_id)+ assert is_valid is expected_valid+ assert returned == expected_message++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.shortio.source.shortio_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = _make_inputs(schema_name="domains")++ self.source.source_for_pipeline(self.config, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "sk-key"+ assert kwargs["endpoint"] == "domains"++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = _make_inputs(schema_name="not_a_table")+ with pytest.raises(ValueError, match="Unknown Short.io schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, inputs)