: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 trustpilot source (#79793)
jake sciottoca1f4bf80a3c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 910b80002616..4ed9a263a74a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -638,6 +638,7 @@ the row lists both.| transistor | HTTP | requests | ✅ || travis_ci | HTTP | requests | ✅ || trello | HTTP | requests | ✅ |+| trustpilot | HTTP | requests + `rest_source.RESTClient` | ✅ || tremendous | HTTP | requests | ✅ || trigger_dev | HTTP | requests | ✅ || trunk_io | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -1377,7 +1378,6 @@ doesn't conflict with concurrent PRs.- tradable_bits- tremendous- triple_whale-- trustpilot- trustradius- turso- twentydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/trustpilot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/trustpilot.pyindex e15aef7376e9..89434e25aa2a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/trustpilot.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/trustpilot.py@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass TrustPilotSourceConfig(config.Config):- pass+ api_key: str+ api_secret: str+ business_unit: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trustpilot/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trustpilot/canonical_descriptions.pynew file mode 100644index 000000000000..7c87847eeb56--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trustpilot/canonical_descriptions.py@@ -0,0 +1,79 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "business_unit": {+ "description": "The Trustpilot profile of the connected business: its identifying domain, review counts and current TrustScore. One row, replaced on every sync.",+ "docs_url": "https://developers.trustpilot.com/business-units-api-(public)/",+ "columns": {+ "id": "Unique identifier of the business unit.",+ "displayName": "Display name of the business unit shown on its Trustpilot profile.",+ "name": "Names of the business unit: the identifying domain name and any referring names.",+ "websiteUrl": "URL of the business unit's website.",+ "country": "Country code of the business unit.",+ "numberOfReviews": "Review counts: total, number used for TrustScore calculation, and per-star breakdown.",+ "status": "Status of the business unit, for example active.",+ "score": "Current rating of the business unit: TrustScore (0 to 5) and star rating.",+ "badFit": "Whether Trustpilot considers reviews a bad fit for this kind of business.",+ "links": "Related Trustpilot API resource links.",+ },+ },+ "service_reviews": {+ "description": "Service reviews left for the business unit, including the reviewer, star rating, review text and any company reply. Synced from the private reviews endpoint, so rows include customer email and order reference.",+ "docs_url": "https://developers.trustpilot.com/business-units-api/",+ "columns": {+ "id": "Unique identifier of the review.",+ "consumer": "The reviewer: id, display name, display location and number of reviews written.",+ "businessUnit": "The business unit the review was written for.",+ "stars": "Star rating given by the reviewer, 1 to 5.",+ "title": "Title of the review.",+ "text": "Body text of the review.",+ "language": "Language code of the review.",+ "createdAt": "When the review was created.",+ "updatedAt": "When the review was last updated, if it was edited.",+ "experiencedAt": "When the reviewer says the experience happened.",+ "numberOfLikes": "Number of likes the review has received.",+ "isVerified": "Whether the review was collected through a verified invitation.",+ "status": "Status of the review, for example active.",+ "companyReply": "The company's reply to the review, with its text and timestamps.",+ "referenceId": "Order or customer reference attached to the review invitation.",+ "referralEmail": "Email address the review invitation was sent to.",+ "source": "Where the review came from, for example an invitation or organic.",+ "tags": "Tags the business has applied to the review, as group and value pairs.",+ "findReviewer": "Find-reviewer requests for the review and their consumer responses.",+ "location": "Business location the review is attached to, if any.",+ "countsTowardsTrustScore": "Whether the review counts towards the business unit's TrustScore.",+ "countsTowardsLocationTrustScore": "Whether the review counts towards the location's TrustScore.",+ "reportData": "Details of any report raised against the review.",+ "complianceLabels": "Compliance labels applied to the review.",+ "invitation": "The invitation the review was collected through, if any.",+ "businessUnitHistory": "Business units the review has previously belonged to.",+ "reviewVerificationLevel": "How strongly the review's authenticity has been verified.",+ "links": "Related Trustpilot API resource links.",+ },+ },+ "product_reviews": {+ "description": "Product reviews left for the business unit's products. Synced from the private product reviews endpoint, so rows include the reviewed product, the consumer's email and the review state.",+ "docs_url": "https://developers.trustpilot.com/product-reviews-api/",+ "columns": {+ "id": "Unique identifier of the product review.",+ "createdAt": "When the product review was created.",+ "stars": "Star rating given by the reviewer, 1 to 5.",+ "content": "Body text of the product review.",+ "consumer": "The reviewer: id, name and email address.",+ "product": "The reviewed product: name, SKU, URL, images, GTIN, MPN and brand.",+ "businessUnitId": "Identifier of the business unit the review belongs to.",+ "language": "Language code of the review.",+ "locale": "Locale the review was collected in.",+ "state": "State of the review, for example published or unpublished.",+ "referenceId": "Order or customer reference attached to the review invitation.",+ "redirectUri": "URI the reviewer was redirected to after leaving the review.",+ "conversationId": "Identifier of the conversation attached to the review, if the company replied.",+ "hasModerationHistory": "Whether the review has been through moderation.",+ "attributeRatings": "Per-attribute ratings the reviewer gave, for example quality or value.",+ "attachments": "Images or videos the reviewer attached, with their processed files.",+ "links": "Related Trustpilot API resource links.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trustpilot/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trustpilot/settings.pynew file mode 100644index 000000000000..be3bf278a604--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trustpilot/settings.py@@ -0,0 +1,78 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++BASE_URL = "https://api.trustpilot.com/v1"+TOKEN_URL = "https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken"++# Trustpilot's review list endpoints accept up to 100 rows per page (default 20); request the max+# to minimise round trips.+PER_PAGE = 100++# The page-numbered review endpoints are documented as "limited to 100,000 records" per query, so+# with PER_PAGE=100 there is nothing past page 1,000. Incremental syncs keep each query window+# small; only the initial backfill of a very large account can reach this cap.+MAX_PAGES = 1000+++@dataclass(frozen=True)+class TrustpilotEndpointConfig:+ name: str+ # Path under /v1 with a {business_unit_id} placeholder.+ path: str+ # Key wrapping the row list in the JSON response; None means the whole body is a single row.+ response_key: str | None+ # Private endpoints need a client-credentials OAuth bearer; public ones take the `apikey` header.+ requires_oauth: bool+ paginated: bool = True+ # Explicit stable sort so page boundaries can't skip or duplicate rows as new reviews arrive+ # mid-sync. Only the service reviews endpoint documents `orderBy`.+ order_by: str | None = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation-time field to partition by.+ partition_key: str | None = None+++TRUSTPILOT_ENDPOINTS: dict[str, TrustpilotEndpointConfig] = {+ "business_unit": TrustpilotEndpointConfig(+ name="business_unit",+ path="/business-units/{business_unit_id}",+ response_key=None,+ requires_oauth=False,+ paginated=False,+ ),+ "service_reviews": TrustpilotEndpointConfig(+ name="service_reviews",+ path="/private/business-units/{business_unit_id}/reviews",+ response_key="reviews",+ requires_oauth=True,+ order_by="createdat.asc",+ # `startDateTime` is the endpoint's only server-side time filter and it keys off the+ # review's creation time, so `createdAt` is the one honest incremental cursor. Edits to an+ # already-synced review only land once a full refresh re-reads it.+ incremental_fields=[+ {+ "label": "createdAt",+ "type": IncrementalFieldType.DateTime,+ "field": "createdAt",+ "field_type": IncrementalFieldType.DateTime,+ }+ ],+ partition_key="createdAt",+ ),+ "product_reviews": TrustpilotEndpointConfig(+ name="product_reviews",+ path="/private/product-reviews/business-units/{business_unit_id}/reviews",+ response_key="productReviews",+ requires_oauth=True,+ # No documented server-side time filter, so this endpoint is full refresh only.+ partition_key="createdAt",+ ),+}++ENDPOINTS = tuple(TRUSTPILOT_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in TRUSTPILOT_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trustpilot/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trustpilot/source.pyindex 598ee63b11ec..4295870eb886 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trustpilot/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trustpilot/source.py@@ -1,21 +1,52 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (+ OAUTH2_PERMANENT_ERROR_MARKER,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.trustpilot import (TrustPilotSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.trustpilot.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.trustpilot.trustpilot import (+ BUSINESS_UNIT_NOT_FOUND_ERROR,+ CREDENTIALS_REJECTED_ERROR,+ TrustpilotResumeConfig,+ trustpilot_source,+ validate_credentials as validate_trustpilot_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class TrustPilotSource(SimpleSource[TrustPilotSourceConfig]):+class TrustPilotSource(ResumableSource[TrustPilotSourceConfig, TrustpilotResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog, safe for public docs+ supported_versions = ("v1",)+ default_version = "v1"+ api_docs_url = "https://developers.trustpilot.com/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.TRUSTPILOT@@ -24,9 +55,103 @@ class TrustPilotSource(SimpleSource[TrustPilotSourceConfig]):def get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.TRUST_PILOT,- category=DataWarehouseSourceCategory.MARKETING___EMAIL,- label="TrustPilot",+ category=DataWarehouseSourceCategory.E_COMMERCE,+ label="Trustpilot",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Trustpilot API key and secret to sync your business unit, service reviews and product reviews into the PostHog data warehouse.++Create an API application in your Trustpilot Business account to get the key (client ID) and secret (client secret). See the [Trustpilot developer docs](https://developers.trustpilot.com/) for details. Set the business unit to your website domain as it appears on your Trustpilot profile, or to your business unit ID.""",iconPath="/static/services/trustpilot.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/trustpilot",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="api_secret",+ label="API secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="business_unit",+ label="Business unit domain or ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="example.com",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.trustpilot.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # The framework's OAuth2 auth stamps this marker on token failures retrying can't fix+ # (invalid_client and other non-429 4xx).+ OAUTH2_PERMANENT_ERROR_MARKER: "Trustpilot rejected the API key and secret. Check both values in your Trustpilot Business account, then update the source.",+ CREDENTIALS_REJECTED_ERROR: "Trustpilot rejected the API credentials. Check the API key and secret in your Trustpilot Business account, then update the source.",+ BUSINESS_UNIT_NOT_FOUND_ERROR: "The Trustpilot business unit was not found. Enter your domain exactly as it appears on your Trustpilot profile, or your business unit ID.",+ "401 Client Error: Unauthorized": "Your Trustpilot API credentials are invalid or have been revoked. Check them in your Trustpilot Business account, then update the source.",+ "403 Client Error: Forbidden": "Your Trustpilot API application is missing access to this data. Check that your Trustpilot plan includes API access, then try again.",+ "404 Client Error: Not Found": "The Trustpilot business unit was not found. Check the business unit domain or ID, then update the source.",+ }++ def get_schemas(+ self,+ config: TrustPilotSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: TrustPilotSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_trustpilot_credentials(config.api_key, config.api_secret, config.business_unit)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TrustpilotResumeConfig]:+ return ResumableSourceManager[TrustpilotResumeConfig](inputs, TrustpilotResumeConfig)++ def source_for_pipeline(+ self,+ config: TrustPilotSourceConfig,+ resumable_source_manager: ResumableSourceManager[TrustpilotResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return trustpilot_source(+ api_key=config.api_key,+ api_secret=config.api_secret,+ business_unit=config.business_unit,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trustpilot/tests/test_trustpilot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trustpilot/tests/test_trustpilot.pynew file mode 100644index 000000000000..5987e98e3863--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trustpilot/tests/test_trustpilot.py@@ -0,0 +1,441 @@+import json+import logging+from datetime import UTC, date, datetime, timedelta, timezone+from typing import Any++import pytest+from unittest import mock++from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.trustpilot.settings import (+ MAX_PAGES,+ PER_PAGE,+ TOKEN_URL,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.trustpilot.trustpilot import (+ TrustpilotAuthError,+ TrustpilotBusinessUnitError,+ TrustpilotPaginator,+ TrustpilotResumeConfig,+ _build_auth,+ _format_start_datetime,+ mint_access_token,+ normalize_business_unit,+ resolve_business_unit_id,+ trustpilot_source,+ validate_credentials,+)++# resolve_business_unit_id, mint_access_token and the sync client all build their tracked+# session in the trustpilot module.+TRUSTPILOT_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.trustpilot.trustpilot.make_tracked_session"+)+RESOLVE_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.trustpilot.trustpilot.resolve_business_unit_id"+)++BUSINESS_UNIT_ID = "507f191e810c19729de860ea"+++def _response(payload: Any, status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(payload).encode()+ return resp+++def _reviews_response(items: list[dict[str, Any]], key: str = "reviews") -> Response:+ return _response({key: items, "links": []})+++def _make_manager(resume_state: TrustpilotResumeConfig | 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 _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ # request.params is one dict mutated in place across pages, so snapshot a copy at send time.+ session.headers = {}+ param_snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ param_snapshots.append(dict(request.params or {}))+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return param_snapshots+++def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++def _source(manager: mock.MagicMock, endpoint: str = "service_reviews", **kwargs: Any):+ return trustpilot_source(+ api_key="key",+ api_secret="secret",+ business_unit="example.com",+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ **kwargs,+ )+++class TestNormalizeBusinessUnit:+ @parameterized.expand(+ [+ ("bare_domain", "example.com", "example.com"),+ ("https_url", "https://example.com/", "example.com"),+ ("url_with_path", "https://example.com/some/page", "example.com"),+ ("www_kept", "www.example.com", "www.example.com"),+ ("uppercase_lowered", "Example.COM", "example.com"),+ ("whitespace", " example.com ", "example.com"),+ ("review_page_url", "https://www.trustpilot.com/review/example.com", "example.com"),+ ("review_page_url_with_query", "https://trustpilot.com/review/example.com?languages=all", "example.com"),+ ("raw_business_unit_id", BUSINESS_UNIT_ID, BUSINESS_UNIT_ID),+ ]+ )+ def test_valid_values(self, _name: str, value: str, expected: str) -> None:+ assert normalize_business_unit(value) == expected++ @parameterized.expand(+ [+ ("empty", ""),+ ("space_inside", "exa mple.com"),+ ("userinfo_injection", "[email protected]"),+ ("query_injection", "example.com?apikey=x"),+ ("leading_hyphen", "-example.com"),+ ("underscore", "exa_mple.com"),+ ]+ )+ def test_invalid_values_raise(self, _name: str, value: str) -> None:+ with pytest.raises(ValueError):+ normalize_business_unit(value)+++class TestFormatStartDatetime:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14"),+ (+ "non_utc_datetime",+ datetime(2026, 3, 4, 3, 58, 14, tzinfo=timezone(timedelta(hours=1))),+ "2026-03-04T02:58:14",+ ),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00"),+ ("string_passthrough", "2026-03-04T02:58:14", "2026-03-04T02:58:14"),+ ]+ )+ def test_format(self, _name: str, value: Any, expected: str) -> None:+ result = _format_start_datetime(value)+ assert result == expected+ assert "+00:00" not in result+ assert not result.endswith("Z")+++class TestBuildAuth:+ def test_public_endpoint_uses_apikey_header(self) -> None:+ auth = _build_auth("key", "secret", requires_oauth=False)+ assert auth == {"type": "api_key", "name": "apikey", "location": "header", "api_key": "key"}++ def test_private_endpoint_uses_client_credentials_with_basic_auth(self) -> None:+ auth = _build_auth("key", "secret", requires_oauth=True)+ # client_auth_method must stay "basic": Trustpilot's token endpoint takes the key/secret+ # as HTTP Basic.+ assert auth == {+ "type": "oauth2",+ "token_url": TOKEN_URL,+ "client_id": "key",+ "client_secret": "secret",+ "grant_type": "client_credentials",+ "client_auth_method": "basic",+ }+++class TestResolveBusinessUnit:+ @mock.patch(TRUSTPILOT_SESSION_PATCH)+ def test_domain_resolves_via_find(self, MockSession) -> None:+ session = MockSession.return_value+ session.get.return_value = _response({"id": BUSINESS_UNIT_ID, "displayName": "Example"})++ assert resolve_business_unit_id("key", "example.com") == BUSINESS_UNIT_ID+ args, kwargs = session.get.call_args+ assert args[0].endswith("/business-units/find")+ assert kwargs["params"] == {"name": "example.com"}+ assert kwargs["headers"] == {"apikey": "key"}++ @mock.patch(TRUSTPILOT_SESSION_PATCH)+ def test_www_domain_falls_back_to_bare_domain(self, MockSession) -> None:+ session = MockSession.return_value+ session.get.side_effect = [+ _response({"details": "not found"}, status_code=404),+ _response({"id": BUSINESS_UNIT_ID}),+ ]++ assert resolve_business_unit_id("key", "www.example.com") == BUSINESS_UNIT_ID+ names = [call.kwargs["params"]["name"] for call in session.get.call_args_list]+ assert names == ["www.example.com", "example.com"]++ @mock.patch(TRUSTPILOT_SESSION_PATCH)+ def test_unknown_domain_raises_business_unit_error(self, MockSession) -> None:+ session = MockSession.return_value+ session.get.return_value = _response({"details": "not found"}, status_code=404)++ with pytest.raises(TrustpilotBusinessUnitError):+ resolve_business_unit_id("key", "example.com")++ @mock.patch(TRUSTPILOT_SESSION_PATCH)+ def test_lookup_response_without_id_fails_loud(self, MockSession) -> None:+ # A 200 without an id is a broken response contract; it must not read as "not found",+ # which would tell the user to fix a business unit value that is actually fine.+ session = MockSession.return_value+ session.get.return_value = _response({"displayName": "Example"})++ with pytest.raises(TrustpilotBusinessUnitError, match="unexpected"):+ resolve_business_unit_id("key", "example.com")++ @mock.patch(TRUSTPILOT_SESSION_PATCH)+ def test_rejected_api_key_raises_auth_error(self, MockSession) -> None:+ session = MockSession.return_value+ session.get.return_value = _response({"details": "unauthorized"}, status_code=401)++ with pytest.raises(TrustpilotAuthError):+ resolve_business_unit_id("key", "example.com")++ @mock.patch(TRUSTPILOT_SESSION_PATCH)+ def test_raw_id_verified_via_business_unit_endpoint(self, MockSession) -> None:+ session = MockSession.return_value+ session.get.return_value = _response({"id": BUSINESS_UNIT_ID})++ assert resolve_business_unit_id("key", BUSINESS_UNIT_ID) == BUSINESS_UNIT_ID+ args, _kwargs = session.get.call_args+ assert args[0].endswith(f"/business-units/{BUSINESS_UNIT_ID}")++ @mock.patch(TRUSTPILOT_SESSION_PATCH)+ def test_unknown_raw_id_raises_business_unit_error(self, MockSession) -> None:+ session = MockSession.return_value+ session.get.return_value = _response({"details": "not found"}, status_code=404)++ with pytest.raises(TrustpilotBusinessUnitError):+ resolve_business_unit_id("key", BUSINESS_UNIT_ID)+++class TestMintAccessToken:+ @mock.patch(TRUSTPILOT_SESSION_PATCH)+ def test_returns_token_on_success(self, MockSession) -> None:+ session = MockSession.return_value+ session.post.return_value = _response({"access_token": "tok", "expires_in": "359999"})++ assert mint_access_token("key", "secret") == "tok"+ _args, kwargs = session.post.call_args+ assert kwargs["auth"] == ("key", "secret")+ assert kwargs["data"] == {"grant_type": "client_credentials"}++ @parameterized.expand(+ [+ ("rejected", _response({"reason": "unauthorized"}, status_code=401)),+ ("no_token_in_body", _response({"unexpected": "shape"})),+ ]+ )+ @mock.patch(TRUSTPILOT_SESSION_PATCH)+ def test_failures_raise_auth_error(self, _name: str, response: Response, MockSession) -> None:+ session = MockSession.return_value+ session.post.return_value = response++ with pytest.raises(TrustpilotAuthError):+ mint_access_token("key", "secret")+++class TestValidateCredentials:+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.trustpilot.trustpilot.mint_access_token"+ )+ @mock.patch(RESOLVE_PATCH)+ def test_valid_credentials(self, mock_resolve, mock_mint) -> None:+ mock_resolve.return_value = BUSINESS_UNIT_ID+ mock_mint.return_value = "tok"++ assert validate_credentials("key", "secret", "example.com") == (True, None)++ @parameterized.expand(+ [+ ("bad_business_unit", TrustpilotBusinessUnitError("No Trustpilot business unit found for 'example.com'.")),+ ("malformed_input", ValueError("Invalid Trustpilot business unit: 'exa mple'.")),+ ("bad_key", TrustpilotAuthError("Trustpilot rejected the API key (HTTP 401).")),+ ]+ )+ @mock.patch(RESOLVE_PATCH)+ def test_resolution_failures_surface_message(self, _name: str, error: Exception, mock_resolve) -> None:+ mock_resolve.side_effect = error++ ok, message = validate_credentials("key", "secret", "example.com")+ assert ok is False+ assert str(error) in (message or "")++ @mock.patch(RESOLVE_PATCH)+ def test_transport_errors_never_raise(self, mock_resolve) -> None:+ mock_resolve.side_effect = ConnectionError("boom")++ ok, message = validate_credentials("key", "secret", "example.com")+ assert ok is False+ assert "Could not connect to Trustpilot" in (message or "")+++class TestPagination:+ @mock.patch(RESOLVE_PATCH, return_value=BUSINESS_UNIT_ID)+ @mock.patch(TRUSTPILOT_SESSION_PATCH)+ def test_pages_until_empty_page(self, MockSession, _mock_resolve) -> None:+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _reviews_response([{"id": "r1"}, {"id": "r2"}]),+ _reviews_response([{"id": "r3"}]),+ _reviews_response([]),+ ],+ )++ manager = _make_manager()+ rows = _rows(_source(manager))++ assert [r["id"] for r in rows] == ["r1", "r2", "r3"]+ assert params[0]["page"] == 1+ assert params[0]["perPage"] == PER_PAGE+ assert params[0]["orderBy"] == "createdat.asc"+ assert params[1]["page"] == 2+ assert params[2]["page"] == 3++ @mock.patch(RESOLVE_PATCH, return_value=BUSINESS_UNIT_ID)+ @mock.patch(TRUSTPILOT_SESSION_PATCH)+ def test_checkpoints_next_page_with_query_window(self, MockSession, _mock_resolve) -> None:+ session = MockSession.return_value+ _wire(session, [_reviews_response([{"id": "r1"}]), _reviews_response([])])++ manager = _make_manager()+ _rows(+ _source(+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 2, 1, tzinfo=UTC),+ )+ )++ manager.save_state.assert_called_once_with(+ TrustpilotResumeConfig(page=2, start_date_time="2026-02-01T00:00:00")+ )++ @mock.patch(RESOLVE_PATCH, return_value=BUSINESS_UNIT_ID)+ @mock.patch(TRUSTPILOT_SESSION_PATCH)+ def test_resume_reissues_saved_query_window(self, MockSession, _mock_resolve) -> None:+ # A resumed run must re-issue the interrupted run's startDateTime: the watermark advanced+ # per batch mid-run, so re-deriving it would shift the query window and page 5 would point+ # at different rows.+ session = MockSession.return_value+ params = _wire(session, [_reviews_response([{"id": "r9"}]), _reviews_response([])])++ manager = _make_manager(TrustpilotResumeConfig(page=5, start_date_time="2026-01-01T00:00:00"))+ rows = _rows(+ _source(+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 2, 1, tzinfo=UTC),+ )+ )++ assert [r["id"] for r in rows] == ["r9"]+ assert params[0]["page"] == 5+ assert params[0]["startDateTime"] == "2026-01-01T00:00:00"++ @mock.patch(RESOLVE_PATCH, return_value=BUSINESS_UNIT_ID)+ @mock.patch(TRUSTPILOT_SESSION_PATCH)+ def test_incremental_filter_added_to_request(self, MockSession, _mock_resolve) -> None:+ session = MockSession.return_value+ params = _wire(session, [_reviews_response([{"id": "r1"}]), _reviews_response([])])++ _rows(+ _source(+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ )+ )+ assert params[0]["startDateTime"] == "2026-03-04T02:58:14"++ @mock.patch(RESOLVE_PATCH, return_value=BUSINESS_UNIT_ID)+ @mock.patch(TRUSTPILOT_SESSION_PATCH)+ def test_full_refresh_endpoint_never_filters(self, MockSession, _mock_resolve) -> None:+ # product_reviews has no server-side time filter; a cursor value must not leak into the request.+ session = MockSession.return_value+ params = _wire(+ session,+ [_reviews_response([{"id": "p1"}], key="productReviews"), _reviews_response([], key="productReviews")],+ )++ rows = _rows(+ _source(+ _make_manager(),+ endpoint="product_reviews",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ )+ assert [r["id"] for r in rows] == ["p1"]+ assert "startDateTime" not in params[0]+ assert "orderBy" not in params[0]++ @mock.patch(RESOLVE_PATCH, return_value=BUSINESS_UNIT_ID)+ @mock.patch(TRUSTPILOT_SESSION_PATCH)+ def test_business_unit_returns_single_row(self, MockSession, _mock_resolve) -> None:+ session = MockSession.return_value+ params = _wire(+ session, [_response({"id": BUSINESS_UNIT_ID, "displayName": "Example", "score": {"trustScore": 4.6}})]+ )++ manager = _make_manager()+ rows = _rows(_source(manager, endpoint="business_unit"))++ assert len(rows) == 1+ assert rows[0]["id"] == BUSINESS_UNIT_ID+ assert "perPage" not in params[0]+ assert "page" not in params[0]+ manager.save_state.assert_not_called()++ @mock.patch(RESOLVE_PATCH, return_value=BUSINESS_UNIT_ID)+ @mock.patch(TRUSTPILOT_SESSION_PATCH)+ def test_no_checkpoint_after_final_page(self, MockSession, _mock_resolve) -> None:+ session = MockSession.return_value+ _wire(session, [_reviews_response([])])++ manager = _make_manager()+ assert _rows(_source(manager)) == []+ manager.save_state.assert_not_called()+++class TestPaginatorQueryCap:+ def test_stops_and_warns_at_query_cap(self, caplog: pytest.LogCaptureFixture) -> None:+ paginator = TrustpilotPaginator()+ paginator.page = MAX_PAGES++ with caplog.at_level(logging.WARNING):+ paginator.update_state(mock.MagicMock(), data=[{"id": "r1"}])++ assert paginator.has_next_page is False+ assert any("query cap" in record.message for record in caplog.records)++ def test_empty_page_stop_does_not_warn(self, caplog: pytest.LogCaptureFixture) -> None:+ paginator = TrustpilotPaginator()++ with caplog.at_level(logging.WARNING):+ paginator.update_state(mock.MagicMock(), data=[])++ assert paginator.has_next_page is False+ assert not caplog.recordsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trustpilot/tests/test_trustpilot_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trustpilot/tests/test_trustpilot_source.pynew file mode 100644index 000000000000..ed6c24c31d87--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trustpilot/tests/test_trustpilot_source.py@@ -0,0 +1,146 @@+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.trustpilot import (+ TrustPilotSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.trustpilot.settings import (+ ENDPOINTS,+ TRUSTPILOT_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.trustpilot.source import TrustPilotSource+from products.warehouse_sources.backend.temporal.data_imports.sources.trustpilot.trustpilot import (+ TrustpilotResumeConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestTrustPilotSource:+ def setup_method(self):+ self.source = TrustPilotSource()+ self.team_id = 123+ self.config = TrustPilotSourceConfig(api_key="key", api_secret="secret", business_unit="example.com")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.TRUSTPILOT++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "TrustPilot"+ assert config.label == "Trustpilot"+ # A finished source ships visible with a soft ALPHA label, never hidden.+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/trustpilot"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key", "api_secret", "business_unit"]++ @parameterized.expand(["api_key", "api_secret"])+ def test_credential_fields_are_secret_passwords(self, field_name):+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == field_name)+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ @parameterized.expand(+ [+ "401 Client Error: Unauthorized for url: https://api.trustpilot.com/v1/private/business-units/x/reviews",+ "403 Client Error: Forbidden for url: https://api.trustpilot.com/v1/private/product-reviews/business-units/x/reviews",+ "404 Client Error: Not Found for url: https://api.trustpilot.com/v1/business-units/x",+ "No Trustpilot business unit found for 'example.com'. Enter your domain exactly as it appears.",+ "Trustpilot rejected the API key (HTTP 401). Check the API key in your Trustpilot Business account.",+ "invalid_client from the OAuth2 token endpoint [oauth2_token_config_error]",+ ],+ )+ def test_non_retryable_errors_match_permanent_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)++ @parameterized.expand(+ [+ "429 Client Error: Too Many Requests for url: https://api.trustpilot.com/v1/business-units/x/reviews",+ "500 Server Error: Internal Server Error for url: https://api.trustpilot.com/v1/business-units/x",+ "HTTP 503 from the OAuth2 token endpoint",+ "HTTPSConnectionPool(host='api.trustpilot.com', port=443): Read timed out.",+ ],+ )+ def test_non_retryable_errors_do_not_match_transient(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_match_endpoints_with_correct_sync_modes(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ assert schemas["service_reviews"].supports_incremental is True+ assert schemas["service_reviews"].supports_append is True+ assert [f["field"] for f in schemas["service_reviews"].incremental_fields] == ["createdAt"]+ for name in ("business_unit", "product_reviews"):+ 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):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["service_reviews"])+ assert len(schemas) == 1+ assert schemas[0].name == "service_reviews"++ def test_lists_tables_without_credentials_publishes_catalog(self):+ # Static endpoint catalog (no I/O) — the public docs table list should render.+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert {table["name"] for table in documented} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self):+ canonical = self.source.get_canonical_descriptions()+ assert set(canonical) == set(TRUSTPILOT_ENDPOINTS)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.trustpilot.source.validate_trustpilot_credentials"+ )+ def test_validate_credentials_plumbs_config(self, mock_validate):+ mock_validate.return_value = (True, None)++ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)+ mock_validate.assert_called_once_with("key", "secret", "example.com")++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is TrustpilotResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.trustpilot.source.trustpilot_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_trustpilot_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "service_reviews"+ inputs.team_id = self.team_id+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_trustpilot_source.call_args.kwargs+ assert kwargs["api_key"] == "key"+ assert kwargs["api_secret"] == "secret"+ assert kwargs["business_unit"] == "example.com"+ assert kwargs["endpoint"] == "service_reviews"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.trustpilot.source.trustpilot_source")+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_trustpilot_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "product_reviews"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_trustpilot_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trustpilot/trustpilot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trustpilot/trustpilot.pynew file mode 100644index 000000000000..7b68a09c475f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trustpilot/trustpilot.py@@ -0,0 +1,342 @@+import re+import logging+import dataclasses+from datetime import UTC, date, datetime+from typing import Any, Optional++from requests import Response++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 (+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ApiKeyAuthConfig,+ OAuth2AuthConfig,+)+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+from products.warehouse_sources.backend.temporal.data_imports.sources.trustpilot.settings import (+ BASE_URL,+ MAX_PAGES,+ PER_PAGE,+ TOKEN_URL,+ TRUSTPILOT_ENDPOINTS,+)++logger = logging.getLogger(__name__)++VALIDATE_TIMEOUT = 15++# Stable substrings for get_non_retryable_errors; keep them in the raised messages below.+BUSINESS_UNIT_NOT_FOUND_ERROR = "No Trustpilot business unit found"+CREDENTIALS_REJECTED_ERROR = "Trustpilot rejected the API"++# Trustpilot business unit IDs are 24-hex Mongo-style object IDs (e.g. 507f191e810c19729de860ea).+_BUSINESS_UNIT_ID_RE = re.compile(r"^[0-9a-f]{24}$")+# Bare hostname characters only, so the configured value can never retarget or malform a request.+_DOMAIN_RE = re.compile(r"^[a-z0-9]([a-z0-9.\-]*[a-z0-9])?$")+++class TrustpilotBusinessUnitError(Exception):+ pass+++class TrustpilotAuthError(Exception):+ pass++[email protected](frozen=True)+class TrustpilotResumeConfig:+ # Next page to fetch, 1-indexed.+ page: int+ # The startDateTime the interrupted run queried with. The incremental watermark advances per+ # batch mid-run and a retry re-reads it, so a resumed attempt must re-issue the original query+ # for its saved page number to point at the same rows; re-yielded rows are deduped by the merge.+ start_date_time: str | None = None+++def normalize_business_unit(value: str) -> str:+ """Reduce user input to a bare domain name or a business unit ID.++ Accepts the bare domain (example.com), a URL (https://example.com/), a Trustpilot review page+ URL (https://www.trustpilot.com/review/example.com), or a raw 24-hex business unit ID. Raises+ ValueError on anything else so the caller can surface a precise message.+ """+ cleaned = value.strip().lower()+ cleaned = re.sub(r"^https?://", "", cleaned)+ host, _, path = cleaned.partition("/")+ host = host.strip()+ # A pasted Trustpilot review URL names the business unit in its path, not its host.+ if host == "trustpilot.com" or host.endswith(".trustpilot.com"):+ match = re.match(r"review/([^/?#]+)", path)+ if match:+ host = match.group(1)+ if host and (_BUSINESS_UNIT_ID_RE.match(host) or _DOMAIN_RE.match(host)):+ return host+ raise ValueError(+ f"Invalid Trustpilot business unit: {value!r}. Enter your website domain as it appears on "+ "your Trustpilot profile (for example 'example.com'), or your business unit ID."+ )+++def is_business_unit_id(value: str) -> bool:+ return bool(_BUSINESS_UNIT_ID_RE.match(value))+++def _raise_for_auth(response: Response) -> None:+ if response.status_code in (401, 403):+ raise TrustpilotAuthError(+ f"{CREDENTIALS_REJECTED_ERROR} key (HTTP {response.status_code}). "+ "Check the API key in your Trustpilot Business account."+ )+++def resolve_business_unit_id(api_key: str, business_unit: str) -> str:+ """Resolve the configured business unit (domain or raw ID) to a verified business unit ID.++ Domains resolve through the public find endpoint; a raw ID is confirmed to exist with the+ public business unit endpoint. Either way a bad value fails here with a precise message+ instead of a 404 deep inside the paginated fetch.+ """+ normalized = normalize_business_unit(business_unit)+ session = make_tracked_session(redact_values=(api_key,))++ if is_business_unit_id(normalized):+ response = session.get(+ f"{BASE_URL}/business-units/{normalized}",+ headers={"apikey": api_key},+ timeout=VALIDATE_TIMEOUT,+ )+ _raise_for_auth(response)+ if response.status_code == 404:+ raise TrustpilotBusinessUnitError(+ f"{BUSINESS_UNIT_NOT_FOUND_ERROR} for ID '{normalized}'. Check the business unit ID "+ "in your Trustpilot Business account."+ )+ response.raise_for_status()+ return normalized++ candidates = [normalized]+ # Profiles are usually keyed on the bare domain, so fall back without the www prefix.+ if normalized.startswith("www."):+ candidates.append(normalized.removeprefix("www."))++ for candidate in candidates:+ response = session.get(+ f"{BASE_URL}/business-units/find",+ params={"name": candidate},+ headers={"apikey": api_key},+ timeout=VALIDATE_TIMEOUT,+ )+ _raise_for_auth(response)+ if response.status_code == 404:+ continue+ response.raise_for_status()+ business_unit_id = response.json().get("id")+ if not isinstance(business_unit_id, str) or not business_unit_id:+ # A 200 without an id is a broken response contract, not a user typo — fail loud+ # instead of falling through to the misleading not-found message.+ raise TrustpilotBusinessUnitError(+ "Trustpilot returned an unexpected business unit lookup response. Try again."+ )+ return business_unit_id++ raise TrustpilotBusinessUnitError(+ f"{BUSINESS_UNIT_NOT_FOUND_ERROR} for '{normalized}'. Enter your domain exactly as it "+ "appears on your Trustpilot profile, or use your business unit ID."+ )+++def mint_access_token(api_key: str, api_secret: str) -> str:+ """Mint a client-credentials access token to confirm the API secret is genuine.++ Only used at credential validation; sync-time requests mint through the framework's OAuth2+ auth, which re-mints on expiry (client-credentials tokens cannot be refreshed, Trustpilot+ expects the same request again).+ """+ # capture=False keeps the token response body out of HTTP samples; allow_redirects=False so a+ # 3xx can't bounce the secret off the token host.+ session = make_tracked_session(redact_values=(api_secret,), capture=False, allow_redirects=False)+ response = session.post(+ TOKEN_URL,+ data={"grant_type": "client_credentials"},+ auth=(api_key, api_secret),+ timeout=VALIDATE_TIMEOUT,+ )+ if response.status_code != 200:+ raise TrustpilotAuthError(+ f"{CREDENTIALS_REJECTED_ERROR} key and secret (HTTP {response.status_code}). "+ "Check both values in your Trustpilot Business account."+ )+ try:+ token = response.json().get("access_token")+ except ValueError:+ raise TrustpilotAuthError("The Trustpilot token endpoint returned an unexpected response. Try again.")+ if not isinstance(token, str) or not token:+ raise TrustpilotAuthError("The Trustpilot token endpoint returned no access token. Try again.")+ return token+++def validate_credentials(api_key: str, api_secret: str, business_unit: str) -> tuple[bool, str | None]:+ """Resolve the business unit with the API key, then mint a token to confirm the secret.++ Both probes are cheap and fetch no review data. There is no per-endpoint scope probe because a+ Trustpilot API application grants the same access to every endpoint this source syncs.+ """+ try:+ resolve_business_unit_id(api_key, business_unit)+ mint_access_token(api_key, api_secret)+ except (ValueError, TrustpilotBusinessUnitError, TrustpilotAuthError) as e:+ return False, str(e)+ except Exception: # noqa: BLE001 — a credential probe must never raise; any failure means "not validated"+ return False, "Could not connect to Trustpilot. Check the API key, secret and business unit, then try again."+ return True, None+++def _format_start_datetime(value: Any) -> str:+ """Format the incremental watermark as the `2013-09-07T13:37:00` shape startDateTime expects.++ Trustpilot timestamps are UTC, so emit UTC without an offset suffix (the endpoint rejects+ neither, but documents the bare shape).+ """+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return aware.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%S")+ return str(value)+++class TrustpilotPaginator(PageNumberPaginator):+ """Page-number paginator that logs when it stops at Trustpilot's 100,000-record query cap.++ The review list endpoints don't page past 100,000 records per query. Stopping silently would+ read as a complete sync, so log what was left behind instead.+ """++ def __init__(self) -> None:+ super().__init__(base_page=1, page_param="page", total_path=None, maximum_page=MAX_PAGES)++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ super().update_state(response, data)+ # Only the cap branch leaves `page` pointing past `maximum_page`; an empty-page stop+ # returns before incrementing.+ if not self._has_next_page and self.maximum_page is not None and self.page > self.maximum_page:+ logger.warning(+ "Trustpilot pagination stopped at the 100,000-record query cap; rows past it were not fetched",+ extra={"maximum_page": self.maximum_page},+ )+++def _build_auth(api_key: str, api_secret: str, requires_oauth: bool) -> ApiKeyAuthConfig | OAuth2AuthConfig:+ if not requires_oauth:+ return {"type": "api_key", "name": "apikey", "location": "header", "api_key": api_key}+ return {+ "type": "oauth2",+ "token_url": TOKEN_URL,+ "client_id": api_key,+ "client_secret": api_secret,+ "grant_type": "client_credentials",+ # Trustpilot's token endpoint takes the key/secret as HTTP Basic (its recommended form).+ "client_auth_method": "basic",+ }+++def trustpilot_source(+ api_key: str,+ api_secret: str,+ business_unit: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[TrustpilotResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = TRUSTPILOT_ENDPOINTS[endpoint]+ business_unit_id = resolve_business_unit_id(api_key, business_unit)+ path = config.path.format(business_unit_id=business_unit_id)++ resume: TrustpilotResumeConfig | None = None+ if config.paginated and resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()++ start_date_time: str | None = None+ if config.incremental_fields and should_use_incremental_field:+ if resume is not None:+ # Re-issue the interrupted run's query window; see TrustpilotResumeConfig.+ start_date_time = resume.start_date_time+ elif db_incremental_field_last_value is not None:+ start_date_time = _format_start_datetime(db_incremental_field_last_value)++ params: dict[str, Any] = {}+ if config.paginated:+ params["perPage"] = PER_PAGE+ if config.order_by:+ params["orderBy"] = config.order_by+ if start_date_time:+ params["startDateTime"] = start_date_time++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": BASE_URL,+ "headers": {"Accept": "application/json"},+ "auth": _build_auth(api_key, api_secret, config.requires_oauth),+ "paginator": TrustpilotPaginator() if config.paginated else "single_page",+ # capture=False: private review rows carry consumer emails, order references and+ # review text, which must stay out of HTTP sample capture (still metered and logged).+ "session": make_tracked_session(redact_values=(api_key, api_secret), capture=False),+ },+ "resource_defaults": {},+ "resources": [+ {+ "name": endpoint,+ "endpoint": {+ "path": path,+ "params": params,+ # response_key None means the whole body is the single row (business unit).+ **({"data_selector": config.response_key} if config.response_key else {}),+ },+ }+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resume is not None and resume.page > 1:+ initial_paginator_state = {"page": resume.page}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Saved AFTER each page is yielded, so a crash re-fetches the last page (merge dedupes)+ # rather than skipping it.+ if state and state.get("page"):+ resumable_source_manager.save_state(+ TrustpilotResumeConfig(page=int(state["page"]), start_date_time=start_date_time)+ )++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint if config.paginated else None,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=config.primary_keys,+ # service_reviews requests orderBy=createdat.asc, so the watermark can checkpoint per+ # batch. The other endpoints are full refresh, where sort order carries no meaning.+ sort_mode="asc",+ 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,+ )