:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add Nuntly import source (#84286)
Tom Owersef6fd9357fd3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/nuntly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/nuntly.pyindex 7ba68ddfbe15..b5d6d2ef0995 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/nuntly.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/nuntly.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass NuntlySourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nuntly/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nuntly/canonical_descriptions.pynew file mode 100644index 000000000000..e9f9f3a6cb34--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nuntly/canonical_descriptions.py@@ -0,0 +1,83 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Emails": {+ "description": "Emails sent through Nuntly, one row per send attempt.",+ "docs_url": "https://nuntly.com/docs/api-reference/emails/list-emails",+ "columns": {+ "id": "Unique identifier for the email.",+ "from": "Sender email address.",+ "to": "Recipient email address, or a list of recipient addresses.",+ "subject": "Email subject line.",+ "status": "Current delivery status (queued, scheduled, processed, failed, sending, sent, delivered, bounced, complained, canceled, rejected).",+ "createdAt": "When the email was created, in ISO 8601 format.",+ "scheduledAt": "When the email is scheduled to send, in ISO 8601 format, if scheduled.",+ },+ },+ "Messages": {+ "description": "Inbound email messages received into a Nuntly inbox.",+ "docs_url": "https://nuntly.com/docs/api-reference/messages/list-messages",+ "columns": {+ "id": "Unique identifier for the message.",+ "createdAt": "When the message record was created, in ISO 8601 format.",+ "inboxId": "Identifier of the inbox the message was received into, if any.",+ "threadId": "Identifier of the thread the message belongs to.",+ "messageId": "The message's RFC 5322 Message-ID header.",+ "from": "Sender email address, in RFC 5322 format.",+ "to": "Recipient email addresses.",+ "cc": "CC'd email addresses, if any.",+ "bcc": "BCC'd email addresses, if any.",+ "replyTo": "Reply-To email addresses, if any.",+ "subject": "Message subject line.",+ "receivedAt": "When the message was received, in ISO 8601 format.",+ "status": "Processing status (received, sent, discarded, failed).",+ "labels": "Labels applied to the message.",+ "attachmentCount": "Number of attachments on the message.",+ },+ },+ "Inboxes": {+ "description": "Inboxes configured to receive inbound email on a Nuntly domain.",+ "docs_url": "https://nuntly.com/docs/api-reference/inboxes/list-inboxes",+ "columns": {+ "id": "Unique identifier for the inbox.",+ "createdAt": "When the inbox was created, in ISO 8601 format.",+ "updatedAt": "When the inbox was last updated, in ISO 8601 format.",+ "domainId": "Identifier of the domain the inbox receives mail on.",+ "domainName": "Name of the domain the inbox receives mail on.",+ "address": "The inbox's full email address.",+ "name": "Human-readable name for the inbox, if set.",+ "namespaceId": "Identifier of the namespace the inbox belongs to, if any.",+ "namespaceName": "Name of the namespace the inbox belongs to, if any.",+ "agentId": "Identifier of the AI agent attached to the inbox, if any.",+ },+ },+ "Domains": {+ "description": "Sending and receiving domains configured on a Nuntly account.",+ "docs_url": "https://nuntly.com/docs/api-reference/domains/list-domains",+ "columns": {+ "id": "Unique identifier for the domain.",+ "name": "The domain name.",+ "status": "Overall domain verification status (bootstrapping, pending, success, failed, temporary_failure).",+ "sendingStatus": "Whether sending is enabled, disabled, or paused for this domain.",+ "receivingStatus": "Inbound-receiving verification status (bootstrapping, pending, success, failed, temporary_failure).",+ "createdAt": "When the domain was added, in ISO 8601 format.",+ "region": "The region the domain's mail infrastructure is hosted in.",+ },+ },+ "Webhooks": {+ "description": "Webhook endpoints configured to receive Nuntly event notifications.",+ "docs_url": "https://nuntly.com/docs/api-reference/webhooks/list-webhooks",+ "columns": {+ "id": "Unique identifier for the webhook.",+ "name": "Human-readable name for the webhook, if set.",+ "endpointUrl": "The URL Nuntly sends event payloads to.",+ "status": "Whether the webhook is enabled, disabled, or revoked.",+ "disabledReason": "Why the webhook was disabled, if applicable (manual, auto_consecutive_failures).",+ "disabledAt": "When the webhook was disabled, in ISO 8601 format, if disabled.",+ "events": "Event types this webhook is subscribed to.",+ "createdAt": "When the webhook was created, in ISO 8601 format.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nuntly/nuntly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nuntly/nuntly.pynew file mode 100644index 000000000000..4d31e1c18853--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nuntly/nuntly.py@@ -0,0 +1,102 @@+from typing import Any, Optional++from posthog.dataclasses import frozen++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 (+ JSONResponseCursorPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.nuntly.settings import ENDPOINTS, MAX_PAGE_SIZE++NUNTLY_BASE_URL = "https://api.nuntly.com"+++@frozen+class NuntlyResumeConfig:+ cursor: str+++def _client_config(api_key: str) -> ClientConfig:+ return {+ "base_url": NUNTLY_BASE_URL,+ "auth": {"type": "bearer", "token": api_key},+ # Every list endpoint returns `{"data": [...], "nextCursor": "<string|null>"}`.+ "paginator": JSONResponseCursorPaginator(cursor_path="nextCursor", cursor_param="cursor"),+ }+++def nuntly_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[NuntlyResumeConfig],+) -> SourceResponse:+ endpoint_config = ENDPOINTS[endpoint]++ rest_config: RESTAPIConfig = {+ "client": _client_config(api_key),+ "resource_defaults": {"write_disposition": "replace"},+ "resources": [+ {+ "name": endpoint,+ "table_name": endpoint_config.table_name,+ "endpoint": {+ "path": endpoint_config.path,+ "params": {"limit": MAX_PAGE_SIZE},+ "data_selector": "data",+ },+ "table_format": "delta",+ }+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ initial_paginator_state = {"cursor": resume.cursor}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's a next page to resume to; the Redis TTL cleans up on+ # completion. Save AFTER a page is yielded so a crash re-yields the last page (merge+ # dedupes on primary key) rather than skipping it.+ if state and state.get("cursor"):+ resumable_source_manager.save_state(NuntlyResumeConfig(cursor=str(state["cursor"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=endpoint_config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[endpoint_config.partition_key],+ column_hints=resource.column_hints,+ )+++def validate_credentials(api_key: str) -> tuple[bool, int | None]:+ return validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ f"{NUNTLY_BASE_URL}/emails",+ headers={"Authorization": f"Bearer {api_key}"},+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nuntly/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nuntly/settings.pynew file mode 100644index 000000000000..e2dad93083a5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nuntly/settings.py@@ -0,0 +1,28 @@+from posthog.dataclasses import frozen++from products.warehouse_sources.backend.types import IncrementalField++# Nuntly caps every list endpoint at 30 rows per page (no larger tier is documented).+MAX_PAGE_SIZE = 30+++@frozen+class NuntlyEndpointConfig:+ path: str+ table_name: str+ primary_keys: list[str]+ # `createdAt` is stable across every endpoint below; none expose an `updated_at` equivalent.+ partition_key: str = "createdAt"+++ENDPOINTS: dict[str, NuntlyEndpointConfig] = {+ "Emails": NuntlyEndpointConfig(path="/emails", table_name="emails", primary_keys=["id"]),+ "Messages": NuntlyEndpointConfig(path="/messages", table_name="messages", primary_keys=["id"]),+ "Inboxes": NuntlyEndpointConfig(path="/inboxes", table_name="inboxes", primary_keys=["id"]),+ "Domains": NuntlyEndpointConfig(path="/domains", table_name="domains", primary_keys=["id"]),+ "Webhooks": NuntlyEndpointConfig(path="/webhooks", table_name="webhooks", primary_keys=["id"]),+}++# Nuntly documents no server-side timestamp filter on any list endpoint (no `since` /+# `updated_after` / date-range param), so every endpoint is full-refresh only.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nuntly/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nuntly/source.pyindex 5e64bc794525..54d757d43a90 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/nuntly/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nuntly/source.py@@ -1,30 +1,121 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.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.errors import auth_non_retryable_errorsfrom 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, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.nuntly import NuntlySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.nuntly.nuntly import (+ NUNTLY_BASE_URL,+ NuntlyResumeConfig,+ nuntly_source,+ validate_credentials as validate_nuntly_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.nuntly.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class NuntlySource(SimpleSource[NuntlySourceConfig]):+class NuntlySource(ResumableSource[NuntlySourceConfig, NuntlyResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://nuntly.com/docs/api-reference/introduction"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.NUNTLY+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return auth_non_retryable_errors(NUNTLY_BASE_URL, service="Nuntly")++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.nuntly.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: NuntlySourceConfig,+ 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: NuntlySourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ is_valid, _ = validate_nuntly_credentials(config.api_key)+ if is_valid:+ return True, None+ return False, "Invalid credentials"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[NuntlyResumeConfig]:+ return ResumableSourceManager[NuntlyResumeConfig](inputs, NuntlyResumeConfig)++ def source_for_pipeline(+ self,+ config: NuntlySourceConfig,+ resumable_source_manager: ResumableSourceManager[NuntlyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return nuntly_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.NUNTLY,category=DataWarehouseSourceCategory.MARKETING___EMAIL,+ releaseStatus=ReleaseStatus.ALPHA,label="Nuntly",+ caption="Enter your Nuntly API key. You can create one in the "+ "[Nuntly dashboard](https://nuntly.com/docs/guides/api-keys).",+ docsUrl="https://posthog.com/docs/cdp/sources/nuntly",iconPath="/static/services/nuntly.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="apk_...",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nuntly/tests/test_nuntly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nuntly/tests/test_nuntly.pynew file mode 100644index 000000000000..fe09100131d9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nuntly/tests/test_nuntly.py@@ -0,0 +1,171 @@+import json+from collections.abc import Iterable+from typing import Any, cast++from unittest.mock import MagicMock, patch++from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.nuntly.nuntly import (+ NuntlyResumeConfig,+ nuntly_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.nuntly.settings import ENDPOINTS+++def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ return resp+++class TestNuntlySourceResumeBehavior:+ """End-to-end cursor pagination + resume behaviour of ``nuntly_source``."""++ def _drive(+ self, endpoint: str, manager: MagicMock, responses: list[Response]+ ) -> tuple[MagicMock, list[dict[str, Any]], list[str]]:+ """Drive ``nuntly_source`` with a mocked HTTP session.++ Returns ``(mock_session, sent_params, sent_urls)``. Params/urls are captured at+ send-time since the underlying Request object is mutated in-place between pages.+ """+ sent_params: list[dict[str, Any]] = []+ sent_urls: list[str] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_params.append(dict(request.params or {}))+ sent_urls.append(request.url)+ return next(response_iter)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ response = nuntly_source(+ api_key="apk_test",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ )+ list(cast(Iterable[Any], response.items()))+ return mock_session, sent_params, sent_urls++ @parameterized.expand([("Emails",), ("Messages",), ("Inboxes",), ("Domains",), ("Webhooks",)])+ def test_fresh_run_walks_pages_and_saves_cursor_after_each_non_terminal_page(self, endpoint: str) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response({"data": [{"id": "1"}], "nextCursor": "cursor-1"}),+ _make_http_response({"data": [{"id": "2"}], "nextCursor": "cursor-2"}),+ _make_http_response({"data": [{"id": "3"}], "nextCursor": None}),+ ]+ _, sent_params, sent_urls = self._drive(endpoint, manager, responses)++ cursors_sent = [p.get("cursor") for p in sent_params]+ assert cursors_sent == [None, "cursor-1", "cursor-2"]+ assert all(p.get("limit") == 30 for p in sent_params)+ assert all(url.startswith(f"https://api.nuntly.com{ENDPOINTS[endpoint].path}") for url in sent_urls)++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [+ NuntlyResumeConfig(cursor="cursor-1"),+ NuntlyResumeConfig(cursor="cursor-2"),+ ]++ def test_resume_seeds_paginator_with_saved_cursor(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = NuntlyResumeConfig(cursor="cursor-resumed")++ responses = [_make_http_response({"data": [{"id": "4"}], "nextCursor": None})]+ _, sent_params, _ = self._drive("Emails", manager, responses)++ assert [p.get("cursor") for p in sent_params] == ["cursor-resumed"]+ manager.load_state.assert_called_once()++ def test_terminal_single_page_does_not_save_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response({"data": [{"id": "only"}], "nextCursor": None})]+ self._drive("Emails", manager, responses)++ manager.save_state.assert_not_called()++ def test_does_not_load_state_when_cannot_resume(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response({"data": [{"id": "a"}], "nextCursor": None})]+ self._drive("Emails", manager, responses)++ manager.load_state.assert_not_called()++ @parameterized.expand([("Emails",), ("Messages",), ("Inboxes",), ("Domains",), ("Webhooks",)])+ def test_source_response_uses_declared_primary_keys_and_partitioning(self, endpoint: str) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.return_value = _make_http_response({"data": [], "nextCursor": None})++ response = nuntly_source(+ api_key="apk_test",+ endpoint=endpoint,+ team_id=1,+ job_id="job",+ resumable_source_manager=manager,+ )++ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["createdAt"]+++class TestValidateCredentials:+ @parameterized.expand([(200, True), (401, False), (403, False), (500, False)])+ def test_status_mapping(self, status_code: int, expected_valid: bool) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.nuntly.nuntly.make_tracked_session"+ ) as mock_make_session:+ mock_session = mock_make_session.return_value+ mock_session.get.return_value = MagicMock(status_code=status_code)++ is_valid, code = validate_credentials("apk_test")++ assert (is_valid, code) == (expected_valid, status_code)++ def test_transport_error_maps_to_false_none(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.nuntly.nuntly.make_tracked_session"+ ) as mock_make_session:+ mock_session = mock_make_session.return_value+ mock_session.get.side_effect = ConnectionError("boom")++ assert validate_credentials("apk_test") == (False, None)+++class TestEndpointSettings:+ @parameterized.expand([(name,) for name in ENDPOINTS])+ def test_every_declared_endpoint_has_a_settings_entry(self, endpoint: str) -> None:+ assert ENDPOINTS[endpoint].path.startswith("/")+ assert ENDPOINTS[endpoint].primary_keys == ["id"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nuntly/tests/test_nuntly_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nuntly/tests/test_nuntly_source.pynew file mode 100644index 000000000000..572909263ff3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nuntly/tests/test_nuntly_source.py@@ -0,0 +1,141 @@+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.nuntly import NuntlySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.nuntly.nuntly import NuntlyResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.nuntly.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.nuntly.source import NuntlySource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestNuntlySource:+ def setup_method(self) -> None:+ self.source = NuntlySource()+ self.team_id = 123+ self.config = NuntlySourceConfig(api_key="apk_test")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.NUNTLY++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Nuntly"+ assert config.label == "Nuntly"+ assert config.category == DataWarehouseSourceCategory.MARKETING___EMAIL+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/nuntly.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/nuntly"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ @parameterized.expand(+ [+ (+ "401 Client Error: Unauthorized for url: https://api.nuntly.com/emails?limit=30",+ True,+ ),+ (+ "403 Client Error: Forbidden for url: https://api.nuntly.com/messages?limit=30",+ True,+ ),+ (+ "429 Client Error: Too Many Requests for url: https://api.nuntly.com/emails",+ False,+ ),+ (+ "500 Server Error: Internal Server Error for url: https://api.nuntly.com/emails",+ False,+ ),+ ]+ )+ def test_non_retryable_errors(self, observed_error: str, expected_match: bool) -> None:+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors) is expected_match++ def test_get_schemas_match_endpoints_full_refresh_only(self) -> None:+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ for schema in schemas.values():+ # Nuntly documents no server-side timestamp filter on any list endpoint.+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Emails"])+ assert len(schemas) == 1+ assert schemas[0].name == "Emails"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["Nope"]) == []++ def test_lists_tables_without_credentials_publishes_catalog(self) -> None:+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert {table["name"] for table in documented} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ canonical = self.source.get_canonical_descriptions()+ assert set(canonical) == set(ENDPOINTS)++ @parameterized.expand(+ [+ (True, True, None),+ (False, False, "Invalid credentials"),+ ]+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.nuntly.source.validate_nuntly_credentials"+ )+ def test_validate_credentials(+ self, probe_valid: bool, expected_valid: bool, expected_message: str | None, mock_validate: mock.Mock+ ) -> None:+ mock_validate.return_value = (probe_valid, 200 if probe_valid else 401)++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("apk_test")++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is NuntlyResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.nuntly.source.nuntly_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_nuntly_source: mock.Mock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "Emails"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_nuntly_source.assert_called_once_with(+ api_key="apk_test",+ endpoint="Emails",+ team_id=self.team_id,+ job_id="job-1",+ resumable_source_manager=manager,+ )