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 postmark import source (#61137)

Tom Owers1e8ab58e5199
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index e27fe03356b5..a20073b44a5d 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -88,6 +88,7 @@ the row lists both.
| plain | HTTP | requests | ✅ |
| polar | HTTP | requests | ✅ |
| postgres | DB protocol | psycopg | ➖ |
+| postmark | HTTP | requests | ✅ |
| recurly | HTTP | requests + `rest_source.RESTClient` | ✅ |
| recharge | HTTP | requests | ✅ |
| reddit_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -204,7 +205,6 @@ doesn't conflict with concurrent PRs.
- pendo
- pipedrive
- plaid
-- postmark
- productboard
- quickbooks
- ringcentral
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index bc91668337bc..9a044cf9c758 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -664,7 +664,7 @@ class PostgresSourceConfig(config.Config):
@config.config
class PostmarkSourceConfig(config.Config):
- pass
+ server_token: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/postmark/postmark.py b/posthog/temporal/data_imports/sources/postmark/postmark.py
new file mode 100644
index 000000000000..ac3eec2a55e9
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/postmark/postmark.py
@@ -0,0 +1,204 @@
+"""Postmark (ActiveCampaign) transactional email source.
+
+Postmark exposes a REST/JSON API at https://api.postmarkapp.com. Server-level resources
+(messages, bounces, templates, message streams) authenticate with a per-server token sent
+in the `X-Postmark-Server-Token` header.
+
+Sync is full-refresh only. Postmark's list endpoints accept `fromdate`/`todate` filters
+(date granularity, `YYYY-MM-DD`), but we have not been able to verify server-side filtering
+against a live token, so we do not advertise incremental sync — matching how the existing
+third-party connectors (Airbyte, Fivetran) treat Postmark. Within a sync, pagination is
+resumable via the saved offset.
+
+Two upstream constraints worth knowing about:
+- The paginated list endpoints cap `count + offset` at 10,000, so a full refresh can only
+ reach the most recent 10,000 rows of each. We log a warning when that window is hit.
+- Messages expire from Postmark after a retention window (45 days by default), so historical
+ data beyond that window is simply unavailable from the API.
+"""
+
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.postmark.settings import (
+ POSTMARK_ENDPOINTS,
+ POSTMARK_MAX_PAGE_SIZE,
+ POSTMARK_MAX_WINDOW,
+ PostmarkEndpointConfig,
+)
+
+POSTMARK_BASE_URL = "https://api.postmarkapp.com"
+
+
+class PostmarkRetryableError(Exception):
+ pass
+
+
+class PostmarkResumeConfig:
+ # Offset of the next page to fetch on paginated list endpoints.
+ next_offset: int = 0
+
+
+def _get_headers(server_token: str) -> dict[str, str]:
+ return {
+ "X-Postmark-Server-Token": server_token,
+ "Accept": "application/json",
+ }
+
+
+def validate_credentials(server_token: str) -> bool:
+ # /message-streams is a cheap read-only call any valid server token can make. Postmark
+ # returns 401 (ErrorCode 10) for an invalid/missing token and 200 otherwise.
+ url = f"{POSTMARK_BASE_URL}/message-streams"
+ try:
+ # `X-Postmark-Server-Token` is not in the sample-capture header denylist, so mask the
+ # token by value to keep it out of any captured HTTP sample.
+ session = make_tracked_session(headers=_get_headers(server_token), redact_values=(server_token,))
+ response = session.get(url, timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+@retry(
+ retry=retry_if_exception_type((PostmarkRetryableError, 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, logger: FilteringBoundLogger) -> dict:
+ response = session.get(url, timeout=60)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise PostmarkRetryableError(f"Postmark API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Postmark API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _iter_flat_endpoint(
+ session: requests.Session,
+ config: PostmarkEndpointConfig,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Fetch a list endpoint that returns its whole payload in a single response."""
+ url = f"{POSTMARK_BASE_URL}{config.path}"
+ data = _fetch(session, url, logger)
+ items = data.get(config.data_key) or []
+ if items:
+ yield items
+
+
+def _iter_paginated_endpoint(
+ session: requests.Session,
+ config: PostmarkEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PostmarkResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Iterate a list endpoint with Postmark's offset/count pagination (max 10,000 window)."""
+ page_size = min(config.page_size or POSTMARK_MAX_PAGE_SIZE, POSTMARK_MAX_PAGE_SIZE)
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ offset: int = resume_config.next_offset if resume_config else 0
+ if offset:
+ logger.debug(f"Postmark: resuming {config.name} from offset={offset}")
+
+ while offset < POSTMARK_MAX_WINDOW:
+ count = min(page_size, POSTMARK_MAX_WINDOW - offset)
+ query = urlencode({"count": count, "offset": offset})
+ url = f"{POSTMARK_BASE_URL}{config.path}?{query}"
+
+ data = _fetch(session, url, logger)
+ items = data.get(config.data_key) or []
+
+ if items:
+ yield items
+
+ # A short page means we've reached the end of the available rows.
+ if len(items) < count:
+ break
+
+ # Advance before the next fetch, then persist so a crash resumes at the next page
+ # rather than re-scanning from the start (merge dedupes the re-yielded boundary).
+ offset += count
+ resumable_source_manager.save_state(PostmarkResumeConfig(next_offset=offset))
+
+ if offset >= POSTMARK_MAX_WINDOW:
+ total = data.get("TotalCount")
+ logger.warning(
+ f"Postmark: reached the {POSTMARK_MAX_WINDOW}-row API window for {config.name} "
+ f"(TotalCount={total}); older rows cannot be synced via this endpoint."
+ )
+
+
+def get_rows(
+ server_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PostmarkResumeConfig],
+) -> Iterator[Any]:
+ config = POSTMARK_ENDPOINTS[endpoint]
+
+ # Align the batcher chunk size with the page size for paginated endpoints so each page
+ # yields its own table before we persist the resume offset for the next page. With a
+ # larger chunk size, several pages would buffer in memory while the offset advances, and
+ # a mid-buffer failure could resume past rows that were never yielded — a silent data gap.
+ chunk_size = config.page_size or 2000
+ batcher = Batcher(logger=logger, chunk_size=chunk_size, chunk_size_bytes=100 * 1024 * 1024)
+
+ # One tracked session for the whole sync — keeps urllib3's TLS connection warm across
+ # pages, and every request inherits the auth headers. The server token is also masked by
+ # value since `X-Postmark-Server-Token` is not in the sample-capture header denylist.
+ session = make_tracked_session(headers=_get_headers(server_token), redact_values=(server_token,))
+
+ if config.page_size is None:
+ source_iter = _iter_flat_endpoint(session, config, logger)
+ else:
+ source_iter = _iter_paginated_endpoint(session, config, logger, resumable_source_manager)
+
+ for batch in source_iter:
+ batcher.batch(batch)
+ if batcher.should_yield():
+ yield batcher.get_table()
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def postmark_source(
+ server_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PostmarkResumeConfig],
+) -> SourceResponse:
+ endpoint_config = POSTMARK_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ server_token=server_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=[endpoint_config.primary_key],
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="month" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
diff --git a/posthog/temporal/data_imports/sources/postmark/settings.py b/posthog/temporal/data_imports/sources/postmark/settings.py
new file mode 100644
index 000000000000..362ab2a02565
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/postmark/settings.py
@@ -0,0 +1,68 @@
+from dataclasses import dataclass
+from typing import Optional
+
+# Postmark caps `count + offset` at 10,000 on its paginated list endpoints, so a full
+# refresh can only reach the most recent 10,000 rows for those endpoints. See the module
+# docstring in `postmark.py` for the data-retention/window caveats.
+POSTMARK_MAX_WINDOW = 10_000
+# Postmark allows at most 500 rows per page on its paginated list endpoints.
+POSTMARK_MAX_PAGE_SIZE = 500
+
+
+@dataclass
+class PostmarkEndpointConfig:
+ name: str
+ path: str
+ # Key in the JSON response body that holds the list of rows (Postmark wraps every
+ # list response, e.g. `{"TotalCount": N, "Messages": [...]}`).
+ data_key: str
+ primary_key: str = "ID"
+ # Stable datetime field used for partitioning. Never an `updated_at`-style field.
+ partition_key: Optional[str] = None
+ # Offset/count-paginated endpoints set a page size (max 500). Flat endpoints return
+ # the whole list in a single response and leave this `None`.
+ page_size: Optional[int] = None
+
+
+POSTMARK_ENDPOINTS: dict[str, PostmarkEndpointConfig] = {
+ "messages_outbound": PostmarkEndpointConfig(
+ name="messages_outbound",
+ path="/messages/outbound",
+ data_key="Messages",
+ primary_key="MessageID",
+ partition_key="ReceivedAt",
+ page_size=POSTMARK_MAX_PAGE_SIZE,
+ ),
+ "messages_inbound": PostmarkEndpointConfig(
+ name="messages_inbound",
+ path="/messages/inbound",
+ data_key="InboundMessages",
+ primary_key="MessageID",
+ partition_key="ReceivedAt",
+ page_size=POSTMARK_MAX_PAGE_SIZE,
+ ),
+ "bounces": PostmarkEndpointConfig(
+ name="bounces",
+ path="/bounces",
+ data_key="Bounces",
+ primary_key="ID",
+ partition_key="BouncedAt",
+ page_size=POSTMARK_MAX_PAGE_SIZE,
+ ),
+ "templates": PostmarkEndpointConfig(
+ name="templates",
+ path="/templates",
+ data_key="Templates",
+ primary_key="TemplateId",
+ page_size=POSTMARK_MAX_PAGE_SIZE,
+ ),
+ "message_streams": PostmarkEndpointConfig(
+ name="message_streams",
+ path="/message-streams",
+ data_key="MessageStreams",
+ primary_key="ID",
+ ),
+}
+
+
+ENDPOINTS = tuple(POSTMARK_ENDPOINTS.keys())
diff --git a/posthog/temporal/data_imports/sources/postmark/source.py b/posthog/temporal/data_imports/sources/postmark/source.py
index cd4bb73664c3..56210d2b5612 100644
--- a/posthog/temporal/data_imports/sources/postmark/source.py
+++ b/posthog/temporal/data_imports/sources/postmark/source.py
@@ -1,19 +1,31 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import PostmarkSourceConfig
+from posthog.temporal.data_imports.sources.postmark.postmark import (
+ PostmarkResumeConfig,
+ postmark_source,
+ validate_credentials as validate_postmark_credentials,
+)
+from posthog.temporal.data_imports.sources.postmark.settings import ENDPOINTS
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class PostmarkSource(SimpleSource[PostmarkSourceConfig]):
+class PostmarkSource(ResumableSource[PostmarkSourceConfig, PostmarkResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.POSTMARK
@@ -23,7 +35,85 @@ class PostmarkSource(SimpleSource[PostmarkSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.POSTMARK,
label="Postmark",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Postmark **Server API token** to pull your Postmark data into the PostHog Data warehouse.
+
+You can find your server token under **Servers → (your server) → API Tokens** in the Postmark dashboard.
+
+The token grants read access to the following server-level resources:
+- Outbound messages
+- Inbound messages
+- Bounces
+- Templates
+- Message streams
+""",
iconPath="/static/services/postmark.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/postmark",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="server_token",
+ label="Server API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: PostmarkSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Postmark's list endpoints accept fromdate/todate filters, but we have not verified
+ # server-side filtering against a live token, so we sync full-refresh only. Within-sync
+ # resumption is handled by ResumableSource.
+ 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: PostmarkSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_postmark_credentials(config.server_token):
+ return True, None
+
+ return False, "Invalid Postmark server API token"
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.postmarkapp.com": (
+ "Your Postmark server API token is invalid or expired. Please check the token and reconnect."
+ ),
+ "403 Client Error: Forbidden for url: https://api.postmarkapp.com": (
+ "Your Postmark server API token does not have the required permissions. Please check the token and try again."
+ ),
+ }
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PostmarkResumeConfig]:
+ return ResumableSourceManager[PostmarkResumeConfig](inputs, PostmarkResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: PostmarkSourceConfig,
+ resumable_source_manager: ResumableSourceManager[PostmarkResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return postmark_source(
+ server_token=config.server_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/posthog/temporal/data_imports/sources/postmark/tests/test_postmark.py b/posthog/temporal/data_imports/sources/postmark/tests/test_postmark.py
new file mode 100644
index 000000000000..43b0b5473cea
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/postmark/tests/test_postmark.py
@@ -0,0 +1,235 @@
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.postmark.postmark import (
+ POSTMARK_BASE_URL,
+ PostmarkResumeConfig,
+ get_rows,
+ postmark_source,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.postmark.settings import ENDPOINTS, POSTMARK_ENDPOINTS, POSTMARK_MAX_WINDOW
+
+
+def _mock_manager(can_resume: bool = False, state: PostmarkResumeConfig | None = None) -> MagicMock:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = can_resume
+ manager.load_state.return_value = state
+ manager.save_state = MagicMock()
+ return manager
+
+
+def _mock_response(status_code: int = 200, json_payload: dict | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = json_payload or {}
+ response.text = "" if response.ok else "error body"
+
+ def _raise_for_status():
+ if not response.ok:
+ raise Exception(f"{status_code} Client Error")
+
+ response.raise_for_status.side_effect = _raise_for_status
+ return response
+
+
+def _query_of(url: str) -> dict[str, list[str]]:
+ return parse_qs(urlparse(url).query)
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok_200", 200, True),
+ ("unauthorized_401", 401, False),
+ ("forbidden_403", 403, False),
+ ("server_500", 500, False),
+ ]
+ )
+ @patch("posthog.temporal.data_imports.sources.postmark.postmark.make_tracked_session")
+ def test_validate_credentials(self, _name: str, status_code: int, expected: bool, mock_session: MagicMock) -> None:
+ mock_session.return_value.get.return_value = _mock_response(status_code=status_code)
+ assert validate_credentials("test-token") is expected
+
+ # Auth token is bound to the session headers; URL is on `.get(...)`.
+ session_kwargs = mock_session.call_args.kwargs
+ assert session_kwargs["headers"]["X-Postmark-Server-Token"] == "test-token"
+ # The token is also masked by value so it never lands in a captured HTTP sample.
+ assert session_kwargs["redact_values"] == ("test-token",)
+ called_args, _ = mock_session.return_value.get.call_args
+ assert called_args[0] == f"{POSTMARK_BASE_URL}/message-streams"
+
+ @patch("posthog.temporal.data_imports.sources.postmark.postmark.make_tracked_session")
+ def test_validate_credentials_network_error_returns_false(self, mock_session: MagicMock) -> None:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("test-token") is False
+
+
+class TestFlatEndpoint:
+ @patch("posthog.temporal.data_imports.sources.postmark.postmark.make_tracked_session")
+ def test_message_streams_yields_single_batch(self, mock_session: MagicMock) -> None:
+ rows = [{"ID": "outbound", "Name": "Transactional", "CreatedAt": "2026-01-01T00:00:00Z"}]
+ mock_session.return_value.get.return_value = _mock_response(json_payload={"MessageStreams": rows})
+
+ tables = list(get_rows("test-token", "message_streams", MagicMock(), _mock_manager()))
+
+ assert len(tables) == 1
+ assert tables[0].num_rows == 1
+ assert tables[0].column("ID").to_pylist() == ["outbound"]
+
+ # The sync session masks the token by value to keep it out of captured HTTP samples.
+ assert mock_session.call_args.kwargs["redact_values"] == ("test-token",)
+
+ # Flat endpoints fetch the bare path with no pagination params.
+ called_url = mock_session.return_value.get.call_args[0][0]
+ assert called_url == f"{POSTMARK_BASE_URL}/message-streams"
+
+ @patch("posthog.temporal.data_imports.sources.postmark.postmark.make_tracked_session")
+ def test_flat_endpoint_empty_response_yields_nothing(self, mock_session: MagicMock) -> None:
+ mock_session.return_value.get.return_value = _mock_response(json_payload={"MessageStreams": []})
+
+ tables = list(get_rows("test-token", "message_streams", MagicMock(), _mock_manager()))
+
+ assert tables == []
+
+
+class TestOffsetPagination:
+ @patch("posthog.temporal.data_imports.sources.postmark.postmark.make_tracked_session")
+ def test_paginates_until_short_page_and_saves_state(self, mock_session: MagicMock) -> None:
+ # First page is full (500 rows) so we ask for a second; second page is short -> stop.
+ page1 = [{"MessageID": f"m{i}", "ReceivedAt": "2026-01-01T00:00:00Z"} for i in range(500)]
+ page2 = [{"MessageID": f"m{i}", "ReceivedAt": "2026-01-01T00:00:00Z"} for i in range(500, 510)]
+
+ mock_session.return_value.get.side_effect = [
+ _mock_response(json_payload={"TotalCount": 510, "Messages": page1}),
+ _mock_response(json_payload={"TotalCount": 510, "Messages": page2}),
+ ]
+
+ manager = _mock_manager()
+ tables = list(get_rows("test-token", "messages_outbound", MagicMock(), manager))
+
+ assert sum(t.num_rows for t in tables) == 510
+ assert mock_session.return_value.get.call_count == 2
+
+ first_q = _query_of(mock_session.return_value.get.call_args_list[0].args[0])
+ second_q = _query_of(mock_session.return_value.get.call_args_list[1].args[0])
+ assert first_q["offset"] == ["0"] and first_q["count"] == ["500"]
+ assert second_q["offset"] == ["500"]
+
+ # State is saved once, after the first (full) page, pointing at the next offset.
+ manager.save_state.assert_called_once()
+ saved: PostmarkResumeConfig = manager.save_state.call_args[0][0]
+ assert saved.next_offset == 500
+
+ @patch("posthog.temporal.data_imports.sources.postmark.postmark.make_tracked_session")
+ def test_single_short_page_does_not_save_state(self, mock_session: MagicMock) -> None:
+ page = [{"MessageID": "m1", "ReceivedAt": "2026-01-01T00:00:00Z"}]
+ mock_session.return_value.get.return_value = _mock_response(json_payload={"TotalCount": 1, "Messages": page})
+
+ manager = _mock_manager()
+ tables = list(get_rows("test-token", "messages_outbound", MagicMock(), manager))
+
+ assert sum(t.num_rows for t in tables) == 1
+ assert mock_session.return_value.get.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @patch("posthog.temporal.data_imports.sources.postmark.postmark.make_tracked_session")
+ def test_resumes_from_saved_offset(self, mock_session: MagicMock) -> None:
+ page = [{"MessageID": "m501", "ReceivedAt": "2026-01-01T00:00:00Z"}]
+ mock_session.return_value.get.return_value = _mock_response(json_payload={"TotalCount": 501, "Messages": page})
+
+ manager = _mock_manager(can_resume=True, state=PostmarkResumeConfig(next_offset=500))
+ list(get_rows("test-token", "messages_outbound", MagicMock(), manager))
+
+ first_q = _query_of(mock_session.return_value.get.call_args_list[0].args[0])
+ assert first_q["offset"] == ["500"]
+
+ @patch("posthog.temporal.data_imports.sources.postmark.postmark.make_tracked_session")
+ def test_stops_at_10k_window_and_warns(self, mock_session: MagicMock) -> None:
+ # Every page is full, so pagination would continue forever if not for the window cap.
+ full_page = [{"MessageID": f"m{i}", "ReceivedAt": "2026-01-01T00:00:00Z"} for i in range(500)]
+ mock_session.return_value.get.return_value = _mock_response(
+ json_payload={"TotalCount": 99999, "Messages": full_page}
+ )
+
+ manager = _mock_manager()
+ logger = MagicMock()
+ list(get_rows("test-token", "messages_outbound", logger, manager))
+
+ # 10,000 / 500 = 20 pages, then the loop terminates at the window boundary.
+ assert mock_session.return_value.get.call_count == POSTMARK_MAX_WINDOW // 500
+ logger.warning.assert_called_once()
+
+ last_q = _query_of(mock_session.return_value.get.call_args_list[-1].args[0])
+ assert int(last_q["offset"][0]) + int(last_q["count"][0]) == POSTMARK_MAX_WINDOW
+
+
+class TestEndpointPrimaryKeys:
+ @parameterized.expand(
+ [
+ ("messages_outbound", "Messages", "MessageID"),
+ ("messages_inbound", "InboundMessages", "MessageID"),
+ ("bounces", "Bounces", "ID"),
+ ("templates", "Templates", "TemplateId"),
+ ("message_streams", "MessageStreams", "ID"),
+ ]
+ )
+ @patch("posthog.temporal.data_imports.sources.postmark.postmark.make_tracked_session")
+ def test_reads_correct_data_key(
+ self, endpoint: str, data_key: str, primary_key: str, mock_session: MagicMock
+ ) -> None:
+ rows = [{primary_key: "x1"}]
+ mock_session.return_value.get.return_value = _mock_response(json_payload={data_key: rows, "TotalCount": 1})
+
+ tables = list(get_rows("test-token", endpoint, MagicMock(), _mock_manager()))
+
+ assert len(tables) == 1
+ assert tables[0].column(primary_key).to_pylist() == ["x1"]
+
+
+class TestSourceResponseShape:
+ @parameterized.expand([(name,) for name in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = postmark_source("test-token", endpoint, MagicMock(), _mock_manager())
+
+ endpoint_config = POSTMARK_ENDPOINTS[endpoint]
+ assert response.name == endpoint
+ assert response.primary_keys == [endpoint_config.primary_key]
+
+ if endpoint_config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_format == "month"
+ assert response.partition_keys == [endpoint_config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+
+class TestRetryable:
+ @patch("tenacity.nap.time.sleep")
+ @patch("posthog.temporal.data_imports.sources.postmark.postmark.make_tracked_session")
+ def test_429_retries_until_success(self, mock_session: MagicMock, _mock_sleep: MagicMock) -> None:
+ mock_session.return_value.get.side_effect = [
+ _mock_response(status_code=429),
+ _mock_response(json_payload={"MessageStreams": [{"ID": "outbound"}]}),
+ ]
+
+ tables = list(get_rows("test-token", "message_streams", MagicMock(), _mock_manager()))
+
+ assert len(tables) == 1
+ assert mock_session.return_value.get.call_count == 2
+
+ @patch("posthog.temporal.data_imports.sources.postmark.postmark.make_tracked_session")
+ def test_401_does_not_retry_and_raises(self, mock_session: MagicMock) -> None:
+ mock_session.return_value.get.return_value = _mock_response(status_code=401)
+
+ with pytest.raises(Exception):
+ list(get_rows("test-token", "message_streams", MagicMock(), _mock_manager()))
+
+ assert mock_session.return_value.get.call_count == 1
diff --git a/posthog/temporal/data_imports/sources/postmark/tests/test_postmark_source.py b/posthog/temporal/data_imports/sources/postmark/tests/test_postmark_source.py
new file mode 100644
index 000000000000..7b66c40149ec
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/postmark/tests/test_postmark_source.py
@@ -0,0 +1,106 @@
+from unittest import mock
+
+from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import PostmarkSourceConfig
+from posthog.temporal.data_imports.sources.postmark.postmark import PostmarkResumeConfig
+from posthog.temporal.data_imports.sources.postmark.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.postmark.source import PostmarkSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestPostmarkSource:
+ def setup_method(self):
+ self.source = PostmarkSource()
+ self.team_id = 123
+ self.config = PostmarkSourceConfig(server_token="test-server-token")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.POSTMARK
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Postmark"
+ assert config.label == "Postmark"
+ assert config.releaseStatus == "alpha"
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/postmark.png"
+ assert len(config.fields) == 1
+
+ token_field = config.fields[0]
+ assert isinstance(token_field, SourceFieldInputConfig)
+ assert token_field.name == "server_token"
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.secret is True
+ assert token_field.required is True
+
+ def test_non_retryable_errors(self):
+ errors = self.source.get_non_retryable_errors()
+ assert any("401" in key for key in errors)
+ assert any("403" in key for key in errors)
+ assert all("api.postmarkapp.com" in key for key in errors)
+
+ def test_get_schemas(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ for schema in schemas:
+ assert schema.supports_incremental is False
+ assert schema.supports_append is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["bounces"])
+
+ assert len(schemas) == 1
+ assert schemas[0].name == "bounces"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["nonexistent"])
+
+ assert schemas == []
+
+ @mock.patch("posthog.temporal.data_imports.sources.postmark.source.validate_postmark_credentials")
+ def test_validate_credentials_success(self, mock_validate):
+ mock_validate.return_value = True
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is True
+ assert error_message is None
+ mock_validate.assert_called_once_with(self.config.server_token)
+
+ @mock.patch("posthog.temporal.data_imports.sources.postmark.source.validate_postmark_credentials")
+ def test_validate_credentials_failure(self, mock_validate):
+ mock_validate.return_value = False
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert error_message == "Invalid Postmark server API token"
+
+ def test_get_resumable_source_manager(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is PostmarkResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.postmark.source.postmark_source")
+ def test_source_for_pipeline(self, mock_postmark_source):
+ mock_postmark_source.return_value = mock.MagicMock()
+
+ inputs = mock.MagicMock()
+ inputs.schema_name = "messages_outbound"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_postmark_source.assert_called_once_with(
+ server_token=self.config.server_token,
+ endpoint="messages_outbound",
+ logger=inputs.logger,
+ resumable_source_manager=manager,
+ )