: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 maxio import source (#69631)
Tom Owers91efdb46ff01
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 64e9bb9a9dba..9ce609abbd13 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -246,6 +246,7 @@ the row lists both.| mailtrap | HTTP | requests | ✅ || marketstack | HTTP | requests | ✅ || matomo | HTTP | requests | ✅ |+| maxio | HTTP | requests + `rest_source.RESTClient` | ✅ || mention | HTTP | requests | ✅ || meta_ads | HTTP | requests | ✅ || metabase | HTTP | requests | ✅ |@@ -636,7 +637,6 @@ doesn't conflict with concurrent PRs.- mailtrap- mantle- marketo-- maxio- mem0- mendeley- mercado_adsdiff --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 3a3a0478b6ef..a7dd6f459b87 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@@ -2237,7 +2237,9 @@ class MatomoSourceConfig(config.Config):@config.configclass MaxioSourceConfig(config.Config):- pass+ subdomain: str+ api_key: str+ region: Literal["us", "eu"] = config.value(default="us")@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/maxio/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/maxio/canonical_descriptions.pynew file mode 100644index 000000000000..957c79efef5e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/maxio/canonical_descriptions.py@@ -0,0 +1,237 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "customers": {+ "description": "A person or organization that is billed for subscriptions on your Maxio site.",+ "docs_url": "https://github.com/maxio-com/ab-python-sdk/blob/main/doc/controllers/customers.md",+ "columns": {+ "id": "The unique identifier for the customer, assigned by Maxio.",+ "first_name": "The first name of the customer.",+ "last_name": "The last name of the customer.",+ "email": "The email address of the customer.",+ "cc_emails": "Comma-separated email addresses that are cc'd on invoice and billing communications.",+ "organization": "The organization (company) name of the customer.",+ "reference": "The unique reference identifier for the customer in your application.",+ "created_at": "The timestamp when the customer was created.",+ "updated_at": "The timestamp of the last update to the customer record.",+ "address": "The customer's shipping street address.",+ "city": "The customer's shipping address city.",+ "state": "The customer's shipping address state or province code.",+ "zip": "The customer's shipping address zip or postal code.",+ "country": "The customer's shipping address country code (ISO 3166-1 alpha-2).",+ "phone": "The phone number of the customer.",+ "verified": "Whether the customer's bank account has been verified (ACH payments).",+ "tax_exempt": "Whether the customer is exempt from taxes.",+ "vat_number": "The VAT registration number of the customer.",+ "parent_id": "The id of the parent customer in a customer hierarchy, if any.",+ "locale": "The locale used for the customer's billing communications.",+ "default_subscription_group_uid": "The uid of the customer's default subscription group, if any.",+ },+ },+ "subscriptions": {+ "description": "A single product subscription for a customer, including its state, product, pricing, and current billing period.",+ "docs_url": "https://github.com/maxio-com/ab-python-sdk/blob/main/doc/controllers/subscriptions.md",+ "columns": {+ "id": "The unique identifier for the subscription, assigned by Maxio.",+ "state": "The current state of the subscription (e.g. active, canceled, past_due, trialing).",+ "balance_in_cents": "The current outstanding subscription balance in cents.",+ "total_revenue_in_cents": "The total revenue collected for the subscription in cents.",+ "product_price_in_cents": "The recurring price of the subscribed product in cents.",+ "created_at": "The timestamp when the subscription was created.",+ "updated_at": "The timestamp of the last update to the subscription.",+ "activated_at": "The timestamp when the subscription first became active.",+ "canceled_at": "The timestamp when the subscription was canceled, if any.",+ "expires_at": "The timestamp when the subscription expires, if any.",+ "current_period_started_at": "The start of the current billing period.",+ "current_period_ends_at": "The end of the current billing period, when the next renewal is assessed.",+ "next_assessment_at": "The timestamp of the next billing assessment.",+ "trial_started_at": "The timestamp when the trial started, if any.",+ "trial_ended_at": "The timestamp when the trial ended, if any.",+ "cancel_at_end_of_period": "Whether the subscription is set to cancel at the end of the current period.",+ "cancellation_method": "How the subscription was canceled (e.g. merchant_ui, api).",+ "payment_collection_method": "How payment is collected (automatic or remittance/invoice).",+ "customer": "The customer that owns the subscription (nested object).",+ "product": "The product the subscription is for (nested object).",+ "credit_card": "The credit card payment profile on the subscription (nested object).",+ "coupon_code": "The coupon code currently applied to the subscription, if any.",+ "currency": "The ISO 4217 currency code of the subscription.",+ "reference": "The unique reference identifier for the subscription in your application.",+ },+ },+ "invoices": {+ "description": "An invoice issued to a customer, with totals, status, and optional line item, discount, tax, credit, payment, and refund breakdowns.",+ "docs_url": "https://github.com/maxio-com/ab-python-sdk/blob/main/doc/controllers/invoices.md",+ "columns": {+ "uid": "Unique identifier for the invoice, prefixed with 'inv_'.",+ "id": "The numeric id of the invoice.",+ "site_id": "The id of the Maxio site the invoice belongs to.",+ "customer_id": "The id of the customer the invoice was issued to.",+ "subscription_id": "The id of the subscription that generated the invoice.",+ "number": "The human-consumable invoice number, unique within the site.",+ "sequence_number": "A monotonically increasing number assigned as invoices are created.",+ "issue_date": "The date the invoice was issued to the customer (YYYY-MM-DD).",+ "due_date": "The date payment of the invoice is due (YYYY-MM-DD).",+ "paid_date": "The date the invoice became fully paid, if it has been.",+ "status": "The current status of the invoice (draft, open, paid, pending, voided).",+ "collection_method": "How payment is collected for the invoice (automatic or remittance).",+ "currency": "The ISO 4217 currency code of the invoice amounts.",+ "subtotal_amount": "The sum of all line items before discounts or taxes.",+ "discount_amount": "The total discount applied to the invoice.",+ "tax_amount": "The total tax on the invoice.",+ "total_amount": "The invoice total (subtotal - discounts + taxes).",+ "paid_amount": "The amount paid on the invoice so far.",+ "due_amount": "The amount still due on the invoice.",+ "line_items": "The line items on the invoice (nested array).",+ "discounts": "The discounts applied to the invoice (nested array).",+ "taxes": "The taxes applied to the invoice (nested array).",+ "credits": "The credit notes applied to the invoice (nested array).",+ "payments": "The payments recorded against the invoice (nested array).",+ "refunds": "The refunds recorded against the invoice (nested array).",+ "created_at": "The timestamp when the invoice was created.",+ "updated_at": "The timestamp of the last update to the invoice.",+ },+ },+ "products": {+ "description": "A product that customers can subscribe to, defining recurring price and billing interval.",+ "docs_url": "https://github.com/maxio-com/ab-python-sdk/blob/main/doc/controllers/products.md",+ "columns": {+ "id": "The unique identifier for the product, assigned by Maxio.",+ "name": "The product name.",+ "handle": "The API handle of the product, unique within the site.",+ "description": "The description of the product.",+ "price_in_cents": "The recurring product price in cents.",+ "interval": "The numeric billing interval, paired with interval_unit.",+ "interval_unit": "The billing interval unit (month or day).",+ "trial_price_in_cents": "The price of the trial period in cents, if any.",+ "trial_interval": "The numeric trial interval, paired with trial_interval_unit.",+ "trial_interval_unit": "The trial interval unit (month or day).",+ "product_family": "The product family the product belongs to (nested object).",+ "archived_at": "The timestamp when the product was archived, if it has been.",+ "created_at": "The timestamp when the product was created.",+ "updated_at": "The timestamp of the last update to the product.",+ "require_credit_card": "Whether a credit card is required at signup.",+ "taxable": "Whether the product is taxable.",+ "default_product_price_point_id": "The id of the product's default price point.",+ },+ },+ "product_families": {+ "description": "A grouping of products, components, and coupons that belong to a single offering.",+ "docs_url": "https://github.com/maxio-com/ab-python-sdk/blob/main/doc/controllers/product-families.md",+ "columns": {+ "id": "The unique identifier for the product family, assigned by Maxio.",+ "name": "The product family name.",+ "handle": "The API handle of the product family, unique within the site.",+ "description": "The description of the product family.",+ "accounting_code": "The accounting code of the product family.",+ "created_at": "The timestamp when the product family was created.",+ "updated_at": "The timestamp of the last update to the product family.",+ "archived_at": "The timestamp when the product family was archived, if it has been.",+ },+ },+ "coupons": {+ "description": "A discount that can be applied to subscriptions, either a flat amount or a percentage.",+ "docs_url": "https://github.com/maxio-com/ab-python-sdk/blob/main/doc/controllers/coupons.md",+ "columns": {+ "id": "The unique identifier for the coupon, assigned by Maxio.",+ "name": "The coupon name.",+ "code": "The coupon code customers use to redeem the coupon.",+ "description": "The description of the coupon.",+ "amount_in_cents": "The flat discount amount in cents (for amount coupons).",+ "percentage": "The discount percentage (for percentage coupons).",+ "recurring": "Whether the coupon applies to renewals after the first period.",+ "duration_period_count": "The number of billing periods a recurring coupon lasts.",+ "end_date": "The date and time the coupon expires, if any.",+ "product_family_id": "The id of the product family the coupon belongs to.",+ "stackable": "Whether the coupon can be combined with other coupons.",+ "compounding_strategy": "How stacked percentage coupons combine (compound or full-price).",+ "created_at": "The timestamp when the coupon was created.",+ "updated_at": "The timestamp of the last update to the coupon.",+ "archived_at": "The timestamp when the coupon was archived, if it has been.",+ },+ },+ "components": {+ "description": "A metered, quantity-based, or on/off charge attached to a product family, billed alongside the base subscription.",+ "docs_url": "https://github.com/maxio-com/ab-python-sdk/blob/main/doc/controllers/components.md",+ "columns": {+ "id": "The unique identifier for the component, assigned by Maxio.",+ "name": "The component name.",+ "handle": "The API handle of the component, unique within the site.",+ "kind": "The kind of component (metered_component, quantity_based_component, on_off_component, prepaid_usage_component, event_based_component).",+ "unit_name": "The name of the unit the component's usage is measured in.",+ "unit_price": "The price per unit for per-unit pricing schemes.",+ "pricing_scheme": "The pricing scheme of the component (per_unit, volume, tiered, stairstep).",+ "product_family_id": "The id of the product family the component belongs to.",+ "price_per_unit_in_cents": "The per-unit price in cents, when using per-unit pricing.",+ "recurring": "Whether the component charge recurs on renewal.",+ "taxable": "Whether the component is taxable.",+ "created_at": "The timestamp when the component was created.",+ "updated_at": "The timestamp of the last update to the component.",+ "archived_at": "The timestamp when the component was archived, if it has been.",+ "default_price_point_id": "The id of the component's default price point.",+ },+ },+ "payment_profiles": {+ "description": "A stored payment method (credit card, bank account, PayPal, or Apple Pay) belonging to a customer.",+ "docs_url": "https://github.com/maxio-com/ab-python-sdk/blob/main/doc/controllers/payment-profiles.md",+ "columns": {+ "id": "The unique identifier for the payment profile, assigned by Maxio.",+ "customer_id": "The id of the customer the payment profile belongs to.",+ "payment_type": "The type of payment method (credit_card, bank_account, paypal_account, apple_pay).",+ "masked_card_number": "The masked credit card number, showing only the last four digits.",+ "card_type": "The credit card brand (e.g. visa, master, amex).",+ "expiration_month": "The credit card expiration month.",+ "expiration_year": "The credit card expiration year.",+ "first_name": "The first name on the payment method.",+ "last_name": "The last name on the payment method.",+ "billing_address": "The billing street address of the payment method.",+ "billing_city": "The billing address city.",+ "billing_state": "The billing address state or province code.",+ "billing_zip": "The billing address zip or postal code.",+ "billing_country": "The billing address country code.",+ "current_vault": "The payment gateway vault the payment method is stored in.",+ "vault_token": "The token identifying the payment method in the gateway vault.",+ "default": "Whether this is the customer's default payment profile.",+ },+ },+ "events": {+ "description": "Site activity events recording changes around the site, such as signups, renewals, payment successes and failures.",+ "docs_url": "https://github.com/maxio-com/ab-python-sdk/blob/main/doc/controllers/events.md",+ "columns": {+ "id": "The unique, monotonically increasing identifier of the event.",+ "key": "The event type key (e.g. signup_success, renewal_success, payment_failure).",+ "message": "A human-readable description of the event.",+ "subscription_id": "The id of the subscription the event relates to, if any.",+ "customer_id": "The id of the customer the event relates to, if any.",+ "created_at": "The timestamp when the event occurred.",+ "event_specific_data": "Additional structured data specific to the event type (nested object).",+ },+ },+ "credit_notes": {+ "description": "A credit issued to a customer that reduces the amount owed; the inverse of an invoice.",+ "docs_url": "https://github.com/maxio-com/ab-python-sdk/blob/main/doc/controllers/invoices.md",+ "columns": {+ "uid": "Unique identifier for the credit note, prefixed with 'cn_'.",+ "site_id": "The id of the Maxio site the credit note belongs to.",+ "customer_id": "The id of the customer the credit note belongs to.",+ "subscription_id": "The id of the subscription that generated the credit note.",+ "number": "The human-consumable credit note number, unique within the site.",+ "sequence_number": "A monotonically increasing number assigned as credit notes are created.",+ "issue_date": "The date the credit note was issued and made available for application (YYYY-MM-DD).",+ "applied_date": "The date the credit note became fully applied to invoices.",+ "status": "The current status of the credit note.",+ "currency": "The ISO 4217 currency code of the credit note amounts.",+ "memo": "The memo printed on the credit note describing the reason for the credit.",+ "subtotal_amount": "The sum of all line items before discounts or taxes.",+ "discount_amount": "The total discount credited back to the customer.",+ "tax_amount": "The total tax credited back to the customer.",+ "total_amount": "The credit note total (subtotal - discounts + taxes).",+ "applied_amount": "The amount already applied to invoices.",+ "remaining_amount": "The amount remaining to be applied to invoices.",+ "line_items": "The line items on the credit note (nested array).",+ "applications": "The applications of the credit note to invoices (nested array).",+ "refunds": "The refunds associated with the credit note (nested array).",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/maxio/maxio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/maxio/maxio.pynew file mode 100644index 000000000000..7de98565e1ed--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/maxio/maxio.py@@ -0,0 +1,221 @@+"""Maxio (Advanced Billing / Chargify) API transport: auth, pagination, resource assembly."""++import re+import dataclasses+from datetime import UTC, datetime+from typing import Any, Optional++from requests import Request, 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 BasePaginator+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.maxio.settings import (+ ENDPOINTS,+ MAXIO_BASE_URLS,+ PAGE_SIZE,+)+++class MaxioResumeConfig:+ endpoint: str+ next_page: int+++def normalize_subdomain(subdomain: str) -> str:+ """Reduce whatever the user entered to the bare Maxio site subdomain.++ Users frequently paste the full host ("acme.chargify.com") or a URL+ ("https://acme.chargify.com/") into the subdomain field. Without normalizing, the+ base URL would end up with a doubled host that can never resolve.+ """+ subdomain = subdomain.strip()+ if "://" in subdomain:+ subdomain = subdomain.split("://", 1)[1]+ subdomain = subdomain.split("/", 1)[0]+ return re.sub(r"\.(chargify\.com|ebilling\.maxio\.com)$", "", subdomain, flags=re.IGNORECASE)+++def get_base_url(subdomain: str, region: str) -> str:+ template = MAXIO_BASE_URLS.get(region, MAXIO_BASE_URLS["us"])+ return template.format(subdomain=normalize_subdomain(subdomain))+++def format_start_datetime(value: Any) -> str:+ """Format an incremental watermark for the `start_datetime` query param.++ The API documents the format as `YYYY-MM-DD HH:MM:SS`, interpreted in the site's+ timezone. We format in UTC; the schema-level lookback window covers the resulting+ skew (see settings.TIMEZONE_SKEW_LOOKBACK_SECONDS).+ """+ if isinstance(value, datetime):+ dt = value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)+ return dt.strftime("%Y-%m-%d %H:%M:%S")+ return str(value)+++def to_since_id(value: Any) -> int:+ return int(value)+++class MaxioPaginator(BasePaginator):+ """Page-number pagination (`page`/`per_page`, page starts at 1).++ The API signals the last page implicitly: a page with fewer rows than `per_page`+ (or no rows) is the final one. Supports seeding from resumable state so a restarted+ job continues from the last checkpointed page.+ """++ def __init__(self, page_size: int = PAGE_SIZE) -> None:+ super().__init__()+ self.page = 1+ self.page_size = page_size++ def init_request(self, request: Request) -> None:+ if request.params is None:+ request.params = {}+ request.params["page"] = self.page+ request.params["per_page"] = self.page_size++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ if data is None or len(data) < self.page_size:+ self._has_next_page = False+ return++ self.page += 1+ self._has_next_page = True++ def update_request(self, request: Request) -> None:+ if request.params is None:+ request.params = {}+ request.params["page"] = self.page++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ if self._has_next_page:+ return {"page": self.page}+ return None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ page = state.get("page")+ if page is not None:+ self.page = int(page)+ self._has_next_page = True+++def get_resource(endpoint_name: str, should_use_incremental_field: bool) -> EndpointResource:+ config = ENDPOINTS[endpoint_name]++ params: dict[str, Any] = {**config.extra_params, **config.sort_params}++ if should_use_incremental_field:+ params.update(config.incremental_sort_params)+ if config.uses_since_id:+ # `since_id` is inclusive (>=), so the watermark row is re-fetched and+ # deduped by the merge on primary keys.+ params["since_id"] = {+ "type": "incremental",+ "cursor_path": "id",+ "initial_value": 0,+ "convert": to_since_id,+ }+ elif config.incremental_date_field:+ params["date_field"] = config.incremental_date_field+ params["start_datetime"] = {+ "type": "incremental",+ "cursor_path": config.incremental_date_field,+ "initial_value": "1970-01-01 00:00:00",+ "convert": format_start_datetime,+ }++ return {+ "name": endpoint_name,+ "table_name": endpoint_name,+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ }+ if should_use_incremental_field+ else "replace",+ "endpoint": {+ "data_selector": config.data_selector,+ "path": config.path,+ "params": params,+ },+ "table_format": "delta",+ }+++def maxio_source(+ api_key: str,+ subdomain: str,+ region: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[MaxioResumeConfig],+ db_incremental_field_last_value: Optional[Any],+ should_use_incremental_field: bool = False,+):+ config: RESTAPIConfig = {+ "client": {+ "base_url": get_base_url(subdomain, region),+ "auth": {+ "type": "http_basic",+ "username": api_key,+ # The API only inspects the username; any non-empty password works.+ "password": "x",+ },+ "paginator": MaxioPaginator(),+ },+ "resource_defaults": {+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ }+ if should_use_incremental_field+ else "replace",+ },+ "resources": [get_resource(endpoint, should_use_incremental_field)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None and resume_config.endpoint == endpoint:+ initial_paginator_state = {"page": resume_config.next_page}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's a next page to resume to; the Redis TTL handles+ # cleanup on completion.+ if state and state.get("page"):+ resumable_source_manager.save_state(MaxioResumeConfig(endpoint=endpoint, next_page=int(state["page"])))++ return rest_api_resource(+ config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+++def validate_credentials(api_key: str, subdomain: str, region: str) -> tuple[bool, str | None]:+ response = make_tracked_session().get(+ f"{get_base_url(subdomain, region)}/customers.json",+ params={"page": 1, "per_page": 1},+ auth=(api_key, "x"),+ )+ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Maxio rejected the API key. Check that the key is valid for this site."+ if response.status_code == 404:+ return False, "Maxio site not found. Check the subdomain and hosting region."+ return False, f"Could not connect to Maxio (HTTP {response.status_code}). Check the subdomain and API key."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/maxio/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/maxio/settings.pynew file mode 100644index 000000000000..bf1dcd7a3fd2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/maxio/settings.py@@ -0,0 +1,180 @@+"""Maxio (Advanced Billing / Chargify) source settings and endpoint catalog."""++import dataclasses++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Maxio Advanced Billing sites are hosted per-region on different domains. The+# subdomain is the site's "site name"; the region is chosen when the account is+# provisioned (see maxio-com/ab-python-sdk `Environment`).+MAXIO_BASE_URLS: dict[str, str] = {+ "us": "https://{subdomain}.chargify.com",+ "eu": "https://{subdomain}.ebilling.maxio.com",+}++# Maximum allowed by the API; any larger value is clamped server-side to 200.+PAGE_SIZE = 200++# `start_datetime` filters are interpreted in the site's configured timezone (not UTC)+# unless a timezone is embedded in the value. We format watermarks as naive UTC and+# re-read a trailing day each incremental run to cover the maximum UTC<->site-timezone+# skew; the merge on primary keys dedupes the overlap.+TIMEZONE_SKEW_LOOKBACK_SECONDS = 24 * 60 * 60++[email protected](frozen=True)+class MaxioEndpointConfig:+ path: str+ # JSONPath into the response body. Most list endpoints return a bare array of+ # `{"<resource>": {...}}` wrappers; invoices/credit notes wrap the array in a key.+ data_selector: str+ primary_keys: list[str]+ # Stable datetime field used for delta partitioning; None disables partitioning.+ partition_keys: list[str] | None+ incremental_fields: list[IncrementalField]+ # Value for the `date_field` query param when syncing incrementally. Only endpoints+ # whose rows can also be *ordered* by a matching stable field advertise incremental+ # sync — the pipeline checkpoints an ascending watermark per batch.+ incremental_date_field: str | None = None+ # Events-style monotonic integer cursor (`since_id`, inclusive) instead of a+ # datetime window.+ uses_since_id: bool = False+ # Static params sent on every request.+ extra_params: dict[str, str | int | bool] = dataclasses.field(default_factory=dict)+ # Explicit stable sort applied on every run (guards against page-boundary drift).+ sort_params: dict[str, str] = dataclasses.field(default_factory=dict)+ # Sort override when syncing incrementally, matching the incremental cursor so+ # rows arrive in ascending cursor order.+ incremental_sort_params: dict[str, str] = dataclasses.field(default_factory=dict)+++def _datetime_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++ENDPOINTS: dict[str, MaxioEndpointConfig] = {+ "customers": MaxioEndpointConfig(+ path="/customers.json",+ data_selector="[*].customer",+ primary_keys=["id"],+ partition_keys=["created_at"],+ # `direction` sorts customers by time of creation only, so `created_at` is the+ # only cursor whose arrival order matches the watermark. `updated_at` filtering+ # exists server-side but rows can't be ordered by it, which would corrupt the+ # per-batch ascending watermark checkpoint.+ incremental_fields=[_datetime_field("created_at")],+ incremental_date_field="created_at",+ sort_params={"direction": "asc"},+ ),+ "subscriptions": MaxioEndpointConfig(+ path="/subscriptions.json",+ data_selector="[*].subscription",+ primary_keys=["id"],+ partition_keys=["created_at"],+ incremental_fields=[_datetime_field("updated_at")],+ incremental_date_field="updated_at",+ sort_params={"sort": "created_at", "direction": "asc"},+ incremental_sort_params={"sort": "updated_at", "direction": "asc"},+ ),+ "invoices": MaxioEndpointConfig(+ path="/invoices.json",+ data_selector="invoices",+ primary_keys=["uid"],+ partition_keys=["created_at"],+ incremental_fields=[_datetime_field("updated_at")],+ incremental_date_field="updated_at",+ extra_params={+ "line_items": "true",+ "discounts": "true",+ "taxes": "true",+ "credits": "true",+ "payments": "true",+ "refunds": "true",+ },+ sort_params={"sort": "created_at", "direction": "asc"},+ incremental_sort_params={"sort": "updated_at", "direction": "asc"},+ ),+ "products": MaxioEndpointConfig(+ path="/products.json",+ data_selector="[*].product",+ primary_keys=["id"],+ partition_keys=["created_at"],+ # Server-side date filtering exists, but the endpoint exposes no sort params so+ # arrival order is undefined — full refresh only (the table is small anyway).+ incremental_fields=[],+ extra_params={"include_archived": "true"},+ ),+ "product_families": MaxioEndpointConfig(+ path="/product_families.json",+ data_selector="[*].product_family",+ primary_keys=["id"],+ partition_keys=["created_at"],+ incremental_fields=[],+ ),+ "coupons": MaxioEndpointConfig(+ path="/coupons.json",+ data_selector="[*].coupon",+ primary_keys=["id"],+ partition_keys=["created_at"],+ # Date filtering is only available via nested `filter[...]` params whose+ # serialization we can't verify against a live site — full refresh only.+ incremental_fields=[],+ ),+ "components": MaxioEndpointConfig(+ path="/components.json",+ data_selector="[*].component",+ primary_keys=["id"],+ partition_keys=["created_at"],+ incremental_fields=[],+ extra_params={"include_archived": "true"},+ ),+ "payment_profiles": MaxioEndpointConfig(+ path="/payment_profiles.json",+ data_selector="[*].payment_profile",+ primary_keys=["id"],+ # Payment profiles carry no creation timestamp.+ partition_keys=None,+ incremental_fields=[],+ ),+ "events": MaxioEndpointConfig(+ path="/events.json",+ data_selector="[*].event",+ primary_keys=["id"],+ partition_keys=["created_at"],+ incremental_fields=[+ {+ "label": "id",+ "type": IncrementalFieldType.Integer,+ "field": "id",+ "field_type": IncrementalFieldType.Integer,+ }+ ],+ uses_since_id=True,+ sort_params={"direction": "asc"},+ ),+ "credit_notes": MaxioEndpointConfig(+ path="/credit_notes.json",+ data_selector="credit_notes",+ primary_keys=["uid"],+ # Credit notes expose no stable creation timestamp (`issue_date` can be absent+ # on drafts), so partitioning stays off.+ partition_keys=None,+ incremental_fields=[],+ extra_params={+ "line_items": "true",+ "discounts": "true",+ "taxes": "true",+ "applications": "true",+ "refunds": "true",+ },+ ),+}++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/maxio/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/maxio/source.pyindex 077b6f22f029..32734fea9aa4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/maxio/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/maxio/source.py@@ -1,31 +1,196 @@-from typing import cast+import re+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.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 MaxioSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.maxio.maxio import (+ MaxioResumeConfig,+ maxio_source,+ normalize_subdomain,+ validate_credentials as validate_maxio_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.maxio.settings import (+ ENDPOINTS,+ TIMEZONE_SKEW_LOOKBACK_SECONDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class MaxioSource(SimpleSource[MaxioSourceConfig]):+class MaxioSource(ResumableSource[MaxioSourceConfig, MaxioResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.MAXIO+ @property+ def connection_host_fields(self) -> list[str]:+ # The stored API key is sent to the host derived from these fields; retargeting+ # either must re-require the key.+ return ["subdomain", "region"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Maxio rejected the API key. Generate a new API key for the site and reconnect.",+ "403 Client Error": "The Maxio API key does not have access to this resource.",+ "404 Client Error": "Maxio site not found. Check the subdomain and hosting region.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.maxio.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: MaxioSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=name,+ supports_incremental=len(endpoint.incremental_fields) > 0,+ supports_append=len(endpoint.incremental_fields) > 0,+ incremental_fields=endpoint.incremental_fields,+ # Datetime windows are interpreted in the site's timezone — re-read a+ # trailing day to cover the skew. Integer cursors (`since_id`) are exact.+ default_incremental_lookback_seconds=(+ TIMEZONE_SKEW_LOOKBACK_SECONDS if endpoint.incremental_date_field else None+ ),+ )+ for name, endpoint in ENDPOINTS.items()+ ]++ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]++ return schemas++ def validate_credentials(+ self, config: MaxioSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ subdomain = normalize_subdomain(config.subdomain)+ if not re.match(r"^[a-zA-Z0-9-]+$", subdomain):+ return False, "Maxio subdomain is incorrect"++ return validate_maxio_credentials(config.api_key, subdomain, config.region)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MaxioResumeConfig]:+ return ResumableSourceManager[MaxioResumeConfig](inputs, MaxioResumeConfig)++ def source_for_pipeline(+ self,+ config: MaxioSourceConfig,+ resumable_source_manager: ResumableSourceManager[MaxioResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ endpoint = ENDPOINTS[inputs.schema_name]++ resource = maxio_source(+ api_key=config.api_key,+ subdomain=config.subdomain,+ region=config.region,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ )++ response = SourceResponse(+ name=resource.name,+ items=lambda: resource,+ primary_keys=endpoint.primary_keys,+ column_hints=resource.column_hints,+ )++ if endpoint.partition_keys:+ response.partition_count = 1+ response.partition_size = 1+ response.partition_mode = "datetime"+ response.partition_format = "week"+ response.partition_keys = endpoint.partition_keys++ return response+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.MAXIO,category=DataWarehouseSourceCategory.PAYMENTS___BILLING,label="Maxio",+ caption=(+ "Connect your Maxio Advanced Billing site to pull customers, subscriptions, "+ "invoices, products, components, coupons, and billing events into the PostHog "+ "Data warehouse. Generate an API key under **Config** > **Integrations** > "+ "**API keys** in your Maxio site."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/maxio",iconPath="/static/services/maxio.png",- keywords=["billing", "subscriptions", "revenue", "saas metrics"],- fields=cast(list[FieldType], []),+ keywords=["billing", "subscriptions", "revenue", "chargify", "advanced billing", "saasoptics"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="subdomain",+ label="Site subdomain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="acme",+ caption="The subdomain of your Maxio site, e.g. `acme` for `acme.chargify.com`.",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Hosting region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US (chargify.com)", value="us"),+ SourceFieldSelectConfigOption(label="EU (ebilling.maxio.com)", value="eu"),+ ],+ ),+ ],+ ),unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/maxio/tests/test_maxio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/maxio/tests/test_maxio.pynew file mode 100644index 000000000000..4f743fdf5e88--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/maxio/tests/test_maxio.py@@ -0,0 +1,378 @@+import json+from collections.abc import Iterable+from datetime import UTC, datetime, timedelta, timezone+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Request, Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.maxio.maxio import (+ MaxioPaginator,+ MaxioResumeConfig,+ format_start_datetime,+ get_base_url,+ get_resource,+ maxio_source,+ normalize_subdomain,+ to_since_id,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.maxio.settings import ENDPOINTS, PAGE_SIZE+++def _make_http_response(body: Any, status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ return resp+++def _customer_page(count: int, start_id: int = 1) -> list[dict[str, Any]]:+ return [{"customer": {"id": start_id + i, "created_at": "2024-01-01T00:00:00Z"}} for i in range(count)]+++def _resource(endpoint_name: str, should_use_incremental_field: bool) -> dict[str, Any]:+ # get_resource returns an EndpointResource TypedDict whose nested values are unions;+ # cast to a plain dict so the structural assertions below stay readable.+ return cast(dict[str, Any], get_resource(endpoint_name, should_use_incremental_field=should_use_incremental_field))+++class TestNormalizeSubdomain:+ @pytest.mark.parametrize(+ ("raw", "expected"),+ [+ ("acme", "acme"),+ (" acme ", "acme"),+ ("acme.chargify.com", "acme"),+ ("ACME.CHARGIFY.COM", "ACME"),+ ("https://acme.chargify.com/", "acme"),+ ("https://acme.ebilling.maxio.com/admin", "acme"),+ ("acme.ebilling.maxio.com", "acme"),+ ],+ )+ def test_normalizes_pasted_values(self, raw: str, expected: str) -> None:+ assert normalize_subdomain(raw) == expected+++class TestGetBaseUrl:+ @pytest.mark.parametrize(+ ("region", "expected"),+ [+ ("us", "https://acme.chargify.com"),+ ("eu", "https://acme.ebilling.maxio.com"),+ # Unknown regions fall back to US rather than crashing the sync.+ ("mars", "https://acme.chargify.com"),+ ],+ )+ def test_region_hosts(self, region: str, expected: str) -> None:+ assert get_base_url("acme", region) == expected+++class TestConverters:+ def test_format_start_datetime_converts_aware_datetime_to_utc(self) -> None:+ value = datetime(2024, 5, 1, 10, 30, 0, tzinfo=timezone(timedelta(hours=-4)))+ assert format_start_datetime(value) == "2024-05-01 14:30:00"++ def test_format_start_datetime_treats_naive_datetime_as_utc(self) -> None:+ assert format_start_datetime(datetime(2024, 5, 1, 10, 30, 0)) == "2024-05-01 10:30:00"++ def test_format_start_datetime_passes_through_initial_string(self) -> None:+ assert format_start_datetime("1970-01-01 00:00:00") == "1970-01-01 00:00:00"++ @pytest.mark.parametrize(("value", "expected"), [(42, 42), ("42", 42)])+ def test_to_since_id(self, value: Any, expected: int) -> None:+ assert to_since_id(value) == expected+++class TestMaxioPaginator:+ def test_initial_state_targets_first_page(self) -> None:+ paginator = MaxioPaginator(page_size=2)+ request = Request(method="GET", url="https://acme.chargify.com/customers.json")+ paginator.init_request(request)++ assert request.params["page"] == 1+ assert request.params["per_page"] == 2+ assert paginator.has_next_page is True++ def test_full_page_advances(self) -> None:+ paginator = MaxioPaginator(page_size=2)+ paginator.update_state(MagicMock(), data=[{"id": 1}, {"id": 2}])++ assert paginator.has_next_page is True+ assert paginator.page == 2++ @pytest.mark.parametrize("data", [[], [{"id": 1}], None])+ def test_short_or_empty_page_terminates(self, data: list[Any] | None) -> None:+ paginator = MaxioPaginator(page_size=2)+ paginator.update_state(MagicMock(), data=data)++ assert paginator.has_next_page is False++ def test_get_resume_state_returns_next_page_when_more(self) -> None:+ paginator = MaxioPaginator(page_size=2)+ paginator.update_state(MagicMock(), data=[{"id": 1}, {"id": 2}])++ assert paginator.get_resume_state() == {"page": 2}++ def test_get_resume_state_none_on_terminal_page(self) -> None:+ paginator = MaxioPaginator(page_size=2)+ paginator.update_state(MagicMock(), data=[{"id": 1}])++ assert paginator.get_resume_state() is None++ def test_set_resume_state_seeds_first_request(self) -> None:+ paginator = MaxioPaginator(page_size=2)+ paginator.set_resume_state({"page": 7})++ request = Request(method="GET", url="https://acme.chargify.com/customers.json")+ paginator.init_request(request)++ assert request.params["page"] == 7+ assert paginator.has_next_page is True++ def test_set_resume_state_ignores_missing_page(self) -> None:+ paginator = MaxioPaginator(page_size=2)+ paginator.set_resume_state({})++ assert paginator.page == 1+++class TestGetResource:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS.keys()))+ def test_full_refresh_has_no_incremental_params(self, endpoint: str) -> None:+ resource = _resource(endpoint, should_use_incremental_field=False)+ params = resource["endpoint"]["params"]++ assert "date_field" not in params+ assert "start_datetime" not in params+ assert "since_id" not in params+ assert resource["write_disposition"] == "replace"+ assert resource["endpoint"]["path"] == ENDPOINTS[endpoint].path+ assert resource["endpoint"]["data_selector"] == ENDPOINTS[endpoint].data_selector++ @pytest.mark.parametrize(+ ("endpoint", "date_field", "sort"),+ [+ ("customers", "created_at", None),+ ("subscriptions", "updated_at", "updated_at"),+ ("invoices", "updated_at", "updated_at"),+ ],+ )+ def test_incremental_datetime_endpoints_set_window_and_sort(+ self, endpoint: str, date_field: str, sort: str | None+ ) -> None:+ resource = _resource(endpoint, should_use_incremental_field=True)+ params = resource["endpoint"]["params"]++ assert params["date_field"] == date_field+ assert params["start_datetime"]["type"] == "incremental"+ assert params["start_datetime"]["cursor_path"] == date_field+ assert params["direction"] == "asc"+ if sort is not None:+ assert params["sort"] == sort+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}++ def test_incremental_events_use_since_id(self) -> None:+ resource = _resource("events", should_use_incremental_field=True)+ params = resource["endpoint"]["params"]++ assert params["since_id"]["type"] == "incremental"+ assert params["since_id"]["cursor_path"] == "id"+ assert params["direction"] == "asc"+ assert "date_field" not in params++ @pytest.mark.parametrize(+ "endpoint", ["products", "product_families", "coupons", "components", "payment_profiles", "credit_notes"]+ )+ def test_full_refresh_only_endpoints_never_get_incremental_params(self, endpoint: str) -> None:+ # These endpoints advertise no incremental fields; even if the pipeline asked for+ # incremental, no server-side filter params must be emitted.+ resource = _resource(endpoint, should_use_incremental_field=True)+ params = resource["endpoint"]["params"]++ assert "date_field" not in params+ assert "start_datetime" not in params+ assert "since_id" not in params++ def test_invoices_include_breakdowns(self) -> None:+ params = _resource("invoices", should_use_incremental_field=False)["endpoint"]["params"]+ for flag in ("line_items", "discounts", "taxes", "credits", "payments", "refunds"):+ assert params[flag] == "true"+++class TestMaxioSourceDrive:+ """End-to-end behaviour of ``maxio_source`` via ``rest_api_resource`` with a mocked session."""++ def _drive(+ self,+ endpoint: str,+ manager: MagicMock,+ responses: list[Response],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ ) -> tuple[list[dict[str, Any]], list[list[Any]]]:+ """Returns ``(sent_params, yielded_pages)``; params are copied at send-time because+ the paginator mutates the Request in place between pages."""+ sent_params: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_params.append(dict(request.params or {}))+ return next(response_iter)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ resource = maxio_source(+ api_key="test-key",+ subdomain="acme",+ region="us",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ should_use_incremental_field=should_use_incremental_field,+ )+ pages = list(cast(Iterable[Any], resource))+ return sent_params, pages++ def test_paginates_and_saves_state_after_each_non_terminal_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response(_customer_page(PAGE_SIZE)),+ _make_http_response(_customer_page(1, start_id=PAGE_SIZE + 1)),+ ]+ sent_params, pages = self._drive("customers", manager, responses)++ assert [p["page"] for p in sent_params] == [1, 2]+ assert all(p["per_page"] == PAGE_SIZE for p in sent_params)+ # Rows are unwrapped from the `{"customer": {...}}` envelope by the data selector.+ assert pages[0][0] == {"id": 1, "created_at": "2024-01-01T00:00:00Z"}++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [MaxioResumeConfig(endpoint="customers", next_page=2)]++ def test_terminal_single_page_does_not_save_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ self._drive("customers", manager, [_make_http_response(_customer_page(3))])++ manager.save_state.assert_not_called()++ def test_resume_seeds_paginator_with_saved_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = MaxioResumeConfig(endpoint="customers", next_page=5)++ sent_params, _ = self._drive("customers", manager, [_make_http_response(_customer_page(1))])++ assert [p["page"] for p in sent_params] == [5]++ def test_resume_state_for_other_endpoint_is_ignored(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = MaxioResumeConfig(endpoint="invoices", next_page=5)++ sent_params, _ = self._drive("customers", manager, [_make_http_response(_customer_page(1))])++ assert [p["page"] for p in sent_params] == [1]++ def test_incremental_run_sends_formatted_watermark(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ sent_params, _ = self._drive(+ "subscriptions",+ manager,+ [_make_http_response([{"subscription": {"id": 1, "created_at": "2024-01-01T00:00:00Z"}}])],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 5, 1, 10, 30, 0, tzinfo=UTC),+ )++ assert sent_params[0]["date_field"] == "updated_at"+ assert sent_params[0]["start_datetime"] == "2024-05-01 10:30:00"+ assert sent_params[0]["sort"] == "updated_at"+ assert sent_params[0]["direction"] == "asc"++ def test_incremental_events_run_sends_since_id(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ sent_params, pages = self._drive(+ "events",+ manager,+ [_make_http_response([{"event": {"id": 101, "key": "signup_success"}}])],+ should_use_incremental_field=True,+ db_incremental_field_last_value=100,+ )++ assert sent_params[0]["since_id"] == 100+ assert pages[0][0]["id"] == 101++ def test_invoices_rows_are_extracted_from_wrapped_response(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ _, pages = self._drive(+ "invoices",+ manager,+ [_make_http_response({"invoices": [{"uid": "inv_1", "created_at": "2024-01-01T00:00:00Z"}]})],+ )++ assert pages[0] == [{"uid": "inv_1", "created_at": "2024-01-01T00:00:00Z"}]+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ ("status_code", "expected_valid", "expected_error_fragment"),+ [+ (200, True, None),+ (401, False, "rejected the API key"),+ (404, False, "site not found"),+ (500, False, "HTTP 500"),+ ],+ )+ def test_status_mapping(self, status_code: int, expected_valid: bool, expected_error_fragment: str | None) -> None:+ response = MagicMock()+ response.status_code = status_code++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.maxio.maxio.make_tracked_session"+ ) as MockSession:+ MockSession.return_value.get.return_value = response+ valid, error = validate_credentials("key", "acme", "us")++ assert valid is expected_valid+ if expected_error_fragment is None:+ assert error is None+ else:+ assert error is not None+ assert expected_error_fragment in error++ def test_probe_targets_region_host_with_basic_auth(self) -> None:+ response = MagicMock()+ response.status_code = 200++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.maxio.maxio.make_tracked_session"+ ) as MockSession:+ MockSession.return_value.get.return_value = response+ validate_credentials("key", "acme", "eu")++ call = MockSession.return_value.get.call_args+ assert call.args[0] == "https://acme.ebilling.maxio.com/customers.json"+ assert call.kwargs["auth"] == ("key", "x")+ assert call.kwargs["params"] == {"page": 1, "per_page": 1}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/maxio/tests/test_maxio_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/maxio/tests/test_maxio_source.pynew file mode 100644index 000000000000..6aa291824b7c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/maxio/tests/test_maxio_source.py@@ -0,0 +1,243 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+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 MaxioSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.maxio.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.maxio.maxio import MaxioResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.maxio.settings import (+ ENDPOINTS,+ TIMEZONE_SKEW_LOOKBACK_SECONDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.maxio.source import MaxioSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(**overrides: Any) -> MaxioSourceConfig:+ defaults: dict[str, Any] = {"subdomain": "acme", "api_key": "test-key", "region": "us"}+ defaults.update(overrides)+ return MaxioSourceConfig(**defaults)+++def _inputs(schema_name: str, should_use_incremental_field: bool = False, **overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": schema_name,+ "schema_id": "schema-id",+ "source_id": "source-id",+ "team_id": 123,+ "should_use_incremental_field": should_use_incremental_field,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-id",+ "logger": MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestMaxioSource:+ def test_source_type(self) -> None:+ assert MaxioSource().source_type == ExternalDataSourceType.MAXIO++ def test_source_config_shape(self) -> None:+ config = MaxioSource().get_source_config++ assert config.category == DataWarehouseSourceCategory.PAYMENTS___BILLING+ assert config.label == "Maxio"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/maxio"+ assert config.unreleasedSource is True+ assert config.releaseStatus == ReleaseStatus.ALPHA++ fields_by_name = {f.name: f for f in config.fields}+ assert set(fields_by_name.keys()) == {"subdomain", "api_key", "region"}++ api_key_field = fields_by_name["api_key"]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.secret is True++ region_field = fields_by_name["region"]+ assert isinstance(region_field, SourceFieldSelectConfig)+ assert region_field.defaultValue == "us"+ assert {option.value for option in region_field.options} == {"us", "eu"}++ def test_connection_host_fields_cover_host_determining_fields(self) -> None:+ assert MaxioSource().connection_host_fields == ["subdomain", "region"]++ def test_get_schemas_lists_every_endpoint(self) -> None:+ schemas = MaxioSource().get_schemas(_config(), team_id=123)++ assert {schema.name for schema in schemas} == set(ENDPOINTS.keys())++ @pytest.mark.parametrize(+ ("schema_name", "supports_incremental", "incremental_field"),+ [+ ("customers", True, "created_at"),+ ("subscriptions", True, "updated_at"),+ ("invoices", True, "updated_at"),+ ("events", True, "id"),+ ("products", False, None),+ ("product_families", False, None),+ ("coupons", False, None),+ ("components", False, None),+ ("payment_profiles", False, None),+ ("credit_notes", False, None),+ ],+ )+ def test_get_schemas_incremental_support(+ self, schema_name: str, supports_incremental: bool, incremental_field: str | None+ ) -> None:+ schemas = {schema.name: schema for schema in MaxioSource().get_schemas(_config(), team_id=123)}+ schema = schemas[schema_name]++ assert schema.supports_incremental is supports_incremental+ assert schema.supports_append is supports_incremental+ if incremental_field is None:+ assert schema.incremental_fields == []+ else:+ assert [f["field"] for f in schema.incremental_fields] == [incremental_field]++ @pytest.mark.parametrize(+ ("schema_name", "expected_lookback"),+ [+ # Datetime windows are interpreted in the site's timezone, so those schemas+ # re-read a trailing day; the integer `since_id` cursor is exact.+ ("customers", TIMEZONE_SKEW_LOOKBACK_SECONDS),+ ("subscriptions", TIMEZONE_SKEW_LOOKBACK_SECONDS),+ ("invoices", TIMEZONE_SKEW_LOOKBACK_SECONDS),+ ("events", None),+ ],+ )+ def test_get_schemas_lookback_only_on_datetime_windows(+ self, schema_name: str, expected_lookback: int | None+ ) -> None:+ schemas = {schema.name: schema for schema in MaxioSource().get_schemas(_config(), team_id=123)}++ assert schemas[schema_name].default_incremental_lookback_seconds == expected_lookback++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = MaxioSource().get_schemas(_config(), team_id=123, names=["customers", "invoices"])++ assert {schema.name for schema in schemas} == {"customers", "invoices"}++ @pytest.mark.parametrize("subdomain", ["bad domain", "acme!", ""])+ def test_validate_credentials_rejects_invalid_subdomain_without_network(self, subdomain: str) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.maxio.source.validate_maxio_credentials"+ ) as mock_validate:+ valid, error = MaxioSource().validate_credentials(_config(subdomain=subdomain), team_id=123)++ assert valid is False+ assert error == "Maxio subdomain is incorrect"+ mock_validate.assert_not_called()++ @pytest.mark.parametrize(("result", "message"), [((True, None), None), ((False, "nope"), "nope")])+ def test_validate_credentials_delegates_to_api_probe(+ self, result: tuple[bool, str | None], message: str | None+ ) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.maxio.source.validate_maxio_credentials",+ return_value=result,+ ) as mock_validate:+ valid, error = MaxioSource().validate_credentials(+ _config(subdomain="https://acme.chargify.com/"), team_id=123+ )++ assert (valid, error) == result+ # A pasted URL must reach the probe as the normalized bare subdomain.+ mock_validate.assert_called_once_with("test-key", "acme", "us")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = MaxioSource().get_resumable_source_manager(_inputs("customers"))++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is MaxioResumeConfig++ def test_non_retryable_errors_cover_auth_failures(self) -> None:+ errors = MaxioSource().get_non_retryable_errors()++ assert any("401" in key for key in errors)+ assert any("403" in key for key in errors)++ def test_canonical_descriptions_match_endpoint_names(self) -> None:+ assert set(CANONICAL_DESCRIPTIONS.keys()) == set(ENDPOINTS.keys())+ assert MaxioSource().get_canonical_descriptions() is CANONICAL_DESCRIPTIONS++ def test_documented_tables_render_without_credentials(self) -> None:+ tables = MaxioSource().get_documented_tables()++ assert {table["name"] for table in tables} == set(ENDPOINTS.keys())+++class TestMaxioSourceForPipeline:+ def _run(self, schema_name: str) -> Any:+ source = MaxioSource()+ inputs = _inputs(schema_name)+ manager = MagicMock(spec=ResumableSourceManager)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.maxio.source.maxio_source"+ ) as mock_source:+ mock_source.return_value.name = schema_name+ mock_source.return_value.column_hints = None+ response = source.source_for_pipeline(_config(), manager, inputs)++ return response, mock_source++ def test_plumbs_config_and_inputs_to_transport(self) -> None:+ _, mock_source = self._run("customers")++ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "test-key"+ assert kwargs["subdomain"] == "acme"+ assert kwargs["region"] == "us"+ assert kwargs["endpoint"] == "customers"+ assert kwargs["team_id"] == 123+ assert kwargs["should_use_incremental_field"] is False+ assert kwargs["db_incremental_field_last_value"] is None++ @pytest.mark.parametrize(+ ("schema_name", "primary_keys", "partition_keys"),+ [+ ("customers", ["id"], ["created_at"]),+ ("subscriptions", ["id"], ["created_at"]),+ ("invoices", ["uid"], ["created_at"]),+ ("events", ["id"], ["created_at"]),+ ("payment_profiles", ["id"], None),+ ("credit_notes", ["uid"], None),+ ],+ )+ def test_primary_keys_and_partitioning(+ self, schema_name: str, primary_keys: list[str], partition_keys: list[str] | None+ ) -> None:+ response, _ = self._run(schema_name)++ assert response.primary_keys == primary_keys+ assert response.partition_keys == partition_keys+ if partition_keys is not None:+ assert response.partition_mode == "datetime"+ assert response.partition_format == "week"++ def test_incremental_last_value_only_passed_when_enabled(self) -> None:+ source = MaxioSource()+ manager = MagicMock(spec=ResumableSourceManager)+ inputs = _inputs("subscriptions", should_use_incremental_field=False)+ inputs.db_incremental_field_last_value = "2024-05-01"++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.maxio.source.maxio_source"+ ) as mock_source:+ mock_source.return_value.name = "subscriptions"+ mock_source.return_value.column_hints = None+ source.source_for_pipeline(_config(), manager, inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None