: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): add Dodo Payments source (#77090)
Tom Owerse35081528598
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex f4fbda8d08e9..abab917c7744 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -215,6 +215,7 @@ the row lists both.| dockerhub | HTTP | requests | ✅ || docuseal | HTTP | requests | ✅ || docusign | HTTP | requests | ✅ |+| dodopayments | HTTP | requests + `rest_source.RESTClient` | ✅ || doit | HTTP | requests | ✅ || doppler | HTTP | requests | ✅ || dovetail | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -904,7 +905,6 @@ doesn't conflict with concurrent PRs.- directus- discord- display_video_360-- dodopayments- dolibarr- donorbox- doorloopdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/canonical_descriptions.pynew file mode 100644index 000000000000..bf15d019219c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/canonical_descriptions.py@@ -0,0 +1,367 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_ROOT = "https://docs.dodopayments.com/api-reference"++# Table and column descriptions taken from the Dodo Payments OpenAPI specification, which is the+# same source the vendor's SDK reference is generated from.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "payments": {+ "description": "One-off and subscription payments collected by Dodo Payments as merchant of record.",+ "docs_url": f"{_DOCS_ROOT}/payments/get-payments",+ "columns": {+ "payment_id": "Unique identifier for the payment.",+ "brand_id": "Brand the payment was collected under.",+ "card_last_four": "The last four digits of the card.",+ "card_network": "Card network like VISA, MASTERCARD etc.",+ "created_at": "Timestamp when the payment was created, in UTC.",+ "currency": "Currency the payment was collected in, as an ISO 4217 code.",+ "customer": "Customer the payment belongs to, including customer_id, name and email.",+ "digital_products_delivered": "Whether the purchased digital products have been delivered.",+ "dispute_status": "Status of any dispute raised against the payment.",+ "has_license_key": "Whether a license key was issued for the payment.",+ "invoice_id": "Invoice ID for this payment. Uses India-specific invoice ID if available.",+ "invoice_url": "URL to download the invoice PDF for this payment.",+ "metadata": "Arbitrary key-value metadata. Values can be string, integer, number, or boolean.",+ "payment_method": "Payment method used, for example card or upi.",+ "payment_method_type": "Sub-type of the payment method, for example credit or debit.",+ "payment_provider": (+ "Which processor handled this payment. `stripe` / `adyen` for BYOP routes (the merchant's "+ "own payment connector); `dodo` for everything Dodo processed itself."+ ),+ "refund_status": "Status of any refund issued against the payment.",+ "status": "Current status of the payment, for example succeeded, failed or processing.",+ "subscription_id": "Subscription this payment was charged for, when it is a recurring payment.",+ "total_amount": "Total charged amount in the currency's smallest unit.",+ },+ },+ "subscriptions": {+ "description": "Recurring subscriptions, their billing schedule and current lifecycle status.",+ "docs_url": f"{_DOCS_ROOT}/subscriptions/list-subscriptions",+ "columns": {+ "subscription_id": "Unique identifier for the subscription.",+ "billing": "Billing address details for payments.",+ "cancel_at_next_billing_date": "Indicates if the subscription will cancel at the next billing date.",+ "cancelled_at": "Cancelled timestamp if the subscription is cancelled.",+ "created_at": "Timestamp when the subscription was created.",+ "currency": "Currency used for the subscription payments.",+ "customer": "Customer details associated with the subscription.",+ "customer_business_name": (+ "Business or legal name associated with the tax id (B2B). When set this is used on the "+ "invoice in place of the customer's personal name."+ ),+ "discounts": "All stacked discounts applied, in order of application.",+ "metadata": "Additional custom data associated with the subscription.",+ "next_billing_date": (+ "Timestamp of the next scheduled billing. Indicates the end of current billing period."+ ),+ "on_demand": "Whether the subscription is on-demand or not.",+ "payment_frequency_count": "Number of payment frequency intervals.",+ "payment_frequency_interval": "Time interval for payment frequency (e.g. month, year).",+ "payment_method_id": "Saved payment method id used for recurring charges.",+ "previous_billing_date": ("Timestamp of the last payment. Indicates the start of current billing period."),+ "product_id": "Identifier of the product associated with this subscription.",+ "product_name": "Name of the product associated with this subscription.",+ "quantity": "Number of units/items included in the subscription.",+ "recurring_pre_tax_amount": (+ "Amount charged before tax for each recurring payment in the currency's smallest unit."+ ),+ "status": "Current status of the subscription.",+ "subscription_period_count": "Number of subscription period intervals.",+ "subscription_period_interval": "Time interval for the subscription period (e.g. month, year).",+ "tax_id": "Tax identifier provided for this subscription (if applicable).",+ "tax_inclusive": "Indicates if the recurring_pre_tax_amount is tax inclusive.",+ "trial_period_days": "Number of days in the trial period (0 if no trial).",+ },+ },+ "customers": {+ "description": "Customers who have paid through Dodo Payments.",+ "docs_url": f"{_DOCS_ROOT}/customers/list-customers",+ "columns": {+ "customer_id": "Unique identifier for the customer.",+ "business_id": "Business the customer belongs to.",+ "created_at": "Timestamp when the customer was created, in UTC.",+ "email": "Customer's email address.",+ "metadata": "Additional metadata for the customer.",+ "name": "Customer's name.",+ "phone_number": "Customer's phone number, if provided.",+ },+ },+ "refunds": {+ "description": "Refunds issued against payments.",+ "docs_url": f"{_DOCS_ROOT}/refunds/list-refunds",+ "columns": {+ "refund_id": "The unique identifier of the refund.",+ "amount": "The refunded amount.",+ "business_id": "The unique identifier of the business issuing the refund.",+ "created_at": "The timestamp of when the refund was created in UTC.",+ "currency": "Currency of the refunded amount, as an ISO 4217 code.",+ "is_partial": "If true the refund is a partial refund.",+ "payment_id": "The unique identifier of the payment associated with the refund.",+ "reason": "The reason provided for the refund, if any.",+ "status": "The current status of the refund.",+ },+ },+ "disputes": {+ "description": "Chargebacks and disputes raised against payments, with their current stage and status.",+ "docs_url": f"{_DOCS_ROOT}/disputes/list-disputes",+ "columns": {+ "dispute_id": "The unique identifier of the dispute.",+ "amount": ("The amount involved in the dispute, represented as a string to accommodate precision."),+ "business_id": "The unique identifier of the business involved in the dispute.",+ "created_at": "The timestamp of when the dispute was created, in UTC.",+ "currency": ("The currency of the disputed amount, represented as an ISO 4217 currency code."),+ "dispute_stage": "The current stage of the dispute process.",+ "dispute_status": "The current status of the dispute.",+ "is_resolved_by_rdr": "Whether the dispute was resolved by Rapid Dispute Resolution.",+ "payment_id": "The unique identifier of the payment associated with the dispute.",+ "payment_provider": "Which processor handled the underlying payment.",+ },+ },+ "payouts": {+ "description": "Settlements paid out to the merchant, with the fees, tax, refunds and chargebacks netted off.",+ "docs_url": f"{_DOCS_ROOT}/payouts/get-payouts",+ "columns": {+ "payout_id": "The unique identifier of the payout.",+ "amount": "The total amount of the payout.",+ "business_id": "The unique identifier of the business associated with the payout.",+ "chargebacks": "The total value of chargebacks associated with the payout.",+ "created_at": "The timestamp when the payout was created, in UTC.",+ "currency": "The currency of the payout, represented as an ISO 4217 currency code.",+ "fee": "The fee charged for processing the payout.",+ "name": "The name of the payout recipient or purpose.",+ "payment_method": "The payment method used for the payout (e.g. bank transfer, card).",+ "payout_document_url": "The URL of the document associated with the payout.",+ "refunds": "The total value of refunds associated with the payout.",+ "remarks": "Any additional remarks or notes associated with the payout.",+ "status": "The current status of the payout.",+ "tax": "The tax applied to the payout.",+ "updated_at": "The timestamp when the payout was last updated, in UTC.",+ },+ },+ "license_keys": {+ "description": "License keys issued to customers by payment and subscription flows, or imported by the merchant.",+ "docs_url": f"{_DOCS_ROOT}/licenses/list-license-keys",+ "columns": {+ "id": "The unique identifier of the license key.",+ "activations_limit": "The maximum number of activations allowed for this license key.",+ "brand_id": "Brand id this license key belongs to.",+ "business_id": "The unique identifier of the business associated with the license key.",+ "created_at": "The timestamp indicating when the license key was created, in UTC.",+ "customer_id": "The unique identifier of the customer associated with the license key.",+ "expires_at": "The timestamp indicating when the license key expires, in UTC.",+ "instances_count": "The current number of instances activated for this license key.",+ "key": "The license key string.",+ "payment_id": "The unique identifier of the payment associated with the license key, if any.",+ "product_id": "The unique identifier of the product associated with the license key.",+ "source": (+ "The source of the license key - 'auto' for keys generated by payment/subscription flows, "+ "'import' for merchant-imported keys."+ ),+ "status": "The current status of the license key (e.g. active, inactive, expired).",+ "subscription_id": ("The unique identifier of the subscription associated with the license key, if any."),+ },+ },+ "license_key_instances": {+ "description": "Individual activations of a license key, one row per activated instance.",+ "docs_url": f"{_DOCS_ROOT}/licenses/list-license-key-instances",+ "columns": {+ "id": "Unique identifier of the license key instance.",+ "business_id": "Business the instance belongs to.",+ "created_at": "Timestamp when the instance was activated, in UTC.",+ "license_key_id": "License key this instance was activated against.",+ "name": "Name given to the activated instance.",+ },+ },+ "balance_ledger_entries": {+ "description": (+ "Merchant balance ledger: every credit and debit against the account balance, including "+ "payments, refunds, disputes, fees and payouts."+ ),+ "docs_url": f"{_DOCS_ROOT}/misc/list-ledger-entries",+ "columns": {+ "id": "Unique identifier of the ledger entry.",+ "after_balance": "Account balance after the entry was applied.",+ "amount": "Amount of the entry in the currency's smallest unit.",+ "before_balance": "Account balance before the entry was applied.",+ "business_id": "Business the ledger entry belongs to.",+ "created_at": "Timestamp when the entry was recorded, in UTC.",+ "currency": "Currency of the entry, as an ISO 4217 code.",+ "description": "Human-readable description of the entry.",+ "event_type": "What produced the entry, for example payment, refund, dispute, payout or tax.",+ "is_credit": "Whether the entry increased (true) or decreased (false) the balance.",+ "reference_object_id": "Identifier of the payment, refund, dispute or payout the entry refers to.",+ "usd_equivalent_amount": "The entry amount converted to USD.",+ },+ },+ "events": {+ "description": "Usage events ingested for metered billing.",+ "docs_url": f"{_DOCS_ROOT}/usage-based-billing/get-events",+ "columns": {+ "event_id": "Unique identifier of the event.",+ "business_id": "Business the event was ingested for.",+ "customer_id": "Customer the usage is attributed to.",+ "event_name": "Name of the event, matched against a meter's configured event name.",+ "metadata": "Arbitrary key-value payload sent with the event.",+ "timestamp": "Timestamp of when the event occurred, in UTC.",+ },+ },+ "products": {+ "description": "Products available for purchase, one-off and recurring.",+ "docs_url": f"{_DOCS_ROOT}/products/get-products",+ "columns": {+ "product_id": "Unique identifier for the product.",+ "business_id": "Unique identifier for the business to which the product belongs.",+ "created_at": "Timestamp when the product was created.",+ "currency": "Currency the product is priced in.",+ "description": "Description of the product, optional.",+ "entitlements": "Entitlements linked to this product.",+ "image": "URL of the product image, optional.",+ "is_recurring": "Indicates if the product is recurring (e.g. subscriptions).",+ "metadata": "Additional custom data associated with the product.",+ "name": "Name of the product, optional.",+ "price": "Price of the product in the lowest denomination of the currency.",+ "pricing_mode": "How the product is priced, for example a fixed price or usage based.",+ "tax_category": "Tax category associated with the product.",+ "tax_inclusive": "Indicates if the price is tax inclusive.",+ "updated_at": "Timestamp when the product was last updated.",+ },+ },+ "product_collections": {+ "description": "Groupings of products presented together in checkout.",+ "docs_url": f"{_DOCS_ROOT}/product-collections/list-product-collections",+ "columns": {+ "id": "Collection ID.",+ "created_at": "Timestamp when created.",+ "description": "Collection description.",+ "image": "Collection image URL.",+ "name": "Collection name.",+ "products_count": "Number of products in the collection.",+ "updated_at": "Timestamp when last updated.",+ },+ },+ "discounts": {+ "description": "Discount codes, their redemption limits and how often they have been used.",+ "docs_url": f"{_DOCS_ROOT}/discounts/get-discounts",+ "columns": {+ "discount_id": "The unique discount ID.",+ "amount": "The discount amount in basis points (e.g. 540 => 5.4%).",+ "business_id": "The business this discount belongs to.",+ "code": "The discount code (up to 16 chars).",+ "created_at": "Timestamp when the discount is created.",+ "currency_options": (+ "Per-currency options (flat deduction / percentage cap + minimum subtotal). Empty for "+ "discounts without any configured currency options."+ ),+ "customer_eligibility": "Who may redeem this discount code.",+ "expires_at": "Optional date/time after which discount is expired.",+ "metadata": "Arbitrary key-value metadata.",+ "name": "Name for the discount.",+ "per_customer_usage_limit": ("Maximum number of times a single customer may redeem this discount, if any."),+ "preserve_on_plan_change": ("Whether this discount should be preserved when a subscription changes plans."),+ "restricted_to": "List of product IDs to which this discount is restricted.",+ "starts_at": "Optional date/time before which the discount is not yet active.",+ "subscription_cycles": "Number of subscription billing cycles this discount is valid for.",+ "times_used": "How many times this discount has been used.",+ "type": "The type of discount (`percentage` or `flat`).",+ "usage_limit": "Usage limit for this discount, if any.",+ },+ },+ "addons": {+ "description": "Add-ons that can be attached to a subscription.",+ "docs_url": f"{_DOCS_ROOT}/addons/list-addons",+ "columns": {+ "id": "id of the Addon.",+ "business_id": "Unique identifier for the business to which the addon belongs.",+ "created_at": "Created time.",+ "currency": "Currency of the Addon.",+ "description": "Optional description of the Addon.",+ "image": "Image of the Addon.",+ "name": "Name of the Addon.",+ "price": "Amount of the addon.",+ "tax_category": "Tax category applied to this Addon.",+ "updated_at": "Updated time.",+ },+ },+ "brands": {+ "description": "Brands configured on the account, each with its own checkout branding and verification state.",+ "docs_url": f"{_DOCS_ROOT}/brands/list-brands",+ "columns": {+ "brand_id": "Unique identifier for the brand.",+ "business_id": "Business the brand belongs to.",+ "description": "Description shown for the brand.",+ "enabled": "Whether the brand is enabled.",+ "image": "URL of the brand logo.",+ "name": "Brand name.",+ "reason_for_hold": "In case the brand verification fails or is put on hold.",+ "statement_descriptor": "Text shown on the customer's card statement.",+ "support_email": "Support email address shown to customers.",+ "url": "The brand's website.",+ "verification_enabled": "Whether domain verification is enabled for the brand.",+ "verification_status": "Current verification status of the brand.",+ },+ },+ "meters": {+ "description": "Meters that aggregate usage events into billable quantities.",+ "docs_url": f"{_DOCS_ROOT}/meters/list-meters",+ "columns": {+ "id": "Unique identifier of the meter.",+ "aggregation": "How matching events are aggregated, for example count or sum.",+ "business_id": "Business the meter belongs to.",+ "description": "Description of the meter.",+ "event_name": "Name of the usage event the meter aggregates.",+ "filter": "Filter applied to events before aggregation.",+ "measurement_unit": "Unit the aggregated usage is measured in.",+ "name": "Display name of the meter.",+ "created_at": "Timestamp when the meter was created.",+ "updated_at": "Timestamp when the meter was last updated.",+ },+ },+ "entitlements": {+ "description": "Entitlements that grant customers access to something on purchase, such as digital files.",+ "docs_url": f"{_DOCS_ROOT}/entitlements/list-entitlements",+ "columns": {+ "id": "Unique identifier of the entitlement.",+ "business_id": "Identifier of the business that owns this entitlement.",+ "created_at": "Timestamp when the entitlement was created.",+ "description": "Optional description supplied at creation.",+ "integration_config": (+ "Integration-specific configuration. For `digital_files` entitlements this includes "+ "presigned download URLs for each attached file."+ ),+ "integration_type": "Platform integration this entitlement uses.",+ "is_active": (+ "Always `true` for entitlements returned by the public API; soft-deleted entitlements are not returned."+ ),+ "metadata": "Arbitrary key-value metadata supplied at creation or via PATCH.",+ "name": "Display name supplied at creation.",+ "updated_at": "Timestamp when the entitlement was last modified.",+ },+ },+ "credit_entitlements": {+ "description": "Credit entitlements: prepaid credit balances customers draw down, with rollover and overage rules.",+ "docs_url": f"{_DOCS_ROOT}/credit-entitlements/list-credit-entitlements",+ "columns": {+ "id": "Unique identifier of the credit entitlement.",+ "business_id": "Business the credit entitlement belongs to.",+ "created_at": "Timestamp when the credit entitlement was created.",+ "currency": "Currency credits are priced in.",+ "description": "Description of the credit entitlement.",+ "expires_after_days": "Number of days after which granted credits expire.",+ "max_rollover_count": "Maximum number of cycles unused credits can roll over for.",+ "name": "Display name of the credit entitlement.",+ "overage_behavior": "Controls how overage is handled at billing cycle end.",+ "overage_enabled": "Whether customers may consume more credits than granted.",+ "overage_limit": "Cap on consumable overage, when overage is enabled.",+ "precision": "Number of decimal places credits are tracked to.",+ "price_per_unit": "Price per credit unit.",+ "rollover_enabled": "Whether unused credits roll over to the next cycle.",+ "rollover_percentage": "Share of unused credits that rolls over.",+ "rollover_timeframe_count": "Number of rollover timeframe intervals.",+ "rollover_timeframe_interval": "Time interval rollover is measured over.",+ "unit": "Unit credits are measured in.",+ "updated_at": "Timestamp when the credit entitlement was last modified.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/dodopayments.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/dodopayments.pynew file mode 100644index 000000000000..e42648f0d320--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/dodopayments.py@@ -0,0 +1,212 @@+import dataclasses+from datetime import UTC, date, datetime+from typing import Any, Optional++from requests import Response++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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.dodopayments.settings import (+ DODOPAYMENTS_ENDPOINTS,+ MODE_HOSTS,+ PAGE_SIZE,+ REQUEST_TIMEOUT_SECONDS,+)+++class DodoPaymentsResumeConfig:+ page_number: int+++def base_url_for_mode(mode: str) -> str:+ """Resolve the API host for a mode, defaulting to live for an unrecognised value."""+ return MODE_HOSTS.get(mode, MODE_HOSTS["live"])+++def to_iso8601(value: Any) -> Optional[str]:+ """Render an incremental watermark as the UTC ISO-8601 string the date filters expect.++ The stored watermark comes back as a datetime for `DateTime` incremental fields, but a+ reset or a hand-edited config can leave a string or an epoch number, so all three are+ accepted. Anything unparseable yields `None`, which drops the filter and full-refreshes+ rather than sending a value the API would reject.+ """+ if value is None or isinstance(value, bool):+ return None+ if isinstance(value, datetime):+ parsed = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ elif isinstance(value, date):+ parsed = datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ elif isinstance(value, int | float):+ try:+ parsed = datetime.fromtimestamp(value, tz=UTC)+ except (OverflowError, OSError, ValueError):+ return None+ elif isinstance(value, str):+ try:+ candidate = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ parsed = candidate.replace(tzinfo=UTC) if candidate.tzinfo is None else candidate.astimezone(UTC)+ else:+ return None+ return parsed.isoformat().replace("+00:00", "Z")+++class DodoPaymentsPaginator(PageNumberPaginator):+ """Zero-based `page_number` pagination that stops on the first short page.++ Dodo Payments list responses are a bare `{"items": [...]}` with no total count, no next+ cursor and no Link header, so the only termination signal is a page holding fewer than+ `page_size` rows. Falling back to the base class's empty-page check would cost one extra+ request per table per sync against a 240 requests/minute budget.+ """++ def __init__(self, page_size: int = PAGE_SIZE, page: Optional[int] = None) -> None:+ super().__init__(base_page=0, page=page, page_param="page_number")+ self._page_size = page_size++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ if data is not None and len(data) < self._page_size:+ self._has_next_page = False+ return+ super().update_state(response, data)++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ return {"page_number": self.page} if self._has_next_page else None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ page_number = state.get("page_number")+ if page_number is not None:+ self.page = int(page_number)+ self._has_next_page = True+++def get_resource(+ endpoint: str, should_use_incremental_field: bool, incremental_start_value: Optional[str]+) -> EndpointResource:+ config = DODOPAYMENTS_ENDPOINTS[endpoint]++ params: dict[str, Any] = {}+ if config.paginated:+ params["page_size"] = PAGE_SIZE+ if should_use_incremental_field and config.start_param and incremental_start_value:+ params[config.start_param] = incremental_start_value++ return {+ "name": endpoint,+ "table_name": endpoint,+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}+ if should_use_incremental_field+ else "replace",+ "table_format": "delta",+ "primary_key": config.primary_keys,+ "endpoint": {+ "path": config.path,+ "params": params,+ "data_selector": "items",+ "paginator": DodoPaymentsPaginator() if config.paginated else "single_page",+ # Every list endpoint wraps its rows in `items`; a body without it is a response+ # shape change, which should fail loud rather than sync zero rows.+ "data_selector_required": True,+ "data_selector_empty_ok": True,+ },+ }+++def dodopayments_source(+ api_key: str,+ mode: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[DodoPaymentsResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = DODOPAYMENTS_ENDPOINTS[endpoint]+ incremental_start_value = to_iso8601(db_incremental_field_last_value) if should_use_incremental_field else None+ resource = get_resource(endpoint, should_use_incremental_field, incremental_start_value)++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": base_url_for_mode(mode),+ "auth": {"type": "bearer", "token": api_key},+ # capture=False: list responses carry customer PII, invoice URLs and redeemable+ # `license_keys.key` values that the name-based scrubbers would not recognise, so keep+ # raw bodies out of HTTP sample capture even where an operator enables it.+ "session": make_tracked_session(capture=False, redact_values=(api_key,)),+ # Every request is built from our own base URL, so pin it and refuse redirects rather+ # than letting a redirect replay the bearer token at another origin.+ "allowed_hosts": [],+ "allow_redirects": False,+ # Bound every request so a stalled connect or a hung read can't hold this worker forever.+ "request_timeout": REQUEST_TIMEOUT_SECONDS,+ },+ "resources": [resource],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ initial_paginator_state = {"page_number": resume.page_number}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Fires after a page has been yielded, so a crash re-yields that page (the merge dedupes+ # on the primary key) instead of skipping it.+ if state and state.get("page_number") is not None:+ resumable_source_manager.save_state(DodoPaymentsResumeConfig(page_number=int(state["page_number"])))++ resource_iter = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ # The date filter is already baked into the request params above, so the framework's own+ # incremental param injection is intentionally unused.+ db_incremental_field_last_value=None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ partition_kwargs: dict[str, Any] = {}+ if config.partition_key is not None:+ partition_kwargs = {+ "partition_count": 1,+ "partition_size": 1,+ "partition_mode": "datetime",+ "partition_format": "month",+ "partition_keys": [config.partition_key],+ }++ return SourceResponse(+ name=endpoint,+ items=lambda: resource_iter,+ primary_keys=config.primary_keys,+ # Dodo Payments documents no ordering guarantee and offers no sort parameter, so we+ # cannot claim rows arrive oldest-first. "desc" holds the watermark back until the sync+ # finishes, which is correct whichever order the API actually returns.+ sort_mode="desc",+ **partition_kwargs,+ )+++def validate_credentials(api_key: str, mode: str) -> tuple[bool, int | None]:+ """Probe the cheapest authenticated list endpoint and report `(is_valid, status_code)`."""+ return validate_via_probe(+ lambda: make_tracked_session(capture=False, allow_redirects=False, redact_values=(api_key,)),+ f"{base_url_for_mode(mode)}/customers?page_size=1",+ headers={"Authorization": f"Bearer {api_key}"},+ allow_redirects=False,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/settings.pynew file mode 100644index 000000000000..931fb1d107d1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/settings.py@@ -0,0 +1,137 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++# Dodo Payments serves test and live data from two entirely separate hosts, each with its own+# API key. A key issued for one mode is rejected by the other, so the mode is an explicit source+# field rather than something we can infer from the key.+MODE_HOSTS = {+ "live": "https://live.dodopayments.com",+ "test": "https://test.dodopayments.com",+}+DEFAULT_MODE = "live"++# Every list endpoint caps `page_size` at 100 (the default is 10).+PAGE_SIZE = 100++# `(connect, read)` seconds. Bounds every REST request so a stalled connect or a hung read cannot+# pin an import worker indefinitely; the read budget is generous because a slow page is still worth+# waiting for against the 240 requests/minute rate limit.+REQUEST_TIMEOUT_SECONDS: tuple[float, float] = (10.0, 60.0)++# Rows whose fields get restated after creation re-read a trailing 30 day window on every+# incremental run. Dodo only filters on `created_at` - there is no updated-since filter anywhere+# in the API - so a bare creation cursor would freeze `status`, `dispute_status` and+# `refund_status` at whatever they were when the row was first imported. Users can change the+# window per table in the schema settings.+RESTATED_LOOKBACK_SECONDS = 30 * 24 * 60 * 60+++@dataclass(frozen=True)+class DodoPaymentsEndpointConfig:+ path: str+ primary_keys: list[str]+ # Query param carrying the server-side "created on or after" filter, when the endpoint has+ # one. `None` means the endpoint offers no date filter at all and must be full-refreshed.+ start_param: str | None = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable creation timestamp used for datetime partitioning. `None` where the resource has no+ # creation timestamp at all (brands).+ partition_key: str | None = "created_at"+ # `/brands` is the one list endpoint that takes no query parameters, so it is a single page.+ paginated: bool = True+ # Fields on these resources are restated in place after creation, so incremental runs need+ # the trailing re-read window above.+ restated: bool = False+++DODOPAYMENTS_ENDPOINTS: dict[str, DodoPaymentsEndpointConfig] = {+ "payments": DodoPaymentsEndpointConfig(+ path="/payments",+ primary_keys=["payment_id"],+ start_param="created_at_gte",+ incremental_fields=[incremental_field("created_at")],+ restated=True,+ ),+ "subscriptions": DodoPaymentsEndpointConfig(+ path="/subscriptions",+ primary_keys=["subscription_id"],+ start_param="created_at_gte",+ incremental_fields=[incremental_field("created_at")],+ restated=True,+ ),+ "customers": DodoPaymentsEndpointConfig(+ path="/customers",+ primary_keys=["customer_id"],+ start_param="created_at_gte",+ incremental_fields=[incremental_field("created_at")],+ restated=True,+ ),+ "refunds": DodoPaymentsEndpointConfig(+ path="/refunds",+ primary_keys=["refund_id"],+ start_param="created_at_gte",+ incremental_fields=[incremental_field("created_at")],+ restated=True,+ ),+ "disputes": DodoPaymentsEndpointConfig(+ path="/disputes",+ primary_keys=["dispute_id"],+ start_param="created_at_gte",+ incremental_fields=[incremental_field("created_at")],+ restated=True,+ ),+ "payouts": DodoPaymentsEndpointConfig(+ path="/payouts",+ primary_keys=["payout_id"],+ start_param="created_at_gte",+ incremental_fields=[incremental_field("created_at")],+ restated=True,+ ),+ "license_keys": DodoPaymentsEndpointConfig(+ path="/license_keys",+ primary_keys=["id"],+ start_param="created_at_gte",+ incremental_fields=[incremental_field("created_at")],+ restated=True,+ ),+ "balance_ledger_entries": DodoPaymentsEndpointConfig(+ path="/balances/ledger",+ primary_keys=["id"],+ start_param="created_at_gte",+ incremental_fields=[incremental_field("created_at")],+ ),+ # Usage-billing events are immutable once ingested, and the filter param is `start`, not+ # `created_at_gte`.+ "events": DodoPaymentsEndpointConfig(+ path="/events",+ primary_keys=["event_id"],+ start_param="start",+ incremental_fields=[incremental_field("timestamp")],+ partition_key="timestamp",+ ),+ # Catalog resources: no date filter of any kind, so full refresh only.+ "products": DodoPaymentsEndpointConfig(path="/products", primary_keys=["product_id"]),+ "product_collections": DodoPaymentsEndpointConfig(path="/product-collections", primary_keys=["id"]),+ "discounts": DodoPaymentsEndpointConfig(path="/discounts", primary_keys=["discount_id"]),+ "addons": DodoPaymentsEndpointConfig(path="/addons", primary_keys=["id"]),+ "brands": DodoPaymentsEndpointConfig(+ path="/brands",+ primary_keys=["brand_id"],+ partition_key=None,+ paginated=False,+ ),+ "meters": DodoPaymentsEndpointConfig(path="/meters", primary_keys=["id"]),+ "license_key_instances": DodoPaymentsEndpointConfig(path="/license_key_instances", primary_keys=["id"]),+ "entitlements": DodoPaymentsEndpointConfig(path="/entitlements", primary_keys=["id"]),+ "credit_entitlements": DodoPaymentsEndpointConfig(path="/credit-entitlements", primary_keys=["id"]),+}++ENDPOINTS = tuple(DODOPAYMENTS_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in DODOPAYMENTS_ENDPOINTS.items() if config.incremental_fields+}++INCREMENTAL_ENDPOINTS = tuple(INCREMENTAL_FIELDS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/source.pyindex efe67a594c1d..7210a2a05d18 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/source.py@@ -1,33 +1,183 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+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 (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.dodopayments import dodopayments as api_client+from products.warehouse_sources.backend.temporal.data_imports.sources.dodopayments.dodopayments import (+ DodoPaymentsResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dodopayments.settings import (+ DEFAULT_MODE,+ DODOPAYMENTS_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ MODE_HOSTS,+ RESTATED_LOOKBACK_SECONDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.dodopayments import (DodoPaymentsSourceConfig,)from products.warehouse_sources.backend.types import ExternalDataSourceType+DODOPAYMENTS_API_KEYS_URL = "https://app.dodopayments.com/developer/api-keys"+@SourceRegistry.register-class DodoPaymentsSource(SimpleSource[DodoPaymentsSourceConfig]):+class DodoPaymentsSource(ResumableSource[DodoPaymentsSourceConfig, DodoPaymentsResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # Dodo Payments serves unversioned paths (`/payments`, `/subscriptions`) with no version+ # header, query param or dated release channel, so there is nothing to pin.+ api_docs_url = "https://docs.dodopayments.com/api-reference/introduction"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.DODOPAYMENTS+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": (+ "Dodo Payments rejected the API key. Check that the key is still active and that it "+ "matches the mode (test or live) selected on this source."+ ),+ "403 Client Error: Forbidden for url": (+ "Your Dodo Payments API key does not have permission for this resource. Grant it read "+ "access in the dashboard under Developer > API Keys and reconnect."+ ),+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.dodopayments.canonical_descriptions import ( # noqa: PLC0415 — lazy import of sibling metadata, per the source architecture contract+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: DodoPaymentsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ schemas = build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ for schema in schemas:+ endpoint = DODOPAYMENTS_ENDPOINTS[schema.name]+ schema.detected_primary_keys = list(endpoint.primary_keys)+ if endpoint.restated:+ schema.default_incremental_lookback_seconds = RESTATED_LOOKBACK_SECONDS+ return schemas++ def validate_credentials(+ self,+ config: DodoPaymentsSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ is_valid, status = api_client.validate_credentials(config.api_key, config.mode)+ if is_valid:+ return True, None+ if status == 401:+ return False, (+ f"Dodo Payments rejected the API key in {config.mode} mode. A test key only works "+ "against test mode, and a live key only against live mode."+ )+ if status == 403:+ return False, (+ "This Dodo Payments API key doesn't have permission to read. Grant it read access "+ "in the dashboard under Developer > API keys and reconnect."+ )+ if status == 429:+ return False, "Dodo Payments is rate limiting these requests. Wait a moment and try again."+ if status is not None and status >= 500:+ return False, "Dodo Payments returned a server error. Try again shortly."+ return False, "Could not reach Dodo Payments with these credentials"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DodoPaymentsResumeConfig]:+ return ResumableSourceManager[DodoPaymentsResumeConfig](inputs, DodoPaymentsResumeConfig)++ def source_for_pipeline(+ self,+ config: DodoPaymentsSourceConfig,+ resumable_source_manager: ResumableSourceManager[DodoPaymentsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return api_client.dodopayments_source(+ api_key=config.api_key,+ mode=config.mode,+ 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,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.DODO_PAYMENTS,category=DataWarehouseSourceCategory.PAYMENTS___BILLING,label="Dodo Payments",+ caption=(+ "Sync payments, subscriptions, customers, refunds, disputes, payouts and your product "+ "catalog from Dodo Payments into PostHog. Create an API key in your Dodo Payments "+ f"dashboard under [Developer > API keys]({DODOPAYMENTS_API_KEYS_URL}). Read access is enough."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/dodo-payments",iconPath="/static/services/dodopayments.png",keywords=["payments", "billing", "merchant of record"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ caption=(+ f"Create a key under [Developer > API keys]({DODOPAYMENTS_API_KEYS_URL}). "+ "A read-only key is enough to sync."+ ),+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="mode",+ label="Mode",+ required=True,+ defaultValue=DEFAULT_MODE,+ caption=(+ "Dodo Payments keeps test and live data on separate hosts with separate keys. "+ "Pick the mode your key was issued for."+ ),+ options=[SourceFieldSelectConfigOption(label=mode.title(), value=mode) for mode in MODE_HOSTS],+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/tests/test_dodopayments.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/tests/test_dodopayments.pynew file mode 100644index 000000000000..a00eb55e1d2a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/tests/test_dodopayments.py@@ -0,0 +1,343 @@+import json+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest import mock++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.dodopayments.dodopayments import (+ DodoPaymentsPaginator,+ DodoPaymentsResumeConfig,+ base_url_for_mode,+ dodopayments_source,+ to_iso8601,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dodopayments.settings import (+ DODOPAYMENTS_ENDPOINTS,+ PAGE_SIZE,+ REQUEST_TIMEOUT_SECONDS,+)++SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.dodopayments.dodopayments.make_tracked_session"+)+REST_RESOURCE_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.dodopayments.dodopayments.rest_api_resource"+)+++def _response(items: list[dict[str, Any]]) -> Response:+ response = Response()+ response.status_code = 200+ response._content = json.dumps({"items": items}).encode()+ return response+++def _page(size: int, start: int = 0) -> Response:+ return _response([{"payment_id": f"pay_{start + i}", "created_at": "2024-05-01T00:00:00Z"} for i in range(size)])+++def _make_manager(resume_state: DodoPaymentsResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append({"url": request.url, "params": dict(request.params or {})})+ prepared = mock.MagicMock()+ prepared.url = request.url+ return prepared++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _source(endpoint: str, manager: mock.MagicMock | None = None, mode: str = "live", **kwargs: Any):+ return dodopayments_source(+ "test-api-key",+ mode,+ endpoint,+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager if manager is not None else _make_manager(),+ **kwargs,+ )+++def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++class TestToIso8601:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (None, None),+ (True, None),+ # A datetime watermark must not be str()'d: "2024-05-01 10:00:00+00:00" is not+ # ISO-8601 and the date filters reject it.+ (datetime(2024, 5, 1, 10, tzinfo=UTC), "2024-05-01T10:00:00Z"),+ (datetime(2024, 5, 1, 10), "2024-05-01T10:00:00Z"),+ (datetime(2024, 5, 1, 12, tzinfo=UTC).astimezone(UTC), "2024-05-01T12:00:00Z"),+ (date(2024, 5, 1), "2024-05-01T00:00:00Z"),+ ("2024-05-01T10:00:00Z", "2024-05-01T10:00:00Z"),+ ("2024-05-01T12:00:00+02:00", "2024-05-01T10:00:00Z"),+ (1714557600, "2024-05-01T10:00:00Z"),+ ("not-a-date", None),+ (object(), None),+ ],+ )+ def test_values(self, value, expected):+ assert to_iso8601(value) == expected+++class TestBaseUrlForMode:+ @pytest.mark.parametrize(+ "mode, expected",+ [+ ("live", "https://live.dodopayments.com"),+ ("test", "https://test.dodopayments.com"),+ ("nonsense", "https://live.dodopayments.com"),+ ],+ )+ def test_mode_selects_host(self, mode, expected):+ assert base_url_for_mode(mode) == expected+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected_valid",+ [(200, True), (401, False), (403, False), (429, False), (500, False)],+ )+ @mock.patch(SESSION_PATCH)+ def test_status_mapping(self, mock_session, status_code, expected_valid):+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)++ is_valid, status = validate_credentials("key", "live")++ assert is_valid is expected_valid+ assert status == status_code++ @pytest.mark.parametrize(+ "mode, expected_url",+ [+ ("live", "https://live.dodopayments.com/customers?page_size=1"),+ ("test", "https://test.dodopayments.com/customers?page_size=1"),+ ],+ )+ @mock.patch(SESSION_PATCH)+ def test_probe_targets_the_host_for_the_mode(self, mock_session, mode, expected_url):+ # A live key probed against the test host (or vice versa) always 401s, so the mode has to+ # reach the probe URL.+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)++ validate_credentials("key", mode)++ call = mock_session.return_value.get.call_args+ assert call.args[0] == expected_url+ assert call.kwargs["headers"]["Authorization"] == "Bearer key"++ @mock.patch(SESSION_PATCH)+ def test_transport_failure_is_not_valid(self, mock_session):+ mock_session.return_value.get.side_effect = Exception("boom")++ assert validate_credentials("key", "live") == (False, None)+++class TestPagination:+ @mock.patch(SESSION_PATCH)+ def test_walks_zero_based_pages_and_stops_on_short_page(self, MockSession):+ requests_seen = _wire(MockSession.return_value, [_page(PAGE_SIZE), _page(3, start=PAGE_SIZE)])+ manager = _make_manager()++ rows = _rows(_source("payments", manager))++ assert len(rows) == PAGE_SIZE + 3+ # Page numbers are 0-based; starting at 1 would silently skip the newest page.+ assert [snapshot["params"]["page_number"] for snapshot in requests_seen] == [0, 1]+ assert requests_seen[0]["params"]["page_size"] == PAGE_SIZE+ # A short page terminates without paying for the extra empty-page request.+ assert len(requests_seen) == 2+ assert manager.save_state.call_args_list == [mock.call(DodoPaymentsResumeConfig(page_number=1))]++ @mock.patch(SESSION_PATCH)+ def test_full_page_then_empty_page_terminates(self, MockSession):+ requests_seen = _wire(MockSession.return_value, [_page(PAGE_SIZE), _page(0)])++ rows = _rows(_source("payments"))++ assert len(rows) == PAGE_SIZE+ assert len(requests_seen) == 2++ @mock.patch(SESSION_PATCH)+ def test_resumes_from_saved_page(self, MockSession):+ requests_seen = _wire(MockSession.return_value, [_page(2, start=400)])++ rows = _rows(_source("payments", _make_manager(DodoPaymentsResumeConfig(page_number=4))))++ assert [row["payment_id"] for row in rows] == ["pay_400", "pay_401"]+ assert requests_seen[0]["params"]["page_number"] == 4++ @mock.patch(SESSION_PATCH)+ def test_unpaginated_endpoint_makes_one_request_without_page_params(self, MockSession):+ # `/brands` accepts no query parameters at all.+ requests_seen = _wire(MockSession.return_value, [_response([{"brand_id": "brand_1"}])])++ rows = _rows(_source("brands"))++ assert [row["brand_id"] for row in rows] == ["brand_1"]+ assert len(requests_seen) == 1+ assert requests_seen[0]["params"] == {}++ def test_paginator_resume_state_is_none_once_exhausted(self):+ paginator = DodoPaymentsPaginator()+ paginator.update_state(_response([]), [])++ assert paginator.has_next_page is False+ assert paginator.get_resume_state() is None+++class TestRequestParams:+ @pytest.mark.parametrize(+ "endpoint, expected_param",+ [+ ("payments", "created_at_gte"),+ ("subscriptions", "created_at_gte"),+ ("balance_ledger_entries", "created_at_gte"),+ # Usage events filter on `start`, not `created_at_gte`.+ ("events", "start"),+ ],+ )+ @mock.patch(SESSION_PATCH)+ def test_incremental_sync_sends_the_endpoints_date_filter(self, MockSession, endpoint, expected_param):+ requests_seen = _wire(MockSession.return_value, [_page(1)])++ _rows(+ _source(+ endpoint,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 5, 1, 10, tzinfo=UTC),+ )+ )++ assert requests_seen[0]["params"][expected_param] == "2024-05-01T10:00:00Z"++ @mock.patch(SESSION_PATCH)+ def test_full_refresh_sends_no_date_filter(self, MockSession):+ requests_seen = _wire(MockSession.return_value, [_page(1)])++ _rows(_source("payments", db_incremental_field_last_value=datetime(2024, 5, 1, tzinfo=UTC)))++ assert "created_at_gte" not in requests_seen[0]["params"]++ @mock.patch(SESSION_PATCH)+ def test_unparseable_watermark_drops_the_filter(self, MockSession):+ # Sending a value the API rejects would fail the whole sync; a full walk is the safe fallback.+ requests_seen = _wire(MockSession.return_value, [_page(1)])++ _rows(_source("payments", should_use_incremental_field=True, db_incremental_field_last_value="garbage"))++ assert "created_at_gte" not in requests_seen[0]["params"]++ @mock.patch(SESSION_PATCH)+ def test_catalog_endpoint_never_gets_a_date_filter(self, MockSession):+ # `/products` exposes no date filter; sending one would be rejected.+ requests_seen = _wire(MockSession.return_value, [_response([{"product_id": "prod_1"}])])++ _rows(+ _source(+ "products",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 5, 1, tzinfo=UTC),+ )+ )++ assert set(requests_seen[0]["params"]) == {"page_size", "page_number"}+++class TestSourceResponseMetadata:+ @pytest.mark.parametrize("endpoint", list(DODOPAYMENTS_ENDPOINTS))+ @mock.patch(SESSION_PATCH)+ def test_metadata_matches_the_endpoint_catalog(self, MockSession, endpoint):+ config = DODOPAYMENTS_ENDPOINTS[endpoint]++ response = _source(endpoint)++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ # Dodo documents no ordering guarantee, so the watermark must only finalize at the end+ # of a successful sync.+ assert response.sort_mode == "desc"+ if config.partition_key is None:+ assert response.partition_mode is None+ assert response.partition_keys is None+ else:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]++ @pytest.mark.parametrize(+ "endpoint, should_use_incremental_field, expected_disposition",+ [+ ("payments", True, {"disposition": "merge", "strategy": "upsert"}),+ ("payments", False, "replace"),+ ("products", False, "replace"),+ ],+ )+ @mock.patch(REST_RESOURCE_PATCH)+ def test_write_disposition_follows_incremental_mode(+ self, mock_rest_api_resource, endpoint, should_use_incremental_field, expected_disposition+ ):+ _source(endpoint, should_use_incremental_field=should_use_incremental_field)++ resource = mock_rest_api_resource.call_args.args[0]["resources"][0]+ assert resource["write_disposition"] == expected_disposition+ assert resource["primary_key"] == DODOPAYMENTS_ENDPOINTS[endpoint].primary_keys++ @mock.patch(REST_RESOURCE_PATCH)+ def test_base_url_follows_the_mode(self, mock_rest_api_resource):+ _source("payments", mode="test")++ assert mock_rest_api_resource.call_args.args[0]["client"]["base_url"] == "https://test.dodopayments.com"++ @mock.patch(REST_RESOURCE_PATCH)+ def test_client_bounds_every_request_with_a_timeout(self, mock_rest_api_resource):+ # Without this a stalled connect or hung read would pin an import worker indefinitely.+ _source("payments")++ assert mock_rest_api_resource.call_args.args[0]["client"]["request_timeout"] == REQUEST_TIMEOUT_SECONDS++ @mock.patch(REST_RESOURCE_PATCH)+ def test_framework_incremental_injection_is_not_used(self, mock_rest_api_resource):+ # The date filter is baked into the request params, so letting the framework inject its own+ # incremental param too would send a second, differently named filter.+ _source(+ "payments",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 5, 1, tzinfo=UTC),+ )++ assert mock_rest_api_resource.call_args.kwargs["db_incremental_field_last_value"] is None+++class TestEndpointCatalog:+ def test_every_incremental_endpoint_declares_a_server_side_filter(self):+ # Without a server-side filter an "incremental" sync would still fetch every page.+ for name, config in DODOPAYMENTS_ENDPOINTS.items():+ assert bool(config.incremental_fields) == (config.start_param is not None), name++ def test_incremental_cursor_matches_the_partition_key(self):+ # The cursor and the partition key must both be creation timestamps that never change.+ for name, config in DODOPAYMENTS_ENDPOINTS.items():+ if not config.incremental_fields:+ continue+ assert [f["field"] for f in config.incremental_fields] == [config.partition_key], namediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/tests/test_dodopayments_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/tests/test_dodopayments_source.pynew file mode 100644index 000000000000..63c816d5e435--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/tests/test_dodopayments_source.py@@ -0,0 +1,184 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.dodopayments.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dodopayments.dodopayments import (+ DodoPaymentsResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dodopayments.settings import (+ DODOPAYMENTS_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_ENDPOINTS,+ INCREMENTAL_FIELDS,+ MODE_HOSTS,+ RESTATED_LOOKBACK_SECONDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dodopayments.source import DodoPaymentsSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.dodopayments import (+ DodoPaymentsSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++API_CLIENT_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.dodopayments.source.api_client"+++class TestDodoPaymentsSource:+ def setup_method(self):+ self.source = DodoPaymentsSource()+ self.team_id = 123+ self.config = DodoPaymentsSourceConfig(api_key="test-api-key", mode="live")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.DODOPAYMENTS++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "DodoPayments"+ assert config.label == "Dodo Payments"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # unreleasedSource hides the source from every user, so a finished source must not set it.+ assert not config.unreleasedSource+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/dodo-payments"++ def test_api_key_field_is_a_secret_password(self):+ field = next(+ f+ for f in self.source.get_source_config.fields+ if isinstance(f, SourceFieldInputConfig) and f.name == "api_key"+ )++ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_mode_field_offers_every_host(self):+ # Test and live data live on separate hosts with separate keys, so the mode cannot be+ # inferred and must be selectable.+ field = next(+ f+ for f in self.source.get_source_config.fields+ if isinstance(f, SourceFieldSelectConfig) and f.name == "mode"+ )++ assert {option.value for option in field.options} == set(MODE_HOSTS)+ assert field.defaultValue in MODE_HOSTS++ @pytest.mark.parametrize(+ "observed_error, matches",+ [+ ("401 Client Error: Unauthorized for url: https://live.dodopayments.com/payments", True),+ ("403 Client Error: Forbidden for url: https://test.dodopayments.com/payouts", True),+ ("500 Server Error for url: https://live.dodopayments.com/payments", False),+ ("429 Client Error: Too Many Requests for url: https://live.dodopayments.com/payments", False),+ ],+ )+ def test_non_retryable_errors_cover_auth_failures_only(self, observed_error, matches):+ assert any(key in observed_error for key in self.source.get_non_retryable_errors()) is matches++ def test_get_schemas_covers_the_endpoint_catalog(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ incremental = {schema.name for schema in schemas if schema.supports_incremental}+ assert incremental == set(INCREMENTAL_ENDPOINTS)+ for schema in schemas:+ assert schema.incremental_fields == INCREMENTAL_FIELDS.get(schema.name, [])++ def test_get_schemas_declares_per_endpoint_primary_keys(self):+ # A shared `id` default would be wrong for payments/subscriptions/refunds and would seed+ # duplicate rows every merge.+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ for name, endpoint in DODOPAYMENTS_ENDPOINTS.items():+ assert schemas[name].detected_primary_keys == endpoint.primary_keys++ def test_restated_endpoints_get_a_default_lookback(self):+ # Dodo only filters on created_at, so a bare cursor would freeze status columns at their+ # first-imported values on tables whose rows are restated in place.+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ with_lookback = {+ name for name, schema in schemas.items() if schema.default_incremental_lookback_seconds is not None+ }+ assert with_lookback == {name for name, e in DODOPAYMENTS_ENDPOINTS.items() if e.restated}+ assert schemas["payments"].default_incremental_lookback_seconds == RESTATED_LOOKBACK_SECONDS++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["payments"])++ assert [schema.name for schema in schemas] == ["payments"]++ def test_canonical_descriptions_are_keyed_by_schema_name(self):+ # A key that doesn't match a schema name is silently ignored, so the curated docs would+ # never reach the table.+ assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)+ assert self.source.get_canonical_descriptions() is CANONICAL_DESCRIPTIONS++ @pytest.mark.parametrize(+ "probe_result, expected_valid, expected_message_fragment",+ [+ ((True, 200), True, None),+ ((False, 401), False, "rejected the API key"),+ ((False, 403), False, "permission to read"),+ ((False, 429), False, "rate limiting"),+ ((False, 500), False, "server error"),+ ((False, None), False, "Could not reach"),+ ],+ )+ @mock.patch(f"{API_CLIENT_PATCH}.validate_credentials")+ def test_validate_credentials_maps_probe_results(+ self, mock_validate, probe_result, expected_valid, expected_message_fragment+ ):+ mock_validate.return_value = probe_result++ is_valid, message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ if expected_message_fragment is None:+ assert message is None+ else:+ assert message is not None and expected_message_fragment in message+ mock_validate.assert_called_once_with("test-api-key", "live")++ def test_get_resumable_source_manager_binds_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is DodoPaymentsResumeConfig++ @mock.patch(f"{API_CLIENT_PATCH}.dodopayments_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "payments"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-05-01T00:00:00Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "test-api-key"+ assert kwargs["mode"] == "live"+ assert kwargs["endpoint"] == "payments"+ assert kwargs["team_id"] is inputs.team_id+ assert kwargs["job_id"] is inputs.job_id+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-05-01T00:00:00Z"++ @mock.patch(f"{API_CLIENT_PATCH}.dodopayments_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "products"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-05-01T00:00:00Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dodopayments.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dodopayments.pyindex 4882d70942e1..6a9a9fe2d62c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dodopayments.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dodopayments.py@@ -1,9 +1,12 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config@config.configclass DodoPaymentsSourceConfig(config.Config):- pass+ api_key: str+ mode: Literal["live", "test"] = config.value(default="live")