: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 Brex source (#62664)
Tom Owers6aee9bb3ca17
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex b8cc30b632ab..83b35a1d93d5 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -54,6 +54,7 @@ the row lists both.| bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ || braze | HTTP | requests | ✅ || brevo | HTTP | requests | ✅ |+| brex | HTTP | requests | ✅ || buildbetter | HTTP | requests | ✅ || calendly | HTTP | requests | ✅ || campaign_monitor | HTTP | requests | ✅ |@@ -204,7 +205,6 @@ doesn't conflict with concurrent PRs.- box- braintree- branch-- brex- campaign_manager_360- checkout_com- chorusdiff --git a/posthog/temporal/data_imports/sources/brex/brex.py b/posthog/temporal/data_imports/sources/brex/brex.pynew file mode 100644index 000000000000..bccf53c659d5--- /dev/null+++ b/posthog/temporal/data_imports/sources/brex/brex.py@@ -0,0 +1,284 @@+import time+import dataclasses+from collections.abc import Callable, Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.brex.settings import BREX_ENDPOINTS, BrexEndpointConfig+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager++BREX_BASE_URL = "https://api.brex.com"+# Expenses caps `limit` at 100; other endpoints don't document a max, so 100 is used uniformly.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+MAX_RETRY_AFTER_SECONDS = 60++CASH_ACCOUNTS_PATH = "/v2/accounts/cash"+# Injected into cash transaction rows so rows from different cash accounts stay distinguishable.+CASH_ACCOUNT_ID_KEY = "account_id"+++class BrexRetryableError(Exception):+ pass+++class BrexResumeConfig:+ # `next_cursor` of the last fully-yielded page for the endpoint (or current cash account).+ cursor: Optional[str] = None+ # Cash account currently being paged; None for top-level endpoints.+ account_id: Optional[str] = None+ # Cash accounts already fully synced in this run.+ completed_account_ids: list[str] = dataclasses.field(default_factory=list)+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }+++def _to_rfc3339(value: Any) -> Optional[str]:+ """Coerce an incremental cursor value to the RFC 3339 date-time format Brex's+ `*_start` filters expect. Watermarks arrive as datetimes, dates, or ISO strings+ depending on the endpoint's incremental field type."""+ if value is None:+ return None+ if isinstance(value, datetime):+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return dt.isoformat().replace("+00:00", "Z")+ if isinstance(value, date):+ return f"{value.isoformat()}T00:00:00Z"+ if isinstance(value, str):+ # Date-only strings (e.g. a posted_at_date watermark) need a time component.+ if len(value) == 10:+ return f"{value}T00:00:00Z"+ return value+ return None+++def _build_url(path: str, params: dict[str, Any]) -> str:+ clean_params = {key: value for key, value in params.items() if value is not None}+ if not clean_params:+ return f"{BREX_BASE_URL}{path}"+ return f"{BREX_BASE_URL}{path}?{urlencode(clean_params)}"+++def _build_params(+ config: BrexEndpointConfig,+ cursor: Optional[str],+ incremental_value: Optional[str],+) -> dict[str, Any]:+ params: dict[str, Any] = {"limit": PAGE_SIZE}+ if cursor is not None:+ params["cursor"] = cursor+ # Brex docs don't state whether the cursor re-encodes the original filters, so the+ # timestamp filter is re-sent on every page to be safe.+ if config.incremental_param is not None and incremental_value is not None:+ params[config.incremental_param] = incremental_value+ return params+++def validate_credentials(api_key: str) -> bool:+ """Confirm the API user token is genuine. /v2/users/me is a cheap authenticated probe.++ A 403 means the token is valid but wasn't granted the Team scope — users may+ legitimately scope tokens to only the endpoints they want to sync, so it's accepted.+ """+ try:+ response = make_tracked_session().get(+ f"{BREX_BASE_URL}/v2/users/me",+ headers=_get_headers(api_key),+ timeout=10,+ )+ return response.status_code in (200, 403)+ except Exception:+ return False+++PageFetcher = Callable[[str], dict[str, Any]]+++def _make_page_fetcher(api_key: str, logger: FilteringBoundLogger) -> PageFetcher:+ headers = _get_headers(api_key)++ @retry(+ retry=retry_if_exception_type((BrexRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+ )+ def fetch_page(page_url: str) -> dict[str, Any]:+ response = make_tracked_session().get(page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ # Brex rate-limits at 1,000 requests per 60s. Honor Retry-After when present,+ # otherwise tenacity's exponential backoff covers it.+ if response.status_code == 429:+ retry_after = response.headers.get("Retry-After")+ if retry_after is not None:+ try:+ time.sleep(min(int(retry_after), MAX_RETRY_AFTER_SECONDS))+ except ValueError:+ pass+ raise BrexRetryableError(f"Brex API rate limited: status=429, url={page_url}")++ if response.status_code >= 500:+ raise BrexRetryableError(f"Brex API error (retryable): status={response.status_code}, url={page_url}")++ if not response.ok:+ logger.error(f"Brex API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response.json()++ return fetch_page+++def _list_cash_account_ids(fetch_page: PageFetcher, logger: FilteringBoundLogger) -> list[str]:+ account_ids: list[str] = []+ cursor: Optional[str] = None++ while True:+ url = _build_url(CASH_ACCOUNTS_PATH, {"limit": PAGE_SIZE, "cursor": cursor})+ data = fetch_page(url)+ items = data.get("items", []) or []+ account_ids.extend(item["id"] for item in items)++ cursor = data.get("next_cursor")+ if not cursor:+ break++ logger.debug(f"Brex: found {len(account_ids)} cash accounts")+ return account_ids+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[BrexResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = BREX_ENDPOINTS[endpoint]+ fetch_page = _make_page_fetcher(api_key, logger)++ incremental_value = _to_rfc3339(db_incremental_field_last_value) if should_use_incremental_field else None++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None:+ logger.debug(+ f"Brex: resuming {endpoint}. cursor={resume_config.cursor}, account_id={resume_config.account_id}, "+ f"completed_account_ids={resume_config.completed_account_ids}"+ )++ if config.fan_out_cash_accounts:+ yield from _get_fan_out_rows(+ config, fetch_page, logger, resumable_source_manager, resume_config, incremental_value+ )+ return++ cursor = resume_config.cursor if resume_config is not None else None++ while True:+ url = _build_url(config.path, _build_params(config, cursor, incremental_value))+ data = fetch_page(url)+ items = data.get("items", []) or []++ if items:+ yield items++ cursor = data.get("next_cursor")+ if not cursor:+ break++ # Save after yielding so a crash re-yields the last batch (merge dedupes on+ # primary key) rather than skipping it.+ resumable_source_manager.save_state(BrexResumeConfig(cursor=cursor))+++def _get_fan_out_rows(+ config: BrexEndpointConfig,+ fetch_page: PageFetcher,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[BrexResumeConfig],+ resume_config: Optional[BrexResumeConfig],+ incremental_value: Optional[str],+) -> Iterator[list[dict[str, Any]]]:+ account_ids = _list_cash_account_ids(fetch_page, logger)++ completed_account_ids = list(resume_config.completed_account_ids) if resume_config is not None else []+ completed_set = set(completed_account_ids)++ for account_id in account_ids:+ if account_id in completed_set:+ continue++ cursor = resume_config.cursor if resume_config is not None and resume_config.account_id == account_id else None+ path = config.path.format(account_id=account_id)++ while True:+ url = _build_url(path, _build_params(config, cursor, incremental_value))+ data = fetch_page(url)+ items = data.get("items", []) or []++ if items:+ yield [{**item, CASH_ACCOUNT_ID_KEY: account_id} for item in items]++ cursor = data.get("next_cursor")+ if not cursor:+ break++ resumable_source_manager.save_state(+ BrexResumeConfig(+ cursor=cursor,+ account_id=account_id,+ completed_account_ids=list(completed_account_ids),+ )+ )++ completed_account_ids.append(account_id)+ completed_set.add(account_id)+ resumable_source_manager.save_state(BrexResumeConfig(completed_account_ids=list(completed_account_ids)))+++def brex_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[BrexResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = BREX_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ # Brex doesn't expose a sort param and doesn't document list ordering. "desc" makes the+ # pipeline commit the incremental watermark only after a fully successful run, which is+ # the safe choice when ascending order can't be requested.+ sort_mode="desc" if config.incremental_fields else "asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/posthog/temporal/data_imports/sources/brex/settings.py b/posthog/temporal/data_imports/sources/brex/settings.pynew file mode 100644index 000000000000..03f2d9cf8375--- /dev/null+++ b/posthog/temporal/data_imports/sources/brex/settings.py@@ -0,0 +1,106 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class BrexEndpointConfig:+ name: str+ path: str+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Server-side timestamp filter query param (RFC 3339 date-time, "on or after" semantics).+ incremental_param: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable datetime field used for partitioning. Never an updated_at-style field, which+ # would rewrite partitions on every sync.+ partition_key: Optional[str] = None+ # When True, the endpoint is paged once per cash account listed from /v2/accounts/cash,+ # with `{account_id}` in the path resolved per account.+ fan_out_cash_accounts: bool = False+++# Brex splits its data across sub-APIs (Transactions, Expenses, Team, Payments, Budgets) that+# all share the same host, bearer auth, and cursor pagination (`cursor` + `limit` params,+# `next_cursor` + `items` in the response body).+#+# Incremental sync is only advertised where Brex exposes a server-side timestamp filter:+# transactions support `posted_at_start` (filters on `posted_at_date`) and expenses support+# `updated_at_start` (filters on `updated_at`). Team/vendors/budgets endpoints have no such+# filter, so they are full refresh only.+BREX_ENDPOINTS: dict[str, BrexEndpointConfig] = {+ "card_transactions": BrexEndpointConfig(+ name="card_transactions",+ path="/v2/transactions/card/primary",+ incremental_param="posted_at_start",+ partition_key="posted_at_date",+ incremental_fields=[+ {+ "label": "posted_at_date",+ "type": IncrementalFieldType.Date,+ "field": "posted_at_date",+ "field_type": IncrementalFieldType.Date,+ },+ ],+ ),+ "cash_transactions": BrexEndpointConfig(+ name="cash_transactions",+ path="/v2/transactions/cash/{account_id}",+ # Transaction ids are likely globally unique, but the docs don't guarantee it across+ # cash accounts, so the injected account id is part of the composite key.+ primary_keys=["account_id", "id"],+ incremental_param="posted_at_start",+ partition_key="posted_at_date",+ fan_out_cash_accounts=True,+ incremental_fields=[+ {+ "label": "posted_at_date",+ "type": IncrementalFieldType.Date,+ "field": "posted_at_date",+ "field_type": IncrementalFieldType.Date,+ },+ ],+ ),+ "expenses": BrexEndpointConfig(+ name="expenses",+ path="/v1/expenses",+ incremental_param="updated_at_start",+ # No partition key: the only stable datetime candidates (purchased_at, submitted_at)+ # are nullable on the expense object.+ incremental_fields=[+ {+ "label": "updated_at",+ "type": IncrementalFieldType.DateTime,+ "field": "updated_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ "users": BrexEndpointConfig(+ name="users",+ path="/v2/users",+ ),+ "departments": BrexEndpointConfig(+ name="departments",+ path="/v2/departments",+ ),+ "locations": BrexEndpointConfig(+ name="locations",+ path="/v2/locations",+ ),+ "vendors": BrexEndpointConfig(+ name="vendors",+ path="/v1/vendors",+ ),+ "budgets": BrexEndpointConfig(+ name="budgets",+ path="/v2/budgets",+ primary_keys=["budget_id"],+ ),+}++ENDPOINTS = tuple(BREX_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in BREX_ENDPOINTS.items() if config.incremental_fields+}diff --git a/posthog/temporal/data_imports/sources/brex/source.py b/posthog/temporal/data_imports/sources/brex/source.pyindex 41cdf646637a..5b6feb74b487 100644--- a/posthog/temporal/data_imports/sources/brex/source.py+++ b/posthog/temporal/data_imports/sources/brex/source.py@@ -1,29 +1,119 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.brex.brex import (+ BrexResumeConfig,+ brex_source,+ validate_credentials as validate_brex_credentials,+)+from posthog.temporal.data_imports.sources.brex.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import BrexSourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class BrexSource(SimpleSource[BrexSourceConfig]):+class BrexSource(ResumableSource[BrexSourceConfig, BrexResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.BREX+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.brex.com": "Brex authentication failed. Your API user token is invalid or has expired — Brex tokens expire after 90 days without API activity. Please generate a new token in your Brex dashboard and reconnect.",+ "403 Client Error: Forbidden for url: https://api.brex.com": "Brex denied access. Please check that your API user token has the required scopes for the tables you are syncing, and that the token's user is still active.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.BREX,label="Brex",+ caption="""Enter your Brex API user token to pull your Brex data into the PostHog Data warehouse.++You can create a token in your [Brex dashboard](https://dashboard.brex.com/settings/developer) under Settings → Developer. Grant read access to the data you want to sync: Transactions and Accounts (card and cash transactions), Expenses, Team (users, departments, locations), Payments (vendors), and Budgets.++Note: Brex tokens expire after 90 days without API activity, so a token that hasn't been used recently may need to be regenerated.""",iconPath="/static/services/brex.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/brex",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API user token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="bxt_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: BrexSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = []+ for endpoint in ENDPOINTS:+ incremental_fields = INCREMENTAL_FIELDS.get(endpoint)+ schemas.append(+ SourceSchema(+ name=endpoint,+ supports_incremental=incremental_fields is not None,+ supports_append=incremental_fields is not None,+ incremental_fields=incremental_fields or [],+ )+ )++ 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: BrexSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_brex_credentials(config.api_key):+ return True, None++ return False, "Invalid Brex API user token. Note that Brex tokens expire after 90 days without API activity."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BrexResumeConfig]:+ return ResumableSourceManager[BrexResumeConfig](inputs, BrexResumeConfig)++ def source_for_pipeline(+ self,+ config: BrexSourceConfig,+ resumable_source_manager: ResumableSourceManager[BrexResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return brex_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/posthog/temporal/data_imports/sources/brex/tests/test_brex.py b/posthog/temporal/data_imports/sources/brex/tests/test_brex.pynew file mode 100644index 000000000000..c5b45806b470--- /dev/null+++ b/posthog/temporal/data_imports/sources/brex/tests/test_brex.py@@ -0,0 +1,408 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest import mock++import requests++from posthog.temporal.data_imports.sources.brex.brex import (+ BrexResumeConfig,+ _build_params,+ _build_url,+ _to_rfc3339,+ brex_source,+ get_rows,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.brex.settings import BREX_ENDPOINTS, ENDPOINTS, INCREMENTAL_FIELDS+++def _make_manager(resume_state: BrexResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _page(items: list[dict[str, Any]], next_cursor: str | None) -> dict[str, Any]:+ return {"items": items, "next_cursor": next_cursor}+++def _response(payload: dict[str, Any], status_code: int = 200, headers: dict[str, str] | None = None) -> mock.MagicMock:+ response = mock.MagicMock()+ response.json.return_value = payload+ response.status_code = status_code+ response.ok = status_code < 400+ response.headers = headers or {}+ return response+++class TestToRfc3339:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (None, None),+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02T03:04:05Z"),+ (datetime(2024, 1, 2, 3, 4, 5), "2024-01-02T03:04:05Z"),+ (date(2024, 1, 2), "2024-01-02T00:00:00Z"),+ ("2024-01-02", "2024-01-02T00:00:00Z"),+ ("2024-01-02T03:04:05Z", "2024-01-02T03:04:05Z"),+ (1700000000, None),+ ],+ )+ def test_to_rfc3339_values(self, value, expected):+ assert _to_rfc3339(value) == expected+++class TestBuildParams:+ def test_always_includes_limit(self):+ params = _build_params(BREX_ENDPOINTS["users"], cursor=None, incremental_value=None)+ assert params == {"limit": 100}++ def test_includes_cursor_when_set(self):+ params = _build_params(BREX_ENDPOINTS["users"], cursor="abc", incremental_value=None)+ assert params["cursor"] == "abc"++ @pytest.mark.parametrize(+ "endpoint, expected_param",+ [+ ("card_transactions", "posted_at_start"),+ ("cash_transactions", "posted_at_start"),+ ("expenses", "updated_at_start"),+ ],+ )+ def test_incremental_param_included_for_incremental_endpoints(self, endpoint, expected_param):+ params = _build_params(BREX_ENDPOINTS[endpoint], cursor=None, incremental_value="2024-01-02T00:00:00Z")+ assert params[expected_param] == "2024-01-02T00:00:00Z"++ @pytest.mark.parametrize("endpoint", ["users", "departments", "locations", "vendors", "budgets"])+ def test_incremental_value_ignored_for_full_refresh_endpoints(self, endpoint):+ params = _build_params(BREX_ENDPOINTS[endpoint], cursor=None, incremental_value="2024-01-02T00:00:00Z")+ assert params == {"limit": 100}++ def test_incremental_param_omitted_without_value(self):+ params = _build_params(BREX_ENDPOINTS["expenses"], cursor=None, incremental_value=None)+ assert "updated_at_start" not in params+++class TestBuildUrl:+ def test_no_params(self):+ assert _build_url("/v2/users", {}) == "https://api.brex.com/v2/users"++ def test_drops_none_values_and_encodes(self):+ url = _build_url("/v1/expenses", {"limit": 100, "cursor": None, "updated_at_start": "2024-01-02T00:00:00Z"})+ assert url == "https://api.brex.com/v1/expenses?limit=100&updated_at_start=2024-01-02T00%3A00%3A00Z"+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected",+ [+ (200, True),+ # A valid token without the Team scope returns 403 — accepted at source-create.+ (403, True),+ (401, False),+ (500, False),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.make_tracked_session")+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):+ mock_session.return_value.get.return_value = _response({}, status_code=status_code)++ assert validate_credentials("bxt_token") is expected++ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.make_tracked_session")+ def test_validate_credentials_swallows_exceptions(self, mock_session):+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("bxt_token") is False++ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.make_tracked_session")+ def test_validate_credentials_sends_bearer_header(self, mock_session):+ mock_session.return_value.get.return_value = _response({}, status_code=200)++ validate_credentials("bxt_token")++ headers = mock_session.return_value.get.call_args.kwargs["headers"]+ assert headers["Authorization"] == "Bearer bxt_token"+++class TestGetRows:+ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.make_tracked_session")+ def test_paginates_via_next_cursor(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response(_page([{"id": "u1"}, {"id": "u2"}], "cursor-2")),+ _response(_page([{"id": "u3"}], None)),+ ]++ manager = _make_manager()+ batches = list(get_rows("bxt_token", "users", mock.MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == ["u1", "u2", "u3"]+ first_url = mock_session.return_value.get.call_args_list[0].args[0]+ second_url = mock_session.return_value.get.call_args_list[1].args[0]+ assert first_url == "https://api.brex.com/v2/users?limit=100"+ assert "cursor=cursor-2" in second_url+ # State is saved only while a next page exists, after the batch has been yielded.+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == BrexResumeConfig(cursor="cursor-2")++ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.make_tracked_session")+ def test_resumes_from_saved_state(self, mock_session):+ mock_session.return_value.get.return_value = _response(_page([{"id": "u9"}], None))++ manager = _make_manager(BrexResumeConfig(cursor="cursor-5"))+ list(get_rows("bxt_token", "users", mock.MagicMock(), manager))++ first_url = mock_session.return_value.get.call_args_list[0].args[0]+ assert "cursor=cursor-5" in first_url++ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.make_tracked_session")+ def test_empty_response_stops_without_saving_state(self, mock_session):+ mock_session.return_value.get.return_value = _response(_page([], None))++ manager = _make_manager()+ batches = list(get_rows("bxt_token", "expenses", mock.MagicMock(), manager))++ assert batches == []+ manager.save_state.assert_not_called()++ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.make_tracked_session")+ def test_incremental_run_passes_server_side_filter(self, mock_session):+ mock_session.return_value.get.return_value = _response(_page([{"id": "e1"}], None))++ manager = _make_manager()+ list(+ get_rows(+ "bxt_token",+ "expenses",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),+ )+ )++ url = mock_session.return_value.get.call_args.args[0]+ assert "updated_at_start=2024-01-02T00%3A00%3A00Z" in url++ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.make_tracked_session")+ def test_full_refresh_run_has_no_filter(self, mock_session):+ mock_session.return_value.get.return_value = _response(_page([{"id": "e1"}], None))++ manager = _make_manager()+ list(get_rows("bxt_token", "expenses", mock.MagicMock(), manager))++ url = mock_session.return_value.get.call_args.args[0]+ assert "updated_at_start" not in url++ @mock.patch("tenacity.nap.time.sleep")+ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.time")+ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.make_tracked_session")+ def test_429_honors_retry_after_then_retries(self, mock_session, mock_time, mock_nap):+ mock_session.return_value.get.side_effect = [+ _response({}, status_code=429, headers={"Retry-After": "7"}),+ _response(_page([{"id": "u1"}], None)),+ ]++ manager = _make_manager()+ batches = list(get_rows("bxt_token", "users", mock.MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == ["u1"]+ mock_time.sleep.assert_called_once_with(7)++ @mock.patch("tenacity.nap.time.sleep")+ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.time")+ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.make_tracked_session")+ def test_429_with_unparseable_retry_after_still_retries(self, mock_session, mock_time, mock_nap):+ mock_session.return_value.get.side_effect = [+ _response({}, status_code=429, headers={"Retry-After": "not-a-number"}),+ _response(_page([{"id": "u1"}], None)),+ ]++ manager = _make_manager()+ batches = list(get_rows("bxt_token", "users", mock.MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == ["u1"]+ mock_time.sleep.assert_not_called()++ @mock.patch("tenacity.nap.time.sleep")+ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.make_tracked_session")+ def test_5xx_is_retried(self, mock_session, mock_nap):+ mock_session.return_value.get.side_effect = [+ _response({}, status_code=502),+ _response(_page([{"id": "u1"}], None)),+ ]++ manager = _make_manager()+ batches = list(get_rows("bxt_token", "users", mock.MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == ["u1"]+ assert mock_session.return_value.get.call_count == 2++ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.make_tracked_session")+ def test_4xx_raises_immediately(self, mock_session):+ response = _response({}, status_code=401)+ response.raise_for_status.side_effect = requests.HTTPError(+ "401 Client Error: Unauthorized for url: https://api.brex.com/v2/users", response=response+ )+ response.text = "unauthorized"+ mock_session.return_value.get.return_value = response++ manager = _make_manager()+ with pytest.raises(requests.HTTPError):+ list(get_rows("bxt_token", "users", mock.MagicMock(), manager))++ assert mock_session.return_value.get.call_count == 1+++class TestGetRowsCashFanOut:+ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.make_tracked_session")+ def test_fans_out_over_cash_accounts_and_injects_account_id(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response(_page([{"id": "acc_1"}, {"id": "acc_2"}], None)),+ _response(_page([{"id": "tx_1", "posted_at_date": "2024-01-01"}], None)),+ _response(_page([{"id": "tx_2", "posted_at_date": "2024-01-02"}], None)),+ ]++ manager = _make_manager()+ batches = list(get_rows("bxt_token", "cash_transactions", mock.MagicMock(), manager))++ rows = [item for batch in batches for item in batch]+ assert [(row["id"], row["account_id"]) for row in rows] == [("tx_1", "acc_1"), ("tx_2", "acc_2")]++ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert urls[0] == "https://api.brex.com/v2/accounts/cash?limit=100"+ assert urls[1].startswith("https://api.brex.com/v2/transactions/cash/acc_1")+ assert urls[2].startswith("https://api.brex.com/v2/transactions/cash/acc_2")++ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.make_tracked_session")+ def test_saves_completed_accounts_between_accounts(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response(_page([{"id": "acc_1"}, {"id": "acc_2"}], None)),+ _response(_page([{"id": "tx_1"}], "cursor-a")),+ _response(_page([{"id": "tx_2"}], None)),+ _response(_page([{"id": "tx_3"}], None)),+ ]++ manager = _make_manager()+ list(get_rows("bxt_token", "cash_transactions", mock.MagicMock(), manager))++ saved_states = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved_states == [+ BrexResumeConfig(cursor="cursor-a", account_id="acc_1", completed_account_ids=[]),+ BrexResumeConfig(cursor=None, account_id=None, completed_account_ids=["acc_1"]),+ BrexResumeConfig(cursor=None, account_id=None, completed_account_ids=["acc_1", "acc_2"]),+ ]++ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.make_tracked_session")+ def test_resume_skips_completed_accounts_and_uses_cursor(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response(_page([{"id": "acc_1"}, {"id": "acc_2"}], None)),+ _response(_page([{"id": "tx_9"}], None)),+ ]++ manager = _make_manager(+ BrexResumeConfig(cursor="cursor-mid", account_id="acc_2", completed_account_ids=["acc_1"])+ )+ batches = list(get_rows("bxt_token", "cash_transactions", mock.MagicMock(), manager))++ rows = [item for batch in batches for item in batch]+ assert [(row["id"], row["account_id"]) for row in rows] == [("tx_9", "acc_2")]++ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert len(urls) == 2+ assert "transactions/cash/acc_2" in urls[1]+ assert "cursor=cursor-mid" in urls[1]++ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.make_tracked_session")+ def test_resume_cursor_not_applied_to_other_accounts(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response(_page([{"id": "acc_1"}], None)),+ _response(_page([{"id": "tx_1"}], None)),+ ]++ manager = _make_manager(BrexResumeConfig(cursor="cursor-mid", account_id="acc_gone", completed_account_ids=[]))+ list(get_rows("bxt_token", "cash_transactions", mock.MagicMock(), manager))++ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert "cursor=" not in urls[1]++ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.make_tracked_session")+ def test_paginates_cash_account_listing(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response(_page([{"id": "acc_1"}], "acc-cursor-2")),+ _response(_page([{"id": "acc_2"}], None)),+ _response(_page([], None)),+ _response(_page([], None)),+ ]++ manager = _make_manager()+ list(get_rows("bxt_token", "cash_transactions", mock.MagicMock(), manager))++ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert "accounts/cash" in urls[0]+ assert "cursor=acc-cursor-2" in urls[1]+ assert "transactions/cash/acc_1" in urls[2]+ assert "transactions/cash/acc_2" in urls[3]++ @mock.patch("posthog.temporal.data_imports.sources.brex.brex.make_tracked_session")+ def test_incremental_filter_applied_per_account(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response(_page([{"id": "acc_1"}], None)),+ _response(_page([{"id": "tx_1"}], None)),+ ]++ manager = _make_manager()+ list(+ get_rows(+ "bxt_token",+ "cash_transactions",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-01-02",+ )+ )++ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ # Account listing carries no filter; the per-account transaction call does.+ assert "posted_at_start" not in urls[0]+ assert "posted_at_start=2024-01-02T00%3A00%3A00Z" in urls[1]+++class TestBrexSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = BREX_ENDPOINTS[endpoint]+ response = brex_source("bxt_token", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ if config.incremental_fields:+ assert response.sort_mode == "desc"+ else:+ assert response.sort_mode == "asc"+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_format == "month"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_cash_transactions_use_composite_primary_key(self):+ response = brex_source("bxt_token", "cash_transactions", mock.MagicMock(), _make_manager())+ assert response.primary_keys == ["account_id", "id"]++ def test_budgets_primary_key_is_budget_id(self):+ response = brex_source("bxt_token", "budgets", mock.MagicMock(), _make_manager())+ assert response.primary_keys == ["budget_id"]++ @pytest.mark.parametrize("config", list(BREX_ENDPOINTS.values()))+ def test_partition_keys_are_stable_posted_dates(self, config):+ if config.partition_key:+ assert config.partition_key == "posted_at_date"++ def test_incremental_fields_only_declared_for_filterable_endpoints(self):+ assert set(INCREMENTAL_FIELDS.keys()) == {"card_transactions", "cash_transactions", "expenses"}diff --git a/posthog/temporal/data_imports/sources/brex/tests/test_brex_source.py b/posthog/temporal/data_imports/sources/brex/tests/test_brex_source.pynew file mode 100644index 000000000000..56c360cd85b3--- /dev/null+++ b/posthog/temporal/data_imports/sources/brex/tests/test_brex_source.py@@ -0,0 +1,163 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.brex.brex import BrexResumeConfig+from posthog.temporal.data_imports.sources.brex.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.brex.source import BrexSource+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import BrexSourceConfig++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestBrexSource:+ def setup_method(self):+ self.source = BrexSource()+ self.team_id = 123+ self.config = BrexSourceConfig(api_key="bxt_test_token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.BREX++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Brex"+ assert config.label == "Brex"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/brex.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ token_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ def test_caption_mentions_token_expiry(self):+ config = self.source.get_source_config+ assert config.caption is not None+ assert "90 days" in config.caption++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.brex.com/v2/transactions/card/primary?limit=100",+ "403 Client Error: Forbidden for url: https://api.brex.com/v1/expenses",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ def test_non_retryable_401_message_mentions_token_expiry(self):+ non_retryable_errors = self.source.get_non_retryable_errors()+ message = non_retryable_errors["401 Client Error: Unauthorized for url: https://api.brex.com"]+ assert message is not None+ assert "90 days" in message++ @pytest.mark.parametrize(+ "other_vendor_error",+ [+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",+ "500 Server Error for url: https://api.brex.com/v1/expenses",+ "429 Client Error: Too Many Requests for url: https://api.brex.com/v2/users",+ ],+ )+ def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_vendor_error for key in non_retryable_errors)++ def test_get_schemas(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ incremental = {schema.name for schema in schemas if schema.supports_incremental}+ # Only transactions and expenses expose a server-side timestamp filter.+ assert incremental == {"card_transactions", "cash_transactions", "expenses"}++ @pytest.mark.parametrize("endpoint", ["card_transactions", "cash_transactions", "expenses"])+ def test_incremental_schemas_advertise_their_fields(self, endpoint):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas[endpoint].incremental_fields == INCREMENTAL_FIELDS[endpoint]+ assert schemas[endpoint].supports_append is True++ @pytest.mark.parametrize("endpoint", ["users", "departments", "locations", "vendors", "budgets"])+ def test_full_refresh_schemas_have_no_incremental_fields(self, endpoint):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas[endpoint].incremental_fields == []+ assert schemas[endpoint].supports_incremental is False+ assert schemas[endpoint].supports_append is False++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["expenses"])+ assert len(schemas) == 1+ assert schemas[0].name == "expenses"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "mock_return, expected_valid",+ [+ (True, True),+ (False, False),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.brex.source.validate_brex_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid):+ 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+ if expected_valid:+ assert error_message is None+ else:+ assert error_message is not None+ assert "90 days" in error_message+ mock_validate.assert_called_once_with(self.config.api_key)++ def test_get_resumable_source_manager_binds_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is BrexResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.brex.source.brex_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_brex_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "expenses"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-01T00:00:00Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_brex_source.assert_called_once()+ kwargs = mock_brex_source.call_args.kwargs+ assert kwargs["api_key"] == "bxt_test_token"+ assert kwargs["endpoint"] == "expenses"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01T00:00:00Z"++ @mock.patch("posthog.temporal.data_imports.sources.brex.source.brex_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_brex_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "users"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-01-01T00:00:00Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_brex_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex b8081dad5da3..52c83a2dffbf 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -274,7 +274,7 @@ class BrevoSourceConfig(config.Config):@config.configclass BrexSourceConfig(config.Config):- pass+ api_key: str@config.config