: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): add Xendit source (#77128)
Tom Owersbe215242f63d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex ec5274777b65..ea109067ec8d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -659,6 +659,7 @@ the row lists both.| wrike | HTTP | requests | ✅ || writesonic | HTTP | requests | ✅ || wufoo | HTTP | requests | ✅ |+| xendit | HTTP | requests + `rest_source.RESTClient` | ✅ || xmatters | HTTP | requests | ✅ || yousign | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || zapier_supported_storage | HTTP | requests | ✅ |@@ -1416,7 +1417,6 @@ doesn't conflict with concurrent PRs.- workramp- world_bank- wufoo-- xendit- xero- xsolla- yahoo_financediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/xendit.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/xendit.pyindex 8617e44ac872..8b5c275ccbf8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/xendit.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/xendit.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass XenditSourceConfig(config.Config):- pass+ api_key: str+ sub_account_user_id: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xendit/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xendit/canonical_descriptions.pynew file mode 100644index 000000000000..b3b25acfc7d2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xendit/canonical_descriptions.py@@ -0,0 +1,52 @@+"""Canonical, documentation-sourced descriptions for Xendit endpoints and columns.++Sourced from the official Xendit API reference (https://docs.xendit.co/api-reference/), keyed by the+resource names in `settings.py` `XENDIT_ENDPOINTS`, which match the `ExternalDataSchema.name` of a+synced Xendit table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "transactions": {+ "description": "Every money movement on the Xendit account: payments, disbursements, refunds, transfers, conversions, fees and adjustments, with their settlement status.",+ "docs_url": "https://docs.xendit.co/apidocs/list-transactions",+ "columns": {+ "id": "Unique ID generated by Xendit for the transaction.",+ "product_id": "ID of the product the transaction belongs to. The prefix differs per product, and the value matches the id returned by that product's own API.",+ "type": "Type of transaction, for example PAYMENT, DISBURSEMENT, REFUND, TRANSFER_IN, TRANSFER_OUT, CONVERSION or WITHDRAWAL.",+ "status": "State of the transaction: PENDING, SUCCESS, FAILED, VOIDED or REVERSED.",+ "channel_category": "Channel category the transaction came through, for example BANK, CARDS, EWALLET, QR_CODE, VIRTUAL_ACCOUNT or XENPLATFORM.",+ "channel_code": "Specific payment channel used within the channel category.",+ "reference_id": "Reference supplied by the merchant to identify their request.",+ "account_identifier": "Account identifier of the transaction. The format differs per channel, for example an account number on BANK and a masked card number on CARDS.",+ "currency": "Currency of the transaction, as an ISO 4217 code.",+ "amount": "Amount of the transaction. Decimal places follow the currency's ISO 4217 definition.",+ "net_amount": "Amount of the transaction after fees and tax are deducted.",+ "net_amount_currency": "Currency of the net amount.",+ "cashflow": "Direction of the money movement: MONEY_IN or MONEY_OUT.",+ "settlement_status": "Settlement state of the transaction: PENDING, EARLY_SETTLED or SETTLED. Null when settlement does not apply.",+ "estimated_settlement_time": "Estimated time the amount will be settled to the merchant's balance. Only set for money-in transactions.",+ "business_id": "ID of the Xendit business account the transaction belongs to.",+ "created": "Time the transaction was created, in UTC.",+ "updated": "Time the transaction was last updated, in UTC.",+ "fee": "Breakdown of the Xendit fee, value added tax, withholding taxes and the fee processing status.",+ "product_data": "Product-specific identifiers for Payments v3 transactions, such as capture_id, payment_request_id, reusable_payment_link_id and payment_link_id.",+ },+ },+ "accounts": {+ "description": "xenPlatform sub-accounts owned or managed by the Xendit account, with their verification status.",+ "docs_url": "https://docs.xendit.co/apidocs/list-accounts",+ "columns": {+ "id": "ID of the account. Used as the for-user-id header to act on behalf of the account.",+ "created": "Time the account was created.",+ "updated": "Time the account was last updated.",+ "type": "Type of account: MANAGED or OWNED.",+ "email": "Email address associated with the account.",+ "public_profile": "Publicly visible profile of the account, including its business name, description and country.",+ "status": "Status of the account: INVITED, REGISTERED, AWAITING_DOCS, PENDING_VERIFICATION, LIVE or SUSPENDED.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xendit/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xendit/settings.pynew file mode 100644index 000000000000..162aa2bf738a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xendit/settings.py@@ -0,0 +1,72 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Xendit's public API only exposes two list endpoints that enumerate a merchant's own records:+# `GET /transactions` (the unified money-movement ledger) and `GET /v2/accounts` (xenPlatform+# sub-accounts). Everything else in the current API reference is either a single-object lookup+# (payments, payouts, sessions, balance), a search that requires an exact identifier+# (`GET /customers` requires `reference_id`), or a child collection with no way to enumerate its+# parents (`GET /recurring/plans/{id}/cycles`), so none of them can be synced as a table.+#+# Both list endpoints share the same contract: cursor pagination via `after_id` + `has_more`, and+# server-side `created[gte]` / `updated[gte]` range filters.++XENDIT_BASE_URL = "https://api.xendit.co"++# `limit` is documented as capped at 50 on /v2/accounts. /transactions documents a default of 10 but+# no maximum, so use the one cap Xendit publishes for this pagination style rather than guessing higher.+PAGE_SIZE = 50+++@dataclass+class XenditEndpointConfig:+ name: str+ path: str+ # Timestamp fields the endpoint filters on server-side, as `<field>[gte]` query params.+ filterable_timestamps: tuple[str, ...] = ()+ partition_key: str | None = "created"+ # Sub-account listing only returns data for xenPlatform accounts, so it is off by default.+ should_sync_default: bool = True+ permission: str = ""+ extra_params: dict[str, str] = field(default_factory=dict)++ @property+ def incremental_fields(self) -> list[IncrementalField]:+ return [+ {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+ for name in self.filterable_timestamps+ ]+++XENDIT_ENDPOINTS: dict[str, XenditEndpointConfig] = {+ "transactions": XenditEndpointConfig(+ name="transactions",+ path="/transactions",+ filterable_timestamps=("updated", "created"),+ permission="Transaction Read",+ ),+ "accounts": XenditEndpointConfig(+ name="accounts",+ path="/v2/accounts",+ filterable_timestamps=("updated", "created"),+ should_sync_default=False,+ permission="Accounts Read",+ ),+}++ENDPOINTS = tuple(XENDIT_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in XENDIT_ENDPOINTS.items()+}++SHOULD_SYNC_DEFAULT: dict[str, bool] = {name: config.should_sync_default for name, config in XENDIT_ENDPOINTS.items()}++# Default cursor field when a schema has no explicit selection.+DEFAULT_INCREMENTAL_FIELD = "updated"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xendit/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xendit/source.pyindex 5a365c0b680c..898493ca2e7d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/xendit/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xendit/source.py@@ -1,30 +1,186 @@-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.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.xendit import XenditSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.xendit.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SHOULD_SYNC_DEFAULT,+ XENDIT_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.xendit.xendit import (+ XenditResumeConfig,+ validate_credentials as validate_xendit_credentials,+ xendit_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+TRANSACTIONS_ENDPOINT = "transactions"+@SourceRegistry.register-class XenditSource(SimpleSource[XenditSourceConfig]):+class XenditSource(ResumableSource[XenditSourceConfig, XenditResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # Xendit has no account-wide API version: the endpoints this source calls take no version+ # header or version query param, and the `/v2` path segment on the accounts endpoint is part of+ # that endpoint's path rather than a version the caller picks. So the unversioned default stands.+ api_docs_url = "https://docs.xendit.co/api-reference/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.XENDIT+ @property+ def connection_host_fields(self) -> list[str]:+ # `sub_account_user_id` picks which xenPlatform sub-account the stored key reads via the+ # `for-user-id` header, so retargeting it must re-require the key.+ return ["sub_account_user_id"]++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.xendit.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Your Xendit API key is invalid or has been revoked. Create a new secret key in the Xendit dashboard and reconnect.",+ "403 Client Error: Forbidden for url": "Your Xendit API key is missing the permission this table needs. Update the key's permissions in the Xendit dashboard and try again.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.XENDIT,category=DataWarehouseSourceCategory.PAYMENTS___BILLING,label="Xendit",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Xendit secret API key to sync your Xendit data into the PostHog Data warehouse.++Create a key in the Xendit dashboard under **Settings > Developers > API keys**. Give it the **Transaction Read** permission to sync transactions, and **Accounts Read** if you also want to sync xenPlatform sub-accounts.""",iconPath="/static/services/xendit.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/xendit",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="Secret API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="sub_account_user_id",+ label="Sub-account user ID (xenPlatform only)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="",+ secret=False,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: XenditSourceConfig,+ 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,+ should_sync_default=SHOULD_SYNC_DEFAULT,+ )++ def validate_credentials(+ self,+ config: XenditSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ endpoint = XENDIT_ENDPOINTS.get(schema_name or TRANSACTIONS_ENDPOINT, XENDIT_ENDPOINTS[TRANSACTIONS_ENDPOINT])+ _reachable, status = validate_xendit_credentials(config.api_key, endpoint.path, config.sub_account_user_id)++ if status == 200:+ return True, None+ # A 403 means the key is genuine but lacks that endpoint's permission. At source creation+ # that's fine, since a user may only grant the permissions for the tables they want, so+ # reject it only when a specific table is being checked.+ if status == 403:+ if schema_name is None:+ return True, None+ return False, f"Your Xendit API key is missing the {endpoint.permission} permission"++ return False, "Invalid Xendit API key"++ def get_endpoint_permissions(+ self,+ config: XenditSourceConfig,+ team_id: int,+ endpoints: list[str],+ api_version: str | None = None,+ ) -> dict[str, str | None]:+ permissions: dict[str, str | None] = {}+ for name in endpoints:+ endpoint = XENDIT_ENDPOINTS.get(name)+ if endpoint is None:+ permissions[name] = None+ continue+ _reachable, status = validate_xendit_credentials(config.api_key, endpoint.path, config.sub_account_user_id)+ # Only an outright denial counts as a missing permission; a throttle, a 5xx or a+ # network blip does not, so those leave the table selectable.+ permissions[name] = (+ f"Your Xendit API key is missing the {endpoint.permission} permission" if status == 403 else None+ )+ return permissions++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[XenditResumeConfig]:+ return ResumableSourceManager[XenditResumeConfig](inputs, XenditResumeConfig)++ def source_for_pipeline(+ self,+ config: XenditSourceConfig,+ resumable_source_manager: ResumableSourceManager[XenditResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return xendit_source(+ api_key=config.api_key,+ 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,+ incremental_field=inputs.incremental_field,+ for_user_id=config.sub_account_user_id,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xendit/tests/test_xendit.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xendit/tests/test_xendit.pynew file mode 100644index 000000000000..13eca7811323--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xendit/tests/test_xendit.py@@ -0,0 +1,297 @@+import json+from collections.abc import Iterable+from datetime import UTC, date, datetime+from typing import Any, cast++import pytest+from unittest import mock++import requests+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.xendit.settings import (+ PAGE_SIZE,+ XENDIT_BASE_URL,+ XENDIT_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.xendit.xendit import (+ XenditResumeConfig,+ _build_params,+ _format_datetime,+ validate_credentials,+ xendit_source,+)++# Both the REST client's session and the credential probe are built by this module's+# make_tracked_session, so one patch target covers the whole transport.+SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.xendit.xendit.make_tracked_session"+++def _response(items: list[dict[str, Any]] | None, has_more: bool, status: int = 200) -> Response:+ body: dict[str, Any] = {"data": items or [], "has_more": has_more, "links": []}+ response = Response()+ response.status_code = status+ response._content = json.dumps(body).encode()+ return response+++def _make_manager(resume_state: XenditResumeConfig | 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]]:+ """Wire a mock session and snapshot each request's params at send time.++ ``request.params`` is one dict mutated in place across pages, so copy it as each request is+ prepared rather than inspecting the shared final state.+ """+ 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 _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any) -> SourceResponse:+ return xendit_source("xnd_key", endpoint, team_id=1, job_id="job-1", resumable_source_manager=manager, **kwargs)+++def _rows(source_response: SourceResponse) -> list[dict[str, Any]]:+ return [row for page in cast("Iterable[Any]", source_response.items()) for row in page]+++class TestFormatDatetime:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),+ (datetime(2026, 1, 15, 10, 30, 45, 123456, tzinfo=UTC), "2026-01-15T10:30:45.123Z"),+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),+ (date(2026, 3, 4), "2026-03-04T00:00:00.000Z"),+ ("2026-03-04T02:58:14.000Z", "2026-03-04T02:58:14.000Z"),+ ],+ )+ def test_format_datetime(self, value: object, expected: str) -> None:+ result = _format_datetime(value)++ assert result == expected+ assert "+00:00" not in result+++class TestBuildParams:+ def test_full_refresh_only_sets_page_size(self) -> None:+ params = _build_params(+ XENDIT_ENDPOINTS["transactions"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ incremental_field="updated",+ )++ assert params == {"limit": PAGE_SIZE}++ def test_first_incremental_sync_sends_no_filter(self) -> None:+ params = _build_params(+ XENDIT_ENDPOINTS["transactions"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ incremental_field="updated",+ )++ assert params == {"limit": PAGE_SIZE}++ @pytest.mark.parametrize("endpoint", sorted(XENDIT_ENDPOINTS))+ @pytest.mark.parametrize(+ "incremental_field, expected_param", [("updated", "updated[gte]"), ("created", "created[gte]")]+ )+ def test_honors_the_selected_cursor_field(self, endpoint: str, incremental_field: str, expected_param: str) -> None:+ params = _build_params(+ XENDIT_ENDPOINTS[endpoint],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ incremental_field=incremental_field,+ )++ assert params[expected_param] == "2026-03-04T02:58:14.000Z"+ assert len(params) == 2++ @pytest.mark.parametrize("incremental_field", [None, "estimated_settlement_time"])+ def test_unfilterable_cursor_field_falls_back_to_updated(self, incremental_field: str | None) -> None:+ # A field Xendit does not filter on server-side would be silently ignored, turning the+ # sync into a full refresh that claims to be incremental.+ params = _build_params(+ XENDIT_ENDPOINTS["transactions"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ incremental_field=incremental_field,+ )++ assert params["updated[gte]"] == "2026-03-04T02:58:14.000Z"+ assert "estimated_settlement_time[gte]" not in params+++class TestValidateCredentials:+ @pytest.mark.parametrize("status_code, expected_valid", [(200, True), (401, False), (403, False), (500, False)])+ @mock.patch(SESSION_PATCH)+ def test_status_is_reported_back(self, mock_session_factory, status_code: int, expected_valid: bool) -> None:+ mock_session_factory.return_value.get.return_value = mock.MagicMock(status_code=status_code)++ reachable, status = validate_credentials("xnd_key", "/transactions")++ assert (reachable, status) == (expected_valid, status_code)+ call = mock_session_factory.return_value.get.call_args+ assert call.args[0] == f"{XENDIT_BASE_URL}/transactions?limit=1"+ assert call.kwargs["headers"] is None++ @mock.patch(SESSION_PATCH)+ def test_sub_account_header_is_sent(self, mock_session_factory) -> None:+ mock_session_factory.return_value.get.return_value = mock.MagicMock(status_code=200)++ validate_credentials("xnd_key", "/transactions", for_user_id="sub-1")++ assert mock_session_factory.return_value.get.call_args.kwargs["headers"] == {"for-user-id": "sub-1"}++ @mock.patch(SESSION_PATCH)+ def test_transport_error_is_swallowed(self, mock_session_factory) -> None:+ mock_session_factory.return_value.get.side_effect = requests.ConnectionError("boom")++ assert validate_credentials("xnd_key", "/transactions") == (False, None)+++class TestPagination:+ @mock.patch(SESSION_PATCH)+ def test_follows_after_id_until_has_more_is_false(self, mock_session_factory) -> None:+ params = _wire(+ mock_session_factory.return_value,+ [+ _response([{"id": "txn_1"}, {"id": "txn_2"}], has_more=True),+ _response([{"id": "txn_3"}], has_more=False),+ ],+ )++ rows = _rows(_source("transactions", _make_manager()))++ assert [row["id"] for row in rows] == ["txn_1", "txn_2", "txn_3"]+ assert params[0] == {"limit": PAGE_SIZE}+ # The cursor is the LAST row of the previous page, not the first.+ assert params[1]["after_id"] == "txn_2"++ @mock.patch(SESSION_PATCH)+ def test_stops_when_the_cursor_does_not_advance(self, mock_session_factory) -> None:+ # An API that keeps claiming has_more while returning the same last row would otherwise+ # be refetched until the activity times out.+ mock_session_factory.return_value.headers = {}+ mock_session_factory.return_value.prepare_request.return_value = mock.MagicMock()+ mock_session_factory.return_value.send.side_effect = [+ _response([{"id": "txn_1"}], has_more=True),+ _response([{"id": "txn_1"}], has_more=True),+ ]++ rows = _rows(_source("transactions", _make_manager()))++ assert [row["id"] for row in rows] == ["txn_1", "txn_1"]+ assert mock_session_factory.return_value.send.call_count == 2++ @pytest.mark.parametrize(+ "last_page",+ [+ _response([], has_more=True),+ _response([{"no_id": True}], has_more=True),+ ],+ )+ @mock.patch(SESSION_PATCH)+ def test_stops_when_no_cursor_can_be_built(self, mock_session_factory, last_page: Response) -> None:+ _wire(mock_session_factory.return_value, [last_page])++ _rows(_source("transactions", _make_manager()))++ assert mock_session_factory.return_value.send.call_count == 1++ @mock.patch(SESSION_PATCH)+ def test_saves_resume_state_after_each_page_but_not_the_last(self, mock_session_factory) -> None:+ _wire(+ mock_session_factory.return_value,+ [_response([{"id": "txn_1"}], has_more=True), _response([{"id": "txn_2"}], has_more=False)],+ )+ manager = _make_manager()++ _rows(_source("transactions", manager))++ assert manager.save_state.call_count == 1+ assert manager.save_state.call_args.args[0] == XenditResumeConfig(after_id="txn_1")++ @mock.patch(SESSION_PATCH)+ def test_resumes_from_saved_cursor(self, mock_session_factory) -> None:+ params = _wire(mock_session_factory.return_value, [_response([{"id": "txn_9"}], has_more=False)])++ rows = _rows(_source("transactions", _make_manager(XenditResumeConfig(after_id="txn_8"))))++ assert [row["id"] for row in rows] == ["txn_9"]+ assert params[0]["after_id"] == "txn_8"++ @mock.patch(SESSION_PATCH)+ def test_incremental_filter_rides_the_first_request(self, mock_session_factory) -> None:+ params = _wire(mock_session_factory.return_value, [_response([{"id": "txn_1"}], has_more=False)])++ _rows(+ _source(+ "transactions",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ incremental_field="updated",+ )+ )++ assert params[0]["updated[gte]"] == "2026-03-04T02:58:14.000Z"++ @mock.patch("tenacity.nap.time.sleep", return_value=None)+ @mock.patch(SESSION_PATCH)+ def test_retries_transient_statuses(self, mock_session_factory, _mock_sleep) -> None:+ _wire(+ mock_session_factory.return_value,+ [+ _response(None, has_more=False, status=429),+ _response(None, has_more=False, status=503),+ _response([{"id": "txn_1"}], has_more=False),+ ],+ )++ rows = _rows(_source("transactions", _make_manager()))++ assert [row["id"] for row in rows] == ["txn_1"]+ assert mock_session_factory.return_value.send.call_count == 3++ @mock.patch(SESSION_PATCH)+ def test_forbidden_response_raises(self, mock_session_factory) -> None:+ _wire(mock_session_factory.return_value, [_response(None, has_more=False, status=403)])++ with pytest.raises(requests.HTTPError):+ _rows(_source("transactions", _make_manager()))+++class TestSourceResponse:+ @pytest.mark.parametrize("endpoint", sorted(XENDIT_ENDPOINTS))+ @mock.patch(SESSION_PATCH)+ def test_response_shape(self, mock_session_factory, endpoint: str) -> None:+ mock_session_factory.return_value.headers = {}++ response = _source(endpoint, _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # Xendit documents no ordering direction on these endpoints, so the watermark must only be+ # committed once a run completes.+ assert response.sort_mode == "desc"+ assert response.partition_mode == "datetime"+ assert response.partition_format == "month"+ # The partition key must be a field that never changes after a row is written.+ assert response.partition_keys == ["created"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xendit/tests/test_xendit_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xendit/tests/test_xendit_source.pynew file mode 100644index 000000000000..a194492fbe2c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xendit/tests/test_xendit_source.py@@ -0,0 +1,204 @@+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.xendit import XenditSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.xendit.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.xendit.settings import ENDPOINTS, XENDIT_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.xendit.source import XenditSource+from products.warehouse_sources.backend.temporal.data_imports.sources.xendit.xendit import XenditResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++VALIDATE_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.xendit.source.validate_xendit_credentials"+)+SOURCE_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.xendit.source.xendit_source"+++def _make_inputs(schema_name: str = "transactions", **overrides):+ defaults = {+ "schema_name": schema_name,+ "schema_id": "schema-1",+ "source_id": "source-1",+ "team_id": 1,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-1",+ "logger": mock.MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return mock.MagicMock(**defaults)+++class TestXenditSource:+ def setup_method(self):+ self.source = XenditSource()+ self.team_id = 123+ self.config = XenditSourceConfig(api_key="xnd_test_key")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.XENDIT++ def test_connection_host_fields_pin_sub_account(self):+ # Retargeting the stored key at another sub-account must force credential re-entry.+ assert self.source.connection_host_fields == ["sub_account_user_id"]++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Xendit"+ assert config.label == "Xendit"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source ships visible: unreleasedSource hides it from users entirely.+ assert not config.unreleasedSource+ assert config.iconPath == "/static/services/xendit.png"++ fields = {field.name: field for field in config.fields if isinstance(field, SourceFieldInputConfig)}+ assert set(fields) == {"api_key", "sub_account_user_id"}+ assert fields["api_key"].type == SourceFieldInputConfigType.PASSWORD+ assert fields["api_key"].required is True+ assert fields["api_key"].secret is True+ # The sub-account id is a xenPlatform-only routing hint, not a credential.+ assert fields["sub_account_user_id"].required is False+ assert fields["sub_account_user_id"].secret is False++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.xendit.co/transactions?limit=50",+ "403 Client Error: Forbidden for url: https://api.xendit.co/v2/accounts?limit=50",+ ],+ )+ def test_auth_failures_are_non_retryable(self, observed_error):+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ def test_get_schemas_lists_every_endpoint(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize("name", sorted(ENDPOINTS))+ def test_endpoints_advertise_both_server_side_filters(self, name):+ schema = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}[name]++ assert schema.supports_incremental is True+ assert {field["field"] for field in schema.incremental_fields} == {"updated", "created"}++ def test_sub_account_table_is_not_synced_by_default(self):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}++ assert schemas["transactions"].should_sync_default is True+ # Sub-accounts only exist for xenPlatform merchants, so selecting it is opt-in.+ assert schemas["accounts"].should_sync_default is False++ @pytest.mark.parametrize(+ "names, expected",+ [+ (["transactions"], {"transactions"}),+ (["nonexistent"], set()),+ ],+ )+ def test_get_schemas_filtered_by_names(self, names, expected):+ assert {s.name for s in self.source.get_schemas(self.config, self.team_id, names=names)} == expected++ def test_canonical_descriptions_cover_every_endpoint(self):+ assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "status, schema_name, expected_valid, expected_message",+ [+ (200, None, True, None),+ (200, "transactions", True, None),+ # A key without a table's permission is still a real key, so source creation succeeds+ # and only the per-table check rejects it.+ (403, None, True, None),+ (403, "accounts", False, "Your Xendit API key is missing the Accounts Read permission"),+ (401, None, False, "Invalid Xendit API key"),+ (None, None, False, "Invalid Xendit API key"),+ ],+ )+ @mock.patch(VALIDATE_PATCH)+ def test_validate_credentials(self, mock_validate, status, schema_name, expected_valid, expected_message):+ mock_validate.return_value = (status == 200, status)++ is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)++ assert (is_valid, message) == (expected_valid, expected_message)++ @mock.patch(VALIDATE_PATCH)+ def test_validate_credentials_probes_the_requested_table(self, mock_validate):+ mock_validate.return_value = (True, 200)++ self.source.validate_credentials(self.config, self.team_id, schema_name="accounts")++ assert mock_validate.call_args.args[1] == XENDIT_ENDPOINTS["accounts"].path++ @pytest.mark.parametrize(+ "status, expected",+ [+ (200, None),+ (403, "Your Xendit API key is missing the Transaction Read permission"),+ # A throttle or a blip is not a permission problem, so the table stays selectable.+ (429, None),+ (None, None),+ ],+ )+ @mock.patch(VALIDATE_PATCH)+ def test_get_endpoint_permissions(self, mock_validate, status, expected):+ mock_validate.return_value = (status == 200, status)++ permissions = self.source.get_endpoint_permissions(self.config, self.team_id, ["transactions"])++ assert permissions == {"transactions": expected}++ @mock.patch(VALIDATE_PATCH)+ def test_get_endpoint_permissions_ignores_unknown_tables(self, mock_validate):+ assert self.source.get_endpoint_permissions(self.config, self.team_id, ["nonexistent"]) == {"nonexistent": None}+ mock_validate.assert_not_called()++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ manager = self.source.get_resumable_source_manager(_make_inputs())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is XenditResumeConfig++ @mock.patch(SOURCE_PATCH)+ def test_source_for_pipeline_plumbs_arguments(self, mock_xendit_source):+ config = XenditSourceConfig(api_key="xnd_test_key", sub_account_user_id="sub-1")+ inputs = _make_inputs(+ schema_name="transactions",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00.000Z",+ incremental_field="updated",+ )+ manager = mock.MagicMock()++ self.source.source_for_pipeline(config, manager, inputs)++ kwargs = mock_xendit_source.call_args.kwargs+ assert kwargs["api_key"] == "xnd_test_key"+ assert kwargs["endpoint"] == "transactions"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00.000Z"+ assert kwargs["incremental_field"] == "updated"+ assert kwargs["for_user_id"] == "sub-1"++ @mock.patch(SOURCE_PATCH)+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self, mock_xendit_source):+ inputs = _make_inputs(+ should_use_incremental_field=False,+ db_incremental_field_last_value="2026-01-01T00:00:00.000Z",+ )++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_xendit_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xendit/xendit.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xendit/xendit.pynew file mode 100644index 000000000000..7d3884351fd0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xendit/xendit.py@@ -0,0 +1,221 @@+import dataclasses+from datetime import UTC, date, datetime+from typing import Any, Optional++from requests import Request, Response++from products.warehouse_sources.backend.temporal.data_imports.sources.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 HttpBasicAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator+from products.warehouse_sources.backend.temporal.data_imports.sources.common.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.xendit.settings import (+ DEFAULT_INCREMENTAL_FIELD,+ PAGE_SIZE,+ XENDIT_BASE_URL,+ XENDIT_ENDPOINTS,+ XenditEndpointConfig,+)+++class XenditResumeConfig:+ after_id: str+++def _format_datetime(value: Any) -> str:+ """Format an incremental cursor value as the ISO 8601 UTC string Xendit's range filters expect."""+ if isinstance(value, datetime):+ dt = value+ elif isinstance(value, date):+ dt = datetime.combine(value, datetime.min.time())+ else:+ return str(value)++ utc_dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+++class XenditCursorPaginator(BasePaginator):+ """Cursor pagination for Xendit list endpoints.++ Responses are shaped `{"data": [...], "has_more": bool, "links": [...]}`. The next page is+ requested by passing the last row's `id` as `after_id`; the `links` HATEOAS entry carries the+ same cursor but as a path-relative URL, so building it from the last row keeps every request+ anchored to our own base URL.+ """++ def __init__(self) -> None:+ super().__init__()+ self._after_id: Optional[str] = None++ def _apply_cursor(self, request: Request) -> None:+ if self._after_id is None:+ return+ if request.params is None:+ request.params = {}+ request.params["after_id"] = self._after_id++ def init_request(self, request: Request) -> None:+ # Honour a seeded resume cursor on the first request.+ self._apply_cursor(request)++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ try:+ body = response.json()+ except Exception:+ body = {}++ rows = data if data is not None else (body.get("data") if isinstance(body, dict) else None) or []+ last_row = rows[-1] if rows else None+ next_after_id = last_row.get("id") if isinstance(last_row, dict) else None++ # A cursor identical to the one just used means the page didn't advance; stop instead of+ # refetching it until the activity times out.+ if not (isinstance(body, dict) and body.get("has_more")) or next_after_id is None:+ self._has_next_page = False+ return+ if str(next_after_id) == self._after_id:+ self._has_next_page = False+ return++ self._after_id = str(next_after_id)+ self._has_next_page = True++ def update_request(self, request: Request) -> None:+ self._apply_cursor(request)++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ return {"after_id": self._after_id} if self._has_next_page and self._after_id is not None else None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ after_id = state.get("after_id")+ if after_id is not None:+ self._after_id = str(after_id)+ self._has_next_page = True++ def __str__(self) -> str:+ return "XenditCursorPaginator()"+++def _build_params(+ config: XenditEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: Optional[str],+) -> dict[str, Any]:+ params: dict[str, Any] = {"limit": PAGE_SIZE, **config.extra_params}++ if not (should_use_incremental_field and db_incremental_field_last_value is not None):+ return params++ # Only the timestamps Xendit filters on server-side may become a query param; anything else+ # would be silently ignored by the API and turn the sync into a disguised full refresh.+ cursor_field = (+ incremental_field+ if incremental_field in config.filterable_timestamps+ else (DEFAULT_INCREMENTAL_FIELD if DEFAULT_INCREMENTAL_FIELD in config.filterable_timestamps else None)+ )+ if cursor_field is not None:+ params[f"{cursor_field}[gte]"] = _format_datetime(db_incremental_field_last_value)++ return params+++def _headers(for_user_id: Optional[str]) -> dict[str, str]:+ # xenPlatform only: scopes the request to one sub-account.+ return {"for-user-id": for_user_id} if for_user_id else {}+++def validate_credentials(api_key: str, path: str, for_user_id: Optional[str] = None) -> tuple[bool, int | None]:+ """Probe one list endpoint and report `(reachable, status_code)`.++ 403 means the key is genuine but lacks that endpoint's permission, so the caller decides+ whether to accept it (source creation) or reject it (per-schema check).+ """+ return validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ f"{XENDIT_BASE_URL}{path}?limit=1",+ headers=_headers(for_user_id) or None,+ auth=HttpBasicAuth(username=api_key, password=""),+ )+++def xendit_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[XenditResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: Optional[str] = None,+ for_user_id: Optional[str] = None,+) -> SourceResponse:+ config = XENDIT_ENDPOINTS[endpoint]+ params = _build_params(config, should_use_incremental_field, db_incremental_field_last_value, incremental_field)++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": XENDIT_BASE_URL,+ "headers": _headers(for_user_id),+ # The secret API key is the Basic auth username, which HttpBasicAuth does not treat as a+ # secret value, so redact it on the session too.+ "session": make_tracked_session(redact_values=(api_key,)),+ "auth": {"type": "http_basic", "username": api_key, "password": ""},+ },+ "resource_defaults": {},+ "resources": [+ {+ "name": endpoint,+ "endpoint": {+ "path": config.path,+ "params": params,+ "data_selector": "data",+ "paginator": XenditCursorPaginator(),+ },+ }+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and resume.after_id:+ initial_paginator_state = {"after_id": resume.after_id}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only when a next page remains, and only after the page was yielded, so a crash+ # re-yields the last page (merge dedupes on id) rather than skipping it.+ if state and state.get("after_id"):+ resumable_source_manager.save_state(XenditResumeConfig(after_id=str(state["after_id"])))++ # Incremental filtering is expressed as static server-side params above, so the framework's own+ # incremental injection is unused here.+ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=["id"],+ 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,+ # Xendit documents these endpoints as "ordered by the created date" without stating a+ # direction, and offers no sort parameter. Declaring "desc" makes the pipeline commit the+ # incremental watermark once a run finishes instead of checkpointing mid-run, which is+ # correct whichever direction the rows actually arrive in.+ sort_mode="desc",+ )