Skip to content

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

feat(warehouse): implement xsolla source (#112386)

Tom Owers3d9e434729ba
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index ac3af128676e..8958bd80bad0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -880,6 +880,7 @@ the row lists both.
| wufoo | HTTP | requests | ✅ |
| xendit | HTTP | requests + `rest_source.RESTClient` | ✅ |
| xmatters | HTTP | requests | ✅ |
+| xsolla | HTTP | requests + `rest_source.RESTClient` | ✅ |
| ynab | HTTP | requests + `rest_source.RESTClient` | ✅ |
| yoco | HTTP | requests + `rest_source.RESTClient` | ✅ |
| yousign | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
@@ -1502,7 +1503,6 @@ doesn't conflict with concurrent PRs.
- wps_office
- wufoo
- xero
-- xsolla
- yahoo_finance
- yandex_metrica
- yotpo
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/xsolla.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/xsolla.py
index f7f7063ca728..87a27c3653cd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/xsolla.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/xsolla.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class XsollaSourceConfig(config.Config):
- pass
+ merchant_id: str
+ api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/canonical_descriptions.py
new file mode 100644
index 000000000000..6534c1a79306
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/canonical_descriptions.py
@@ -0,0 +1,127 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+PAY_STATION_DOCS = "https://developers.xsolla.com/api/pay-station/"
+SUBSCRIPTIONS_DOCS = "https://developers.xsolla.com/api/subscriptions/"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "transactions": {
+ "description": "Payments made in your games, including payments that did not complete.",
+ "docs_url": "https://developers.xsolla.com/api/pay-station/operation/find-transactions/",
+ "columns": {
+ "id": "Xsolla transaction ID, copied from transaction.id.",
+ "create_date": "Date and time when the transaction was created, copied from transaction.create_date.",
+ "transaction": "Transaction data: project, payment method, status, external ID, and dates.",
+ "user": "User details: ID, name, email, phone, and country.",
+ "payment_details": "Amounts, currencies, fees, and taxes for the payment and the payout.",
+ "purchase": "Purchased virtual currency, virtual items, subscription, or simple checkout amount.",
+ "payment_system": "Payment system that processed the transaction.",
+ },
+ },
+ "subscriptions": {
+ "description": "Subscriptions across all projects of the merchant.",
+ "docs_url": "https://developers.xsolla.com/api/subscriptions/operation/get-subscriptions/",
+ "columns": {
+ "id": "Subscription ID.",
+ "status": "Subscription status.",
+ "user": "User who owns the subscription.",
+ "plan": "Subscription plan and the project it belongs to.",
+ "product": "Product the plan is linked to.",
+ "charge_amount": "Billing amount.",
+ "currency": "Currency of the purchase. Three-letter currency code per ISO 4217.",
+ "date_create": "Subscription creation date.",
+ "date_end": "Subscription end date.",
+ "date_last_charge": "Last subscription charge date.",
+ "date_next_charge": "Next subscription charge date.",
+ "comment": "Reason for changing the subscription status.",
+ },
+ },
+ "subscription_payments": {
+ "description": "Subscription charges for each project.",
+ "docs_url": SUBSCRIPTIONS_DOCS,
+ "columns": {
+ "id": "Subscription payment ID.",
+ "project_id": "ID of the project that the payment belongs to.",
+ "id_payment": "Xsolla transaction ID of the charge.",
+ "status": "Transaction status: done or fail.",
+ "date_payment": "Date and time of the charge.",
+ "subscription": "Subscription that was charged, with its plan.",
+ },
+ },
+ "subscription_plans": {
+ "description": "Subscription plans for each project.",
+ "docs_url": SUBSCRIPTIONS_DOCS,
+ "columns": {
+ "id": "Subscription plan ID.",
+ "project_id": "ID of the project that the plan belongs to.",
+ "external_id": "Plan external ID.",
+ "name": "Localized plan names.",
+ "localized_name": "Plan name in the default locale.",
+ "description": "Localized plan descriptions.",
+ "charge": "Charge amount, currency, billing period, and prices in other currencies.",
+ "trial": "Trial period.",
+ "grace_period": "Grace period.",
+ "expiration": "Plan expiration period.",
+ "status": "Plan status.",
+ "group_id": "Group ID that the plan is linked to.",
+ "tags": "Plan tags.",
+ },
+ },
+ "subscription_products": {
+ "description": "Subscription products for each project.",
+ "docs_url": SUBSCRIPTIONS_DOCS,
+ "columns": {
+ "id": "Product ID.",
+ "project_id": "ID of the project that the product belongs to.",
+ "name": "Product name.",
+ "description": "Localized product descriptions.",
+ "group_id": "Group ID that the product is linked to.",
+ },
+ },
+ "payouts": {
+ "description": "Payouts from Xsolla to the merchant.",
+ "docs_url": "https://developers.xsolla.com/api/pay-station/operation/get-payouts/",
+ "columns": {
+ "id": "Payout ID, copied from payout.id.",
+ "payout": "Payout ID, date, note, and currency.",
+ "transfer": "Bank transfer date, note, and currency.",
+ "rate": "Exchange rate between the payout currency and the transfer currency.",
+ "canceled": "Whether the payout was canceled.",
+ },
+ },
+ "reports": {
+ "description": "Monthly financial reports for the merchant.",
+ "docs_url": "https://developers.xsolla.com/api/pay-station/operation/get-reports/",
+ "columns": {
+ "report_id": "Financial report ID.",
+ "agreement_document_id": "ID of the agreement document that the report belongs to.",
+ "currency": "Report currency.",
+ "month": "Report month.",
+ "year": "Report year.",
+ "is_direct_payout": "Whether the report is for a direct payout.",
+ "is_draft_by_agreement": "Whether the report is a draft under the agreement.",
+ },
+ },
+ "promotions": {
+ "description": "Promotions configured for the merchant's projects.",
+ "docs_url": SUBSCRIPTIONS_DOCS,
+ "columns": {
+ "id": "Promotion ID.",
+ "technical_name": "Promotion technical name.",
+ "project": "Project that the promotion belongs to.",
+ "datetime": "Start and end of the promotion.",
+ "enabled": "Whether the promotion is enabled.",
+ "is_active": "Whether the promotion is currently active.",
+ "is_infinite": "Whether the promotion has no end date.",
+ "read_only": "Whether the promotion is read-only.",
+ },
+ },
+ "projects": {
+ "description": "Projects in the merchant's Publisher Account.",
+ "docs_url": PAY_STATION_DOCS,
+ "columns": {
+ "id": "Project ID.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/settings.py
new file mode 100644
index 000000000000..f3c082af4e22
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/settings.py
@@ -0,0 +1,99 @@
+from datetime import date
+from typing import Literal
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseAction
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+API_BASE_URL = "https://api.xsolla.com/merchant"
+API_DOCS_URL = "https://developers.xsolla.com/api/getting-started/"
+PAGE_SIZE = 100
+# Xsolla has no endpoint that reports when a merchant's history starts, so date-bounded endpoints
+# walk forward from a fixed date that predates Pay Station.
+HISTORY_START = date(2010, 1, 1)
+# Incremental transaction syncs read this many days again. This catches status changes on recent
+# transactions, and rows that arrived out of order inside the last window.
+TRANSACTIONS_LOOKBACK_DAYS = 7
+
+AUTH_ERROR = "Xsolla rejected the credentials. Check the merchant ID and the company API key."
+RESPONSE_ACTIONS: list[ResponseAction] = [
+ {"status_code": 401, "action": "raise", "message": AUTH_ERROR},
+ {"status_code": 403, "action": "raise", "message": AUTH_ERROR},
+]
+
+
+@frozen
+class XsollaEndpoint:
+ path: str
+ primary_keys: tuple[str, ...] = ("id",)
+ # Project endpoints are read once per project that the merchant owns.
+ scope: Literal["merchant", "project"] = "merchant"
+ paginated: bool = True
+ # Endpoints that need datetime_from/datetime_to are read in windows of this many days.
+ window_days: int | None = None
+ # Nested values copied to the row root, so that they can be primary keys or incremental fields.
+ lifted_fields: tuple[tuple[str, str, str], ...] = ()
+ partition_key: str | None = None
+
+
+ENDPOINTS: dict[str, XsollaEndpoint] = {
+ "transactions": XsollaEndpoint(
+ path="merchants/{merchant_id}/reports/transactions/search.json",
+ window_days=7,
+ lifted_fields=(("id", "transaction", "id"), ("create_date", "transaction", "create_date")),
+ partition_key="create_date",
+ ),
+ "subscriptions": XsollaEndpoint(
+ path="merchants/{merchant_id}/subscriptions",
+ partition_key="date_create",
+ ),
+ "subscription_payments": XsollaEndpoint(
+ path="projects/{project_id}/subscriptions/payments",
+ primary_keys=("project_id", "id"),
+ scope="project",
+ partition_key="date_payment",
+ ),
+ "subscription_plans": XsollaEndpoint(
+ path="projects/{project_id}/subscriptions/plans",
+ primary_keys=("project_id", "id"),
+ scope="project",
+ ),
+ "subscription_products": XsollaEndpoint(
+ path="projects/{project_id}/subscriptions/products",
+ primary_keys=("project_id", "id"),
+ scope="project",
+ ),
+ "payouts": XsollaEndpoint(
+ path="merchants/{merchant_id}/reports/transfers",
+ paginated=False,
+ # Xsolla rejects report periods longer than 92 days.
+ window_days=92,
+ lifted_fields=(("id", "payout", "id"),),
+ ),
+ "reports": XsollaEndpoint(
+ path="merchants/{merchant_id}/reports",
+ primary_keys=("report_id",),
+ paginated=False,
+ window_days=92,
+ ),
+ "promotions": XsollaEndpoint(
+ path="merchants/{merchant_id}/promotions",
+ paginated=False,
+ ),
+ "projects": XsollaEndpoint(
+ path="merchants/{merchant_id}/projects",
+ paginated=False,
+ ),
+}
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "transactions": [
+ {
+ "label": "create_date",
+ "type": IncrementalFieldType.DateTime,
+ "field": "create_date",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ],
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/source.py
index 7c733b888cd7..28f1d52c2711 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/source.py
@@ -1,25 +1,141 @@
from typing import cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+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, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.xsolla import XsollaSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.xsolla.settings import (
+ API_DOCS_URL,
+ AUTH_ERROR,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.xsolla.xsolla import (
+ MERCHANT_ID_ERROR,
+ XsollaResumeConfig,
+ validate_credentials as validate_xsolla_credentials,
+ xsolla_source,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class XsollaSource(SimpleSource[XsollaSourceConfig]):
+class XsollaSource(ResumableSource[XsollaSourceConfig, XsollaResumeConfig]):
+ lists_tables_without_credentials = True
+ # The version is the path segment after /merchant. The endpoints this source reads are on v2.
+ supported_versions = ("v2",)
+ default_version = "v2"
+ api_docs_url = API_DOCS_URL
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.XSOLLA
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ AUTH_ERROR: AUTH_ERROR,
+ MERCHANT_ID_ERROR: MERCHANT_ID_ERROR,
+ "401 Client Error": AUTH_ERROR,
+ "403 Client Error": AUTH_ERROR,
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.xsolla.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: XsollaSourceConfig,
+ 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, merge_only={"transactions"})
+
+ def validate_credentials(
+ self,
+ config: XsollaSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_xsolla_credentials(config, self.resolve_api_version(api_version))
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[XsollaResumeConfig]:
+ return ResumableSourceManager[XsollaResumeConfig](inputs, XsollaResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: XsollaSourceConfig,
+ resumable_source_manager: ResumableSourceManager[XsollaResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return xsolla_source(
+ config=config,
+ endpoint_name=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ manager=resumable_source_manager,
+ api_version=self.resolve_api_version(inputs.api_version),
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.XSOLLA,
category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
label="Xsolla",
+ caption=(
+ "Connect your Xsolla merchant account. Find the merchant ID in "
+ "[Publisher Account](https://publisher.xsolla.com/) under **Company settings > Company**. "
+ "Create the API key under **Company settings > API keys**. "
+ "Use a company API key, because a project API key cannot read merchant reports. "
+ "Incremental transaction syncs read the last seven days again to collect status changes."
+ ),
+ docsUrl="https://posthog.com/docs/cdp/sources/xsolla",
iconPath="/static/services/xsolla.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="merchant_id",
+ label="Merchant ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="123456",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/tests/test_xsolla.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/tests/test_xsolla.py
new file mode 100644
index 000000000000..20a5dd4ab1d1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/tests/test_xsolla.py
@@ -0,0 +1,208 @@
+from collections.abc import Iterable, Iterator
+from datetime import UTC, datetime
+from typing import Any
+
+import pytest
+import time_machine
+from unittest.mock import MagicMock, patch
+
+import requests_mock
+from requests import Session
+
+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.generated_configs.xsolla import XsollaSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.xsolla.settings import AUTH_ERROR
+from products.warehouse_sources.backend.temporal.data_imports.sources.xsolla.xsolla import (
+ MERCHANT_ID_ERROR,
+ XsollaResumeConfig,
+ validate_credentials,
+ xsolla_source,
+)
+
+BASE = "https://api.xsolla.com/merchant/v2"
+SEARCH_URL = f"{BASE}/merchants/123/reports/transactions/search.json"
+
+
+def rows_of(response: SourceResponse) -> list[dict[str, Any]]:
+ items = response.items()
+ assert isinstance(items, Iterable)
+ return [row for page in items for row in page]
+
+
+def transaction(transaction_id: int, created: str) -> dict[str, Any]:
+ return {"transaction": {"id": transaction_id, "create_date": created, "status": "done"}, "user": {"id": "u1"}}
+
+
[email protected](autouse=True)
+def fixed_clock() -> Iterator[None]:
+ with time_machine.travel("2010-01-20T12:00:00Z", tick=False):
+ yield
+
+
+def http() -> Iterator[requests_mock.Mocker]:
+ with (
+ requests_mock.Mocker() as mock,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session",
+ side_effect=lambda **kwargs: Session(),
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.xsolla.xsolla.make_tracked_session",
+ side_effect=lambda **kwargs: Session(),
+ ),
+ ):
+ yield mock
+
+
+def config() -> XsollaSourceConfig:
+ return XsollaSourceConfig(merchant_id="123", api_key="test-xsolla-key")
+
+
+def manager() -> MagicMock:
+ mock = MagicMock(spec=ResumableSourceManager)
+ mock.can_resume.return_value = False
+ return mock
+
+
+def test_transactions_walk_every_window_and_page(
+ http: requests_mock.Mocker, config: XsollaSourceConfig, manager: MagicMock
+) -> None:
+ first_window = [transaction(i, "2010-01-02T10:00:00+00:00") for i in range(100)]
+ last_window = [transaction(500, "2010-01-19T10:00:00+00:00")]
+
+ def page(request: Any, context: Any) -> list[dict[str, Any]]:
+ window = request.qs["datetime_from"][0]
+ offset = int(request.qs["offset"][0])
+ if window.startswith("2010-01-01"):
+ return first_window[offset : offset + 100]
+ if window.startswith("2010-01-15"):
+ return last_window[offset : offset + 100]
+ return []
+
+ http.get(SEARCH_URL, json=page)
+ rows = rows_of(xsolla_source(config, "transactions", 1, "job", manager, "v2"))
+
+ assert [row["id"] for row in rows] == [*range(100), 500]
+ assert rows[-1]["create_date"] == "2010-01-19T10:00:00+00:00"
+ requested = [(r.qs["datetime_from"][0], r.qs["datetime_to"][0], r.qs["offset"][0]) for r in http.request_history]
+ assert requested == [
+ ("2010-01-01t00:00:00z", "2010-01-07t23:59:59z", "0"),
+ ("2010-01-01t00:00:00z", "2010-01-07t23:59:59z", "100"),
+ ("2010-01-08t00:00:00z", "2010-01-14t23:59:59z", "0"),
+ ("2010-01-15t00:00:00z", "2010-01-20t23:59:59z", "0"),
+ ]
+ assert http.request_history[0].headers["Authorization"].startswith("Basic ")
+
+
+ "use_incremental,watermark,expected_start",
+ [
+ (False, None, "2010-01-01t00:00:00z"),
+ (True, None, "2010-01-01t00:00:00z"),
+ (True, datetime(2010, 1, 18, 9, tzinfo=UTC), "2010-01-11t00:00:00z"),
+ (True, "2010-01-18T09:00:00Z", "2010-01-11t00:00:00z"),
+ ],
+)
+def test_transactions_start_window(
+ http: requests_mock.Mocker,
+ config: XsollaSourceConfig,
+ manager: MagicMock,
+ use_incremental: bool,
+ watermark: Any,
+ expected_start: str,
+) -> None:
+ http.get(SEARCH_URL, json=[])
+
+ rows_of(
+ xsolla_source(
+ config,
+ "transactions",
+ 1,
+ "job",
+ manager,
+ "v2",
+ should_use_incremental_field=use_incremental,
+ db_incremental_field_last_value=watermark,
+ )
+ )
+
+ assert http.request_history[0].qs["datetime_from"][0] == expected_start
+
+
+def test_transactions_resume_from_saved_window_and_offset(
+ http: requests_mock.Mocker, config: XsollaSourceConfig, manager: MagicMock
+) -> None:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = XsollaResumeConfig(window_start="2010-01-08", offset=200)
+ http.get(SEARCH_URL, json=[])
+
+ rows_of(xsolla_source(config, "transactions", 1, "job", manager, "v2"))
+
+ first = http.request_history[0]
+ assert (first.qs["datetime_from"][0], first.qs["offset"][0]) == ("2010-01-08t00:00:00z", "200")
+ assert manager.save_state.call_args_list[-1].args[0] == XsollaResumeConfig(window_start="2010-01-21")
+
+
+def test_project_tables_read_each_project_and_resume_after_finished_projects(
+ http: requests_mock.Mocker, config: XsollaSourceConfig, manager: MagicMock
+) -> None:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = XsollaResumeConfig(project_id=20)
+ http.get(f"{BASE}/merchants/123/projects", json=[{"id": 30}, {"id": 10}, {"id": 20}])
+ http.get(f"{BASE}/projects/20/subscriptions/products", json=[{"id": 1, "name": "VIP"}])
+ http.get(f"{BASE}/projects/30/subscriptions/products", json=[{"id": 1, "name": "Pass"}])
+
+ response = xsolla_source(config, "subscription_products", 1, "job", manager, "v2")
+ rows = rows_of(response)
+
+ assert [(row["project_id"], row["id"], row["name"]) for row in rows] == [(20, 1, "VIP"), (30, 1, "Pass")]
+ assert response.primary_keys == ["project_id", "id"]
+ assert not any("/projects/10/" in request.url for request in http.request_history)
+ assert manager.save_state.call_args_list[-1].args[0] == XsollaResumeConfig(project_id=31)
+
+
+def test_report_windows_drop_rows_already_seen_in_an_earlier_window(
+ http: requests_mock.Mocker, config: XsollaSourceConfig, manager: MagicMock
+) -> None:
+ with time_machine.travel("2010-06-01T12:00:00Z", tick=False):
+ http.get(
+ f"{BASE}/merchants/123/reports/transfers",
+ json=[{"payout": {"id": 7, "date": "2010-03-31T00:00:00+00:00"}, "canceled": 0}],
+ )
+ rows = rows_of(xsolla_source(config, "payouts", 1, "job", manager, "v2"))
+
+ assert len(http.request_history) == 2
+ assert [row["id"] for row in rows] == [7]
+
+
+def test_sync_raises_actionable_error_on_rejected_credentials(
+ http: requests_mock.Mocker, config: XsollaSourceConfig, manager: MagicMock
+) -> None:
+ http.get(f"{BASE}/merchants/123/promotions", status_code=401, json={"message": "Unauthorized"})
+
+ with pytest.raises(Exception, match=AUTH_ERROR):
+ rows_of(xsolla_source(config, "promotions", 1, "job", manager, "v2"))
+
+
+ "merchant_id,status,expected",
+ [
+ ("123", 200, (True, None)),
+ ("123", 401, (False, AUTH_ERROR)),
+ ("123", 403, (False, AUTH_ERROR)),
+ ("123", 500, (False, "Xsolla returned an unexpected response (HTTP 500). Try again later.")),
+ ("123.evil.example", 200, (False, MERCHANT_ID_ERROR)),
+ ],
+)
+def test_validate_credentials(
+ http: requests_mock.Mocker, merchant_id: str, status: int, expected: tuple[bool, str | None]
+) -> None:
+ http.get(f"{BASE}/merchants/123/projects", status_code=status, json=[])
+
+ result = validate_credentials(XsollaSourceConfig(merchant_id=merchant_id, api_key="test-xsolla-key"), "v2")
+
+ assert result == expected
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/xsolla.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/xsolla.py
new file mode 100644
index 000000000000..8745edb129db
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/xsolla.py
@@ -0,0 +1,279 @@
+from collections.abc import Callable, Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any
+
+from posthog.dataclasses import frozen
+
+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.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.generated_configs.xsolla import XsollaSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.xsolla.settings import (
+ API_BASE_URL,
+ AUTH_ERROR,
+ ENDPOINTS,
+ HISTORY_START,
+ PAGE_SIZE,
+ RESPONSE_ACTIONS,
+ TRANSACTIONS_LOOKBACK_DAYS,
+ XsollaEndpoint,
+)
+
+MERCHANT_ID_ERROR = "Enter the merchant ID as a number. You can find it in Publisher Account under Company settings."
+
+
+@frozen
+class XsollaResumeConfig:
+ window_start: str | None = None
+ project_id: int | None = None
+ offset: int = 0
+
+
+def parse_merchant_id(merchant_id: str) -> str:
+ merchant_id = merchant_id.strip()
+ if not merchant_id.isascii() or not merchant_id.isdigit():
+ raise ValueError(MERCHANT_ID_ERROR)
+ return merchant_id
+
+
+def validate_credentials(config: XsollaSourceConfig, api_version: str) -> tuple[bool, str | None]:
+ try:
+ merchant_id = parse_merchant_id(config.merchant_id)
+ except ValueError as error:
+ return False, str(error)
+
+ session = make_tracked_session(redact_values=(config.api_key,))
+ response = session.get(
+ f"{API_BASE_URL}/{api_version}/merchants/{merchant_id}/projects",
+ auth=(merchant_id, config.api_key),
+ timeout=30,
+ )
+ if response.status_code == 200:
+ return True, None
+ if response.status_code in (401, 403):
+ return False, AUTH_ERROR
+ return False, f"Xsolla returned an unexpected response (HTTP {response.status_code}). Try again later."
+
+
+def _rest_config(
+ config: XsollaSourceConfig,
+ merchant_id: str,
+ name: str,
+ endpoint: XsollaEndpoint,
+ path: str,
+ params: dict[str, Any],
+ api_version: str,
+ data_map: Callable[[dict[str, Any]], dict[str, Any]] | None,
+) -> RESTAPIConfig:
+ return {
+ "client": {
+ "base_url": f"{API_BASE_URL}/{api_version}/",
+ "auth": {"type": "http_basic", "username": merchant_id, "password": config.api_key},
+ "paginator": {"type": "offset", "limit": PAGE_SIZE, "total_path": None}
+ if endpoint.paginated
+ else "single_page",
+ },
+ "resources": [
+ {
+ "name": name,
+ "table_name": name,
+ "endpoint": {
+ "path": path,
+ "params": params,
+ "response_actions": RESPONSE_ACTIONS,
+ # The projects list shape is not documented, so only the documented list endpoints fail loud.
+ "data_selector_required": name != "projects",
+ },
+ "table_format": "delta",
+ "data_map": data_map,
+ }
+ ],
+ }
+
+
+def _row_mapper(endpoint: XsollaEndpoint, project_id: int | None) -> Callable[[dict[str, Any]], dict[str, Any]] | None:
+ if not endpoint.lifted_fields and project_id is None:
+ return None
+
+ def map_row(row: dict[str, Any]) -> dict[str, Any]:
+ for target, parent, child in endpoint.lifted_fields:
+ nested = row.get(parent)
+ row[target] = nested.get(child) if isinstance(nested, dict) else None
+ if project_id is not None:
+ row["project_id"] = project_id
+ return row
+
+ return map_row
+
+
+def _watermark_date(value: Any) -> date | None:
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ return value.date()
+ if isinstance(value, date):
+ return value
+ return datetime.fromisoformat(str(value).replace("Z", "+00:00")).date()
+
+
+def _window_params(name: str, window_start: date, window_end: date) -> dict[str, str]:
+ if name == "transactions":
+ # Transaction search accepts ISO 8601 date-times, so adjacent windows never overlap.
+ return {
+ "datetime_from": f"{window_start.isoformat()}T00:00:00Z",
+ "datetime_to": f"{window_end.isoformat()}T23:59:59Z",
+ "type": "all",
+ }
+ # Report endpoints accept YYYY-MM-DD only.
+ return {"datetime_from": window_start.isoformat(), "datetime_to": window_end.isoformat()}
+
+
+def list_project_ids(
+ config: XsollaSourceConfig, merchant_id: str, team_id: int, job_id: str, api_version: str
+) -> list[int]:
+ endpoint = ENDPOINTS["projects"]
+ resource = rest_api_resource(
+ _rest_config(
+ config,
+ merchant_id,
+ "projects",
+ endpoint,
+ endpoint.path.format(merchant_id=merchant_id),
+ {},
+ api_version,
+ None,
+ ),
+ team_id,
+ job_id,
+ None,
+ )
+ return sorted({int(project["id"]) for page in resource for project in page if project.get("id") is not None})
+
+
+def xsolla_source(
+ config: XsollaSourceConfig,
+ endpoint_name: str,
+ team_id: int,
+ job_id: str,
+ manager: ResumableSourceManager[XsollaResumeConfig],
+ api_version: str,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> SourceResponse:
+ endpoint = ENDPOINTS.get(endpoint_name)
+ if endpoint is None:
+ raise ValueError(f"Unknown Xsolla table: {endpoint_name}. Select a table from the source configuration.")
+ merchant_id = parse_merchant_id(config.merchant_id)
+
+ start = HISTORY_START
+ watermark = _watermark_date(db_incremental_field_last_value) if should_use_incremental_field else None
+ if watermark is not None:
+ start = max(start, watermark - timedelta(days=TRANSACTIONS_LOOKBACK_DAYS))
+
+ def read(
+ path: str, params: dict[str, Any], project_id: int | None, offset: int, save: Callable[[int | None], None]
+ ) -> Iterator[list[dict[str, Any]]]:
+ def resume_hook(paginator_state: dict[str, Any] | None) -> None:
+ save(int(paginator_state["offset"]) if paginator_state else None)
+ manager.safe_point()
+
+ yield from rest_api_resource(
+ _rest_config(
+ config,
+ merchant_id,
+ endpoint_name,
+ endpoint,
+ path,
+ params,
+ api_version,
+ _row_mapper(endpoint, project_id),
+ ),
+ team_id,
+ job_id,
+ None,
+ resume_hook=resume_hook,
+ initial_paginator_state={"offset": offset} if endpoint.paginated else None,
+ )
+
+ def windowed_items(state: XsollaResumeConfig) -> Iterator[list[dict[str, Any]]]:
+ assert endpoint.window_days is not None
+ path = endpoint.path.format(merchant_id=merchant_id)
+ today = datetime.now(UTC).date()
+ window_start = date.fromisoformat(state.window_start) if state.window_start else start
+ offset = state.offset
+ # Report windows can return the same payout or report twice, and these tables stay small.
+ seen: set[tuple[Any, ...]] = set()
+
+ while window_start <= today:
+ window_end = min(window_start + timedelta(days=endpoint.window_days - 1), today)
+ next_start = window_end + timedelta(days=1)
+
+ def save(next_offset: int | None, current: date = window_start, following: date = next_start) -> None:
+ if next_offset is None:
+ manager.save_state(XsollaResumeConfig(window_start=following.isoformat()))
+ else:
+ manager.save_state(XsollaResumeConfig(window_start=current.isoformat(), offset=next_offset))
+
+ for page in read(path, _window_params(endpoint_name, window_start, window_end), None, offset, save):
+ if endpoint.paginated:
+ yield page
+ continue
+ rows = []
+ for row in page:
+ key = tuple(row.get(field) for field in endpoint.primary_keys)
+ if None in key or key not in seen:
+ seen.add(key)
+ rows.append(row)
+ if rows:
+ yield rows
+
+ window_start = next_start
+ offset = 0
+
+ def project_items(state: XsollaResumeConfig) -> Iterator[list[dict[str, Any]]]:
+ for project_id in list_project_ids(config, merchant_id, team_id, job_id, api_version):
+ if state.project_id is not None and project_id < state.project_id:
+ continue
+ offset = state.offset if project_id == state.project_id else 0
+
+ def save(next_offset: int | None, current: int = project_id) -> None:
+ if next_offset is None:
+ # Project IDs are read in ascending order, so the next run starts after this project.
+ manager.save_state(XsollaResumeConfig(project_id=current + 1))
+ else:
+ manager.save_state(XsollaResumeConfig(project_id=current, offset=next_offset))
+
+ yield from read(endpoint.path.format(project_id=project_id), {}, project_id, offset, save)
+
+ def items() -> Iterator[list[dict[str, Any]]]:
+ state = (manager.load_state() if manager.can_resume() else None) or XsollaResumeConfig()
+ if endpoint.scope == "project":
+ yield from project_items(state)
+ elif endpoint.window_days is not None:
+ yield from windowed_items(state)
+ else:
+ yield from read(
+ endpoint.path.format(merchant_id=merchant_id),
+ {},
+ None,
+ state.offset,
+ lambda next_offset: (
+ manager.save_state(XsollaResumeConfig(offset=next_offset)) if next_offset is not None else None
+ ),
+ )
+
+ return SourceResponse(
+ name=endpoint_name,
+ items=items,
+ primary_keys=list(endpoint.primary_keys),
+ # Xsolla does not document the order of rows inside a window. The pipeline stores the
+ # watermark of a "desc" source only after the sync completes.
+ sort_mode="desc",
+ partition_keys=[endpoint.partition_key] if endpoint.partition_key else None,
+ partition_mode="datetime" if endpoint.partition_key else None,
+ partition_format="month" if endpoint.partition_key else None,
+ )