: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 Vendr import source (#84453)
Tom Owersa893b82f7f8b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/vendr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/vendr.pyindex 405f2a9244ff..efa5c131d383 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/vendr.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/vendr.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass VendrSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vendr/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vendr/canonical_descriptions.pynew file mode 100644index 000000000000..54a7911fdfa2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vendr/canonical_descriptions.py@@ -0,0 +1,67 @@+"""Canonical, documentation-sourced descriptions for Vendr endpoints and columns.++Sourced from the official Vendr developer docs (https://developers.vendr.com/api/catalog-api).+Keyed by the resource names in `settings.py` `VENDR_ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced Vendr table. Columns absent here fall back to LLM+enrichment - the docs page renders parameter/response schemas without expandable nested object+fields (e.g. `pagination`, `category`, `defaultPriceRange`), so coverage here is intentionally+partial rather than guessed.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Companies": {+ "description": "A software vendor in Vendr's catalog, with the product families and products it sells.",+ "docs_url": "https://developers.vendr.com/api/catalog-api",+ "columns": {+ "id": "Unique identifier for the company.",+ "name": "Display name of the company.",+ "legalName": "Company's registered legal name.",+ "domain": "Primary domain of the company's website.",+ "description": "Description of the company and what it sells.",+ "discontinued": "Whether the company (and its products) is discontinued.",+ "lastUpdatedAt": "Time the catalog entry was last updated by Vendr.",+ "url": "URL of the company's website.",+ "icon": "URL of the company's logo.",+ "fiscalYearEnd": "Month the company's fiscal year ends.",+ "realPurchaseCount": "Number of real, verified purchases behind this catalog entry.",+ },+ },+ "Categories": {+ "description": "A product category in Vendr's catalog, used to classify companies and products.",+ "docs_url": "https://developers.vendr.com/api/catalog-api",+ "columns": {+ "id": "Unique identifier for the category.",+ "name": "Display name of the category.",+ },+ },+ "ProductFamilies": {+ "description": "A group of related products sold by the same company (e.g. editions of one product line).",+ "docs_url": "https://developers.vendr.com/api/catalog-api",+ "columns": {+ "id": "Unique identifier for the product family.",+ "name": "Display name of the product family.",+ "lastUpdatedAt": "Time the catalog entry was last updated by Vendr.",+ "company_id": "Identifier of the company this product family belongs to.",+ },+ },+ "Products": {+ "description": "A single product sold by a company, with its pricing tiers and add-ons.",+ "docs_url": "https://developers.vendr.com/api/catalog-api",+ "columns": {+ "id": "Unique identifier for the product.",+ "name": "Display name of the product.",+ "description": "Description of the product.",+ "isCustomEstimateAvailable": "Whether a custom price estimate is available for this product via the Pricing API.",+ "lastUpdatedAt": "Time the catalog entry was last updated by Vendr.",+ "productFamilyId": "Identifier of the product family this product belongs to, if any.",+ "icon": "URL of the product's icon.",+ "url": "URL of the product's page.",+ "currency": "Currency of the product's default price.",+ "company_id": "Identifier of the company this product belongs to.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vendr/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vendr/settings.pynew file mode 100644index 000000000000..2f22af9608e3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vendr/settings.py@@ -0,0 +1,83 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.types import IncrementalField++# Vendr's documented maximum page size for every list endpoint (default is 10 if unset).+PAGE_SIZE = 100+++# frozen=False: VendrEndpointConfig is passed as `endpoint_configs: Mapping[str, FanoutEndpointLike]`,+# and mypy treats a frozen dataclass's fields as read-only, which is incompatible with that+# Protocol's plain (read-write) attributes.+@dataclass(frozen=False)+class VendrEndpointConfig:+ name: str+ path: str+ primary_keys: list[str]+ # Value for this endpoint's own `sortBy` enum. The accepted values differ per endpoint+ # (Companies/Categories: "name"; the two company-scoped lists: "name" or "sortOrder"), so+ # it's declared per endpoint rather than shared, and always sent explicitly so page+ # boundaries stay stable even if Vendr changes an implicit default.+ sort_by: str+ page_size: int = PAGE_SIZE+ # Required by the shared fan-out helper's `FanoutEndpointLike` protocol. Vendr's catalog API+ # documents no updated-since/created-since filter on any endpoint, so every table here is+ # full refresh.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+ fanout: DependentEndpointConfig | None = None+++# Product families and products both hang off a company and are fetched with the company's `id`+# bound into the `{companyId}` path placeholder. Vendr's single-resource lookups+# (`GET /v1/catalog/product-families/{id}`, `GET /v1/catalog/products/{id}`) take no company+# context at all, which confirms `id` is a global identifier — so the child tables key on `id`+# alone rather than a `(company_id, id)` composite.+_COMPANIES_FANOUT = DependentEndpointConfig(+ parent_name="Companies",+ resolve_param="companyId",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "company_id"},+ # Companies' own `sortBy` enum only accepts "name" - pin it explicitly rather than relying+ # on the (currently identical) implicit default.+ parent_params={"sortBy": "name", "sortOrder": "asc"},+)++VENDR_ENDPOINTS: dict[str, VendrEndpointConfig] = {+ "Companies": VendrEndpointConfig(+ name="Companies",+ path="/v1/catalog/companies",+ primary_keys=["id"],+ sort_by="name",+ ),+ "Categories": VendrEndpointConfig(+ name="Categories",+ path="/v1/catalog/categories",+ primary_keys=["id"],+ sort_by="name",+ ),+ "ProductFamilies": VendrEndpointConfig(+ name="ProductFamilies",+ path="/v1/catalog/companies/{companyId}/product-families",+ primary_keys=["id"],+ sort_by="sortOrder",+ fanout=_COMPANIES_FANOUT,+ ),+ "Products": VendrEndpointConfig(+ name="Products",+ path="/v1/catalog/companies/{companyId}/products",+ primary_keys=["id"],+ sort_by="sortOrder",+ fanout=_COMPANIES_FANOUT,+ ),+}++ENDPOINTS = tuple(VENDR_ENDPOINTS)++# No endpoint documents a server-side updated-since/created-since filter, so nothing is+# incremental — every table is a full-refresh snapshot of the current catalog.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vendr/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vendr/source.pyindex e956c890bdbb..f0a7ee0986c5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/vendr/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vendr/source.py@@ -1,19 +1,43 @@-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.vendr import VendrSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.vendr.settings import ENDPOINTS, VENDR_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.vendr.vendr import (+ VendrResumeConfig,+ validate_credentials as validate_vendr_credentials,+ vendr_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class VendrSource(SimpleSource[VendrSourceConfig]):+class VendrSource(ResumableSource[VendrSourceConfig, VendrResumeConfig]):+ # Every endpoint here is a static entry in ENDPOINTS with no I/O - safe for public docs.+ lists_tables_without_credentials = True+ # Vendr's OpenPrice API has no versioned path segment, version header, or dated release -+ # https://api.vendr.com is the only documented base.+ api_docs_url = "https://developers.vendr.com/docs/introduction"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.VENDR@@ -24,7 +48,80 @@ class VendrSource(SimpleSource[VendrSourceConfig]):name=SchemaExternalDataSourceType.VENDR,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,label="Vendr (OpenPrice API)",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="Sync Vendr's OpenPrice software catalog: companies, products, product "+ "families, and categories. Access is partnership-gated - email "+ "[[email protected]](mailto:[email protected]) to request an API key.",iconPath="/static/services/vendr.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Your Vendr API key is invalid or has been revoked. "+ "Contact [email protected] to get a new key, then reconnect.",+ "403 Client Error: Forbidden for url": "Your Vendr API key does not have access to the catalog. "+ "Check your partnership terms with Vendr, then reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.vendr.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: VendrSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ schemas = build_endpoint_schemas(ENDPOINTS, {}, names)+ for schema in schemas:+ schema.detected_primary_keys = VENDR_ENDPOINTS[schema.name].primary_keys+ return schemas++ def validate_credentials(+ self,+ config: VendrSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ ok, _status_code = validate_vendr_credentials(config.api_key)+ if ok:+ return True, None+ return False, "Invalid Vendr API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[VendrResumeConfig]:+ return ResumableSourceManager[VendrResumeConfig](inputs, VendrResumeConfig)++ def source_for_pipeline(+ self,+ config: VendrSourceConfig,+ resumable_source_manager: ResumableSourceManager[VendrResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return vendr_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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vendr/tests/test_vendr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vendr/tests/test_vendr.pynew file mode 100644index 000000000000..719446595205--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vendr/tests/test_vendr.py@@ -0,0 +1,199 @@+from typing import Any, cast++import pytest+from unittest.mock import Mock, patch++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.vendr.settings import VENDR_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.vendr.vendr import (+ VendrResumeConfig,+ _client_config,+ _get_resource,+ validate_credentials,+ vendr_source,+)+++class _FakeResource:+ def __init__(self, name: str, rows: list[dict]) -> None:+ self.name = name+ self._rows = rows++ def add_map(self, mapper):+ self._rows = [mapper(dict(row)) for row in self._rows]+ return self++ def __iter__(self):+ return iter(self._rows)+++def _make_manager(resume_state: VendrResumeConfig | None = None) -> Mock:+ manager = Mock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++class TestVendrTransport:+ def test_client_config_uses_api_key_header_and_pins_host(self) -> None:+ config = _client_config("secret-key")++ assert config["base_url"] == "https://api.vendr.com"+ assert config["auth"] == {+ "type": "api_key",+ "api_key": "secret-key",+ "name": "X-API-Key",+ "location": "header",+ }+ # Vendr's base URL is fixed, so pin every request to it and never follow redirects+ # off-host - the API key rides in a custom (non-Authorization) header.+ assert config["allowed_hosts"] == []+ assert config["allow_redirects"] is False++ @parameterized.expand(+ [+ ("Companies", "/v1/catalog/companies", {"sortBy": "name", "sortOrder": "asc"}),+ ("Categories", "/v1/catalog/categories", {"sortBy": "name", "sortOrder": "asc"}),+ ]+ )+ def test_get_resource_top_level_endpoints(self, endpoint, expected_path, expected_params) -> None:+ resource = cast(dict[str, Any], _get_resource(VENDR_ENDPOINTS[endpoint]))++ assert resource["name"] == endpoint+ assert resource["write_disposition"] == "replace"+ assert resource["table_format"] == "delta"+ assert resource["endpoint"]["path"] == expected_path+ assert resource["endpoint"]["params"] == expected_params+ assert resource["endpoint"]["data_selector"] == "data"+ assert resource["endpoint"]["paginator"] == {"type": "offset", "limit": 100, "total_path": None}++ @parameterized.expand([("ProductFamilies",), ("Products",)])+ def test_get_resource_rejects_fanout_endpoints(self, endpoint) -> None:+ with pytest.raises(ValueError, match="Fan-out endpoint"):+ _get_resource(VENDR_ENDPOINTS[endpoint])++ @parameterized.expand(+ [+ (200, True, 200),+ (401, False, 401),+ (403, False, 403),+ (429, False, 429),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.vendr.vendr.make_tracked_session")+ def test_validate_credentials_status_mapping(self, status, expected_ok, expected_status, mock_session) -> None:+ mock_session.return_value.get.return_value = Mock(status_code=status)++ result = validate_credentials("secret-key")++ assert result == (expected_ok, expected_status)+ call = mock_session.return_value.get.call_args+ assert call.args[0] == "https://api.vendr.com/v1/catalog/companies?limit=1"+ assert call.kwargs["headers"]["X-API-Key"] == "secret-key"+ assert call.kwargs["allow_redirects"] is False++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.vendr.vendr.rest_api_resource")+ def test_top_level_source_response(self, mock_rest_api_resource) -> None:+ mock_rest_api_resource.return_value = Mock()++ response = vendr_source(+ api_key="key",+ endpoint="Companies",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ )++ assert response.name == "Companies"+ assert response.primary_keys == ["id"]++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.vendr.vendr.rest_api_resource")+ def test_top_level_source_resumes_from_saved_state(self, mock_rest_api_resource) -> None:+ mock_rest_api_resource.return_value = Mock()+ manager = _make_manager(VendrResumeConfig(paginator_state={"offset": 200}))++ vendr_source(+ api_key="key",+ endpoint="Companies",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )++ assert mock_rest_api_resource.call_args.kwargs["initial_paginator_state"] == {"offset": 200}++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.vendr.vendr.rest_api_resource")+ def test_top_level_source_saves_checkpoints_after_batches(self, mock_rest_api_resource) -> None:+ mock_rest_api_resource.return_value = Mock()+ manager = _make_manager()++ vendr_source(+ api_key="key",+ endpoint="Companies",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )++ resume_hook = mock_rest_api_resource.call_args.kwargs["resume_hook"]+ resume_hook({"offset": 100})+ manager.save_state.assert_called_once_with(VendrResumeConfig(paginator_state={"offset": 100}))++ # A terminal (falsy) checkpoint is not persisted - the Redis TTL handles cleanup.+ manager.save_state.reset_mock()+ resume_hook(None)+ manager.save_state.assert_not_called()++ @parameterized.expand([("ProductFamilies",), ("Products",)])+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.vendr.vendr.build_dependent_resource")+ def test_fanout_wiring(self, endpoint, mock_build_dependent_resource) -> None:+ mock_build_dependent_resource.return_value = _FakeResource(endpoint, [])+ manager = _make_manager()++ response = vendr_source(+ api_key="key",+ endpoint=endpoint,+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )++ kwargs = mock_build_dependent_resource.call_args.kwargs+ assert kwargs["child_endpoint"] == endpoint+ assert kwargs["fanout"].parent_name == "Companies"+ assert kwargs["fanout"].resolve_param == "companyId"+ assert kwargs["fanout"].resolve_field == "id"+ assert kwargs["path_format_values"] == {}+ assert kwargs["page_size_param"] == "limit"+ assert kwargs["parent_endpoint_extra"] == {+ "paginator": {"type": "offset", "limit": 100, "total_path": None},+ "data_selector": "data",+ }+ assert kwargs["child_endpoint_extra"] == {+ "paginator": {"type": "offset", "limit": 100, "total_path": None},+ "data_selector": "data",+ }+ assert kwargs["child_params_extra"] == {"sortBy": "sortOrder", "sortOrder": "asc"}+ assert kwargs["resume_hook"] is not None+ assert response.primary_keys == ["id"]++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_products_fanout_row_format(self, mock_rest_api_resources) -> None:+ mock_rest_api_resources.return_value = [+ _FakeResource("Companies", [{"id": "co_1"}]),+ _FakeResource("Products", [{"id": "prod_1", "name": "Widget", "_Companies_id": "co_1"}]),+ ]++ response = vendr_source(+ api_key="key",+ endpoint="Products",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ )++ assert list(cast(Any, response.items())) == [{"id": "prod_1", "name": "Widget", "company_id": "co_1"}]+ assert response.primary_keys == ["id"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vendr/tests/test_vendr_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vendr/tests/test_vendr_source.pynew file mode 100644index 000000000000..22d188b7aaee--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vendr/tests/test_vendr_source.py@@ -0,0 +1,153 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ 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.vendr import VendrSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.vendr.settings import ENDPOINTS, VENDR_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.vendr.source import VendrSource+from products.warehouse_sources.backend.temporal.data_imports.sources.vendr.vendr import VendrResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestVendrSource:+ def setup_method(self) -> None:+ self.source = VendrSource()+ self.team_id = 123+ self.config = VendrSourceConfig(api_key="vendr-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.VENDR++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Vendr"+ assert config.category == DataWarehouseSourceCategory.FINANCE___ACCOUNTING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source ships visible: unreleasedSource hides the connector from every user.+ assert not config.unreleasedSource+ assert config.iconPath == "/static/services/vendr.png"++ field_names = [f.name for f in config.fields]+ assert field_names == ["api_key"]++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ def test_lists_tables_without_credentials(self) -> None:+ # Every endpoint is a static entry in ENDPOINTS with no I/O - safe for public docs.+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_lists_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ def test_get_schemas_are_full_refresh_only(self) -> None:+ # Vendr's catalog API documents no updated-since/created-since filter on any endpoint.+ 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_expose_primary_keys(self) -> None:+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}+ for name in ENDPOINTS:+ assert schemas[name].detected_primary_keys == VENDR_ENDPOINTS[name].primary_keys++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Companies"])+ assert [schema.name for schema in schemas] == ["Companies"]++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["Nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ companies = next(t for t in tables if t["name"] == "Companies")+ assert companies["sync_methods"] == ["Full refresh"]+ assert companies["primary_keys"] == ["id"]+ assert companies["description"]++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.vendr.com/v1/catalog/companies?limit=100",+ "403 Client Error: Forbidden for url: https://api.vendr.com/v1/catalog/categories?limit=100",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests for url: https://api.vendr.com/v1/catalog/companies",+ "500 Server Error: Internal Server Error for url: https://api.vendr.com/v1/catalog/companies",+ "HTTPSConnectionPool(host='api.vendr.com', port=443): Read timed out.",+ ],+ )+ def test_non_retryable_errors_does_not_match_unrelated(self, other_error: str) -> None:+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ @parameterized.expand(+ [+ ((True, None), True, None),+ ((False, 401), False, "Invalid Vendr API key"),+ ((False, 403), False, "Invalid Vendr API key"),+ ((False, None), False, "Invalid Vendr API key"),+ ]+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.vendr.source.validate_vendr_credentials"+ )+ def test_validate_credentials(self, mock_return, expected_valid, expected_message, mock_validate) -> None:+ 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("vendr-key")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is VendrResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.vendr.source.vendr_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_vendr_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "Products"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_vendr_source.assert_called_once()+ kwargs = mock_vendr_source.call_args.kwargs+ assert kwargs["api_key"] == "vendr-key"+ assert kwargs["endpoint"] == "Products"+ assert kwargs["team_id"] == self.team_id+ assert kwargs["job_id"] == "job-1"+ assert kwargs["resumable_source_manager"] is manager++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(VENDR_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vendr/vendr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vendr/vendr.pynew file mode 100644index 000000000000..af0f72fc10d1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vendr/vendr.py@@ -0,0 +1,148 @@+import dataclasses+from typing import Any, Optional++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.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ EndpointResource,+ PaginatorConfig,+)+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.vendr.settings import (+ PAGE_SIZE,+ VENDR_ENDPOINTS,+ VendrEndpointConfig,+)++BASE_URL = "https://api.vendr.com"++# Vendr's `pagination` response object isn't documented field-by-field (only that a list+# response carries one), so we don't parse a `total`/`hasMore` field to decide when to stop.+# Stopping once a page comes back shorter than `limit` (or empty) is sufficient and doesn't+# depend on an unconfirmed field name.+_PAGINATOR: PaginatorConfig = {"type": "offset", "limit": PAGE_SIZE, "total_path": None}++[email protected](frozen=True)+class VendrResumeConfig:+ # Opaque framework checkpoint: an offset position for a top-level endpoint, or per-company+ # fan-out state (current company, completed companies, child offset) for a company-scoped+ # one. Round-tripped into `initial_paginator_state` on resume.+ paginator_state: dict[str, Any]+++def _client_config(api_key: str) -> ClientConfig:+ return {+ "base_url": BASE_URL,+ "headers": {"Accept": "application/json"},+ # The API key rides in the framework auth config so its value is redacted from logs;+ # only the non-secret Accept header is set above.+ "auth": {"type": "api_key", "api_key": api_key, "name": "X-API-Key", "location": "header"},+ # Vendr's base URL is fixed (not user-configurable), so pin every request - including+ # paginator next-page state - to it and never follow redirects off it.+ "allowed_hosts": [],+ "allow_redirects": False,+ }+++def validate_credentials(api_key: str) -> tuple[bool, int | None]:+ """Confirm the API key is genuine with one cheap, low-privilege list call."""+ return validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,), allow_redirects=False),+ f"{BASE_URL}/v1/catalog/companies?limit=1",+ headers={"X-API-Key": api_key, "Accept": "application/json"},+ allow_redirects=False,+ )+++def _get_resource(config: VendrEndpointConfig) -> EndpointResource:+ if config.fanout:+ raise ValueError(f"Fan-out endpoint '{config.name}' must use the fan-out path")+ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": "replace",+ "endpoint": {+ "path": config.path,+ "params": {"sortBy": config.sort_by, "sortOrder": "asc"},+ "paginator": _PAGINATOR,+ "data_selector": "data",+ },+ "table_format": "delta",+ }+++def vendr_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[VendrResumeConfig],+) -> SourceResponse:+ config = VENDR_ENDPOINTS[endpoint]++ 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 = resume_config.paginator_state++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's a next page to resume to; the Redis TTL handles cleanup on+ # completion. Saved AFTER a page is yielded, so a crash re-fetches from the next position+ # and never skips a page (a re-fetched page is deduped by the write disposition below).+ if state:+ resumable_source_manager.save_state(VendrResumeConfig(paginator_state=dict(state)))++ if config.fanout is not None:+ items = build_dependent_resource(+ endpoint_configs=VENDR_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=config.fanout,+ client_config=_client_config(api_key),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ child_params_extra={"sortBy": config.sort_by, "sortOrder": "asc"},+ parent_endpoint_extra={"paginator": _PAGINATOR, "data_selector": "data"},+ child_endpoint_extra={"paginator": _PAGINATOR, "data_selector": "data"},+ page_size_param="limit",+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+ return SourceResponse(+ name=endpoint,+ items=lambda: items,+ primary_keys=config.primary_keys,+ )++ rest_config: RESTAPIConfig = {+ "client": _client_config(api_key),+ "resources": [_get_resource(config)],+ }++ 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=config.primary_keys,+ column_hints=resource.column_hints,+ )