Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement paperform import source (#69382)

Tom Owers8d7ac1be2c82
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index c07ad3a23eb3..9e67752a08a4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -262,6 +262,7 @@ the row lists both.
| optimizely | HTTP | requests | ✅ |
| pagerduty | HTTP | requests | ✅ |
| pandadoc | HTTP | requests | ✅ |
+| paperform | HTTP | requests | ✅ |
| papersign | HTTP | requests | ✅ |
| partnerize | HTTP | requests | ✅ |
| partnerstack | HTTP | requests | ✅ |
@@ -626,7 +627,6 @@ doesn't conflict with concurrent PRs.
- oveit
- pabbly_subscriptions_billing
- pagerduty
-- paperform
- pardot
- payfit
- paylocity
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 0450effc4a65..83868d7389cd 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
@@ -2491,7 +2491,7 @@ class PandaDocSourceConfig(config.Config):
@config.config
class PaperformSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paperform/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paperform/canonical_descriptions.py
new file mode 100644
index 000000000000..5c99d875d152
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paperform/canonical_descriptions.py
@@ -0,0 +1,121 @@
+"""Canonical, documentation-sourced descriptions for Paperform endpoints and columns.
+
+Sourced from the official Paperform API reference (https://paperform.readme.io). Keyed by the
+endpoint names in `settings.py` `PAPERFORM_ENDPOINTS`, which match the `ExternalDataSchema.name` of
+a synced Paperform table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "forms": {
+ "description": "A Paperform form with its slugs, sharing URLs, tags, and submission count.",
+ "docs_url": "https://paperform.readme.io/reference/listforms",
+ "columns": {
+ "id": "Unique identifier of the form.",
+ "slug": "The default generated slug for the form.",
+ "custom_slug": "The custom slug for the form if set.",
+ "space_id": "ID of the space which contains the form.",
+ "title": "The title of the form.",
+ "description": "The description of the form.",
+ "cover_image_url": "The cover image for the form.",
+ "url": "The main sharing URL for the form.",
+ "additional_urls": "Additional URLs for the form.",
+ "live": "Whether the form is currently accepting submissions.",
+ "tags": "The tags assigned to the form.",
+ "submission_count": "The number of submissions the form has received.",
+ "created_at": "Time the form was created, in the account timezone.",
+ "updated_at": "Time the form was last updated, in the account timezone.",
+ "account_timezone": "The configured timezone for the account.",
+ "created_at_utc": "Time the form was created, in UTC.",
+ "updated_at_utc": "Time the form was last updated, in UTC.",
+ },
+ },
+ "form_fields": {
+ "description": "A field (question) on a Paperform form, such as a text input, dropdown, or signature.",
+ "docs_url": "https://paperform.readme.io/reference/listformfields",
+ "columns": {
+ "form_id": "ID of the form this field belongs to.",
+ "key": "The unique key for this field within its form.",
+ "custom_key": "The custom key of this field.",
+ "title": "The title of this field.",
+ "description": "The description of this field.",
+ "required": "Whether this field is required.",
+ "placeholder": "The placeholder for this field.",
+ "type": "The type of field (e.g. text, email, choices, signature).",
+ },
+ },
+ "submissions": {
+ "description": "A completed submission to a Paperform form, including the answers, device, and any charge.",
+ "docs_url": "https://paperform.readme.io/reference/listformsubmissions",
+ "columns": {
+ "id": "Unique identifier of the submission.",
+ "form_id": "ID of the form for the submission.",
+ "data": "The answers from the form, keyed by field key.",
+ "device": "Information about the device which made the submission.",
+ "charge": "Details of any payment charged with the submission.",
+ "pdfs": "The PDFs generated for the submission.",
+ "created_at": "Time the submission was made, in the account timezone.",
+ "account_timezone": "The configured timezone for the account.",
+ "created_at_utc": "Time the submission was made, in UTC.",
+ },
+ },
+ "partial_submissions": {
+ "description": "An in-progress (not yet submitted) response to a Paperform form, with the answers so far.",
+ "docs_url": "https://paperform.readme.io/reference/listformpartialsubmissions",
+ "columns": {
+ "id": "Unique identifier of the partial submission.",
+ "form_id": "ID of the form for the partial submission.",
+ "data": "The answers so far, keyed by field key.",
+ "last_answered": "The last field the respondent answered.",
+ "submitted_at": "Time the partial submission was completed, if it was, in the account timezone.",
+ "created_at": "Time the partial submission was created, in the account timezone.",
+ "updated_at": "Time the partial submission was last updated, in the account timezone.",
+ "account_timezone": "The configured timezone for the account.",
+ "submitted_at_utc": "Time the partial submission was completed, if it was, in UTC.",
+ "created_at_utc": "Time the partial submission was created, in UTC.",
+ "updated_at_utc": "Time the partial submission was last updated, in UTC.",
+ },
+ },
+ "products": {
+ "description": "A product sold through a Paperform form's payment fields.",
+ "docs_url": "https://paperform.readme.io/reference/listformproducts",
+ "columns": {
+ "form_id": "ID of the form this product belongs to.",
+ "SKU": "Product SKU, unique within its form.",
+ "name": "Product name.",
+ "price": "Product price.",
+ "quantity": "Product quantity available.",
+ "minimum": "Minimum number of this product that can be selected.",
+ "maximum": "Maximum number of this product that can be selected.",
+ },
+ },
+ "coupons": {
+ "description": "A discount coupon configured on a Paperform form.",
+ "docs_url": "https://paperform.readme.io/reference/listformcoupons",
+ "columns": {
+ "form_id": "ID of the form this coupon belongs to.",
+ "code": "The coupon code, unique within its form.",
+ "enabled": "Whether the coupon is enabled.",
+ "target": "The target of the coupon (price or subscription).",
+ "discountAmount": "The discount as an amount.",
+ "discountPercentage": "The discount as a percentage.",
+ "expiresAt": "The date and time when the coupon expires.",
+ },
+ },
+ "spaces": {
+ "description": "A Paperform space used to organize forms. Requires a Business or Agency plan.",
+ "docs_url": "https://paperform.readme.io/reference/listspaces",
+ "columns": {
+ "id": "Unique identifier of the space.",
+ "name": "The name of the space.",
+ "created_at": "Time the space was created, in the account timezone.",
+ "updated_at": "Time the space was last updated, in the account timezone.",
+ "account_timezone": "The configured timezone for the account.",
+ "created_at_utc": "Time the space was created, in UTC.",
+ "updated_at_utc": "Time the space was last updated, in UTC.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paperform/paperform.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paperform/paperform.py
new file mode 100644
index 000000000000..fff71fc6c0d5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paperform/paperform.py
@@ -0,0 +1,307 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.paperform.settings import (
+ PAPERFORM_ENDPOINTS,
+ PaperformEndpointConfig,
+)
+
+PAPERFORM_BASE_URL = "https://api.paperform.co/v1"
+# Paginated list endpoints cap `limit` at 100 (default 20); the largest page minimises round trips
+# against the 60 req/min rate limit.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+# Cheap endpoint used to confirm an API key is genuine. The key is account-wide, so one probe
+# validates the credential for every Standard API endpoint.
+DEFAULT_PROBE_PATH = "/forms"
+
+
+class PaperformRetryableError(Exception):
+ pass
+
+
+class PaperformResumeConfig:
+ # `after_id` cursor for the next page to fetch. None starts a list at its first page.
+ cursor: str | None = None
+ # The form currently being processed. A stable form-ID bookmark (not a positional index) so a
+ # form added or removed between a crash and the retry can't resume us into the wrong form. None
+ # for the account-level endpoints (forms, spaces).
+ form_id: str | None = None
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}
+
+
+def _format_after_date(value: Any) -> str:
+ """Format the incremental watermark for Paperform's `after_date` filter (UTC ISO 8601).
+
+ Truncates to whole seconds, which rounds the lower bound *down* — so a sync re-fetches at most
+ a few boundary rows (the merge dedupes them on the primary key) rather than skipping any.
+ """
+ normalized_value = coerce_datetime_to_utc(value)
+ if normalized_value is None:
+ return str(value)
+ return normalized_value.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _page_params(cursor: str | None, after_date: str | None) -> dict[str, Any]:
+ # Ascending creation order keeps already-fetched pages stable while new rows arrive (they only
+ # ever append) and matches the pipeline's ascending incremental watermark bookkeeping.
+ params: dict[str, Any] = {"limit": PAGE_SIZE, "sort": "ASC"}
+ if cursor is not None:
+ # The API documents `after_date` as overwritten by `after_id`, so only the first page
+ # carries the watermark; later pages advance purely on the id cursor.
+ params["after_id"] = cursor
+ elif after_date is not None:
+ params["after_date"] = after_date
+ return params
+
+
+@retry(
+ retry=retry_if_exception_type((PaperformRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ path: str,
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ response = session.get(
+ f"{PAPERFORM_BASE_URL}{path}",
+ params=params,
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ # Paperform rate-limits at 60 req/min and returns 429 with rate-limit headers; exponential
+ # backoff comfortably outlasts the one-minute window.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise PaperformRetryableError(f"Paperform API error (retryable): status={response.status_code}, path={path}")
+
+ if not response.ok:
+ logger.error(f"Paperform API error: status={response.status_code}, body={response.text}, path={path}")
+ response.raise_for_status()
+
+ data = response.json()
+ if not isinstance(data, dict):
+ raise PaperformRetryableError(f"Paperform returned an unexpected payload for {path}: {type(data).__name__}")
+
+ return data
+
+
+def _extract_rows(data: dict[str, Any], config: PaperformEndpointConfig, path: str) -> list[dict[str, Any]]:
+ # Every list endpoint wraps rows as {"results": {"<resource>": [...]}, "has_more": bool, ...}.
+ results = data.get("results")
+ if not isinstance(results, dict) or not isinstance(results.get(config.results_key), list):
+ raise PaperformRetryableError(f"Paperform returned an unexpected 'results' payload for {path}")
+ return results[config.results_key]
+
+
+def _iter_pages(
+ session: requests.Session,
+ config: PaperformEndpointConfig,
+ path: str,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[PaperformResumeConfig],
+ start_cursor: str | None,
+ after_date: str | None,
+ form_id: str | None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Page through a paginated list endpoint, yielding one page of raw rows at a time.
+
+ Saves resume state AFTER yielding each page (pointing at the next page) so a crash re-fetches
+ the in-flight page rather than skipping it — the merge dedupes the re-pulled rows on the
+ primary key.
+ """
+ cursor = start_cursor
+ while True:
+ data = _fetch_page(session, path, _page_params(cursor, after_date), logger)
+ items = _extract_rows(data, config, path)
+
+ if items:
+ yield items
+
+ # `has_more` is false (or the page came back empty) once we've reached the end of the list.
+ if not data.get("has_more") or not items:
+ break
+
+ cursor = str(items[-1]["id"])
+ manager.save_state(PaperformResumeConfig(cursor=cursor, form_id=form_id))
+
+
+def _iter_form_ids(session: requests.Session, logger: FilteringBoundLogger) -> Iterator[str]:
+ """Page through /forms and yield each form id, for fanning out form-scoped endpoints."""
+ cursor: str | None = None
+ while True:
+ data = _fetch_page(session, "/forms", _page_params(cursor, after_date=None), logger)
+ items = _extract_rows(data, PAPERFORM_ENDPOINTS["forms"], "/forms")
+ for item in items:
+ yield str(item["id"])
+ if not data.get("has_more") or not items:
+ break
+ cursor = str(items[-1]["id"])
+
+
+def _get_top_level_rows(
+ session: requests.Session,
+ config: PaperformEndpointConfig,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[PaperformResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ resume = manager.load_state() if manager.can_resume() else None
+ start_cursor = resume.cursor if resume else None
+ yield from _iter_pages(session, config, config.path, logger, manager, start_cursor, after_date=None, form_id=None)
+
+
+def _get_form_scoped_rows(
+ session: requests.Session,
+ config: PaperformEndpointConfig,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[PaperformResumeConfig],
+ after_date: str | None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Fan a form-scoped endpoint out over every form, injecting `form_id` into each row.
+
+ Fields, products, and coupons don't carry their form id in the response, so we add it here to
+ keep the composite ["form_id", ...] key unique across the whole table. Submissions already
+ include `form_id` — the payload value wins over the injected one.
+ """
+ form_ids = list(_iter_form_ids(session, logger))
+
+ # Resolve the saved form-ID bookmark to the slice of forms still to process. If the bookmarked
+ # form no longer exists (deleted between runs), start over — merge dedupes the re-pulled rows.
+ resume = manager.load_state() if manager.can_resume() else None
+ remaining = form_ids
+ resume_cursor: str | None = None
+ if resume is not None and resume.form_id is not None and resume.form_id in form_ids:
+ remaining = form_ids[form_ids.index(resume.form_id) :]
+ resume_cursor = resume.cursor
+ logger.debug(f"Paperform: resuming {config.name} from form_id={resume.form_id}, cursor={resume_cursor}")
+
+ for index, form_id in enumerate(remaining):
+ path = config.path.format(form_id=form_id)
+ start_cursor = resume_cursor # only the resumed-into form uses the saved cursor
+ resume_cursor = None
+
+ if config.paginated:
+ for items in _iter_pages(session, config, path, logger, manager, start_cursor, after_date, form_id):
+ yield [{"form_id": form_id, **item} for item in items]
+ else:
+ # Fields, products, and coupons return the whole collection in one response.
+ data = _fetch_page(session, path, {}, logger)
+ items = _extract_rows(data, config, path)
+ if items:
+ yield [{"form_id": form_id, **item} for item in items]
+
+ # Advance the bookmark to the next form so a crash between forms resumes correctly. Its
+ # first page is fetched fresh (cursor=None).
+ if index + 1 < len(remaining):
+ manager.save_state(PaperformResumeConfig(cursor=None, form_id=remaining[index + 1]))
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PaperformResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = PAPERFORM_ENDPOINTS[endpoint]
+ # One session reused across every page (and every form, for fan-out) so urllib3 keeps the
+ # connection alive instead of re-handshaking per request. The API key is redacted from logs.
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+
+ after_date: str | None = None
+ if should_use_incremental_field and config.incremental_fields and db_incremental_field_last_value is not None:
+ after_date = _format_after_date(db_incremental_field_last_value)
+
+ if config.form_scoped:
+ yield from _get_form_scoped_rows(session, config, logger, resumable_source_manager, after_date)
+ else:
+ yield from _get_top_level_rows(session, config, logger, resumable_source_manager)
+
+
+def paperform_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PaperformResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = PAPERFORM_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ # We request `sort=ASC` (creation order) on every paginated endpoint, so rows arrive
+ # oldest-first within each form and the ascending watermark bookkeeping is correct.
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single endpoint to validate the API key.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+ try:
+ response = session.get(f"{PAPERFORM_BASE_URL}{path}", params={"limit": 1}, timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to Paperform: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Paperform returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ status, message = check_access(api_key)
+ if status == 200:
+ return True, None
+ if status == 401:
+ return False, "Invalid Paperform API key"
+ if status == 403:
+ # The key authenticated but the account can't use the API — Paperform gates API access
+ # behind its paid plans.
+ return (
+ False,
+ "Your Paperform plan does not include API access. API access requires a Pro, Business, or Agency plan.",
+ )
+ return False, message or "Could not validate Paperform API key"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paperform/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paperform/settings.py
new file mode 100644
index 000000000000..289a930d1410
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paperform/settings.py
@@ -0,0 +1,109 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# `created_at` / `updated_at` are rendered in the account's local timezone; the `_utc` variants are
+# proper UTC ISO 8601 strings, so those are what we cursor and partition on.
+CREATED_AT_UTC_INCREMENTAL: IncrementalField = {
+ "label": "created_at_utc",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at_utc",
+ "field_type": IncrementalFieldType.DateTime,
+}
+
+
+@dataclass
+class PaperformEndpointConfig:
+ name: str
+ # Path under the v1 base URL. Form-scoped endpoints carry a `{form_id}` placeholder that the
+ # transport fills in per form while fanning out.
+ path: str
+ # Key inside the response's `results` object that holds the row array,
+ # e.g. {"results": {"submissions": [...]}, "has_more": true}.
+ results_key: str = ""
+ # Form-scoped endpoints live under /forms/{slug_or_id}/... and must be iterated once per form.
+ form_scoped: bool = False
+ # Whether the endpoint accepts limit/after_id/sort pagination params. Fields, products, and
+ # coupons return the whole collection in one response (their only query param is `search`).
+ paginated: bool = True
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Only submissions expose a server-side creation-time filter (`after_date`) worth cursoring on.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable creation timestamp used for datetime partitioning; None disables partitioning.
+ partition_key: str | None = None
+
+
+# Paperform v1 API (https://paperform.readme.io). Most resources hang off a form, so the transport
+# lists forms once and fans the form-scoped endpoints out per form, injecting `form_id` into every
+# row to keep composite keys unique across the whole table.
+#
+# Incremental sync: list endpoints filter with `after_date` on creation time only, so it's a safe
+# cursor solely for immutable rows. Submissions never change once made -> incremental. Partial
+# submissions keep mutating after creation (`last_answered`, `updated_at`, `submitted_at`) and forms
+# are edited in place, so a creation-time cursor would freeze their updates -> full refresh only.
+PAPERFORM_ENDPOINTS: dict[str, PaperformEndpointConfig] = {
+ "forms": PaperformEndpointConfig(
+ name="forms",
+ path="/forms",
+ results_key="forms",
+ partition_key="created_at_utc",
+ ),
+ "form_fields": PaperformEndpointConfig(
+ name="form_fields",
+ path="/forms/{form_id}/fields",
+ results_key="fields",
+ form_scoped=True,
+ paginated=False,
+ # A field's `key` is only unique within its form.
+ primary_keys=["form_id", "key"],
+ ),
+ "submissions": PaperformEndpointConfig(
+ name="submissions",
+ path="/forms/{form_id}/submissions",
+ results_key="submissions",
+ form_scoped=True,
+ # Submission ids are UUIDs but the docs don't state global uniqueness, so keep the parent
+ # form id in the key.
+ primary_keys=["form_id", "id"],
+ incremental_fields=[CREATED_AT_UTC_INCREMENTAL],
+ partition_key="created_at_utc",
+ ),
+ "partial_submissions": PaperformEndpointConfig(
+ name="partial_submissions",
+ path="/forms/{form_id}/partial-submissions",
+ results_key="partial-submissions",
+ form_scoped=True,
+ primary_keys=["form_id", "id"],
+ partition_key="created_at_utc",
+ ),
+ "products": PaperformEndpointConfig(
+ name="products",
+ path="/forms/{form_id}/products",
+ results_key="products",
+ form_scoped=True,
+ paginated=False,
+ # A product's SKU is only unique within its form.
+ primary_keys=["form_id", "SKU"],
+ ),
+ "coupons": PaperformEndpointConfig(
+ name="coupons",
+ path="/forms/{form_id}/coupons",
+ results_key="coupons",
+ form_scoped=True,
+ paginated=False,
+ # A coupon's code is only unique within its form.
+ primary_keys=["form_id", "code"],
+ ),
+ "spaces": PaperformEndpointConfig(
+ name="spaces",
+ path="/spaces",
+ results_key="spaces",
+ partition_key="created_at_utc",
+ ),
+}
+
+ENDPOINTS = tuple(PAPERFORM_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in PAPERFORM_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paperform/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paperform/source.py
index e07a28ec9447..b1bcdd591b6a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/paperform/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paperform/source.py
@@ -1,19 +1,42 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PaperformSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.paperform.paperform import (
+ PaperformResumeConfig,
+ paperform_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.paperform.settings import (
+ INCREMENTAL_FIELDS,
+ PAPERFORM_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class PaperformSource(SimpleSource[PaperformSourceConfig]):
+class PaperformSource(ResumableSource[PaperformSourceConfig, PaperformResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.PAPERFORM
@@ -24,7 +47,91 @@ class PaperformSource(SimpleSource[PaperformSourceConfig]):
name=SchemaExternalDataSourceType.PAPERFORM,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="Paperform",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Paperform API key to pull your forms and submissions data into the PostHog Data warehouse.
+
+You can create an API key under **Account → Developer** in [Paperform](https://paperform.co). API access requires a Pro, Business, or Agency plan, and the `spaces` table additionally requires a Business or Agency plan.
+""",
iconPath="/static/services/paperform.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/paperform",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
unreleasedSource=True,
)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.paperform.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.paperform.co": "Your Paperform API key is invalid or has been revoked. Generate a new key under Account → Developer, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.paperform.co": "Your Paperform plan does not include access to this data. API access requires a Pro, Business, or Agency plan, and the spaces table requires a Business or Agency plan.",
+ }
+
+ def get_schemas(
+ self,
+ config: PaperformSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas: list[SourceSchema] = []
+ for endpoint in PAPERFORM_ENDPOINTS:
+ if names is not None and endpoint not in names:
+ continue
+ incremental_fields = INCREMENTAL_FIELDS.get(endpoint, [])
+ supports_incremental = bool(incremental_fields)
+ schemas.append(
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=supports_incremental,
+ supports_append=supports_incremental,
+ incremental_fields=incremental_fields,
+ )
+ )
+ return schemas
+
+ def validate_credentials(
+ self, config: PaperformSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The API key is account-wide, so a single probe validates the credential for every schema.
+ return validate_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PaperformResumeConfig]:
+ return ResumableSourceManager[PaperformResumeConfig](inputs, PaperformResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: PaperformSourceConfig,
+ resumable_source_manager: ResumableSourceManager[PaperformResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in PAPERFORM_ENDPOINTS:
+ raise ValueError(f"Unknown Paperform schema '{inputs.schema_name}'")
+
+ return paperform_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ 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,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paperform/tests/test_paperform.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paperform/tests/test_paperform.py
new file mode 100644
index 000000000000..ef1d68e23f97
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paperform/tests/test_paperform.py
@@ -0,0 +1,338 @@
+from datetime import UTC, datetime
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.paperform import paperform
+from products.warehouse_sources.backend.temporal.data_imports.sources.paperform.paperform import (
+ PAGE_SIZE,
+ PaperformResumeConfig,
+ PaperformRetryableError,
+ _format_after_date,
+ check_access,
+ get_rows,
+ paperform_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.paperform.settings import (
+ ENDPOINTS,
+ PAPERFORM_ENDPOINTS,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = paperform._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: PaperformResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[PaperformResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> PaperformResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: PaperformResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _envelope(results_key: str, items: list[dict], has_more: bool = False) -> dict:
+ return {"status": "ok", "results": {results_key: items}, "has_more": has_more, "total": len(items)}
+
+
+class _FakeFetch:
+ """Dispatches on (path, after_id cursor) and records every call's params."""
+
+ def __init__(self, pages: dict[tuple[str, str | None], dict]) -> None:
+ self._pages = pages
+ self.calls: list[tuple[str, dict]] = []
+
+ def __call__(self, session: Any, path: str, params: dict, logger: Any) -> dict:
+ self.calls.append((path, params))
+ return self._pages[(path, params.get("after_id"))]
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ fetch: _FakeFetch,
+ endpoint: str,
+ **kwargs: Any,
+ ) -> list[dict]:
+ monkeypatch.setattr(paperform, "_fetch_page", fetch)
+ monkeypatch.setattr(paperform, "make_tracked_session", lambda **_: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_key="pf-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_top_level_single_page_yields_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ fetch = _FakeFetch({("/forms", None): _envelope("forms", [{"id": "f1"}, {"id": "f2"}])})
+ rows = self._collect(manager, monkeypatch, fetch, "forms")
+ assert rows == [{"id": "f1"}, {"id": "f2"}]
+ # has_more is false, so we stop without persisting resume state.
+ assert manager.saved == []
+
+ def test_top_level_follows_after_id_cursor_until_has_more_false(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ fetch = _FakeFetch(
+ {
+ ("/forms", None): _envelope("forms", [{"id": "f1"}, {"id": "f2"}], has_more=True),
+ ("/forms", "f2"): _envelope("forms", [{"id": "f3"}]),
+ }
+ )
+ rows = self._collect(manager, monkeypatch, fetch, "forms")
+ assert [r["id"] for r in rows] == ["f1", "f2", "f3"]
+ # State is saved after the first page (cursor advances to the last id), then we stop.
+ assert [(s.cursor, s.form_id) for s in manager.saved] == [("f2", None)]
+ # Every page requests the largest page size in stable ascending creation order.
+ assert all(p["limit"] == PAGE_SIZE and p["sort"] == "ASC" for _, p in fetch.calls)
+
+ def test_top_level_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(PaperformResumeConfig(cursor="f2"))
+ # The initial (cursor=None) page must never be fetched on resume.
+ fetch = _FakeFetch({("/forms", "f2"): _envelope("forms", [{"id": "f3"}])})
+ rows = self._collect(manager, monkeypatch, fetch, "forms")
+ assert rows == [{"id": "f3"}]
+
+ def test_fan_out_injects_form_id_and_bookmarks_next_form(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ fetch = _FakeFetch(
+ {
+ ("/forms", None): _envelope("forms", [{"id": "f1"}, {"id": "f2"}]),
+ ("/forms/f1/submissions", None): _envelope("submissions", [{"id": "s1"}, {"id": "s2"}], has_more=True),
+ ("/forms/f1/submissions", "s2"): _envelope("submissions", [{"id": "s3"}]),
+ ("/forms/f2/submissions", None): _envelope("submissions", [{"id": "s4"}]),
+ }
+ )
+ rows = self._collect(manager, monkeypatch, fetch, "submissions")
+ assert rows == [
+ {"form_id": "f1", "id": "s1"},
+ {"form_id": "f1", "id": "s2"},
+ {"form_id": "f1", "id": "s3"},
+ {"form_id": "f2", "id": "s4"},
+ ]
+ # Mid-form page cursor, then the bookmark advancing to the next form (fresh first page).
+ assert [(s.cursor, s.form_id) for s in manager.saved] == [("s2", "f1"), (None, "f2")]
+
+ def test_fan_out_resumes_from_bookmarked_form_and_cursor(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(PaperformResumeConfig(cursor="s9", form_id="f2"))
+ fetch = _FakeFetch(
+ {
+ ("/forms", None): _envelope("forms", [{"id": "f1"}, {"id": "f2"}]),
+ ("/forms/f2/submissions", "s9"): _envelope("submissions", [{"id": "s10"}]),
+ }
+ )
+ rows = self._collect(manager, monkeypatch, fetch, "submissions")
+ # f1 was fully processed before the crash and must not be re-fetched.
+ assert rows == [{"form_id": "f2", "id": "s10"}]
+
+ def test_fan_out_restarts_when_bookmarked_form_no_longer_exists(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(PaperformResumeConfig(cursor="s9", form_id="deleted-form"))
+ fetch = _FakeFetch(
+ {
+ ("/forms", None): _envelope("forms", [{"id": "f1"}]),
+ ("/forms/f1/submissions", None): _envelope("submissions", [{"id": "s1"}]),
+ }
+ )
+ rows = self._collect(manager, monkeypatch, fetch, "submissions")
+ assert rows == [{"form_id": "f1", "id": "s1"}]
+
+ def test_fan_out_non_paginated_endpoint_fetches_each_form_once(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ fetch = _FakeFetch(
+ {
+ ("/forms", None): _envelope("forms", [{"id": "f1"}, {"id": "f2"}]),
+ ("/forms/f1/products", None): _envelope("products", [{"SKU": "P-1"}]),
+ ("/forms/f2/products", None): _envelope("products", []),
+ }
+ )
+ rows = self._collect(manager, monkeypatch, fetch, "products")
+ assert rows == [{"form_id": "f1", "SKU": "P-1"}]
+ # Non-paginated child requests carry no pagination params.
+ product_calls = [params for path, params in fetch.calls if path.endswith("/products")]
+ assert product_calls == [{}, {}]
+
+ def test_incremental_watermark_only_on_first_page_of_each_form(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ fetch = _FakeFetch(
+ {
+ ("/forms", None): _envelope("forms", [{"id": "f1"}, {"id": "f2"}]),
+ ("/forms/f1/submissions", None): _envelope("submissions", [{"id": "s1"}], has_more=True),
+ ("/forms/f1/submissions", "s1"): _envelope("submissions", [{"id": "s2"}]),
+ ("/forms/f2/submissions", None): _envelope("submissions", []),
+ }
+ )
+ self._collect(
+ manager,
+ monkeypatch,
+ fetch,
+ "submissions",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 2, 3, 4, 5, 999999, tzinfo=UTC),
+ )
+ params_by_call = {(path, params.get("after_id")): params for path, params in fetch.calls}
+ # The forms listing that drives the fan-out is never date-filtered.
+ assert "after_date" not in params_by_call[("/forms", None)]
+ # Each form's first page carries the watermark (truncated down to whole seconds)...
+ assert params_by_call[("/forms/f1/submissions", None)]["after_date"] == "2024-01-02T03:04:05Z"
+ assert params_by_call[("/forms/f2/submissions", None)]["after_date"] == "2024-01-02T03:04:05Z"
+ # ...and later pages advance purely on after_id (the API ignores after_date alongside it).
+ assert "after_date" not in params_by_call[("/forms/f1/submissions", "s1")]
+
+ def test_full_refresh_ignores_stale_watermark(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ fetch = _FakeFetch(
+ {
+ ("/forms", None): _envelope("forms", [{"id": "f1"}]),
+ ("/forms/f1/partial-submissions", None): _envelope("partial-submissions", [{"id": "p1"}]),
+ }
+ )
+ # partial_submissions declares no incremental fields, so a leftover watermark must not filter.
+ self._collect(
+ manager,
+ monkeypatch,
+ fetch,
+ "partial_submissions",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ )
+ assert all("after_date" not in params for _, params in fetch.calls)
+
+
+class TestFormatAfterDate:
+ @parameterized.expand(
+ [
+ ("aware_datetime", datetime(2024, 5, 6, 7, 8, 9, 123456, tzinfo=UTC), "2024-05-06T07:08:09Z"),
+ ("naive_datetime_assumed_utc", datetime(2024, 5, 6, 7, 8, 9), "2024-05-06T07:08:09Z"),
+ ("string_passthrough", "2024-05-06T07:08:09Z", "2024-05-06T07:08:09Z"),
+ ]
+ )
+ def test_formats_watermark(self, _name: str, value: Any, expected: str) -> None:
+ assert _format_after_date(value) == expected
+
+
+class TestFetchPage:
+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else _envelope("forms", [])
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(PaperformRetryableError):
+ _fetch_page_unwrapped(session, "/forms", {}, MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, "/forms", {}, MagicMock())
+
+ def test_non_dict_body_is_retryable(self) -> None:
+ session = self._session_returning(200, [{"id": "f1"}])
+ with pytest.raises(PaperformRetryableError):
+ _fetch_page_unwrapped(session, "/forms", {}, MagicMock())
+
+ def test_missing_results_key_raises_retryable_on_extract(self) -> None:
+ config = PAPERFORM_ENDPOINTS["forms"]
+ with pytest.raises(PaperformRetryableError):
+ paperform._extract_rows({"status": "ok", "results": {}}, config, "/forms")
+
+
+class TestCheckAccess:
+ @staticmethod
+ def _session(response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, None),
+ ("unauthorized", 401, False, "Invalid Paperform API key"),
+ (
+ "forbidden_no_api_plan",
+ 403,
+ False,
+ "Your Paperform plan does not include API access. API access requires a Pro, Business, or Agency plan.",
+ ),
+ ("server_error", 500, False, "Paperform returned HTTP 500"),
+ ]
+ )
+ @patch(f"{paperform.__name__}.make_tracked_session")
+ def test_validate_credentials(
+ self,
+ _name: str,
+ status: int,
+ expected_valid: bool,
+ expected_message: str | None,
+ mock_session: MagicMock,
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ mock_session.return_value = self._session(response)
+ assert validate_credentials("pf-key") == (expected_valid, expected_message)
+
+ @patch(f"{paperform.__name__}.make_tracked_session")
+ def test_connection_error_maps_to_zero(self, mock_session: MagicMock) -> None:
+ mock_session.return_value = self._session(requests.ConnectionError("boom"))
+ status, message = check_access("pf-key")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+
+class TestPaperformSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ config = PAPERFORM_ENDPOINTS[endpoint]
+ response = paperform_source(
+ api_key="pf-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ assert response.sort_mode == "asc"
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+
+ def test_form_scoped_endpoints_include_form_id_in_primary_key(self) -> None:
+ # This table aggregates rows across every form, so per-form identifiers (submission id,
+ # field key, SKU, coupon code) are only unique with the parent form id in the key.
+ for config in PAPERFORM_ENDPOINTS.values():
+ if config.form_scoped:
+ assert config.primary_keys[0] == "form_id"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paperform/tests/test_paperform_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paperform/tests/test_paperform_source.py
new file mode 100644
index 000000000000..7c013071f2d5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paperform/tests/test_paperform_source.py
@@ -0,0 +1,149 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PaperformSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.paperform.paperform import PaperformResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.paperform.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.paperform.source import PaperformSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestPaperformSource:
+ def setup_method(self) -> None:
+ self.source = PaperformSource()
+ self.team_id = 123
+ self.config = PaperformSourceConfig(api_key="pf-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.PAPERFORM
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Paperform"
+ assert config.label == "Paperform"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # The source is still landing across PRs, so it stays hidden until released.
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/paperform"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_only_submissions_supports_incremental(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert set(schemas) == set(ENDPOINTS)
+ assert schemas["submissions"].supports_incremental is True
+ assert [f["field"] for f in schemas["submissions"].incremental_fields] == ["created_at_utc"]
+ # Forms and partial submissions mutate after creation, so a creation-time cursor would
+ # freeze their updates — they must stay full refresh.
+ assert all(
+ s.supports_incremental is False and s.incremental_fields == []
+ for name, s in schemas.items()
+ if name != "submissions"
+ )
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["submissions"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "submissions"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://api.paperform.co/v1/forms?limit=100",
+ ),
+ (
+ "forbidden",
+ "403 Client Error: Forbidden for url: https://api.paperform.co/v1/spaces?limit=100",
+ ),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.paperform.co/v1/forms"),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.paperform.co/v1/forms"),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.paperform.source.validate_credentials"
+ )
+ def test_validate_credentials_delegates_with_api_key(self, mock_validate: mock.MagicMock) -> None:
+ # The status-to-message mapping lives in paperform.validate_credentials; here we only assert
+ # the source probes with the configured key and returns the delegate's verdict unchanged.
+ mock_validate.return_value = (False, "Invalid Paperform API key")
+ result = self.source.validate_credentials(self.config, self.team_id)
+ mock_validate.assert_called_once_with("pf-key")
+ assert result == (False, "Invalid Paperform API key")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is PaperformResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.paperform.source.paperform_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "submissions"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-01-01T00:00:00Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "pf-key"
+ assert kwargs["endpoint"] == "submissions"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01T00:00:00Z"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.paperform.source.paperform_source")
+ def test_source_for_pipeline_drops_watermark_on_full_refresh(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "submissions"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2024-01-01T00:00:00Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ # A full refresh must re-read everything, even when a stale watermark is still stored.
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown Paperform schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)