:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement inflowinventory import source (#68593)
Tom Owers43d7e9c3c2ae
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex b771a190cd05..4d4416765ff9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -188,6 +188,7 @@ the row lists both.| hubspot | HTTP | requests | ✅ || hugging_face | HTTP | requests | ✅ || incident_io | HTTP | requests | ✅ |+| inflowinventory | HTTP | requests | ✅ || insightly | HTTP | requests | ✅ || instatus | HTTP | requests | ✅ || intercom | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -492,7 +493,6 @@ doesn't conflict with concurrent PRs.- ikas- illumina_basespace- imagga-- inflowinventory- infor_nexus- insightfuldiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex dcfa8cd4a219..af1d04d0a222 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -1611,7 +1611,8 @@ class IncidentIoSourceConfig(config.Config):@config.configclass InflowinventorySourceConfig(config.Config):- pass+ company_id: str+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/inflowinventory/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/inflowinventory/canonical_descriptions.pynew file mode 100644index 000000000000..cebd7b6a5ad1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/inflowinventory/canonical_descriptions.py@@ -0,0 +1,89 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the inFlow Inventory Cloud API docs (https://cloudapi.inflowinventory.com/docs).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+_DOCS_URL = "https://cloudapi.inflowinventory.com/docs"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "products": {+ "description": "A product (inventory item) tracked in inFlow Inventory.",+ "docs_url": _DOCS_URL,+ "columns": {+ "productId": "The unique ID of the product.",+ "name": "The product name.",+ "sku": "The product's stock keeping unit (SKU).",+ "description": "A description of the product.",+ "itemType": "The type of item (e.g. stocked product, service, or non-stocked).",+ "isActive": "Whether the product is active.",+ "defaultPrice": "The default sales price of the product.",+ "cost": "The cost of the product.",+ "barcode": "The product's barcode value.",+ "categoryId": "The ID of the category the product belongs to.",+ "timestamp": "The row version timestamp used for change tracking.",+ },+ },+ "customers": {+ "description": "A customer in inFlow Inventory that sales orders are placed for.",+ "docs_url": _DOCS_URL,+ "columns": {+ "customerId": "The unique ID of the customer.",+ "name": "The customer name.",+ "email": "The customer's primary email address.",+ "phone": "The customer's phone number.",+ "remarks": "Free-text remarks recorded against the customer.",+ "isActive": "Whether the customer is active.",+ "defaultCarrier": "The default shipping carrier for the customer.",+ "defaultPaymentTerms": "The default payment terms for the customer.",+ "timestamp": "The row version timestamp used for change tracking.",+ },+ },+ "vendors": {+ "description": "A vendor (supplier) that purchase orders are placed with in inFlow Inventory.",+ "docs_url": _DOCS_URL,+ "columns": {+ "vendorId": "The unique ID of the vendor.",+ "name": "The vendor name.",+ "email": "The vendor's primary email address.",+ "phone": "The vendor's phone number.",+ "remarks": "Free-text remarks recorded against the vendor.",+ "isActive": "Whether the vendor is active.",+ "defaultCarrier": "The default shipping carrier for the vendor.",+ "defaultPaymentTerms": "The default payment terms for the vendor.",+ "timestamp": "The row version timestamp used for change tracking.",+ },+ },+ "sales_orders": {+ "description": "A sales order recording products sold to a customer.",+ "docs_url": _DOCS_URL,+ "columns": {+ "salesOrderId": "The unique ID of the sales order.",+ "orderNumber": "The human-readable order number.",+ "customerId": "The ID of the customer the order is for.",+ "orderDate": "The date the order was placed.",+ "orderStatus": "The current status of the order.",+ "total": "The total value of the order.",+ "subTotal": "The order subtotal before tax and shipping.",+ "currencyCode": "The currency the order is denominated in.",+ "lines": "The line items on the order.",+ "timestamp": "The row version timestamp used for change tracking.",+ },+ },+ "purchase_orders": {+ "description": "A purchase order recording products bought from a vendor.",+ "docs_url": _DOCS_URL,+ "columns": {+ "purchaseOrderId": "The unique ID of the purchase order.",+ "orderNumber": "The human-readable order number.",+ "vendorId": "The ID of the vendor the order is placed with.",+ "orderDate": "The date the order was placed.",+ "orderStatus": "The current status of the order.",+ "total": "The total value of the order.",+ "subTotal": "The order subtotal before tax and shipping.",+ "currencyCode": "The currency the order is denominated in.",+ "lines": "The line items on the order.",+ "timestamp": "The row version timestamp used for change tracking.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/inflowinventory/inflowinventory.py b/products/warehouse_sources/backend/temporal/data_imports/sources/inflowinventory/inflowinventory.pynew file mode 100644index 000000000000..ee87cc5748aa--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/inflowinventory/inflowinventory.py@@ -0,0 +1,192 @@+import re+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from urllib3.util.retry import Retry++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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.inflowinventory.settings import (+ INFLOWINVENTORY_ENDPOINTS,+)++INFLOWINVENTORY_BASE_URL = "https://cloudapi.inflowinventory.com"+# inFlow requires a date-based API version header on every request; pin a recent documented version.+INFLOWINVENTORY_API_VERSION = "2023-04-01"+# The list endpoints accept up to 100 records per page; the largest page minimises round trips.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+# inFlow company IDs are GUIDs. Restrict to host/path-safe characters so the credential stays+# pinned to cloudapi.inflowinventory.com and can't be redirected via a crafted path segment.+COMPANY_ID_REGEX = re.compile(r"^[a-zA-Z0-9-]+$")+++class InflowInventoryRetryableError(Exception):+ """Raised for transient API responses (429 / 5xx) so tenacity retries them."""+++class InflowInventoryResumeConfig:+ # The `after` cursor is the ID of the last row yielded. inFlow returns rows ordered by ID, so a+ # crashed full-refresh sync resumes from the record after the last one persisted; merge dedupes+ # on the primary key.+ after: str | None = None+++def base_url(company_id: str) -> str:+ return f"{INFLOWINVENTORY_BASE_URL}/{company_id}"+++def _headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": f"application/json;version={INFLOWINVENTORY_API_VERSION}",+ }+++def _make_session(api_key: str) -> requests.Session:+ # Redirects are pinned off so the Bearer key can't be replayed to a cross-host redirect target+ # (SSRF / credential-exfiltration defense). urllib3 retries are disabled so tenacity (on+ # `_fetch_page`) is the single retry layer — otherwise 429/5xx would be retried by both.+ return make_tracked_session(+ headers=_headers(api_key), redact_values=(api_key,), allow_redirects=False, retry=Retry(total=0)+ )+++@retry(+ retry=retry_if_exception_type((InflowInventoryRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ company_id: str,+ path: str,+ after: str | None,+ count: int,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ params: dict[str, Any] = {"count": count}+ if after is not None:+ params["after"] = after++ response = session.get(+ f"{base_url(company_id)}/{path}",+ params=params,+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise InflowInventoryRetryableError(+ f"inFlow Inventory API error (retryable): status={response.status_code}, path={path}"+ )++ if not response.ok:+ logger.error(f"inFlow Inventory API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ data = response.json()+ # inFlow list endpoints return a bare JSON array of records. A non-list body on a 200 is a+ # permanent contract violation, not transient, so raise ValueError (not retryable) to fail fast.+ if not isinstance(data, list):+ raise ValueError(f"inFlow Inventory returned an unexpected payload for {path}: {type(data).__name__}")+ return data+++def get_rows(+ api_key: str,+ company_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[InflowInventoryResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = INFLOWINVENTORY_ENDPOINTS[endpoint]+ session = _make_session(api_key)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ after = resume.after if resume else None+ if resume and resume.after:+ logger.debug(f"inFlow Inventory: resuming {endpoint} after cursor {after}")++ while True:+ items = _fetch_page(session, company_id, config.path, after, PAGE_SIZE, logger)+ if items:+ yield items++ # A short page (or an empty one) means we've reached the end of the collection.+ if len(items) < PAGE_SIZE:+ break++ next_after = items[-1].get(config.id_field)+ if next_after is None:+ # Without a cursor value we can't request the next page safely — stop rather than loop.+ logger.warning(f"inFlow Inventory: {endpoint} row missing '{config.id_field}', ending pagination")+ break++ after = str(next_after)+ # Save AFTER yielding so a crash re-fetches from the last cursor (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(InflowInventoryResumeConfig(after=after))+++def inflowinventory_source(+ api_key: str,+ company_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[InflowInventoryResumeConfig],+) -> SourceResponse:+ config = INFLOWINVENTORY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ company_id=company_id,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )+++def check_access(api_key: str, company_id: str, path: str = "products") -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the credentials.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, ``400`` for a malformed company ID, other HTTP status otherwise.+ """+ if not COMPANY_ID_REGEX.match(company_id):+ return 400, "The inFlow Inventory company ID contains unsupported characters"++ session = _make_session(api_key)+ try:+ response = session.get(f"{base_url(company_id)}/{path}", params={"count": 1}, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to inFlow Inventory: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"inFlow Inventory returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_key: str, company_id: str) -> tuple[bool, str | None]:+ status, message = check_access(api_key, company_id)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid inFlow Inventory API key"+ return False, message or "Could not validate inFlow Inventory credentials"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/inflowinventory/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/inflowinventory/settings.pynew file mode 100644index 000000000000..878265396c59--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/inflowinventory/settings.py@@ -0,0 +1,34 @@+from dataclasses import dataclass+++@dataclass+class InflowInventoryEndpointConfig:+ name: str+ # API path segment (kebab-case), appended after the company ID. The table name (`name`) uses+ # underscores so it maps to a valid warehouse table.+ path: str+ # inFlow names each entity's ID field after the entity (e.g. `productId`). The same field is+ # the `after` pagination cursor, so we track it once and reuse it as the primary key.+ id_field: str++ @property+ def primary_keys(self) -> list[str]:+ return [self.id_field]+++# inFlow Inventory top-level list endpoints. All are full-refresh only: the documented list+# endpoints expose cursor pagination but no reliably ordered server-side timestamp filter, so+# there is no incremental cursor to advance safely (see the implementing-warehouse-sources skill).+INFLOWINVENTORY_ENDPOINTS: dict[str, InflowInventoryEndpointConfig] = {+ "products": InflowInventoryEndpointConfig(name="products", path="products", id_field="productId"),+ "customers": InflowInventoryEndpointConfig(name="customers", path="customers", id_field="customerId"),+ "vendors": InflowInventoryEndpointConfig(name="vendors", path="vendors", id_field="vendorId"),+ "sales_orders": InflowInventoryEndpointConfig(name="sales_orders", path="sales-orders", id_field="salesOrderId"),+ "purchase_orders": InflowInventoryEndpointConfig(+ name="purchase_orders", path="purchase-orders", id_field="purchaseOrderId"+ ),+}++ENDPOINTS = tuple(INFLOWINVENTORY_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/inflowinventory/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/inflowinventory/source.pyindex 6eda707de5fa..04c48269dcba 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/inflowinventory/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/inflowinventory/source.py@@ -1,32 +1,151 @@-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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (InflowinventorySourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.inflowinventory.inflowinventory import (+ InflowInventoryResumeConfig,+ inflowinventory_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.inflowinventory.settings import (+ ENDPOINTS,+ INFLOWINVENTORY_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class InflowinventorySource(SimpleSource[InflowinventorySourceConfig]):+class InflowinventorySource(ResumableSource[InflowinventorySourceConfig, InflowInventoryResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.INFLOWINVENTORY+ @property+ def connection_host_fields(self) -> list[str]:+ # The Bearer key is sent to cloudapi.inflowinventory.com/<company_id>, so retargeting the+ # company ID must re-require the key — otherwise a preserved credential could be aimed at+ # another account's path.+ return ["company_id"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.INFLOWINVENTORY,category=DataWarehouseSourceCategory.E_COMMERCE,label="Inflowinventory",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your inFlow Inventory company ID and API key to pull your inventory and order data into the PostHog Data warehouse.++Find your company ID and create an API key on the **Integrations** page in [inFlow](https://www.inflowinventory.com/). API access requires a paid plan with the API add-on, and the key is only shown once — copy it before leaving the page.+""",iconPath="/static/services/inflowinventory.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/inflowinventory",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="company_id",+ label="Company ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.inflowinventory.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://cloudapi.inflowinventory.com": "Your inFlow Inventory API key is invalid or has been revoked. Generate a new key on the Integrations page in inFlow, then reconnect.",+ "403 Client Error: Forbidden for url: https://cloudapi.inflowinventory.com": "Your inFlow Inventory API key does not have access to this data, or the account's plan does not include API access. Check the key and plan, then reconnect.",+ }++ def get_schemas(+ self,+ config: InflowinventorySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — inFlow's list endpoints expose cursor pagination but+ # no reliably ordered server-side timestamp filter, so there is no incremental cursor.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ detected_primary_keys=INFLOWINVENTORY_ENDPOINTS[endpoint].primary_keys,+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: InflowinventorySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The API key is account-wide, so a single probe validates access to every schema.+ return validate_credentials(config.api_key, config.company_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[InflowInventoryResumeConfig]:+ return ResumableSourceManager[InflowInventoryResumeConfig](inputs, InflowInventoryResumeConfig)++ def source_for_pipeline(+ self,+ config: InflowinventorySourceConfig,+ resumable_source_manager: ResumableSourceManager[InflowInventoryResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in INFLOWINVENTORY_ENDPOINTS:+ raise ValueError(f"Unknown inFlow Inventory schema '{inputs.schema_name}'")++ return inflowinventory_source(+ api_key=config.api_key,+ company_id=config.company_id,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/inflowinventory/tests/test_inflowinventory.py b/products/warehouse_sources/backend/temporal/data_imports/sources/inflowinventory/tests/test_inflowinventory.pynew file mode 100644index 000000000000..0eb9d1c5e737--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/inflowinventory/tests/test_inflowinventory.py@@ -0,0 +1,263 @@+from typing import Any++import pytest+from unittest import mock+from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.inflowinventory import inflowinventory+from products.warehouse_sources.backend.temporal.data_imports.sources.inflowinventory.inflowinventory import (+ PAGE_SIZE,+ InflowInventoryResumeConfig,+ InflowInventoryRetryableError,+ check_access,+ get_rows,+ inflowinventory_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.inflowinventory.settings import (+ ENDPOINTS,+ INFLOWINVENTORY_ENDPOINTS,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = inflowinventory._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: InflowInventoryResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[InflowInventoryResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> InflowInventoryResumeConfig | None:+ return self._state++ def save_state(self, data: InflowInventoryResumeConfig) -> None:+ self.saved.append(data)+++def _full_page(start_id: int) -> list[dict]:+ return [{"productId": str(start_id + i)} for i in range(PAGE_SIZE)]+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: dict[Any, list[dict]],+ endpoint: str = "products",+ ) -> list[dict]:+ def fake_fetch(session: Any, company_id: str, path: str, after: Any, count: int, logger: Any) -> list[dict]:+ return pages[after]++ monkeypatch.setattr(inflowinventory, "_fetch_page", fake_fetch)+ monkeypatch.setattr(inflowinventory, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="inflow-key",+ company_id="co-123",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_single_short_page_yields_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {None: [{"productId": "1"}, {"productId": "2"}]})+ assert rows == [{"productId": "1"}, {"productId": "2"}]+ # The page is short (< PAGE_SIZE), so we stop without persisting resume state.+ assert manager.saved == []++ def test_follows_after_cursor_until_short_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ # Last row of the first full page has productId str(PAGE_SIZE - 1), which becomes the cursor.+ last_id = str(PAGE_SIZE - 1)+ pages = {None: _full_page(0), last_id: [{"productId": "9999"}]}+ rows = self._collect(manager, monkeypatch, pages)+ assert len(rows) == PAGE_SIZE + 1+ assert [s.after for s in manager.saved] == [last_id]++ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(InflowInventoryResumeConfig(after="42"))+ # The unpaginated first page (after=None) must never be fetched on resume.+ pages = {"42": [{"productId": "5"}]}+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [{"productId": "5"}]++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {None: []})+ assert rows == []+ assert manager.saved == []++ def test_full_page_missing_id_field_stops(self, monkeypatch: Any) -> None:+ # A full page whose last row lacks the cursor field can't be paginated past — stop instead+ # of looping forever on the same cursor.+ page = _full_page(0)+ page[-1] = {"name": "no id here"}+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {None: page})+ assert len(rows) == PAGE_SIZE+ assert manager.saved == []+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body if body is not None else []+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(InflowInventoryRetryableError):+ _fetch_page_unwrapped(session, "co-1", "products", None, PAGE_SIZE, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "co-1", "products", None, PAGE_SIZE, MagicMock())++ def test_success_returns_list_body(self) -> None:+ body = [{"productId": "1"}]+ session = self._session_returning(200, body)+ result = _fetch_page_unwrapped(session, "co-1", "products", None, PAGE_SIZE, MagicMock())+ assert result == body++ def test_non_list_body_raises_value_error(self) -> None:+ session = self._session_returning(200, {"error": "nope"})+ with pytest.raises(ValueError):+ _fetch_page_unwrapped(session, "co-1", "products", None, PAGE_SIZE, MagicMock())++ def test_first_page_omits_after_param(self) -> None:+ session = self._session_returning(200, [])+ _fetch_page_unwrapped(session, "co-1", "products", None, PAGE_SIZE, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"count": PAGE_SIZE}++ def test_paginated_request_sends_after_cursor(self) -> None:+ session = self._session_returning(200, [])+ _fetch_page_unwrapped(session, "co-1", "customers", "abc", PAGE_SIZE, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"count": PAGE_SIZE, "after": "abc"}++ def test_request_targets_company_scoped_url(self) -> None:+ session = self._session_returning(200, [])+ _fetch_page_unwrapped(session, "co-1", "sales-orders", None, PAGE_SIZE, MagicMock())+ args, _ = session.get.call_args+ assert args[0] == "https://cloudapi.inflowinventory.com/co-1/sales-orders"+++class TestCheckAccess:+ @staticmethod+ def _build_session(response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ return session++ def _patch_session(self, monkeypatch: Any, response: Any) -> MagicMock:+ session = self._build_session(response)+ monkeypatch.setattr(inflowinventory, "make_tracked_session", lambda **kwargs: session)+ return session++ @parameterized.expand(+ [+ ("ok", 200, True, 200, None),+ ("unauthorized", 401, False, 401, None),+ ("forbidden", 403, False, 403, None),+ ("server_error", 500, False, 500, "inFlow Inventory returned HTTP 500"),+ ]+ )+ @mock.patch.object(inflowinventory, "make_tracked_session")+ def test_status_mapping(+ self,+ _name: str,+ status: int,+ ok: bool,+ expected_status: int,+ expected_message: str | None,+ mock_make_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ mock_make_session.return_value = self._build_session(response)+ assert check_access("inflow-key", "co-123") == (expected_status, expected_message)++ def test_malformed_company_id_short_circuits(self, monkeypatch: Any) -> None:+ # A bad company ID never reaches the network — no session is created.+ session = self._patch_session(monkeypatch, MagicMock())+ status, message = check_access("inflow-key", "bad id/../evil")+ assert status == 400+ assert message is not None+ session.get.assert_not_called()++ def test_connection_error_maps_to_zero(self, monkeypatch: Any) -> None:+ self._patch_session(monkeypatch, requests.ConnectionError("boom"))+ status, message = check_access("inflow-key", "co-123")+ assert status == 0+ assert message is not None and "boom" in message++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid inFlow Inventory API key"),+ ("forbidden", 403, False, "Invalid inFlow Inventory API key"),+ ("server_error", 500, False, "inFlow Inventory returned HTTP 500"),+ ]+ )+ @mock.patch.object(inflowinventory, "make_tracked_session")+ def test_validate_credentials(+ self,+ _name: str,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ mock_make_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ mock_make_session.return_value = self._build_session(response)+ assert validate_credentials("inflow-key", "co-123") == (expected_valid, expected_message)+++class TestInflowInventorySourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = inflowinventory_source(+ api_key="inflow-key",+ company_id="co-123",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == INFLOWINVENTORY_ENDPOINTS[endpoint].primary_keys+ # No stable creation timestamp is guaranteed across every object, so we don't partition.+ assert response.partition_mode is None++ def test_every_endpoint_primary_key_matches_id_field(self) -> None:+ assert all(config.primary_keys == [config.id_field] for config in INFLOWINVENTORY_ENDPOINTS.values())+ assert set(INFLOWINVENTORY_ENDPOINTS) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/inflowinventory/tests/test_inflowinventory_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/inflowinventory/tests/test_inflowinventory_source.pynew file mode 100644index 000000000000..0d68e51685aa--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/inflowinventory/tests/test_inflowinventory_source.py@@ -0,0 +1,173 @@+import pytest+from unittest import mock++from parameterized import parameterized++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 import (+ InflowinventorySourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.inflowinventory.inflowinventory import (+ InflowInventoryResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.inflowinventory.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.inflowinventory.source import (+ InflowinventorySource,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestInflowinventorySource:+ def setup_method(self) -> None:+ self.source = InflowinventorySource()+ self.team_id = 123+ self.config = InflowinventorySourceConfig(company_id="co-123", api_key="inflow-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.INFLOWINVENTORY++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Inflowinventory"+ assert config.label == "Inflowinventory"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source is visible — it must not carry the scaffolding flag.+ assert not config.unreleasedSource+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/inflowinventory"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["company_id", "api_key"]++ def test_company_id_field_is_plain_text(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "company_id")+ assert field.type == SourceFieldInputConfigType.TEXT+ assert field.secret is False+ assert field.required is True++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_connection_host_fields_pins_company_id(self) -> None:+ # The secret key is sent to a host/path derived from company_id, so retargeting it must+ # re-require the key.+ assert self.source.connection_host_fields == ["company_id"]++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["customers"])+ assert len(schemas) == 1+ assert schemas[0].name == "customers"++ 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)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://cloudapi.inflowinventory.com/co-123/products?count=100",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://cloudapi.inflowinventory.com/co-123/customers?count=100",+ ),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://cloudapi.inflowinventory.com/co-123/products",+ ),+ (+ "rate_limited",+ "429 Client Error: Too Many Requests for url: https://cloudapi.inflowinventory.com/co-123/customers",+ ),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid inFlow Inventory API key"),+ ("forbidden", 403, False, "Invalid inFlow Inventory API key"),+ ("server_error", 500, False, "inFlow Inventory returned HTTP 500"),+ ("connection_error", 0, False, "Could not connect to inFlow Inventory: boom"),+ ]+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.inflowinventory.inflowinventory.check_access"+ )+ def test_validate_credentials(+ self,+ _name: str,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ mock_check: mock.MagicMock,+ ) -> None:+ message = (+ "inFlow Inventory returned HTTP 500"+ if status == 500+ else ("Could not connect to inFlow Inventory: boom" if status == 0 else None)+ )+ mock_check.return_value = (status, message)+ is_valid, returned = self.source.validate_credentials(self.config, self.team_id)+ assert is_valid is expected_valid+ assert returned == expected_message++ 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 InflowInventoryResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.inflowinventory.source.inflowinventory_source"+ )+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "products"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "inflow-key"+ assert kwargs["company_id"] == "co-123"+ assert kwargs["endpoint"] == "products"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown inFlow Inventory schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)