: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 smaily import source (#69367)
Tom Owersa97434583348
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 425d642be4e6..6cecbe657bd3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -326,6 +326,7 @@ the row lists both.| simplecast | HTTP | requests | ✅ || simplesat | HTTP | requests | ✅ || slack | HTTP | requests + `rest_source.RESTClient` | ✅ |+| smaily | HTTP | requests | ✅ || smartreach | HTTP | requests | ✅ || smartsheet | HTTP | requests | ✅ || snapchat_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -700,7 +701,6 @@ doesn't conflict with concurrent PRs.- simfin- simplecast- simplesat-- smaily- smartengage- smartwaiver- sonar_clouddiff --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 620d495790da..b9d58ff25e68 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@@ -3168,7 +3168,9 @@ class SlackSourceConfig(config.Config):@config.configclass SmailySourceConfig(config.Config):- pass+ subdomain: str+ username: str+ password: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smaily/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smaily/canonical_descriptions.pynew file mode 100644index 000000000000..d29ac837fd8e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smaily/canonical_descriptions.py@@ -0,0 +1,127 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Smaily API docs (https://smaily.com/help/api/).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "campaigns": {+ "description": "An email campaign sent (or drafted) in your Smaily account.",+ "docs_url": "https://smaily.com/help/api/campaigns-3/list-campaigns/",+ "columns": {+ "id": "Unique ID of the campaign.",+ "name": "Campaign name and message subject.",+ "template": "Template used in the campaign; 'DELETED' when the template was removed.",+ "tags": "List of campaign tags.",+ "created_at": "Campaign creation date, in Europe/Tallinn timezone.",+ "completed_at": "Campaign completion date; set only when the campaign's status is COMPLETED.",+ "status": "Campaign status: DRAFT, PENDING (sending in progress), COMPLETED, or CANCELLED.",+ },+ },+ "campaign_statistics": {+ "description": "Delivery, open, and click statistics for each campaign.",+ "docs_url": "https://smaily.com/help/api/campaigns-3/api-campaign-statistics/",+ "columns": {+ "id": "Campaign ID.",+ "name": "Campaign name and message subject.",+ "from": "Sender address of the campaign.",+ "reply_to": "Reply-To email address.",+ "template": "Template used in the campaign; 'DELETED' when the template was removed.",+ "status": "Campaign status: DRAFT, PENDING, COMPLETED, or CANCELLED.",+ "created_at": "Campaign creation date, in Europe/Tallinn timezone.",+ "completed_at": "Campaign completion date; set only when the campaign's status is COMPLETED.",+ "total_count": "Number of messages enqueued.",+ "delivered_count": "Number of messages successfully delivered.",+ "bounce_count": "Number of messages bounced.",+ "click_count": "Number of link clicks.",+ "unique_click_count": "Number of recipients who have clicked at least one link.",+ "click_percent": "Percentage of recipients who have clicked at least one link.",+ "view_count": "Number of times message images were downloaded.",+ "unique_view_count": "Number of recipients who have downloaded images at least once.",+ "view_percent": "Percentage of recipients who have downloaded images at least once.",+ "opened_count": "Number of recipients who have opened the message.",+ "opened_percent": "Percentage of recipients who have opened the message.",+ "unsubscribe_count": "Number of unsubscribed recipients.",+ "complaint_count": "Number of recipients who reported the message as spam.",+ "forward_count": "Number of times the message was forwarded.",+ },+ },+ "segments": {+ "description": "A subscriber segment (list) in your Smaily account.",+ "docs_url": "https://smaily.com/help/api/segments/list-segments/",+ "columns": {+ "id": "Segment ID.",+ "name": "Segment name.",+ "subscribers_count": "Number of subscribers in the segment.",+ },+ },+ "segment_subscribers": {+ "description": "Subscribers per segment, including subscription status, engagement timestamps, and any custom data fields. One row per subscriber per segment.",+ "docs_url": "https://smaily.com/help/api/segments/list-subscribers-of-a-segment/",+ "columns": {+ "segment_id": "ID of the segment the subscriber belongs to (added by PostHog for uniqueness).",+ "email": "Subscriber's email address.",+ "is_unsubscribed": "Subscription status: 0 - subscribed, 1 - unsubscribed.",+ "last_response_code": "Response code of the last failed message.",+ "last_response_at": "Date and time of the last failed email, in Europe/Tallinn timezone.",+ "created_at": "Date and time when the subscriber was added to Smaily.",+ "subscribed_at": "Date and time when the subscriber was added or re-subscribed.",+ "modified_at": "Date and time when the subscriber's data was last updated.",+ "last_open_at": "Latest date and time when the subscriber opened an email.",+ "total_opens": "Total number of emails opened.",+ "last_click_at": "Latest date and time when the subscriber clicked a trackable link.",+ "total_clicks": "Total number of clicks made.",+ "unsubscribed_at": "Date and time when the subscriber was marked unsubscribed.",+ },+ },+ "templates": {+ "description": "An email template in your Smaily account.",+ "docs_url": "https://smaily.com/help/api/templates-2/list-templates/",+ "columns": {+ "id": "Template ID.",+ "type": "Template type: 'default' (drag-and-drop) or 'wysiwyg' (custom HTML).",+ "name": "Template name.",+ "created_at": "Template creation datetime in RFC3339 format.",+ "modified_at": "Template last modification datetime in RFC3339 format.",+ "preview_url": "URL to the template's HTML preview.",+ },+ },+ "automations": {+ "description": "An automation workflow in your Smaily account.",+ "docs_url": "https://smaily.com/help/api/automations-2/list-automation-workflows/",+ "columns": {+ "id": "Automation workflow ID.",+ "name": "Automation workflow name.",+ "sections": "The workflow's 'Send Message' actions, each with its subject and template.",+ "tags": "List of automation workflow tags.",+ "created_at": "Workflow creation date, in Europe/Tallinn timezone.",+ "activated_at": "Workflow activation date; set only while the workflow is ACTIVE.",+ "status": "Automation workflow status: INACTIVE or ACTIVE.",+ },+ },+ "ab_tests": {+ "description": "An A/B test campaign in your Smaily account.",+ "docs_url": "https://smaily.com/help/api/a-b-tests/list-a-b-tests/",+ "columns": {+ "id": "A/B test ID.",+ "name": "A/B test name.",+ "sections": "List of sections in the A/B test, each with its subject and template.",+ "tags": "List of A/B test tags.",+ "created_at": "A/B test creation date, in Europe/Tallinn timezone.",+ "completed_at": "A/B test completion date; set only when the test's status is COMPLETED.",+ "status": "A/B test status: DRAFT, PENDING (sending in progress), COMPLETED, or CANCELLED.",+ },+ },+ "users": {+ "description": "A user of your Smaily organization.",+ "docs_url": "https://smaily.com/help/api/organizations/list-users-of-an-organization/",+ "columns": {+ "id": "User ID.",+ "email": "User's email address.",+ "first_name": "User's first name.",+ "last_name": "User's last name.",+ "is_owner": "Whether the user owns the organization.",+ "role": "User's role in the organization.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smaily/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smaily/settings.pynew file mode 100644index 000000000000..a6ce567993ac--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smaily/settings.py@@ -0,0 +1,85 @@+from dataclasses import dataclass, field++SEGMENT_SUBSCRIBERS = "segment_subscribers"+CAMPAIGN_STATISTICS = "campaign_statistics"+++@dataclass+class SmailyEndpointConfig:+ name: str+ path: str+ # Smaily's page-index parameter is named `page` on some endpoints and `offset` on others+ # (both are page numbers, not row offsets). `None` means the endpoint is not paginated.+ page_param: str | None = None+ # Explicit per-request row limit. Some endpoints return ALL rows when `limit` is omitted or 0,+ # so we always pass the documented per-endpoint cap.+ page_size: int | None = None+ extra_params: dict[str, str] = field(default_factory=dict)+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+++# Smaily list endpoints (https://smaily.com/help/api/). All are full refresh only: the API exposes+# no server-side `updated_after`-style filter on any list endpoint, so there is no reliable+# incremental cursor to advance (its Airbyte connector is likewise full-refresh only).+# Where the endpoint supports it we sort by `created_at` ascending so page boundaries stay stable+# while rows are inserted mid-sync.+SMAILY_ENDPOINTS: dict[str, SmailyEndpointConfig] = {+ "campaigns": SmailyEndpointConfig(+ name="campaigns",+ path="campaign.php",+ page_param="page",+ page_size=10000,+ extra_params={"sort_by": "created_at", "sort_order": "ASC"},+ ),+ CAMPAIGN_STATISTICS: SmailyEndpointConfig(+ # Fan-out: one request per campaign id (`campaign.php?id=...`), returning a single+ # statistics object per campaign.+ name=CAMPAIGN_STATISTICS,+ path="campaign.php",+ ),+ "segments": SmailyEndpointConfig(+ name="segments",+ path="list.php",+ ),+ SEGMENT_SUBSCRIBERS: SmailyEndpointConfig(+ # Fan-out: `contact.php` requires a `list` (segment id) param, so subscribers are synced+ # per segment. A subscriber can belong to several segments, hence the composite key —+ # `email` alone is only unique within one segment.+ name=SEGMENT_SUBSCRIBERS,+ path="contact.php",+ page_param="offset",+ page_size=25000,+ primary_keys=["segment_id", "email"],+ ),+ "templates": SmailyEndpointConfig(+ name="templates",+ path="templates.php",+ page_param="page",+ page_size=1000,+ extra_params={"sort_by": "created_at", "sort_order": "asc"},+ ),+ "automations": SmailyEndpointConfig(+ name="automations",+ path="autoresponder.php",+ page_param="page",+ page_size=10000,+ extra_params={"sort_by": "created_at", "sort_order": "ASC"},+ ),+ "ab_tests": SmailyEndpointConfig(+ name="ab_tests",+ path="split.php",+ page_param="offset",+ page_size=10000,+ extra_params={"sort_by": "created_at", "sort_order": "ASC"},+ ),+ "users": SmailyEndpointConfig(+ name="users",+ path="organizations/users.php",+ page_param="page",+ page_size=250,+ ),+}++ENDPOINTS = tuple(SMAILY_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smaily/smaily.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smaily/smaily.pynew file mode 100644index 000000000000..6a7ac4656a5c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smaily/smaily.py@@ -0,0 +1,325 @@+import re+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.smaily.settings import (+ CAMPAIGN_STATISTICS,+ SEGMENT_SUBSCRIBERS,+ SMAILY_ENDPOINTS,+ SmailyEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 60+# Fan-out endpoints issue one request per parent; yield + checkpoint every N parents so a resumed+# job re-fetches at most one chunk.+STATS_CHUNK_SIZE = 100+# Cheap endpoint used to confirm credentials are genuine: `list.php` takes no params and every API+# user can read it, so one probe validates access to the account.+DEFAULT_PROBE_PATH = "list.php"+# Smaily represents empty datetimes as a zero date instead of null.+ZERO_DATETIME = "0000-00-00 00:00:00"++_SUBDOMAIN_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$")+++class SmailyRetryableError(Exception):+ pass+++class SmailyResumeConfig:+ # Page index within the endpoint (or within the current parent for fan-out endpoints).+ page: int = 0+ # Fan-out endpoints only: parent ids (segments / campaigns) still to fetch, current one first.+ # `None` for top-level endpoints.+ pending_parent_ids: list[str] | None = None+++def normalize_subdomain(subdomain: str) -> str:+ """Reduce whatever the user pasted (bare subdomain, full URL, `x.sendsmaily.net`) to the bare+ subdomain, and reject anything that couldn't be one — the subdomain is interpolated into the+ request host, so it must never smuggle in another domain or a path."""+ value = subdomain.strip().lower()+ value = re.sub(r"^https?://", "", value)+ value = value.split("/", 1)[0]+ value = value.removesuffix(".sendsmaily.net")+ if not _SUBDOMAIN_RE.match(value):+ raise ValueError(f"Invalid Smaily subdomain: '{subdomain}'")+ return value+++def _base_url(subdomain: str) -> str:+ return f"https://{normalize_subdomain(subdomain)}.sendsmaily.net/api"+++def _make_session(username: str, password: str) -> requests.Session:+ session = make_tracked_session(headers={"Accept": "application/json"}, redact_values=(password,))+ session.auth = (username, password)+ return session+++@retry(+ retry=retry_if_exception_type((SmailyRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch(+ session: requests.Session,+ url: str,+ params: dict[str, Any],+ logger: FilteringBoundLogger,+ expect_list: bool = False,+) -> Any:+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)++ # Smaily rate limits at 5 requests/second per IP and returns 429 when exceeded.+ if response.status_code == 429 or response.status_code >= 500:+ raise SmailyRetryableError(f"Smaily API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Smaily API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ try:+ # Smaily serves JSON with a text/html Content-Type header, so parse unconditionally.+ data = response.json()+ except ValueError as e:+ raise SmailyRetryableError(f"Smaily returned a non-JSON payload for {url}") from e++ # Shape validation lives inside the retried function so a malformed payload gets the same+ # backoff treatment as a transport error instead of failing the sync on the first hit.+ if expect_list and (not isinstance(data, list) or not all(isinstance(row, dict) for row in data)):+ raise SmailyRetryableError(f"Smaily returned an unexpected payload for {url}: {type(data).__name__}")++ return data+++def _paged_params(config: SmailyEndpointConfig, page: int) -> dict[str, Any]:+ assert config.page_param is not None+ return {**config.extra_params, "limit": config.page_size, config.page_param: page}+++def _list_rows(+ session: requests.Session,+ base_url: str,+ config: SmailyEndpointConfig,+ manager: ResumableSourceManager[SmailyResumeConfig],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ url = f"{base_url}/{config.path}"++ if config.page_param is None:+ rows = _fetch(session, url, dict(config.extra_params), logger, expect_list=True)+ if rows:+ yield rows+ return++ resume = manager.load_state() if manager.can_resume() else None+ page = resume.page if resume else 0++ while True:+ rows = _fetch(session, url, _paged_params(config, page), logger, expect_list=True)+ if rows:+ yield rows++ assert config.page_size is not None+ if len(rows) < config.page_size:+ break++ page += 1+ # Save AFTER yielding so a crash re-fetches the last page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ manager.save_state(SmailyResumeConfig(page=page))+++def _fetch_all_pages(+ session: requests.Session,+ base_url: str,+ config: SmailyEndpointConfig,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ url = f"{base_url}/{config.path}"+ rows: list[dict[str, Any]] = []+ page = 0+ while True:+ page_rows = _fetch(session, url, _paged_params(config, page), logger, expect_list=True)+ rows.extend(page_rows)+ assert config.page_size is not None+ if len(page_rows) < config.page_size:+ return rows+ page += 1+++def _normalize_subscriber(row: dict[str, Any], segment_id: str) -> dict[str, Any]:+ # Zero dates become nulls so the columns can be parsed as timestamps downstream. `segment_id`+ # is injected for the composite primary key (subscriber rows don't carry their segment).+ normalized: dict[str, Any] = {key: (None if value == ZERO_DATETIME else value) for key, value in row.items()}+ normalized["segment_id"] = segment_id+ return normalized+++def _segment_subscriber_rows(+ session: requests.Session,+ base_url: str,+ manager: ResumableSourceManager[SmailyResumeConfig],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ config = SMAILY_ENDPOINTS[SEGMENT_SUBSCRIBERS]+ url = f"{base_url}/{config.path}"++ resume = manager.load_state() if manager.can_resume() else None+ if resume and resume.pending_parent_ids is not None:+ pending = list(resume.pending_parent_ids)+ page = resume.page+ else:+ segments = _fetch(session, f"{base_url}/list.php", {}, logger, expect_list=True)+ # Sort by id so the resume queue stays deterministic (list.php orders by mutable name).+ pending = sorted(str(segment["id"]) for segment in segments)+ page = 0++ while pending:+ segment_id = pending[0]++ while True:+ params = {"list": segment_id, **_paged_params(config, page)}+ rows = _fetch(session, url, params, logger, expect_list=True)+ normalized = [_normalize_subscriber(row, segment_id) for row in rows]+ if normalized:+ yield normalized++ assert config.page_size is not None+ if len(rows) < config.page_size:+ break++ page += 1+ manager.save_state(SmailyResumeConfig(page=page, pending_parent_ids=pending))++ pending = pending[1:]+ page = 0+ manager.save_state(SmailyResumeConfig(page=0, pending_parent_ids=pending))+++def _campaign_statistics_rows(+ session: requests.Session,+ base_url: str,+ manager: ResumableSourceManager[SmailyResumeConfig],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ config = SMAILY_ENDPOINTS[CAMPAIGN_STATISTICS]+ url = f"{base_url}/{config.path}"++ resume = manager.load_state() if manager.can_resume() else None+ if resume and resume.pending_parent_ids is not None:+ pending = list(resume.pending_parent_ids)+ else:+ campaigns = _fetch_all_pages(session, base_url, SMAILY_ENDPOINTS["campaigns"], logger)+ pending = [str(campaign["id"]) for campaign in campaigns]++ batch: list[dict[str, Any]] = []+ while pending:+ campaign_id = pending[0]+ stats = _fetch(session, url, {"id": campaign_id}, logger)+ if isinstance(stats, dict) and stats:+ batch.append(stats)+ else:+ # Keep one row per campaign even when the stats payload is unusable (e.g. an empty+ # list for a never-sent campaign) so the table doesn't silently omit campaigns;+ # the stats columns stay null. Match the numeric id type of regular stats rows.+ logger.warning(f"Smaily: campaign {campaign_id} statistics had an unexpected payload shape")+ batch.append({"id": int(campaign_id) if campaign_id.isdigit() else campaign_id})++ pending = pending[1:]+ if batch and (len(batch) >= STATS_CHUNK_SIZE or not pending):+ yield batch+ batch = []+ manager.save_state(SmailyResumeConfig(page=0, pending_parent_ids=pending))+++def get_rows(+ subdomain: str,+ username: str,+ password: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SmailyResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = SMAILY_ENDPOINTS[endpoint]+ session = _make_session(username, password)+ base_url = _base_url(subdomain)++ if endpoint == SEGMENT_SUBSCRIBERS:+ yield from _segment_subscriber_rows(session, base_url, resumable_source_manager, logger)+ elif endpoint == CAMPAIGN_STATISTICS:+ yield from _campaign_statistics_rows(session, base_url, resumable_source_manager, logger)+ else:+ yield from _list_rows(session, base_url, config, resumable_source_manager, logger)+++def smaily_source(+ subdomain: str,+ username: str,+ password: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SmailyResumeConfig],+) -> SourceResponse:+ config = SMAILY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ subdomain=subdomain,+ username=username,+ password=password,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )+++def check_access(subdomain: str, username: str, password: str) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the credentials.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem or malformed subdomain, other HTTP status otherwise.+ """+ try:+ base_url = _base_url(subdomain)+ except ValueError as e:+ return 0, str(e)++ session = _make_session(username, password)+ try:+ response = session.get(f"{base_url}/{DEFAULT_PROBE_PATH}", timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Smaily: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Smaily returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(subdomain: str, username: str, password: str) -> tuple[bool, str | None]:+ status, message = check_access(subdomain, username, password)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Smaily credentials. Check your subdomain, API username and password."+ return False, message or "Could not validate Smaily credentials"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smaily/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smaily/source.pyindex 01b5c1e7b2bd..5b46eb053455 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/smaily/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smaily/source.py@@ -1,19 +1,39 @@-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 SmailySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.smaily.settings import ENDPOINTS, SMAILY_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.smaily.smaily import (+ SmailyResumeConfig,+ smaily_source,+ validate_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SmailySource(SimpleSource[SmailySourceConfig]):+class SmailySource(ResumableSource[SmailySourceConfig, SmailyResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SMAILY@@ -24,7 +44,112 @@ class SmailySource(SimpleSource[SmailySourceConfig]):name=SchemaExternalDataSourceType.SMAILY,category=DataWarehouseSourceCategory.MARKETING___EMAIL,label="Smaily",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["sendsmaily", "email marketing"],+ caption="""Enter your Smaily API credentials to pull your email marketing data into the PostHog Data warehouse.++Create an API user in [Smaily](https://smaily.com) under **Account preferences → Integrations → API users**. Your subdomain is the first part of your Smaily URL, e.g. `mycompany` for `mycompany.sendsmaily.net`.+""",iconPath="/static/services/smaily.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/smaily",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="subdomain",+ label="Smaily subdomain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="mycompany",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="username",+ label="API username",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="password",+ label="API password",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),unreleasedSource=True,)++ @property+ def connection_host_fields(self) -> list[str]:+ # The stored API password is sent to `{subdomain}.sendsmaily.net`; retargeting the+ # subdomain must re-require the credentials.+ return ["subdomain"]++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.smaily.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Smaily authentication failed. Check your subdomain, API username and password, then reconnect.",+ "403 Client Error: Forbidden for url": "Your Smaily API user does not have access to this data. Check the API user's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: SmailySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — Smaily's list endpoints expose no 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: SmailySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The API user is account-wide, so a single probe validates access to every schema.+ return validate_credentials(config.subdomain, config.username, config.password)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SmailyResumeConfig]:+ return ResumableSourceManager[SmailyResumeConfig](inputs, SmailyResumeConfig)++ def source_for_pipeline(+ self,+ config: SmailySourceConfig,+ resumable_source_manager: ResumableSourceManager[SmailyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in SMAILY_ENDPOINTS:+ raise ValueError(f"Unknown Smaily schema '{inputs.schema_name}'")++ return smaily_source(+ subdomain=config.subdomain,+ username=config.username,+ password=config.password,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smaily/tests/test_smaily.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smaily/tests/test_smaily.pynew file mode 100644index 000000000000..06e1d84e5519--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smaily/tests/test_smaily.py@@ -0,0 +1,394 @@+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.smaily import smaily+from products.warehouse_sources.backend.temporal.data_imports.sources.smaily.settings import (+ CAMPAIGN_STATISTICS,+ ENDPOINTS,+ SEGMENT_SUBSCRIBERS,+ SMAILY_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.smaily.smaily import (+ SmailyResumeConfig,+ SmailyRetryableError,+ check_access,+ get_rows,+ normalize_subdomain,+ smaily_source,+ validate_credentials,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_unwrapped = smaily._fetch.__wrapped__ # type: ignore[attr-defined]++BASE_URL = "https://acme.sendsmaily.net/api"+++class _FakeResumableManager:+ def __init__(self, state: SmailyResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[SmailyResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> SmailyResumeConfig | None:+ return self._state++ def save_state(self, data: SmailyResumeConfig) -> None:+ self.saved.append(data)+++class _FakeApi:+ """Routes `_fetch(session, url, params, logger)` calls to canned responses and records requests."""++ def __init__(self, responder: Any) -> None:+ self._responder = responder+ self.requests: list[tuple[str, dict[str, Any]]] = []++ def __call__(self, session: Any, url: str, params: dict[str, Any], logger: Any, expect_list: bool = False) -> Any:+ self.requests.append((url, dict(params)))+ return self._responder(url, params)+++def _collect(+ monkeypatch: Any,+ endpoint: str,+ responder: Any,+ manager: _FakeResumableManager | None = None,+) -> tuple[list[dict], _FakeApi, _FakeResumableManager]:+ api = _FakeApi(responder)+ manager = manager or _FakeResumableManager()+ monkeypatch.setattr(smaily, "_fetch", api)+ monkeypatch.setattr(smaily, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ subdomain="acme",+ username="user",+ password="pass",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows, api, manager+++class TestNormalizeSubdomain:+ @parameterized.expand(+ [+ ("bare", "acme", "acme"),+ ("uppercase_and_whitespace", " ACME ", "acme"),+ ("full_domain", "acme.sendsmaily.net", "acme"),+ ("full_url_with_path", "https://acme.sendsmaily.net/api/", "acme"),+ ("hyphenated", "my-company", "my-company"),+ ]+ )+ def test_valid_inputs(self, _name: str, raw: str, expected: str) -> None:+ assert normalize_subdomain(raw) == expected++ @parameterized.expand(+ [+ ("empty", ""),+ ("other_domain", "evil.com"),+ ("smuggled_credentials", "[email protected]"),+ ("leading_hyphen", "-acme"),+ ]+ )+ def test_invalid_inputs_are_rejected(self, _name: str, raw: str) -> None:+ with pytest.raises(ValueError):+ normalize_subdomain(raw)+++class TestFetch:+ def _session_returning(self, status_code: int, body: Any = None, invalid_json: bool = False) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ if invalid_json:+ response.json.side_effect = ValueError("not json")+ else:+ 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(SmailyRetryableError):+ _fetch_unwrapped(session, f"{BASE_URL}/campaign.php", {}, 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_unwrapped(session, f"{BASE_URL}/campaign.php", {}, MagicMock())++ def test_non_json_body_is_retryable(self) -> None:+ # Smaily serves JSON with a text/html Content-Type; an HTML error page must not crash the sync.+ session = self._session_returning(200, invalid_json=True)+ with pytest.raises(SmailyRetryableError):+ _fetch_unwrapped(session, f"{BASE_URL}/campaign.php", {}, MagicMock())++ @parameterized.expand([("dict_body", {"error": "nope"}), ("non_dict_rows", ["oops"])])+ def test_unexpected_list_shape_is_retryable_inside_fetch(self, _name: str, body: Any) -> None:+ # Shape validation must run inside the retried function so a malformed payload gets+ # backoff instead of failing the sync on the first hit.+ session = self._session_returning(200, body)+ with pytest.raises(SmailyRetryableError):+ _fetch_unwrapped(session, f"{BASE_URL}/campaign.php", {}, MagicMock(), expect_list=True)+++class TestTopLevelEndpoints:+ def test_pages_until_short_page(self, monkeypatch: Any) -> None:+ page_size = SMAILY_ENDPOINTS["campaigns"].page_size+ assert page_size is not None+ pages = {+ 0: [{"id": i} for i in range(page_size)],+ 1: [{"id": page_size}],+ }+ rows, api, manager = _collect(monkeypatch, "campaigns", lambda url, params: pages[params["page"]])++ assert len(rows) == page_size + 1+ # State is saved after the first full page so a retry skips straight to page 1.+ assert [s.page for s in manager.saved] == [1]++ def test_uses_endpoint_specific_page_param_and_limit(self, monkeypatch: Any) -> None:+ # Smaily names the page-index param `page` on some endpoints and `offset` on others;+ # mixing them up silently returns page 0 forever.+ _, campaigns_api, _ = _collect(monkeypatch, "campaigns", lambda url, params: [])+ _, ab_tests_api, _ = _collect(monkeypatch, "ab_tests", lambda url, params: [])++ campaigns_url, campaigns_params = campaigns_api.requests[0]+ assert campaigns_url == f"{BASE_URL}/campaign.php"+ assert campaigns_params["page"] == 0+ assert campaigns_params["limit"] == SMAILY_ENDPOINTS["campaigns"].page_size+ assert campaigns_params["sort_by"] == "created_at"++ ab_tests_url, ab_tests_params = ab_tests_api.requests[0]+ assert ab_tests_url == f"{BASE_URL}/split.php"+ assert ab_tests_params["offset"] == 0+ assert "page" not in ab_tests_params++ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(SmailyResumeConfig(page=3))+ rows, api, _ = _collect(monkeypatch, "campaigns", lambda url, params: [{"id": 1}], manager)++ assert rows == [{"id": 1}]+ assert api.requests[0][1]["page"] == 3++ def test_unpaginated_endpoint_fetches_once_without_page_params(self, monkeypatch: Any) -> None:+ rows, api, manager = _collect(monkeypatch, "segments", lambda url, params: [{"id": 4, "name": "Women"}])++ assert rows == [{"id": 4, "name": "Women"}]+ assert api.requests == [(f"{BASE_URL}/list.php", {})]+ assert manager.saved == []++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ rows, _, manager = _collect(monkeypatch, "campaigns", lambda url, params: [])+ assert rows == []+ assert manager.saved == []+++class TestSegmentSubscribers:+ @staticmethod+ def _responder(subscribers_by_segment: dict[str, list[list[dict] | None]]) -> Any:+ def respond(url: str, params: dict[str, Any]) -> Any:+ if url.endswith("/list.php"):+ return [{"id": segment_id} for segment_id in subscribers_by_segment]+ return subscribers_by_segment[params["list"]][params["offset"]]++ return respond++ def test_fans_out_over_segments_and_annotates_rows(self, monkeypatch: Any) -> None:+ responder = self._responder(+ {+ "1": [[{"email": "[email protected]", "last_open_at": "0000-00-00 00:00:00", "custom_field": "jah"}]],+ "2": [[{"email": "[email protected]", "last_open_at": "2024-01-01 10:00:00"}]],+ }+ )+ rows, _, _ = _collect(monkeypatch, SEGMENT_SUBSCRIBERS, responder)++ # The same email in two segments stays two distinct rows keyed by (segment_id, email).+ assert rows == [+ {"email": "[email protected]", "last_open_at": None, "custom_field": "jah", "segment_id": "1"},+ {"email": "[email protected]", "last_open_at": "2024-01-01 10:00:00", "segment_id": "2"},+ ]++ def test_paginates_within_segment_and_saves_state_after_yield(self, monkeypatch: Any) -> None:+ page_size = SMAILY_ENDPOINTS[SEGMENT_SUBSCRIBERS].page_size+ assert page_size is not None+ responder = self._responder(+ {+ "1": [+ [{"email": f"user{i}@x.com"} for i in range(page_size)],+ [{"email": "[email protected]"}],+ ],+ }+ )+ rows, _, manager = _collect(monkeypatch, SEGMENT_SUBSCRIBERS, responder)++ assert len(rows) == page_size + 1+ # First save: next page of segment 1; second save: segment 1 finished, queue empty.+ assert [(s.page, s.pending_parent_ids) for s in manager.saved] == [(1, ["1"]), (0, [])]++ def test_resumes_mid_segment_without_refetching_segment_list(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(SmailyResumeConfig(page=2, pending_parent_ids=["5", "6"]))+ responder = self._responder(+ {+ "5": [None, None, [{"email": "[email protected]"}]], # only page 2 is ever requested+ "6": [[{"email": "[email protected]"}]],+ }+ )+ rows, api, _ = _collect(monkeypatch, SEGMENT_SUBSCRIBERS, responder, manager)++ assert [row["email"] for row in rows] == ["[email protected]", "[email protected]"]+ # The segment list must not be re-fetched on resume — ids come from the saved queue.+ assert all(not url.endswith("/list.php") for url, _ in api.requests)+ assert api.requests[0][1] == {"list": "5", "limit": 25000, "offset": 2}+++class TestCampaignStatistics:+ @staticmethod+ def _responder(stats_by_id: dict[str, Any]) -> Any:+ def respond(url: str, params: dict[str, Any]) -> Any:+ if "id" in params:+ return stats_by_id[params["id"]]+ return [{"id": int(campaign_id)} for campaign_id in stats_by_id]++ return respond++ def test_yields_one_row_per_campaign(self, monkeypatch: Any) -> None:+ responder = self._responder(+ {+ "1": {"id": 1, "delivered_count": 10},+ "2": {"id": 2, "delivered_count": 20},+ }+ )+ rows, _, manager = _collect(monkeypatch, CAMPAIGN_STATISTICS, responder)++ assert rows == [{"id": 1, "delivered_count": 10}, {"id": 2, "delivered_count": 20}]+ assert manager.saved[-1].pending_parent_ids == []++ def test_resume_skips_already_processed_campaigns(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(SmailyResumeConfig(page=0, pending_parent_ids=["3"]))+ responder = self._responder({"3": {"id": 3, "delivered_count": 30}})+ rows, api, _ = _collect(monkeypatch, CAMPAIGN_STATISTICS, responder, manager)++ assert rows == [{"id": 3, "delivered_count": 30}]+ # The campaign listing must not be re-fetched on resume.+ assert api.requests == [(f"{BASE_URL}/campaign.php", {"id": "3"})]++ def test_unusable_stats_payload_yields_id_only_row(self, monkeypatch: Any) -> None:+ # A campaign whose stats come back malformed (e.g. an empty list) must not silently+ # vanish from the table — it keeps a row with a numeric id and null stats columns.+ responder = self._responder({"1": [], "2": {"id": 2, "delivered_count": 20}})+ rows, _, _ = _collect(monkeypatch, CAMPAIGN_STATISTICS, responder)++ assert rows == [{"id": 1}, {"id": 2, "delivered_count": 20}]+++class TestCheckAccess:+ @staticmethod+ def _session(response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ return session++ @parameterized.expand(+ [+ ("ok", 200, True, 200, None),+ ("unauthorized", 401, False, 401, None),+ ("forbidden", 403, False, 403, None),+ ("server_error", 500, False, 500, "Smaily returned HTTP 500"),+ ]+ )+ @patch(f"{smaily.__name__}.make_tracked_session")+ def test_status_mapping(+ self,+ _name: str,+ status: int,+ ok: bool,+ expected_status: int,+ expected_message: str | None,+ mock_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ mock_session.return_value = self._session(response)+ assert check_access("acme", "user", "pass") == (expected_status, expected_message)++ @patch(f"{smaily.__name__}.make_tracked_session")+ def test_connection_error_maps_to_zero(self, mock_session: MagicMock) -> None:+ mock_session.return_value = self._session(requests.ConnectionError("boom"))+ status, message = check_access("acme", "user", "pass")+ assert status == 0+ assert message is not None and "boom" in message++ def test_invalid_subdomain_fails_without_a_request(self) -> None:+ valid, message = validate_credentials("evil.com/path?x=", "user", "pass")+ assert valid is False+ assert message is not None and "subdomain" in message.lower()++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ (+ "unauthorized",+ 401,+ False,+ "Invalid Smaily credentials. Check your subdomain, API username and password.",+ ),+ ("forbidden", 403, False, "Invalid Smaily credentials. Check your subdomain, API username and password."),+ ("server_error", 500, False, "Smaily returned HTTP 500"),+ ]+ )+ @patch(f"{smaily.__name__}.make_tracked_session")+ def test_validate_credentials(+ self,+ _name: str,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ mock_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ mock_session.return_value = self._session(response)+ assert validate_credentials("acme", "user", "pass") == (expected_valid, expected_message)+++class TestSmailySourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = smaily_source(+ subdomain="acme",+ username="user",+ password="pass",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == SMAILY_ENDPOINTS[endpoint].primary_keys++ def test_segment_subscribers_key_includes_parent_segment(self) -> None:+ # `email` alone is only unique within one segment; dropping the parent id from the key+ # would multi-match merges for subscribers in several segments.+ assert SMAILY_ENDPOINTS[SEGMENT_SUBSCRIBERS].primary_keys == ["segment_id", "email"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smaily/tests/test_smaily_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smaily/tests/test_smaily_source.pynew file mode 100644index 000000000000..a1a894858105--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smaily/tests/test_smaily_source.py@@ -0,0 +1,131 @@+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 SmailySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.smaily.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.smaily.smaily import SmailyResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.smaily.source import SmailySource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestSmailySource:+ def setup_method(self) -> None:+ self.source = SmailySource()+ self.team_id = 123+ self.config = SmailySourceConfig(subdomain="acme", username="user", password="pass")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.SMAILY++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Smaily"+ assert config.label == "Smaily"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/smaily"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["subdomain", "username", "password"]++ def test_password_field_is_secret(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "password")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_subdomain_is_a_connection_host_field(self) -> None:+ # The stored password is sent to `{subdomain}.sendsmaily.net`; retargeting the subdomain+ # without re-entering the password would let an editor replay the credential elsewhere.+ assert self.source.connection_host_fields == ["subdomain"]++ 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=["campaigns"])+ assert len(schemas) == 1+ assert schemas[0].name == "campaigns"++ 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:+ assert self.source.lists_tables_without_credentials is True+ 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(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://acme.sendsmaily.net/api/campaign.php?page=0",+ ),+ ("forbidden", "403 Client Error: Forbidden for url: https://acme.sendsmaily.net/api/contact.php?list=1"),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name: str, 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(+ [+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://acme.sendsmaily.net/api/campaign.php",+ ),+ (+ "rate_limited",+ "429 Client Error: Too Many Requests for url: https://acme.sendsmaily.net/api/list.php",+ ),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.smaily.source.validate_credentials")+ def test_validate_credentials_delegates_with_config_values(self, mock_validate: mock.MagicMock) -> None:+ # The status-to-message mapping lives in smaily.validate_credentials; here we only assert+ # the source probes with the configured credentials and returns the verdict unchanged.+ mock_validate.return_value = (False, "Invalid Smaily credentials")+ result = self.source.validate_credentials(self.config, self.team_id)+ mock_validate.assert_called_once_with("acme", "user", "pass")+ assert result == (False, "Invalid Smaily credentials")++ 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 SmailyResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.smaily.source.smaily_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "campaigns"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["subdomain"] == "acme"+ assert kwargs["username"] == "user"+ assert kwargs["password"] == "pass"+ assert kwargs["endpoint"] == "campaigns"+ 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 Smaily schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)