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 recurly import source (#61148)

Tom Owers1b4ca8cb1d3b
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index b8990f469dd9..f31fd713f0f6 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -87,6 +87,7 @@ the row lists both.
| plain | HTTP | requests | ✅ |
| polar | HTTP | requests | ✅ |
| postgres | DB protocol | psycopg | ➖ |
+| recurly | HTTP | requests + `rest_source.RESTClient` | ✅ |
| recharge | HTTP | requests | ✅ |
| reddit_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
| redshift | DB protocol | psycopg (Postgres-compatible) | ➖ |
@@ -205,7 +206,6 @@ doesn't conflict with concurrent PRs.
- postmark
- productboard
- quickbooks
-- recurly
- ringcentral
- salesloft
- sendgrid
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 096f959c7fdc..e6ca899a043d 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -684,7 +684,8 @@ class RechargeSourceConfig(config.Config):
@config.config
class RecurlySourceConfig(config.Config):
- pass
+ api_key: str
+ region: Literal["us", "eu"] = config.value(default="us")
@config.config
diff --git a/posthog/temporal/data_imports/sources/recurly/recurly.py b/posthog/temporal/data_imports/sources/recurly/recurly.py
new file mode 100644
index 000000000000..aa938e34ceab
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/recurly/recurly.py
@@ -0,0 +1,239 @@
+import dataclasses
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import parse_qs, urlparse
+
+from requests import Request, Response
+
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.rest_source import RESTAPIConfig, rest_api_resource
+from posthog.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator
+from posthog.temporal.data_imports.sources.common.rest_source.resource import Resource
+from posthog.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.recurly.settings import RECURLY_BASE_URLS, RECURLY_ENDPOINTS
+
+# Pinning the API version is required — Recurly rejects requests without it.
+RECURLY_API_VERSION = "v2021-02-25"
+# Recurly caps list endpoints at 200 records per page.
+PAGE_LIMIT = 200
+DEFAULT_SORT_FIELD = "updated_at"
+# `sort` and `begin_time` only accept these timestamp columns.
+VALID_SORT_FIELDS = ("created_at", "updated_at")
+
+
+class RecurlyResumeConfig:
+ next_cursor: str
+
+
+def _headers() -> dict[str, str]:
+ return {"Accept": f"application/vnd.recurly.{RECURLY_API_VERSION}"}
+
+
+def _base_url(region: str) -> str:
+ return RECURLY_BASE_URLS.get(region, RECURLY_BASE_URLS["us"])
+
+
+def _format_datetime(value: Any) -> Optional[str]:
+ """Format an incremental cursor value as an ISO8601 timestamp for `begin_time`.
+
+ Recurly treats a partial timestamp without a timezone as UTC, so we always
+ emit an explicit UTC value.
+ """
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ utc_value = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return utc_value.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ if isinstance(value, date):
+ # Promote a bare date to midnight UTC so begin_time is always a full datetime.
+ return datetime(value.year, value.month, value.day, tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ return str(value)
+
+
+def _extract_cursor(next_path: Optional[str]) -> Optional[str]:
+ """Pull the `cursor` query param out of the `next` path Recurly returns."""
+ if not next_path:
+ return None
+ cursors = parse_qs(urlparse(next_path).query).get("cursor")
+ return cursors[0] if cursors else None
+
+
+class RecurlyPaginator(BasePaginator):
+ """Cursor pagination for Recurly's list endpoints.
+
+ Recurly returns ``{"has_more": bool, "next": "<path>?cursor=...", "data": [...]}``.
+ The ``next`` value is a relative path, so rather than chasing the URL we extract
+ its ``cursor`` and re-apply it as a query param on the same request — this keeps
+ the original ``sort``/``order``/``begin_time`` params intact and makes the cursor
+ trivially resumable.
+ """
+
+ def __init__(self) -> None:
+ super().__init__()
+ self._next_cursor: Optional[str] = None
+
+ def init_request(self, request: Request) -> None:
+ # Honour a seeded resume cursor on the first request.
+ if self._next_cursor is not None:
+ if request.params is None:
+ request.params = {}
+ request.params["cursor"] = self._next_cursor
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ self._next_cursor = None
+ try:
+ body = response.json()
+ except ValueError:
+ body = None
+
+ if not isinstance(body, dict) or not body.get("has_more"):
+ self._has_next_page = False
+ return
+
+ cursor = _extract_cursor(body.get("next"))
+ if cursor:
+ self._next_cursor = cursor
+ self._has_next_page = True
+ else:
+ self._has_next_page = False
+
+ def update_request(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ if self._next_cursor is not None:
+ request.params["cursor"] = self._next_cursor
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ if self._next_cursor is not None and self._has_next_page:
+ return {"next_cursor": self._next_cursor}
+ return None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ next_cursor = state.get("next_cursor")
+ if next_cursor is not None:
+ self._next_cursor = str(next_cursor)
+ self._has_next_page = True
+
+
+def get_resource(
+ endpoint: str,
+ should_use_incremental_field: bool,
+ incremental_field: Optional[str],
+ db_incremental_field_last_value: Optional[Any],
+) -> EndpointResource:
+ config = RECURLY_ENDPOINTS[endpoint]
+ incremental = should_use_incremental_field and config.supports_incremental
+
+ if incremental:
+ # Sort by the cursor the user chose so `begin_time` and the watermark agree.
+ # Ascending order is mandatory: Recurly warns that descending `updated_at`
+ # lets concurrently-updated rows slip behind the cursor and never return.
+ sort_field = incremental_field if incremental_field in VALID_SORT_FIELDS else DEFAULT_SORT_FIELD
+ else:
+ # Full refresh: a stable ascending `created_at` sort avoids page-boundary
+ # skips/duplicates if rows are inserted mid-sync.
+ sort_field = "created_at"
+
+ params: dict[str, Any] = {
+ "limit": PAGE_LIMIT,
+ "sort": sort_field,
+ "order": "asc",
+ }
+ if incremental and db_incremental_field_last_value is not None:
+ params["begin_time"] = _format_datetime(db_incremental_field_last_value)
+
+ return {
+ "name": endpoint,
+ "table_name": endpoint,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if incremental else "replace",
+ "endpoint": {
+ "data_selector": "data",
+ "path": config.path,
+ "params": params,
+ },
+ "table_format": "delta",
+ }
+
+
+def recurly_source(
+ api_key: str,
+ region: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[RecurlyResumeConfig],
+ db_incremental_field_last_value: Optional[Any],
+ should_use_incremental_field: bool = False,
+ incremental_field: Optional[str] = None,
+) -> Resource:
+ incremental = should_use_incremental_field and RECURLY_ENDPOINTS[endpoint].supports_incremental
+
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": _base_url(region),
+ "headers": _headers(),
+ "auth": {
+ "type": "http_basic",
+ "username": api_key,
+ "password": "",
+ },
+ "paginator": RecurlyPaginator(),
+ },
+ "resource_defaults": {
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if incremental else "replace",
+ },
+ "resources": [
+ get_resource(endpoint, should_use_incremental_field, incremental_field, db_incremental_field_last_value)
+ ],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"next_cursor": resume_config.next_cursor}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Persist only when there's a next page; the Redis TTL handles cleanup on completion.
+ if state and state.get("next_cursor"):
+ resumable_source_manager.save_state(RecurlyResumeConfig(next_cursor=str(state["next_cursor"])))
+
+ return rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+
+def validate_credentials(api_key: str, region: str) -> tuple[bool, Optional[str]]:
+ try:
+ res = make_tracked_session().get(
+ f"{_base_url(region)}/accounts",
+ params={"limit": 1},
+ headers=_headers(),
+ auth=(api_key, ""),
+ timeout=30,
+ )
+ except Exception as e:
+ return False, f"Could not reach Recurly ({e}). Please check your network and region, then try again."
+
+ if res.status_code == 200:
+ return True, None
+ if res.status_code == 401:
+ return (
+ False,
+ "Recurly rejected the API key (401 Unauthorized). Create a private API key under "
+ "Integrations > API Credentials in Recurly and confirm the selected region matches your site.",
+ )
+ if res.status_code == 403:
+ return (
+ False,
+ "The Recurly API key is valid but lacks permission to read this site (403 Forbidden). "
+ "Check the key's permissions and try again.",
+ )
+ return False, f"Recurly returned an unexpected status ({res.status_code}) while validating credentials."
diff --git a/posthog/temporal/data_imports/sources/recurly/settings.py b/posthog/temporal/data_imports/sources/recurly/settings.py
new file mode 100644
index 000000000000..d10167e96155
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/recurly/settings.py
@@ -0,0 +1,68 @@
+from dataclasses import dataclass
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+# Recurly's API key authenticates to a single site; the host selects the data residency region.
+RECURLY_BASE_URLS: dict[str, str] = {
+ "us": "https://v3.recurly.com",
+ "eu": "https://v3.eu.recurly.com",
+}
+
+# Every Recurly resource we sync carries a stable `created_at` we can partition on.
+RECURLY_PARTITION_KEY = "created_at"
+
+
+@dataclass
+class RecurlyEndpoint:
+ name: str
+ path: str
+ # `supports_incremental` is only `True` where the list endpoint exposes the
+ # server-side `begin_time` filter (confirmed against the v2021-02-25 OpenAPI spec).
+ # Endpoints that only accept `sort` (no time filter) stay full-refresh, since an
+ # "incremental" sync would still read every page.
+ supports_incremental: bool
+
+
+RECURLY_ENDPOINTS: dict[str, RecurlyEndpoint] = {
+ "accounts": RecurlyEndpoint("accounts", "/accounts", True),
+ "acquisitions": RecurlyEndpoint("acquisitions", "/acquisitions", True),
+ "add_ons": RecurlyEndpoint("add_ons", "/add_ons", True),
+ "coupons": RecurlyEndpoint("coupons", "/coupons", True),
+ "credit_payments": RecurlyEndpoint("credit_payments", "/credit_payments", True),
+ "dunning_campaigns": RecurlyEndpoint("dunning_campaigns", "/dunning_campaigns", False),
+ "external_subscriptions": RecurlyEndpoint("external_subscriptions", "/external_subscriptions", False),
+ "gift_cards": RecurlyEndpoint("gift_cards", "/gift_cards", True),
+ "invoices": RecurlyEndpoint("invoices", "/invoices", True),
+ "items": RecurlyEndpoint("items", "/items", True),
+ "line_items": RecurlyEndpoint("line_items", "/line_items", True),
+ "measured_units": RecurlyEndpoint("measured_units", "/measured_units", True),
+ "plans": RecurlyEndpoint("plans", "/plans", True),
+ "shipping_methods": RecurlyEndpoint("shipping_methods", "/shipping_methods", True),
+ "subscriptions": RecurlyEndpoint("subscriptions", "/subscriptions", True),
+ "transactions": RecurlyEndpoint("transactions", "/transactions", True),
+}
+
+ENDPOINTS = tuple(RECURLY_ENDPOINTS.keys())
+
+
+def _incremental_fields() -> list[IncrementalField]:
+ return [
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ]
+
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: (_incremental_fields() if endpoint.supports_incremental else [])
+ for name, endpoint in RECURLY_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/recurly/source.py b/posthog/temporal/data_imports/sources/recurly/source.py
index acd17532af16..0f0474a9e156 100644
--- a/posthog/temporal/data_imports/sources/recurly/source.py
+++ b/posthog/temporal/data_imports/sources/recurly/source.py
@@ -1,29 +1,145 @@
-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 RecurlySourceConfig
+from posthog.temporal.data_imports.sources.recurly.recurly import (
+ RecurlyResumeConfig,
+ recurly_source,
+ validate_credentials as validate_recurly_credentials,
+)
+from posthog.temporal.data_imports.sources.recurly.settings import (
+ INCREMENTAL_FIELDS,
+ RECURLY_ENDPOINTS,
+ RECURLY_PARTITION_KEY,
+)
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class RecurlySource(SimpleSource[RecurlySourceConfig]):
+class RecurlySource(ResumableSource[RecurlySourceConfig, RecurlyResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.RECURLY
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized": "Recurly rejected the API key. Generate a new private API key in Recurly and reconnect.",
+ "403 Client Error: Forbidden": "The Recurly API key does not have access to this resource. Check the key's permissions and reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: RecurlySourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=name,
+ supports_incremental=endpoint.supports_incremental,
+ supports_append=endpoint.supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(name, []),
+ )
+ for name, endpoint in RECURLY_ENDPOINTS.items()
+ ]
+
+ 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: RecurlySourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_recurly_credentials(config.api_key, config.region)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RecurlyResumeConfig]:
+ return ResumableSourceManager[RecurlyResumeConfig](inputs, RecurlyResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: RecurlySourceConfig,
+ resumable_source_manager: ResumableSourceManager[RecurlyResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ resource = recurly_source(
+ api_key=config.api_key,
+ region=config.region,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ incremental_field=inputs.incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ )
+ return SourceResponse(
+ name=resource.name,
+ items=lambda: resource,
+ primary_keys=["id"],
+ column_hints=resource.column_hints,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="week",
+ partition_keys=[RECURLY_PARTITION_KEY],
+ sort_mode="asc",
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.RECURLY,
label="Recurly",
+ caption=(
+ "Connect your Recurly site using a **private API key**. Create one in Recurly under "
+ "**Integrations > API Credentials**. The key authenticates to a single Recurly site, so "
+ "pick the region that matches it."
+ ),
+ docsUrl="https://posthog.com/docs/cdp/sources/recurly",
iconPath="/static/services/recurly.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldSelectConfig(
+ name="region",
+ label="Region",
+ required=True,
+ defaultValue="us",
+ options=[
+ SourceFieldSelectConfigOption(label="US (v3.recurly.com)", value="us"),
+ SourceFieldSelectConfigOption(label="EU (v3.eu.recurly.com)", value="eu"),
+ ],
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
)
diff --git a/posthog/temporal/data_imports/sources/recurly/tests/test_recurly.py b/posthog/temporal/data_imports/sources/recurly/tests/test_recurly.py
new file mode 100644
index 000000000000..eb4f38d55d23
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/recurly/tests/test_recurly.py
@@ -0,0 +1,342 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, date, datetime
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Request, Response
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.recurly.recurly import (
+ RecurlyPaginator,
+ RecurlyResumeConfig,
+ _extract_cursor,
+ _format_datetime,
+ get_resource,
+ recurly_source,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.recurly.settings import RECURLY_ENDPOINTS
+
+INCREMENTAL_ENDPOINTS = [name for name, e in RECURLY_ENDPOINTS.items() if e.supports_incremental]
+FULL_REFRESH_ENDPOINTS = [name for name, e in RECURLY_ENDPOINTS.items() if not e.supports_incremental]
+
+
+def _list_body(data: list[dict[str, Any]], has_more: bool = False, next_path: str | None = None) -> dict[str, Any]:
+ return {"object": "list", "has_more": has_more, "next": next_path, "data": data}
+
+
+def _resource(endpoint: str, **kwargs: Any) -> dict[str, Any]:
+ # get_resource returns an EndpointResource TypedDict whose nested values are unions;
+ # cast to a plain dict so the structural assertions below stay readable.
+ return cast(dict[str, Any], get_resource(endpoint, **kwargs))
+
+
+class TestRecurlyHelpers:
+ @pytest.mark.parametrize(
+ "next_path, expected",
+ [
+ ("/accounts?cursor=abc123&limit=200", "abc123"),
+ ("/sites/subdomain-foo/accounts?sort=updated_at&cursor=zzz", "zzz"),
+ ("/accounts?limit=200", None),
+ ("", None),
+ (None, None),
+ ],
+ )
+ def test_extract_cursor(self, next_path, expected):
+ assert _extract_cursor(next_path) == expected
+
+ def test_format_datetime_naive_datetime_gets_utc_z_suffix(self):
+ assert _format_datetime(datetime(2024, 1, 2, 3, 4, 5, 678000)) == "2024-01-02T03:04:05.678Z"
+
+ def test_format_datetime_aware_datetime_converted_to_utc(self):
+ from datetime import timedelta, timezone
+
+ value = datetime(2024, 1, 2, 5, 0, 0, tzinfo=timezone(timedelta(hours=2)))
+ assert _format_datetime(value) == "2024-01-02T03:00:00.000Z"
+
+ def test_format_datetime_date(self):
+ assert _format_datetime(date(2024, 1, 2)) == "2024-01-02T00:00:00.000Z"
+
+ def test_format_datetime_none(self):
+ assert _format_datetime(None) is None
+
+ def test_format_datetime_string_passthrough(self):
+ assert _format_datetime("2024-01-02T00:00:00Z") == "2024-01-02T00:00:00Z"
+
+
+class TestRecurlyPaginator:
+ def test_initial_state(self):
+ paginator = RecurlyPaginator()
+ assert paginator._next_cursor is None
+ # BasePaginator starts True so the first request fires; update_state flips it.
+ assert paginator.has_next_page is True
+
+ def test_update_state_has_more_extracts_cursor(self):
+ paginator = RecurlyPaginator()
+ response = MagicMock()
+ response.json.return_value = _list_body([{"id": "a1"}], has_more=True, next_path="/accounts?cursor=next-1")
+ paginator.update_state(response)
+ assert paginator._next_cursor == "next-1"
+ assert paginator.has_next_page is True
+
+ def test_update_state_no_more_when_has_more_false(self):
+ paginator = RecurlyPaginator()
+ response = MagicMock()
+ response.json.return_value = _list_body([{"id": "a1"}], has_more=False, next_path="/accounts?cursor=ignored")
+ paginator.update_state(response)
+ assert paginator._next_cursor is None
+ assert paginator.has_next_page is False
+
+ def test_update_state_has_more_but_missing_cursor_terminates(self):
+ paginator = RecurlyPaginator()
+ response = MagicMock()
+ response.json.return_value = _list_body([{"id": "a1"}], has_more=True, next_path="/accounts?limit=200")
+ paginator.update_state(response)
+ assert paginator._next_cursor is None
+ assert paginator.has_next_page is False
+
+ def test_update_state_invalid_json_terminates(self):
+ paginator = RecurlyPaginator()
+ response = MagicMock()
+ response.json.side_effect = ValueError("no json")
+ paginator.update_state(response)
+ assert paginator.has_next_page is False
+
+ @pytest.mark.parametrize("seeded_cursor", [None, "cursor-2000"])
+ def test_init_request_honours_seeded_cursor(self, seeded_cursor):
+ paginator = RecurlyPaginator()
+ if seeded_cursor is not None:
+ paginator.set_resume_state({"next_cursor": seeded_cursor})
+
+ request = Request(method="GET", url="https://v3.recurly.com/accounts")
+ paginator.init_request(request)
+
+ if seeded_cursor is None:
+ assert request.params is None or "cursor" not in request.params
+ else:
+ assert request.params["cursor"] == seeded_cursor
+
+ def test_get_resume_state_returns_state_when_next_page(self):
+ paginator = RecurlyPaginator()
+ response = MagicMock()
+ response.json.return_value = _list_body([], has_more=True, next_path="/accounts?cursor=c-42")
+ paginator.update_state(response)
+ assert paginator.get_resume_state() == {"next_cursor": "c-42"}
+
+ def test_get_resume_state_returns_none_on_terminal_page(self):
+ paginator = RecurlyPaginator()
+ response = MagicMock()
+ response.json.return_value = _list_body([], has_more=False)
+ paginator.update_state(response)
+ assert paginator.get_resume_state() is None
+
+ def test_set_resume_state_round_trip(self):
+ paginator = RecurlyPaginator()
+ paginator.set_resume_state({"next_cursor": "c-99"})
+ assert paginator._next_cursor == "c-99"
+ assert paginator.has_next_page is True
+ assert paginator.get_resume_state() == {"next_cursor": "c-99"}
+
+ def test_set_resume_state_coerces_to_string(self):
+ paginator = RecurlyPaginator()
+ paginator.set_resume_state({"next_cursor": 12345})
+ assert paginator._next_cursor == "12345"
+
+ def test_set_resume_state_ignores_missing_cursor(self):
+ paginator = RecurlyPaginator()
+ paginator.set_resume_state({})
+ assert paginator._next_cursor is None
+
+
+class TestGetResource:
+ @pytest.mark.parametrize("endpoint", INCREMENTAL_ENDPOINTS)
+ def test_full_refresh_resource_uses_replace_and_stable_sort(self, endpoint):
+ resource = _resource(
+ endpoint, should_use_incremental_field=False, incremental_field=None, db_incremental_field_last_value=None
+ )
+ assert resource["name"] == endpoint
+ assert resource["table_name"] == endpoint
+ assert resource["write_disposition"] == "replace"
+ assert resource["endpoint"]["path"] == RECURLY_ENDPOINTS[endpoint].path
+ assert resource["endpoint"]["data_selector"] == "data"
+ params = resource["endpoint"]["params"]
+ assert params["sort"] == "created_at"
+ assert params["order"] == "asc"
+ assert params["limit"] == 200
+ assert "begin_time" not in params
+
+ @pytest.mark.parametrize("endpoint", INCREMENTAL_ENDPOINTS)
+ def test_incremental_resource_uses_merge_and_begin_time(self, endpoint):
+ resource = _resource(
+ endpoint,
+ should_use_incremental_field=True,
+ incremental_field="updated_at",
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ )
+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
+ params = resource["endpoint"]["params"]
+ assert params["sort"] == "updated_at"
+ assert params["order"] == "asc"
+ assert params["begin_time"] == "2024-01-01T00:00:00.000Z"
+
+ def test_incremental_honours_chosen_field(self):
+ resource = _resource(
+ "accounts",
+ should_use_incremental_field=True,
+ incremental_field="created_at",
+ db_incremental_field_last_value=None,
+ )
+ assert resource["endpoint"]["params"]["sort"] == "created_at"
+
+ def test_incremental_falls_back_to_updated_at_for_unknown_field(self):
+ resource = _resource(
+ "accounts",
+ should_use_incremental_field=True,
+ incremental_field="not_a_field",
+ db_incremental_field_last_value=None,
+ )
+ assert resource["endpoint"]["params"]["sort"] == "updated_at"
+
+ def test_no_begin_time_without_last_value(self):
+ resource = _resource(
+ "accounts",
+ should_use_incremental_field=True,
+ incremental_field="updated_at",
+ db_incremental_field_last_value=None,
+ )
+ assert "begin_time" not in resource["endpoint"]["params"]
+
+ @pytest.mark.parametrize("endpoint", FULL_REFRESH_ENDPOINTS)
+ def test_full_refresh_endpoint_ignores_incremental_request(self, endpoint):
+ # Even if the pipeline asks for incremental, an endpoint without a server-side
+ # time filter must stay full-refresh.
+ resource = _resource(
+ endpoint,
+ should_use_incremental_field=True,
+ incremental_field="updated_at",
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ )
+ assert resource["write_disposition"] == "replace"
+ assert resource["endpoint"]["params"]["sort"] == "created_at"
+ assert "begin_time" not in resource["endpoint"]["params"]
+
+
+def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected_valid",
+ [(200, True), (401, False), (403, False), (500, False)],
+ )
+ def test_status_code_mapping(self, status_code, expected_valid):
+ with patch("posthog.temporal.data_imports.sources.recurly.recurly.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _make_http_response({}, status_code=status_code)
+ is_valid, message = validate_credentials("key", "us")
+
+ assert is_valid is expected_valid
+ if not expected_valid:
+ assert message
+
+ def test_connection_error_is_invalid(self):
+ with patch("posthog.temporal.data_imports.sources.recurly.recurly.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ is_valid, message = validate_credentials("key", "us")
+
+ assert is_valid is False
+ assert message
+
+ @pytest.mark.parametrize("region, expected_host", [("us", "v3.recurly.com"), ("eu", "v3.eu.recurly.com")])
+ def test_region_selects_host(self, region, expected_host):
+ with patch("posthog.temporal.data_imports.sources.recurly.recurly.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _make_http_response({}, status_code=200)
+ validate_credentials("key", region)
+
+ called_url = mock_session.return_value.get.call_args.args[0]
+ assert expected_host in called_url
+
+
+class TestRecurlySourceResumeBehavior:
+ def _drive(self, endpoint: str, manager: MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ return next(response_iter)
+
+ with patch(
+ "posthog.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ resource = recurly_source(
+ api_key="test-key",
+ region="us",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=None,
+ should_use_incremental_field=False,
+ )
+ list(cast(Iterable[Any], resource))
+ return sent_params
+
+ def test_fresh_run_saves_cursor_after_each_non_terminal_page(self):
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response(_list_body([{"id": "a1"}], has_more=True, next_path="/accounts?cursor=cur-1")),
+ _make_http_response(_list_body([{"id": "a2"}], has_more=True, next_path="/accounts?cursor=cur-2")),
+ _make_http_response(_list_body([{"id": "a3"}], has_more=False)),
+ ]
+ sent_params = self._drive("accounts", manager, responses)
+
+ assert [p.get("cursor") for p in sent_params] == [None, "cur-1", "cur-2"]
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [
+ RecurlyResumeConfig(next_cursor="cur-1"),
+ RecurlyResumeConfig(next_cursor="cur-2"),
+ ]
+
+ def test_resume_seeds_paginator_with_saved_cursor(self):
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = RecurlyResumeConfig(next_cursor="cur-resumed")
+
+ responses = [_make_http_response(_list_body([{"id": "a4"}], has_more=False))]
+ sent_params = self._drive("accounts", manager, responses)
+
+ assert [p.get("cursor") for p in sent_params] == ["cur-resumed"]
+ manager.load_state.assert_called_once()
+
+ def test_terminal_single_page_does_not_save_state(self):
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response(_list_body([{"id": "only"}], has_more=False))]
+ self._drive("accounts", manager, responses)
+
+ manager.save_state.assert_not_called()
+
+ def test_does_not_load_state_when_cannot_resume(self):
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response(_list_body([{"id": "a"}], has_more=False))]
+ self._drive("accounts", manager, responses)
+
+ manager.load_state.assert_not_called()
diff --git a/posthog/temporal/data_imports/sources/recurly/tests/test_recurly_source.py b/posthog/temporal/data_imports/sources/recurly/tests/test_recurly_source.py
new file mode 100644
index 000000000000..d9aa2e170fbd
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/recurly/tests/test_recurly_source.py
@@ -0,0 +1,159 @@
+from types import SimpleNamespace
+from typing import cast
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import RecurlySourceConfig
+from posthog.temporal.data_imports.sources.recurly.recurly import RecurlyResumeConfig
+from posthog.temporal.data_imports.sources.recurly.settings import ENDPOINTS, RECURLY_ENDPOINTS
+from posthog.temporal.data_imports.sources.recurly.source import RecurlySource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+INCREMENTAL_ENDPOINTS = [name for name, e in RECURLY_ENDPOINTS.items() if e.supports_incremental]
+FULL_REFRESH_ENDPOINTS = [name for name, e in RECURLY_ENDPOINTS.items() if not e.supports_incremental]
+
+
+class TestRecurlySource:
+ def setup_method(self):
+ self.source = RecurlySource()
+ self.team_id = 123
+ self.config = RecurlySourceConfig(api_key="test-key", region="us")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.RECURLY
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Recurly"
+ assert config.label == "Recurly"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/recurly.png"
+ assert len(config.fields) == 2
+
+ api_key_field = config.fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+ region_field = config.fields[1]
+ assert isinstance(region_field, SourceFieldSelectConfig)
+ assert region_field.name == "region"
+ assert region_field.defaultValue == "us"
+ assert {option.value for option in region_field.options} == {"us", "eu"}
+
+ @pytest.mark.parametrize(
+ "expected_key",
+ ["401 Client Error: Unauthorized", "403 Client Error: Forbidden"],
+ )
+ def test_non_retryable_errors_includes_auth_keys(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_returns_every_endpoint(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize("endpoint", INCREMENTAL_ENDPOINTS)
+ def test_incremental_endpoints_advertise_incremental(self, endpoint):
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
+ assert schema.supports_incremental is True
+ assert schema.supports_append is True
+ assert {field["field"] for field in schema.incremental_fields} == {"created_at", "updated_at"}
+
+ @pytest.mark.parametrize("endpoint", FULL_REFRESH_ENDPOINTS)
+ def test_full_refresh_endpoints_do_not_advertise_incremental(self, endpoint):
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
+ assert schema.supports_incremental is False
+ assert schema.supports_append is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["accounts"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "accounts"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ ((True, None), True, None),
+ ((False, "Recurly rejected the API key."), False, "Recurly rejected the API key."),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.recurly.source.validate_recurly_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(self.config.api_key, self.config.region)
+
+ def test_get_resumable_source_manager_is_bound_to_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is RecurlyResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.recurly.source.recurly_source")
+ def test_source_for_pipeline_plumbs_inputs(self, mock_recurly_source):
+ mock_recurly_source.return_value = SimpleNamespace(name="accounts", column_hints=None)
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+ inputs = SimpleNamespace(
+ schema_name="accounts",
+ team_id=self.team_id,
+ job_id="job-1",
+ should_use_incremental_field=True,
+ incremental_field="updated_at",
+ db_incremental_field_last_value="2024-01-01T00:00:00Z",
+ )
+
+ response = self.source.source_for_pipeline(self.config, manager, cast(SourceInputs, inputs))
+
+ mock_recurly_source.assert_called_once_with(
+ api_key="test-key",
+ region="us",
+ endpoint="accounts",
+ team_id=self.team_id,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ incremental_field="updated_at",
+ db_incremental_field_last_value="2024-01-01T00:00:00Z",
+ )
+ assert response.name == "accounts"
+ assert response.primary_keys == ["id"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["created_at"]
+ assert response.sort_mode == "asc"
+
+ @mock.patch("posthog.temporal.data_imports.sources.recurly.source.recurly_source")
+ def test_source_for_pipeline_drops_last_value_on_full_refresh(self, mock_recurly_source):
+ mock_recurly_source.return_value = SimpleNamespace(name="plans", column_hints=None)
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+ inputs = SimpleNamespace(
+ schema_name="plans",
+ team_id=self.team_id,
+ job_id="job-2",
+ should_use_incremental_field=False,
+ incremental_field=None,
+ db_incremental_field_last_value="2024-01-01T00:00:00Z",
+ )
+
+ self.source.source_for_pipeline(self.config, manager, cast(SourceInputs, inputs))
+
+ # When the user isn't running incrementally, no watermark should leak through.
+ assert mock_recurly_source.call_args.kwargs["db_incremental_field_last_value"] is None