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(warehouse-sources): sync asknicely daily stats and unsubscribes (#99671)

Tom Owersb51054ec34e5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 3e395363559a..3aec6d168a80 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -551,15 +551,17 @@ Excluded as not table-shaped: `notetakerTranscript.info` is a single-object gett
## Asknicely — gaps
-Today (1): `responses`
+Today (3): `contacts_unsubscribed`, `responses`, `stats`
Diffed against: <https://asknicely.asknice.ly/help/apidocs/responses>
-- [ ] `GET /api/v1/stats` — daily historical time series (sent, delivered, opened, responded, promoters/passives/detractors, NPS, CSAT) - the vendor's headline metric, already tabular (high)
-- [ ] `GET /api/v1/contacts/unsubscribed` — paginated opt-out list with unsubscribe timestamps; the suppression table for any send analysis (medium)
+- [x] `GET /api/v1/stats` — daily historical time series (sent, delivered, opened, responded, promoters/passives/detractors, NPS, CSAT) - the vendor's headline metric, already tabular (high)
+- [x] `GET /api/v1/contacts/unsubscribed` — paginated opt-out list with unsubscribe timestamps; the suppression table for any send analysis (medium)
- [ ] `GET /api/v1/sentstats/{days}` — send-funnel counts for a rolling window, segmentable by custom property and question type (low)
-Note: AskNicely's v1 API is genuinely small; the only other GETs are a single-contact lookup (/contact/get/{search}/{key}, not a list) and /getnps/{days} which returns one scalar derivable from responses. Source uses a static ENDPOINTS = ("responses",) tuple - no dynamic table discovery.
+Note: AskNicely's v1 API is genuinely small; the only other GETs are a single-contact lookup (/contact/get/{search}/{key}, not a list) and /getnps/{days} which returns one scalar derivable from responses. Source uses a static ENDPOINTS tuple - no dynamic table discovery.
+
+Note on sentstats: skipped deliberately. It returns one unkeyed, untimestamped aggregate object for a rolling window, so a table of it holds a single row whose meaning depends on when the sync ran. Every column is a sum over the same columns `stats` now returns per day, so the same numbers come from a query over `stats` for any window. Its one extra capability - segmenting by a custom property via `filters[]`/`values[]` - cannot be expressed in a static endpoint catalog without hardcoding one customer's property.
## AssemblyAI — adequate
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.py
index 80fff771eb42..2212f871b8d2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/asknicely.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/asknicely.py
@@ -1,17 +1,26 @@
import re
import dataclasses
+from collections.abc import Callable
from datetime import UTC, date, datetime
from typing import Any, Optional
from requests import Request, Response
-from products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.settings import RESPONSES_PAGE_SIZE
+from products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.settings import (
+ PRIMARY_KEYS,
+ RESPONSES_PAGE_SIZE,
+ UNSUBSCRIBED_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.rest_source import (
RESTAPIConfig,
rest_api_resource,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
+ SinglePagePaginator,
+)
+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.typings import SourceResponse
@@ -20,6 +29,7 @@ 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")
+UNSUBSCRIBED_TIMESTAMP_FIELDS = ("unsubscribetime",)
@dataclasses.dataclass
@@ -54,6 +64,14 @@ def build_responses_url(subdomain: str, page_number: int, since_time: int, page_
return f"{_base_url(subdomain)}/api/v1/responses/asc/{page_size}/{page_number}/{since_time}/json/answered/responded"
+def build_stats_url(subdomain: str) -> str:
+ return f"{_base_url(subdomain)}/api/v1/stats"
+
+
+def build_unsubscribed_url(subdomain: str) -> str:
+ return f"{_base_url(subdomain)}/api/v1/contacts/unsubscribed"
+
+
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}")
@@ -81,8 +99,8 @@ def _parse_int(value: Any) -> Optional[int]:
return None
-def _normalize_row(row: dict[str, Any]) -> dict[str, Any]:
- for field in TIMESTAMP_FIELDS:
+def _normalize_row(row: dict[str, Any], timestamp_fields: tuple[str, ...] = TIMESTAMP_FIELDS) -> 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())
@@ -165,77 +183,131 @@ class AskNicelyResponsesPaginator(BasePaginator):
self._has_next_page = True
-def asknicely_source(
+class AskNicelyUnsubscribedPaginator(BasePaginator):
+ """Page-number paginator for AskNicely's unsubscribed contacts list.
+
+ `pagenumber` is 1-based and the response carries no total or page count, so a short page
+ is the only end-of-list signal. Stopping there also bounds the run if the API clamps an
+ out-of-range page to the last one rather than returning nothing — it documents neither.
+ """
+
+ def __init__(self, page_number: int = 1, page_size: int = UNSUBSCRIBED_PAGE_SIZE) -> None:
+ super().__init__()
+ self.page_number = page_number
+ self.page_size = page_size
+
+ def _apply(self, request: Request) -> None:
+ request.params = {**(request.params or {}), "pagenumber": self.page_number, "pagesize": self.page_size}
+
+ def init_request(self, request: Request) -> None:
+ self._apply(request)
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ if not data or len(data) < self.page_size:
+ self._has_next_page = False
+ return
+
+ self.page_number += 1
+ self._has_next_page = True
+
+ def update_request(self, request: Request) -> None:
+ self._apply(request)
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ # self.page_number already points at the next page to fetch (update_state incremented it).
+ if self._has_next_page:
+ return {"page_number": self.page_number}
+ return None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ page_number = state.get("page_number")
+ if page_number is not None:
+ self.page_number = int(page_number)
+ self._has_next_page = True
+
+
+def _client_config(subdomain: str, api_key: str) -> ClientConfig:
+ # `capture=False`: rows carry free-text survey comments, internal notes and contact emails
+ # 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 replays the `X-apikey` header to a redirect target, so an
+ # upstream 3xx can't leak the credential off the validated host.
+ session = make_tracked_session(redact_values=(api_key,), capture=False, allow_redirects=False)
+ return {
+ "base_url": _base_url(subdomain),
+ "headers": _get_headers(api_key),
+ "session": session,
+ "allow_redirects": False,
+ }
+
+
+def _checkpoint_saver(
+ resumable_source_manager: ResumableSourceManager[AskNicelyResumeConfig],
+) -> Callable[[Optional[dict[str, Any]]], None]:
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Save AFTER a page is yielded and only when more pages remain, so a crash re-yields the
+ # last page rather than skipping it — merge dedupes on the primary key.
+ if state and state.get("page_number") is not None:
+ resumable_source_manager.save_state(
+ AskNicelyResumeConfig(page_number=int(state["page_number"]), since_time=int(state.get("since_time", 0)))
+ )
+
+ return save_checkpoint
+
+
+def _resume_state(
+ resumable_source_manager: ResumableSourceManager[AskNicelyResumeConfig],
+) -> Optional[dict[str, Any]]:
+ if not resumable_source_manager.can_resume():
+ return None
+ resume = resumable_source_manager.load_state()
+ if resume is None:
+ return None
+ return {"page_number": resume.page_number, "since_time": resume.since_time}
+
+
+def _responses_source(
subdomain: str,
api_key: str,
- endpoint: str,
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[AskNicelyResumeConfig],
- should_use_incremental_field: bool = False,
- db_incremental_field_last_value: Optional[Any] = None,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
) -> SourceResponse:
since_time = _since_time_for_run(should_use_incremental_field, db_incremental_field_last_value)
- paginator = AskNicelyResponsesPaginator(subdomain=subdomain, since_time=since_time)
-
- # `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` (client config below) never replays the `X-apikey` header to a
- # redirect target, so an upstream 3xx can't leak the credential off the validated host.
- session = make_tracked_session(redact_values=(api_key,), capture=False, allow_redirects=False)
-
config: RESTAPIConfig = {
- "client": {
- "base_url": _base_url(subdomain),
- "headers": _get_headers(api_key),
- "session": session,
- "allow_redirects": False,
- },
+ "client": _client_config(subdomain, api_key),
"resource_defaults": {},
"resources": [
{
- "name": endpoint,
+ "name": "responses",
"endpoint": {
# The paginator rewrites the full request URL each page, so the path here is a
# placeholder for the first request before init_request runs.
"path": build_responses_url(subdomain, page_number=1, since_time=since_time),
"data_selector": "data",
- "paginator": paginator,
+ "paginator": AskNicelyResponsesPaginator(subdomain=subdomain, since_time=since_time),
},
"data_map": _normalize_row,
}
],
}
- 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 = {"page_number": resume.page_number, "since_time": resume.since_time}
-
- def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
- # Save AFTER a page is yielded and only when more pages remain, so a crash re-yields the
- # last page rather than skipping it — merge dedupes on the primary key.
- if state and state.get("page_number") is not None:
- resumable_source_manager.save_state(
- AskNicelyResumeConfig(page_number=int(state["page_number"]), since_time=int(state["since_time"]))
- )
-
resource = rest_api_resource(
config,
team_id,
job_id,
db_incremental_field_last_value,
- resume_hook=save_checkpoint,
- initial_paginator_state=initial_paginator_state,
+ resume_hook=_checkpoint_saver(resumable_source_manager),
+ initial_paginator_state=_resume_state(resumable_source_manager),
)
return SourceResponse(
- name=endpoint,
+ name="responses",
items=lambda: resource,
- primary_keys=["response_id"],
+ primary_keys=PRIMARY_KEYS["responses"],
sort_mode="asc",
partition_count=1,
partition_size=1,
@@ -247,6 +319,108 @@ def asknicely_source(
)
+def _stats_source(subdomain: str, api_key: str, team_id: int, job_id: str) -> SourceResponse:
+ config: RESTAPIConfig = {
+ "client": _client_config(subdomain, api_key),
+ "resource_defaults": {},
+ "resources": [
+ {
+ "name": "stats",
+ "endpoint": {
+ # Unnarrowed: the year/month/day params only filter the series down, and we
+ # want every day AskNicely holds.
+ "path": build_stats_url(subdomain),
+ "data_selector": "data",
+ "paginator": SinglePagePaginator(),
+ },
+ }
+ ],
+ }
+
+ resource = rest_api_resource(config, team_id, job_id, None)
+
+ return SourceResponse(
+ name="stats",
+ items=lambda: resource,
+ primary_keys=PRIMARY_KEYS["stats"],
+ column_hints=resource.column_hints,
+ )
+
+
+def _unsubscribed_source(
+ subdomain: str,
+ api_key: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[AskNicelyResumeConfig],
+) -> SourceResponse:
+ config: RESTAPIConfig = {
+ "client": _client_config(subdomain, api_key),
+ "resource_defaults": {},
+ "resources": [
+ {
+ "name": "contacts_unsubscribed",
+ "endpoint": {
+ "path": build_unsubscribed_url(subdomain),
+ "data_selector": "data",
+ "paginator": AskNicelyUnsubscribedPaginator(),
+ },
+ "data_map": lambda row: _normalize_row(row, UNSUBSCRIBED_TIMESTAMP_FIELDS),
+ }
+ ],
+ }
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=_checkpoint_saver(resumable_source_manager),
+ initial_paginator_state=_resume_state(resumable_source_manager),
+ )
+
+ return SourceResponse(
+ name="contacts_unsubscribed",
+ items=lambda: resource,
+ primary_keys=PRIMARY_KEYS["contacts_unsubscribed"],
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ # An opt-out is recorded once and never moves, so partitions never rewrite.
+ partition_keys=["unsubscribetime"],
+ column_hints=resource.column_hints,
+ )
+
+
+def asknicely_source(
+ subdomain: str,
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[AskNicelyResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ if endpoint == "responses":
+ return _responses_source(
+ subdomain,
+ api_key,
+ team_id,
+ job_id,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ if endpoint == "stats":
+ return _stats_source(subdomain, api_key, team_id, job_id)
+ if endpoint == "contacts_unsubscribed":
+ return _unsubscribed_source(subdomain, api_key, team_id, job_id, resumable_source_manager)
+
+ raise ValueError(f"Unknown AskNicely endpoint: {endpoint}")
+
+
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
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.py
index f7bdc9454a1e..b05a739a2586 100644
--- 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.py
@@ -30,4 +30,37 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"deliverymethod": "Channel the survey was delivered through (e.g. email).",
},
},
+ "stats": {
+ "description": "Daily survey statistics: one row per calendar day with send, delivery, open and response counts alongside the NPS, CSAT and 5-star scores for that day.",
+ "docs_url": "https://asknicely.asknice.ly/help/apidocs/stats",
+ "columns": {
+ "year": "Year of the day the row covers.",
+ "month": "Month of the day the row covers, not zero-padded.",
+ "day": "Day of the month the row covers, not zero-padded.",
+ "weekday": "Abbreviated weekday name for the day the row covers (e.g. Thu).",
+ "sent": "Number of surveys sent that day.",
+ "delivered": "Number of sent surveys that were delivered.",
+ "opened": "Number of delivered surveys that were opened.",
+ "responded": "Number of surveys that were answered.",
+ "promoters": "Number of NPS responses scoring 9 or 10.",
+ "passives": "Number of NPS responses scoring 7 or 8.",
+ "detractors": "Number of NPS responses scoring 0 to 6.",
+ "nps": "Net Promoter Score for the day, null when there were no NPS responses.",
+ "fivestar": "Average 5-star rating for the day, null when there were no 5-star responses.",
+ "csat": "CSAT score for the day, null when there were no CSAT responses.",
+ "comment_length": "Average length of the comments left that day.",
+ "comment_responded_percent": "Percentage of respondents who also left a comment.",
+ "surveys_responded_percent": "Percentage of sent surveys that were answered.",
+ "surveys_opened_responded_percent": "Percentage of opened surveys that were answered.",
+ },
+ },
+ "contacts_unsubscribed": {
+ "description": "Contacts who opted out through the unsubscribe link in a survey email. Use it to suppress them from send and response analysis.",
+ "docs_url": "https://asknicely.asknice.ly/help/apidocs/getunsubscribed",
+ "columns": {
+ "id": "Identifier of the contact who unsubscribed. Matches contact_id on the responses table.",
+ "unsubscribetime": "Unix timestamp when the contact unsubscribed.",
+ "email": "Email address of the contact who unsubscribed.",
+ },
+ },
}
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.py
index ad7215901fb8..c0bf3dd07832 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/settings.py
@@ -4,10 +4,24 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
# 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",)
+# The unsubscribed list defaults to 1,000 rows per page. Send it explicitly so page
+# numbering stays stable even if the account default ever differs.
+UNSUBSCRIBED_PAGE_SIZE = 1000
+# AskNicely's warehousing-shaped GETs. The rest of the v1 API is either action-only
+# (contact add/trigger, send survey) or a single-value rollup of `stats` (sentstats, getnps).
+ENDPOINTS = ("responses", "stats", "contacts_unsubscribed")
+
+PRIMARY_KEYS: dict[str, list[str]] = {
+ "responses": ["response_id"],
+ # `stats` labels each daily row with its date parts rather than carrying a date column.
+ "stats": ["year", "month", "day"],
+ "contacts_unsubscribed": ["id"],
+}
+
+# Only `responses` takes a server-side time cutoff (`since_time`). `stats` rows keep changing
+# after their date — a survey sent on Monday and opened on Friday moves Monday's counts — and
+# the unsubscribed list takes no time filter at all, so both sync as a full refresh.
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
"responses": [
{
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.py
index 7a5b9c457326..a3ef888f8155 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
@@ -55,7 +55,7 @@ class AsknicelySource(ResumableSource[AsknicelySourceConfig, AskNicelyResumeConf
label="AskNicely",
releaseStatus=ReleaseStatus.ALPHA,
keywords=["nps", "csat", "survey"],
- caption="""Sync your AskNicely survey responses (NPS, CSAT, 5-star) into the PostHog Data warehouse.
+ caption="""Sync your AskNicely survey responses (NPS, CSAT, 5-star), daily stats and unsubscribed contacts 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",
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.py
index 6d1dcbdfee5a..364ce228a570 100644
--- 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.py
@@ -13,9 +13,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.
_to_unix_timestamp,
asknicely_source,
build_responses_url,
+ build_stats_url,
+ build_unsubscribed_url,
validate_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.settings import RESPONSES_PAGE_SIZE
+from products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.settings import (
+ RESPONSES_PAGE_SIZE,
+ UNSUBSCRIBED_PAGE_SIZE,
+)
MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.asknicely"
@@ -37,22 +42,27 @@ def _manager(resume: Optional[AskNicelyResumeConfig] = None) -> mock.MagicMock:
return manager
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[str]:
- """Wire a mock session and capture each request's URL AT PREPARE TIME.
+def _wire(session: mock.MagicMock, responses: list[Response]) -> list[tuple[str, dict[str, Any]]]:
+ """Wire a mock session and capture each request's URL and params AT PREPARE TIME.
- The paginator mutates ``request.url`` in place across pages, so inspecting it after the run
- shows only the final URL — snapshot it when each request is prepared instead.
+ The paginators mutate ``request.url`` and ``request.params`` in place across pages, so
+ inspecting them after the run shows only the final page — snapshot each request as it is
+ prepared instead.
"""
session.headers = {}
- url_snapshots: list[str] = []
+ snapshots: list[tuple[str, dict[str, Any]]] = []
def _prepare(request: Any) -> mock.MagicMock:
- url_snapshots.append(request.url)
+ snapshots.append((request.url, dict(request.params or {})))
return mock.MagicMock()
session.prepare_request.side_effect = _prepare
session.send.side_effect = responses
- return url_snapshots
+ return snapshots
+
+
+def _urls(calls: list[tuple[str, dict[str, Any]]]) -> list[str]:
+ return [url for url, _ in calls]
def _rows(source_response) -> list[dict[str, Any]]:
@@ -105,15 +115,16 @@ class TestAsknicely:
manager: mock.MagicMock,
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Any = None,
- ) -> tuple[list[dict[str, Any]], list[str]]:
+ endpoint: str = "responses",
+ ) -> tuple[list[dict[str, Any]], list[tuple[str, dict[str, Any]]]]:
session = mock.MagicMock()
- urls = _wire(session, responses)
+ calls = _wire(session, responses)
with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
rows = _rows(
asknicely_source(
subdomain="acme",
api_key="key",
- endpoint="responses",
+ endpoint=endpoint,
team_id=1,
job_id="job-1",
resumable_source_manager=manager,
@@ -121,7 +132,7 @@ class TestAsknicely:
db_incremental_field_last_value=db_incremental_field_last_value,
)
)
- return rows, urls
+ return rows, calls
def test_paginates_until_totalpages_and_normalizes_rows(self) -> None:
manager = _manager()
@@ -130,12 +141,12 @@ class TestAsknicely:
_response([{"response_id": "r2", "responded": "200"}], total_pages=2),
]
- rows, urls = self._run(responses, manager)
+ rows, calls = self._run(responses, manager)
assert [row["response_id"] for row in rows] == ["r1", "r2"]
# String timestamps are coerced to ints via the data_map.
assert rows[0]["responded"] == 100
- assert urls == [
+ assert _urls(calls) == [
build_responses_url("acme", page_number=1, since_time=0),
build_responses_url("acme", page_number=2, since_time=0),
]
@@ -148,48 +159,48 @@ class TestAsknicely:
_response([]),
]
- rows, urls = self._run(responses, _manager())
+ rows, calls = self._run(responses, _manager())
assert len(rows) == RESPONSES_PAGE_SIZE
- assert len(urls) == 2
+ assert len(calls) == 2
def test_short_page_without_totalpages_terminates(self) -> None:
- rows, urls = self._run([_response([{"response_id": "r1", "responded": "100"}])], _manager())
+ rows, calls = self._run([_response([{"response_id": "r1", "responded": "100"}])], _manager())
assert [row["response_id"] for row in rows] == ["r1"]
- assert len(urls) == 1
+ assert len(calls) == 1
def test_incremental_since_time_steps_back_one_second(self) -> None:
- _, urls = self._run(
+ _, calls = self._run(
[_response([])],
_manager(),
should_use_incremental_field=True,
db_incremental_field_last_value=1700000000,
)
- assert urls == [build_responses_url("acme", page_number=1, since_time=1699999999)]
+ assert _urls(calls) == [build_responses_url("acme", page_number=1, since_time=1699999999)]
def test_incremental_since_time_clamps_at_zero(self) -> None:
- _, urls = self._run(
+ _, calls = self._run(
[_response([])],
_manager(),
should_use_incremental_field=True,
db_incremental_field_last_value=0,
)
- assert urls == [build_responses_url("acme", page_number=1, since_time=0)]
+ assert _urls(calls) == [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(
+ _, calls = self._run(
[_response([])],
manager,
should_use_incremental_field=True,
db_incremental_field_last_value=1700000000,
)
- assert urls == [build_responses_url("acme", page_number=3, since_time=500)]
+ assert _urls(calls) == [build_responses_url("acme", page_number=3, since_time=500)]
def test_no_checkpoint_on_single_short_page(self) -> None:
# A run that finishes on its first page must never checkpoint — there is no next page.
@@ -197,6 +208,59 @@ class TestAsknicely:
self._run([_response([{"response_id": "r1", "responded": "100"}])], manager)
manager.save_state.assert_not_called()
+ def test_unsubscribed_paginates_by_page_number_and_normalizes_rows(self) -> None:
+ manager = _manager()
+ first = [
+ {"id": str(i), "unsubscribetime": "1452219376", "email": f"c{i}@example.com"}
+ for i in range(UNSUBSCRIBED_PAGE_SIZE)
+ ]
+ responses = [_response(first), _response([{"id": "last", "unsubscribetime": "1452219999"}])]
+
+ rows, calls = self._run(responses, manager, endpoint="contacts_unsubscribed")
+
+ assert len(rows) == UNSUBSCRIBED_PAGE_SIZE + 1
+ # The unix timestamp arrives as a string; it has to be an int to partition on and to
+ # compare against the responses table's timestamps.
+ assert rows[0]["unsubscribetime"] == 1452219376
+ assert _urls(calls) == [build_unsubscribed_url("acme")] * 2
+ assert [params["pagenumber"] for _, params in calls] == [1, 2]
+ assert {params["pagesize"] for _, params in calls} == {UNSUBSCRIBED_PAGE_SIZE}
+ # The short second page ends the walk, so only the one page boundary is checkpointed.
+ manager.save_state.assert_called_once_with(AskNicelyResumeConfig(page_number=2, since_time=0))
+
+ def test_unsubscribed_resumes_from_saved_page(self) -> None:
+ manager = _manager(AskNicelyResumeConfig(page_number=3, since_time=0))
+
+ _, calls = self._run([_response([])], manager, endpoint="contacts_unsubscribed")
+
+ assert [params["pagenumber"] for _, params in calls] == [3]
+
+ def test_stats_fetches_one_page_and_never_checkpoints(self) -> None:
+ # The stats series comes back whole, so a second request would re-read the same rows
+ # and a saved checkpoint would leave a later run resuming a page that never existed.
+ manager = _manager()
+
+ rows, calls = self._run(
+ [_response([{"year": "2023", "month": "8", "day": "16", "nps": "50.0"}])],
+ manager,
+ endpoint="stats",
+ )
+
+ assert [row["day"] for row in rows] == ["16"]
+ assert _urls(calls) == [build_stats_url("acme")]
+ manager.save_state.assert_not_called()
+
+ def test_unknown_endpoint_raises(self) -> None:
+ with pytest.raises(ValueError, match="Unknown AskNicely endpoint"):
+ asknicely_source(
+ subdomain="acme",
+ api_key="key",
+ endpoint="nope",
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=_manager(),
+ )
+
def test_sync_session_disables_capture_and_redirects(self) -> None:
# Survey bodies stay out of HTTP sample capture, and the X-apikey header must never be
# replayed to a redirect target.
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.py
index ee437f5819c5..69724c6c7175 100644
--- 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.py
@@ -42,18 +42,22 @@ class TestAsknicelySource:
assert self.source.connection_host_fields == ["subdomain"]
def test_get_schemas(self) -> None:
- schemas = self.source.get_schemas(self.config, self.team_id)
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
- assert [s.name for s in schemas] == ["responses"]
- responses = schemas[0]
+ responses = schemas["responses"]
assert responses.supports_incremental is True
assert responses.supports_append is True
assert [f["field"] for f in responses.incremental_fields] == ["responded"]
+ # Neither `stats` nor the unsubscribed list takes a server-side time cutoff, so
+ # advertising them as incremental would silently skip rows every sync.
+ for name in ("stats", "contacts_unsubscribed"):
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].supports_append is False
+ assert schemas[name].incremental_fields == []
+
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 [s.name for s in self.source.get_schemas(self.config, self.team_id, names=["stats"])] == ["stats"]
assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []
@pytest.mark.parametrize("subdomain", ["not a subdomain", "acme.asknice.ly", "evil/../path", ""])