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 gocardless import source (#62906)

Tom Owersd91335f42263
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 6efcf8113644..f6b26d793672 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -81,6 +81,7 @@ the row lists both.
| front | HTTP | requests | ✅ |
| github | HTTP | requests | ✅ |
| gitlab | HTTP | requests | ✅ |
+| gocardless | HTTP | requests | ✅ |
| gong | HTTP | requests | ✅ |
| google_ads | gRPC | google-ads (googleads.client) | ✅ |
| google_sheets | HTTP (vendor SDK) | gspread | ✅ |
@@ -246,7 +247,6 @@ doesn't conflict with concurrent PRs.
- freshbooks
- fullstory
- gladly
-- gocardless
- google_ad_manager
- google_analytics
- google_cloud_storage
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 769e4b87afb5..87cac1757563 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -604,7 +604,8 @@ class GladlySourceConfig(config.Config):
@config.config
class GoCardlessSourceConfig(config.Config):
- pass
+ access_token: str
+ environment: Literal["live", "sandbox"] = config.value(default="live")
@config.config
diff --git a/posthog/temporal/data_imports/sources/gocardless/gocardless.py b/posthog/temporal/data_imports/sources/gocardless/gocardless.py
new file mode 100644
index 000000000000..cb7ffd9a8af6
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/gocardless/gocardless.py
@@ -0,0 +1,185 @@
+import dataclasses
+from collections.abc import 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.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.gocardless.settings import GOCARDLESS_ENDPOINTS, GoCardlessEndpointConfig
+
+GOCARDLESS_HOSTS = {
+ "live": "https://api.gocardless.com",
+ "sandbox": "https://api-sandbox.gocardless.com",
+}
+# Every request must pin an API version via this header.
+GOCARDLESS_VERSION = "2015-07-06"
+# GoCardless list pages cap at 500 items.
+PAGE_SIZE = 500
+REQUEST_TIMEOUT_SECONDS = 60
+# 1000 req/min rate limit; 429s carry ratelimit headers but backoff suffices.
+MAX_RETRY_ATTEMPTS = 5
+
+
+class GoCardlessRetryableError(Exception):
+ pass
+
+
+class GoCardlessResumeConfig:
+ # GoCardless cursor pagination: `after=<id>` from meta.cursors.after; the
+ # static params are deterministically rebuilt from job inputs on resume.
+ after: str
+
+
+def _get_session(access_token: str) -> requests.Session:
+ return make_tracked_session(
+ headers={
+ "Authorization": f"Bearer {access_token}",
+ "GoCardless-Version": GOCARDLESS_VERSION,
+ },
+ redact_values=(access_token,),
+ )
+
+
+def _base_url(environment: str) -> str:
+ host = GOCARDLESS_HOSTS.get(environment)
+ if host is None:
+ raise ValueError(f"Invalid GoCardless environment: {environment}")
+ return host
+
+
+def _format_created_at(value: Any) -> str:
+ """Format an incremental cursor for GoCardless's created_at filters (ISO 8601 UTC with ms)."""
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ if isinstance(value, date):
+ return value.strftime("%Y-%m-%dT00:00:00.000Z")
+ return str(value)
+
+
+def _build_params(
+ config: GoCardlessEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ after: Optional[str],
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"limit": PAGE_SIZE}
+
+ if config.incremental_fields and should_use_incremental_field and db_incremental_field_last_value is not None:
+ # `gte` re-fetches the boundary row (merge dedupes on primary key) so
+ # records sharing the watermark timestamp are never skipped.
+ params["created_at[gte]"] = _format_created_at(db_incremental_field_last_value)
+
+ if after is not None:
+ params["after"] = after
+
+ return params
+
+
+def validate_credentials(environment: str, access_token: str) -> bool:
+ """Confirm the access token is valid with a cheap one-customer probe."""
+ try:
+ response = _get_session(access_token).get(
+ f"{_base_url(environment)}/customers?{urlencode({'limit': 1})}",
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def get_rows(
+ environment: str,
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[GoCardlessResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = GOCARDLESS_ENDPOINTS[endpoint]
+ session = _get_session(access_token)
+ base_url = _base_url(environment)
+
+ 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"GoCardless: resuming {endpoint} from cursor {after}")
+
+ @retry(
+ retry=retry_if_exception_type((GoCardlessRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> dict[str, Any]:
+ response = session.get(page_url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise GoCardlessRetryableError(
+ f"GoCardless API error (retryable): status={response.status_code}, url={page_url}"
+ )
+
+ if not response.ok:
+ logger.error(f"GoCardless API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ while True:
+ params = _build_params(config, should_use_incremental_field, db_incremental_field_last_value, after)
+ data = fetch_page(f"{base_url}{config.path}?{urlencode(params)}")
+ items = data.get(config.data_key, []) or []
+
+ if items:
+ yield items
+
+ next_after = ((data.get("meta") or {}).get("cursors") or {}).get("after")
+ if not next_after or not items:
+ break
+
+ after = next_after
+ # 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(GoCardlessResumeConfig(after=after))
+
+
+def gocardless_source(
+ environment: str,
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[GoCardlessResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = GOCARDLESS_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ environment=environment,
+ access_token=access_token,
+ 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],
+ # GoCardless lists are reverse-chronological with no sort param; the
+ # pipeline commits desc-sort watermarks only when a run completes.
+ sort_mode="desc" if config.incremental_fields else "asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/gocardless/settings.py b/posthog/temporal/data_imports/sources/gocardless/settings.py
new file mode 100644
index 000000000000..193e3a8b9351
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/gocardless/settings.py
@@ -0,0 +1,73 @@
+from dataclasses import dataclass, field
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class GoCardlessEndpointConfig:
+ name: str
+ path: str
+ # Key the rows live under in the response body (GoCardless wraps per resource).
+ data_key: str
+ primary_key: str = "id"
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Every GoCardless resource carries an immutable created_at.
+ partition_key: str = "created_at"
+
+
+# GoCardless list endpoints filter only on created_at (no updated_at), and core
+# records (payments, mandates, subscriptions) mutate status over time — so the
+# append-only events stream (GoCardless's change log) is the one honest
+# incremental, and the mutable tables stay full refresh (the pattern Fivetran
+# uses). Lists are reverse-chronological with no sort param.
+GOCARDLESS_ENDPOINTS: dict[str, GoCardlessEndpointConfig] = {
+ "customers": GoCardlessEndpointConfig(
+ name="customers",
+ path="/customers",
+ data_key="customers",
+ ),
+ "mandates": GoCardlessEndpointConfig(
+ name="mandates",
+ path="/mandates",
+ data_key="mandates",
+ ),
+ "payments": GoCardlessEndpointConfig(
+ name="payments",
+ path="/payments",
+ data_key="payments",
+ ),
+ "subscriptions": GoCardlessEndpointConfig(
+ name="subscriptions",
+ path="/subscriptions",
+ data_key="subscriptions",
+ ),
+ "payouts": GoCardlessEndpointConfig(
+ name="payouts",
+ path="/payouts",
+ data_key="payouts",
+ ),
+ "refunds": GoCardlessEndpointConfig(
+ name="refunds",
+ path="/refunds",
+ data_key="refunds",
+ ),
+ "events": GoCardlessEndpointConfig(
+ name="events",
+ path="/events",
+ data_key="events",
+ incremental_fields=[
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+}
+
+ENDPOINTS = tuple(GOCARDLESS_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in GOCARDLESS_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/posthog/temporal/data_imports/sources/gocardless/source.py b/posthog/temporal/data_imports/sources/gocardless/source.py
index e9e95e395af0..079a5a6511d5 100644
--- a/posthog/temporal/data_imports/sources/gocardless/source.py
+++ b/posthog/temporal/data_imports/sources/gocardless/source.py
@@ -1,29 +1,130 @@
-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.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 GoCardlessSourceConfig
+from posthog.temporal.data_imports.sources.gocardless.gocardless import (
+ GoCardlessResumeConfig,
+ gocardless_source,
+ validate_credentials as validate_gocardless_credentials,
+)
+from posthog.temporal.data_imports.sources.gocardless.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class GoCardlessSource(SimpleSource[GoCardlessSourceConfig]):
+class GoCardlessSource(ResumableSource[GoCardlessSourceConfig, GoCardlessResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.GOCARDLESS
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.gocardless.com": "GoCardless authentication failed. Please check your access token.",
+ "401 Client Error: Unauthorized for url: https://api-sandbox.gocardless.com": "GoCardless authentication failed. Please check your access token (and that it matches the selected environment).",
+ "403 Client Error: Forbidden for url: https://api.gocardless.com": "GoCardless denied access. Please check your access token's permissions.",
+ "403 Client Error: Forbidden for url: https://api-sandbox.gocardless.com": "GoCardless denied access. Please check your access token's permissions.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.GO_CARDLESS,
label="GoCardless",
+ caption="""Enter your GoCardless access token to pull your GoCardless payments data into the PostHog Data warehouse.
+
+Create a read-only access token in the [GoCardless dashboard](https://manage.gocardless.com/developers) under Developers > Create > Access token. Sandbox and live environments use separate hosts and tokens — make sure the environment matches your token.""",
iconPath="/static/services/gocardless.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/gocardless",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="environment",
+ label="Environment",
+ required=True,
+ defaultValue="live",
+ options=[
+ SourceFieldSelectConfigOption(label="Live", value="live"),
+ SourceFieldSelectConfigOption(label="Sandbox", value="sandbox"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="access_token",
+ label="Access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: GoCardlessSourceConfig,
+ 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: GoCardlessSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_gocardless_credentials(config.environment, config.access_token):
+ return True, None
+
+ return False, "Invalid GoCardless access token"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GoCardlessResumeConfig]:
+ return ResumableSourceManager[GoCardlessResumeConfig](inputs, GoCardlessResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: GoCardlessSourceConfig,
+ resumable_source_manager: ResumableSourceManager[GoCardlessResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return gocardless_source(
+ environment=config.environment,
+ access_token=config.access_token,
+ 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/gocardless/tests/test_gocardless.py b/posthog/temporal/data_imports/sources/gocardless/tests/test_gocardless.py
new file mode 100644
index 000000000000..26e8a8b582a1
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/gocardless/tests/test_gocardless.py
@@ -0,0 +1,221 @@
+from datetime import UTC, date, datetime
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.gocardless.gocardless import (
+ GoCardlessResumeConfig,
+ _base_url,
+ _build_params,
+ _format_created_at,
+ get_rows,
+ gocardless_source,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.gocardless.settings import ENDPOINTS, GOCARDLESS_ENDPOINTS
+
+
+def _make_manager(resume_state: GoCardlessResumeConfig | 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 _response(data_key: str, items: list[dict[str, Any]], after: str | None = None) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = {data_key: items, "meta": {"cursors": {"before": None, "after": after}, "limit": 500}}
+ resp.status_code = 200
+ resp.ok = True
+ return resp
+
+
+class TestBaseUrl:
+ @pytest.mark.parametrize(
+ "environment, expected",
+ [
+ ("live", "https://api.gocardless.com"),
+ ("sandbox", "https://api-sandbox.gocardless.com"),
+ ],
+ )
+ def test_known_environment_returns_host(self, environment, expected):
+ assert _base_url(environment) == expected
+
+ def test_invalid_environment_raises(self):
+ with pytest.raises(ValueError):
+ _base_url("evil.example.com")
+
+
+class TestFormatCreatedAt:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2024, 1, 2, 3, 4, 5, 123000, tzinfo=UTC), "2024-01-02T03:04:05.123Z"),
+ (datetime(2024, 1, 2, 3, 4, 5), "2024-01-02T03:04:05.000Z"),
+ (date(2024, 1, 2), "2024-01-02T00:00:00.000Z"),
+ ("2024-01-02T03:04:05.000Z", "2024-01-02T03:04:05.000Z"),
+ ],
+ )
+ def test_format_values(self, value, expected):
+ assert _format_created_at(value) == expected
+
+
+class TestBuildParams:
+ def test_incremental_events_filters_on_created_at(self):
+ params = _build_params(
+ GOCARDLESS_ENDPOINTS["events"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),
+ after=None,
+ )
+
+ assert params["created_at[gte]"] == "2024-01-02T00:00:00.000Z"
+ assert params["limit"] == 500
+
+ def test_full_refresh_has_no_filter(self):
+ params = _build_params(
+ GOCARDLESS_ENDPOINTS["payments"],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ after="CU123",
+ )
+
+ assert "created_at[gte]" not in params
+ assert params["after"] == "CU123"
+
+ def test_non_incremental_endpoint_ignores_watermark(self):
+ params = _build_params(
+ GOCARDLESS_ENDPOINTS["payments"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),
+ after=None,
+ )
+
+ assert "created_at[gte]" not in params
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected",
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ (500, False),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.gocardless.gocardless.make_tracked_session")
+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ assert validate_credentials("live", "token") is expected
+
+ @mock.patch("posthog.temporal.data_imports.sources.gocardless.gocardless.make_tracked_session")
+ def test_validate_credentials_rejects_bad_environment_without_request(self, mock_session):
+ assert validate_credentials("evil", "token") is False
+ mock_session.return_value.get.assert_not_called()
+
+
+class TestGetRows:
+ @mock.patch("posthog.temporal.data_imports.sources.gocardless.gocardless.make_tracked_session")
+ def test_paginates_via_meta_cursors(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response("payments", [{"id": "PM1"}], after="PM1"),
+ _response("payments", [{"id": "PM2"}], after=None),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("live", "token", "payments", mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == ["PM1", "PM2"]
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0].after == "PM1"
+ second_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert parse_qs(urlparse(second_url).query)["after"] == ["PM1"]
+
+ @mock.patch("posthog.temporal.data_imports.sources.gocardless.gocardless.make_tracked_session")
+ def test_requests_carry_version_header(self, mock_session):
+ mock_session.return_value.get.return_value = _response("payments", [])
+
+ manager = _make_manager()
+ list(get_rows("live", "token", "payments", mock.MagicMock(), manager))
+
+ headers = mock_session.call_args.kwargs["headers"]
+ assert headers["GoCardless-Version"] == "2015-07-06"
+
+ @mock.patch("posthog.temporal.data_imports.sources.gocardless.gocardless.make_tracked_session")
+ def test_sandbox_uses_sandbox_host(self, mock_session):
+ mock_session.return_value.get.return_value = _response("payments", [])
+
+ manager = _make_manager()
+ list(get_rows("sandbox", "token", "payments", mock.MagicMock(), manager))
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert urlparse(url).netloc == "api-sandbox.gocardless.com"
+
+ @mock.patch("posthog.temporal.data_imports.sources.gocardless.gocardless.make_tracked_session")
+ def test_incremental_request_includes_filter(self, mock_session):
+ mock_session.return_value.get.return_value = _response("events", [])
+
+ manager = _make_manager()
+ list(
+ get_rows(
+ "live",
+ "token",
+ "events",
+ 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 parse_qs(urlparse(url).query)["created_at[gte]"] == ["2024-01-02T00:00:00.000Z"]
+
+ @mock.patch("posthog.temporal.data_imports.sources.gocardless.gocardless.make_tracked_session")
+ def test_resumes_from_saved_cursor(self, mock_session):
+ mock_session.return_value.get.return_value = _response("payments", [])
+
+ manager = _make_manager(GoCardlessResumeConfig(after="PM_RESUME"))
+ list(get_rows("live", "token", "payments", mock.MagicMock(), manager))
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert parse_qs(urlparse(url).query)["after"] == ["PM_RESUME"]
+
+ @mock.patch("posthog.temporal.data_imports.sources.gocardless.gocardless.make_tracked_session")
+ def test_empty_page_with_cursor_stops(self, mock_session):
+ mock_session.return_value.get.return_value = _response("payments", [], after="PM_LOOP")
+
+ manager = _make_manager()
+ batches = list(get_rows("live", "token", "payments", mock.MagicMock(), manager))
+
+ assert batches == []
+ assert mock_session.return_value.get.call_count == 1
+ manager.save_state.assert_not_called()
+
+
+class TestGoCardlessSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = GOCARDLESS_ENDPOINTS[endpoint]
+ response = gocardless_source("live", "token", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == [config.primary_key]
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["created_at"]
+ # Lists are reverse-chronological; only the incremental events stream
+ # declares desc so the pipeline defers its watermark commit.
+ if config.incremental_fields:
+ assert response.sort_mode == "desc"
+ else:
+ assert response.sort_mode == "asc"
+
+ @pytest.mark.parametrize("config", list(GOCARDLESS_ENDPOINTS.values()))
+ def test_partition_keys_are_stable_creation_fields(self, config):
+ assert config.partition_key == "created_at"
diff --git a/posthog/temporal/data_imports/sources/gocardless/tests/test_gocardless_source.py b/posthog/temporal/data_imports/sources/gocardless/tests/test_gocardless_source.py
new file mode 100644
index 000000000000..95bfb8ace0b6
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/gocardless/tests/test_gocardless_source.py
@@ -0,0 +1,151 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import GoCardlessSourceConfig
+from posthog.temporal.data_imports.sources.gocardless.gocardless import GoCardlessResumeConfig
+from posthog.temporal.data_imports.sources.gocardless.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.gocardless.source import GoCardlessSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestGoCardlessSource:
+ def setup_method(self):
+ self.source = GoCardlessSource()
+ self.team_id = 123
+ self.config = GoCardlessSourceConfig(environment="live", access_token="access-token")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.GOCARDLESS
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "GoCardless"
+ assert config.label == "GoCardless"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/gocardless.png"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["environment", "access_token"]
+
+ 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 == "live"
+ assert {option.value for option in env_field.options} == {"live", "sandbox"}
+
+ def test_access_token_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 == "access_token"
+ )
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.secret is True
+ assert token_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.gocardless.com/customers?limit=500",
+ "401 Client Error: Unauthorized for url: https://api-sandbox.gocardless.com/payments",
+ "403 Client Error: Forbidden for url: https://api.gocardless.com/events",
+ ],
+ )
+ 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_vendor_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.gocardless.com/payments",
+ ],
+ )
+ 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 the append-only events change log has an honest incremental;
+ # mutable tables (payments, mandates) change status after creation.
+ assert incremental == {"events"}
+
+ def test_incremental_schemas_advertise_their_fields(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["events"].incremental_fields == INCREMENTAL_FIELDS["events"]
+ assert schemas["payments"].incremental_fields == []
+ assert schemas["payments"].supports_append is False
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["events"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "events"
+
+ 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 GoCardless access token"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.gocardless.source.validate_gocardless_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("live", "access-token")
+
+ 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 GoCardlessResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.gocardless.source.gocardless_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_gc_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "events"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05.000Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_gc_source.assert_called_once()
+ kwargs = mock_gc_source.call_args.kwargs
+ assert kwargs["environment"] == "live"
+ assert kwargs["access_token"] == "access-token"
+ assert kwargs["endpoint"] == "events"
+ 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:05.000Z"
+
+ @mock.patch("posthog.temporal.data_imports.sources.gocardless.source.gocardless_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_gc_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "payments"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05.000Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_gc_source.call_args.kwargs["db_incremental_field_last_value"] is None