:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement pabbly_subscriptions_billing import source (#69385)
Tom Owers0efa055de7e5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 56741d344703..f21fc263d8e5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -340,6 +340,7 @@ the row lists both.| ortto | HTTP | requests | ✅ || oura | HTTP | requests | ✅ || outbrain | HTTP | requests | ✅ |+| pabbly_subscriptions_billing | HTTP | requests | ✅ || packagist | HTTP | requests | ✅ || paddle | HTTP | requests | ✅ || optimizely | HTTP | requests | ✅ |@@ -800,7 +801,6 @@ doesn't conflict with concurrent PRs.- outlook- outreach- oveit-- pabbly_subscriptions_billing- pagerduty- pardot- paylocitydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 2003e65983a8..35a6afb14c7d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -3030,7 +3030,8 @@ class OveitSourceConfig(config.Config):@config.configclass PabblySubscriptionsBillingSourceConfig(config.Config):- pass+ api_key: str+ secret_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/canonical_descriptions.pynew file mode 100644index 000000000000..5d5d613e3f14--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/canonical_descriptions.py@@ -0,0 +1,228 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Pabbly Subscription Billing API docs+# (https://apidocs.pabbly.com/pabbly/subscription-billing).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+PABBLY_DOCS_URL = "https://apidocs.pabbly.com/pabbly/subscription-billing"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "customers": {+ "description": "A customer in your Pabbly Subscription Billing account.",+ "docs_url": PABBLY_DOCS_URL,+ "columns": {+ "id": "The unique ID of the customer.",+ "first_name": "The customer's first name.",+ "last_name": "The customer's last name.",+ "email_id": "The customer's email address.",+ "phone": "The customer's phone number.",+ "company_name": "The customer's company name.",+ "billing_address": "The customer's billing address.",+ "shipping_address": "The customer's shipping address.",+ "tax_id": "The customer's tax ID.",+ "credit": "The credit balance on the customer's account.",+ "portal_status": "Whether the customer has access to the self-service portal.",+ "createdAt": "When the customer was created.",+ "updatedAt": "When the customer was last updated.",+ },+ },+ "subscriptions": {+ "description": "A subscription of a customer to one of your plans.",+ "docs_url": PABBLY_DOCS_URL,+ "columns": {+ "id": "The unique ID of the subscription.",+ "customer_id": "The ID of the customer who owns the subscription.",+ "product_id": "The ID of the product the subscribed plan belongs to.",+ "plan_id": "The ID of the plan the customer is subscribed to.",+ "email_id": "The email address of the subscribed customer.",+ "amount": "The recurring amount charged for the subscription.",+ "currency_code": "The currency of the subscription amount.",+ "quantity": "The billed quantity of the plan.",+ "setup_fee": "The one-time setup fee charged on activation.",+ "status": "The current status of the subscription (e.g. live, trial, cancelled, expired).",+ "trial_days": "The number of trial days granted.",+ "trial_expiry_date": "When the trial period ends.",+ "activation_date": "When the subscription was activated.",+ "last_billing_date": "When the subscription was last billed.",+ "next_billing_date": "When the subscription will next be billed.",+ "expiry_date": "When the subscription expires.",+ "canceled_date": "When the subscription was cancelled, if it was.",+ "gateway_type": "The payment gateway type used to collect payments.",+ "payment_method": "The payment method used for the subscription.",+ "coupon": "The coupon applied to the subscription, if any.",+ "createdAt": "When the subscription was created.",+ "updatedAt": "When the subscription was last updated.",+ },+ },+ "products": {+ "description": "A product you sell; plans, addons, and coupons are grouped under a product.",+ "docs_url": PABBLY_DOCS_URL,+ "columns": {+ "id": "The unique ID of the product.",+ "product_name": "The product's name.",+ "status": "Whether the product is active.",+ "createdAt": "When the product was created.",+ "updatedAt": "When the product was last updated.",+ },+ },+ "invoices": {+ "description": "An invoice issued for a subscription.",+ "docs_url": PABBLY_DOCS_URL,+ "columns": {+ "id": "The unique ID of the invoice.",+ "invoice_id": "The human-readable invoice number.",+ "customer_id": "The ID of the customer the invoice was issued to.",+ "subscription_id": "The ID of the subscription the invoice belongs to.",+ "product_id": "The ID of the product the invoiced plan belongs to.",+ "amount": "The total amount of the invoice.",+ "due_amount": "The amount still due on the invoice.",+ "due_date": "When payment of the invoice is due.",+ "paid_date": "When the invoice was paid.",+ "status": "The current status of the invoice (e.g. paid, unpaid).",+ "currency_code": "The currency of the invoice amount.",+ "invoice_link": "A link to view the invoice.",+ "credit_note": "The credit note attached to the invoice, if any.",+ "createdAt": "When the invoice was created.",+ "updatedAt": "When the invoice was last updated.",+ },+ },+ "transactions": {+ "description": "A payment transaction of a customer.",+ "docs_url": PABBLY_DOCS_URL,+ "columns": {+ "id": "The unique ID of the transaction.",+ "customer_id": "The ID of the customer the transaction belongs to.",+ "subscription_id": "The ID of the subscription the transaction was made for.",+ "invoice_id": "The ID of the invoice the transaction settles.",+ "product_id": "The ID of the product the charged plan belongs to.",+ "plan_id": "The ID of the charged plan.",+ "amount": "The amount of the transaction.",+ "currency_code": "The currency of the transaction amount.",+ "status": "The current status of the transaction (e.g. success, failed).",+ "type": "The type of the transaction.",+ "gateway_type": "The payment gateway the transaction went through.",+ "reference_id": "The gateway's reference for the transaction.",+ "createdAt": "When the transaction was created.",+ "updatedAt": "When the transaction was last updated.",+ },+ },+ "refunds": {+ "description": "A refunded payment transaction of a customer.",+ "docs_url": PABBLY_DOCS_URL,+ "columns": {+ "id": "The unique ID of the refund transaction.",+ "customer_id": "The ID of the customer the refund belongs to.",+ "subscription_id": "The ID of the subscription the refunded payment was made for.",+ "invoice_id": "The ID of the invoice the refunded payment settled.",+ "amount": "The refunded amount.",+ "currency_code": "The currency of the refunded amount.",+ "status": "The current status of the refund.",+ "gateway_type": "The payment gateway the refund went through.",+ "reference_id": "The gateway's reference for the refund.",+ "createdAt": "When the refund was created.",+ "updatedAt": "When the refund was last updated.",+ },+ },+ "addons": {+ "description": "An addon that can be attached to plans of a product.",+ "docs_url": PABBLY_DOCS_URL,+ "columns": {+ "id": "The unique ID of the addon.",+ "product_id": "The ID of the product the addon belongs to.",+ "name": "The addon's name.",+ "code": "The addon's code.",+ "price": "The price of the addon.",+ "billing_cycle": "How often the addon is billed.",+ "billing_period": "The billing period unit of the addon.",+ "associate_plans": "The plans the addon is associated with.",+ "status": "Whether the addon is active.",+ "createdAt": "When the addon was created.",+ "updatedAt": "When the addon was last updated.",+ },+ },+ "addon_list_category": {+ "description": "An addon category of a product, used to group its addons.",+ "docs_url": PABBLY_DOCS_URL,+ "columns": {+ "id": "The unique ID of the addon category.",+ "product_id": "The ID of the product the addon category belongs to.",+ "category_name": "The addon category's name.",+ },+ },+ "coupons": {+ "description": "A discount coupon that can be applied to plans of a product.",+ "docs_url": PABBLY_DOCS_URL,+ "columns": {+ "id": "The unique ID of the coupon.",+ "product_id": "The ID of the product the coupon belongs to.",+ "coupon_code": "The code customers enter to redeem the coupon.",+ "coupon_name": "The coupon's name.",+ "discount": "The discount value of the coupon.",+ "discount_type": "Whether the discount is a fixed amount or a percentage.",+ "apply_to": "Which charges the coupon applies to.",+ "redemption_type": "How often the coupon discount recurs.",+ "maximum_redemption": "The maximum number of times the coupon can be redeemed.",+ "used_redemption": "The number of times the coupon has been redeemed.",+ "valid_upto": "When the coupon expires.",+ "status": "Whether the coupon is active.",+ "createdAt": "When the coupon was created.",+ "updatedAt": "When the coupon was last updated.",+ },+ },+ "licenses": {+ "description": "A license batch of a product, used to hand out license codes with subscriptions.",+ "docs_url": PABBLY_DOCS_URL,+ "columns": {+ "id": "The unique ID of the license batch.",+ "product_id": "The ID of the product the licenses belong to.",+ "plan_id": "The ID of the plan the licenses are handed out with.",+ "name": "The license batch's name.",+ "method": "How license codes are generated or imported.",+ "license_codes": "The license codes in the batch.",+ "total_license": "The total number of licenses in the batch.",+ "used_license": "The number of licenses already handed out.",+ "status": "Whether the license batch is active.",+ "createdAt": "When the license batch was created.",+ "updatedAt": "When the license batch was last updated.",+ },+ },+ "multiplans": {+ "description": "A multiplan checkout page combining several plans of a product.",+ "docs_url": PABBLY_DOCS_URL,+ "columns": {+ "id": "The unique ID of the multiplan.",+ "product_id": "The ID of the product the multiplan belongs to.",+ "page_title": "The title of the multiplan checkout page.",+ "checkout_page": "The URL of the multiplan checkout page.",+ "plans": "The plans offered on the multiplan checkout page.",+ "createdAt": "When the multiplan was created.",+ "updatedAt": "When the multiplan was last updated.",+ },+ },+ "payment_methods": {+ "description": "A stored payment method of a customer.",+ "docs_url": PABBLY_DOCS_URL,+ "columns": {+ "id": "The unique ID of the payment method.",+ "customer_id": "The ID of the customer the payment method belongs to.",+ "type": "The type of the payment method.",+ "gateway": "The payment gateway the payment method is stored with.",+ "createdAt": "When the payment method was created.",+ "updatedAt": "When the payment method was last updated.",+ },+ },+ "payment_gateways": {+ "description": "A payment gateway connected to your Pabbly Subscription Billing account.",+ "docs_url": PABBLY_DOCS_URL,+ "columns": {+ "id": "The unique ID of the payment gateway connection.",+ "gateway_name": "The payment gateway's name.",+ "gateway_type": "The payment gateway's type.",+ "gateway_status": "Whether the payment gateway is enabled.",+ "gateway_url": "The payment gateway's URL, if any.",+ "createdAt": "When the payment gateway was connected.",+ "updatedAt": "When the payment gateway connection was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/pabbly_subscriptions_billing.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/pabbly_subscriptions_billing.pynew file mode 100644index 000000000000..fe77405433dd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/pabbly_subscriptions_billing.py@@ -0,0 +1,262 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.pabbly_subscriptions_billing.settings import (+ PABBLY_ENDPOINTS,+ PabblyEndpointConfig,+)++PABBLY_BASE_URL = "https://payments.pabbly.com/api/v1"+# List endpoints accept `limit` up to 100 (default 50); the largest page minimises round trips+# against the account's 10,000 requests/day quota.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint used to confirm the API key + secret key pair is genuine. The pair is+# account-wide, so one probe validates access to every endpoint.+DEFAULT_PROBE_PATH = "/customers"+++class PabblyRetryableError(Exception):+ pass+++class PabblyResumeConfig:+ # Next `page` to fetch. For top-level endpoints this is the endpoint's own page; for fan-out+ # children it is the PARENT listing's page — a crashed sync resumes from the first parent page+ # whose children weren't all yielded, and merge dedupes re-pulled rows on the primary key.+ page: int = 1+++def _make_session(api_key: str, secret_key: str, capture: bool = False) -> requests.Session:+ # HTTP sample capture is opt-in: it defaults off here (so the credential-validation probe and+ # any future caller stay safe by default) and get_rows enables it per endpoint via the+ # capture_http_samples flag, which is only set on catalog-metadata endpoints.+ # Pabbly authenticates with HTTP Basic only: API key as username, secret key as password.+ # (Its docs portal shows a generic Bearer example, but the live API rejects Bearer tokens.)+ session = make_tracked_session(+ headers={"Accept": "application/json"}, redact_values=(api_key, secret_key), capture=capture+ )+ session.auth = (api_key, secret_key)+ return session+++def _is_no_data_message(message: str) -> bool:+ # Pabbly signals "this resource has no rows" with messages like "No transaction found" /+ # "No data found" rather than an empty list. Auth failures ("Invalid user api") don't match.+ lowered = message.lower()+ return lowered.startswith("no ") and "found" in lowered+++@retry(+ retry=retry_if_exception_type((PabblyRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ path: str,+ page: int,+ limit: int,+ logger: FilteringBoundLogger,+ ignore_no_data_errors: bool,+) -> list[dict[str, Any]]:+ response = session.get(+ f"{PABBLY_BASE_URL}{path}",+ params={"page": page, "limit": limit},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise PabblyRetryableError(f"Pabbly API error (retryable): status={response.status_code}, path={path}")++ # Pabbly answers some endpoints with a 400 when the resource simply has no data (e.g. a+ # product with no addons). Its Airbyte connector ignores those the same way.+ if response.status_code == 400 and ignore_no_data_errors:+ logger.debug(f"Pabbly: treating 400 as empty page. path={path}, body={response.text[:200]}")+ return []++ if not response.ok:+ logger.error(f"Pabbly API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ data = response.json()+ if not isinstance(data, dict):+ raise PabblyRetryableError(f"Pabbly returned an unexpected payload for {path}: {type(data).__name__}")++ # Every response is wrapped in {"status": ..., "message": ..., "data": ...}. A "no data"+ # error envelope can come back with HTTP 200 too.+ if data.get("status") == "error":+ message = str(data.get("message", ""))+ if _is_no_data_message(message):+ return []+ raise ValueError(f"Pabbly API returned an error for {path}: {message}")++ rows = data.get("data")+ if rows is None:+ return []+ if isinstance(rows, dict):+ return [rows]+ if not isinstance(rows, list):+ raise PabblyRetryableError(f"Pabbly returned an unexpected data field for {path}: {type(rows).__name__}")+ return rows+++def _iter_top_level(+ session: requests.Session,+ config: PabblyEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PabblyResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.page if resume else 1+ if resume:+ logger.debug(f"Pabbly: resuming {config.name} from page {page}")++ while True:+ rows = _fetch_page(session, config.path, page, PAGE_SIZE, logger, config.ignore_no_data_errors)+ if rows:+ yield rows++ # A short page means we've reached the end of the list.+ if len(rows) < PAGE_SIZE:+ break++ page += 1+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes any re-pulled rows on the primary key.+ resumable_source_manager.save_state(PabblyResumeConfig(page=page))+++def _iter_children_of_parent(+ session: requests.Session,+ config: PabblyEndpointConfig,+ parent_id: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ path = config.path.format(parent_id=parent_id)+ page = 1+ while True:+ rows = _fetch_page(session, path, page, PAGE_SIZE, logger, config.ignore_no_data_errors)+ if rows:+ if config.parent_field:+ for row in rows:+ row.setdefault(config.parent_field, parent_id)+ yield rows+ if len(rows) < PAGE_SIZE:+ break+ page += 1+++def _iter_fan_out(+ session: requests.Session,+ config: PabblyEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PabblyResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ assert config.parent is not None+ parent_config = PABBLY_ENDPOINTS[config.parent]++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ parent_page = resume.page if resume else 1+ if resume:+ logger.debug(f"Pabbly: resuming {config.name} from parent page {parent_page}")++ while True:+ parents = _fetch_page(+ session, parent_config.path, parent_page, PAGE_SIZE, logger, parent_config.ignore_no_data_errors+ )+ for parent in parents:+ parent_id = str(parent["id"])+ yield from _iter_children_of_parent(session, config, parent_id, logger)++ if len(parents) < PAGE_SIZE:+ break++ parent_page += 1+ # Save AFTER every child of this parent page has been yielded — a crash resumes from the+ # next parent page, re-pulling at most one parent page's children (merge dedupes them).+ resumable_source_manager.save_state(PabblyResumeConfig(page=parent_page))+++def get_rows(+ api_key: str,+ secret_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PabblyResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = PABBLY_ENDPOINTS[endpoint]+ session = _make_session(api_key, secret_key, capture=config.capture_http_samples)++ if config.parent is not None:+ yield from _iter_fan_out(session, config, logger, resumable_source_manager)+ else:+ yield from _iter_top_level(session, config, logger, resumable_source_manager)+++def pabbly_source(+ api_key: str,+ secret_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PabblyResumeConfig],+) -> SourceResponse:+ config = PABBLY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ secret_key=secret_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def check_access(api_key: str, secret_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the API key + secret key pair.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure (Pabbly+ answers invalid credentials with a 403), ``0`` for a connection problem, other HTTP+ status otherwise.+ """+ session = _make_session(api_key, secret_key)+ try:+ response = session.get(f"{PABBLY_BASE_URL}{path}", params={"page": 1, "limit": 1}, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Pabbly Subscription Billing: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Pabbly Subscription Billing returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_key: str, secret_key: str) -> tuple[bool, str | None]:+ status, message = check_access(api_key, secret_key)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Pabbly Subscription Billing API key or secret key"+ return False, message or "Could not validate Pabbly Subscription Billing credentials"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/settings.pynew file mode 100644index 000000000000..b2823fc76e93--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/settings.py@@ -0,0 +1,124 @@+from dataclasses import dataclass, field+from typing import Optional+++@dataclass+class PabblyEndpointConfig:+ name: str+ # Path under /api/v1. Fan-out child paths contain a "{parent_id}" placeholder.+ path: str+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation-time field to partition by. None when the resource has no createdAt.+ partition_key: Optional[str] = "createdAt"+ # Fan-out: name of the parent endpoint whose ids fill "{parent_id}" in `path`.+ parent: Optional[str] = None+ # Fan-out: column carrying the parent id on child rows. Most child objects already include+ # it (e.g. transactions carry customer_id); we inject it when the API omits it so the+ # composite primary key is always populated.+ parent_field: Optional[str] = None+ # Pabbly answers some endpoints with a 400 or a {"status": "error", "message": "No X found"}+ # envelope when there is simply no data (its Airbyte connector ignores those the same way).+ # When True, such responses are treated as an empty page instead of an error.+ ignore_no_data_errors: bool = False+ # HTTP sample capture stores raw response bodies as diagnostic artifacts on a shared prefix+ # readable beyond the importing project. The name-based scrubbers only drop known auth keys, so+ # capture is opt-in: it defaults off and is enabled only for endpoints whose bodies are limited+ # to product/plan catalog metadata. It stays off for endpoints carrying customer PII (names,+ # addresses, tax IDs), payment data, redeemable secrets (license/coupon codes), or bearer URLs+ # (invoice links, gateway webhook URLs) the scrubbers can't recognise. Requests stay metered and+ # logged either way.+ capture_http_samples: bool = False+++# Pabbly Subscription Billing REST endpoints (https://apidocs.pabbly.com/pabbly/subscription-billing).+# All are full refresh only: the API exposes no documented server-side created/updated-after+# filter, so there is no incremental cursor to advance (its Airbyte connector is likewise+# full-refresh only across every stream).+#+# Pabbly ids look globally unique (Mongo-style object ids), but the docs don't guarantee it, so+# fan-out children key on (parent id, id) to stay unique table-wide.+PABBLY_ENDPOINTS: dict[str, PabblyEndpointConfig] = {+ "customers": PabblyEndpointConfig(name="customers", path="/customers"),+ "subscriptions": PabblyEndpointConfig(name="subscriptions", path="/subscriptions"),+ "invoices": PabblyEndpointConfig(name="invoices", path="/invoices"),+ "products": PabblyEndpointConfig(+ name="products",+ path="/products",+ ignore_no_data_errors=True,+ # Product catalog metadata only (no customer content or credentials); safe to capture.+ capture_http_samples=True,+ ),+ "multiplans": PabblyEndpointConfig(+ name="multiplans",+ path="/multiplans",+ # Checkout-page catalog metadata only (no customer content or credentials); safe to capture.+ capture_http_samples=True,+ ),+ "payment_gateways": PabblyEndpointConfig(name="payment_gateways", path="/paymentgateways"),+ "addons": PabblyEndpointConfig(+ name="addons",+ path="/addons/{parent_id}",+ primary_keys=["product_id", "id"],+ parent="products",+ parent_field="product_id",+ ignore_no_data_errors=True,+ # Addon catalog metadata only (no customer content or credentials); safe to capture.+ capture_http_samples=True,+ ),+ "addon_list_category": PabblyEndpointConfig(+ name="addon_list_category",+ path="/addonlistcategory/{parent_id}",+ primary_keys=["product_id", "id"],+ # Addon categories expose no createdAt to partition by.+ partition_key=None,+ parent="products",+ parent_field="product_id",+ ignore_no_data_errors=True,+ # Addon-category catalog metadata only (no customer content or credentials); safe to capture.+ capture_http_samples=True,+ ),+ "coupons": PabblyEndpointConfig(+ name="coupons",+ path="/coupon/{parent_id}",+ primary_keys=["product_id", "id"],+ parent="products",+ parent_field="product_id",+ ignore_no_data_errors=True,+ ),+ "licenses": PabblyEndpointConfig(+ name="licenses",+ path="/products/{parent_id}/licenses",+ primary_keys=["product_id", "id"],+ parent="products",+ parent_field="product_id",+ ignore_no_data_errors=True,+ ),+ "payment_methods": PabblyEndpointConfig(+ name="payment_methods",+ path="/paymentmethods/{parent_id}",+ primary_keys=["customer_id", "id"],+ parent="customers",+ parent_field="customer_id",+ ignore_no_data_errors=True,+ ),+ "refunds": PabblyEndpointConfig(+ name="refunds",+ path="/refund/{parent_id}",+ primary_keys=["customer_id", "id"],+ parent="customers",+ parent_field="customer_id",+ ignore_no_data_errors=True,+ ),+ "transactions": PabblyEndpointConfig(+ name="transactions",+ path="/transactions/{parent_id}",+ primary_keys=["customer_id", "id"],+ parent="customers",+ parent_field="customer_id",+ ignore_no_data_errors=True,+ ),+}++ENDPOINTS = tuple(PABBLY_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/source.pyindex 541221fb4479..e8a5c0031da7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/source.py@@ -1,21 +1,44 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (PabblySubscriptionsBillingSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.pabbly_subscriptions_billing.pabbly_subscriptions_billing import (+ PabblyResumeConfig,+ pabbly_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.pabbly_subscriptions_billing.settings import (+ ENDPOINTS,+ PABBLY_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class PabblySubscriptionsBillingSource(SimpleSource[PabblySubscriptionsBillingSourceConfig]):+class PabblySubscriptionsBillingSource(ResumableSource[PabblySubscriptionsBillingSourceConfig, PabblyResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PABBLYSUBSCRIPTIONSBILLING@@ -25,8 +48,98 @@ class PabblySubscriptionsBillingSource(SimpleSource[PabblySubscriptionsBillingSoreturn SourceConfig(name=SchemaExternalDataSourceType.PABBLY_SUBSCRIPTIONS_BILLING,category=DataWarehouseSourceCategory.PAYMENTS___BILLING,- label="Pabbly Subscriptions Billing",+ label="Pabbly Subscription Billing",+ keywords=["pabbly subscriptions"],+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Pabbly Subscription Billing API key and secret key to pull your billing data into the PostHog Data warehouse.++You can generate both keys under **Settings → API Settings** in [Pabbly Subscription Billing](https://payments.pabbly.com). The keys grant read access to your customers, subscriptions, products, invoices, transactions, and related billing objects.+""",iconPath="/static/services/pabbly_subscriptions_billing.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/pabbly-subscriptions-billing",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="secret_key",+ label="Secret key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.pabbly_subscriptions_billing.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://payments.pabbly.com": "Your Pabbly Subscription Billing API key or secret key is invalid or has been regenerated. Generate new keys under Settings → API Settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://payments.pabbly.com": "Your Pabbly Subscription Billing API key or secret key is invalid or has been regenerated. Generate new keys under Settings → API Settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: PabblySubscriptionsBillingSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — Pabbly exposes no server-side created/updated-after+ # filter, so there is no incremental cursor to advance.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: PabblySubscriptionsBillingSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The API key + secret key pair is account-wide, so a single probe validates access to+ # every schema.+ return validate_credentials(config.api_key, config.secret_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PabblyResumeConfig]:+ return ResumableSourceManager[PabblyResumeConfig](inputs, PabblyResumeConfig)++ def source_for_pipeline(+ self,+ config: PabblySubscriptionsBillingSourceConfig,+ resumable_source_manager: ResumableSourceManager[PabblyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in PABBLY_ENDPOINTS:+ raise ValueError(f"Unknown Pabbly Subscription Billing schema '{inputs.schema_name}'")++ return pabbly_source(+ api_key=config.api_key,+ secret_key=config.secret_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/tests/test_pabbly_subscriptions_billing.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/tests/test_pabbly_subscriptions_billing.pynew file mode 100644index 000000000000..0ba1972b6612--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/tests/test_pabbly_subscriptions_billing.py@@ -0,0 +1,407 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.pabbly_subscriptions_billing import (+ pabbly_subscriptions_billing as pabbly,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.pabbly_subscriptions_billing.pabbly_subscriptions_billing import (+ PAGE_SIZE,+ PabblyResumeConfig,+ PabblyRetryableError,+ check_access,+ get_rows,+ pabbly_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.pabbly_subscriptions_billing.settings import (+ ENDPOINTS,+ PABBLY_ENDPOINTS,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = pabbly._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: PabblyResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[PabblyResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> PabblyResumeConfig | None:+ return self._state++ def save_state(self, data: PabblyResumeConfig) -> None:+ self.saved.append(data)+++def _full_page(prefix: str) -> list[dict]:+ return [{"id": f"{prefix}{i}"} for i in range(PAGE_SIZE)]+++def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: dict[tuple[str, int], list[dict]],+ endpoint: str,+) -> list[dict]:+ def fake_fetch(+ session: Any, path: str, page: int, limit: int, logger: Any, ignore_no_data_errors: bool+ ) -> list[dict]:+ return pages.get((path, page), [])++ monkeypatch.setattr(pabbly, "_fetch_page", fake_fetch)+ monkeypatch.setattr(pabbly, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="pabbly-key",+ secret_key="pabbly-secret",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows+++class TestGetRowsTopLevel:+ def test_single_short_page_yields_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, {("/customers", 1): [{"id": "1"}, {"id": "2"}]}, "customers")+ assert rows == [{"id": "1"}, {"id": "2"}]+ # The list ended on the first page, so no resume state is persisted.+ assert manager.saved == []++ def test_follows_page_pagination_until_short_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ ("/customers", 1): _full_page("a"),+ ("/customers", 2): [{"id": "last"}],+ }+ rows = _collect(manager, monkeypatch, pages, "customers")+ assert len(rows) == PAGE_SIZE + 1+ # State is saved after the first full page (pointing at the next page), then we stop.+ assert [s.page for s in manager.saved] == [2]++ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(PabblyResumeConfig(page=3))+ # Pages 1 and 2 must never be re-fetched on resume.+ rows = _collect(manager, monkeypatch, {("/customers", 3): [{"id": "5"}]}, "customers")+ assert rows == [{"id": "5"}]++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, {}, "customers")+ assert rows == []+ assert manager.saved == []+++class TestGetRowsFanOut:+ def test_fetches_children_for_each_parent_and_injects_parent_id(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ ("/customers", 1): [{"id": "cus_1"}, {"id": "cus_2"}],+ ("/transactions/cus_1", 1): [{"id": "tra_1"}],+ # The API already stamps customer_id on this row; injection must not overwrite it.+ ("/transactions/cus_2", 1): [{"id": "tra_2", "customer_id": "already-set"}],+ }+ rows = _collect(manager, monkeypatch, pages, "transactions")+ assert rows == [+ {"id": "tra_1", "customer_id": "cus_1"},+ {"id": "tra_2", "customer_id": "already-set"},+ ]+ # A single short parent page means the whole sync fit in one pass — no state persisted.+ assert manager.saved == []++ def test_paginates_children_within_a_parent(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ ("/products", 1): [{"id": "pro_1"}],+ ("/addons/pro_1", 1): _full_page("add_a"),+ ("/addons/pro_1", 2): [{"id": "add_last"}],+ }+ rows = _collect(manager, monkeypatch, pages, "addons")+ assert len(rows) == PAGE_SIZE + 1+ assert all(row["product_id"] == "pro_1" for row in rows)++ def test_saves_state_after_each_full_parent_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ ("/customers", 1): _full_page("cus_a"),+ ("/customers", 2): [{"id": "cus_last"}],+ }+ rows = _collect(manager, monkeypatch, pages, "refunds")+ assert rows == []+ # Resume state advances to parent page 2 only once every child of page 1 was yielded.+ assert [s.page for s in manager.saved] == [2]++ def test_resumes_from_saved_parent_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(PabblyResumeConfig(page=2))+ pages = {+ # Parent page 1 must never be re-fetched on resume.+ ("/customers", 1): [{"id": "cus_wrong"}],+ ("/customers", 2): [{"id": "cus_1"}],+ ("/paymentmethods/cus_1", 1): [{"id": "pay_1"}],+ }+ rows = _collect(manager, monkeypatch, pages, "payment_methods")+ assert rows == [{"id": "pay_1", "customer_id": "cus_1"}]++ def test_parent_row_without_an_id_fails_fast(self, monkeypatch: Any) -> None:+ # A parent row missing its primary key must raise rather than silently drop its children.+ manager = _FakeResumableManager()+ pages = {+ ("/products", 1): [{"name": "no id"}],+ }+ with pytest.raises(KeyError):+ _collect(manager, monkeypatch, pages, "coupons")+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body if body is not None else {"status": "success", "data": []}+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(PabblyRetryableError):+ _fetch_page_unwrapped(session, "/customers", 1, PAGE_SIZE, MagicMock(), False)++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "/customers", 1, PAGE_SIZE, MagicMock(), False)++ def test_400_raises_when_endpoint_does_not_ignore_no_data_errors(self) -> None:+ session = self._session_returning(400)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "/customers", 1, PAGE_SIZE, MagicMock(), False)++ def test_400_is_empty_page_when_endpoint_ignores_no_data_errors(self) -> None:+ session = self._session_returning(400)+ assert _fetch_page_unwrapped(session, "/addons/pro_1", 1, PAGE_SIZE, MagicMock(), True) == []++ def test_success_returns_data_rows(self) -> None:+ session = self._session_returning(200, {"status": "success", "data": [{"id": "1"}]})+ assert _fetch_page_unwrapped(session, "/customers", 1, PAGE_SIZE, MagicMock(), False) == [{"id": "1"}]++ def test_dict_data_is_wrapped_into_a_single_row(self) -> None:+ session = self._session_returning(200, {"status": "success", "data": {"id": "1"}})+ assert _fetch_page_unwrapped(session, "/customers", 1, PAGE_SIZE, MagicMock(), False) == [{"id": "1"}]++ def test_missing_data_key_is_empty_page(self) -> None:+ session = self._session_returning(200, {"status": "success"})+ assert _fetch_page_unwrapped(session, "/customers", 1, PAGE_SIZE, MagicMock(), False) == []++ def test_non_dict_body_is_retryable(self) -> None:+ session = self._session_returning(200, [{"id": "1"}])+ with pytest.raises(PabblyRetryableError):+ _fetch_page_unwrapped(session, "/customers", 1, PAGE_SIZE, MagicMock(), False)++ @parameterized.expand(+ [+ ("no_transaction_found", "No transaction found"),+ ("no_data_found", "No data found"),+ ]+ )+ def test_no_data_error_envelope_is_empty_page(self, _name: str, message: str) -> None:+ # Pabbly can answer "resource has no rows" as an HTTP 200 error envelope.+ session = self._session_returning(200, {"status": "error", "message": message})+ assert _fetch_page_unwrapped(session, "/refund/cus_1", 1, PAGE_SIZE, MagicMock(), True) == []++ def test_other_error_envelope_raises(self) -> None:+ session = self._session_returning(200, {"status": "error", "message": "Invalid user api"})+ with pytest.raises(ValueError, match="Invalid user api"):+ _fetch_page_unwrapped(session, "/customers", 1, PAGE_SIZE, MagicMock(), False)++ def test_sends_page_and_limit_params(self) -> None:+ session = self._session_returning(200)+ _fetch_page_unwrapped(session, "/subscriptions", 4, PAGE_SIZE, MagicMock(), False)+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"page": 4, "limit": PAGE_SIZE}+++class TestMakeSession:+ @patch(f"{pabbly.__name__}.make_tracked_session")+ def test_authenticates_with_http_basic(self, mock_session: MagicMock) -> None:+ # Pabbly only accepts HTTP Basic (API key as username, secret key as password); a+ # regression to Bearer headers would fail against the live API.+ session = MagicMock()+ mock_session.return_value = session+ pabbly._make_session("pabbly-key", "pabbly-secret")+ assert session.auth == ("pabbly-key", "pabbly-secret")+ assert mock_session.call_args.kwargs["redact_values"] == ("pabbly-key", "pabbly-secret")+++class TestHttpSampleCapture:+ @parameterized.expand(+ [+ # Capture is opt-in: only endpoints limited to product/plan catalog metadata may write raw+ # bodies to HTTP samples. Everything carrying customer PII, payment data, redeemable+ # secrets, or bearer URLs the scrubbers can't recognise must stay out of captured samples.+ ("products", True),+ ("multiplans", True),+ ("addons", True),+ ("addon_list_category", True),+ ("customers", False),+ ("subscriptions", False),+ ("invoices", False),+ ("payment_gateways", False),+ ("payment_methods", False),+ ("refunds", False),+ ("transactions", False),+ ("licenses", False),+ ("coupons", False),+ ]+ )+ @patch(f"{pabbly.__name__}._fetch_page")+ @patch(f"{pabbly.__name__}.make_tracked_session")+ def test_capture_enabled_only_for_catalog_metadata_endpoints(+ self,+ endpoint: str,+ expected_capture: bool,+ mock_session: MagicMock,+ mock_fetch: MagicMock,+ ) -> None:+ mock_session.return_value = MagicMock()+ mock_fetch.return_value = []++ list(+ get_rows(+ api_key="pabbly-key",+ secret_key="pabbly-secret",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )++ assert mock_session.call_args.kwargs["capture"] is expected_capture++ @patch(f"{pabbly.__name__}.make_tracked_session")+ def test_credential_probe_never_captures(self, mock_session: MagicMock) -> None:+ # The probe hits /customers, so a captured sample would persist a raw customer record;+ # credential validation must run with capture off.+ session = MagicMock()+ session.get.return_value = MagicMock(status_code=200, ok=True)+ mock_session.return_value = session++ pabbly.check_access("pabbly-key", "pabbly-secret")++ assert mock_session.call_args.kwargs["capture"] is False+++class TestCheckAccess:+ @staticmethod+ def _session(response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ return session++ @parameterized.expand(+ [+ ("ok", 200, True, 200, None),+ ("unauthorized", 401, False, 401, None),+ ("forbidden", 403, False, 403, None),+ ("server_error", 500, False, 500, "Pabbly Subscription Billing returned HTTP 500"),+ ]+ )+ @patch(f"{pabbly.__name__}.make_tracked_session")+ def test_status_mapping(+ self,+ _name: str,+ status: int,+ ok: bool,+ expected_status: int,+ expected_message: str | None,+ mock_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ mock_session.return_value = self._session(response)+ assert check_access("pabbly-key", "pabbly-secret") == (expected_status, expected_message)++ @patch(f"{pabbly.__name__}.make_tracked_session")+ def test_connection_error_maps_to_zero(self, mock_session: MagicMock) -> None:+ mock_session.return_value = self._session(requests.ConnectionError("boom"))+ status, message = check_access("pabbly-key", "pabbly-secret")+ assert status == 0+ assert message is not None and "boom" in message++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid Pabbly Subscription Billing API key or secret key"),+ ("forbidden", 403, False, "Invalid Pabbly Subscription Billing API key or secret key"),+ ("server_error", 500, False, "Pabbly Subscription Billing returned HTTP 500"),+ ]+ )+ @patch(f"{pabbly.__name__}.make_tracked_session")+ def test_validate_credentials(+ self,+ _name: str,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ mock_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ mock_session.return_value = self._session(response)+ assert validate_credentials("pabbly-key", "pabbly-secret") == (expected_valid, expected_message)+++class TestPabblySourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ config = PABBLY_ENDPOINTS[endpoint]+ response = pabbly_source(+ api_key="pabbly-key",+ secret_key="pabbly-secret",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_fan_out_children_key_on_parent_and_id(self) -> None:+ # Pabbly doesn't document that child ids are globally unique, so a per-parent id must+ # still be unique table-wide via the composite key.+ for config in PABBLY_ENDPOINTS.values():+ if config.parent:+ assert config.parent_field is not None+ assert config.primary_keys == [config.parent_field, "id"]+ assert "{parent_id}" in config.path+ else:+ assert config.primary_keys == ["id"]+ assert "{parent_id}" not in config.pathdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/tests/test_pabbly_subscriptions_billing_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/tests/test_pabbly_subscriptions_billing_source.pynew file mode 100644index 000000000000..7f9e117f3c82--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/tests/test_pabbly_subscriptions_billing_source.py@@ -0,0 +1,148 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (+ PabblySubscriptionsBillingSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.pabbly_subscriptions_billing.pabbly_subscriptions_billing import (+ PabblyResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.pabbly_subscriptions_billing.settings import (+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.pabbly_subscriptions_billing.source import (+ PabblySubscriptionsBillingSource,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestPabblySubscriptionsBillingSource:+ def setup_method(self) -> None:+ self.source = PabblySubscriptionsBillingSource()+ self.team_id = 123+ self.config = PabblySubscriptionsBillingSourceConfig(api_key="pabbly-key", secret_key="pabbly-secret")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.PABBLYSUBSCRIPTIONSBILLING++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "PabblySubscriptionsBilling"+ assert config.label == "Pabbly Subscription Billing"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/pabbly-subscriptions-billing"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key", "secret_key"]++ @parameterized.expand([("api_key",), ("secret_key",)])+ def test_credential_fields_are_secret_passwords(self, name: str) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == name)+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_connection_host_fields(self) -> None:+ # Both fields are secrets and the base URL is hardcoded, so there is no non-secret field+ # an editor could retarget to reuse a preserved credential against another host.+ assert self.source.connection_host_fields == []++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["subscriptions"])+ assert len(schemas) == 1+ assert schemas[0].name == "subscriptions"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://payments.pabbly.com/api/v1/customers?page=1&limit=100",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://payments.pabbly.com/api/v1/subscriptions?page=1&limit=100",+ ),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://payments.pabbly.com/api/v1/customers",+ ),+ (+ "rate_limited",+ "429 Client Error: Too Many Requests for url: https://payments.pabbly.com/api/v1/subscriptions",+ ),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.pabbly_subscriptions_billing.source.validate_credentials"+ )+ def test_validate_credentials_delegates_with_both_keys(self, mock_validate: mock.MagicMock) -> None:+ # The status-to-message mapping lives in the transport module; here we only assert the+ # source probes with the configured key pair and returns the delegate's verdict unchanged.+ mock_validate.return_value = (False, "Invalid Pabbly Subscription Billing API key or secret key")+ result = self.source.validate_credentials(self.config, self.team_id)+ mock_validate.assert_called_once_with("pabbly-key", "pabbly-secret")+ assert result == (False, "Invalid Pabbly Subscription Billing API key or secret key")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is PabblyResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.pabbly_subscriptions_billing.source.pabbly_source"+ )+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "transactions"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "pabbly-key"+ assert kwargs["secret_key"] == "pabbly-secret"+ assert kwargs["endpoint"] == "transactions"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown Pabbly Subscription Billing schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)