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): add Postscript source (#77081)

Tom Owers2d186597ad6f
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 0f58c4aa1c4b..fc4e0531c1a6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -484,6 +484,7 @@ the row lists both.
| plaid | HTTP | requests | ✅ |
| postgres | DB protocol | psycopg | ➖ |
| postmark | HTTP | requests | ✅ |
+| postscript | HTTP | requests + `rest_source.RESTClient` | ✅ |
| prefect_cloud | HTTP | requests | ✅ |
| pretix | HTTP | requests | ✅ |
| printify | HTTP | requests | ✅ |
@@ -1214,7 +1215,6 @@ doesn't conflict with concurrent PRs.
- podium
- polygon
- poplar
-- postscript
- power_bi_admin
- practicepanther
- preset
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/postscript.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/postscript.py
index 300bf9d8639b..392c8f8aaa6e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/postscript.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/postscript.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class PostscriptSourceConfig(config.Config):
- pass
+ api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postscript/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postscript/canonical_descriptions.py
new file mode 100644
index 000000000000..954f49dc470f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postscript/canonical_descriptions.py
@@ -0,0 +1,34 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "subscribers": {
+ "description": "A person who has been collected into your Postscript shop, with their contact details, subscription status, and custom properties.",
+ "docs_url": "https://developers.postscript.io/reference/get-subscribers",
+ "columns": {
+ "id": "Unique identifier for the subscriber.",
+ "created_at": "When the subscriber was created, in ISO 8601 format.",
+ "updated_at": "When the subscriber was last updated, in ISO 8601 format.",
+ "email": "The subscriber's email address.",
+ "phone_number": "The subscriber's phone number.",
+ "ps_id": "Postscript tracking ID for the subscriber, also stored in the ps_id cookie on the storefront.",
+ "shopify_customer_id": "Identifier of the matching customer in the connected Shopify store.",
+ "properties": "Built-in subscriber properties Postscript maintains, such as has_purchased, days_since_purchase, categories, and birthday.",
+ "subscriptions": "Per-channel sending permission, with a can_send flag for promotional and transactional messaging.",
+ "tags": "Tags applied to the subscriber.",
+ "data": "Custom subscriber properties set on the subscriber.",
+ },
+ },
+ "keywords": {
+ "description": "An active keyword for your shop that people can text in to subscribe or trigger an automation.",
+ "docs_url": "https://developers.postscript.io/reference/get-keywords",
+ "columns": {
+ "id": "Unique identifier for the keyword.",
+ "keyword": "The word people text in to trigger this keyword.",
+ "triggered_count": "How many times the keyword has been triggered.",
+ "created_at": "When the keyword was created, in ISO 8601 format.",
+ "updated_at": "When the keyword was last updated, in ISO 8601 format.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postscript/postscript.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postscript/postscript.py
new file mode 100644
index 000000000000..54ebdff79b34
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postscript/postscript.py
@@ -0,0 +1,202 @@
+import dataclasses
+from typing import Any, Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (
+ coerce_datetime_to_utc,
+)
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+ EndpointResource,
+ IncrementalConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.postscript.settings import (
+ POSTSCRIPT_BASE_URL,
+ POSTSCRIPT_ENDPOINTS,
+ PostscriptEndpointConfig,
+)
+
+
+class PostscriptResumeConfig:
+ page: int
+
+
+def _format_postscript_datetime(value: Any) -> str:
+ """Format the incremental watermark for Postscript's `<field>__gte` filters.
+
+ Truncating to whole seconds rounds the lower bound down, and `__gte` is inclusive, so a
+ resumed sync re-reads a few boundary rows (the merge dedupes them on `id`) instead of
+ skipping any.
+ """
+ normalized_value = coerce_datetime_to_utc(value)
+ if normalized_value is None:
+ return str(value)
+ return normalized_value.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _postscript_incremental_window(cursor_path: str) -> IncrementalConfig:
+ return {
+ "cursor_path": cursor_path,
+ "start_param": f"{cursor_path}__gte",
+ "initial_value": "1970-01-01T00:00:00Z",
+ "convert": _format_postscript_datetime,
+ }
+
+
+def _rest_api_client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": POSTSCRIPT_BASE_URL,
+ "auth": {"type": "bearer", "token": api_key},
+ "headers": {"Accept": "application/json"},
+ # Pin every request to the Postscript host and refuse to follow a 3xx, so a redirect
+ # can never replay the bearer token off-host.
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ }
+
+
+def _page_paginator() -> PageNumberPaginator:
+ # Postscript pages are 1-based and the body reports `page_info.total_pages`, so pagination
+ # stops after the last page instead of paying an extra empty-page request.
+ return PageNumberPaginator(base_page=1, page_param="page", total_path="page_info.total_pages")
+
+
+def _resolve_cursor_field(config: PostscriptEndpointConfig, requested: str | None) -> str:
+ """Pick the incremental cursor, honoring the user's choice when we advertise it.
+
+ A field we never advertised has no matching `__gte` filter or `sort` value, so the API
+ would 400 on it; fall back to the endpoint's default rather than failing the sync.
+ """
+ advertised = {f["field"] for f in config.incremental_fields}
+ if requested in advertised:
+ return str(requested)
+ return str(config.default_incremental_field)
+
+
+def get_resource(
+ endpoint: str,
+ api_version: str,
+ should_use_incremental_field: bool,
+ incremental_field_name: str | None = None,
+) -> EndpointResource:
+ config = POSTSCRIPT_ENDPOINTS[endpoint]
+ use_incremental = should_use_incremental_field and bool(config.incremental_fields)
+
+ params: dict[str, Any] = {}
+ if config.stable_sort_field is not None:
+ # The sort field must match the filtered column so rows arrive in watermark order.
+ sort_field = _resolve_cursor_field(config, incremental_field_name) if use_incremental else None
+ params["sort"] = f"{sort_field or config.stable_sort_field}__asc"
+
+ endpoint_config: Endpoint = {
+ "path": config.path_template.format(api_version=api_version),
+ "params": params,
+ "data_selector": config.data_selector,
+ # The wrapper key is documented on every list response, so a body without it means the
+ # API shape changed — fail loud rather than silently syncing 0 rows. A wholly empty
+ # body still counts as a valid 0-row page: it isn't documented whether a shop with no
+ # keywords gets `{"keywords": []}` or `{}`, and failing that shop's sync would be worse
+ # than accepting the empty page.
+ "data_selector_required": True,
+ "data_selector_empty_ok": True,
+ "paginator": _page_paginator() if config.paginated else SinglePagePaginator(),
+ }
+ if use_incremental:
+ endpoint_config["incremental"] = _postscript_incremental_window(
+ _resolve_cursor_field(config, incremental_field_name)
+ )
+
+ return {
+ "name": config.name,
+ "table_name": config.name,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if use_incremental else "replace",
+ "endpoint": endpoint_config,
+ "table_format": "delta",
+ }
+
+
+def validate_credentials(api_key: str, api_version: str) -> tuple[bool, str | None]:
+ response = make_tracked_session(redact_values=(api_key,), allow_redirects=False).get(
+ f"{POSTSCRIPT_BASE_URL}/api/{api_version}/subscribers",
+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ params={"page": 1},
+ timeout=10,
+ )
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, "Invalid Postscript API key"
+ if response.status_code == 403:
+ return (
+ False,
+ "Postscript rejected the API key. Use a shop Private API Key from Settings > "
+ "Integrations > API in your Postscript account. Partner keys are not supported.",
+ )
+ return False, f"Postscript API returned an unexpected status code: {response.status_code}"
+
+
+def postscript_source(
+ api_key: str,
+ endpoint: str,
+ api_version: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: Optional[ResumableSourceManager[PostscriptResumeConfig]] = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ endpoint_config = POSTSCRIPT_ENDPOINTS[endpoint]
+
+ config: RESTAPIConfig = {
+ "client": _rest_api_client_config(api_key),
+ "resource_defaults": {},
+ "resources": [get_resource(endpoint, api_version, should_use_incremental_field, incremental_field)],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager is not None and resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"page": resume_config.page}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Persist only while there is another page to resume to; the Redis TTL cleans up on
+ # completion.
+ if resumable_source_manager is None or not state or state.get("page") is None:
+ return
+ resumable_source_manager.save_state(PostscriptResumeConfig(page=int(state["page"])))
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint if resumable_source_manager is not None else None,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return SourceResponse(
+ name=endpoint_config.name,
+ items=lambda: resource,
+ primary_keys=endpoint_config.primary_key,
+ # Every paginated request pins `sort=<field>__asc`, so rows arrive oldest-first.
+ sort_mode="asc",
+ 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/products/warehouse_sources/backend/temporal/data_imports/sources/postscript/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postscript/settings.py
new file mode 100644
index 000000000000..a132a57153a6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postscript/settings.py
@@ -0,0 +1,59 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+POSTSCRIPT_BASE_URL = "https://api.postscript.io"
+
+
+@dataclass
+class PostscriptEndpointConfig:
+ name: str
+ # `{api_version}` is filled from the source's resolved version pin, never hardcoded here.
+ path_template: str
+ data_selector: str
+ primary_key: list[str]
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: str | None = None
+ partition_key: str | None = None
+ # Endpoints without a documented `page` param return their whole collection in one response.
+ paginated: bool = True
+ # Field used for the explicit `sort` param on full-refresh syncs. Immutable columns keep
+ # page boundaries stable while rows are written during the sync.
+ stable_sort_field: str | None = None
+
+
+POSTSCRIPT_ENDPOINTS: dict[str, PostscriptEndpointConfig] = {
+ "subscribers": PostscriptEndpointConfig(
+ name="subscribers",
+ path_template="/api/{api_version}/subscribers",
+ data_selector="subscribers",
+ primary_key=["id"],
+ # Both columns have matching server-side `__gte` filters and `sort` values. updated_at
+ # is the default because it catches unsubscribes and property changes, but it moves,
+ # so a subscriber edited mid-sync shifts to a later page and can skew a page boundary.
+ # created_at is offered as the immutable alternative for anyone who prefers stable
+ # pagination over catching updates.
+ incremental_fields=[incremental_field("updated_at"), incremental_field("created_at")],
+ default_incremental_field="updated_at",
+ # created_at never moves once a subscriber is collected, unlike updated_at.
+ partition_key="created_at",
+ stable_sort_field="created_at",
+ ),
+ "keywords": PostscriptEndpointConfig(
+ name="keywords",
+ path_template="/api/{api_version}/keywords",
+ data_selector="keywords",
+ primary_key=["id"],
+ # The endpoint documents no query parameters at all, so there is no server-side time
+ # filter and no `sort` to pin: full refresh over a single response.
+ partition_key="created_at",
+ paginated=False,
+ ),
+}
+
+ENDPOINTS = tuple(POSTSCRIPT_ENDPOINTS)
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in POSTSCRIPT_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postscript/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postscript/source.py
index 76cf92c42628..2cf4209edb3f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postscript/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postscript/source.py
@@ -1,32 +1,135 @@
-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.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,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.postscript import (
PostscriptSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.postscript.postscript import (
+ PostscriptResumeConfig,
+ postscript_source,
+ validate_credentials as validate_postscript_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.postscript.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class PostscriptSource(SimpleSource[PostscriptSourceConfig]):
+class PostscriptSource(ResumableSource[PostscriptSourceConfig, PostscriptResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ # `v2` is the `/api/v2/` path segment every request uses, and the version Postscript took
+ # out of beta as its current API.
+ supported_versions = ("v2",)
+ default_version = "v2"
+ api_docs_url = "https://developers.postscript.io/reference"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.POSTSCRIPT
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url": "Invalid Postscript API key. Create a new Private API Key in your Postscript account and reconnect.",
+ "403 Client Error: Forbidden for url": "Postscript rejected the API key. Use a shop Private API Key rather than a partner key, and check that the key is still active.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.postscript.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: PostscriptSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: PostscriptSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_postscript_credentials(config.api_key, self.resolve_api_version(api_version))
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PostscriptResumeConfig]:
+ return ResumableSourceManager[PostscriptResumeConfig](inputs, PostscriptResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: PostscriptSourceConfig,
+ resumable_source_manager: ResumableSourceManager[PostscriptResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return postscript_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ api_version=self.resolve_api_version(inputs.api_version),
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ 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,
+ incremental_field=inputs.incremental_field,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.POSTSCRIPT,
category=DataWarehouseSourceCategory.MARKETING___EMAIL,
label="Postscript",
+ caption=(
+ "Import SMS subscribers and keywords from your Postscript shop.\n\n"
+ "Create a Private API Key in your Postscript account under Settings > "
+ "Integrations > API. Partner API keys are not supported."
+ ),
+ docsUrl="https://posthog.com/docs/cdp/sources/postscript",
iconPath="/static/services/postscript.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ keywords=["sms", "text messaging"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="Private API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postscript/tests/test_postscript.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postscript/tests/test_postscript.py
new file mode 100644
index 000000000000..3ae31fa00ee8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postscript/tests/test_postscript.py
@@ -0,0 +1,220 @@
+from datetime import UTC, datetime
+from typing import Any, cast
+
+from unittest.mock import MagicMock, Mock, patch
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.postscript.postscript import (
+ PostscriptResumeConfig,
+ _format_postscript_datetime,
+ _rest_api_client_config,
+ get_resource,
+ postscript_source,
+ validate_credentials,
+)
+
+
+def _subscribers_response(total_pages: int) -> Mock:
+ response = Mock()
+ response.json.return_value = {"page_info": {"page": 1, "total_pages": total_pages}, "subscribers": []}
+ return response
+
+
+class TestPostscriptTransport:
+ @parameterized.expand(
+ [
+ ("naive_datetime", datetime(2026, 3, 1, 12, 30, 45, 999999), "2026-03-01T12:30:45Z"),
+ ("aware_datetime", datetime(2026, 3, 1, 12, 30, 45, tzinfo=UTC), "2026-03-01T12:30:45Z"),
+ ("passthrough_string", "1970-01-01T00:00:00Z", "1970-01-01T00:00:00Z"),
+ ]
+ )
+ def test_format_postscript_datetime(self, _name, value, expected) -> None:
+ assert _format_postscript_datetime(value) == expected
+
+ @parameterized.expand(
+ [
+ ("updated_at", "updated_at"),
+ ("created_at", "created_at"),
+ # An unadvertised field has no matching `__gte` filter or `sort` value, so it would
+ # 400 the API — fall back to the endpoint default instead.
+ ("unknown_field_falls_back", "last_seen_at"),
+ ("none_falls_back", None),
+ ]
+ )
+ def test_subscribers_incremental_filter_and_sort_agree(self, _name, requested) -> None:
+ resource = cast(
+ Any,
+ get_resource("subscribers", "v2", should_use_incremental_field=True, incremental_field_name=requested),
+ )
+ expected = requested if requested in ("updated_at", "created_at") else "updated_at"
+
+ endpoint = resource["endpoint"]
+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
+ assert endpoint["incremental"]["start_param"] == f"{expected}__gte"
+ assert endpoint["incremental"]["cursor_path"] == expected
+ # The sort column has to match the filtered column, or rows stop arriving in
+ # watermark order and the asc checkpoint corrupts.
+ assert endpoint["params"]["sort"] == f"{expected}__asc"
+
+ def test_subscribers_full_refresh_pins_stable_sort(self) -> None:
+ resource = cast(Any, get_resource("subscribers", "v2", should_use_incremental_field=False))
+ endpoint = resource["endpoint"]
+ assert resource["write_disposition"] == "replace"
+ assert "incremental" not in endpoint
+ # created_at is immutable, so page boundaries stay stable while rows are written
+ # during the sync.
+ assert endpoint["params"]["sort"] == "created_at__asc"
+
+ @parameterized.expand([("incremental", True), ("full_refresh", False)])
+ def test_keywords_never_paginates_or_filters(self, _name, should_use_incremental_field) -> None:
+ resource = cast(Any, get_resource("keywords", "v2", should_use_incremental_field=should_use_incremental_field))
+ endpoint = resource["endpoint"]
+ # /keywords documents no query params: no page, no sort, no time filter.
+ assert isinstance(endpoint["paginator"], SinglePagePaginator)
+ assert endpoint["params"] == {}
+ assert "incremental" not in endpoint
+ assert resource["write_disposition"] == "replace"
+
+ @parameterized.expand(
+ [
+ ("subscribers", "subscribers", "/api/v2/subscribers"),
+ ("keywords", "keywords", "/api/v2/keywords"),
+ ]
+ )
+ def test_resource_path_uses_resolved_api_version(self, _name, endpoint, expected_path) -> None:
+ resource = cast(Any, get_resource(endpoint, "v2", should_use_incremental_field=False))
+ assert resource["endpoint"]["path"] == expected_path
+ assert resource["endpoint"]["data_selector"] == endpoint
+ assert resource["endpoint"]["data_selector_required"] is True
+
+ @parameterized.expand(
+ [
+ # page_info.total_pages is the authoritative stop signal, so a full last page
+ # doesn't trigger one more (empty) request.
+ ("last_page", 1, False),
+ ("more_pages", 3, True),
+ ]
+ )
+ def test_subscribers_paginator_stops_on_total_pages(self, _name, total_pages, expected_has_next) -> None:
+ resource = cast(Any, get_resource("subscribers", "v2", should_use_incremental_field=False))
+ paginator = resource["endpoint"]["paginator"]
+ assert isinstance(paginator, PageNumberPaginator)
+
+ request = Mock()
+ request.params = None
+ paginator.init_request(request)
+ # Postscript pages are 1-based; starting at 0 would silently drop the first page.
+ assert request.params == {"page": 1}
+
+ paginator.update_state(_subscribers_response(total_pages), data=[{"id": "s_1"}])
+ assert paginator.has_next_page is expected_has_next
+
+ @parameterized.expand(
+ [
+ (200, True, None),
+ (401, False, "Invalid Postscript API key"),
+ (403, False, "shop Private API Key"),
+ (500, False, "unexpected status code"),
+ ]
+ )
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postscript.postscript.make_tracked_session"
+ )
+ def test_validate_credentials_status_mapping(self, status, expected_valid, message_fragment, mock_session) -> None:
+ mock_session.return_value.get.return_value = Mock(status_code=status)
+
+ is_valid, message = validate_credentials("sk_postscript", "v2")
+
+ assert is_valid is expected_valid
+ if message_fragment is None:
+ assert message is None
+ else:
+ assert message is not None and message_fragment in message
+
+ call = mock_session.return_value.get.call_args
+ assert call.args[0] == "https://api.postscript.io/api/v2/subscribers"
+ assert call.kwargs["headers"]["Authorization"] == "Bearer sk_postscript"
+ # The validation session must refuse redirects so a 3xx can't replay the token off-host.
+ assert mock_session.call_args.kwargs["allow_redirects"] is False
+ assert mock_session.call_args.kwargs["redact_values"] == ("sk_postscript",)
+
+ def test_rest_client_config_pins_host_and_blocks_redirects(self) -> None:
+ # A redirect off the Postscript host would otherwise replay the bearer token.
+ config = _rest_api_client_config("sk_postscript")
+ assert config["allowed_hosts"] == []
+ assert config["allow_redirects"] is False
+ assert config["auth"] == {"type": "bearer", "token": "sk_postscript"}
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.postscript.postscript.rest_api_resource")
+ def test_resume_state_seeds_paginator(self, mock_rest_api_resource) -> None:
+ manager = MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = PostscriptResumeConfig(page=7)
+
+ postscript_source(
+ api_key="sk_postscript",
+ endpoint="subscribers",
+ api_version="v2",
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ )
+
+ assert mock_rest_api_resource.call_args.kwargs["initial_paginator_state"] == {"page": 7}
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.postscript.postscript.rest_api_resource")
+ def test_resume_hook_saves_only_a_real_next_page(self, mock_rest_api_resource) -> None:
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+
+ postscript_source(
+ api_key="sk_postscript",
+ endpoint="subscribers",
+ api_version="v2",
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ )
+
+ resume_hook = mock_rest_api_resource.call_args.kwargs["resume_hook"]
+
+ resume_hook({"page": 3})
+ assert manager.save_state.call_args.args[0] == PostscriptResumeConfig(page=3)
+
+ manager.save_state.reset_mock()
+ # The paginator returns None once it is on the last page — persisting then would
+ # resume a finished sync onto a page that no longer exists.
+ resume_hook(None)
+ resume_hook({})
+ manager.save_state.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("subscribers", "subscribers", ["id"], ["created_at"]),
+ ("keywords", "keywords", ["id"], ["created_at"]),
+ ]
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.postscript.postscript.rest_api_resource")
+ def test_source_response_shape(
+ self, _name, endpoint, expected_keys, expected_partition_keys, mock_rest_api_resource
+ ) -> None:
+ response = postscript_source(
+ api_key="sk_postscript",
+ endpoint=endpoint,
+ api_version="v2",
+ team_id=1,
+ job_id="job-1",
+ should_use_incremental_field=True,
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == expected_keys
+ # Every paginated request pins `<field>__asc`, so rows really do arrive oldest-first.
+ assert response.sort_mode == "asc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == expected_partition_keys
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postscript/tests/test_postscript_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postscript/tests/test_postscript_source.py
new file mode 100644
index 000000000000..d6718125ce69
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postscript/tests/test_postscript_source.py
@@ -0,0 +1,139 @@
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.postscript import (
+ PostscriptSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.postscript.postscript import (
+ PostscriptResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.postscript.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.postscript.source import PostscriptSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestPostscriptSource:
+ def setup_method(self) -> None:
+ self.source = PostscriptSource()
+ self.team_id = 123
+ self.config = PostscriptSourceConfig(api_key="sk_postscript")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.POSTSCRIPT
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Postscript"
+ assert config.label == "Postscript"
+ assert config.category == DataWarehouseSourceCategory.MARKETING___EMAIL
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/postscript.png"
+ # The source ships visible — a truthy unreleasedSource hides it from every user.
+ assert not config.unreleasedSource
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ assert [f.name for f in config.fields] == ["api_key"]
+ field = config.fields[0]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_get_schemas_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_get_schemas_incremental_semantics(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+
+ # /subscribers is the only endpoint with server-side `__gte` filters; /keywords accepts
+ # no query params at all, so declaring it incremental would silently full-scan forever.
+ assert schemas["subscribers"].supports_incremental is True
+ assert [f["field"] for f in schemas["subscribers"].incremental_fields] == ["updated_at", "created_at"]
+ assert schemas["keywords"].supports_incremental is False
+ assert schemas["keywords"].incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["keywords"])
+ assert [s.name for s in schemas] == ["keywords"]
+
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://api.postscript.io/api/v2/subscribers",
+ True,
+ ),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.postscript.io/api/v2/keywords", True),
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.postscript.io", False),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.postscript.io", False),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures_only(self, _name, observed_error, expect_match) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable) is expect_match
+
+ def test_resolve_api_version_defaults_to_v2(self) -> None:
+ assert self.source.resolve_api_version(None) == "v2"
+ assert self.source.default_version in self.source.supported_versions
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postscript.source.validate_postscript_credentials"
+ )
+ def test_validate_credentials_plumbs_key_and_resolved_version(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.return_value = (True, None)
+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)
+ assert mock_validate.call_args.args == ("sk_postscript", "v2")
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert manager._data_class is PostscriptResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.postscript.source.postscript_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_postscript_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "subscribers"
+ inputs.team_id = self.team_id
+ inputs.job_id = "job-1"
+ inputs.api_version = None
+ inputs.should_use_incremental_field = True
+ inputs.incremental_field = "updated_at"
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_postscript_source.call_args.kwargs
+ assert kwargs["api_key"] == "sk_postscript"
+ assert kwargs["endpoint"] == "subscribers"
+ assert kwargs["api_version"] == "v2"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["incremental_field"] == "updated_at"
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.postscript.source.postscript_source")
+ def test_source_for_pipeline_omits_watermark_when_not_incremental(
+ self, mock_postscript_source: mock.MagicMock
+ ) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "subscribers"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_postscript_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_canonical_descriptions_cover_endpoints(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(ENDPOINTS)