:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement asknicely import source (#71179)
Tom Owersb40dd33477a5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 215363c117c3..8ea04b80d634 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -64,6 +64,7 @@ the row lists both.| appsflyer | HTTP (CSV reports) | requests | ✅ || asana | HTTP | requests | ✅ || ashby | HTTP | requests | ✅ |+| asknicely | HTTP | requests | ✅ || assemblyai | HTTP | requests | ✅ || attentive | HTTP (webhook-first) | requests (webhook management) | ✅ || attio | HTTP | requests + `rest_source.RESTClient` | ✅ |diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/asknicely.py b/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/asknicely.pynew file mode 100644index 000000000000..7e82e679f492--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/asknicely.py@@ -0,0 +1,215 @@+import re+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.settings import RESPONSES_PAGE_SIZE+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++SUBDOMAIN_REGEX = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9-]*$")++# Unix-timestamp fields AskNicely returns as strings; coerced to ints so the incremental+# watermark comparison and datetime partitioning work numerically.+TIMESTAMP_FIELDS = ("sent", "opened", "responded", "lastemailed", "created", "case_closed_time")++REQUEST_TIMEOUT_SECONDS = 60+++class AskNicelyResumeConfig:+ # 1-based next page to fetch. Page numbering is only stable relative to the since_time+ # cutoff the run started with, so the cutoff is persisted alongside it.+ page_number: int+ since_time: int+++def _base_url(subdomain: str) -> str:+ # Each AskNicely customer gets their own subdomain of asknice.ly, so only the label needs+ # validating — the credential can never be sent to a host outside AskNicely's domain.+ if not SUBDOMAIN_REGEX.match(subdomain):+ raise ValueError(f"Invalid AskNicely subdomain: {subdomain!r}")+ return f"https://{subdomain}.asknice.ly"+++def _get_headers(api_key: str) -> dict[str, str]:+ return {"X-apikey": api_key, "Accept": "application/json"}+++def build_responses_url(subdomain: str, page_number: int, since_time: int, page_size: int = RESPONSES_PAGE_SIZE) -> str:+ """Build the path-segment-paginated responses URL.++ Segments: /responses/{sort_direction}/{pagesize}/{pagenumber}/{since_time}/{format}/{filter}/{sort_by}.+ `answered` restricts rows to actual survey responses (vs sent-but-unanswered), and+ `responded` keys both the sort and the since_time cutoff to the response timestamp,+ matching the advertised incremental field. Ascending sort keeps earlier pages stable+ while new responses land on the tail.+ """+ return f"{_base_url(subdomain)}/api/v1/responses/asc/{page_size}/{page_number}/{since_time}/json/answered/responded"+++def _to_unix_timestamp(value: Any) -> int:+ if isinstance(value, bool):+ raise ValueError(f"Cannot convert incremental field value to a unix timestamp: {value!r}")+ if isinstance(value, int):+ return value+ if isinstance(value, float):+ return int(value)+ if isinstance(value, str) and value.strip().isdigit():+ return int(value.strip())+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return int(aware.timestamp())+ if isinstance(value, date):+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())+ raise ValueError(f"Cannot convert incremental field value to a unix timestamp: {value!r}")+++def _parse_int(value: Any) -> Optional[int]:+ if isinstance(value, bool):+ return None+ if isinstance(value, int):+ return value+ if isinstance(value, str) and value.strip().isdigit():+ return int(value.strip())+ return None+++def _normalize_row(row: dict[str, Any]) -> dict[str, Any]:+ for field in TIMESTAMP_FIELDS:+ value = row.get(field)+ if isinstance(value, str) and value.strip().isdigit():+ row[field] = int(value.strip())+ return row+++@retry(+ # Transient connection breaks only — 429/5xx status retries are already handled with+ # backoff by the tracked session's urllib3 Retry policy.+ retry=retry_if_exception_type(+ (requests.ReadTimeout, requests.ConnectionError, requests.exceptions.ChunkedEncodingError)+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict[str, Any]:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ if not response.ok:+ logger.error(f"AskNicely API error: status={response.status_code}, body={response.text[:500]}, url={url}")+ response.raise_for_status()++ return response.json()+++def get_rows(+ subdomain: str,+ api_key: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AskNicelyResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> Iterator[list[dict[str, Any]]]:+ # One session reused across every page so urllib3 keeps the connection alive.+ # `capture=False`: response rows carry free-text survey comments and internal notes the+ # name-based sample scrubbers can't recognise, so keep bodies out of HTTP sample storage+ # entirely. Requests are still metered and logged (status + url).+ # `allow_redirects=False`: never replay the `X-apikey` header to a redirect target, so an+ # upstream 3xx (including an open redirect) can't leak the credential off the validated host.+ session = make_tracked_session(redact_values=(api_key,), capture=False, allow_redirects=False)+ headers = _get_headers(api_key)++ since_time = 0+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ # The docs don't state whether since_time is inclusive; step back one second so a+ # boundary-second response is never skipped — merge dedupes re-pulled rows on response_id.+ since_time = max(_to_unix_timestamp(db_incremental_field_last_value) - 1, 0)++ page_number = 1+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None:+ # Page numbering is only stable against the cutoff the interrupted run used, so resume+ # with the saved since_time rather than a freshly derived one.+ page_number = resume.page_number+ since_time = resume.since_time+ logger.debug(f"AskNicely: resuming responses from page {page_number} (since_time={since_time})")++ while True:+ url = build_responses_url(subdomain, page_number, since_time)+ data = _fetch_page(session, url, headers, logger)+ items = data.get("data") or []+ if not items:+ break++ yield [_normalize_row(item) for item in items]++ total_pages = _parse_int(data.get("totalpages"))+ if total_pages is not None and page_number >= total_pages:+ break+ if total_pages is None and len(items) < RESPONSES_PAGE_SIZE:+ break++ page_number += 1+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the last+ # page rather than skipping it — merge dedupes on the primary key.+ resumable_source_manager.save_state(AskNicelyResumeConfig(page_number=page_number, since_time=since_time))+++def asknicely_source(+ subdomain: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AskNicelyResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ subdomain=subdomain,+ api_key=api_key,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=["response_id"],+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ # `responded` is set once when the customer answers, so partitions never rewrite.+ partition_keys=["responded"],+ )+++def validate_credentials(subdomain: str, api_key: str) -> tuple[bool, str | None]:+ try:+ # `capture=False`: the probe fetches a real response row, whose free-text fields must+ # stay out of HTTP sample storage just like the sync path's.+ # `allow_redirects=False`: keep the `X-apikey` header from being replayed to a redirect+ # target, matching the sync path's credential boundary.+ response = make_tracked_session(redact_values=(api_key,), capture=False, allow_redirects=False).get(+ build_responses_url(subdomain, page_number=1, since_time=0, page_size=1),+ headers=_get_headers(api_key),+ timeout=30,+ )+ except Exception as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code in (401, 403):+ return False, "Invalid AskNicely API key. You can find your API key in AskNicely under Settings > API."+ return False, f"AskNicely returned an unexpected status code: {response.status_code}"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/canonical_descriptions.pynew file mode 100644index 000000000000..f7bdc9454a1e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/canonical_descriptions.py@@ -0,0 +1,33 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "responses": {+ "description": "Individual survey responses (NPS, CSAT, or 5-star) with the score, comment, and contact details for each respondent.",+ "docs_url": "https://asknicely.asknice.ly/help/apidocs/responses",+ "columns": {+ "response_id": "Unique identifier for the response.",+ "person_id": "Identifier of the person (contact) the survey was sent to.",+ "contact_id": "Identifier of the contact record in AskNicely.",+ "name": "Name of the respondent.",+ "email": "Email address of the respondent.",+ "answer": "The score the respondent gave (e.g. 0-10 for NPS).",+ "answerlabel": "Label associated with the answer, where the survey uses labelled options.",+ "comment": "Free-text comment left by the respondent.",+ "note": "Internal notes attached to the response.",+ "status": "Delivery/response status of the survey (e.g. answered).",+ "dontcontact": "Whether the contact has opted out of further surveys.",+ "sent": "Unix timestamp when the survey was sent.",+ "opened": "Unix timestamp when the survey was opened, or 0 if never opened.",+ "responded": "Unix timestamp when the respondent answered the survey.",+ "lastemailed": "Unix timestamp when the contact was last emailed.",+ "created": "Unix timestamp when the contact record was created.",+ "segment": "Segment the contact belongs to.",+ "question_type": "Survey metric type for this response: nps, csat, or 5star.",+ "published": "Whether the response has been approved for publishing as a testimonial.",+ "publishedname": "Display name used when the response is published as a testimonial.",+ "deliverymethod": "Channel the survey was delivered through (e.g. email).",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/settings.pynew file mode 100644index 000000000000..ad7215901fb8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/settings.py@@ -0,0 +1,20 @@+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# AskNicely caps (and defaults) the responses page size at 50,000 rows per request;+# stay well below that so a single page is cheap to parse and hold in memory.+RESPONSES_PAGE_SIZE = 5000++# The responses history is AskNicely's one warehousing-shaped stream. The other API+# endpoints (contact add/trigger, send survey) are action-only and return no history.+ENDPOINTS = ("responses",)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ "responses": [+ {+ "label": "responded",+ "type": IncrementalFieldType.DateTime,+ "field": "responded",+ "field_type": IncrementalFieldType.Integer,+ },+ ],+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/source.pyindex 4d6e20f1b9bb..e504435312b0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/source.py@@ -1,30 +1,154 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.asknicely import (+ SUBDOMAIN_REGEX,+ AskNicelyResumeConfig,+ asknicely_source,+ validate_credentials as validate_asknicely_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AsknicelySourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AsknicelySource(SimpleSource[AsknicelySourceConfig]):+class AsknicelySource(ResumableSource[AsknicelySourceConfig, AskNicelyResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ASKNICELY+ @property+ def connection_host_fields(self) -> list[str]:+ # `subdomain` selects the AskNicely tenant the stored API key is sent to;+ # retargeting it must re-require the key.+ return ["subdomain"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.ASKNICELY,category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,label="AskNicely",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["nps", "csat", "survey"],+ caption="""Sync your AskNicely survey responses (NPS, CSAT, 5-star) into the PostHog Data warehouse.++Your account subdomain is the first part of your AskNicely URL (`https://<subdomain>.asknice.ly`). You can find your API key in AskNicely under **Settings > API**.""",iconPath="/static/services/asknicely.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/asknicely",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="subdomain",+ label="Account subdomain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="yourcompany",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid AskNicely API key. Please check your key under Settings > API in AskNicely and reconnect.",+ "403 Client Error": "Your AskNicely API key does not have access. Please check the key under Settings > API in AskNicely and reconnect.",+ "Unauthorized for url": "Invalid AskNicely API key. Please check your key under Settings > API in AskNicely and reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: AsknicelySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=(fields := INCREMENTAL_FIELDS.get(endpoint)) is not None,+ supports_append=fields is not None,+ incremental_fields=fields or [],+ )+ 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: AsknicelySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ subdomain = config.subdomain.strip()+ if not SUBDOMAIN_REGEX.match(subdomain):+ return (+ False,+ "AskNicely subdomain is incorrect — it should look like `yourcompany` (from https://yourcompany.asknice.ly)",+ )++ return validate_asknicely_credentials(subdomain, config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AskNicelyResumeConfig]:+ return ResumableSourceManager[AskNicelyResumeConfig](inputs, AskNicelyResumeConfig)++ def source_for_pipeline(+ self,+ config: AsknicelySourceConfig,+ resumable_source_manager: ResumableSourceManager[AskNicelyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return asknicely_source(+ subdomain=config.subdomain.strip(),+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/tests/test_asknicely.py b/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/tests/test_asknicely.pynew file mode 100644index 000000000000..1799c2a95d41--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/tests/test_asknicely.py@@ -0,0 +1,258 @@+from datetime import UTC, date, datetime+from typing import Any, Optional++import pytest+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.asknicely import (+ AskNicelyResumeConfig,+ _normalize_row,+ _to_unix_timestamp,+ asknicely_source,+ build_responses_url,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.settings import RESPONSES_PAGE_SIZE++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.asknicely"+++def _page(rows: list[dict[str, Any]], total_pages: Optional[int] = None) -> mock.MagicMock:+ response = mock.MagicMock()+ response.ok = True+ response.status_code = 200+ body: dict[str, Any] = {"success": True, "data": rows}+ if total_pages is not None:+ body["totalpages"] = str(total_pages)+ response.json.return_value = body+ return response+++def _manager(resume: Optional[AskNicelyResumeConfig] = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume is not None+ manager.load_state.return_value = resume+ return manager+++class TestAsknicely:+ def test_build_responses_url(self) -> None:+ assert build_responses_url("acme", page_number=2, since_time=1700000000) == (+ f"https://acme.asknice.ly/api/v1/responses/asc/{RESPONSES_PAGE_SIZE}/2/1700000000/json/answered/responded"+ )++ @pytest.mark.parametrize("subdomain", ["", "acme.asknice.ly", "a/b", "a b", "-leading"])+ def test_build_responses_url_rejects_invalid_subdomain(self, subdomain: str) -> None:+ with pytest.raises(ValueError):+ build_responses_url(subdomain, page_number=1, since_time=0)++ @pytest.mark.parametrize(+ ("value", "expected"),+ [+ (1700000000, 1700000000),+ (1700000000.9, 1700000000),+ ("1700000000", 1700000000),+ (datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC), 1700000000),+ (datetime(2023, 11, 14, 22, 13, 20), 1700000000),+ (date(2023, 11, 14), 1699920000),+ ],+ )+ def test_to_unix_timestamp(self, value: Any, expected: int) -> None:+ assert _to_unix_timestamp(value) == expected++ @pytest.mark.parametrize("value", ["not-a-timestamp", None, True, {"ts": 1}])+ def test_to_unix_timestamp_rejects_unusable_values(self, value: Any) -> None:+ with pytest.raises(ValueError):+ _to_unix_timestamp(value)++ def test_normalize_row_coerces_string_timestamps(self) -> None:+ row = _normalize_row(+ {"response_id": "r1", "responded": "1418692529", "sent": "1418692531", "opened": "0", "comment": "12345"}+ )+ assert row["responded"] == 1418692529+ assert row["sent"] == 1418692531+ assert row["opened"] == 0+ # Non-timestamp fields keep their original type even when digit-like.+ assert row["comment"] == "12345"++ def _run(+ self,+ pages: list[mock.MagicMock],+ manager: mock.MagicMock,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ ) -> tuple[list[list[dict[str, Any]]], list[str]]:+ session = mock.MagicMock()+ session.get.side_effect = pages+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ batches = list(+ get_rows(+ subdomain="acme",+ api_key="key",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ )+ urls = [call.args[0] for call in session.get.call_args_list]+ return batches, urls++ def test_paginates_until_totalpages_and_normalizes_rows(self) -> None:+ manager = _manager()+ pages = [+ _page([{"response_id": "r1", "responded": "100"}], total_pages=2),+ _page([{"response_id": "r2", "responded": "200"}], total_pages=2),+ ]++ batches, urls = self._run(pages, manager)++ assert [row["response_id"] for batch in batches for row in batch] == ["r1", "r2"]+ assert batches[0][0]["responded"] == 100+ assert urls == [+ build_responses_url("acme", page_number=1, since_time=0),+ build_responses_url("acme", page_number=2, since_time=0),+ ]+ # Only the intermediate page boundary is checkpointed — never past the final page.+ manager.save_state.assert_called_once_with(AskNicelyResumeConfig(page_number=2, since_time=0))++ def test_stops_on_empty_page_when_totalpages_missing(self) -> None:+ pages = [+ _page([{"response_id": "r1", "responded": "100"}] * RESPONSES_PAGE_SIZE),+ _page([]),+ ]++ batches, urls = self._run(pages, _manager())++ assert len(batches) == 1+ assert len(urls) == 2++ def test_short_page_without_totalpages_terminates(self) -> None:+ batches, urls = self._run([_page([{"response_id": "r1", "responded": "100"}])], _manager())++ assert len(batches) == 1+ assert len(urls) == 1++ def test_incremental_since_time_steps_back_one_second(self) -> None:+ _, urls = self._run(+ [_page([])],+ _manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000,+ )+ assert urls == [build_responses_url("acme", page_number=1, since_time=1699999999)]++ def test_incremental_since_time_clamps_at_zero(self) -> None:+ _, urls = self._run(+ [_page([])],+ _manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=0,+ )+ assert urls == [build_responses_url("acme", page_number=1, since_time=0)]++ def test_resumes_from_saved_page_and_cutoff(self) -> None:+ # The saved since_time must win over a freshly derived one: page numbering is only+ # stable against the cutoff the interrupted run used.+ manager = _manager(AskNicelyResumeConfig(page_number=3, since_time=500))++ _, urls = self._run(+ [_page([])],+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000,+ )++ assert urls == [build_responses_url("acme", page_number=3, since_time=500)]++ def test_state_saved_only_after_yield(self) -> None:+ # A crash mid-batch must re-yield the last page on resume, not skip it — so the+ # checkpoint may only be written once the batch has been handed to the pipeline.+ manager = _manager()+ session = mock.MagicMock()+ session.get.side_effect = [+ _page([{"response_id": "r1", "responded": "100"}], total_pages=2),+ _page([{"response_id": "r2", "responded": "200"}], total_pages=2),+ ]++ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ rows = get_rows(+ subdomain="acme",+ api_key="key",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ )+ next(rows)+ manager.save_state.assert_not_called()+ next(rows)+ manager.save_state.assert_called_once_with(AskNicelyResumeConfig(page_number=2, since_time=0))++ def test_sync_session_disables_redirects(self) -> None:+ # The X-apikey header must never be replayed to a redirect target.+ session = mock.MagicMock()+ session.get.side_effect = [_page([])]+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session) as make_session:+ list(+ get_rows(+ subdomain="acme",+ api_key="key",+ logger=mock.MagicMock(),+ resumable_source_manager=_manager(),+ )+ )+ assert make_session.call_args.kwargs["allow_redirects"] is False++ def test_validate_credentials_session_disables_redirects(self) -> None:+ session = mock.MagicMock()+ session.get.return_value = mock.MagicMock(status_code=200)+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session) as make_session:+ validate_credentials("acme", "key")+ assert make_session.call_args.kwargs["allow_redirects"] is False++ def test_source_response_shape(self) -> None:+ response = asknicely_source(+ subdomain="acme",+ api_key="key",+ endpoint="responses",+ logger=mock.MagicMock(),+ resumable_source_manager=_manager(),+ )++ assert response.name == "responses"+ assert response.primary_keys == ["response_id"]+ assert response.sort_mode == "asc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["responded"]++ @pytest.mark.parametrize(+ ("status_code", "expected_valid", "expected_message_fragment"),+ [+ (200, True, None),+ (401, False, "Invalid AskNicely API key"),+ (403, False, "Invalid AskNicely API key"),+ (500, False, "unexpected status code: 500"),+ ],+ )+ def test_validate_credentials_status_mapping(+ self, status_code: int, expected_valid: bool, expected_message_fragment: str | None+ ) -> None:+ session = mock.MagicMock()+ session.get.return_value = mock.MagicMock(status_code=status_code)++ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ is_valid, error_message = validate_credentials("acme", "key")++ assert is_valid is expected_valid+ if expected_message_fragment is None:+ assert error_message is None+ else:+ assert error_message is not None and expected_message_fragment in error_message++ def test_validate_credentials_rejects_invalid_subdomain(self) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ is_valid, error_message = validate_credentials("bad domain", "key")++ assert is_valid is False+ assert error_message is not None+ mock_session.return_value.get.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/tests/test_asknicely_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/tests/test_asknicely_source.pynew file mode 100644index 000000000000..25f08b509a8c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/tests/test_asknicely_source.py@@ -0,0 +1,159 @@+from typing import Any++import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.asknicely import AskNicelyResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.source import AsknicelySource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AsknicelySourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(**overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "responses",+ "schema_id": "schema-1",+ "source_id": "source-1",+ "team_id": 123,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-1",+ "logger": mock.MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestAsknicelySource:+ def setup_method(self) -> None:+ self.source = AsknicelySource()+ self.team_id = 123+ self.config = AsknicelySourceConfig(subdomain="acme", api_key="test-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.ASKNICELY++ def test_subdomain_is_a_connection_host_field(self) -> None:+ # Changing the subdomain retargets which AskNicely tenant the stored key is+ # sent to, so it must force the API key to be re-entered.+ assert self.source.connection_host_fields == ["subdomain"]++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Asknicely"+ assert config.label == "AskNicely"+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA++ subdomain_field, api_key_field = config.fields+ assert isinstance(subdomain_field, SourceFieldInputConfig)+ assert subdomain_field.name == "subdomain"+ assert subdomain_field.type == SourceFieldInputConfigType.TEXT+ assert subdomain_field.required is True++ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.name == "api_key"+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.required is True+ assert api_key_field.secret is True++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error", "Unauthorized for url"])+ def test_non_retryable_errors(self, expected_key: str) -> None:+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert [s.name for s in schemas] == ["responses"]+ responses = schemas[0]+ assert responses.supports_incremental is True+ assert responses.supports_append is True+ assert [f["field"] for f in responses.incremental_fields] == ["responded"]++ def test_get_schemas_filtered_by_names(self) -> None:+ assert [s.name for s in self.source.get_schemas(self.config, self.team_id, names=["responses"])] == [+ "responses"+ ]+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []++ @pytest.mark.parametrize("subdomain", ["not a subdomain", "acme.asknice.ly", "evil/../path", ""])+ def test_validate_credentials_rejects_bad_subdomain_without_a_request(self, subdomain: str) -> None:+ config = AsknicelySourceConfig(subdomain=subdomain, api_key="test-key")++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.source.validate_asknicely_credentials"+ ) as mock_validate:+ is_valid, error_message = self.source.validate_credentials(config, self.team_id)++ assert is_valid is False+ assert error_message is not None and "subdomain" in error_message+ mock_validate.assert_not_called()++ @pytest.mark.parametrize(+ ("mock_return", "expected_valid"),+ [+ ((True, None), True),+ ((False, "Invalid AskNicely API key"), False),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.source.validate_asknicely_credentials"+ )+ def test_validate_credentials_delegates_to_transport(+ self,+ mock_validate: mock.MagicMock,+ mock_return: tuple[bool, str | None],+ expected_valid: bool,+ ) -> None:+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == mock_return[1]+ mock_validate.assert_called_once_with("acme", "test-key")++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is AskNicelyResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.source.asknicely_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = _make_inputs(+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000,+ incremental_field="responded",+ )+ manager = mock.MagicMock(spec=ResumableSourceManager)++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once_with(+ subdomain="acme",+ api_key="test-key",+ endpoint="responses",+ logger=inputs.logger,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000,+ )++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.source.asknicely_source")+ def test_source_for_pipeline_drops_last_value_on_full_refresh(self, mock_source: mock.MagicMock) -> None:+ # A stale watermark left over from a previous incremental run must not leak into a+ # full-refresh sync, or the refresh would silently skip older responses.+ inputs = _make_inputs(should_use_incremental_field=False, db_incremental_field_last_value=1700000000)++ self.source.source_for_pipeline(self.config, mock.MagicMock(spec=ResumableSourceManager), inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 09c4b95828d0..4cc0d3106dc5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -382,7 +382,8 @@ class AshbySourceConfig(config.Config):@config.configclass AsknicelySourceConfig(config.Config):- pass+ subdomain: str+ api_key: str@config.config