Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add 4 missing tables to the ZonkaFeedback source (#119095)

Tom Owersb85ecfd80fec
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index b5ea92c10710..35878a60ba44 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -1241,8 +1241,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/zep/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/zep/zep.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/zoho_crm.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/settings.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/zonka_feedback.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/zoom/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/zoom/zoom.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/zuora/zuora.py
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 48fd3a8fe237..b3b9bd46c8af 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
@@ -13568,10 +13568,10 @@ Today (4): `contacts`, `responses`, `survey_links`, `surveys`
Diffed against: <https://apidocs.zonkafeedback.com/api/collections/2077940/TVCY7Cby>
- [x] `survey-links` — shareable per-survey link objects from the Survey Links API (GET /survey-links); each carries the URL and tracking code used to attribute a collected response (high)
-- [ ] `workspaces` — lookup resolving the workspace ID carried on surveys and responses; required to segment reporting by workspace (high)
-- [ ] `locations` — lookup resolving the location ID on responses - the standard breakdown dimension for multi-site CX programs (high)
-- [ ] `distribution-logs` — survey send log; pairing it with responses gives delivery, open and response rates instead of responses alone (high)
-- [ ] `users` — lookup resolving the user IDs on tasks and response assignments (medium)
+- [x] `workspaces` — lookup resolving the workspace ID carried on surveys and responses; required to segment reporting by workspace (high)
+- [x] `locations` — lookup resolving the location ID on responses - the standard breakdown dimension for multi-site CX programs (high)
+- [x] `distribution-logs` — survey send log; pairing it with responses gives delivery, open and response rates instead of responses alone (high)
+- [x] `users` — lookup resolving the user IDs on tasks and response assignments (medium)
- [ ] `tasks` — close-the-loop follow-up tasks raised from responses, with status and assignee (medium)
- [ ] `contactlist (contact segments)` — contact-to-segment membership, the audience dimension for response analysis (medium)
- [ ] `devices` — kiosk/device lookup resolving the device ID on offline responses (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/canonical_descriptions.py
index 71a24973ca66..9b0e97bd9a80 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/canonical_descriptions.py
@@ -59,4 +59,60 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"createdOn": "The timestamp the link was created, in ISO 8601 UTC.",
},
},
+ "workspaces": {
+ "description": "A workspace in the Zonka Feedback account. Workspaces group surveys and are used to segment reporting.",
+ "docs_url": "https://apidocs.zonkafeedback.com/",
+ "columns": {
+ "id": "The unique ID of the workspace, referenced by `workspaceId` on surveys.",
+ "workspaceName": "The name of the workspace.",
+ "modifiedDate": "The timestamp the workspace was last modified, in ISO 8601 UTC.",
+ "modifiedBy": "The name of the user who last modified the workspace.",
+ },
+ },
+ "locations": {
+ "description": "A location in the Zonka Feedback account, such as a site or branch that surveys and responses belong to.",
+ "docs_url": "https://apidocs.zonkafeedback.com/",
+ "columns": {
+ "id": "The unique ID of the location, referenced by `locationId` on surveys and responses.",
+ "name": "The name of the location.",
+ "address": "The address of the location.",
+ "externalId": "Your own identifier for the location.",
+ "isActive": "Whether the location is active.",
+ "labels": "The location labels assigned to the location.",
+ },
+ },
+ "users": {
+ "description": "A user of the Zonka Feedback account, such as an admin, a responder or a device user.",
+ "docs_url": "https://apidocs.zonkafeedback.com/",
+ "columns": {
+ "id": "The unique ID of the user, referenced by user IDs on responses and tasks.",
+ "name": "The user's name.",
+ "email": "The user's email address.",
+ "mobile": "The user's mobile number.",
+ "externalId": "Your own identifier for the user.",
+ "designation": "The user's job title.",
+ "role": "The user's role: admin, viewrespond, viewonly, deviceuser or external.",
+ "labels": "The user labels assigned to the user.",
+ "lastLogin": "The timestamp the user last logged in, in ISO 8601 UTC.",
+ "isOwner": "Whether the user is the account owner.",
+ "isActive": "Whether the user is active.",
+ "locationId": "The IDs of the locations the user is assigned to.",
+ },
+ },
+ "distribution_logs": {
+ "description": "One survey send through email, SMS or WhatsApp, with when the recipient opened and submitted it. Pair with responses to get delivery, open and response rates.",
+ "docs_url": "https://apidocs.zonkafeedback.com/",
+ "columns": {
+ "to": "The email address or phone number the survey was sent to.",
+ "sentDateTime": "The timestamp the survey was sent, in ISO 8601 UTC.",
+ "surveyId": "The ID of the survey that was sent.",
+ "surveyName": "The name of the survey that was sent.",
+ "emailOpened": "The timestamp the recipient opened the email, or null.",
+ "surveyOpened": "The timestamp the recipient opened the survey, or null.",
+ "SurveySubmitted": "The timestamp the recipient submitted the survey, or null.",
+ "locationName": "The name of the location the send is attributed to.",
+ "channel": "The channel the survey was sent through: email, sms or whatsapp.",
+ "status": "The distribution status: responded, surveyOpened, emailOpened or noResponse.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/settings.py
index 67901c0351d3..aff39478473a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/settings.py
@@ -1,19 +1,27 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Optional
+from posthog.dataclasses import frozen
-@dataclass
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+
+@frozen
class ZonkaFeedbackEndpointConfig:
name: str
path: str
# Zonka Feedback object IDs are unique within an account, so `id` is a safe primary key.
primary_keys: list[str] = field(default_factory=lambda: ["id"])
partition_key: Optional[str] = None
+ # False for list endpoints with no documented `page` parameter: a page-number walk that stops on
+ # an empty page would request the same full list forever.
+ paginated: bool = True
-# Zonka Feedback v2.1 account-level list endpoints. All are full-refresh only: the public REST
-# list endpoints expose page/page_size pagination but no documented server-side `updated_after`
-# date cursor, so there is no genuine incremental cursor to advance.
+# Zonka Feedback v2.1 account-level list endpoints. All except `distribution_logs` are full-refresh
+# only: their list endpoints expose page/page_size pagination but no documented server-side
+# `updated_after` date cursor, so there is no genuine incremental cursor to advance.
ZONKA_FEEDBACK_ENDPOINTS: dict[str, ZonkaFeedbackEndpointConfig] = {
"responses": ZonkaFeedbackEndpointConfig(name="responses", path="/responses"),
"surveys": ZonkaFeedbackEndpointConfig(name="surveys", path="/surveys"),
@@ -21,9 +29,25 @@ ZONKA_FEEDBACK_ENDPOINTS: dict[str, ZonkaFeedbackEndpointConfig] = {
# Snake_case schema name, hyphenated vendor path — the shareable link objects returned by the
# Survey Links API. Zonka object IDs live in the `id` field, so the default primary key applies.
"survey_links": ZonkaFeedbackEndpointConfig(name="survey_links", path="/survey-links"),
+ "workspaces": ZonkaFeedbackEndpointConfig(name="workspaces", path="/workspaces", paginated=False),
+ "locations": ZonkaFeedbackEndpointConfig(name="locations", path="/locations"),
+ "users": ZonkaFeedbackEndpointConfig(name="users", path="/users"),
+ # Log rows carry no ID. One row is one send of a survey on one channel to one recipient, so the
+ # send time completes the key.
+ "distribution_logs": ZonkaFeedbackEndpointConfig(
+ name="distribution_logs",
+ path="/distribution-logs",
+ primary_keys=["surveyId", "channel", "to", "sentDateTime"],
+ partition_key="sentDateTime",
+ ),
}
ENDPOINTS = tuple(ZONKA_FEEDBACK_ENDPOINTS.keys())
-# Full refresh only — no endpoint exposes a server-side timestamp filter to drive incremental sync.
-INCREMENTAL_FIELDS: dict[str, list] = {}
+# `distribution-logs` requires a `startDate`/`endDate` window, which doubles as a server-side filter.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "distribution_logs": [incremental_field("sentDateTime")],
+}
+
+# The send channels `distribution-logs` accepts; the endpoint requires one per request.
+DISTRIBUTION_LOG_CHANNELS: tuple[str, ...] = ("email", "sms", "whatsapp")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/source.py
index 65075027e7c0..75594aa021ab 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/source.py
@@ -139,8 +139,7 @@ An Admin can generate an auth token under **Company Settings → Developers →
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- # Every endpoint is full refresh only — Zonka Feedback's list endpoints expose no server-side
- # timestamp filter (INCREMENTAL_FIELDS is empty), so there is no incremental cursor to advance.
+ # Only `distribution_logs` has a server-side date filter; every other endpoint is full refresh.
return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
def validate_credentials(
@@ -178,4 +177,7 @@ An Admin can generate an auth token under **Company Settings → Developers →
team_id=inputs.team_id,
job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
+ 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/zonka_feedback/tests/test_zonka_feedback.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/tests/test_zonka_feedback.py
index 0814c85d42d9..d4654a67256b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/tests/test_zonka_feedback.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/tests/test_zonka_feedback.py
@@ -1,12 +1,14 @@
from typing import Any
import pytest
+import time_machine
import requests
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
DriveResult,
+ RecordedRequest,
ScriptedResponse,
SourceDriver,
always,
@@ -15,10 +17,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.tes
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.zonkafeedback import (
ZonkaFeedbackSourceConfig,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.zonka_feedback.settings import (
- ENDPOINTS,
- ZONKA_FEEDBACK_ENDPOINTS,
-)
from products.warehouse_sources.backend.temporal.data_imports.sources.zonka_feedback.source import ZonkaFeedbackSource
from products.warehouse_sources.backend.temporal.data_imports.sources.zonka_feedback.zonka_feedback import (
ZonkaFeedbackResumeConfig,
@@ -39,10 +37,45 @@ def _redirect(location: str = "https://evil.example.com/") -> ScriptedResponse:
def _run(
- script: Any, endpoint: str = "responses", resume_state: ZonkaFeedbackResumeConfig | None = None
+ script: Any, endpoint: str = "responses", resume_state: ZonkaFeedbackResumeConfig | None = None, **inputs: Any
) -> DriveResult:
driver = SourceDriver(ZonkaFeedbackSource(), ZonkaFeedbackSourceConfig(auth_token="zonka-token", data_center="us1"))
- return driver.run(endpoint, script, resume_state=resume_state)
+ return driver.run(endpoint, script, resume_state=resume_state, **inputs)
+
+
+SURVEY_PAGES: dict[int, list[dict[str, Any]]] = {1: [{"id": "s2"}, {"id": "s1"}], 2: [{"id": "s3"}, {"name": "no id"}]}
+LOG_EMAIL_FIRST = {
+ "sentDateTime": "2026-03-02T10:00:00.000Z",
+ "surveyId": "s1",
+ "channel": "email",
+ "emailOpened": None,
+ "status": "noResponse",
+}
+LOG_EMAIL_SECOND = {**LOG_EMAIL_FIRST, "to": "[email protected]", "sentDateTime": "2026-03-01T09:00:00.000Z"}
+LOG_WHATSAPP_NO_KEYS = {"to": "+15550100", "sentDateTime": "2026-02-27T08:00:00.000Z", "status": "responded"}
+LOG_PAGES: dict[tuple[str, str, int], list[dict[str, Any]]] = {
+ ("s1", "email", 1): [LOG_EMAIL_FIRST],
+ ("s1", "email", 2): [LOG_EMAIL_SECOND],
+ ("s3", "whatsapp", 1): [LOG_WHATSAPP_NO_KEYS],
+}
+
+
+def _zonka_account(request: RecordedRequest) -> ScriptedResponse:
+ page = int(request.param("page") or 1)
+ if request.path == "/surveys":
+ return _response(SURVEY_PAGES.get(page, []))
+ assert request.path == "/distribution-logs"
+ key = (request.param("surveyId") or "", request.param("channel") or "", page)
+ return _response(LOG_PAGES.get(key, []))
+
+
+def _log_requests(result: DriveResult) -> list[tuple[str | None, str | None, str | None]]:
+ return [
+ (request.param("surveyId"), request.param("channel"), request.param("page"))
+ for request in result.requests
+ if request.path == "/distribution-logs"
+ ]
class TestPagination:
@@ -143,6 +176,142 @@ class TestZonkaFeedbackSourceResponse:
assert response.partition_mode is None
assert response.partition_keys is None
- def test_every_endpoint_uses_id_primary_key(self) -> None:
- assert all(config.primary_keys == ["id"] for config in ZONKA_FEEDBACK_ENDPOINTS.values())
- assert set(ZONKA_FEEDBACK_ENDPOINTS) == set(ENDPOINTS)
+ @parameterized.expand(
+ [
+ ("paginated", "locations", [[{"id": "l1"}], [{"id": "l2"}], []], ["1", "2", "3"]),
+ # A page-number walk on an endpoint that ignores `page` would fetch the same list forever.
+ ("unpaginated", "workspaces", [[{"id": "w1"}, {"id": "w2"}]], [None]),
+ ]
+ )
+ def test_list_endpoint_walk(
+ self, _name: str, endpoint: str, pages: list[list[dict[str, Any]]], expected_pages: list[str | None]
+ ) -> None:
+ result = _run([_response(page) for page in pages], endpoint=endpoint)
+
+ assert result.raised is None
+ assert result.rows == [row for page in pages for row in page]
+ assert result.params("page") == expected_pages
+
+
+def _state(survey_id: str, channel: str, page: int, end_date: str = "2026-06-01") -> ZonkaFeedbackResumeConfig:
+ return ZonkaFeedbackResumeConfig(next_page=page, survey_id=survey_id, channel=channel, end_date=end_date)
+
+
+class TestDistributionLogs:
+ @time_machine.travel("2026-06-01T23:30:00Z", tick=False)
+ def test_walks_every_survey_and_channel(self) -> None:
+ result = _run(_zonka_account, endpoint="distribution_logs")
+
+ assert result.raised is None
+ assert result.params("page")[:3] == ["1", "2", "3"]
+ assert _log_requests(result) == [
+ ("s1", "email", "1"),
+ ("s1", "email", "2"),
+ ("s1", "email", "3"),
+ ("s1", "sms", "1"),
+ ("s1", "whatsapp", "1"),
+ ("s2", "email", "1"),
+ ("s2", "sms", "1"),
+ ("s2", "whatsapp", "1"),
+ ("s3", "email", "1"),
+ ("s3", "sms", "1"),
+ ("s3", "whatsapp", "1"),
+ ("s3", "whatsapp", "2"),
+ ]
+ assert result.rows == [
+ LOG_EMAIL_FIRST,
+ LOG_EMAIL_SECOND,
+ {"surveyId": "s3", "channel": "whatsapp", **LOG_WHATSAPP_NO_KEYS},
+ ]
+ # Each pair is saved before it is read, so a pair with no rows still moves the saved cursor on.
+ assert result.committed_states == [
+ _state("s1", "email", 1),
+ _state("s1", "email", 2),
+ _state("s1", "email", 3),
+ _state("s1", "sms", 1),
+ _state("s1", "whatsapp", 1),
+ _state("s2", "email", 1),
+ _state("s2", "sms", 1),
+ _state("s2", "whatsapp", 1),
+ _state("s3", "email", 1),
+ _state("s3", "sms", 1),
+ _state("s3", "whatsapp", 1),
+ _state("s3", "whatsapp", 2),
+ ]
+ assert result.completed_state is None
+
+ @time_machine.travel("2026-06-01T23:30:00Z", tick=False)
+ def test_resume_keeps_the_saved_end_date(self) -> None:
+ result = _run(_zonka_account, endpoint="distribution_logs", resume_state=_state("s1", "email", 2, "2026-05-30"))
+
+ assert result.raised is None
+ log_requests = [request for request in result.requests if request.path == "/distribution-logs"]
+ assert {request.param("endDate") for request in log_requests} == {"2026-05-30"}
+
+ @parameterized.expand(
+ [
+ ("mid_pair", ZonkaFeedbackResumeConfig(next_page=2, survey_id="s1", channel="email"), ("s1", "email", "2")),
+ (
+ "later_channel",
+ ZonkaFeedbackResumeConfig(next_page=1, survey_id="s3", channel="sms"),
+ ("s3", "sms", "1"),
+ ),
+ (
+ "survey_deleted_since",
+ ZonkaFeedbackResumeConfig(next_page=4, survey_id="s15", channel="sms"),
+ ("s2", "email", "1"),
+ ),
+ ("past_last_pair", ZonkaFeedbackResumeConfig(next_page=2, survey_id="s9", channel="email"), None),
+ ]
+ )
+ def test_resumes_from_saved_pair(
+ self,
+ _name: str,
+ resume_state: ZonkaFeedbackResumeConfig,
+ expected_first_request: tuple[str, str, str] | None,
+ ) -> None:
+ result = _run(_zonka_account, endpoint="distribution_logs", resume_state=resume_state)
+
+ assert result.raised is None
+ log_requests = _log_requests(result)
+ assert (log_requests[0] if log_requests else None) == expected_first_request
+ assert ("s1", "email", "1") not in log_requests
+
+ @parameterized.expand(
+ [
+ ("full_refresh", {}, "2010-01-01"),
+ (
+ "incremental",
+ {"incremental_field": "sentDateTime", "db_incremental_field_last_value": "2026-03-05T00:30:00Z"},
+ "2026-03-04",
+ ),
+ (
+ "full_refresh_ignores_stale_watermark",
+ {
+ "incremental_field": "sentDateTime",
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": "2026-03-05T00:30:00Z",
+ },
+ "2010-01-01",
+ ),
+ ]
+ )
+ @time_machine.travel("2026-06-01T23:30:00Z", tick=False)
+ def test_date_window(self, _name: str, inputs: dict[str, Any], expected_start: str) -> None:
+ result = _run(_zonka_account, endpoint="distribution_logs", **inputs)
+
+ assert result.raised is None
+ log_requests = [request for request in result.requests if request.path == "/distribution-logs"]
+ assert {request.param("startDate") for request in log_requests} == {expected_start}
+ assert {request.param("endDate") for request in log_requests} == {"2026-06-01"}
+
+ def test_unparseable_watermark_fails_loud(self) -> None:
+ result = _run(
+ _zonka_account,
+ endpoint="distribution_logs",
+ incremental_field="sentDateTime",
+ db_incremental_field_last_value="not a date",
+ )
+
+ assert isinstance(result.raised, ValueError)
+ assert result.requests == []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/zonka_feedback.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/zonka_feedback.py
index 682d26b71368..5318a09ca482 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/zonka_feedback.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/zonka_feedback.py
@@ -1,20 +1,29 @@
-import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_value
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.auth import BearerTokenAuth
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
PageNumberPaginator,
+ SinglePagePaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import AuthConfig
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.zonka_feedback.settings import (
+ DISTRIBUTION_LOG_CHANNELS,
ZONKA_FEEDBACK_ENDPOINTS,
+ ZonkaFeedbackEndpointConfig,
)
# Vendor API version labels — opaque strings, never parsed or ordered. v2.1 is Zonka's current
@@ -35,13 +44,22 @@ FIRST_PAGE = 1
# Cheap endpoint used to confirm an auth token is genuine. The admin-generated token is account-wide,
# so one probe validates access to every list endpoint.
DEFAULT_PROBE_PATH = "/surveys"
+# `distribution-logs` requires a `startDate`, and the docs give no bound on how far back it may go.
+# A full refresh starts before any Zonka Feedback account existed.
+DISTRIBUTION_LOGS_EARLIEST_DATE = date(2010, 1, 1)
+@frozen
class ZonkaFeedbackResumeConfig:
# Next page to fetch (1-indexed). Page-number pagination is deterministic, so a crashed
# full-refresh sync resumes from the page after the last one yielded; merge dedupes on `id`.
next_page: int = 1
+ # `distribution_logs` only: the survey and channel that `next_page` belongs to.
+ survey_id: Optional[str] = None
+ channel: Optional[str] = None
+ # `distribution_logs` only: the `endDate` the saved page was fetched under. New sends enter the
+ # front of each descending result, so resuming under a later `endDate` would shift the saved page.
+ end_date: Optional[str] = None
def base_url(data_center: str) -> str:
@@ -58,6 +76,129 @@ def _auth_config(auth_token: str) -> AuthConfig:
return {"type": "bearer", "token": auth_token}
+def _client(auth_token: str, data_center: str) -> RESTClient:
+ return RESTClient(
+ base_url=base_url(data_center),
+ headers={"Accept": "application/json"},
+ auth=BearerTokenAuth(token=auth_token),
+ paginator=PageNumberPaginator(base_page=FIRST_PAGE, page_param="page"),
+ allowed_hosts=[],
+ allow_redirects=False,
+ )
+
+
+def _distribution_logs_start_date(db_incremental_field_last_value: Optional[Any]) -> date:
+ if db_incremental_field_last_value is None:
+ return DISTRIBUTION_LOGS_EARLIEST_DATE
+ watermark = parse_datetime_value(db_incremental_field_last_value)
+ if watermark is None:
+ raise ValueError("The Zonka Feedback distribution log timestamp is invalid. Reset the table sync.")
+ # `startDate` is a calendar date in an undocumented time zone, so step back one day to keep
+ # every send at or after the watermark; merge dedupes the overlap on the primary key.
+ return watermark.date() - timedelta(days=1)
+
+
+def _distribution_logs(
+ client: RESTClient,
+ manager: ResumableSourceManager[ZonkaFeedbackResumeConfig],
+ start_date: date,
+ end_date: date,
+) -> Iterator[list[dict[str, Any]]]:
+ survey_ids: set[str] = set()
+ for surveys in client.paginate(
+ path="/surveys", params={"page_size": PAGE_SIZE}, data_selector="result", data_selector_required=True
+ ):
+ manager.safe_point()
+ survey_ids.update(str(survey["id"]) for survey in surveys if survey.get("id"))
+
+ # A fixed order lets a resumed attempt skip the survey and channel pairs that an earlier attempt finished.
+ pairs = [(survey_id, channel) for survey_id in sorted(survey_ids) for channel in DISTRIBUTION_LOG_CHANNELS]
+ start_index = 0
+ first_page = FIRST_PAGE
+ resume = manager.load_state() if manager.can_resume() else None
+ if resume is not None and resume.survey_id is not None and resume.channel in DISTRIBUTION_LOG_CHANNELS:
+ resume_key = (resume.survey_id, DISTRIBUTION_LOG_CHANNELS.index(resume.channel))
+ # A survey deleted since the earlier attempt resumes at the next pair in the order.
+ start_index = next(
+ (
+ index
+ for index, (survey_id, channel) in enumerate(pairs)
+ if (survey_id, DISTRIBUTION_LOG_CHANNELS.index(channel)) >= resume_key
+ ),
+ len(pairs),
+ )
+ if start_index < len(pairs) and pairs[start_index] == (resume.survey_id, resume.channel):
+ first_page = resume.next_page
+ if resume.end_date:
+ end_date = date.fromisoformat(resume.end_date)
+
+ def checkpoint(page: int, survey_id: str, channel: str) -> None:
+ manager.save_state(
+ ZonkaFeedbackResumeConfig(
+ next_page=page, survey_id=survey_id, channel=channel, end_date=end_date.isoformat()
+ )
+ )
+
+ next_page: dict[str, Optional[int]] = {}
+
+ def remember_next_page(state: Optional[dict[str, Any]], _has_next_page: bool) -> None:
+ next_page["page"] = int(state["page"]) if state and state.get("page") is not None else None
+
+ for index in range(start_index, len(pairs)):
+ survey_id, channel = pairs[index]
+ # Save the pair before reading it, so a run of pairs with no rows still makes durable progress.
+ checkpoint(first_page, survey_id, channel)
+ manager.safe_point()
+ for rows in client.paginate(
+ path="/distribution-logs",
+ params={
+ "surveyId": survey_id,
+ "channel": channel,
+ "startDate": start_date.isoformat(),
+ "endDate": end_date.isoformat(),
+ "page_size": PAGE_SIZE,
+ },
+ data_selector="result",
+ data_selector_required=True,
+ initial_paginator_state={"page": first_page},
+ page_state_hook=remember_next_page,
+ ):
+ if not rows:
+ manager.safe_point()
+ continue
+ page = next_page.get("page")
+ if page is not None:
+ checkpoint(page, survey_id, channel)
+ # The request already names the survey and channel; fill them in so the key is never null.
+ yield [{"surveyId": survey_id, "channel": channel, **row} for row in rows]
+ first_page = FIRST_PAGE
+
+
+def _distribution_logs_response(
+ auth_token: str,
+ data_center: str,
+ config: ZonkaFeedbackEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[ZonkaFeedbackResumeConfig],
+ db_incremental_field_last_value: Optional[Any],
+) -> SourceResponse:
+ client = _client(auth_token, data_center)
+ start_date = _distribution_logs_start_date(db_incremental_field_last_value)
+ end_date = datetime.now(UTC).date()
+ return SourceResponse(
+ name=config.name,
+ items=lambda: _distribution_logs(client, resumable_source_manager, start_date, end_date),
+ primary_keys=config.primary_keys,
+ # Each survey and channel returns its sends newest first, and the walk goes survey by survey.
+ sort_mode="desc",
+ on_complete=resumable_source_manager.clear_state,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
def zonka_feedback_source(
auth_token: str,
data_center: str,
@@ -69,6 +210,11 @@ def zonka_feedback_source(
) -> SourceResponse:
config = ZONKA_FEEDBACK_ENDPOINTS[endpoint]
+ if endpoint == "distribution_logs":
+ return _distribution_logs_response(
+ auth_token, data_center, config, resumable_source_manager, db_incremental_field_last_value
+ )
+
rest_config: RESTAPIConfig = {
"client": {
"base_url": base_url(data_center),
@@ -76,7 +222,9 @@ def zonka_feedback_source(
"auth": _auth_config(auth_token),
# There is no `has_more` flag and the server may cap the page size below what we request,
# so short pages are not a reliable stop signal — terminate on the first empty page.
- "paginator": PageNumberPaginator(base_page=FIRST_PAGE, page_param="page"),
+ "paginator": PageNumberPaginator(base_page=FIRST_PAGE, page_param="page")
+ if config.paginated
+ else SinglePagePaginator(),
# Pin the credentialed request to the validated Zonka Feedback host and reject any 3xx so
# a compromised or misconfigured endpoint can't retarget the bearer token at another origin.
"allowed_hosts": [],