: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 flowlu import source (#69328)
Tom Owers48f809ca1b16
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 6fde2f894696..c259091dfa9f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -181,6 +181,7 @@ the row lists both.| firehydrant | HTTP | requests | ✅ || flexmail | HTTP | requests | ✅ || float_app | HTTP | requests | ✅ |+| flowlu | HTTP | requests | ✅ || fly_io | HTTP | requests | ✅ || formbricks | HTTP | requests | ✅ || front | HTTP | requests | ✅ |diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/canonical_descriptions.pynew file mode 100644index 000000000000..eeb4278a2a97--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/canonical_descriptions.py@@ -0,0 +1,108 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Flowlu REST API docs (https://developers.flowlu.com).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "accounts": {+ "description": "A CRM account in Flowlu — an organization or contact you do business with.",+ "docs_url": "https://developers.flowlu.com",+ "columns": {+ "id": "The unique ID of the account.",+ "name": "The account's display name.",+ "type": "The account type (organization or contact).",+ },+ },+ "leads": {+ "description": "A CRM opportunity (Flowlu's API keeps the legacy 'lead' entity name) tracked through a sales pipeline.",+ "docs_url": "https://developers.flowlu.com",+ "columns": {+ "id": "The unique ID of the opportunity.",+ "name": "The opportunity's name.",+ },+ },+ "pipelines": {+ "description": "A CRM sales pipeline that opportunities move through.",+ "docs_url": "https://developers.flowlu.com",+ "columns": {+ "id": "The unique ID of the pipeline.",+ "name": "The pipeline's name.",+ },+ },+ "tasks": {+ "description": "A task in Flowlu's task management module.",+ "docs_url": "https://developers.flowlu.com",+ "columns": {+ "id": "The unique ID of the task.",+ "name": "The task's title.",+ },+ },+ "projects": {+ "description": "A project in Flowlu's project management module.",+ "docs_url": "https://developers.flowlu.com",+ "columns": {+ "id": "The unique ID of the project.",+ "name": "The project's name.",+ },+ },+ "invoices": {+ "description": "An invoice issued to a customer in Flowlu's finance module.",+ "docs_url": "https://developers.flowlu.com",+ "columns": {+ "id": "The unique ID of the invoice.",+ },+ },+ "estimates": {+ "description": "An estimate (quote) prepared for a customer in Flowlu's finance module.",+ "docs_url": "https://developers.flowlu.com",+ "columns": {+ "id": "The unique ID of the estimate.",+ },+ },+ "customer_payments": {+ "description": "A payment received from a customer, typically applied against an invoice.",+ "docs_url": "https://developers.flowlu.com",+ "columns": {+ "id": "The unique ID of the payment.",+ },+ },+ "transactions": {+ "description": "A money transaction (income or expense) recorded in Flowlu's finance module.",+ "docs_url": "https://developers.flowlu.com",+ "columns": {+ "id": "The unique ID of the transaction.",+ },+ },+ "agile_issues": {+ "description": "An issue (user story, task, or bug) on a Flowlu agile board.",+ "docs_url": "https://developers.flowlu.com",+ "columns": {+ "id": "The unique ID of the issue.",+ "name": "The issue's title.",+ },+ },+ "agile_sprints": {+ "description": "A sprint within a Flowlu agile project.",+ "docs_url": "https://developers.flowlu.com",+ "columns": {+ "id": "The unique ID of the sprint.",+ "name": "The sprint's name.",+ },+ },+ "timesheets": {+ "description": "A time-tracking entry logged against tasks or projects in Flowlu.",+ "docs_url": "https://developers.flowlu.com",+ "columns": {+ "id": "The unique ID of the timesheet entry.",+ },+ },+ "products": {+ "description": "A product or service from Flowlu's product catalog.",+ "docs_url": "https://developers.flowlu.com",+ "columns": {+ "id": "The unique ID of the product.",+ "name": "The product's name.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/flowlu.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/flowlu.pynew file mode 100644index 000000000000..833b1988a6c3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/flowlu.py@@ -0,0 +1,187 @@+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 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.flowlu.settings import FLOWLU_ENDPOINTS++REQUEST_TIMEOUT_SECONDS = 60+# Flowlu pages are 1-indexed. List endpoints return ~50 records per page by default; a per-page+# size param isn't reliably documented, so we only advance `page` and stop on the first empty page.+BASE_PAGE = 1+# Cheap list endpoint used to confirm an API key is genuine. Tasks are part of Flowlu's core+# module set, so the endpoint exists on every account regardless of which apps are enabled.+DEFAULT_PROBE_PATH = "/task/tasks/list"+++class FlowluRetryableError(Exception):+ pass+++class FlowluResumeConfig:+ # Next page to fetch (1-indexed). Page-number pagination is deterministic, so a crashed+ # full-refresh sync resumes from the page after the last one yielded; merge dedupes on `id`.+ next_page: int = BASE_PAGE+++def base_url(subdomain: str) -> str:+ """Per-account hostname: every Flowlu portal lives on its own subdomain."""+ return f"https://{subdomain}.flowlu.com/api/v1/module"+++@retry(+ retry=retry_if_exception_type((FlowluRetryableError, 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,+ api_key: str,+ subdomain: str,+ path: str,+ page: int,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ # Flowlu authenticates via the `api_key` query parameter (not a header); the tracked session+ # redacts it from logged URLs via `redact_values`.+ params: dict[str, str | int] = {"api_key": api_key, "page": page}+ response = session.get(+ f"{base_url(subdomain)}{path}",+ params=params,+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise FlowluRetryableError(f"Flowlu API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"Flowlu API error: status={response.status_code}, body={response.text[:500]}, path={path}")+ # Raise manually instead of `raise_for_status()`: that embeds `response.url`, which carries the+ # `api_key` query param, and this message reaches sync error logs viewable by users who can't see+ # secret fields. Keep the "<status> Client Error: <reason> for url" shape that+ # `get_non_retryable_errors()` matches on, but point it at the query-string-free URL.+ kind = "Client Error" if response.status_code < 500 else "Server Error"+ raise requests.HTTPError(+ f"{response.status_code} {kind}: {response.reason} for url: {base_url(subdomain)}{path}",+ response=response,+ )++ data = response.json()+ # Every list endpoint wraps its payload as `{"response": {"items": [...], "total": ..., ...}}`;+ # anything else means a malformed response, so fail loudly rather than silently advancing the+ # cursor past lost rows.+ if not isinstance(data, dict) or not isinstance(data.get("response"), dict):+ raise FlowluRetryableError(f"Flowlu returned an unexpected payload for {path}: {type(data).__name__}")++ items = data["response"].get("items")+ if not isinstance(items, list):+ raise FlowluRetryableError(f"Flowlu response for {path} is missing the 'items' list")++ return items+++def get_rows(+ api_key: str,+ subdomain: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FlowluResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = FLOWLU_ENDPOINTS[endpoint]+ # `redact_values` masks the API key in logged URLs and captured samples. `allow_redirects=False`+ # stops a 30x from replaying the credentialed `api_key` query param off-host (defense-in-depth;+ # Smokescreen already blocks internal hosts).+ session = make_tracked_session(+ headers={"Accept": "application/json"}, redact_values=(api_key,), allow_redirects=False+ )++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.next_page if resume else BASE_PAGE+ if resume and resume.next_page > BASE_PAGE:+ logger.debug(f"Flowlu: resuming {endpoint} from page {page}")++ while True:+ items = _fetch_page(session, api_key, subdomain, config.path, page, logger)++ # An empty `items` page is the end-of-collection signal (page-number pagination with no+ # authoritative `has_more` flag).+ if not items:+ break++ yield items++ page += 1+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(FlowluResumeConfig(next_page=page))+++def flowlu_source(+ api_key: str,+ subdomain: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FlowluResumeConfig],+) -> SourceResponse:+ config = FLOWLU_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ subdomain=subdomain,+ 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, subdomain: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single list endpoint to validate the API key.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(+ headers={"Accept": "application/json"}, redact_values=(api_key,), allow_redirects=False+ )+ try:+ params: dict[str, str | int] = {"api_key": api_key, "page": BASE_PAGE}+ response = session.get(+ f"{base_url(subdomain)}{path}",+ params=params,+ timeout=15,+ )+ except Exception:+ # Don't surface the exception text: `requests` transport errors can embed the prepared URL,+ # which carries the `api_key` query param, and this message can reach editors who can't view secrets.+ return 0, "Could not connect to Flowlu"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Flowlu returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_key: str, subdomain: str) -> tuple[bool, str | None]:+ status, message = check_access(api_key, subdomain)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Flowlu API key"+ return False, message or "Could not validate Flowlu credentials"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/settings.pynew file mode 100644index 000000000000..a481e0cf839b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/settings.py@@ -0,0 +1,38 @@+from dataclasses import dataclass, field+++@dataclass+class FlowluEndpointConfig:+ name: str+ # Path under `https://{subdomain}.flowlu.com/api/v1/module` (e.g. "/crm/account/list").+ path: str+ # Flowlu record IDs are integers unique per entity type within an account, and each endpoint+ # maps to its own warehouse table, so `id` is a safe primary key.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+++# Flowlu REST API list endpoints (`/api/v1/module/<module>/<entity>/list`). All are full-refresh+# only: the list endpoints expose no documented server-side `updated_after`-style filter, so there+# is no genuine incremental cursor to advance (a client-side scan of every page would cost the+# same as a full refresh — see the implementing-warehouse-sources skill). Airbyte's Flowlu+# connector is likewise full-refresh only.+FLOWLU_ENDPOINTS: dict[str, FlowluEndpointConfig] = {+ "accounts": FlowluEndpointConfig(name="accounts", path="/crm/account/list"),+ # Flowlu's API keeps the legacy `lead` entity name for CRM opportunities.+ "leads": FlowluEndpointConfig(name="leads", path="/crm/lead/list"),+ "pipelines": FlowluEndpointConfig(name="pipelines", path="/crm/pipeline/list"),+ "tasks": FlowluEndpointConfig(name="tasks", path="/task/tasks/list"),+ "projects": FlowluEndpointConfig(name="projects", path="/st/projects/list"),+ "invoices": FlowluEndpointConfig(name="invoices", path="/fin/invoice/list"),+ "estimates": FlowluEndpointConfig(name="estimates", path="/fin/estimate/list"),+ "customer_payments": FlowluEndpointConfig(name="customer_payments", path="/fin/customer_payment/list"),+ "transactions": FlowluEndpointConfig(name="transactions", path="/fin/transaction/list"),+ "agile_issues": FlowluEndpointConfig(name="agile_issues", path="/agile/issues/list"),+ "agile_sprints": FlowluEndpointConfig(name="agile_sprints", path="/agile/sprints/list"),+ "timesheets": FlowluEndpointConfig(name="timesheets", path="/timetracker/timesheets/list"),+ "products": FlowluEndpointConfig(name="products", path="/products/product/list"),+}++ENDPOINTS = tuple(FLOWLU_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/source.pyindex c60a2e402f61..282ecaa2d7e5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/source.py@@ -1,30 +1,153 @@-from typing import cast+import re+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+from products.warehouse_sources.backend.temporal.data_imports.sources.flowlu.flowlu import (+ FlowluResumeConfig,+ flowlu_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.flowlu.settings import ENDPOINTS, FLOWLU_ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FlowluSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType+# Flowlu account subdomains are alphanumeric with optional internal hyphens (a valid DNS label:+# no leading or trailing hyphen).+SUBDOMAIN_REGEX = re.compile(r"^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$")+@SourceRegistry.register-class FlowluSource(SimpleSource[FlowluSourceConfig]):+class FlowluSource(ResumableSource[FlowluSourceConfig, FlowluResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.FLOWLU+ @property+ def connection_host_fields(self) -> list[str]:+ # The stored API key is sent to `https://{subdomain}.flowlu.com`, so retargeting+ # `subdomain` must force the editor to re-enter the key (prevents credential exfiltration).+ return ["subdomain"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.FLOWLU,category=DataWarehouseSourceCategory.CRM,label="Flowlu",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Flowlu API key and account subdomain to pull your CRM, project, task, and finance data into the PostHog Data warehouse.++You can create an API key under **Portal Settings → API Settings** in Flowlu. Your subdomain is the first part of your portal URL — for `acme.flowlu.com` the subdomain is `acme`.""",iconPath="/static/services/flowlu.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/flowlu",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="subdomain",+ label="Account subdomain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="acme",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.flowlu.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # Flowlu hosts are per-account subdomains, so match the stable status prefix rather than a+ # fixed hostname. A bad or revoked API key can never be fixed by retrying.+ return {+ "401 Client Error: Unauthorized for url": "Your Flowlu API key is invalid or has been revoked. Generate a new key under Portal Settings → API Settings, then reconnect.",+ "403 Client Error: Forbidden for url": "Your Flowlu API key does not have access to this data. Check the key's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: FlowluSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — Flowlu's list endpoints expose no documented+ # server-side timestamp filter, so there is no incremental cursor to advance.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ 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: FlowluSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if not SUBDOMAIN_REGEX.match(config.subdomain):+ return False, "Flowlu account subdomain is invalid"++ # The API key is account-wide, so a single probe validates access to every schema.+ return validate_credentials(config.api_key, config.subdomain)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FlowluResumeConfig]:+ return ResumableSourceManager[FlowluResumeConfig](inputs, FlowluResumeConfig)++ def source_for_pipeline(+ self,+ config: FlowluSourceConfig,+ resumable_source_manager: ResumableSourceManager[FlowluResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in FLOWLU_ENDPOINTS:+ raise ValueError(f"Unknown Flowlu schema '{inputs.schema_name}'")++ return flowlu_source(+ api_key=config.api_key,+ subdomain=config.subdomain,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/tests/test_flowlu.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/tests/test_flowlu.pynew file mode 100644index 000000000000..54f7dd42489a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/tests/test_flowlu.py@@ -0,0 +1,243 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.flowlu import flowlu+from products.warehouse_sources.backend.temporal.data_imports.sources.flowlu.flowlu import (+ FlowluResumeConfig,+ FlowluRetryableError,+ check_access,+ flowlu_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.flowlu.settings import ENDPOINTS, FLOWLU_ENDPOINTS++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = flowlu._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: FlowluResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[FlowluResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> FlowluResumeConfig | None:+ return self._state++ def save_state(self, data: FlowluResumeConfig) -> None:+ self.saved.append(data)+++def _envelope(items: list[dict], total: int | None = None) -> dict[str, Any]:+ return {"response": {"items": items, "total": total if total is not None else len(items), "count": len(items)}}+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[int, list[dict]], endpoint: str = "accounts"+ ) -> list[dict]:+ def fake_fetch(session: Any, api_key: str, subdomain: str, path: str, page: int, logger: Any) -> list[dict]:+ return pages[page]++ monkeypatch.setattr(flowlu, "_fetch_page", fake_fetch)+ monkeypatch.setattr(flowlu, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="fl-key",+ subdomain="acme",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_follows_pagination_until_empty_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ 1: [{"id": 1}],+ 2: [{"id": 2}],+ 3: [],+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [{"id": 1}, {"id": 2}]++ def test_saves_next_page_after_yielding_each_batch(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ 1: [{"id": 1}],+ 2: [{"id": 2}],+ 3: [],+ }+ self._collect(manager, monkeypatch, pages)+ # State is saved AFTER each non-empty page is yielded, pointing at the next page to fetch.+ assert [s.next_page for s in manager.saved] == [2, 3]++ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(FlowluResumeConfig(next_page=2))+ pages = {+ # Page 1 must never be fetched on resume.+ 2: [{"id": 2}],+ 3: [],+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [{"id": 2}]++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {1: []})+ assert rows == []+ 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(FlowluRetryableError):+ _fetch_page_unwrapped(session, "fl-key", "acme", "/crm/account/list", 1, 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, "fl-key", "acme", "/crm/account/list", 1, MagicMock())++ def test_client_error_message_omits_api_key_and_keeps_status_prefix(self) -> None:+ # `raise_for_status()` would embed the full request URL (with the `api_key` query param) in the+ # error text, which surfaces in sync error logs; the raised message must drop the query string+ # while keeping the "<status> Client Error: <reason> for url" prefix `get_non_retryable_errors`+ # matches on.+ response = MagicMock()+ response.status_code = 401+ response.ok = False+ response.reason = "Unauthorized"+ response.url = "https://acme.flowlu.com/api/v1/module/crm/account/list?api_key=fl-key&page=1"+ response.json.return_value = {}+ response.text = ""+ session = MagicMock()+ session.get.return_value = response++ with pytest.raises(requests.HTTPError) as exc_info:+ _fetch_page_unwrapped(session, "fl-key", "acme", "/crm/account/list", 1, MagicMock())++ message = str(exc_info.value)+ assert "fl-key" not in message+ assert "api_key" not in message+ assert message.startswith("401 Client Error: Unauthorized for url")++ def test_success_returns_items(self) -> None:+ session = self._session_returning(200, _envelope([{"id": 1}]))+ items = _fetch_page_unwrapped(session, "fl-key", "acme", "/crm/account/list", 1, MagicMock())+ assert items == [{"id": 1}]++ @parameterized.expand(+ [+ ("bare_array", [{"id": 1}]),+ ("missing_response_key", {"data": []}),+ ("non_dict_response", {"response": []}),+ ("missing_items", {"response": {"total": 0}}),+ ]+ )+ def test_malformed_payload_is_retryable(self, _name: str, body: Any) -> None:+ session = self._session_returning(200, body)+ with pytest.raises(FlowluRetryableError):+ _fetch_page_unwrapped(session, "fl-key", "acme", "/crm/account/list", 1, MagicMock())++ def test_request_targets_account_host_with_api_key_param(self) -> None:+ session = self._session_returning(200, _envelope([]))+ _fetch_page_unwrapped(session, "fl-key", "acme", "/task/tasks/list", 3, MagicMock())+ args, kwargs = session.get.call_args+ assert args[0] == "https://acme.flowlu.com/api/v1/module/task/tasks/list"+ assert kwargs["params"] == {"api_key": "fl-key", "page": 3}+++class TestCheckAccess:+ def _patch_session(self, response: Any) -> Any:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ return patch.object(flowlu, "make_tracked_session", lambda **kwargs: session)++ @parameterized.expand(+ [+ (200, True, 200, None),+ (401, False, 401, None),+ (403, False, 403, None),+ (500, False, 500, "Flowlu returned HTTP 500"),+ ]+ )+ def test_status_mapping(self, status: int, ok: bool, expected_status: int, expected_message: str | None) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ with self._patch_session(response):+ assert check_access("fl-key", "acme") == (expected_status, expected_message)++ def test_connection_error_maps_to_zero(self) -> None:+ # The message must be a fixed string: `requests` exceptions can embed the prepared URL+ # (carrying the `api_key` query param), so the raw exception text must never be surfaced.+ with self._patch_session(requests.ConnectionError("https://acme.flowlu.com/...?api_key=fl-key")):+ status, message = check_access("fl-key", "acme")+ assert status == 0+ assert message == "Could not connect to Flowlu"++ @parameterized.expand(+ [+ (200, True, None),+ (401, False, "Invalid Flowlu API key"),+ (403, False, "Invalid Flowlu API key"),+ (500, False, "Flowlu returned HTTP 500"),+ ]+ )+ def test_validate_credentials(self, status: int, expected_valid: bool, expected_message: str | None) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ with self._patch_session(response):+ assert validate_credentials("fl-key", "acme") == (expected_valid, expected_message)+++class TestFlowluSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = flowlu_source(+ api_key="fl-key",+ subdomain="acme",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # No stable creation timestamp could be verified across every object, so we don't partition.+ assert response.partition_mode is None++ def test_every_endpoint_uses_id_primary_key(self) -> None:+ assert all(config.primary_keys == ["id"] for config in FLOWLU_ENDPOINTS.values())+ assert set(FLOWLU_ENDPOINTS) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/tests/test_flowlu_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/tests/test_flowlu_source.pynew file mode 100644index 000000000000..652f52cea68d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/tests/test_flowlu_source.py@@ -0,0 +1,159 @@+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.flowlu import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.flowlu.flowlu import FlowluResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.flowlu.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.flowlu.source import FlowluSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FlowluSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestFlowluSource:+ def setup_method(self) -> None:+ self.source = FlowluSource()+ self.team_id = 123+ self.config = FlowluSourceConfig(api_key="fl-key", subdomain="acme")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.FLOWLU++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.label == "Flowlu"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/flowlu"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key", "subdomain"]++ 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_include_subdomain(self) -> None:+ # The API key is sent to the customer-controlled `{subdomain}.flowlu.com` host, so editing+ # the subdomain must force re-entering the key.+ assert self.source.connection_host_fields == ["subdomain"]++ 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=["tasks"])+ assert len(schemas) == 1+ assert schemas[0].name == "tasks"++ 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://acme.flowlu.com/api/v1/module/crm/account/list?api_key=[REDACTED]&page=1",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://acme.flowlu.com/api/v1/module/fin/invoice/list?api_key=[REDACTED]&page=1",+ ),+ ]+ )+ 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://acme.flowlu.com/api/v1/module/task/tasks/list",+ ),+ (+ "rate_limited",+ "429 Client Error: Too Many Requests for url: https://acme.flowlu.com/api/v1/module/crm/lead/list",+ ),+ ]+ )+ 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(+ [+ ("path_traversal", "acme.flowlu.com/evil"),+ ("dotted_host", "evil.example"),+ ("empty", ""),+ ("whitespace", "acme corp"),+ ("leading_hyphen", "-acme"),+ ("trailing_hyphen", "acme-"),+ ]+ )+ def test_validate_credentials_rejects_invalid_subdomain_without_probe(self, _name: str, subdomain: str) -> None:+ config = FlowluSourceConfig(api_key="fl-key", subdomain=subdomain)+ with mock.patch.object(source_module, "validate_credentials") as mock_validate:+ valid, message = self.source.validate_credentials(config, self.team_id)+ assert valid is False+ assert message == "Flowlu account subdomain is invalid"+ mock_validate.assert_not_called()++ @parameterized.expand(+ [+ ("valid", (True, None)),+ ("invalid_key", (False, "Invalid Flowlu API key")),+ ("connect_error", (False, "Could not connect to Flowlu: boom")),+ ]+ )+ def test_validate_credentials_delegates_to_probe(self, _name: str, underlying: tuple[bool, str | None]) -> None:+ # The status → message mapping is covered by the flowlu.validate_credentials unit test; here+ # we only guard that the source extracts the credentials and returns the probe result unchanged.+ with mock.patch.object(source_module, "validate_credentials", return_value=underlying) as mock_validate:+ result = self.source.validate_credentials(self.config, self.team_id)+ assert result == underlying+ mock_validate.assert_called_once_with("fl-key", "acme")++ 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 FlowluResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.flowlu.source.flowlu_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "tasks"+ 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"] == "fl-key"+ assert kwargs["subdomain"] == "acme"+ assert kwargs["endpoint"] == "tasks"+ 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 Flowlu schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)diff --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 3f088c668953..c6d7ebdb0780 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@@ -1366,7 +1366,8 @@ class FloatAppSourceConfig(config.Config):@config.configclass FlowluSourceConfig(config.Config):- pass+ api_key: str+ subdomain: str@config.config