: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 tawk_to import source (#71207)
Tom Owersd358981d20a3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 4ceb92bf1a50..ca1bc1a9bcd8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -495,6 +495,7 @@ the row lists both.| taboola | HTTP | requests | ✅ || tailscale | HTTP | requests | ✅ || tavus | HTTP | requests | ✅ |+| tawk_to | HTTP | requests | ✅ || teamcity | HTTP | requests | ✅ || teamtailor | HTTP | requests | ✅ || teamwork | HTTP | requests | ✅ |@@ -941,7 +942,6 @@ doesn't conflict with concurrent PRs.- swonkie- synthesia- systeme-- tawk_to- teachable- telli- tempodiff --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 10cb30471925..2f40e653aba5 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@@ -4302,7 +4302,8 @@ class TavusSourceConfig(config.Config):@config.configclass TawkToSourceConfig(config.Config):- pass+ api_key: str+ property_id: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tawk_to/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tawk_to/canonical_descriptions.pynew file mode 100644index 000000000000..fd53404281ac--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tawk_to/canonical_descriptions.py@@ -0,0 +1,42 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# tawk.to's full API reference is only provided after REST API access approval, so column+# coverage is limited to fields verified from public sources; everything else falls back to+# LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "properties": {+ "description": "A tawk.to property (site) on the account, the container for widgets, chats, tickets, and members.",+ "docs_url": "https://help.tawk.to/article/rest-api",+ "columns": {+ "propertyId": "Unique identifier of the property.",+ "name": "Display name of the property.",+ },+ },+ "chats": {+ "description": "A live-chat conversation on a property, including its message transcript.",+ "docs_url": "https://help.tawk.to/article/rest-api",+ "columns": {+ "id": "Unique identifier of the chat.",+ "propertyId": "Identifier of the property the chat belongs to.",+ "createdOn": "Timestamp when the chat was created.",+ "messages": "Ordered message transcript of the chat, including sender and message type.",+ },+ },+ "tickets": {+ "description": "A support ticket raised on a property, created from missed chats or the ticket form.",+ "docs_url": "https://help.tawk.to/article/rest-api",+ "columns": {+ "id": "Unique identifier of the ticket.",+ "propertyId": "Identifier of the property the ticket belongs to.",+ },+ },+ "members": {+ "description": "An agent who is a member of a property, with their role and status.",+ "docs_url": "https://help.tawk.to/article/rest-api",+ "columns": {+ "propertyId": "Identifier of the property the member belongs to.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tawk_to/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tawk_to/settings.pynew file mode 100644index 000000000000..0acabe6550ee--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tawk_to/settings.py@@ -0,0 +1,70 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField+++@dataclass+class TawkToEndpointConfig:+ name: str+ # RPC-style method name appended to the base URL (e.g. "chat.list"). Every tawk.to API+ # call is a POST with a JSON body — there are no GET/PUT/DELETE verbs.+ method: str+ # Whether the endpoint requires a `propertyId` in the request body. Property-scoped+ # endpoints fan out over every property on the account (or the single configured one).+ scoped_to_property: bool+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation-time field used for datetime partitioning. Only set where the field is+ # verified to exist on the response objects.+ partition_key: Optional[str] = None+ # Whether the endpoint's list responses are paginated with `size`/`offset` body params.+ paginated: bool = True+ should_sync_default: bool = True+++# tawk.to's full API reference is gated behind an access-approval process, so the endpoint+# behavior below is assembled from the public help-center summary, community-reported request+# bodies, and live probes of the RPC paths (401 vs 404). `chat.list` is confirmed to accept+# `size`/`offset` pagination with `{ok, total, data}` responses; `ticket.list` is assumed to+# paginate the same way (a repeated-page guard in tawk_to.py protects against the assumption+# being wrong). List endpoints also accept `startDate`/`endDate` filters, but community reports+# of those filters silently returning empty result sets mean we can't trust them for+# incremental sync — every endpoint ships full-refresh only until the filters are verified+# against a live account.+TAWK_TO_ENDPOINTS: dict[str, TawkToEndpointConfig] = {+ "properties": TawkToEndpointConfig(+ name="properties",+ method="property.list",+ scoped_to_property=False,+ primary_keys=["propertyId"],+ paginated=False,+ ),+ "chats": TawkToEndpointConfig(+ name="chats",+ method="chat.list",+ scoped_to_property=True,+ primary_keys=["id"],+ partition_key="createdOn",+ ),+ "tickets": TawkToEndpointConfig(+ name="tickets",+ method="ticket.list",+ scoped_to_property=True,+ primary_keys=["id"],+ ),+ "members": TawkToEndpointConfig(+ name="members",+ method="members.list",+ scoped_to_property=True,+ # Member ids can't be verified without an approved API key; the composite key is a+ # best guess. Harmless while the endpoint is full-refresh only (no merge happens).+ primary_keys=["propertyId", "id"],+ paginated=False,+ ),+}++ENDPOINTS = tuple(TAWK_TO_ENDPOINTS.keys())++# No endpoint advertises incremental sync: the API's startDate/endDate filters are+# community-reported to be unreliable and can't be curl-verified while API access is gated.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tawk_to/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tawk_to/source.pyindex c27d9436a2a7..58549d50d710 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tawk_to/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tawk_to/source.py@@ -1,30 +1,143 @@-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.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 TawkToSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.tawk_to.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ TAWK_TO_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.tawk_to.tawk_to import (+ TawkToResumeConfig,+ tawk_to_source,+ validate_credentials as validate_tawk_to_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class TawkToSource(SimpleSource[TawkToSourceConfig]):+class TawkToSource(ResumableSource[TawkToSourceConfig, TawkToResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.TAWKTO+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.tawk.to": "Your tawk.to API key is invalid or has been revoked. Generate a new REST API key in your tawk.to profile, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.tawk.to": "Your tawk.to API key does not have the required permissions for this data. Check the key's scopes, then reconnect.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.TAWK_TO,category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,label="tawk.to",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["tawkto", "live chat"],+ caption="""Enter your tawk.to REST API key to pull your chats, tickets, properties, and property members into the PostHog Data warehouse.++tawk.to's REST API is available by request: submit the [REST API Access Request Form](https://help.tawk.to/article/rest-api), then generate an API key under **Edit Profile → REST API Keys**. The key needs read access to properties, chat history, tickets, and members.""",iconPath="/static/services/tawk_to.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/tawk-to",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="property_id",+ label="Property ID",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="Leave blank to sync all properties",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.tawk_to.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: TawkToSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=TAWK_TO_ENDPOINTS[endpoint].should_sync_default,+ )+ 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: TawkToSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_tawk_to_credentials(config.api_key):+ return True, None++ return False, "Invalid tawk.to API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TawkToResumeConfig]:+ return ResumableSourceManager[TawkToResumeConfig](inputs, TawkToResumeConfig)++ def source_for_pipeline(+ self,+ config: TawkToSourceConfig,+ resumable_source_manager: ResumableSourceManager[TawkToResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ property_id = (config.property_id or "").strip() or None+ return tawk_to_source(+ api_key=config.api_key,+ property_id=property_id,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tawk_to/tawk_to.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tawk_to/tawk_to.pynew file mode 100644index 000000000000..3771623ea703--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tawk_to/tawk_to.py@@ -0,0 +1,235 @@+import dataclasses+from collections.abc import Iterator+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.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.tawk_to.settings import (+ TAWK_TO_ENDPOINTS,+ TawkToEndpointConfig,+)++TAWK_TO_BASE_URL = "https://api.tawk.to/v1"+# Community-verified working page size for chat.list; the API's maximum is undocumented.+PAGE_SIZE = 50+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+++class TawkToRetryableError(Exception):+ pass+++class TawkToApiError(Exception):+ """The API answered 2xx but with `{"ok": false, ...}` in the body."""+++class TawkToResumeConfig:+ # Row offset within the property currently being paged through.+ offset: int = 0+ # The property currently being processed — a stable ID bookmark (not a positional index),+ # so properties added/removed between a crash and the retry can't resume us into the wrong+ # property. None for the account-level `properties` endpoint.+ property_id: str | None = None+++def _post(+ session: requests.Session,+ api_key: str,+ method: str,+ body: dict[str, Any],+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ @retry(+ retry=retry_if_exception_type((TawkToRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+ )+ def _do_post() -> dict[str, Any]:+ url = f"{TAWK_TO_BASE_URL}/{method}"+ # tawk.to is RPC-over-POST: the API key rides HTTP Basic auth as the username with an+ # empty password, and every parameter goes in the JSON body.+ response = session.post(+ url,+ json=body,+ auth=(api_key, ""),+ headers={"Accept": "application/json"},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ # Documented 429 error code is `rate_limited`; reset headers aren't documented, so+ # exponential backoff is the fallback.+ if response.status_code == 429 or response.status_code >= 500:+ raise TawkToRetryableError(f"tawk.to API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"tawk.to API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ data = response.json()+ if data.get("ok") is False:+ raise TawkToApiError(+ f"tawk.to API returned an error for {method}: error={data.get('error')}, message={data.get('message')}"+ )+ return data++ return _do_post()+++def validate_credentials(api_key: str) -> bool:+ """Confirm the API key is valid. `property.list` with an empty body is the cheapest+ authenticated probe (an invalid key gets `{"ok": false, "error": "auth_error"}` with 401)."""+ try:+ response = make_tracked_session(redact_values=(api_key,), capture=False).post(+ f"{TAWK_TO_BASE_URL}/property.list",+ json={},+ auth=(api_key, ""),+ headers={"Accept": "application/json"},+ timeout=10,+ )+ return response.status_code == 200 and response.json().get("ok") is True+ except Exception:+ return False+++def _list_property_ids(session: requests.Session, api_key: str, logger: FilteringBoundLogger) -> list[str]:+ data = _post(session, api_key, "property.list", {}, logger)+ return [item["propertyId"] for item in data.get("data") or [] if item.get("propertyId")]+++def _paged_property_rows(+ session: requests.Session,+ api_key: str,+ config: TawkToEndpointConfig,+ property_id: str,+ start_offset: int,+ resumable_source_manager: ResumableSourceManager[TawkToResumeConfig],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ offset = start_offset+ prev_items: list[dict[str, Any]] | None = None++ while True:+ data = _post(+ session,+ api_key,+ config.method,+ {"propertyId": property_id, "size": PAGE_SIZE, "offset": offset},+ logger,+ )+ items = data.get("data") or []+ if not items:+ break++ # `offset` pagination is confirmed for chat.list but assumed for other list methods.+ # If the server ignores it and replays the same page, stop instead of looping/duplicating.+ if items == prev_items:+ logger.warning(+ f"tawk.to: {config.method} returned an identical page at offset={offset} for "+ f"property {property_id}; the API may not support offset pagination — stopping early"+ )+ break++ for item in items:+ item.setdefault("propertyId", property_id)+ yield items++ offset += len(items)+ total = data.get("total")+ if len(items) < PAGE_SIZE or (isinstance(total, int) and offset >= total):+ break++ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the last+ # page rather than skipping it.+ resumable_source_manager.save_state(TawkToResumeConfig(offset=offset, property_id=property_id))+ prev_items = items+++def get_rows(+ api_key: str,+ property_id: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TawkToResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = TAWK_TO_ENDPOINTS[endpoint]+ # One session reused across every request so urllib3 keeps the connection alive instead of+ # re-handshaking per call. `redact_values` masks the key in tracked logs/samples; `capture=False`+ # keeps response bodies out of HTTP sample capture — chat and ticket payloads carry customer+ # conversation text the name-based scrubbers can't recognise.+ session = make_tracked_session(redact_values=(api_key,), capture=False)++ if not config.scoped_to_property:+ data = _post(session, api_key, config.method, {}, logger)+ items = data.get("data") or []+ if items:+ yield items+ return++ property_ids = [property_id] if property_id else _list_property_ids(session, api_key, logger)++ # Resolve the saved property-ID bookmark to the slice of properties still to process. If the+ # bookmarked property no longer exists (removed between runs), start over from the first one.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = property_ids+ resume_offset = 0+ if resume is not None and resume.property_id is not None and resume.property_id in property_ids:+ remaining = property_ids[property_ids.index(resume.property_id) :]+ resume_offset = resume.offset+ logger.debug(f"tawk.to: resuming {endpoint} from property {resume.property_id}, offset={resume_offset}")++ for index, pid in enumerate(remaining):+ if config.paginated:+ yield from _paged_property_rows(+ session, api_key, config, pid, resume_offset, resumable_source_manager, logger+ )+ else:+ data = _post(session, api_key, config.method, {"propertyId": pid}, logger)+ items = data.get("data") or []+ for item in items:+ item.setdefault("propertyId", pid)+ if items:+ yield items+ resume_offset = 0 # only the resumed-into property starts at the saved offset++ # Advance the bookmark to the next property so a crash between properties resumes there.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(TawkToResumeConfig(offset=0, property_id=remaining[index + 1]))+++def tawk_to_source(+ api_key: str,+ property_id: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TawkToResumeConfig],+) -> SourceResponse:+ config = TAWK_TO_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ property_id=property_id,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ # List order is unverified (the ticket sort enum suggests newest-first defaults). Inert+ # while every endpoint is full-refresh only, but declared desc so a future incremental+ # rollout doesn't inherit a corrupt-watermark default.+ sort_mode="desc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tawk_to/tests/test_tawk_to.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tawk_to/tests/test_tawk_to.pynew file mode 100644index 000000000000..edd82bbab692--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tawk_to/tests/test_tawk_to.py@@ -0,0 +1,228 @@+from typing import Any++import pytest+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.tawk_to.settings import (+ ENDPOINTS,+ TAWK_TO_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.tawk_to.tawk_to import (+ PAGE_SIZE,+ TawkToApiError,+ TawkToResumeConfig,+ get_rows,+ tawk_to_source,+ validate_credentials,+)++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.tawk_to.tawk_to"+++def _make_manager(resume_state: TawkToResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _response(body: dict[str, Any], status_code: int = 200) -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body+ return response+++def _page(items: list[dict[str, Any]], total: int) -> dict[str, Any]:+ return {"ok": True, "total": total, "data": items}+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, body, expected",+ [+ (200, {"ok": True, "data": []}, True),+ (200, {"ok": False, "error": "auth_error"}, False),+ (401, {"ok": False, "error": "auth_error", "message": "invalid_auth"}, False),+ (500, {}, False),+ ],+ )+ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_status_and_body_mapping(self, mock_session, status_code, body, expected):+ mock_session.return_value.post.return_value = _response(body, status_code)++ assert validate_credentials("key") is expected++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_swallows_exceptions(self, mock_session):+ mock_session.return_value.post.side_effect = Exception("boom")++ assert validate_credentials("key") is False+++class TestGetRows:+ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_paginates_with_advancing_offset(self, mock_session):+ first_page = [{"id": str(n)} for n in range(PAGE_SIZE)]+ second_page = [{"id": "last"}]+ mock_session.return_value.post.side_effect = [+ _response(_page(first_page, total=PAGE_SIZE + 1)),+ _response(_page(second_page, total=PAGE_SIZE + 1)),+ ]++ manager = _make_manager()+ batches = list(get_rows("key", "prop-1", "chats", mock.MagicMock(), manager))++ bodies = [call.kwargs["json"] for call in mock_session.return_value.post.call_args_list]+ assert bodies[0] == {"propertyId": "prop-1", "size": PAGE_SIZE, "offset": 0}+ assert bodies[1] == {"propertyId": "prop-1", "size": PAGE_SIZE, "offset": PAGE_SIZE}+ assert sum(len(batch) for batch in batches) == PAGE_SIZE + 1+ # State is saved only while more pages remain, after the batch is yielded.+ manager.save_state.assert_called_once()+ saved = manager.save_state.call_args.args[0]+ assert saved.offset == PAGE_SIZE+ assert saved.property_id == "prop-1"++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_short_page_terminates_without_saving_state(self, mock_session):+ mock_session.return_value.post.return_value = _response(_page([{"id": "1"}], total=1))++ manager = _make_manager()+ batches = list(get_rows("key", "prop-1", "chats", mock.MagicMock(), manager))++ assert mock_session.return_value.post.call_count == 1+ assert [item["id"] for batch in batches for item in batch] == ["1"]+ manager.save_state.assert_not_called()++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_repeated_page_stops_instead_of_looping(self, mock_session):+ page = [{"id": str(n)} for n in range(PAGE_SIZE)]+ mock_session.return_value.post.side_effect = [+ _response(_page(page, total=10_000)),+ _response(_page(page, total=10_000)),+ ]++ logger = mock.MagicMock()+ batches = list(get_rows("key", "prop-1", "chats", logger, _make_manager()))++ assert mock_session.return_value.post.call_count == 2+ assert sum(len(batch) for batch in batches) == PAGE_SIZE+ logger.warning.assert_called_once()++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_rows_carry_property_id(self, mock_session):+ mock_session.return_value.post.return_value = _response(+ _page([{"id": "1"}, {"id": "2", "propertyId": "original"}], total=2)+ )++ batches = list(get_rows("key", "prop-1", "chats", mock.MagicMock(), _make_manager()))++ rows = [item for batch in batches for item in batch]+ assert rows[0]["propertyId"] == "prop-1"+ # An API-provided propertyId is never overwritten.+ assert rows[1]["propertyId"] == "original"++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_fans_out_over_all_properties_when_none_configured(self, mock_session):+ mock_session.return_value.post.side_effect = [+ _response({"ok": True, "data": [{"propertyId": "prop-1"}, {"propertyId": "prop-2"}]}),+ _response(_page([{"id": "a"}], total=1)),+ _response(_page([{"id": "b"}], total=1)),+ ]++ manager = _make_manager()+ batches = list(get_rows("key", None, "chats", mock.MagicMock(), manager))++ bodies = [call.kwargs["json"] for call in mock_session.return_value.post.call_args_list]+ assert bodies[0] == {}+ assert bodies[1]["propertyId"] == "prop-1"+ assert bodies[2]["propertyId"] == "prop-2"+ assert [item["id"] for batch in batches for item in batch] == ["a", "b"]+ # The bookmark advances to the next property so a crash in between resumes there.+ saved = manager.save_state.call_args.args[0]+ assert saved.property_id == "prop-2"+ assert saved.offset == 0++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_resumes_from_saved_property_and_offset(self, mock_session):+ mock_session.return_value.post.side_effect = [+ _response({"ok": True, "data": [{"propertyId": "prop-1"}, {"propertyId": "prop-2"}]}),+ _response(_page([{"id": "b"}], total=100)),+ ]++ manager = _make_manager(TawkToResumeConfig(offset=50, property_id="prop-2"))+ list(get_rows("key", None, "chats", mock.MagicMock(), manager))++ bodies = [call.kwargs["json"] for call in mock_session.return_value.post.call_args_list]+ # prop-1 is skipped entirely; prop-2 starts at the saved offset.+ assert len(bodies) == 2+ assert bodies[1] == {"propertyId": "prop-2", "size": PAGE_SIZE, "offset": 50}++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_missing_bookmarked_property_starts_over(self, mock_session):+ mock_session.return_value.post.side_effect = [+ _response({"ok": True, "data": [{"propertyId": "prop-1"}]}),+ _response(_page([{"id": "a"}], total=1)),+ ]++ manager = _make_manager(TawkToResumeConfig(offset=50, property_id="gone"))+ list(get_rows("key", None, "chats", mock.MagicMock(), manager))++ bodies = [call.kwargs["json"] for call in mock_session.return_value.post.call_args_list]+ assert bodies[1] == {"propertyId": "prop-1", "size": PAGE_SIZE, "offset": 0}++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_properties_endpoint_is_a_single_unscoped_call(self, mock_session):+ mock_session.return_value.post.return_value = _response(+ {"ok": True, "data": [{"propertyId": "prop-1", "name": "Site"}]}+ )++ manager = _make_manager()+ batches = list(get_rows("key", None, "properties", mock.MagicMock(), manager))++ assert mock_session.return_value.post.call_count == 1+ assert mock_session.return_value.post.call_args.kwargs["json"] == {}+ assert batches == [[{"propertyId": "prop-1", "name": "Site"}]]+ manager.save_state.assert_not_called()++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_unpaginated_scoped_endpoint_sends_only_property_id(self, mock_session):+ mock_session.return_value.post.return_value = _response({"ok": True, "data": [{"role": "admin"}]})++ batches = list(get_rows("key", "prop-1", "members", mock.MagicMock(), _make_manager()))++ assert mock_session.return_value.post.call_count == 1+ assert mock_session.return_value.post.call_args.kwargs["json"] == {"propertyId": "prop-1"}+ assert batches == [[{"role": "admin", "propertyId": "prop-1"}]]++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_ok_false_body_raises(self, mock_session):+ mock_session.return_value.post.return_value = _response(+ {"ok": False, "error": "validation_error", "message": "body"}+ )++ with pytest.raises(TawkToApiError, match="validation_error"):+ list(get_rows("key", "prop-1", "chats", mock.MagicMock(), _make_manager()))+++class TestTawkToSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = TAWK_TO_ENDPOINTS[endpoint]+ response = tawk_to_source("key", None, endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ assert response.sort_mode == "desc"+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ @pytest.mark.parametrize("config", list(TAWK_TO_ENDPOINTS.values()))+ def test_partition_keys_are_stable_creation_fields(self, config):+ if config.partition_key:+ assert config.partition_key == "createdOn"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tawk_to/tests/test_tawk_to_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tawk_to/tests/test_tawk_to_source.pynew file mode 100644index 000000000000..d581a22ae375--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tawk_to/tests/test_tawk_to_source.py@@ -0,0 +1,134 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++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 TawkToSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.tawk_to.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.tawk_to.source import TawkToSource+from products.warehouse_sources.backend.temporal.data_imports.sources.tawk_to.tawk_to import TawkToResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.tawk_to.source"+++class TestTawkToSource:+ def setup_method(self):+ self.source = TawkToSource()+ self.team_id = 123+ self.config = TawkToSourceConfig(api_key="api-key")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.TAWKTO++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "TawkTo"+ assert config.label == "tawk.to"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/tawk_to.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key", "property_id"]++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ def test_property_id_field_is_optional(self):+ config = self.source.get_source_config+ property_field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "property_id"+ )+ assert property_field.required is False+ assert property_field.secret is False++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.tawk.to/v1/chat.list",+ "403 Client Error: Forbidden for url: https://api.tawk.to/v1/ticket.list",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",+ "500 Server Error for url: https://api.tawk.to/v1/chat.list",+ ],+ )+ def test_non_retryable_errors_does_not_match_unrelated(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_are_full_refresh_only(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ # tawk.to's date filters are unverified (API reference is access-gated), so no endpoint+ # may advertise incremental sync until they're confirmed against a live account.+ assert all(not schema.supports_incremental and not schema.supports_append for schema in schemas)+ assert all(schema.incremental_fields == [] for schema in schemas)++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["chats"])+ assert [schema.name for schema in schemas] == ["chats"]++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ (True, True, None),+ (False, False, "Invalid tawk.to API key"),+ ],+ )+ @mock.patch(f"{MODULE}.validate_tawk_to_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ 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 == expected_message+ mock_validate.assert_called_once_with(self.config.api_key)++ def test_get_resumable_source_manager_binds_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is TawkToResumeConfig++ @mock.patch(f"{MODULE}.tawk_to_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_tawk_to_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "chats"+ manager = mock.MagicMock()+ config = TawkToSourceConfig(api_key="api-key", property_id="prop-1")++ self.source.source_for_pipeline(config, manager, inputs)++ kwargs = mock_tawk_to_source.call_args.kwargs+ assert kwargs["api_key"] == "api-key"+ assert kwargs["property_id"] == "prop-1"+ assert kwargs["endpoint"] == "chats"+ assert kwargs["resumable_source_manager"] is manager++ @pytest.mark.parametrize("raw_property_id", [None, "", " "])+ @mock.patch(f"{MODULE}.tawk_to_source")+ def test_source_for_pipeline_normalizes_blank_property_id(self, mock_tawk_to_source, raw_property_id):+ inputs = mock.MagicMock()+ inputs.schema_name = "chats"+ config = TawkToSourceConfig(api_key="api-key", property_id=raw_property_id)++ self.source.source_for_pipeline(config, mock.MagicMock(), inputs)++ assert mock_tawk_to_source.call_args.kwargs["property_id"] is None