Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement mailosaur import source (#67810)

Tom Owers7ddf0ed53b9e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 4194ace4a8fe..c3b585436ae1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -199,6 +199,7 @@ the row lists both.
| mailersend | HTTP | requests | ✅ |
| mailgun | HTTP | requests | ✅ |
| mailjet | HTTP | requests | ✅ |
+| mailosaur | HTTP | requests | ✅ |
| marketstack | HTTP | requests | ✅ |
| matomo | HTTP | requests | ✅ |
| meta_ads | HTTP | requests | ✅ |
@@ -505,7 +506,6 @@ doesn't conflict with concurrent PRs.
- looker
- loops
- luma
-- mailosaur
- mailtrap
- mantle
- marketo
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.py
index 25cb2eeb7854..57f63d714015 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
@@ -1927,7 +1927,7 @@ class MailjetSourceConfig(config.Config):
@config.config
class MailosaurSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/canonical_descriptions.py
new file mode 100644
index 000000000000..00d11acb2b3b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/canonical_descriptions.py
@@ -0,0 +1,48 @@
+"""Canonical, documentation-sourced descriptions for Mailosaur endpoints and columns.
+
+Sourced from the official Mailosaur API reference (https://mailosaur.com/docs/api/). Keyed by the
+endpoint names in `settings.py` `MAILOSAUR_ENDPOINTS`, which match the `ExternalDataSchema.name` of
+a synced Mailosaur table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "servers": {
+ "description": "Virtual test inboxes (SMTP/SMS servers) on the Mailosaur account.",
+ "docs_url": "https://mailosaur.com/docs/api/servers/",
+ "columns": {
+ "id": "Unique identifier for the server.",
+ "name": "The name of the server.",
+ "users": "Users with access to the server.",
+ "messages": "The number of messages currently held by the server.",
+ },
+ },
+ "messages": {
+ "description": "Summaries of emails and SMS messages received by each server. The parent server id is injected as `server`.",
+ "docs_url": "https://mailosaur.com/docs/api/messages/",
+ "columns": {
+ "id": "Unique identifier for the message.",
+ "server": "Identifier of the server that received the message (injected during sync).",
+ "received": "The datetime the message was received.",
+ "type": "The type of message (e.g. Email or SMS).",
+ "subject": "The message's subject line.",
+ "from": "The sender(s) of the message, each with a name and email/phone.",
+ "to": "The recipient(s) of the message, each with a name and email/phone.",
+ "cc": "Carbon-copy recipients of the message.",
+ "bcc": "Blind carbon-copy recipients of the message.",
+ },
+ },
+ "usage_transactions": {
+ "description": "The last 31 days of account transactional usage, one row per day.",
+ "docs_url": "https://mailosaur.com/docs/api/usage/",
+ "columns": {
+ "timestamp": "The date of the usage record.",
+ "email": "The number of emails received that day.",
+ "sms": "The number of SMS messages received that day.",
+ "previews": "The number of email previews generated that day.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/mailosaur.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/mailosaur.py
new file mode 100644
index 000000000000..77d034a5653a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/mailosaur.py
@@ -0,0 +1,272 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode, urlsplit
+
+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.mailosaur.settings import (
+ MAILOSAUR_ENDPOINTS,
+ MailosaurEndpointConfig,
+)
+
+# All Mailosaur API traffic is HTTPS against the single documented host.
+MAILOSAUR_BASE_URL = "https://mailosaur.com"
+
+# Messages list pagination — itemsPerPage caps at 1000 (default 50); pull the max to minimize round-trips.
+MESSAGES_PAGE_SIZE = 1000
+
+MAILOSAUR_HEADERS = {"Accept": "application/json"}
+
+
+class MailosaurRetryableError(Exception):
+ pass
+
+
+class MailosaurResumeConfig:
+ # Server whose messages we were paginating when the sync was interrupted. A stable
+ # server-id bookmark (not a positional index) so servers added/removed between a crash
+ # and the retry can't resume us into the wrong server. `None` for the non-fan-out
+ # endpoints (servers, usage_transactions), which are a single request.
+ server_id: str | None = None
+ # Next page (0-based) to fetch for `server_id`.
+ page: int = 0
+
+
+def _auth(api_key: str) -> tuple[str, str]:
+ """Mailosaur authenticates with the API key as the HTTP Basic auth username and no password."""
+ return (api_key, "")
+
+
+def _format_received_after(value: Any) -> str | None:
+ """Format an incremental cursor value as an ISO-8601 UTC timestamp for `receivedAfter`."""
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ # The messages cursor is a DateTime field, so anything else is a bug — fail loud rather than
+ # sending Mailosaur an unparseable receivedAfter it would silently ignore (a full re-fetch).
+ raise TypeError(f"Unsupported receivedAfter value type: {type(value)!r}")
+
+
+def _extract_items(data: Any) -> list[dict[str, Any]]:
+ """Mailosaur list endpoints wrap results as ``{"items": [...]}``; be defensive and also
+ accept a bare array in case a response comes back unwrapped."""
+ if isinstance(data, dict):
+ items = data.get("items")
+ return items if isinstance(items, list) else []
+ if isinstance(data, list):
+ return data
+ return []
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ MailosaurRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch(
+ session: requests.Session,
+ api_key: str,
+ path: str,
+ logger: FilteringBoundLogger,
+ params: dict[str, Any] | None = None,
+) -> Any:
+ url = f"{MAILOSAUR_BASE_URL}{path}"
+ if params:
+ url = f"{url}?{urlencode(params)}"
+
+ response = session.get(url, auth=_auth(api_key), headers=MAILOSAUR_HEADERS, timeout=60)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise MailosaurRetryableError(f"Mailosaur API error (retryable): status={response.status_code}, path={path}")
+
+ if not response.ok:
+ logger.error(f"Mailosaur API error: status={response.status_code}, body={response.text}, path={path}")
+ # raise_for_status() would embed the full request URL in the exception, which is surfaced
+ # as the schema's latest_error. Mailosaur authenticates via HTTP Basic auth today, but
+ # rebuild the error from scheme/host/path only so a redirect or future query-param auth can
+ # never leak the api_key into stored error state. The "<status> Client Error: <reason> for
+ # url: https://mailosaur.com" prefix stays stable for get_non_retryable_errors() matching.
+ safe = urlsplit(response.url)
+ raise requests.HTTPError(
+ f"{response.status_code} Client Error: {response.reason} for url: {safe.scheme}://{safe.netloc}{safe.path}",
+ response=response,
+ )
+
+ return response.json()
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ """Probe the account-level `GET /api/servers` endpoint to confirm the key is genuine.
+
+ An account-level key is required to enumerate servers (and therefore to sync any mail);
+ a server-scoped key is rejected here, which is the correct signal for this connector.
+ """
+ url = f"{MAILOSAUR_BASE_URL}/api/servers"
+ try:
+ response = make_tracked_session(redact_values=(api_key,)).get(
+ url, auth=_auth(api_key), headers=MAILOSAUR_HEADERS, timeout=10
+ )
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, "Invalid Mailosaur API key"
+ if response.status_code == 403:
+ return False, "This Mailosaur API key cannot list servers. Use an account-level API key."
+ return False, f"Mailosaur API error: {response.status_code}"
+
+
+def _iter_servers(session: requests.Session, api_key: str, logger: FilteringBoundLogger) -> list[dict[str, Any]]:
+ """List every server on the account. The endpoint returns all servers in one response."""
+ data = _fetch(session, api_key, "/api/servers", logger)
+ return _extract_items(data)
+
+
+def _get_message_rows(
+ session: requests.Session,
+ api_key: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MailosaurResumeConfig],
+ received_after: str | None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Fan out over every server, yielding message summaries newest-first per server.
+
+ Each summary omits its parent server, so we inject `server` onto every row to make the
+ (server, id) primary key unique table-wide. `receivedAfter` bounds the low end server-side,
+ so incremental syncs only walk the delta.
+ """
+ servers = _iter_servers(session, api_key, logger)
+ server_ids = [server["id"] for server in servers]
+
+ # Resolve the saved bookmark to the slice of servers still to process. If the bookmarked
+ # server no longer exists (deleted between runs), start over from the first — merge dedupes
+ # the re-pulled rows on the primary key.
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ remaining = server_ids
+ resume_page = 0
+ if resume is not None and resume.server_id is not None and resume.server_id in server_ids:
+ remaining = server_ids[server_ids.index(resume.server_id) :]
+ resume_page = resume.page
+ logger.debug(f"Mailosaur: resuming messages from server_id={resume.server_id}, page={resume_page}")
+
+ for index, server_id in enumerate(remaining):
+ page = resume_page if index == 0 else 0
+ while True:
+ params: dict[str, Any] = {
+ "server": server_id,
+ "page": page,
+ "itemsPerPage": MESSAGES_PAGE_SIZE,
+ }
+ if received_after:
+ params["receivedAfter"] = received_after
+
+ items = _extract_items(_fetch(session, api_key, "/api/messages", logger, params))
+ if items:
+ for item in items:
+ item["server"] = server_id
+ yield items
+
+ # Offset pagination: a short (or empty) page means we've reached the end for this server.
+ if len(items) < MESSAGES_PAGE_SIZE:
+ break
+
+ page += 1
+ # Save AFTER yielding so a crash re-yields the last page (merge dedupes) rather than
+ # skipping it. Bookmark the NEXT page to fetch for the current server.
+ resumable_source_manager.save_state(MailosaurResumeConfig(server_id=server_id, page=page))
+
+ # Advance the bookmark to the next server so a crash between servers resumes correctly.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(MailosaurResumeConfig(server_id=remaining[index + 1], page=0))
+
+
+def _get_simple_rows(
+ session: requests.Session,
+ api_key: str,
+ config: MailosaurEndpointConfig,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Single-request endpoints (servers, usage_transactions) that return the full table at once."""
+ items = _extract_items(_fetch(session, api_key, config.path, logger))
+ if items:
+ yield items
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MailosaurResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = MAILOSAUR_ENDPOINTS[endpoint]
+ # One session reused across every page (and, for the fan-out, every server) so urllib3
+ # keeps the connection alive instead of re-handshaking per request. `redact_values` masks
+ # the API key in logged URLs and captured samples.
+ session = make_tracked_session(redact_values=(api_key,))
+
+ if config.fan_out_over_servers:
+ received_after = (
+ _format_received_after(db_incremental_field_last_value)
+ if should_use_incremental_field and db_incremental_field_last_value
+ else None
+ )
+ yield from _get_message_rows(session, api_key, logger, resumable_source_manager, received_after)
+ return
+
+ yield from _get_simple_rows(session, api_key, config, logger)
+
+
+def mailosaur_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MailosaurResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ endpoint_config = MAILOSAUR_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=endpoint_config.primary_keys,
+ # Messages arrive newest-first and the API exposes no ascending sort, so the watermark
+ # (max received) is finalized only at end of sync — see finalize_desc_sort_incremental_value.
+ sort_mode="desc" if endpoint_config.fan_out_over_servers else "asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="week" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/settings.py
new file mode 100644
index 000000000000..8f2fb42a1029
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/settings.py
@@ -0,0 +1,60 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class MailosaurEndpointConfig:
+ name: str
+ path: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable datetime column to partition by (never a mutable field like `updated`).
+ partition_key: Optional[str] = None
+ # Whether the endpoint is scoped per server and must be fanned out over `GET /api/servers`.
+ fan_out_over_servers: bool = False
+ should_sync_default: bool = True
+
+
+MAILOSAUR_ENDPOINTS: dict[str, MailosaurEndpointConfig] = {
+ # Every server (virtual inbox) on the account. Full refresh only — the servers list
+ # carries no timestamp we could filter or partition on.
+ "servers": MailosaurEndpointConfig(
+ name="servers",
+ path="/api/servers",
+ primary_keys=["id"],
+ ),
+ # Message summaries per server. Fanned out over every server, incremental via the
+ # `receivedAfter` server-side filter on the immutable `received` timestamp. Message ids
+ # are GUIDs, but the summary payload omits the server, so we inject it and key on
+ # (server, id) to stay unique table-wide across the fan-out.
+ "messages": MailosaurEndpointConfig(
+ name="messages",
+ path="/api/messages",
+ primary_keys=["server", "id"],
+ partition_key="received",
+ fan_out_over_servers=True,
+ incremental_fields=[
+ {
+ "label": "received",
+ "type": IncrementalFieldType.DateTime,
+ "field": "received",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ # Rolling last-31-days of account transactional usage (emails / SMS / previews per day).
+ # No server-side time filter, so it is full refresh only.
+ "usage_transactions": MailosaurEndpointConfig(
+ name="usage_transactions",
+ path="/api/usage/transactions",
+ primary_keys=["timestamp"],
+ ),
+}
+
+ENDPOINTS = tuple(MAILOSAUR_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in MAILOSAUR_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/source.py
index 808aaf8c960c..70ef49c14d75 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/source.py
@@ -1,19 +1,43 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MailosaurSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailosaur.mailosaur import (
+ MailosaurResumeConfig,
+ mailosaur_source,
+ validate_credentials as validate_mailosaur_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailosaur.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ MAILOSAUR_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class MailosaurSource(SimpleSource[MailosaurSourceConfig]):
+class MailosaurSource(ResumableSource[MailosaurSourceConfig, MailosaurResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.MAILOSAUR
@@ -24,7 +48,89 @@ class MailosaurSource(SimpleSource[MailosaurSourceConfig]):
name=SchemaExternalDataSourceType.MAILOSAUR,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Mailosaur",
- iconPath="/static/services/mailosaur.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Mailosaur API key to sync your email and SMS testing data into the PostHog Data warehouse.
+
+You can find your API key in your [Mailosaur account settings](https://mailosaur.com/app/keys).
+
+Use an **account-level** API key — a server-scoped key cannot list servers, so it can't enumerate the mail to sync.""",
+ iconPath="/static/services/mailosaur.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/mailosaur",
+ 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.mailosaur.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://mailosaur.com": "Your Mailosaur API key is invalid or has been revoked. Create a new key in your Mailosaur account settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://mailosaur.com": "Your Mailosaur API key cannot access this data. Use an account-level API key, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: MailosaurSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=has_incremental,
+ supports_append=has_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=MAILOSAUR_ENDPOINTS[endpoint].should_sync_default,
+ detected_primary_keys=MAILOSAUR_ENDPOINTS[endpoint].primary_keys,
+ )
+
+ schemas = [_build_schema(endpoint) 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: MailosaurSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_mailosaur_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MailosaurResumeConfig]:
+ return ResumableSourceManager[MailosaurResumeConfig](inputs, MailosaurResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: MailosaurSourceConfig,
+ resumable_source_manager: ResumableSourceManager[MailosaurResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return mailosaur_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/tests/test_mailosaur.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/tests/test_mailosaur.py
new file mode 100644
index 000000000000..593a65db7ed1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/tests/test_mailosaur.py
@@ -0,0 +1,248 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailosaur import mailosaur
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailosaur.mailosaur import (
+ MailosaurResumeConfig,
+ _extract_items,
+ _format_received_after,
+ get_rows,
+ mailosaur_source,
+ validate_credentials,
+)
+
+
+class _FakeManager:
+ """In-memory stand-in for ResumableSourceManager so we can assert save/resume behavior."""
+
+ def __init__(self, state: MailosaurResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[MailosaurResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> MailosaurResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: MailosaurResumeConfig) -> None:
+ self.saved.append(data)
+ self._state = data
+
+
+def _drain(iterator: Any) -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ for batch in iterator:
+ rows.extend(batch)
+ return rows
+
+
+class TestExtractItems:
+ @parameterized.expand(
+ [
+ ("wrapped", {"items": [{"id": "a"}, {"id": "b"}]}, [{"id": "a"}, {"id": "b"}]),
+ ("bare_list", [{"id": "a"}], [{"id": "a"}]),
+ ("empty_wrapped", {"items": []}, []),
+ ("missing_items", {"foo": 1}, []),
+ ("none", None, []),
+ ]
+ )
+ def test_extract_items(self, _name: str, payload: Any, expected: list[dict[str, Any]]) -> None:
+ # Mailosaur wraps list results as {"items": [...]}; the bare-list branch guards an
+ # unwrapped response so a shape change doesn't silently sync zero rows.
+ assert _extract_items(payload) == expected
+
+
+class TestFormatReceivedAfter:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00Z"),
+ ("none", None, None),
+ ]
+ )
+ def test_format(self, _name: str, value: Any, expected: str | None) -> None:
+ assert _format_received_after(value) == expected
+
+ @parameterized.expand([("int_epoch", 1234567890), ("string", "not-a-date")])
+ def test_unexpected_type_raises(self, _name: str, value: Any) -> None:
+ # The messages cursor is a DateTime; an int/str would produce a receivedAfter Mailosaur
+ # silently ignores (a full re-fetch), so we fail loud instead.
+ with pytest.raises(TypeError):
+ _format_received_after(value)
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, True),
+ ("unauthorized", 401, False),
+ ("forbidden", 403, False),
+ ("server_error", 500, False),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status_code: int, expected_ok: bool) -> None:
+ response = MagicMock()
+ response.status_code = status_code
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.mailosaur.mailosaur.make_tracked_session"
+ ) as session_factory:
+ session_factory.return_value.get.return_value = response
+ ok, error = validate_credentials("key")
+ assert ok is expected_ok
+ assert (error is None) is expected_ok
+
+
+class TestMessagesFanOut:
+ def _run(
+ self,
+ fetch_side_effect: Any,
+ manager: _FakeManager,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ ) -> tuple[list[dict[str, Any]], MagicMock]:
+ with (
+ patch.object(mailosaur, "make_tracked_session"),
+ patch.object(mailosaur, "_fetch", side_effect=fetch_side_effect) as fetch,
+ ):
+ rows = _drain(
+ get_rows(
+ api_key="key",
+ endpoint="messages",
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+ )
+ return rows, fetch
+
+ def test_injects_server_and_fans_out_over_servers(self) -> None:
+ def fetch(session: Any, api_key: str, path: str, logger: Any, params: Any = None) -> Any:
+ if path == "/api/servers":
+ return {"items": [{"id": "s1"}, {"id": "s2"}]}
+ return {"items": [{"id": f"m-{params['server']}"}]}
+
+ rows, _ = self._run(fetch, _FakeManager())
+ # Every message row must carry its parent server id — that's half of the (server, id)
+ # primary key, and the summary payload omits it.
+ assert rows == [
+ {"id": "m-s1", "server": "s1"},
+ {"id": "m-s2", "server": "s2"},
+ ]
+
+ def test_paginates_until_short_page_and_saves_state_after_each_page(self) -> None:
+ # One server, two pages: a full page continues, a short page terminates.
+ with patch.object(mailosaur, "MESSAGES_PAGE_SIZE", 2):
+
+ def fetch(session: Any, api_key: str, path: str, logger: Any, params: Any = None) -> Any:
+ if path == "/api/servers":
+ return {"items": [{"id": "s1"}]}
+ if params["page"] == 0:
+ return {"items": [{"id": "a"}, {"id": "b"}]}
+ return {"items": [{"id": "c"}]}
+
+ manager = _FakeManager()
+ rows, _ = self._run(fetch, manager)
+
+ assert [r["id"] for r in rows] == ["a", "b", "c"]
+ # State is saved AFTER yielding the first (full) page, bookmarking the next page to fetch,
+ # so a crash re-yields rather than skips (merge dedupes on the primary key).
+ assert MailosaurResumeConfig(server_id="s1", page=1) in manager.saved
+
+ def test_resumes_from_saved_server_bookmark(self) -> None:
+ seen_servers: list[str] = []
+
+ def fetch(session: Any, api_key: str, path: str, logger: Any, params: Any = None) -> Any:
+ if path == "/api/servers":
+ return {"items": [{"id": "s1"}, {"id": "s2"}]}
+ seen_servers.append(params["server"])
+ return {"items": [{"id": f"m-{params['server']}"}]}
+
+ # Bookmarked at s2 — s1 was already synced, so the resumed run must skip it.
+ manager = _FakeManager(MailosaurResumeConfig(server_id="s2", page=0))
+ rows, _ = self._run(fetch, manager)
+ assert seen_servers == ["s2"]
+ assert [r["id"] for r in rows] == ["m-s2"]
+
+ def test_incremental_passes_received_after(self) -> None:
+ captured: dict[str, Any] = {}
+
+ def fetch(session: Any, api_key: str, path: str, logger: Any, params: Any = None) -> Any:
+ if path == "/api/servers":
+ return {"items": [{"id": "s1"}]}
+ captured.update(params)
+ return {"items": []}
+
+ self._run(
+ fetch,
+ _FakeManager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),
+ )
+ assert captured.get("receivedAfter") == "2026-01-02T03:04:05Z"
+
+ def test_no_received_after_on_full_refresh(self) -> None:
+ captured: dict[str, Any] = {}
+
+ def fetch(session: Any, api_key: str, path: str, logger: Any, params: Any = None) -> Any:
+ if path == "/api/servers":
+ return {"items": [{"id": "s1"}]}
+ captured.update(params)
+ return {"items": []}
+
+ self._run(fetch, _FakeManager(), should_use_incremental_field=False)
+ assert "receivedAfter" not in captured
+
+
+class TestSimpleEndpoints:
+ @parameterized.expand([("servers", "/api/servers"), ("usage_transactions", "/api/usage/transactions")])
+ def test_single_request_yields_items(self, endpoint: str, expected_path: str) -> None:
+ def fetch(session: Any, api_key: str, path: str, logger: Any, params: Any = None) -> Any:
+ assert path == expected_path
+ return {"items": [{"id": "x"}]}
+
+ with (
+ patch.object(mailosaur, "make_tracked_session"),
+ patch.object(mailosaur, "_fetch", side_effect=fetch),
+ ):
+ rows = _drain(
+ get_rows(
+ api_key="key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=_FakeManager(), # type: ignore[arg-type]
+ )
+ )
+ assert rows == [{"id": "x"}]
+
+
+class TestMailosaurSourceResponse:
+ @parameterized.expand(
+ [
+ ("messages", ["server", "id"], "desc", ["received"]),
+ ("servers", ["id"], "asc", None),
+ ("usage_transactions", ["timestamp"], "asc", None),
+ ]
+ )
+ def test_source_response_shape(
+ self, endpoint: str, primary_keys: list[str], sort_mode: str, partition_keys: list[str] | None
+ ) -> None:
+ response = mailosaur_source(
+ api_key="key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=_FakeManager(), # type: ignore[arg-type]
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ # sort_mode must match the real arrival order — messages come newest-first (desc), and a
+ # wrong value corrupts the incremental watermark checkpoint.
+ assert response.sort_mode == sort_mode
+ assert response.partition_keys == partition_keys
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/tests/test_mailosaur_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/tests/test_mailosaur_source.py
new file mode 100644
index 000000000000..c9fa74762d62
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/tests/test_mailosaur_source.py
@@ -0,0 +1,152 @@
+from datetime import UTC, datetime
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailosaur.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailosaur.mailosaur import MailosaurResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailosaur.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailosaur.source import MailosaurSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config(api_key: str = "key") -> Any:
+ config = MagicMock()
+ config.api_key = api_key
+ return config
+
+
+class TestSourceConfig:
+ def test_source_type(self) -> None:
+ assert MailosaurSource().source_type == ExternalDataSourceType.MAILOSAUR
+
+ def test_config_metadata(self) -> None:
+ config = MailosaurSource().get_source_config
+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # Ships hidden while it's an unreleased alpha connector.
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/mailosaur"
+
+ def test_api_key_field_is_required_secret(self) -> None:
+ fields = {
+ f.name: f for f in MailosaurSource().get_source_config.fields if isinstance(f, SourceFieldInputConfig)
+ }
+ assert set(fields) == {"api_key"}
+ assert fields["api_key"].required is True
+ assert fields["api_key"].secret is True
+
+
+class TestGetSchemas:
+ def test_incremental_only_where_server_filter_exists(self) -> None:
+ schemas = {s.name: s for s in MailosaurSource().get_schemas(_config(), team_id=1)}
+ assert set(schemas) == set(ENDPOINTS)
+ # Only messages exposes a server-side `receivedAfter` filter, so it's the only incremental table.
+ assert schemas["messages"].supports_incremental is True
+ assert [f["field"] for f in schemas["messages"].incremental_fields] == ["received"]
+ assert schemas["servers"].supports_incremental is False
+ assert schemas["usage_transactions"].supports_incremental is False
+
+ def test_messages_primary_key_is_composite(self) -> None:
+ # Message summaries omit the server, so the key must include the injected parent id to stay
+ # unique table-wide across the fan-out.
+ schemas = {s.name: s for s in MailosaurSource().get_schemas(_config(), team_id=1)}
+ assert schemas["messages"].detected_primary_keys == ["server", "id"]
+
+ def test_names_filter(self) -> None:
+ schemas = MailosaurSource().get_schemas(_config(), team_id=1, names=["servers"])
+ assert {s.name for s in schemas} == {"servers"}
+
+ def test_documented_tables_render_without_credentials(self) -> None:
+ assert MailosaurSource.lists_tables_without_credentials is True
+ tables = {t["name"]: t for t in MailosaurSource().get_documented_tables()}
+ assert set(tables) == set(ENDPOINTS)
+ assert "Incremental" in tables["messages"]["sync_methods"]
+ assert tables["servers"]["sync_methods"] == ["Full refresh"]
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", True, None), ("bad", False, "Invalid Mailosaur API key")])
+ def test_delegates_to_transport(self, _name: str, ok: bool, error: str | None) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.mailosaur.source.validate_mailosaur_credentials",
+ return_value=(ok, error),
+ ) as mocked:
+ result = MailosaurSource().validate_credentials(_config("abc"), team_id=1)
+ assert result == (ok, error)
+ mocked.assert_called_once_with("abc")
+
+
+class TestResumableWiring:
+ def test_get_resumable_source_manager_binds_data_class(self) -> None:
+ inputs = MagicMock()
+ inputs.logger = MagicMock()
+ manager = MailosaurSource().get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is MailosaurResumeConfig
+
+ def test_source_for_pipeline_passes_incremental_value_only_when_enabled(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "messages"
+ inputs.logger = MagicMock()
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = datetime(2026, 1, 1, tzinfo=UTC)
+ manager = MagicMock()
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.mailosaur.source.mailosaur_source"
+ ) as mocked:
+ MailosaurSource().source_for_pipeline(_config(), manager, inputs)
+ mocked.assert_called_once_with(
+ api_key="key",
+ endpoint="messages",
+ logger=inputs.logger,
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+
+ def test_source_for_pipeline_drops_incremental_value_when_disabled(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "servers"
+ inputs.logger = MagicMock()
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = datetime(2026, 1, 1, tzinfo=UTC)
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.mailosaur.source.mailosaur_source"
+ ) as mocked:
+ MailosaurSource().source_for_pipeline(_config(), MagicMock(), inputs)
+ # A full-refresh table must not carry a stale cursor into the request.
+ assert mocked.call_args.kwargs["db_incremental_field_last_value"] is None
+
+
+class TestNonRetryableErrors:
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://mailosaur.com/api/servers", True),
+ ("forbidden", "403 Client Error: Forbidden for url: https://mailosaur.com/api/messages", True),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://mailosaur.com/api/messages", False),
+ (
+ "server_error",
+ "500 Server Error: Internal Server Error for url: https://mailosaur.com/api/servers",
+ False,
+ ),
+ ]
+ )
+ def test_only_credential_errors_are_non_retryable(self, _name: str, observed: str, should_match: bool) -> None:
+ non_retryable = MailosaurSource().get_non_retryable_errors()
+ assert any(key in observed for key in non_retryable) is should_match
+
+
+class TestCanonicalDescriptions:
+ def test_keys_are_known_endpoints(self) -> None:
+ assert set(CANONICAL_DESCRIPTIONS).issubset(set(ENDPOINTS))
+
+ def test_source_exposes_canonical_descriptions(self) -> None:
+ assert MailosaurSource().get_canonical_descriptions() is CANONICAL_DESCRIPTIONS