: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 Gumroad source (#77082)
Tom Owers4dea18556b85
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 289a0e7b33c6..255c09d3e764 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -299,6 +299,7 @@ the row lists both.| gridly | HTTP | requests | ✅ || groq | HTTP | requests | ✅ || guardian | HTTP | requests | ✅ |+| gumroad | HTTP | requests | ✅ || guru | HTTP | requests | ✅ || gusto | HTTP | requests | ✅ || harvest | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -1022,7 +1023,6 @@ doesn't conflict with concurrent PRs.- growthbook- guesty- gumloop-- gumroad- harness- harness_ccm- harness_seidiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/gumroad.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/gumroad.pyindex 0f7de6e2b6a4..3dca8f163031 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/gumroad.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/gumroad.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass GumroadSourceConfig(config.Config):- pass+ access_token: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/canonical_descriptions.pynew file mode 100644index 000000000000..813329621eaf--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/canonical_descriptions.py@@ -0,0 +1,169 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "sales": {+ "description": "A completed purchase of one of your Gumroad products, including refunds, chargebacks, and recurring subscription charges.",+ "docs_url": "https://gumroad.com/api#sales",+ "columns": {+ "id": "Unique identifier for the sale.",+ "created_at": "When the sale was made.",+ "email": "Email address the purchase is associated with.",+ "purchase_email": "Email address entered at checkout.",+ "seller_id": "Identifier of the seller who made the sale.",+ "product_id": "Identifier of the product that was bought.",+ "product_name": "Name of the product that was bought.",+ "product_permalink": "Short permalink of the product that was bought.",+ "price": "Amount paid, in the smallest unit of the sale currency (for example cents).",+ "currency": "ISO code of the currency the sale is denominated in.",+ "gumroad_fee": "Gumroad's fee for the sale, in the smallest unit of the sale currency.",+ "formatted_display_price": "Sale price formatted with its currency symbol.",+ "formatted_total_price": "Total charged, formatted with its currency symbol.",+ "quantity": "Number of units bought.",+ "order_id": "Numeric order identifier shared by every sale in the same order.",+ "full_name": "Name given by the buyer.",+ "purchaser_id": "Identifier of the buyer's Gumroad account, when they have one.",+ "refunded": "Whether the sale was fully refunded.",+ "partially_refunded": "Whether part of the sale was refunded.",+ "chargedback": "Whether the sale was charged back and the chargeback was not reversed.",+ "disputed": "Whether the sale was disputed.",+ "dispute_won": "Whether a dispute on the sale was resolved in your favor.",+ "subscription_id": "Identifier of the subscription this charge belongs to, for memberships.",+ "recurring_charge": "Whether this is a renewal rather than the first charge of a subscription.",+ "is_recurring_billing": "Whether the product is billed on a recurring basis.",+ "is_product_physical": "Whether the product requires shipping.",+ "variants": "Versions the buyer selected, as a name to value map.",+ "custom_fields": "Values the buyer entered in the product's custom fields.",+ "offer_code": "Discount code applied to the sale, when there was one.",+ "affiliate": "Affiliate credited with the sale, when there was one.",+ "referrer": "Where the buyer came from.",+ "country": "Buyer's country.",+ "country_iso2": "Two-letter ISO code of the buyer's country.",+ "state": "Buyer's state or region.",+ "city": "Buyer's city.",+ "zip_code": "Buyer's postal code.",+ "product_rating": "Rating the buyer left for the product, when they left one.",+ "license_key": "License key issued for the sale, for licensed products.",+ },+ },+ "products": {+ "description": "A product on your Gumroad account, with its pricing, versions, and published state.",+ "docs_url": "https://gumroad.com/api#products",+ "columns": {+ "id": "Unique identifier for the product.",+ "name": "Product name.",+ "description": "Product description.",+ "price": "Default price, in the smallest unit of the product currency.",+ "currency": "ISO code of the currency the product is priced in.",+ "formatted_price": "Default price formatted with its currency symbol.",+ "short_url": "Public URL of the product page.",+ "custom_permalink": "Custom permalink set for the product, when there is one.",+ "published": "Whether the product is published and available to buy.",+ "deleted": "Whether the product has been deleted.",+ "max_purchase_count": "Cap on how many times the product can be bought, when set.",+ "tags": "Tags applied to the product.",+ "taxonomy_id": "Identifier of the category the product is filed under.",+ "category": "Path of the category the product is filed under.",+ "thumbnail_url": "URL of the product thumbnail.",+ "require_shipping": "Whether the product needs a shipping address.",+ "customizable_price": "Whether buyers can pay what they want.",+ "subscription_duration": "Billing period for a membership product.",+ "is_tiered_membership": "Whether the product is a tiered membership.",+ "variants": "Version groupings on the product and the options in each.",+ "custom_fields": "Custom fields buyers fill in at checkout.",+ "sales_count": "Number of successful sales. Needs the view_sales scope.",+ "sales_usd_cents": "Lifetime revenue in US cents. Needs the view_sales scope.",+ },+ },+ "payouts": {+ "description": "A settled payout Gumroad sent to your bank account or PayPal address.",+ "docs_url": "https://gumroad.com/api#payouts",+ "columns": {+ "id": "Unique identifier for the payout.",+ "created_at": "When the payout was created.",+ "processed_at": "When the payout completed, for completed payouts.",+ "amount": "Payout amount, as a decimal string in the payout currency.",+ "currency": "ISO code of the payout currency.",+ "status": "Current state of the payout.",+ "payment_processor": "Processor that sent the payout.",+ "bank_account_visual": "Masked bank account the payout was sent to.",+ "paypal_email": "PayPal address the payout was sent to.",+ },+ },+ "subscribers": {+ "description": "An active subscription to one of your membership products.",+ "docs_url": "https://gumroad.com/api#subscribers",+ "columns": {+ "id": "Unique identifier for the subscription.",+ "product_id": "Identifier of the membership product.",+ "product_name": "Name of the membership product.",+ "email": "Email address of the subscriber.",+ "user_id": "Identifier of the subscriber's Gumroad account, when they have one.",+ "user_email": "Email address on the subscriber's Gumroad account.",+ "purchase_ids": "Identifiers of the sales that make up this subscription.",+ "created_at": "When the subscription started.",+ "recurrence": "How often the subscription is billed.",+ "charge_occurrence_count": "Number of charges the subscription is limited to, when limited.",+ "user_requested_cancellation_at": "When the subscriber asked to cancel.",+ "cancelled_at": "When the subscription was cancelled.",+ "ended_at": "When the subscription ended.",+ "failed_at": "When billing failed permanently.",+ "free_trial_ends_at": "When the free trial ends.",+ "status": "Current state of the subscription.",+ "license_key": "License key issued for the subscription, for licensed products.",+ },+ },+ "product_reviews": {+ "description": "A review left on one of your products, as shown on its public product page.",+ "docs_url": "https://gumroad.com/api#reviews",+ "columns": {+ "id": "Unique identifier for the review.",+ "product_id": "Identifier of the reviewed product, carried down from the product list.",+ "rating": "Star rating the reviewer gave.",+ "message": "Text of the review.",+ "created_at": "When the review was submitted.",+ "purchase_id": "Identifier of the sale the review is attached to.",+ "rater_name": "Name of the reviewer, or Anonymous.",+ "response": "Your reply to the review, with its own message and timestamp.",+ },+ },+ "offer_codes": {+ "description": "A discount code that applies to a product, including universal codes that apply to every product.",+ "docs_url": "https://gumroad.com/api#offer-codes",+ "columns": {+ "id": "Unique identifier for the offer code.",+ "product_id": "Identifier of the product the code was listed under, carried down from the product list.",+ "name": "The code buyers enter at checkout.",+ "amount_cents": "Fixed discount in the smallest unit of the product currency, for fixed-amount codes.",+ "percent_off": "Discount percentage, for percentage codes.",+ "max_purchase_count": "Cap on how many times the code can be used, when set.",+ "minimum_amount_cents": "Minimum order amount the code applies to, when set.",+ "universal": "Whether the code applies to every product on the account.",+ "times_used": "Number of times the code has been used.",+ },+ },+ "variant_categories": {+ "description": "A grouping of versions on a product, such as Tier or Format.",+ "docs_url": "https://gumroad.com/api#variant-categories",+ "columns": {+ "id": "Unique identifier for the version grouping.",+ "product_id": "Identifier of the product the grouping belongs to, carried down from the product list.",+ "title": "Name of the grouping shown at checkout.",+ },+ },+ "custom_fields": {+ "description": "A field buyers fill in at checkout for a product.",+ "docs_url": "https://gumroad.com/api#custom-fields",+ "columns": {+ "id": "Unique identifier for the custom field.",+ "product_id": "Identifier of the product the field was listed under, carried down from the product list.",+ "name": "Label shown to the buyer.",+ "type": "Kind of input the field renders.",+ "required": "Whether the buyer must fill the field in.",+ "global": "Whether the field applies to every product on the account.",+ "collect_per_product": "Whether the value is collected once per product in the cart.",+ "products": "Identifiers of the products the field is attached to.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/gumroad.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/gumroad.pynew file mode 100644index 000000000000..9dbe8a9c0179--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/gumroad.py@@ -0,0 +1,273 @@+import dataclasses+from collections.abc import Callable, Iterable+from typing import Any, Optional, cast++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (+ coerce_datetime_to_utc,+)+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.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ JSONResponseCursorPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,+ IncrementalConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.settings import (+ GUMROAD_BASE_URL,+ GUMROAD_ENDPOINTS,+ INCREMENTAL_START_PARAM,+ PAGE_KEY_CURSOR_PATH,+ PAGE_KEY_PARAM,+ GumroadEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 30.0+++class GumroadResumeConfig:+ """Paginator checkpoint — the `page_key` cursor of the page we have not yet fetched."""++ page_key: str+++def _format_gumroad_date(value: Any) -> str:+ """Format the incremental watermark for Gumroad's `after` filter (YYYY-MM-DD).++ Gumroad only accepts whole dates and filters on `created_at >= <date>`, so truncating to+ the day rounds the lower bound down: a sync re-reads the watermark day rather than+ skipping rows created later on it. The merge dedupes the overlap on the primary key.+ """+ normalized_value = coerce_datetime_to_utc(value)+ if normalized_value is None:+ return str(value)+ return normalized_value.strftime("%Y-%m-%d")+++def _gumroad_incremental_window(cursor_path: str) -> IncrementalConfig:+ return {+ "cursor_path": cursor_path,+ "start_param": INCREMENTAL_START_PARAM,+ "initial_value": "1970-01-01",+ "convert": _format_gumroad_date,+ }+++def _page_key_paginator() -> JSONResponseCursorPaginator:+ return JSONResponseCursorPaginator(cursor_path=PAGE_KEY_CURSOR_PATH, cursor_param=PAGE_KEY_PARAM)+++def _paginator_for(config: GumroadEndpointConfig) -> BasePaginator:+ return _page_key_paginator() if config.paginated else SinglePagePaginator()+++def _rest_api_client_config(access_token: str) -> ClientConfig:+ return {+ "base_url": GUMROAD_BASE_URL,+ "auth": {"type": "bearer", "token": access_token},+ "headers": {"Accept": "application/json"},+ # `capture=False`: sales and subscriber rows carry redeemable `license_key` values, and+ # reviews and custom fields carry arbitrary customer text the name-based sample scrubbers+ # can't redact, so keep every response body out of HTTP sample storage. Requests stay+ # metered and logged.+ "session": make_tracked_session(redact_values=(access_token,), capture=False, allow_redirects=False),+ # Pin every request (and the bearer header) to the Gumroad host and refuse to follow a+ # 3xx, so a server-side redirect can never replay the credential off-host.+ "allowed_hosts": [],+ "allow_redirects": False,+ "request_timeout": REQUEST_TIMEOUT_SECONDS,+ }+++def get_resource(+ endpoint: str,+ should_use_incremental_field: bool,+ incremental_field_name: str | None = None,+) -> EndpointResource:+ config = GUMROAD_ENDPOINTS[endpoint]+ if config.fanout:+ raise ValueError(f"Fan-out endpoint '{endpoint}' must use the fan-out path")++ endpoint_config: Endpoint = {+ "path": config.path,+ "params": dict(config.extra_params),+ "data_selector": config.data_selector,+ # Every documented Gumroad response wraps its rows in a named key, so a body without it+ # means the shape changed — fail loud rather than silently syncing 0 rows.+ "data_selector_required": True,+ "paginator": _paginator_for(config),+ }++ use_incremental = should_use_incremental_field and bool(config.incremental_fields)+ if use_incremental:+ endpoint_config["incremental"] = _gumroad_incremental_window(+ incremental_field_name or config.default_incremental_field or "created_at"+ )++ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if use_incremental else "replace",+ "endpoint": endpoint_config,+ "table_format": "delta",+ }+++def _make_source_response(+ endpoint_config: GumroadEndpointConfig,+ items_fn: Callable[[], Iterable[Any]],+) -> SourceResponse:+ return SourceResponse(+ name=endpoint_config.name,+ items=items_fn,+ primary_keys=endpoint_config.primary_key,+ # Every Gumroad list endpoint orders `created_at DESC, id DESC`, and there is no+ # parameter to reverse it, so rows always arrive newest-first.+ sort_mode="desc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )+++def gumroad_source(+ access_token: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: Optional[ResumableSourceManager[GumroadResumeConfig]] = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = GUMROAD_ENDPOINTS[endpoint]++ if endpoint_config.fanout:+ parent_config = GUMROAD_ENDPOINTS[endpoint_config.fanout.parent_name]+ # Dependent resources don't currently support resume in the rest_source framework;+ # the manager is intentionally not threaded into this path.+ dependent_resource = cast(+ Iterable[Any],+ build_dependent_resource(+ endpoint_configs=GUMROAD_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=dataclasses.replace(endpoint_config.fanout, child_params=dict(endpoint_config.extra_params)),+ client_config=_rest_api_client_config(access_token),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=db_incremental_field_last_value,+ should_use_incremental_field=should_use_incremental_field,+ incremental_field=incremental_field,+ incremental_config_factory=_gumroad_incremental_window,+ # Gumroad list endpoints take no page-size parameter; the server fixes it.+ page_size_param=None,+ parent_endpoint_extra={+ "paginator": _paginator_for(parent_config),+ "data_selector": parent_config.data_selector,+ "data_selector_required": True,+ },+ child_endpoint_extra={+ "paginator": _paginator_for(endpoint_config),+ "data_selector": endpoint_config.data_selector,+ "data_selector_required": True,+ },+ ),+ )+ return _make_source_response(endpoint_config, lambda: dependent_resource)++ config: RESTAPIConfig = {+ "client": _rest_api_client_config(access_token),+ "resource_defaults": {},+ "resources": [get_resource(endpoint, should_use_incremental_field, incremental_field)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ resume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = None+ if resumable_source_manager is not None:+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"cursor": resume_config.page_key}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only while there is another page to resume to; the Redis TTL cleans up+ # on completion.+ if resumable_source_manager is None or not state:+ return+ cursor = state.get("cursor")+ if cursor:+ resumable_source_manager.save_state(GumroadResumeConfig(page_key=str(cursor)))++ resume_hook = save_checkpoint++ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=resume_hook,+ initial_paginator_state=initial_paginator_state,+ )+ return _make_source_response(endpoint_config, lambda: resource)+++def _get(access_token: str, path: str, params: dict[str, str] | None = None) -> int | None:+ """Probe `path` and return the HTTP status code, or None if the request never completed.++ Transport failures (DNS error, connection reset, timeout before any response) are not+ permission problems, so they surface as None and let each caller decide how to treat an+ unreachable host. `capture=False` keeps the real `/v2/user` and `/v2/sales` probe responses+ out of HTTP sample storage.+ """+ try:+ response = make_tracked_session(redact_values=(access_token,), capture=False, allow_redirects=False).get(+ f"{GUMROAD_BASE_URL}{path}",+ headers={"Authorization": f"Bearer {access_token}", "Accept": "application/json"},+ params=params,+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ except requests.RequestException:+ return None+ return response.status_code+++def validate_credentials(access_token: str) -> tuple[bool, str | None]:+ # `/v2/user` is readable by every scope Gumroad can issue, so a non-200 here means the token+ # itself is bad rather than under-scoped.+ status_code = _get(access_token, "/v2/user")+ if status_code is None:+ return False, "Couldn't reach Gumroad to validate the access token. Check your connection and try again."+ if status_code == 200:+ return True, None+ if status_code in (401, 403):+ return (+ False,+ "Gumroad rejected the access token. Generate a new one under Settings > Advanced > "+ "Applications and reconnect.",+ )+ return False, f"Gumroad API returned an unexpected status code: {status_code}"+++def check_endpoint_permission(access_token: str, path: str) -> bool:+ """Whether the token can read `path`. Only a 403 counts as a missing scope; a transport failure+ leaves the probe unable to tell, so we treat the endpoint as reachable rather than denied."""+ return _get(access_token, path) != 403diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/settings.pynew file mode 100644index 000000000000..c2726bcc83e1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/settings.py@@ -0,0 +1,156 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++GUMROAD_BASE_URL = "https://api.gumroad.com"++# Gumroad's list endpoints take no page-size parameter — the server fixes it per resource+# (10 for sales/products/payouts, 100 for subscribers and reviews). `page_size` below is only+# carried to satisfy the fan-out helper's protocol; no request ever sends it.+SERVER_FIXED_PAGE_SIZE = 10++# Response wrapper key holding the next cursor, and the request param that consumes it.+PAGE_KEY_CURSOR_PATH = "next_page_key"+PAGE_KEY_PARAM = "page_key"++# `after` filters on `created_at >= <date>` at day granularity, so a resumed sync always+# re-reads from midnight of the watermark's day. The merge dedupes those rows on the primary key.+INCREMENTAL_START_PARAM = "after"+++@dataclass+class GumroadEndpointConfig:+ name: str+ path: str+ data_selector: str+ primary_key: list[str]+ # Endpoints whose response carries `next_page_key`; the rest return the full collection.+ paginated: bool = True+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+ partition_key: str | None = None+ page_size: int = SERVER_FIXED_PAGE_SIZE+ extra_params: dict[str, str] = field(default_factory=dict)+ fanout: DependentEndpointConfig | None = None+ # Path probed to tell whether the token carries the OAuth scope this table needs.+ permission_probe_path: str = "/v2/user"+ required_scope: str = "view_public"+++# Every product-scoped table fans out over `/v2/products`, carrying the parent's `id` in as+# `product_id`. Universal offer codes and global custom fields are returned under every product+# they apply to, so the parent id is part of those tables' primary keys.+_PRODUCT_FANOUT = DependentEndpointConfig(+ parent_name="products",+ resolve_param="product_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "product_id"},+)+++GUMROAD_ENDPOINTS: dict[str, GumroadEndpointConfig] = {+ "sales": GumroadEndpointConfig(+ name="sales",+ path="/v2/sales",+ data_selector="sales",+ primary_key=["id"],+ incremental_fields=[incremental_field("created_at")],+ default_incremental_field="created_at",+ partition_key="created_at",+ permission_probe_path="/v2/sales",+ required_scope="view_sales",+ ),+ "products": GumroadEndpointConfig(+ name="products",+ path="/v2/products",+ data_selector="products",+ primary_key=["id"],+ # The product payload carries no timestamp at all (no created_at/updated_at), so there+ # is nothing to filter or partition on — full refresh.+ permission_probe_path="/v2/products",+ ),+ "payouts": GumroadEndpointConfig(+ name="payouts",+ path="/v2/payouts",+ data_selector="payouts",+ primary_key=["id"],+ incremental_fields=[incremental_field("created_at")],+ default_incremental_field="created_at",+ partition_key="created_at",+ # Upcoming (not yet paid out) payouts are prepended with a null id, which would break the+ # primary key. Ask for settled payouts only.+ extra_params={"include_upcoming": "false"},+ permission_probe_path="/v2/payouts",+ required_scope="view_payouts",+ ),+ "subscribers": GumroadEndpointConfig(+ name="subscribers",+ path="/v2/products/{product_id}/subscribers",+ data_selector="subscribers",+ # Subscription ids are account-wide unique (the top-level `/v2/subscribers/{id}` endpoint+ # resolves them without a product), and each row already carries its own `product_id`.+ primary_key=["id"],+ partition_key="created_at",+ # Pagination is opt-in on this endpoint; without it the whole collection comes back in+ # one response and `next_page_key` is never set.+ extra_params={"paginated": "true"},+ fanout=DependentEndpointConfig(+ parent_name="products",+ resolve_param="product_id",+ resolve_field="id",+ # The subscriber payload already carries `product_id`; nothing to copy down.+ include_from_parent=[],+ ),+ permission_probe_path="/v2/sales",+ required_scope="view_sales",+ ),+ "product_reviews": GumroadEndpointConfig(+ name="product_reviews",+ path="/v2/products/{product_id}/reviews",+ data_selector="product_reviews",+ primary_key=["product_id", "id"],+ partition_key="created_at",+ fanout=_PRODUCT_FANOUT,+ permission_probe_path="/v2/products",+ ),+ "offer_codes": GumroadEndpointConfig(+ name="offer_codes",+ path="/v2/products/{product_id}/offer_codes",+ data_selector="offer_codes",+ # Universal offer codes are listed under every product, so the same code id repeats.+ primary_key=["product_id", "id"],+ paginated=False,+ fanout=_PRODUCT_FANOUT,+ permission_probe_path="/v2/products",+ ),+ "variant_categories": GumroadEndpointConfig(+ name="variant_categories",+ path="/v2/products/{product_id}/variant_categories",+ data_selector="variant_categories",+ primary_key=["product_id", "id"],+ paginated=False,+ fanout=_PRODUCT_FANOUT,+ permission_probe_path="/v2/products",+ ),+ "custom_fields": GumroadEndpointConfig(+ name="custom_fields",+ path="/v2/products/{product_id}/custom_fields",+ data_selector="custom_fields",+ # Global custom fields are attached to many products and repeat across them.+ primary_key=["product_id", "id"],+ paginated=False,+ fanout=_PRODUCT_FANOUT,+ permission_probe_path="/v2/products",+ ),+}++ENDPOINTS = tuple(GUMROAD_ENDPOINTS)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in GUMROAD_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/source.pyindex 7885ab3993cd..002ca5ccdd93 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/source.py@@ -1,32 +1,170 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.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, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.gumroad import (GumroadSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.gumroad import (+ GumroadResumeConfig,+ check_endpoint_permission,+ gumroad_source,+ validate_credentials as validate_gumroad_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.settings import (+ ENDPOINTS,+ GUMROAD_ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class GumroadSource(SimpleSource[GumroadSourceConfig]):+class GumroadSource(ResumableSource[GumroadSourceConfig, GumroadResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = ("v2",)+ default_version = "v2"+ api_docs_url = "https://gumroad.com/api"++ # Deliberately not a `WebhookSource`: Gumroad's resource subscriptions are API-manageable, but+ # every delivery is sent as `application/x-www-form-urlencoded` (the JSON content type is only+ # assigned to zapier.com endpoints, and no API parameter overrides it) and the ping payload+ # names its fields differently from the REST sale object, so webhook rows could not merge into+ # the polled tables. Deltas come from the incremental `after` window instead.+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GUMROAD+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Gumroad rejected the access token. Generate a new one under Settings > Advanced > Applications and reconnect.",+ "403 Client Error: Forbidden for url": "The Gumroad access token is missing a scope required for this table. Reconnect with a token that has access to the tables you're syncing.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: GumroadSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: GumroadSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_gumroad_credentials(config.access_token)++ def get_endpoint_permissions(+ self,+ config: GumroadSourceConfig,+ team_id: int,+ endpoints: list[str],+ api_version: str | None = None,+ ) -> dict[str, str | None]:+ # Gumroad scopes are per-resource, so a token can read products while being refused sales+ # or payouts. Probe each distinct path once and reuse the verdict for the tables sharing it.+ results: dict[str, str | None] = {}+ probed: dict[str, bool] = {}+ for name in endpoints:+ endpoint_config = GUMROAD_ENDPOINTS.get(name)+ if endpoint_config is None:+ results[name] = None+ continue++ path = endpoint_config.permission_probe_path+ if path not in probed:+ probed[path] = check_endpoint_permission(config.access_token, path)++ results[name] = (+ None+ if probed[path]+ else f"Your Gumroad access token is missing the {endpoint_config.required_scope} scope."+ )+ return results++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GumroadResumeConfig]:+ return ResumableSourceManager[GumroadResumeConfig](inputs, GumroadResumeConfig)++ def source_for_pipeline(+ self,+ config: GumroadSourceConfig,+ resumable_source_manager: ResumableSourceManager[GumroadResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return gumroad_source(+ access_token=config.access_token,+ 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,+ incremental_field=inputs.incremental_field,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.GUMROAD,category=DataWarehouseSourceCategory.E_COMMERCE,- label="Gumroad (Antiwork)",+ label="Gumroad",+ caption=(+ "Import sales, products, payouts, subscribers, reviews, offer codes, versions, and "+ "custom fields from your Gumroad account.\n\n"+ "Create an application under Settings > Advanced > Applications, then generate an "+ "access token for it. The token needs the `view_sales`, `view_payouts`, and "+ "`view_public` scopes."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/gumroad",iconPath="/static/services/gumroad.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ keywords=["antiwork", "creator", "digital products"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="access_token",+ label="Access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/tests/test_gumroad.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/tests/test_gumroad.pynew file mode 100644index 000000000000..9e7ac46cc8b2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/tests/test_gumroad.py@@ -0,0 +1,287 @@+from datetime import UTC, date, datetime+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, Mock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponseCursorPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.gumroad import (+ GumroadResumeConfig,+ _format_gumroad_date,+ _paginator_for,+ _rest_api_client_config,+ check_endpoint_permission,+ get_resource,+ gumroad_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.settings import GUMROAD_ENDPOINTS+++class _FakeDltResource:+ def __init__(self, name: str, rows: list[dict]) -> None:+ self.name = name+ self._rows = rows++ def add_map(self, mapper):+ self._rows = [mapper(dict(row)) for row in self._rows]+ return self++ def __iter__(self):+ return iter(self._rows)+++def _response(body: dict[str, Any]) -> Mock:+ response = Mock()+ response.json.return_value = body+ return response+++class TestGumroadTransport:+ @parameterized.expand(+ [+ # Gumroad rejects anything that isn't YYYY-MM-DD with a 400, so an ISO datetime+ # watermark has to be truncated to its date before it reaches the `after` param.+ ("naive_datetime", datetime(2026, 3, 1, 12, 30, 45, 999999), "2026-03-01"),+ ("aware_datetime", datetime(2026, 3, 1, 23, 59, 59, tzinfo=UTC), "2026-03-01"),+ ("date", date(2026, 3, 1), "2026-03-01"),+ ("passthrough_string", "1970-01-01", "1970-01-01"),+ ]+ )+ def test_format_gumroad_date(self, _name, value, expected) -> None:+ assert _format_gumroad_date(value) == expected++ def test_page_key_paginator_round_trips_cursor(self) -> None:+ resource = cast(dict[str, Any], get_resource("sales", should_use_incremental_field=False))+ paginator = resource["endpoint"]["paginator"]+ assert isinstance(paginator, JSONResponseCursorPaginator)++ request = Mock()+ request.params = {}+ paginator.update_state(_response({"success": True, "sales": [], "next_page_key": "cursor-2"}), data=[{}])+ assert paginator.has_next_page is True+ paginator.update_request(request)+ assert request.params["page_key"] == "cursor-2"++ # A response without `next_page_key` is the last page.+ paginator.update_state(_response({"success": True, "sales": []}), data=[{}])+ assert paginator.has_next_page is False++ @parameterized.expand(+ [+ ("sales", JSONResponseCursorPaginator),+ ("products", JSONResponseCursorPaginator),+ ("payouts", JSONResponseCursorPaginator),+ ("subscribers", JSONResponseCursorPaginator),+ ("product_reviews", JSONResponseCursorPaginator),+ # These return the whole collection in one response and never emit `next_page_key`.+ ("offer_codes", SinglePagePaginator),+ ("variant_categories", SinglePagePaginator),+ ("custom_fields", SinglePagePaginator),+ ]+ )+ def test_paginator_matches_endpoint_pagination(self, endpoint, expected_type) -> None:+ assert isinstance(_paginator_for(GUMROAD_ENDPOINTS[endpoint]), expected_type)++ def test_payouts_request_excludes_upcoming(self) -> None:+ # Upcoming payouts are returned with a null id, which would break the primary key.+ resource = cast(dict[str, Any], get_resource("payouts", should_use_incremental_field=False))+ assert resource["endpoint"]["params"] == {"include_upcoming": "false"}++ @parameterized.expand([("sales",), ("payouts",)])+ def test_incremental_resource_uses_after_window(self, endpoint) -> None:+ resource = cast(dict[str, Any], get_resource(endpoint, should_use_incremental_field=True))+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}+ incremental = resource["endpoint"]["incremental"]+ assert incremental["start_param"] == "after"+ assert incremental["cursor_path"] == "created_at"+ assert incremental["convert"] is _format_gumroad_date++ @parameterized.expand([("sales",), ("payouts",), ("products",)])+ def test_full_refresh_resource_sends_no_window(self, endpoint) -> None:+ resource = cast(dict[str, Any], get_resource(endpoint, should_use_incremental_field=False))+ assert resource["write_disposition"] == "replace"+ assert "incremental" not in resource["endpoint"]++ def test_products_has_no_incremental_window_even_when_requested(self) -> None:+ # The product payload carries no timestamp, so there is nothing to filter on.+ resource = cast(dict[str, Any], get_resource("products", should_use_incremental_field=True))+ assert resource["write_disposition"] == "replace"+ assert "incremental" not in resource["endpoint"]++ def test_get_resource_rejects_fanout_endpoint(self) -> None:+ with pytest.raises(ValueError, match="Fan-out endpoint"):+ get_resource("offer_codes", should_use_incremental_field=False)++ @parameterized.expand(+ [+ ("sales", ["id"], "created_at"),+ ("products", ["id"], None),+ ("payouts", ["id"], "created_at"),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.gumroad.rest_api_resource")+ def test_top_level_source_response_shape(self, endpoint, primary_keys, partition_key, _mock) -> None:+ response = gumroad_source(access_token="tok", endpoint=endpoint, team_id=1, job_id="job-1")+ assert response.primary_keys == primary_keys+ # Every Gumroad list endpoint orders created_at DESC with no way to reverse it.+ assert response.sort_mode == "desc"+ assert response.partition_keys == ([partition_key] if partition_key else None)++ @parameterized.expand(+ [+ ("offer_codes", ["product_id", "id"]),+ ("variant_categories", ["product_id", "id"]),+ ("custom_fields", ["product_id", "id"]),+ ("product_reviews", ["product_id", "id"]),+ ("subscribers", ["id"]),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.gumroad.build_dependent_resource")+ def test_fanout_primary_keys_are_unique_table_wide(self, endpoint, primary_keys, mock_build) -> None:+ # Universal offer codes and global custom fields are repeated under every product they+ # apply to, so the parent product id has to be part of the key.+ mock_build.return_value = iter([])+ response = gumroad_source(access_token="tok", endpoint=endpoint, team_id=1, job_id="job-1")+ assert response.primary_keys == primary_keys++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_offer_codes_fanout_row_carries_product_id(self, mock_rest_api_resources) -> None:+ mock_rest_api_resources.return_value = [+ _FakeDltResource("products", [{"id": "prod_1", "name": "Product"}]),+ _FakeDltResource("offer_codes", [{"id": "code_1", "name": "LAUNCH", "_products_id": "prod_1"}]),+ ]++ response = gumroad_source(access_token="tok", endpoint="offer_codes", team_id=1, job_id="job-1")++ rows = list(cast(Any, response.items()))+ assert rows == [{"id": "code_1", "name": "LAUNCH", "product_id": "prod_1"}]++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.gumroad.build_dependent_resource")+ def test_fanout_wiring(self, mock_build) -> None:+ mock_build.return_value = iter([])++ gumroad_source(access_token="tok", endpoint="subscribers", team_id=1, job_id="job-1")++ kwargs = mock_build.call_args.kwargs+ # Gumroad list endpoints take no page-size parameter; sending one would be undocumented.+ assert kwargs["page_size_param"] is None+ assert kwargs["parent_endpoint_extra"]["data_selector"] == "products"+ assert kwargs["child_endpoint_extra"]["data_selector"] == "subscribers"+ # Without `paginated=true` the subscribers endpoint returns the entire collection in one+ # response and never emits a cursor.+ assert kwargs["fanout"].child_params == {"paginated": "true"}+ assert kwargs["fanout"].parent_name == "products"+ assert kwargs["fanout"].resolve_param == "product_id"++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.gumroad.rest_api_resource")+ def test_resume_state_seeds_paginator_cursor(self, mock_rest_api_resource) -> None:+ manager = MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = GumroadResumeConfig(page_key="cursor-9")++ gumroad_source(+ access_token="tok",+ endpoint="sales",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )++ assert mock_rest_api_resource.call_args.kwargs["initial_paginator_state"] == {"cursor": "cursor-9"}++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.gumroad.rest_api_resource")+ def test_resume_hook_saves_only_a_real_next_cursor(self, mock_rest_api_resource) -> None:+ manager = MagicMock()+ manager.can_resume.return_value = False++ gumroad_source(+ access_token="tok",+ endpoint="sales",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )++ resume_hook = mock_rest_api_resource.call_args.kwargs["resume_hook"]+ resume_hook({"cursor": "cursor-3"})+ assert manager.save_state.call_args.args[0] == GumroadResumeConfig(page_key="cursor-3")++ manager.save_state.reset_mock()+ resume_hook(None)+ resume_hook({})+ resume_hook({"cursor": None})+ manager.save_state.assert_not_called()++ @parameterized.expand(+ [+ (200, True, None),+ (401, False, "rejected the access token"),+ (403, False, "rejected the access token"),+ (500, False, "unexpected status code"),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.gumroad.make_tracked_session")+ def test_validate_credentials_status_mapping(self, status, expected_valid, message_fragment, mock_session) -> None:+ mock_session.return_value.get.return_value = Mock(status_code=status)++ is_valid, message = validate_credentials("gumroad-token")++ assert is_valid is expected_valid+ if message_fragment is None:+ assert message is None+ else:+ assert message is not None and message_fragment in message++ call = mock_session.return_value.get.call_args+ # `/v2/user` is readable by every scope Gumroad issues, so a failure here is the token+ # itself rather than a missing scope.+ assert call.args[0] == "https://api.gumroad.com/v2/user"+ assert call.kwargs["headers"]["Authorization"] == "Bearer gumroad-token"+ # The probe must refuse redirects so a 3xx can't replay the bearer token off-host.+ assert mock_session.call_args.kwargs["allow_redirects"] is False+ assert mock_session.call_args.kwargs["redact_values"] == ("gumroad-token",)++ @parameterized.expand(+ [+ (200, True),+ (403, False),+ # A 401 means the whole token is bad, and a 500 is transient — neither is a scope+ # problem, so neither should be reported to the user as one.+ (401, True),+ (500, True),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.gumroad.make_tracked_session")+ def test_check_endpoint_permission_only_treats_403_as_denial(self, status, expected, mock_session) -> None:+ mock_session.return_value.get.return_value = Mock(status_code=status)+ assert check_endpoint_permission("gumroad-token", "/v2/sales") is expected++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.gumroad.make_tracked_session")+ def test_probe_transport_error_does_not_leak_out(self, mock_session) -> None:+ # A DNS/connection failure isn't a permission problem, so it must not raise out of the+ # schema picker / source creation path: the endpoint stays "reachable" and validation+ # reports a connectivity problem rather than blaming the token.+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")++ assert check_endpoint_permission("gumroad-token", "/v2/sales") is True++ is_valid, message = validate_credentials("gumroad-token")+ assert is_valid is False+ assert message is not None and "reach Gumroad" in message++ def test_rest_client_config_pins_host_and_blocks_redirects(self) -> None:+ # A redirect off the Gumroad host would otherwise replay the bearer token.+ config = _rest_api_client_config("gumroad-token")+ assert config["allowed_hosts"] == []+ assert config["allow_redirects"] is False+ assert config["auth"] == {"type": "bearer", "token": "gumroad-token"}+ assert config["base_url"] == "https://api.gumroad.com"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/tests/test_gumroad_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/tests/test_gumroad_source.pynew file mode 100644index 000000000000..31f67da1017f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/tests/test_gumroad_source.py@@ -0,0 +1,187 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.gumroad import (+ GumroadSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.gumroad import GumroadResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.settings import (+ ENDPOINTS,+ GUMROAD_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.source import GumroadSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++INCREMENTAL_ENDPOINTS = {"sales", "payouts"}+++class TestGumroadSource:+ def setup_method(self) -> None:+ self.source = GumroadSource()+ self.team_id = 123+ self.config = GumroadSourceConfig(access_token="gumroad-token")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.GUMROAD++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Gumroad"+ assert config.category == DataWarehouseSourceCategory.E_COMMERCE+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/gumroad.png"+ # The source ships visible — a truthy unreleasedSource hides it from every user.+ assert not config.unreleasedSource++ def test_access_token_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ assert [f.name for f in config.fields] == ["access_token"]+ field = config.fields[0]+ assert isinstance(field, SourceFieldInputConfig)+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_pinned_version_matches_the_paths_the_code_calls(self) -> None:+ assert self.source.default_version == "v2"+ assert self.source.supported_versions == ("v2",)+ assert all(config.path.startswith("/v2/") for config in GUMROAD_ENDPOINTS.values())++ def test_get_schemas_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize("name", sorted(ENDPOINTS))+ def test_get_schemas_incremental_semantics(self, name: str) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == name)++ # Only /sales and /payouts take a server-side `after` filter; everything else would have+ # to page the whole collection, which is a full refresh in disguise.+ if name in INCREMENTAL_ENDPOINTS:+ assert schema.supports_incremental is True+ assert [f["field"] for f in schema.incremental_fields] == ["created_at"]+ else:+ assert schema.supports_incremental is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["sales"])+ assert [s.name for s in schemas] == ["sales"]++ @pytest.mark.parametrize(+ "name,expected_keys",+ [+ ("sales", ["id"]),+ ("products", ["id"]),+ ("payouts", ["id"]),+ ("subscribers", ["id"]),+ # Universal offer codes and global custom fields are listed under every product they+ # apply to, so the parent id has to be in the key or the rows collide.+ ("offer_codes", ["product_id", "id"]),+ ("custom_fields", ["product_id", "id"]),+ ("variant_categories", ["product_id", "id"]),+ ("product_reviews", ["product_id", "id"]),+ ],+ )+ def test_primary_keys(self, name: str, expected_keys: list[str]) -> None:+ assert GUMROAD_ENDPOINTS[name].primary_key == expected_keys++ @pytest.mark.parametrize(+ "observed_error,expect_match",+ [+ ("401 Client Error: Unauthorized for url: https://api.gumroad.com/v2/sales", True),+ ("403 Client Error: Forbidden for url: https://api.gumroad.com/v2/payouts", True),+ ("500 Server Error: Internal Server Error for url: https://api.gumroad.com/v2/sales", False),+ ],+ )+ def test_non_retryable_errors_match_auth_failures_only(self, observed_error: str, expect_match: bool) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable) is expect_match++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.source.validate_gumroad_credentials"+ )+ def test_validate_credentials_plumbs_access_token(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)+ assert mock_validate.call_args.args == ("gumroad-token",)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.source.check_endpoint_permission"+ )+ def test_get_endpoint_permissions_reports_missing_scope_per_table(self, mock_probe: mock.MagicMock) -> None:+ # A token can hold view_public without view_payouts, and the user needs to see which+ # table that costs them rather than having source creation fail.+ mock_probe.side_effect = lambda _token, path: path != "/v2/payouts"++ results = self.source.get_endpoint_permissions(+ self.config, self.team_id, ["sales", "payouts", "products", "offer_codes"]+ )++ assert results["sales"] is None+ assert results["products"] is None+ assert results["offer_codes"] is None+ assert results["payouts"] is not None and "view_payouts" in results["payouts"]++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.source.check_endpoint_permission"+ )+ def test_get_endpoint_permissions_probes_each_path_once(self, mock_probe: mock.MagicMock) -> None:+ # All four product-scoped tables share one probe path; probing per table would issue a+ # request per row of the schema picker.+ mock_probe.return_value = True++ self.source.get_endpoint_permissions(+ self.config, self.team_id, ["products", "offer_codes", "custom_fields", "variant_categories"]+ )++ assert [call.args[1] for call in mock_probe.call_args_list] == ["/v2/products"]++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert manager._data_class is GumroadResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.source.gumroad_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_gumroad_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "sales"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"+ inputs.should_use_incremental_field = True+ inputs.incremental_field = "created_at"+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_gumroad_source.call_args.kwargs+ assert kwargs["access_token"] == "gumroad-token"+ assert kwargs["endpoint"] == "sales"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["incremental_field"] == "created_at"+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.gumroad.source.gumroad_source")+ def test_source_for_pipeline_omits_watermark_when_not_incremental(+ self, mock_gumroad_source: mock.MagicMock+ ) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "sales"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_gumroad_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_canonical_descriptions_cover_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)