: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 Torii source (#73205)
Tom Owers075ebca767f4
diff --git a/frontend/public/services/torii.png b/frontend/public/services/torii.pngindex a005d8302e46..4bea0628c0c6 100644Binary files a/frontend/public/services/torii.png and b/frontend/public/services/torii.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 7fe27035e342..f434b9214398 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -562,6 +562,7 @@ the row lists both.| tmdb | HTTP | requests | ✅ || todoist | HTTP | requests | ✅ || together_ai | HTTP | requests | ✅ |+| torii | HTTP | requests + `rest_source.RESTClient` | ✅ || travis_ci | HTTP | requests | ✅ || trello | HTTP | requests | ✅ || tremendous | HTTP | requests | ✅ |@@ -1329,7 +1330,6 @@ doesn't conflict with concurrent PRs.- tipalti- toast- toggl-- torii- track_pms- transistor- tremendousdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/torii.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/torii.pyindex d26163d11ff0..0fd605fe206e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/torii.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/torii.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass ToriiSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/torii/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/torii/canonical_descriptions.pynew file mode 100644index 000000000000..76e41c0d1180--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/torii/canonical_descriptions.py@@ -0,0 +1,91 @@+"""Canonical, documentation-sourced descriptions for Torii endpoints and columns.++Sourced from the public Torii API reference (https://developers.toriihq.com). Keyed by the+resource names in `settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced+Torii 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 = {+ "Apps": {+ "description": "A SaaS application discovered in the organization by Torii, with ownership, usage, and vendor metadata.",+ "docs_url": "https://developers.toriihq.com/reference/getapps",+ "columns": {+ "id": "Unique identifier for the app.",+ "name": "Name of the application.",+ "primaryOwner": "The user primarily responsible for the app.",+ "appOwners": "All users assigned as owners of the app.",+ "state": "Lifecycle state of the app (e.g. active, deprecated).",+ "category": "Category Torii has classified the app under.",+ "url": "Homepage or login URL for the app.",+ "imageUrl": "URL of the app's logo.",+ "description": "Short description of the app.",+ "tags": "Tags applied to the app in Torii.",+ "score": "Torii's risk/adoption score for the app.",+ "isCustom": "Whether this is a custom (manually added) app rather than one from Torii's catalog.",+ "addedBy": "The user or source that added the app to Torii.",+ "creationTime": "Time the app record was created in Torii.",+ "isHidden": "Whether the app is hidden from the main app list.",+ "sources": "Data sources (e.g. SSO, expense feeds) that discovered this app.",+ "vendor": "The vendor/company that publishes the app.",+ "activeUsersCount": "Number of currently active users of the app.",+ "lastVisitTime": "Most recent time any user accessed the app.",+ },+ },+ "Users": {+ "description": "A user in the organization tracked by Torii, with role and app-access summary.",+ "docs_url": "https://developers.toriihq.com/reference/getusers",+ "columns": {+ "firstName": "User's first name.",+ "lastName": "User's last name.",+ "email": "User's primary email address.",+ "additionalEmails": "Other email addresses associated with the user.",+ "creationTime": "Time the user record was created in Torii.",+ "idRole": "Identifier of the user's assigned role.",+ "role": "Name of the user's assigned role.",+ "lifecycleStatus": "User's employment lifecycle status: active, offboarding, or offboarded.",+ "isDeletedInIdentitySources": "Whether the user has been removed from the organization's identity sources.",+ "isExternal": "Whether the user is external to the organization.",+ "activeAppsCount": "Number of apps this user is an active user of.",+ },+ },+ "Contracts": {+ "description": "A SaaS contract tracked in Torii, covering renewal and ownership details for an app.",+ "docs_url": "https://developers.toriihq.com/reference/getcontracts",+ "columns": {+ "id": "Unique identifier for the contract.",+ "idApp": "Identifier of the app this contract covers.",+ "name": "Name of the contract.",+ "owner": "The user responsible for the contract.",+ "status": "Current status of the contract.",+ "createdBy": "The user who created the contract record in Torii.",+ },+ },+ "Transactions": {+ "description": "A recognized, mapped expense transaction associated with a SaaS app.",+ "docs_url": "https://developers.toriihq.com/reference/gettransactions",+ "columns": {+ "id": "Unique identifier for the transaction.",+ "idApp": "Identifier of the app this transaction is mapped to.",+ "appName": "Name of the app this transaction is mapped to.",+ "idAppAccount": "Identifier of the specific app account/instance charged.",+ "appAccountName": "Name of the specific app account/instance charged.",+ "fileName": "Name of the source file the transaction was imported from.",+ "transactionDate": "Date the transaction occurred.",+ "amount": "Transaction amount, including original currency value and organization-currency converted value.",+ "source": "System or feed the transaction was sourced from (e.g. a card feed or expense tool).",+ "description": "Free-text description of the transaction.",+ "department": "Department the transaction is attributed to.",+ "domain": "Email or billing domain associated with the transaction.",+ "externalAccountId": "Identifier of the account in the external source system.",+ "externalAccountName": "Name of the account in the external source system.",+ "mappingStatus": "Whether the transaction has been mapped to an app, is unmapped, or archived.",+ "mappingLogic": "Explanation of how the transaction was matched to its app.",+ "reportedByFullName": "Full name of the person who reported/submitted the transaction, if applicable.",+ "idExternalTransaction": "Identifier of the transaction in the external source system.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/torii/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/torii/settings.pynew file mode 100644index 000000000000..21a085dcb821--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/torii/settings.py@@ -0,0 +1,119 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource+from products.warehouse_sources.backend.types import IncrementalField++TORII_BASE_URL = "https://api.toriihq.com/v1.0"+# Contracts only gains cursor pagination, search, sort, and filters under API version 1.1 (the+# default for keys created after Aug 1 2026; older keys default to 1.0). Sending the header+# explicitly on every request pins us to the richer, documented behavior regardless of key age.+TORII_API_VERSION = "1.1"++PAGE_SIZE = 500++ENDPOINTS = (+ "Apps",+ "Users",+ "Contracts",+ "Transactions",+)++# Torii's public API reference documents no server-side "updated since" / "created since" filter on+# any of these list endpoints, so every endpoint is full-refresh only (an empty entry means+# full-refresh — see `build_endpoint_schemas`).+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}++PRIMARY_KEYS: dict[str, list[str]] = {+ "Apps": ["id"],+ "Users": ["id"],+ "Contracts": ["id"],+ "Transactions": ["id"],+}++# Stable, never-changing datetime field to partition each table on. Contracts has no documented+# creation-timestamp field, so it isn't partitioned.+PARTITION_KEYS: dict[str, str | None] = {+ "Apps": "creationTime",+ "Users": "creationTime",+ "Contracts": None,+ "Transactions": "transactionDate",+}++# Explicit field lists (beyond the API's sparse defaults) for the endpoints whose default response+# omits fields a SaaS-spend/governance use case needs. Only fields confirmed in the public API+# reference are listed.+_APP_FIELDS = (+ "id,name,primaryOwner,appOwners,state,category,url,imageUrl,description,tags,score,"+ "isCustom,addedBy,creationTime,isHidden,sources,vendor,activeUsersCount,lastVisitTime"+)++_CONTRACT_FIELDS = "id,idApp,name,owner,status,createdBy"++_TRANSACTION_FIELDS = (+ "id,idApp,appName,idAppAccount,appAccountName,fileName,transactionDate,amount,source,"+ "description,department,domain,externalAccountId,externalAccountName,mappingStatus,"+ "mappingLogic,reportedByFullName,idExternalTransaction"+)+++def get_resource(name: str) -> EndpointResource:+ resources: dict[str, EndpointResource] = {+ "Apps": {+ "name": "Apps",+ "table_name": "apps",+ "write_disposition": "replace",+ "table_format": "delta",+ "endpoint": {+ "data_selector": "apps",+ "path": "/apps",+ "params": {+ "fields": _APP_FIELDS,+ "size": PAGE_SIZE,+ "sort": "creationTime:asc",+ },+ },+ },+ "Users": {+ "name": "Users",+ "table_name": "users",+ "write_disposition": "replace",+ "table_format": "delta",+ "endpoint": {+ "data_selector": "users",+ "path": "/users",+ "params": {+ "size": PAGE_SIZE,+ "sort": "creationTime:asc",+ },+ },+ },+ "Contracts": {+ "name": "Contracts",+ "table_name": "contracts",+ "write_disposition": "replace",+ "table_format": "delta",+ "endpoint": {+ "data_selector": "contracts",+ "path": "/contracts",+ "params": {+ "fields": _CONTRACT_FIELDS,+ "size": PAGE_SIZE,+ "sort": "id:asc",+ },+ },+ },+ "Transactions": {+ "name": "Transactions",+ "table_name": "transactions",+ "write_disposition": "replace",+ "table_format": "delta",+ "endpoint": {+ "data_selector": "transactions",+ "path": "/transactions",+ "params": {+ "fields": _TRANSACTION_FIELDS,+ "size": PAGE_SIZE,+ "sort": "transactionDate:asc",+ },+ },+ },+ }+ return resources[name]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/torii/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/torii/source.pyindex 191be9a109e2..091e21fcb61d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/torii/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/torii/source.py@@ -1,30 +1,129 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.torii import ToriiSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.torii.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.torii.torii import (+ ToriiResumeConfig,+ torii_source,+ validate_credentials as validate_torii_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class ToriiSource(SimpleSource[ToriiSourceConfig]):+class ToriiSource(ResumableSource[ToriiSourceConfig, ToriiResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = ("1.1",)+ default_version = "1.1"+ api_docs_url = "https://developers.toriihq.com"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.TORII+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.toriihq.com": "Your Torii API key is invalid or expired. Please generate a new key from Settings > API Access and reconnect.",+ "403 Client Error: Forbidden for url: https://api.toriihq.com": "Your Torii API key does not have permission to access this resource.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.torii.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: ToriiSourceConfig,+ 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: ToriiSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ if validate_torii_credentials(config.api_key):+ return True, None++ return False, "Invalid credentials"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ToriiResumeConfig]:+ return ResumableSourceManager[ToriiResumeConfig](inputs, ToriiResumeConfig)++ def source_for_pipeline(+ self,+ config: ToriiSourceConfig,+ resumable_source_manager: ResumableSourceManager[ToriiResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return torii_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,+ api_version=self.resolve_api_version(inputs.api_version),+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.TORII,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,label="Torii",+ caption="Import discovered SaaS apps, users, contracts, and spend transactions from Torii.",+ docsUrl="https://posthog.com/docs/cdp/sources/torii",iconPath="/static/services/torii.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ keywords=["saas management", "spend", "licenses", "contracts"],+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ caption="Generate an API key in Torii under **Settings > API Access** (admin permissions required).",+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/torii/tests/test_torii.py b/products/warehouse_sources/backend/temporal/data_imports/sources/torii/tests/test_torii.pynew file mode 100644index 000000000000..ec2dcab66aa6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/torii/tests/test_torii.py@@ -0,0 +1,180 @@+import json+from collections.abc import Iterable+from typing import Any, Optional, cast++import pytest+from unittest import mock++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.torii.settings import (+ ENDPOINTS,+ PARTITION_KEYS,+ PRIMARY_KEYS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.torii.torii import (+ ToriiResumeConfig,+ torii_source,+ validate_credentials,+)++# RESTClient builds its session via make_tracked_session in the rest_client module.+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+# validate_credentials builds its own tracked session in the torii module.+TORII_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.torii.torii.make_tracked_session"+)++_DATA_SELECTOR = {+ "Apps": "apps",+ "Users": "users",+ "Contracts": "contracts",+ "Transactions": "transactions",+}+++def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ return resp+++def _make_manager(resume_cursor: Optional[str] = None) -> mock.MagicMock:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = resume_cursor is not None+ manager.load_state.return_value = ToriiResumeConfig(cursor=resume_cursor) if resume_cursor else None+ return manager+++class TestToriiSourceResumeBehavior:+ """End-to-end pagination/resume behaviour of ``torii_source`` via ``rest_api_resource``."""++ def _drive(+ self, endpoint: str, manager: mock.MagicMock, responses: list[Response]+ ) -> tuple[mock.MagicMock, list[dict[str, Any]]]:+ """Drive ``torii_source`` with a mocked HTTP session.++ Returns ``(mock_session, sent_params)`` where ``sent_params`` is a list of shallow+ copies of ``request.params`` captured at send-time — the underlying Request object is+ mutated in-place by the paginator between pages, so we can't rely on mock+ ``call_args_list`` to preserve history.+ """+ sent_params: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_params.append(dict(request.params or {}))+ return next(response_iter)++ with mock.patch(CLIENT_SESSION_PATCH) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ response = torii_source(+ api_key="test-key",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ api_version="1.1",+ )+ list(cast("Iterable[Any]", response.items()))+ return mock_session, sent_params++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_fresh_run_saves_cursor_after_each_non_terminal_page(self, endpoint: str) -> None:+ manager = _make_manager()+ key = _DATA_SELECTOR[endpoint]++ responses = [+ _make_http_response({key: [{"id": "1"}], "count": 1, "total": 3, "nextCursor": "cursor-1"}),+ _make_http_response({key: [{"id": "2"}], "count": 1, "total": 3, "nextCursor": "cursor-2"}),+ _make_http_response({key: [{"id": "3"}], "count": 1, "total": 3}),+ ]+ _, sent_params = self._drive(endpoint, manager, responses)++ cursors_sent = [p.get("cursor") for p in sent_params]+ assert cursors_sent == [None, "cursor-1", "cursor-2"]++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [+ ToriiResumeConfig(cursor="cursor-1"),+ ToriiResumeConfig(cursor="cursor-2"),+ ]++ def test_resume_seeds_paginator_with_saved_cursor(self) -> None:+ manager = _make_manager(resume_cursor="cursor-resumed")+ responses = [_make_http_response({"apps": [{"id": "only"}]})]+ _, sent_params = self._drive("Apps", manager, responses)++ assert [p.get("cursor") for p in sent_params] == ["cursor-resumed"]+ manager.load_state.assert_called_once()++ def test_terminal_single_page_does_not_save_state(self) -> None:+ manager = _make_manager()+ responses = [_make_http_response({"apps": [{"id": "only"}]})]+ self._drive("Apps", manager, responses)+ manager.save_state.assert_not_called()++ def test_does_not_load_state_when_cannot_resume(self) -> None:+ manager = _make_manager()+ responses = [_make_http_response({"apps": [{"id": "a"}]})]+ self._drive("Apps", manager, responses)+ manager.load_state.assert_not_called()++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_sends_pinned_api_version_header(self, endpoint: str) -> None:+ manager = _make_manager()+ key = _DATA_SELECTOR[endpoint]+ responses = [_make_http_response({key: [{"id": "1"}]})]+ mock_session, _ = self._drive(endpoint, manager, responses)+ assert mock_session.headers == {"X-API-Version": "1.1"}+++class TestToriiSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_response_metadata_per_endpoint(self, MockSession: mock.MagicMock, endpoint: str) -> None:+ manager = _make_manager()++ response = torii_source(+ api_key="test-key",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ api_version="1.1",+ )++ assert response.name == endpoint+ assert response.primary_keys == PRIMARY_KEYS[endpoint]++ partition_key = PARTITION_KEYS[endpoint]+ if partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_format == "month"+ assert response.partition_keys == [partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_format is None+ assert response.partition_keys is None+++class TestValidateCredentials:+ @pytest.mark.parametrize("status_code, expected", [(200, True), (401, False), (403, False), (500, False)])+ @mock.patch(TORII_SESSION_PATCH)+ def test_status_mapping(self, mock_session: mock.MagicMock, status_code: int, expected: bool) -> None:+ response = mock.MagicMock()+ response.status_code = status_code+ mock_session.return_value.get.return_value = response+ assert validate_credentials("test-key") is expected++ @mock.patch(TORII_SESSION_PATCH)+ def test_swallows_exceptions(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("test-key") is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/torii/tests/test_torii_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/torii/tests/test_torii_source.pynew file mode 100644index 000000000000..b270d1e2d8c5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/torii/tests/test_torii_source.py@@ -0,0 +1,141 @@+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.torii import ToriiSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.torii.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.torii.source import ToriiSource+from products.warehouse_sources.backend.temporal.data_imports.sources.torii.torii import ToriiResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestToriiSource:+ def setup_method(self):+ self.source = ToriiSource()+ self.team_id = 123+ self.config = ToriiSourceConfig(api_key="test-key")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.TORII++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Torii"+ assert config.label == "Torii"+ assert config.category is not None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert not config.unreleasedSource+ assert config.iconPath == "/static/services/torii.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.toriihq.com/v1.0/apps",+ "403 Client Error: Forbidden for url: https://api.toriihq.com/v1.0/contracts",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_vendor_error",+ [+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",+ "500 Server Error for url: https://api.toriihq.com/v1.0/users",+ ],+ )+ def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_vendor_error for key in non_retryable_errors)++ def test_get_schemas_covers_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ def test_get_schemas_full_refresh_only(self):+ # Torii's public API reference documents no server-side "updated since" filter on any+ # of these endpoints.+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert all(not schema.supports_incremental for schema in schemas)+ assert all(not schema.supports_append for schema in schemas)+ assert all(schema.incremental_fields == [] for schema in schemas)++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Apps"])+ assert len(schemas) == 1+ assert schemas[0].name == "Apps"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ (True, True, None),+ (False, False, "Invalid credentials"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.torii.source.validate_torii_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with(self.config.api_key)++ def test_get_resumable_source_manager_binds_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is ToriiResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.torii.source.torii_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_torii_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "Apps"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"+ inputs.api_version = None+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_torii_source.assert_called_once()+ kwargs = mock_torii_source.call_args.kwargs+ assert kwargs["api_key"] == "test-key"+ assert kwargs["endpoint"] == "Apps"+ assert kwargs["team_id"] == self.team_id+ assert kwargs["job_id"] == "job-1"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["api_version"] == "1.1"++ def test_resolves_pinned_api_version_when_set(self):+ inputs = mock.MagicMock()+ inputs.schema_name = "Apps"+ inputs.api_version = "1.1"+ manager = mock.MagicMock()++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.torii.source.torii_source"+ ) as mock_torii_source:+ self.source.source_for_pipeline(self.config, manager, inputs)+ assert mock_torii_source.call_args.kwargs["api_version"] == "1.1"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/torii/torii.py b/products/warehouse_sources/backend/temporal/data_imports/sources/torii/torii.pynew file mode 100644index 000000000000..b35584289263--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/torii/torii.py@@ -0,0 +1,88 @@+import dataclasses+from typing import Any, Optional++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.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.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.torii.settings import (+ PARTITION_KEYS,+ PRIMARY_KEYS,+ TORII_BASE_URL,+ get_resource,+)+++class ToriiResumeConfig:+ cursor: str+++def torii_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[ToriiResumeConfig],+ api_version: str,+) -> SourceResponse:+ resource = get_resource(endpoint)++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": TORII_BASE_URL,+ "headers": {"X-API-Version": api_version},+ "auth": {"type": "bearer", "token": api_key},+ "paginator": {"type": "cursor", "cursor_path": "nextCursor", "cursor_param": "cursor"},+ },+ "resources": [resource],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"cursor": resume_config.cursor}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist while there's a next page to resume to; the Redis TTL handles cleanup on+ # completion. Saved after a page is yielded (see rest_api_resource) so a crash re-yields the+ # last page (merge dedupes on the primary key) rather than skipping it.+ if state and state.get("cursor"):+ resumable_source_manager.save_state(ToriiResumeConfig(cursor=str(state["cursor"])))++ result = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ partition_key = PARTITION_KEYS.get(endpoint)++ return SourceResponse(+ name=result.name,+ items=lambda: result,+ primary_keys=PRIMARY_KEYS[endpoint],+ partition_mode="datetime" if partition_key else None,+ partition_format="month" if partition_key else None,+ partition_keys=[partition_key] if partition_key else None,+ column_hints=result.column_hints,+ )+++def validate_credentials(api_key: str) -> bool:+ """Confirm the API key is genuine. GET /orgs/my is the cheapest authenticated call and needs+ no resource-specific scope."""+ ok, _status = validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ f"{TORII_BASE_URL}/orgs/my",+ headers={"Authorization": f"Bearer {api_key}"},+ )+ return ok