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 anvil import source (#107250)

Tom Owers0b5e2afa7cac
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 017634dcb59f..f054e7a7a5de 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -72,6 +72,7 @@ the row lists both.
| amplemarket | HTTP | requests + `rest_source.RESTClient` | ✅ |
| amplitude | HTTP | requests | ✅ |
| anthropic | HTTP | requests | ✅ |
+| anvil | HTTP (GraphQL) | requests | ✅ |
| apify_dataset | HTTP | requests | ✅ |
| apitally | HTTP | requests + `rest_source.RESTClient` | ✅ |
| apollo | HTTP | requests | ✅ |
@@ -858,7 +859,6 @@ doesn't conflict with concurrent PRs.
- amazon_sqs
- anodot_cost
- anomalo
-- anvil
- apaleo
- appcues
- appdirect
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/anvil.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/anvil.py
new file mode 100644
index 000000000000..d76257ceb70e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/anvil.py
@@ -0,0 +1,351 @@
+import dataclasses
+from collections.abc import Callable, Iterator
+from typing import Any
+
+import requests
+from structlog.types import FilteringBoundLogger
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.anvil.settings import (
+ ANVIL_ENDPOINTS,
+ ANVIL_GRAPHQL_URL,
+ PAGE_SIZE,
+ AnvilEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import (
+ DEFAULT_RETRY,
+ 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.common.schema import schema_for_resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+# GraphQL queries are idempotent reads, so retrying POST is safe. The default retry list
+# excludes POST, which would leave the 429s from Anvil's 4 requests/second development-key
+# rate limit unretried; Anvil sends Retry-After on 429, which the transport honors.
+_ANVIL_RETRY = DEFAULT_RETRY.new(allowed_methods=frozenset(DEFAULT_RETRY.allowed_methods or ()) | {"POST"})
+
+_CURRENT_USER_QUERY = "query { currentUser { eid } }"
+
+_ORGANIZATION_EIDS_QUERY = "query { currentUser { organizations { eid } } }"
+
+
+class AnvilAPIError(Exception):
+ """A GraphQL-level error, which Anvil returns in HTTP 200 bodies with an `errors` array."""
+
+
[email protected](frozen=True)
+class AnvilResumeConfig:
+ # Page number to request next within the bookmarked parent's page walk. None means
+ # "start the parent at its first page".
+ next_offset: int | None = None
+ # The parent currently being paged: an organization eid for the per-organization
+ # endpoints, a weld eid for the weldDatas fan-out (a job syncs one endpoint, so the
+ # kind is unambiguous). A stable eid, not a positional index, so parents created or
+ # deleted between a crash and the retry can't resume us into the wrong parent.
+ parent_eid: str | None = None
+
+
+class _NoopLogger:
+ def error(self, *args: Any, **kwargs: Any) -> None:
+ return None
+
+
+def _build_organizations_query(item_fields: str) -> str:
+ return f"""
+query Organizations {{
+ currentUser {{
+ organizations {{
+{item_fields}
+ }}
+ }}
+}}
+"""
+
+
+def _build_organization_page_query(page_field: str, item_fields: str) -> str:
+ return f"""
+query OrganizationPage($organizationEid: String!, $limit: Int, $offset: Int) {{
+ organization(organizationEid: $organizationEid) {{
+ {page_field}(limit: $limit, offset: $offset) {{
+ page
+ pageCount
+ items {{
+{item_fields}
+ }}
+ }}
+ }}
+}}
+"""
+
+
+def _build_weld_datas_query(item_fields: str) -> str:
+ return f"""
+query WeldDatas($weldEid: String!, $limit: Int, $offset: Int) {{
+ weld(eid: $weldEid) {{
+ weldDatas(limit: $limit, offset: $offset) {{
+ page
+ pageCount
+ items {{
+{item_fields}
+ }}
+ }}
+ }}
+}}
+"""
+
+
+def _make_session(api_key: str) -> requests.Session:
+ # Anvil authenticates with HTTP Basic auth: the API key as the username, empty password.
+ # `capture=False`: responses carry signer names, emails, and document metadata that the
+ # name-based scrubbers can't recognise.
+ session = make_tracked_session(retry=_ANVIL_RETRY, redact_values=(api_key,), capture=False)
+ session.auth = (api_key, "")
+ return session
+
+
+def _execute(
+ session: requests.Session,
+ query: str,
+ variables: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ response = session.post(
+ ANVIL_GRAPHQL_URL, json={"query": query, "variables": variables}, timeout=REQUEST_TIMEOUT_SECONDS
+ )
+
+ if not response.ok:
+ logger.error(f"Anvil API error: status={response.status_code}, body={response.text}")
+ response.raise_for_status()
+
+ body = response.json()
+ errors = body.get("errors")
+ if errors:
+ message = "; ".join(str(error.get("message", error)) for error in errors if isinstance(error, dict))
+ raise AnvilAPIError(f"Anvil API error: {message}")
+
+ return body.get("data") or {}
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ """One cheap probe: `currentUser` resolves only for a genuine API key."""
+ session = _make_session(api_key)
+ try:
+ data = _execute(session, _CURRENT_USER_QUERY, {}, _NoopLogger()) # type: ignore[arg-type]
+ except requests.HTTPError as e:
+ if e.response is not None and e.response.status_code in (401, 403):
+ return False, "Anvil rejected the API key"
+ return False, "Could not reach the Anvil API"
+ except AnvilAPIError as e:
+ return False, str(e)
+ except Exception:
+ return False, "Could not reach the Anvil API"
+
+ if not (data.get("currentUser") or {}).get("eid"):
+ return False, "Anvil did not return a user for this API key"
+ return True, None
+
+
+_Execute = Callable[[str, dict[str, Any]], dict[str, Any]]
+
+
+def _iter_pages(
+ execute: _Execute,
+ query: str,
+ variables: dict[str, Any],
+ unwrap: Callable[[dict[str, Any]], dict[str, Any] | None],
+ resume_offset: int | None,
+ logger: FilteringBoundLogger,
+ context: str,
+) -> Iterator[tuple[list[dict[str, Any]], int | None]]:
+ """Walk one paginated Page field, yielding `(items, next_offset)` per page.
+
+ Anvil's `offset` argument is a page number (the Workflow API guide passes a `$pageNum`
+ variable straight into `offset`), and the response's `page`/`pageCount` fields drive
+ termination. The first request omits `offset` so the server's own first-page number seeds
+ the walk, keeping the arithmetic correct whatever base the numbering starts at.
+ `next_offset` is None on the final page so callers don't persist resume state past the
+ end of the walk.
+ """
+ offset = resume_offset
+ previous_page: int | None = None
+ while True:
+ page_variables: dict[str, Any] = {**variables, "limit": PAGE_SIZE}
+ if offset is not None:
+ page_variables["offset"] = offset
+ data = execute(query, page_variables)
+
+ page_obj = unwrap(data)
+ if page_obj is None:
+ # The parent was deleted between enumeration and this fetch; its rows are gone
+ # with it, so skip rather than failing the whole sync.
+ logger.warning(f"Anvil: {context} no longer exists, skipping")
+ return
+
+ items = page_obj.get("items") or []
+ page = page_obj.get("page")
+ page_count = page_obj.get("pageCount")
+
+ # A page that does not advance means the server ignored the requested offset;
+ # looping on it would re-fetch the same rows forever.
+ if previous_page is not None and (not isinstance(page, int) or page <= previous_page):
+ raise AnvilAPIError(
+ f"Anvil pagination did not advance for {context}: requested offset {offset}, got page {page}"
+ )
+
+ next_offset: int | None = None
+ if items and isinstance(page, int) and isinstance(page_count, int) and page < page_count:
+ next_offset = page + 1
+
+ yield items, next_offset
+
+ if next_offset is None:
+ return
+ previous_page = page
+ offset = next_offset
+
+
+def _list_organization_eids(execute: _Execute) -> list[str]:
+ data = execute(_ORGANIZATION_EIDS_QUERY, {})
+ organizations = (data.get("currentUser") or {}).get("organizations") or []
+ return [organization["eid"] for organization in organizations if organization.get("eid")]
+
+
+def _list_weld_eids(execute: _Execute, logger: FilteringBoundLogger) -> list[str]:
+ weld_eids: list[str] = []
+ for organization_eid in _list_organization_eids(execute):
+ pages = _iter_pages(
+ execute,
+ _build_organization_page_query("welds", "eid"),
+ {"organizationEid": organization_eid},
+ lambda data: (data.get("organization") or {}).get("welds"),
+ None,
+ logger,
+ f"organization {organization_eid}",
+ )
+ for items, _ in pages:
+ weld_eids.extend(item["eid"] for item in items if item.get("eid"))
+ return weld_eids
+
+
+def _get_parent_paged_rows(
+ execute: _Execute,
+ query: str,
+ parent_eids: list[str],
+ # GraphQL variable naming the parent; also the column stamped onto every row.
+ variable_name: str,
+ unwrap: Callable[[dict[str, Any]], dict[str, Any] | None],
+ resumable_source_manager: ResumableSourceManager[AnvilResumeConfig],
+ logger: FilteringBoundLogger,
+ context_label: str,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk one page walk per parent, tagging each row with the parent it came from.
+
+ The bookmark is a stable parent eid. If the bookmarked parent no longer exists, start
+ over from the first one; merge dedupes the re-pulled rows on the primary key.
+ `resume_offset` is consumed by the bookmarked parent only.
+ """
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ remaining = parent_eids
+ resume_offset: int | None = None
+ if resume is not None and resume.parent_eid is not None and resume.parent_eid in parent_eids:
+ remaining = parent_eids[parent_eids.index(resume.parent_eid) :]
+ resume_offset = resume.next_offset
+ logger.debug(f"Anvil: resuming {context_label} walk from {resume.parent_eid}, offset={resume_offset}")
+
+ for index, parent_eid in enumerate(remaining):
+ for items, next_offset in _iter_pages(
+ execute,
+ query,
+ {variable_name: parent_eid},
+ unwrap,
+ resume_offset,
+ logger,
+ f"{context_label} {parent_eid}",
+ ):
+ rows = [{**item, variable_name: parent_eid} for item in items]
+ if rows:
+ yield rows
+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the
+ # last page rather than skipping it; merge dedupes on the primary key.
+ if next_offset:
+ resumable_source_manager.save_state(AnvilResumeConfig(next_offset=next_offset, parent_eid=parent_eid))
+ resume_offset = None
+
+ # Advance the bookmark so a crash between parents resumes at the next one.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(AnvilResumeConfig(next_offset=None, parent_eid=remaining[index + 1]))
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AnvilResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config: AnvilEndpointConfig = schema_for_resource(ANVIL_ENDPOINTS, endpoint)
+ session = _make_session(api_key)
+
+ def execute(query: str, variables: dict[str, Any]) -> dict[str, Any]:
+ return _execute(session, query, variables, logger)
+
+ if config.fan_out_weld_datas:
+ yield from _get_parent_paged_rows(
+ execute,
+ _build_weld_datas_query(config.item_fields),
+ _list_weld_eids(execute, logger),
+ "weldEid",
+ lambda data: (data.get("weld") or {}).get("weldDatas"),
+ resumable_source_manager,
+ logger,
+ "weld",
+ )
+ return
+
+ if config.organization_page_field is None:
+ data = execute(_build_organizations_query(config.item_fields), {})
+ rows = (data.get("currentUser") or {}).get("organizations") or []
+ if rows:
+ yield rows
+ return
+
+ page_field = config.organization_page_field
+ yield from _get_parent_paged_rows(
+ execute,
+ _build_organization_page_query(page_field, config.item_fields),
+ _list_organization_eids(execute),
+ "organizationEid",
+ lambda data: (data.get("organization") or {}).get(page_field),
+ resumable_source_manager,
+ logger,
+ "organization",
+ )
+
+
+def anvil_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AnvilResumeConfig],
+) -> SourceResponse:
+ config: AnvilEndpointConfig = schema_for_resource(ANVIL_ENDPOINTS, endpoint)
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1 if config.partition_key else None,
+ partition_size=1 if config.partition_key else None,
+ 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,
+ # Anvil doesn't document list ordering guarantees, so the pipeline defers any
+ # watermark commit until a run completes.
+ sort_mode="desc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/canonical_descriptions.py
new file mode 100644
index 000000000000..499c4138ba31
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/canonical_descriptions.py
@@ -0,0 +1,122 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "organizations": {
+ "description": "An Anvil organization: the entity that holds a set of workflows, PDF templates, and users.",
+ "docs_url": "https://www.useanvil.com/docs/api/graphql/reference/#definition-Organization",
+ "columns": {
+ "eid": "Unique identifier of the organization.",
+ "name": "Name of the organization.",
+ "slug": "URL slug of the organization.",
+ "isPersonal": "Whether this is a personal organization rather than a team one.",
+ "isSubscribed": "Whether the organization has an active subscription.",
+ "useTestSignatureProvider": "Whether e-signatures use Anvil's test signature provider.",
+ "signatureProviderType": "The e-signature provider in use: etch or docusign.",
+ "availableSignatureProviderTypes": "The e-signature providers the organization can use.",
+ "isSso": "Whether the organization authenticates with SSO.",
+ "remainingUsers": "Number of user slots remaining for the organization.",
+ "logoURL": "URL of the organization's logo.",
+ "stylesheetURL": "URL of the organization's white-label CSS stylesheet.",
+ "billingEmail": "Email address used for billing correspondence.",
+ "supportEmail": "Support email address, used as the reply-to for emails Anvil sends to users.",
+ "createdAt": "Timestamp when the organization was created.",
+ "updatedAt": "Timestamp when the organization was last updated.",
+ },
+ },
+ "casts": {
+ "description": "A cast is a PDF template: a base PDF plus the field configuration used to fill it.",
+ "docs_url": "https://www.useanvil.com/docs/api/graphql/reference/#definition-Cast",
+ "columns": {
+ "eid": "Unique identifier of the template. The same value as the PDF template ID.",
+ "organizationEid": "Identifier of the organization the template belongs to.",
+ "type": "MIME type of the underlying file, e.g. application/pdf.",
+ "name": "Internal name of the template.",
+ "title": "Display title of the template.",
+ "isTemplate": "Whether the cast is a reusable template.",
+ "versionNumber": "Current version number of the template.",
+ "latestDraftVersionNumber": "Latest draft version number.",
+ "publishedNumber": "Current published version number.",
+ "publishedAt": "Timestamp when the template was last published.",
+ "hasUnpublishedChanges": "Whether the template has draft changes that are not yet published.",
+ "hasBeenPublished": "Whether the template has ever been published.",
+ "allowedAliasIds": "Field alias IDs allowed when filling the template.",
+ "createdAt": "Timestamp when the template was created.",
+ "updatedAt": "Timestamp when the template was last updated.",
+ "archivedAt": "Timestamp when the template was archived; null while active.",
+ },
+ },
+ "welds": {
+ "description": "A weld is a workflow definition: it combines webforms and PDF templates into a document workflow.",
+ "docs_url": "https://www.useanvil.com/docs/api/graphql/reference/#definition-Weld",
+ "columns": {
+ "eid": "Unique identifier of the workflow.",
+ "organizationEid": "Identifier of the organization the workflow belongs to.",
+ "slug": "URL slug of the workflow.",
+ "name": "Name of the workflow.",
+ "visibility": "Visibility of the workflow.",
+ "versionNumber": "Current version number of the workflow.",
+ "latestDraftVersionNumber": "Latest draft version number.",
+ "publishedNumber": "Current published version number.",
+ "publishedAt": "Timestamp when the workflow was last published.",
+ "hasUnpublishedChanges": "Whether the workflow has draft changes that are not yet published.",
+ "hasBeenPublished": "Whether the workflow has ever been published.",
+ "hasSigners": "Whether the workflow includes e-signature steps.",
+ "signatureProviderType": "The e-signature provider the workflow uses: etch or docusign.",
+ "availableSignatureProviderTypes": "The e-signature providers the workflow can use.",
+ "submissionsCount": "Total number of submissions (weld datas) started by this workflow.",
+ "createdAt": "Timestamp when the workflow was created.",
+ "updatedAt": "Timestamp when the workflow was last updated.",
+ "archivedAt": "Timestamp when the workflow was archived; null while active.",
+ "expiresAt": "Timestamp when the workflow expires; null when it does not expire.",
+ },
+ },
+ "weld_datas": {
+ "description": "A weld data is one workflow submission: an instance of a workflow with its completion and signer status.",
+ "docs_url": "https://www.useanvil.com/docs/api/graphql/reference/#definition-WeldData",
+ "columns": {
+ "eid": "Unique identifier of the submission.",
+ "weldEid": "Identifier of the workflow the submission belongs to.",
+ "displayTitle": "Title of the submission shown in the Anvil UI.",
+ "status": "Status of the submission: created, in-progress, ready-to-sign, awaiting-signatures, completed, or declined.",
+ "isTest": "Whether this is a test submission. Test submissions are not billed.",
+ "isExpired": "Whether the submission has expired or been locked.",
+ "isComplete": "Whether all forms in the workflow have been filled. Signers may still need to sign.",
+ "isAllComplete": "Whether all forms are filled and all signers have signed.",
+ "completionPercentage": "How complete the submission is, between 0 and 1.",
+ "numberRemainingSigners": "Number of signers who have not signed yet.",
+ "hasSigners": "Whether the submission has signers.",
+ "payloadCanBeUpdated": "Whether the submission's payload can still be updated.",
+ "weldVersionId": "Version of the workflow the submission runs against.",
+ "createdAt": "Timestamp when the submission was created.",
+ "updatedAt": "Timestamp when the submission was last updated.",
+ "dataUpdatedAt": "Timestamp when the submission's data was last updated.",
+ "expiresAt": "Timestamp when the submission expires; null when it does not expire.",
+ "archivedAt": "Timestamp when the submission was archived; null while active.",
+ "embeddedAt": "Timestamp when the submission was embedded in an external app.",
+ },
+ },
+ "etch_packets": {
+ "description": "An etch packet is an e-signature packet: a collection of documents sent to one or more signers.",
+ "docs_url": "https://www.useanvil.com/docs/api/graphql/reference/#definition-EtchPacket",
+ "columns": {
+ "eid": "Unique identifier of the packet.",
+ "organizationEid": "Identifier of the organization the packet belongs to.",
+ "name": "Name of the packet shown in the Anvil UI.",
+ "status": "Status of the packet: draft, sent, delivered, partial, declined, voided, or completed.",
+ "isTest": "Whether this is a test packet. Test packets are not billed and their documents are watermarked.",
+ "allowUpdates": "Whether the packet's payload can be updated after creation.",
+ "containsFillData": "Whether the packet's payload contains data that fills PDFs.",
+ "numberRemainingSigners": "Number of signers who have not signed yet.",
+ "detailsURL": "URL to the packet in the Anvil dashboard.",
+ "documentGroup": "The filled and sent documents with their signers and per-signer signing status.",
+ "createdAt": "Timestamp when the packet was created.",
+ "updatedAt": "Timestamp when the packet was last updated.",
+ "archivedAt": "Timestamp when the packet was archived; null while active.",
+ "completedAt": "Timestamp when all signers finished signing.",
+ "sentAt": "Timestamp when the packet was sent to signers.",
+ "embeddedAt": "Timestamp when the packet was embedded in an external app.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/settings.py
new file mode 100644
index 000000000000..cfcd09c110a7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/settings.py
@@ -0,0 +1,188 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+ANVIL_GRAPHQL_URL = "https://graphql.useanvil.com"
+
+# Anvil caps `limit` at 500 rows per page; 100 keeps each response's size moderate while the
+# rate limit (4 requests/second on development keys) bounds request throughput anyway.
+PAGE_SIZE = 100
+
+# Selections stay on metadata scalars. Filled PDFs, signed documents, submission form data
+# (`payload`, `files`), and capability URLs (`continueURL`, `pin`) must never reach the
+# warehouse, so they are not selected.
+_ORGANIZATION_ITEM_FIELDS = """
+eid
+name
+slug
+isPersonal
+isSubscribed
+useTestSignatureProvider
+signatureProviderType
+availableSignatureProviderTypes
+isSso
+remainingUsers
+logoURL
+stylesheetURL
+billingEmail
+supportEmail
+createdAt
+updatedAt
+"""
+
+_CAST_ITEM_FIELDS = """
+eid
+type
+name
+title
+isTemplate
+versionNumber
+latestDraftVersionNumber
+publishedNumber
+publishedAt
+hasUnpublishedChanges
+hasBeenPublished
+allowedAliasIds
+createdAt
+updatedAt
+archivedAt
+"""
+
+_WELD_ITEM_FIELDS = """
+eid
+slug
+name
+visibility
+versionNumber
+latestDraftVersionNumber
+publishedNumber
+publishedAt
+hasUnpublishedChanges
+hasBeenPublished
+hasSigners
+signatureProviderType
+availableSignatureProviderTypes
+submissionsCount
+createdAt
+updatedAt
+archivedAt
+expiresAt
+"""
+
+_WELD_DATA_ITEM_FIELDS = """
+eid
+displayTitle
+status
+isTest
+isExpired
+isComplete
+isAllComplete
+completionPercentage
+numberRemainingSigners
+hasSigners
+payloadCanBeUpdated
+weldVersionId
+createdAt
+updatedAt
+dataUpdatedAt
+expiresAt
+archivedAt
+embeddedAt
+"""
+
+_ETCH_PACKET_ITEM_FIELDS = """
+eid
+name
+status
+isTest
+allowUpdates
+containsFillData
+numberRemainingSigners
+detailsURL
+createdAt
+updatedAt
+archivedAt
+completedAt
+sentAt
+embeddedAt
+documentGroup {
+eid
+status
+provider
+currentRoutingStep
+createdAt
+updatedAt
+completedAt
+signers {
+eid
+aliasId
+status
+provider
+name
+email
+routingOrder
+signatureExperience
+signActionType
+clientUserId
+createdAt
+updatedAt
+completedAt
+}
+}
+"""
+
+
+@dataclass(frozen=True)
+class AnvilEndpointConfig:
+ # GraphQL selection for one row of this endpoint.
+ item_fields: str
+ # Paginated Page field on Organization (`casts`, `welds`, `etchPackets`); None for the
+ # single-query organizations endpoint and the per-weld fan-out.
+ organization_page_field: str | None = None
+ # Fan out one `weld(eid: ...) { weldDatas }` page walk per weld across every organization.
+ fan_out_weld_datas: bool = False
+ # Anvil eids are 20-character object identifiers unique across their system, so a row's
+ # own eid is a table-wide key even for fan-out children.
+ primary_keys: list[str] = field(default_factory=lambda: ["eid"])
+ # Stable creation timestamp for partitioning; None for the tiny organizations table.
+ partition_key: str | None = "createdAt"
+ description: str | None = None
+
+
+ANVIL_ENDPOINTS: dict[str, AnvilEndpointConfig] = {
+ "organizations": AnvilEndpointConfig(
+ item_fields=_ORGANIZATION_ITEM_FIELDS,
+ partition_key=None,
+ description="The Anvil organizations your API key's user belongs to",
+ ),
+ "casts": AnvilEndpointConfig(
+ item_fields=_CAST_ITEM_FIELDS,
+ organization_page_field="casts",
+ description="PDF templates, fetched per organization",
+ ),
+ "welds": AnvilEndpointConfig(
+ item_fields=_WELD_ITEM_FIELDS,
+ organization_page_field="welds",
+ description="Workflow definitions, fetched per organization",
+ ),
+ "weld_datas": AnvilEndpointConfig(
+ item_fields=_WELD_DATA_ITEM_FIELDS,
+ fan_out_weld_datas=True,
+ description=(
+ "Workflow submissions, fetched per workflow (one page walk per weld), "
+ "so syncs scale with the number of workflows"
+ ),
+ ),
+ "etch_packets": AnvilEndpointConfig(
+ item_fields=_ETCH_PACKET_ITEM_FIELDS,
+ organization_page_field="etchPackets",
+ description="E-signature packets with their signer status, fetched per organization",
+ ),
+}
+
+ENDPOINTS = tuple(ANVIL_ENDPOINTS.keys())
+
+# The list fields take `dateStart`/`dateEnd` (welds, etchPackets) and `fromDate`/`toDate`
+# (weldDatas) arguments, but Anvil does not document which timestamp they filter on or the
+# ordering they imply, so no endpoint advertises a cursor and every table syncs as full refresh.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/source.py
index 565e72f7de83..5d062ff2f933 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/source.py
@@ -1,14 +1,49 @@
-from typing import cast
+from typing import Optional, cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.anvil.anvil import (
+ AnvilResumeConfig,
+ anvil_source,
+ validate_credentials as validate_anvil_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.anvil.settings import (
+ ANVIL_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.anvil import AnvilSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
+_SCHEMA_DESCRIPTIONS: dict[str, str] = {
+ name: config.description for name, config in ANVIL_ENDPOINTS.items() if config.description
+}
+
@SourceRegistry.register
-class AnvilSource(SimpleSource[AnvilSourceConfig]):
+class AnvilSource(ResumableSource[AnvilSourceConfig, AnvilResumeConfig]):
+ # Anvil's GraphQL API is unversioned; the REST-only fill/generate endpoints carry the
+ # /v1 path segment, but this source never calls them.
+ api_docs_url = "https://www.useanvil.com/docs/api/graphql/reference/"
+
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ANVIL
@@ -19,8 +54,82 @@ class AnvilSource(SimpleSource[AnvilSourceConfig]):
name=ExternalDataSourceType.ANVIL,
category=DataWarehouseSourceCategory.SALES,
label="Anvil",
- keywords=["useanvil.com"],
+ keywords=["useanvil.com", "e-signature", "pdf"],
+ caption="""Sync metadata about your Anvil documents into the PostHog Data warehouse: organizations, PDF templates (casts), workflows (welds), workflow submissions, and e-signature packets with their signer status.
+
+Create an API key in your Anvil organization settings, under API settings. Development keys are rate limited to 4 requests per second, so large accounts sync faster with a production key.
+
+Only metadata is synced. Filled PDFs, signed documents, and submission form data never leave Anvil.""",
iconPath="/static/services/anvil.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/anvil",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.anvil.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # An invalid or revoked key surfaces as a requests HTTPError once the transport's
+ # retries are exhausted; match the stable status text and host, not the per-request
+ # detail.
+ return {
+ "401 Client Error: Unauthorized for url: https://graphql.useanvil.com": "Your Anvil API key is invalid or has been revoked. Create a new API key in your Anvil organization's API settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://graphql.useanvil.com": "Your Anvil API key does not have access to this data. Check the key's organization in your Anvil API settings, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: AnvilSourceConfig,
+ 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, descriptions=_SCHEMA_DESCRIPTIONS)
+
+ def validate_credentials(
+ self,
+ config: AnvilSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ is_valid, error = validate_anvil_credentials(config.api_key)
+ if is_valid:
+ return True, None
+
+ return False, error or "Invalid Anvil API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AnvilResumeConfig]:
+ return ResumableSourceManager[AnvilResumeConfig](inputs, AnvilResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AnvilSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AnvilResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return anvil_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/tests/test_anvil.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/tests/test_anvil.py
new file mode 100644
index 000000000000..82b3b7c072a0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/tests/test_anvil.py
@@ -0,0 +1,328 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.anvil.anvil import (
+ AnvilAPIError,
+ AnvilResumeConfig,
+ _build_organization_page_query,
+ _build_weld_datas_query,
+ _execute,
+ anvil_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.anvil.settings import (
+ ANVIL_ENDPOINTS,
+ ENDPOINTS,
+ PAGE_SIZE,
+)
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.anvil.anvil"
+
+
+def _make_manager(resume_state: AnvilResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _response(payload: dict[str, Any], status_code: int = 200) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = payload
+ resp.status_code = status_code
+ resp.ok = status_code < 400
+ if status_code >= 400:
+ resp.raise_for_status.side_effect = requests.HTTPError(
+ f"{status_code} Client Error: Unauthorized for url: https://graphql.useanvil.com",
+ response=resp,
+ )
+ return resp
+
+
+def _org_eids(*eids: str) -> mock.MagicMock:
+ return _response({"data": {"currentUser": {"organizations": [{"eid": eid} for eid in eids]}}})
+
+
+def _org_page(page_field: str, items: list[dict[str, Any]], page: int = 1, page_count: int = 1) -> mock.MagicMock:
+ return _response({"data": {"organization": {page_field: {"page": page, "pageCount": page_count, "items": items}}}})
+
+
+def _weld_datas_page(items: list[dict[str, Any]], page: int = 1, page_count: int = 1) -> mock.MagicMock:
+ return _response({"data": {"weld": {"weldDatas": {"page": page, "pageCount": page_count, "items": items}}}})
+
+
+def _mock_session(mock_make_session: mock.MagicMock, responses: list[mock.MagicMock]) -> mock.MagicMock:
+ session = mock.MagicMock()
+ session.post.side_effect = responses
+ mock_make_session.return_value = session
+ return session
+
+
+class TestExecute:
+ def test_graphql_errors_raise_with_joined_messages(self):
+ session = mock.MagicMock()
+ session.post.return_value = _response(
+ {"errors": [{"message": "Must be authenticated"}, {"message": "Weld not found"}], "data": None}
+ )
+
+ with pytest.raises(AnvilAPIError) as exc_info:
+ _execute(session, "query {}", {}, mock.MagicMock())
+
+ assert "Must be authenticated" in str(exc_info.value)
+ assert "Weld not found" in str(exc_info.value)
+
+ def test_http_error_raises_after_logging(self):
+ session = mock.MagicMock()
+ session.post.return_value = _response({}, status_code=401)
+
+ with pytest.raises(requests.HTTPError) as exc_info:
+ _execute(session, "query {}", {}, mock.MagicMock())
+
+ assert "401" in str(exc_info.value)
+
+
+class TestValidateCredentials:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_valid_key_authenticates_with_basic_auth(self, mock_make_session):
+ session = _mock_session(mock_make_session, [_response({"data": {"currentUser": {"eid": "u1"}}})])
+
+ assert validate_credentials("key-1") == (True, None)
+ assert session.auth == ("key-1", "")
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_rejected_key_returns_message(self, mock_make_session):
+ _mock_session(mock_make_session, [_response({}, status_code=401)])
+
+ is_valid, error = validate_credentials("bad-key")
+ assert is_valid is False
+ assert error == "Anvil rejected the API key"
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_graphql_error_returns_its_message(self, mock_make_session):
+ # Anvil responds HTTP 200 with an errors body when no auth header is readable.
+ _mock_session(mock_make_session, [_response({"errors": [{"message": "Must be authenticated"}]})])
+
+ is_valid, error = validate_credentials("key-1")
+ assert is_valid is False
+ assert error is not None and "Must be authenticated" in error
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_network_failure_returns_unreachable(self, mock_make_session):
+ mock_make_session.return_value.post.side_effect = requests.ConnectionError("boom")
+
+ assert validate_credentials("key-1") == (False, "Could not reach the Anvil API")
+
+
+class TestOrganizations:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_single_query_yields_every_organization(self, mock_make_session):
+ session = _mock_session(
+ mock_make_session,
+ [_response({"data": {"currentUser": {"organizations": [{"eid": "o1"}, {"eid": "o2"}]}}})],
+ )
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "organizations", mock.MagicMock(), manager))
+
+ assert [row["eid"] for batch in batches for row in batch] == ["o1", "o2"]
+ assert session.post.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_no_organizations_yields_no_batches(self, mock_make_session):
+ _mock_session(mock_make_session, [_response({"data": {"currentUser": {"organizations": []}}})])
+
+ assert list(get_rows("key", "organizations", mock.MagicMock(), _make_manager())) == []
+
+
+class TestOrganizationPagedEndpoints:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_paginates_by_page_number_and_tags_rows(self, mock_make_session):
+ session = _mock_session(
+ mock_make_session,
+ [
+ _org_eids("o1", "o2"),
+ _org_page("casts", [{"eid": "c1"}], page=1, page_count=2),
+ _org_page("casts", [{"eid": "c2"}], page=2, page_count=2),
+ _org_page("casts", [{"eid": "c3"}]),
+ ],
+ )
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "casts", mock.MagicMock(), manager))
+
+ assert [row for batch in batches for row in batch] == [
+ {"eid": "c1", "organizationEid": "o1"},
+ {"eid": "c2", "organizationEid": "o1"},
+ {"eid": "c3", "organizationEid": "o2"},
+ ]
+ page_calls = [call.kwargs["json"]["variables"] for call in session.post.call_args_list[1:]]
+ # The first request per organization omits `offset` so the server's own first-page
+ # number seeds the walk; the follow-up asks for the returned page + 1.
+ assert "offset" not in page_calls[0]
+ assert page_calls[0]["limit"] == PAGE_SIZE
+ assert page_calls[1]["offset"] == 2
+ assert [call["organizationEid"] for call in page_calls] == ["o1", "o1", "o2"]
+ # Mid-organization page checkpoint, then a bookmark advancing to the next organization.
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert [(state.next_offset, state.parent_eid) for state in saved] == [(2, "o1"), (None, "o2")]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_resumes_from_bookmarked_organization_and_offset(self, mock_make_session):
+ session = _mock_session(
+ mock_make_session,
+ [
+ _org_eids("o1", "o2"),
+ _org_page("casts", [{"eid": "c9"}], page=3, page_count=3),
+ ],
+ )
+
+ manager = _make_manager(AnvilResumeConfig(next_offset=3, parent_eid="o2"))
+ list(get_rows("key", "casts", mock.MagicMock(), manager))
+
+ page_calls = session.post.call_args_list[1:]
+ assert len(page_calls) == 1
+ variables = page_calls[0].kwargs["json"]["variables"]
+ assert variables["organizationEid"] == "o2"
+ assert variables["offset"] == 3
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_deleted_organization_is_skipped(self, mock_make_session):
+ _mock_session(
+ mock_make_session,
+ [
+ _org_eids("o1", "o2"),
+ _response({"data": {"organization": None}}),
+ _org_page("casts", [{"eid": "c1"}]),
+ ],
+ )
+
+ batches = list(get_rows("key", "casts", mock.MagicMock(), _make_manager()))
+
+ assert [row for batch in batches for row in batch] == [{"eid": "c1", "organizationEid": "o2"}]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_non_advancing_page_raises_instead_of_looping(self, mock_make_session):
+ _mock_session(
+ mock_make_session,
+ [
+ _org_eids("o1"),
+ _org_page("casts", [{"eid": "c1"}], page=1, page_count=2),
+ _org_page("casts", [{"eid": "c1"}], page=1, page_count=2),
+ ],
+ )
+
+ with pytest.raises(AnvilAPIError) as exc_info:
+ list(get_rows("key", "casts", mock.MagicMock(), _make_manager()))
+
+ assert "did not advance" in str(exc_info.value)
+
+
+class TestWeldDatasFanOut:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_fans_out_over_welds_across_organizations(self, mock_make_session):
+ session = _mock_session(
+ mock_make_session,
+ [
+ _org_eids("o1", "o2"),
+ _org_page("welds", [{"eid": "w1"}]),
+ _org_page("welds", [{"eid": "w2"}]),
+ _weld_datas_page([{"eid": "d1"}], page=1, page_count=2),
+ _weld_datas_page([{"eid": "d2"}], page=2, page_count=2),
+ _weld_datas_page([{"eid": "d3"}]),
+ ],
+ )
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "weld_datas", mock.MagicMock(), manager))
+
+ assert [row for batch in batches for row in batch] == [
+ {"eid": "d1", "weldEid": "w1"},
+ {"eid": "d2", "weldEid": "w1"},
+ {"eid": "d3", "weldEid": "w2"},
+ ]
+ weld_data_calls = [call.kwargs["json"]["variables"] for call in session.post.call_args_list[3:]]
+ assert [call["weldEid"] for call in weld_data_calls] == ["w1", "w1", "w2"]
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert [(state.next_offset, state.parent_eid) for state in saved] == [(2, "w1"), (None, "w2")]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_deleted_weld_is_skipped(self, mock_make_session):
+ _mock_session(
+ mock_make_session,
+ [
+ _org_eids("o1"),
+ _org_page("welds", [{"eid": "w1"}, {"eid": "w2"}]),
+ _response({"data": {"weld": None}}),
+ _weld_datas_page([{"eid": "d1"}]),
+ ],
+ )
+
+ batches = list(get_rows("key", "weld_datas", mock.MagicMock(), _make_manager()))
+
+ assert [row for batch in batches for row in batch] == [{"eid": "d1", "weldEid": "w2"}]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_resumes_from_bookmarked_weld(self, mock_make_session):
+ session = _mock_session(
+ mock_make_session,
+ [
+ _org_eids("o1"),
+ _org_page("welds", [{"eid": "w1"}, {"eid": "w2"}]),
+ _weld_datas_page([{"eid": "d9"}]),
+ ],
+ )
+
+ manager = _make_manager(AnvilResumeConfig(next_offset=2, parent_eid="w2"))
+ list(get_rows("key", "weld_datas", mock.MagicMock(), manager))
+
+ weld_data_calls = session.post.call_args_list[2:]
+ assert len(weld_data_calls) == 1
+ variables = weld_data_calls[0].kwargs["json"]["variables"]
+ assert variables["weldEid"] == "w2"
+ assert variables["offset"] == 2
+
+
+class TestQueryDocuments:
+ @pytest.mark.parametrize(
+ "endpoint",
+ [name for name in ENDPOINTS if ANVIL_ENDPOINTS[name].organization_page_field],
+ )
+ def test_organization_page_query_declares_its_variables(self, endpoint):
+ config = ANVIL_ENDPOINTS[endpoint]
+ assert config.organization_page_field is not None
+ query = _build_organization_page_query(config.organization_page_field, config.item_fields)
+
+ for declaration in ("$organizationEid: String!", "$limit: Int", "$offset: Int"):
+ assert declaration in query
+ assert f"{config.organization_page_field}(limit: $limit, offset: $offset)" in query
+
+ def test_weld_datas_query_declares_its_variables(self):
+ query = _build_weld_datas_query(ANVIL_ENDPOINTS["weld_datas"].item_fields)
+
+ for declaration in ("$weldEid: String!", "$limit: Int", "$offset: Int"):
+ assert declaration in query
+ assert "weld(eid: $weldEid)" in query
+
+
+class TestAnvilSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_partition_wiring_per_endpoint(self, endpoint):
+ config = ANVIL_ENDPOINTS[endpoint]
+ response = anvil_source("key", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ # List ordering is undocumented, so the watermark commits only at run end.
+ assert response.sort_mode == "desc"
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/tests/test_anvil_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/tests/test_anvil_source.py
new file mode 100644
index 000000000000..9bb3432eca76
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/tests/test_anvil_source.py
@@ -0,0 +1,65 @@
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.anvil.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.anvil.source import AnvilSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.anvil import AnvilSourceConfig
+
+
+class TestAnvilSource:
+ def setup_method(self):
+ self.source = AnvilSource()
+ self.team_id = 123
+ self.config = AnvilSourceConfig(api_key="key-1")
+
+ def test_get_schemas_every_table_is_full_refresh_only(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ # No endpoint has a verified server-side timestamp filter, so advertising a cursor
+ # would ship an incremental sync that silently re-fetches everything.
+ assert not any(schema.supports_incremental or schema.supports_append for schema in schemas)
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["weld_datas"])
+ assert [schema.name for schema in schemas] == ["weld_datas"]
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_non_retryable_errors_match_anvil_auth_failures(self):
+ # The verbatim message requests raises once the transport's retries are exhausted.
+ auth_error = "401 Client Error: Unauthorized for url: https://graphql.useanvil.com"
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in auth_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "Anvil API error: Weld not found",
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ ],
+ )
+ def test_non_retryable_errors_do_not_match_unrelated(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ ((True, None), True, None),
+ ((False, "Anvil rejected the API key"), False, "Anvil rejected the API key"),
+ ((False, None), False, "Invalid Anvil API key"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.anvil.source.validate_anvil_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with("key-1")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/anvil.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/anvil.py
index b2f06d57ad4e..8549928fcf9e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/anvil.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/anvil.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class AnvilSourceConfig(config.Config):
- pass
+ api_key: str