Skip to content

: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.

feat(data-warehouse): implement braintree import source (#62939)

Tom Owers799b8dfa5f7e
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index bbcc50471ef5..4aafa5b14961 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.
| bamboohr | HTTP | requests | ✅ |
| bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) |
| bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ |
+| braintree | HTTP (GraphQL) | requests | ✅ |
| braze | HTTP | requests | ✅ |
| brevo | HTTP | requests | ✅ |
| brex | HTTP | requests | ✅ |
@@ -219,7 +220,6 @@ doesn't conflict with concurrent PRs.
- azure_blob
- bigcommerce
- box
-- braintree
- branch
- campaign_manager_360
- checkout_com
diff --git a/posthog/temporal/data_imports/sources/braintree/braintree.py b/posthog/temporal/data_imports/sources/braintree/braintree.py
new file mode 100644
index 000000000000..c35c3595756f
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/braintree/braintree.py
@@ -0,0 +1,214 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+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 posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.braintree.settings import BRAINTREE_ENDPOINTS, BraintreeEndpointConfig
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+BRAINTREE_HOSTS = {
+ "production": "https://payments.braintree-api.com/graphql",
+ "sandbox": "https://payments.sandbox.braintree-api.com/graphql",
+}
+# Pinned GraphQL API version (date-versioned header, required).
+BRAINTREE_VERSION = "2019-01-01"
+PAGE_SIZE = 100
+# Braintree recommends generous timeouts due to async transaction processing.
+REQUEST_TIMEOUT_SECONDS = 120
+MAX_RETRY_ATTEMPTS = 5
+
+
+class BraintreeRetryableError(Exception):
+ pass
+
+
+class BraintreeGraphQLError(Exception):
+ pass
+
+
+class BraintreeResumeConfig:
+ # Relay-style pagination: `after` is the cursor of the last edge consumed;
+ # the search input is rebuilt deterministically from job inputs on resume.
+ after: str
+
+
+def _get_session(public_key: str, private_key: str) -> requests.Session:
+ session = make_tracked_session(
+ headers={"Braintree-Version": BRAINTREE_VERSION},
+ redact_values=(private_key,),
+ )
+ session.auth = (public_key, private_key)
+ return session
+
+
+def _base_url(environment: str) -> str:
+ host = BRAINTREE_HOSTS.get(environment)
+ if host is None:
+ raise ValueError(f"Invalid Braintree environment: {environment}")
+ return host
+
+
+def _format_created_at(value: Any) -> str:
+ """Format an incremental cursor for a createdAt greaterThanOrEqualTo filter (ISO 8601 UTC)."""
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return value.strftime("%Y-%m-%dT00:00:00Z")
+ return str(value)
+
+
+def _build_query(config: BraintreeEndpointConfig) -> str:
+ return f"""
+query ($input: {config.input_type}, $first: Int!, $after: String) {{
+ search {{
+ {config.search_field} (input: $input, first: $first, after: $after) {{
+ pageInfo {{ hasNextPage }}
+ edges {{
+ cursor
+ node {{
+{config.node_fields}
+ }}
+ }}
+ }}
+ }}
+}}
+"""
+
+
+def _execute(
+ session: requests.Session,
+ url: str,
+ query: str,
+ variables: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ response = session.post(url, json={"query": query, "variables": variables}, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise BraintreeRetryableError(f"Braintree API error (retryable): status={response.status_code}")
+
+ if not response.ok:
+ logger.error(f"Braintree API error: status={response.status_code}, body={response.text}")
+ response.raise_for_status()
+
+ body = response.json()
+ errors = body.get("errors")
+ if errors:
+ message = "; ".join(str(error.get("message", error)) for error in errors)
+ raise BraintreeGraphQLError(f"Braintree GraphQL error: {message}")
+
+ return body.get("data") or {}
+
+
+class _NoopLogger:
+ def error(self, *args: Any, **kwargs: Any) -> None:
+ return None
+
+
+def validate_credentials(environment: str, public_key: str, private_key: str) -> bool:
+ """Confirm the key pair is valid with the GraphQL ping query."""
+ try:
+ session = _get_session(public_key, private_key)
+ data = _execute(session, _base_url(environment), "query { ping }", {}, _NoopLogger()) # type: ignore[arg-type]
+ return data.get("ping") == "pong"
+ except Exception:
+ return False
+
+
+def get_rows(
+ environment: str,
+ public_key: str,
+ private_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BraintreeResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = BRAINTREE_ENDPOINTS[endpoint]
+ session = _get_session(public_key, private_key)
+ url = _base_url(environment)
+ query = _build_query(config)
+
+ search_input: dict[str, Any] = {}
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ # `greaterThanOrEqualTo` re-fetches the boundary row (merge dedupes on
+ # primary key) so records sharing the watermark are never skipped.
+ search_input = {"createdAt": {"greaterThanOrEqualTo": _format_created_at(db_incremental_field_last_value)}}
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ after: Optional[str] = resume_config.after if resume_config is not None else None
+ if after is not None:
+ logger.debug(f"Braintree: resuming {endpoint} from cursor")
+
+ @retry(
+ retry=retry_if_exception_type((BraintreeRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=2, max=90),
+ reraise=True,
+ )
+ def execute(variables: dict[str, Any]) -> dict[str, Any]:
+ return _execute(session, url, query, variables, logger)
+
+ while True:
+ data = execute({"input": search_input or None, "first": PAGE_SIZE, "after": after})
+ connection = ((data.get("search") or {}).get(config.search_field)) or {}
+ edges = connection.get("edges") or []
+ items = [edge.get("node") for edge in edges if edge.get("node")]
+
+ if items:
+ yield items
+
+ has_next = bool((connection.get("pageInfo") or {}).get("hasNextPage"))
+ last_cursor = edges[-1].get("cursor") if edges else None
+ if not has_next or not last_cursor or not items:
+ break
+
+ after = last_cursor
+ # Save state AFTER yielding the page so a crash re-yields the last page
+ # (merge dedupes on primary key) rather than skipping it.
+ resumable_source_manager.save_state(BraintreeResumeConfig(after=after))
+
+
+def braintree_source(
+ environment: str,
+ public_key: str,
+ private_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BraintreeResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = BRAINTREE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ environment=environment,
+ public_key=public_key,
+ private_key=private_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_key],
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[config.partition_key],
+ # Search result ordering is undocumented, so the pipeline defers the
+ # watermark commit until a run completes.
+ sort_mode="desc",
+ )
diff --git a/posthog/temporal/data_imports/sources/braintree/settings.py b/posthog/temporal/data_imports/sources/braintree/settings.py
new file mode 100644
index 000000000000..edeb367ddd6a
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/braintree/settings.py
@@ -0,0 +1,86 @@
+from dataclasses import dataclass, field
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+_CREATED_AT_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "createdAt",
+ "type": IncrementalFieldType.DateTime,
+ "field": "createdAt",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+# Node field selections per stream — conservative, well-documented fields only.
+_TRANSACTION_FIELDS = """
+ id
+ legacyId
+ createdAt
+ status
+ amount { value currencyCode }
+ orderId
+ merchantAccountId
+ paymentMethodSnapshot { __typename }
+"""
+
+_REFUND_FIELDS = """
+ id
+ legacyId
+ createdAt
+ status
+ amount { value currencyCode }
+ refundedTransaction { id }
+ orderId
+"""
+
+_DISPUTE_FIELDS = """
+ id
+ legacyId
+ createdAt
+ receivedDate
+ status
+ type
+ caseNumber
+ amountDisputed { value currencyCode }
+"""
+
+
+@dataclass
+class BraintreeEndpointConfig:
+ # Field on the GraphQL `search` root.
+ search_field: str
+ # GraphQL input type name for the `search` field (e.g. TransactionSearchInput).
+ input_type: str
+ node_fields: str
+ primary_key: str = "id"
+ incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(_CREATED_AT_INCREMENTAL_FIELDS))
+ partition_key: str = "createdAt"
+
+
+# Braintree's GraphQL search supports createdAt range filters on these
+# streams, giving genuine server-side incremental. Result ordering is not
+# documented, so incremental streams declare sort_mode="desc" — the pipeline
+# then commits the watermark only when a run completes.
+BRAINTREE_ENDPOINTS: dict[str, BraintreeEndpointConfig] = {
+ "transactions": BraintreeEndpointConfig(
+ search_field="transactions",
+ input_type="TransactionSearchInput",
+ node_fields=_TRANSACTION_FIELDS,
+ ),
+ "refunds": BraintreeEndpointConfig(
+ search_field="refunds",
+ input_type="RefundSearchInput",
+ node_fields=_REFUND_FIELDS,
+ ),
+ "disputes": BraintreeEndpointConfig(
+ search_field="disputes",
+ input_type="DisputeSearchInput",
+ node_fields=_DISPUTE_FIELDS,
+ ),
+}
+
+ENDPOINTS = tuple(BRAINTREE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in BRAINTREE_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/posthog/temporal/data_imports/sources/braintree/source.py b/posthog/temporal/data_imports/sources/braintree/source.py
index 2d7c7052879f..7f7c641e0410 100644
--- a/posthog/temporal/data_imports/sources/braintree/source.py
+++ b/posthog/temporal/data_imports/sources/braintree/source.py
@@ -1,29 +1,138 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-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.braintree.braintree import (
+ BraintreeResumeConfig,
+ braintree_source,
+ validate_credentials as validate_braintree_credentials,
+)
+from posthog.temporal.data_imports.sources.braintree.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from 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 SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import BraintreeSourceConfig
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class BraintreeSource(SimpleSource[BraintreeSourceConfig]):
+class BraintreeSource(ResumableSource[BraintreeSourceConfig, BraintreeResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BRAINTREE
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://payments.braintree-api.com": "Braintree authentication failed. Please check your public and private keys.",
+ "401 Client Error: Unauthorized for url: https://payments.sandbox.braintree-api.com": "Braintree authentication failed. Please check your public and private keys (and that they match the selected environment).",
+ "Braintree GraphQL error": "Braintree rejected the request. Please check that your API keys have access to the requested data.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.BRAINTREE,
label="Braintree",
+ caption="""Enter your Braintree API keys to pull your payments data into the PostHog Data warehouse.
+
+You can find your public and private keys in the [Braintree control panel](https://www.braintreegateway.com/) under Settings > API Keys. Sandbox and production use separate keys — make sure the environment matches.""",
iconPath="/static/services/braintree.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/braintree",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="environment",
+ label="Environment",
+ required=True,
+ defaultValue="production",
+ options=[
+ SourceFieldSelectConfigOption(label="Production", value="production"),
+ SourceFieldSelectConfigOption(label="Sandbox", value="sandbox"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="public_key",
+ label="Public key",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="private_key",
+ label="Private key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: BraintreeSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ 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: BraintreeSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_braintree_credentials(config.environment, config.public_key, config.private_key):
+ return True, None
+
+ return False, "Invalid Braintree API keys"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BraintreeResumeConfig]:
+ return ResumableSourceManager[BraintreeResumeConfig](inputs, BraintreeResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BraintreeSourceConfig,
+ resumable_source_manager: ResumableSourceManager[BraintreeResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return braintree_source(
+ environment=config.environment,
+ public_key=config.public_key,
+ private_key=config.private_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/braintree/tests/test_braintree.py b/posthog/temporal/data_imports/sources/braintree/tests/test_braintree.py
new file mode 100644
index 000000000000..f6e073fbf07e
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/braintree/tests/test_braintree.py
@@ -0,0 +1,204 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.braintree.braintree import (
+ PAGE_SIZE,
+ BraintreeGraphQLError,
+ BraintreeResumeConfig,
+ _base_url,
+ _build_query,
+ _format_created_at,
+ braintree_source,
+ get_rows,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.braintree.settings import BRAINTREE_ENDPOINTS, ENDPOINTS
+
+_MODULE = "posthog.temporal.data_imports.sources.braintree.braintree"
+
+
+def _make_manager(resume_state: BraintreeResumeConfig | 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 _search_response(search_field: str, edges: list[dict[str, Any]], has_next: bool = False) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = {
+ "data": {"search": {search_field: {"pageInfo": {"hasNextPage": has_next}, "edges": edges}}}
+ }
+ resp.status_code = 200
+ resp.ok = True
+ return resp
+
+
+def _edge(node_id: str) -> dict[str, Any]:
+ return {"cursor": f"cur-{node_id}", "node": {"id": node_id, "createdAt": "2024-01-01T00:00:00Z"}}
+
+
+class TestBaseUrl:
+ def test_production_and_sandbox_hosts(self):
+ assert _base_url("production") == "https://payments.braintree-api.com/graphql"
+ assert _base_url("sandbox") == "https://payments.sandbox.braintree-api.com/graphql"
+
+ def test_invalid_environment_raises(self):
+ with pytest.raises(ValueError):
+ _base_url("evil")
+
+
+class TestBuildQuery:
+ @pytest.mark.parametrize(
+ "endpoint, input_type",
+ [
+ ("transactions", "TransactionSearchInput"),
+ ("refunds", "RefundSearchInput"),
+ ("disputes", "DisputeSearchInput"),
+ ],
+ )
+ def test_query_uses_correct_input_type(self, endpoint, input_type):
+ query = _build_query(BRAINTREE_ENDPOINTS[endpoint])
+ assert f"$input: {input_type}" in query
+ assert BRAINTREE_ENDPOINTS[endpoint].search_field in query
+
+
+class TestFormatCreatedAt:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (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-02T03:04:05Z", "2024-01-02T03:04:05Z"),
+ ],
+ )
+ def test_format_values(self, value, expected):
+ assert _format_created_at(value) == expected
+
+
+class TestValidateCredentials:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_valid_on_pong(self, mock_session):
+ resp = mock.MagicMock()
+ resp.json.return_value = {"data": {"ping": "pong"}}
+ resp.status_code = 200
+ resp.ok = True
+ mock_session.return_value.post.return_value = resp
+
+ assert validate_credentials("production", "pub", "priv") is True
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_invalid_on_graphql_error(self, mock_session):
+ resp = mock.MagicMock()
+ resp.json.return_value = {"errors": [{"message": "Invalid API key"}]}
+ resp.status_code = 200
+ resp.ok = True
+ mock_session.return_value.post.return_value = resp
+
+ assert validate_credentials("production", "pub", "priv") is False
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_invalid_on_exception(self, mock_session):
+ mock_session.return_value.post.side_effect = Exception("boom")
+ assert validate_credentials("production", "pub", "priv") is False
+
+
+class TestGetRows:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_paginates_via_relay_cursors(self, mock_session):
+ mock_session.return_value.post.side_effect = [
+ _search_response("transactions", [_edge("t1"), _edge("t2")], has_next=True),
+ _search_response("transactions", [_edge("t3")], has_next=False),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("production", "pub", "priv", "transactions", mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == ["t1", "t2", "t3"]
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0].after == "cur-t2"
+ second_vars = mock_session.return_value.post.call_args_list[1].kwargs["json"]["variables"]
+ assert second_vars["after"] == "cur-t2"
+ assert second_vars["first"] == PAGE_SIZE
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_incremental_search_input_has_gte_filter(self, mock_session):
+ mock_session.return_value.post.return_value = _search_response("transactions", [])
+
+ manager = _make_manager()
+ list(
+ get_rows(
+ "production",
+ "pub",
+ "priv",
+ "transactions",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),
+ )
+ )
+
+ variables = mock_session.return_value.post.call_args.kwargs["json"]["variables"]
+ assert variables["input"] == {"createdAt": {"greaterThanOrEqualTo": "2024-01-02T00:00:00Z"}}
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_full_scan_has_null_input(self, mock_session):
+ mock_session.return_value.post.return_value = _search_response("transactions", [])
+
+ manager = _make_manager()
+ list(get_rows("production", "pub", "priv", "transactions", mock.MagicMock(), manager))
+
+ variables = mock_session.return_value.post.call_args.kwargs["json"]["variables"]
+ assert variables["input"] is None
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_resumes_from_saved_cursor(self, mock_session):
+ mock_session.return_value.post.return_value = _search_response("transactions", [])
+
+ manager = _make_manager(BraintreeResumeConfig(after="cur-resume"))
+ list(get_rows("production", "pub", "priv", "transactions", mock.MagicMock(), manager))
+
+ variables = mock_session.return_value.post.call_args.kwargs["json"]["variables"]
+ assert variables["after"] == "cur-resume"
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_graphql_error_raises(self, mock_session):
+ resp = mock.MagicMock()
+ resp.json.return_value = {"errors": [{"message": "validation error"}]}
+ resp.status_code = 200
+ resp.ok = True
+ mock_session.return_value.post.return_value = resp
+
+ manager = _make_manager()
+ with pytest.raises(BraintreeGraphQLError):
+ list(get_rows("production", "pub", "priv", "transactions", mock.MagicMock(), manager))
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_session_uses_basic_auth_and_version_header(self, mock_session):
+ mock_session.return_value.post.return_value = _search_response("transactions", [])
+
+ manager = _make_manager()
+ list(get_rows("production", "pub", "priv", "transactions", mock.MagicMock(), manager))
+
+ assert mock_session.return_value.auth == ("pub", "priv")
+ headers = mock_session.call_args.kwargs["headers"]
+ assert headers["Braintree-Version"]
+
+
+class TestBraintreeSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = BRAINTREE_ENDPOINTS[endpoint]
+ response = braintree_source("production", "pub", "priv", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == [config.primary_key]
+ # Search ordering is undocumented — watermark commits only at run end.
+ assert response.sort_mode == "desc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["createdAt"]
diff --git a/posthog/temporal/data_imports/sources/braintree/tests/test_braintree_source.py b/posthog/temporal/data_imports/sources/braintree/tests/test_braintree_source.py
new file mode 100644
index 000000000000..45a1c6bab234
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/braintree/tests/test_braintree_source.py
@@ -0,0 +1,148 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from posthog.temporal.data_imports.sources.braintree.braintree import BraintreeResumeConfig
+from posthog.temporal.data_imports.sources.braintree.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.braintree.source import BraintreeSource
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import BraintreeSourceConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestBraintreeSource:
+ def setup_method(self):
+ self.source = BraintreeSource()
+ self.team_id = 123
+ self.config = BraintreeSourceConfig(environment="production", public_key="pub", private_key="priv")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.BRAINTREE
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Braintree"
+ assert config.label == "Braintree"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/braintree.png"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["environment", "public_key", "private_key"]
+
+ def test_environment_field_is_a_select_with_default(self):
+ config = self.source.get_source_config
+ env_field = next(f for f in config.fields if f.name == "environment")
+ assert isinstance(env_field, SourceFieldSelectConfig)
+ assert env_field.defaultValue == "production"
+ assert {option.value for option in env_field.options} == {"production", "sandbox"}
+
+ def test_private_key_field_is_secret_password(self):
+ config = self.source.get_source_config
+ key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "private_key")
+ assert key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert key_field.secret is True
+ assert key_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://payments.braintree-api.com/graphql",
+ "401 Client Error: Unauthorized for url: https://payments.sandbox.braintree-api.com/graphql",
+ "Braintree GraphQL error: User does not have permission",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://payments.braintree-api.com/graphql",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_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)
+ # Every search stream supports the createdAt range filter.
+ assert all(schema.supports_incremental for schema in schemas)
+ assert all(schema.supports_append for schema in schemas)
+
+ def test_schemas_advertise_created_at_cursor(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["transactions"].incremental_fields == INCREMENTAL_FIELDS["transactions"]
+ assert [f["field"] for f in schemas["transactions"].incremental_fields] == ["createdAt"]
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["transactions"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "transactions"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid Braintree API keys"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.braintree.source.validate_braintree_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with("production", "pub", "priv")
+
+ 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 BraintreeResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.braintree.source.braintree_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_bt_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "transactions"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_bt_source.assert_called_once()
+ kwargs = mock_bt_source.call_args.kwargs
+ assert kwargs["environment"] == "production"
+ assert kwargs["public_key"] == "pub"
+ assert kwargs["private_key"] == "priv"
+ assert kwargs["endpoint"] == "transactions"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-01-02T03:04:05Z"
+
+ @mock.patch("posthog.temporal.data_imports.sources.braintree.source.braintree_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_bt_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "transactions"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_bt_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 99ac394d2759..8c1e64b3afb3 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -262,7 +262,9 @@ class BoxSourceConfig(config.Config):
@config.config
class BraintreeSourceConfig(config.Config):
- pass
+ public_key: str
+ private_key: str
+ environment: Literal["production", "sandbox"] = config.value(default="production")
@config.config