: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 sendowl import source (#68577)
Tom Owersabfcd5d811ae
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 7e082012f644..51c05a824b8a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -304,6 +304,7 @@ the row lists both.| secoda | HTTP | requests | ✅ || segment | HTTP | requests | ✅ || sendgrid | HTTP | requests | ✅ |+| sendowl | HTTP | requests | ✅ || sentry | HTTP | requests + `rest_source.RESTClient` | ✅ || servicenow | HTTP | requests | ✅ || shipstation | HTTP | requests | ✅ |@@ -652,7 +653,6 @@ doesn't conflict with concurrent PRs.- sap_successfactors- savvycal- search_ads_360-- sendowl- sendpulse- senseforce- serpstatdiff --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 cba2fbd13a4e..9adb045cbb39 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@@ -2942,7 +2942,8 @@ class SendPulseSourceConfig(config.Config):@config.configclass SendowlSourceConfig(config.Config):- pass+ api_key: str+ api_secret: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendowl/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendowl/canonical_descriptions.pynew file mode 100644index 000000000000..cf3dbb16ab8e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendowl/canonical_descriptions.py@@ -0,0 +1,70 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the SendOwl API docs (https://dashboard.sendowl.com/developers).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "products": {+ "description": "A SendOwl product — a digital item, bundle, subscription, or drip content available for sale.",+ "docs_url": "https://dashboard.sendowl.com/developers/api/products",+ "columns": {+ "id": "The unique ID of the product.",+ "name": "The display name of the product.",+ "product_type": "The type of product (e.g. digital, bundle, subscription, drip).",+ "price": "The price of the product.",+ "currency_code": "The ISO currency code the product is priced in.",+ "sales_page_url": "The hosted sales/checkout page URL for the product.",+ "instant_buy_url": "The direct add-to-cart/instant-buy URL for the product.",+ "add_to_cart_url": "The add-to-cart URL for the product.",+ "created_at": "The date and time the product was created.",+ "updated_at": "The date and time the product was last updated.",+ },+ },+ "orders": {+ "description": "A SendOwl order — a completed purchase, including buyer, line items, and payment details.",+ "docs_url": "https://dashboard.sendowl.com/developers/api/orders",+ "columns": {+ "id": "The unique ID of the order.",+ "state": "The current state of the order (e.g. completed, refunded).",+ "buyer_email": "The email address of the buyer.",+ "buyer_name": "The name of the buyer.",+ "settled_currency": "The currency the order settled in.",+ "settled_gross": "The gross amount of the order in the settled currency.",+ "settled_tax": "The tax amount of the order in the settled currency.",+ "cart": "The cart contents — the line items purchased in this order.",+ "discount_code": "The discount code applied to the order, if any.",+ "created_at": "The date and time the order was created.",+ "updated_at": "The date and time the order was last updated.",+ },+ },+ "subscriptions": {+ "description": "A SendOwl subscription — a recurring purchase of a subscription product by a customer.",+ "docs_url": "https://dashboard.sendowl.com/developers/api/subscriptions",+ "columns": {+ "id": "The unique ID of the subscription.",+ "state": "The current state of the subscription (e.g. active, cancelled, expired).",+ "product_id": "The ID of the subscription product.",+ "buyer_email": "The email address of the subscriber.",+ "buyer_name": "The name of the subscriber.",+ "created_at": "The date and time the subscription was created.",+ "updated_at": "The date and time the subscription was last updated.",+ },+ },+ "discount_codes": {+ "description": "A SendOwl discount code — a coupon that applies a discount at checkout.",+ "docs_url": "https://dashboard.sendowl.com/developers/api/discount_codes",+ "columns": {+ "id": "The unique ID of the discount code.",+ "code": "The discount code string entered by buyers at checkout.",+ "discount_type": "The type of discount (e.g. percentage, fixed amount).",+ "percentage": "The percentage discount applied, when the type is percentage-based.",+ "amount": "The fixed amount discounted, when the type is amount-based.",+ "usage_count": "The number of times the code has been used.",+ "usage_limit": "The maximum number of times the code may be used.",+ "expiry_date": "The date the discount code expires.",+ "created_at": "The date and time the discount code was created.",+ "updated_at": "The date and time the discount code was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendowl/sendowl.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendowl/sendowl.pynew file mode 100644index 000000000000..5b33ce02f284--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendowl/sendowl.py@@ -0,0 +1,154 @@+import base64+import dataclasses+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.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.sendowl.settings import SENDOWL_ENDPOINTS++SENDOWL_BASE_URL = "https://www.sendowl.com"+# SendOwl caps `per_page` at 50 (default 10); the largest page minimises round trips while+# staying under the documented ~1 request/second advisory.+PER_PAGE = 50+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint used to confirm the credentials are genuine. The key pair is account-wide, so+# one probe validates access to every list endpoint.+DEFAULT_PROBE_PATH = "/api/v1/products"+++class SendowlRetryableError(Exception):+ pass+++class SendowlResumeConfig:+ # Next page to fetch (1-indexed). Page-number pagination is deterministic, so a crashed+ # full-refresh sync resumes from the page after the last one yielded; merge dedupes on `id`.+ next_page: int = 1+++def _headers(api_key: str, api_secret: str) -> dict[str, str]:+ # SendOwl uses HTTP Basic auth with the API key as username and the secret as password.+ # `make_tracked_session` has no `auth=` hook, so the header is built by hand here.+ token = base64.b64encode(f"{api_key}:{api_secret}".encode()).decode()+ return {"Authorization": f"Basic {token}", "Accept": "application/json"}+++@retry(+ retry=retry_if_exception_type((SendowlRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ path: str,+ wrapper_key: str,+ page: int,+ per_page: int,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ response = session.get(+ f"{SENDOWL_BASE_URL}{path}",+ params={"page": page, "per_page": per_page},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise SendowlRetryableError(f"SendOwl API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"SendOwl API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ data = response.json()+ # SendOwl list endpoints return a bare JSON array of single-key wrapper objects, e.g.+ # `[{"product": {...}}, ...]`. Unwrap each item so downstream tables hold the flat record.+ # Subscript access fails fast if the wrapper key is missing rather than silently importing the+ # outer dict (which would lack the primary key and carry a nested object as a stray field).+ if not isinstance(data, list):+ raise SendowlRetryableError(f"SendOwl returned an unexpected payload for {path}: {type(data).__name__}")+ return [row[wrapper_key] if isinstance(row, dict) else row for row in data]+++def get_rows(+ api_key: str,+ api_secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SendowlResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = SENDOWL_ENDPOINTS[endpoint]+ # `redact_values` masks both credential strings in logged URLs and captured samples.+ session = make_tracked_session(headers=_headers(api_key, api_secret), redact_values=(api_key, api_secret))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.next_page if resume else 1+ if resume and resume.next_page > 1:+ logger.debug(f"SendOwl: resuming {endpoint} from page {page}")++ while True:+ items = _fetch_page(session, config.path, config.wrapper_key, page, PER_PAGE, logger)+ if items:+ yield items++ # SendOwl exposes no `has_more` flag, so a short (or empty) page marks the end of the+ # collection.+ if len(items) < PER_PAGE:+ break++ page += 1+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(SendowlResumeConfig(next_page=page))+++def sendowl_source(+ api_key: str,+ api_secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SendowlResumeConfig],+) -> SourceResponse:+ config = SENDOWL_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ api_secret=api_secret,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )+++def check_access(api_key: str, api_secret: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single list endpoint to validate the API key pair.++ 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, api_secret), redact_values=(api_key, api_secret))+ try:+ response = session.get(f"{SENDOWL_BASE_URL}{path}", params={"page": 1, "per_page": 1}, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to SendOwl: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"SendOwl returned HTTP {response.status_code}"++ return 200, Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendowl/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendowl/settings.pynew file mode 100644index 000000000000..be0b262c3140--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendowl/settings.py@@ -0,0 +1,30 @@+from dataclasses import dataclass, field+++@dataclass+class SendowlEndpointConfig:+ name: str+ path: str+ # SendOwl wraps every list item in a single-key object, e.g. `/api/v1/products` returns+ # `[{"product": {...}}, ...]`. `wrapper_key` names that key so `_fetch_page` can unwrap it.+ wrapper_key: str+ # SendOwl object IDs are unique per account, so `id` is a safe primary key.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+++# SendOwl list endpoints. All are full-refresh only. Resources are versioned per path: products,+# subscriptions and discount codes live under `/api/v1`, while orders use `/api/v1_3`.+SENDOWL_ENDPOINTS: dict[str, SendowlEndpointConfig] = {+ "products": SendowlEndpointConfig(name="products", path="/api/v1/products", wrapper_key="product"),+ "orders": SendowlEndpointConfig(name="orders", path="/api/v1_3/orders", wrapper_key="order"),+ "subscriptions": SendowlEndpointConfig(+ name="subscriptions", path="/api/v1/subscriptions", wrapper_key="subscription"+ ),+ "discount_codes": SendowlEndpointConfig(+ name="discount_codes", path="/api/v1/discount_codes", wrapper_key="discount_code"+ ),+}++ENDPOINTS = tuple(SENDOWL_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendowl/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendowl/source.pyindex 62de732948e8..46536e79e04b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendowl/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendowl/source.py@@ -1,19 +1,42 @@-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.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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SendowlSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.sendowl.sendowl import (+ SendowlResumeConfig,+ check_access,+ sendowl_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.sendowl.settings import (+ ENDPOINTS,+ SENDOWL_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SendowlSource(SimpleSource[SendowlSourceConfig]):+class SendowlSource(ResumableSource[SendowlSourceConfig, SendowlResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SENDOWL@@ -24,7 +47,104 @@ class SendowlSource(SimpleSource[SendowlSourceConfig]):name=SchemaExternalDataSourceType.SENDOWL,category=DataWarehouseSourceCategory.E_COMMERCE,label="Sendowl",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your SendOwl API credentials to pull your SendOwl data into the PostHog Data warehouse.++You can create an API key and secret under **Settings → API credentials** in the [SendOwl dashboard](https://dashboard.sendowl.com/settings/api_keys). Grant the key the **Manager** permission for read access to products, orders, subscriptions, and discount codes.+""",iconPath="/static/services/sendowl.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/sendowl",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="api_secret",+ label="API secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.sendowl.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # Invalid or revoked credentials surface as a requests HTTPError when `_fetch_page` calls+ # `raise_for_status()`. Retrying can never satisfy a credential problem, so stop the sync.+ # Match the stable status text and base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://www.sendowl.com": "Your SendOwl API credentials are invalid or have been revoked. Generate a new key and secret under Settings → API credentials, then reconnect.",+ "403 Client Error: Forbidden for url: https://www.sendowl.com": "Your SendOwl API credentials do not have access to this data. Check the key's permission scope (use Manager for full read access), then reconnect.",+ }++ def get_schemas(+ self,+ config: SendowlSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — SendOwl's list endpoints expose no reliable+ # server-side timestamp filter for a genuine incremental cursor.+ 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: SendowlSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The API key pair is account-wide, so a single probe validates access to every schema;+ # there is no per-endpoint scope to check.+ status, message = check_access(config.api_key, config.api_secret)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid SendOwl API credentials"+ return False, message or "Could not validate SendOwl API credentials"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SendowlResumeConfig]:+ return ResumableSourceManager[SendowlResumeConfig](inputs, SendowlResumeConfig)++ def source_for_pipeline(+ self,+ config: SendowlSourceConfig,+ resumable_source_manager: ResumableSourceManager[SendowlResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in SENDOWL_ENDPOINTS:+ raise ValueError(f"Unknown SendOwl schema '{inputs.schema_name}'")++ return sendowl_source(+ api_key=config.api_key,+ api_secret=config.api_secret,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendowl/tests/test_sendowl.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendowl/tests/test_sendowl.pynew file mode 100644index 000000000000..b722bdbdd47e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendowl/tests/test_sendowl.py@@ -0,0 +1,208 @@+import base64+from typing import Any++import pytest+from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.sendowl import sendowl+from products.warehouse_sources.backend.temporal.data_imports.sources.sendowl.sendowl import (+ SendowlResumeConfig,+ SendowlRetryableError,+ _headers,+ check_access,+ get_rows,+ sendowl_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.sendowl.settings import (+ ENDPOINTS,+ SENDOWL_ENDPOINTS,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = sendowl._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: SendowlResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[SendowlResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> SendowlResumeConfig | None:+ return self._state++ def save_state(self, data: SendowlResumeConfig) -> None:+ self.saved.append(data)+++def _wrapped(wrapper_key: str, rows: list[dict]) -> list[dict]:+ # SendOwl returns each list item under a single-key wrapper, e.g. `{"product": {...}}`.+ return [{wrapper_key: row} for row in rows]+++class TestHeaders:+ def test_builds_basic_auth_from_key_and_secret(self) -> None:+ headers = _headers("key123", "secret456")+ expected = base64.b64encode(b"key123:secret456").decode()+ assert headers["Authorization"] == f"Basic {expected}"+ assert headers["Accept"] == "application/json"+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[int, list[dict]], endpoint: str = "products"+ ) -> list[dict]:+ def fake_fetch(session: Any, path: str, wrapper_key: str, page: int, per_page: int, logger: Any) -> list[dict]:+ return pages[page]++ monkeypatch.setattr(sendowl, "_fetch_page", fake_fetch)+ monkeypatch.setattr(sendowl, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="sendowl-key",+ api_secret="sendowl-secret",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_single_short_page_yields_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {1: [{"id": 1}, {"id": 2}]})+ assert rows == [{"id": 1}, {"id": 2}]+ # A short page ends the sync, so no resume state is persisted.+ assert manager.saved == []++ def test_follows_pagination_until_short_page(self, monkeypatch: Any) -> None:+ full_page = [{"id": i} for i in range(sendowl.PER_PAGE)]+ pages = {1: full_page, 2: [{"id": 999}]}+ rows = self._collect(_FakeResumableManager(), monkeypatch, pages)+ assert rows == [*full_page, {"id": 999}]++ def test_saves_next_page_after_yielding_full_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ full_page = [{"id": i} for i in range(sendowl.PER_PAGE)]+ pages = {1: full_page, 2: [{"id": 999}]}+ self._collect(manager, monkeypatch, pages)+ # State is saved AFTER the full page 1 is yielded (pointing at page 2), never for the final page.+ assert [s.next_page for s in manager.saved] == [2]++ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(SendowlResumeConfig(next_page=2))+ full_page = [{"id": i} for i in range(sendowl.PER_PAGE)]+ # Page 1 must never be fetched on resume.+ pages = {2: full_page, 3: [{"id": 7}]}+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [*full_page, {"id": 7}]++ def test_empty_page_does_not_yield(self, monkeypatch: Any) -> None:+ rows = self._collect(_FakeResumableManager(), monkeypatch, {1: []})+ assert rows == []+++class TestFetchPage:+ 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(SendowlRetryableError):+ _fetch_page_unwrapped(session, "/api/v1/products", "product", 1, 50, 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_page_unwrapped(session, "/api/v1/products", "product", 1, 50, MagicMock())++ def test_success_unwraps_single_key_wrapper(self) -> None:+ body = _wrapped("product", [{"id": 1, "name": "Ebook"}, {"id": 2, "name": "Course"}])+ session = self._session_returning(200, body)+ result = _fetch_page_unwrapped(session, "/api/v1/products", "product", 1, 50, MagicMock())+ assert result == [{"id": 1, "name": "Ebook"}, {"id": 2, "name": "Course"}]++ def test_non_list_payload_raises_retryable(self) -> None:+ session = self._session_returning(200, {"error": "unexpected"})+ with pytest.raises(SendowlRetryableError):+ _fetch_page_unwrapped(session, "/api/v1/products", "product", 1, 50, MagicMock())++ def test_request_uses_page_and_per_page_params(self) -> None:+ session = self._session_returning(200, [])+ _fetch_page_unwrapped(session, "/api/v1_3/orders", "order", 3, 50, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"page": 3, "per_page": 50}+++class TestCheckAccess:+ def _patch_session(self, monkeypatch: Any, response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ monkeypatch.setattr(sendowl, "make_tracked_session", lambda **kwargs: session)+ return session++ @parameterized.expand(+ [+ ("reachable", 200, True, 200, None),+ ("unauthorized", 401, False, 401, None),+ ("forbidden", 403, False, 403, None),+ ("server_error", 500, False, 500, "SendOwl returned HTTP 500"),+ ]+ )+ def test_status_mapping(+ self, _name: str, status: int, ok: bool, expected_status: int, expected_message: str | None+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ # parameterized.expand can't also receive the `monkeypatch` fixture, so manage our own.+ with pytest.MonkeyPatch.context() as mp:+ self._patch_session(mp, response)+ assert check_access("sendowl-key", "sendowl-secret") == (expected_status, expected_message)++ def test_connection_error_maps_to_zero(self, monkeypatch: Any) -> None:+ self._patch_session(monkeypatch, requests.ConnectionError("boom"))+ status, message = check_access("sendowl-key", "sendowl-secret")+ assert status == 0+ assert message is not None and "boom" in message+++class TestSendowlSourceResponse:+ @parameterized.expand([("products",), ("orders",), ("subscriptions",), ("discount_codes",)])+ def test_response_uses_id_primary_key(self, endpoint: str) -> None:+ response = sendowl_source(+ api_key="sendowl-key",+ api_secret="sendowl-secret",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ 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 SENDOWL_ENDPOINTS.values())+ assert set(SENDOWL_ENDPOINTS) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendowl/tests/test_sendowl_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendowl/tests/test_sendowl_source.pynew file mode 100644index 000000000000..33c0d592b58e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendowl/tests/test_sendowl_source.py@@ -0,0 +1,153 @@+import pytest+from unittest import mock++from parameterized import parameterized++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 import SendowlSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.sendowl.sendowl import SendowlResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.sendowl.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.sendowl.source import SendowlSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestSendowlSource:+ def setup_method(self) -> None:+ self.source = SendowlSource()+ self.team_id = 123+ self.config = SendowlSourceConfig(api_key="sendowl-key", api_secret="sendowl-secret")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.SENDOWL++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Sendowl"+ assert config.label == "Sendowl"+ 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/sendowl"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key", "api_secret"]++ @parameterized.expand([("api_key",), ("api_secret",)])+ def test_credential_fields_are_secret_passwords(self, field_name: str) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == field_name)+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_connection_host_fields(self) -> None:+ # Both fields are secrets; the base URL is hardcoded and the account is implicit in the key+ # pair. There is no non-secret field that retargets where the credentials are sent.+ 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=["orders"])+ assert len(schemas) == 1+ assert schemas[0].name == "orders"++ 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)++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://www.sendowl.com/api/v1/products?page=1&per_page=50",),+ ("403 Client Error: Forbidden for url: https://www.sendowl.com/api/v1_3/orders?page=2&per_page=50",),+ ]+ )+ 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://www.sendowl.com/api/v1/products",),+ ("HTTPSConnectionPool(host='www.sendowl.com', port=443): Read timed out.",),+ ("429 Client Error: Too Many Requests for url: https://www.sendowl.com/api/v1_3/orders",),+ ]+ )+ 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(+ [+ ("reachable", 200, True, None),+ ("unauthorized", 401, False, "Invalid SendOwl API credentials"),+ ("forbidden", 403, False, "Invalid SendOwl API credentials"),+ ("server_error", 500, False, "SendOwl returned HTTP 500"),+ ("connection_error", 0, False, "Could not connect to SendOwl: boom"),+ ]+ )+ def test_validate_credentials(+ self,+ _name: str,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ ) -> None:+ message = (+ "SendOwl returned HTTP 500"+ if status == 500+ else ("Could not connect to SendOwl: boom" if status == 0 else None)+ )+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.sendowl.source.check_access"+ ) as mock_check:+ 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.sendowl.source.check_access")+ def test_validate_credentials_probes_the_credential_pair(self, mock_check: mock.MagicMock) -> None:+ mock_check.return_value = (200, None)+ self.source.validate_credentials(self.config, self.team_id, schema_name="orders")+ mock_check.assert_called_once_with("sendowl-key", "sendowl-secret")++ 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 SendowlResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.sendowl.source.sendowl_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_sendowl_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "products"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_sendowl_source.assert_called_once()+ kwargs = mock_sendowl_source.call_args.kwargs+ assert kwargs["api_key"] == "sendowl-key"+ assert kwargs["api_secret"] == "sendowl-secret"+ assert kwargs["endpoint"] == "products"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown SendOwl schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)