:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement docuseal import source (#66760)
Tom Owersdcf3165db7ca
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex b6ad01691d8f..d561ce2bc160 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -100,6 +100,7 @@ the row lists both.| deel | HTTP | requests | ✅ || delighted | HTTP | requests | ✅ || dixa | HTTP | requests | ✅ |+| docuseal | HTTP | requests | ✅ || doit | HTTP | requests | ✅ || drip | HTTP | requests | ✅ || easypost | HTTP | requests | ✅ |@@ -366,7 +367,6 @@ doesn't conflict with concurrent PRs.- ding_connect- display_video_360- dockerhub-- docuseal- docusign- dolibarr- dremiodiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/docuseal/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/docuseal/canonical_descriptions.pynew file mode 100644index 000000000000..dbb155a2eb0a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/docuseal/canonical_descriptions.py@@ -0,0 +1,72 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions are taken from the DocuSeal API docs (https://www.docuseal.com/docs/api). Partial+# coverage is fine — any column not listed here falls back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "templates": {+ "description": "A reusable document template with the fields submitters fill in to create submissions.",+ "docs_url": "https://www.docuseal.com/docs/api#list-all-templates",+ "columns": {+ "id": "Unique identifier of the template.",+ "slug": "Unique slug of the template, used in shareable links.",+ "name": "Name of the template.",+ "schema": "List of documents attached to the template.",+ "fields": "List of fields to be filled in the document.",+ "submitters": "List of submitter roles defined on the template.",+ "author_id": "Unique identifier of the template author.",+ "archived_at": "Timestamp the template was archived, or null if active.",+ "created_at": "Timestamp the template was created.",+ "updated_at": "Timestamp the template was last updated.",+ "source": "Source the template was created from (e.g. native, api, embed).",+ "external_id": "Your application-specific unique identifier for the template.",+ "folder_name": "Name of the folder the template belongs to.",+ },+ },+ "submissions": {+ "description": "A signing request created from a template, grouping the submitters and documents involved.",+ "docs_url": "https://www.docuseal.com/docs/api#list-all-submissions",+ "columns": {+ "id": "Unique identifier of the submission.",+ "source": "Source the submission was created from (e.g. api, link, bulk).",+ "submitters_order": "Order in which submitters receive the signing request (preserved or random).",+ "slug": "Unique slug of the submission.",+ "status": "Aggregate status of the submission (e.g. pending, completed, declined, expired).",+ "audit_log_url": "URL of the submission's audit log PDF.",+ "combined_document_url": "URL of the combined signed documents PDF.",+ "expire_at": "Timestamp the submission expires, or null.",+ "completed_at": "Timestamp all submitters completed the submission, or null.",+ "created_at": "Timestamp the submission was created.",+ "updated_at": "Timestamp the submission was last updated.",+ "archived_at": "Timestamp the submission was archived, or null if active.",+ "submitters": "List of submitters belonging to the submission.",+ "template": "The template the submission was created from.",+ "created_by_user": "The user who created the submission.",+ },+ },+ "submitters": {+ "description": "An individual party on a submission who fills in fields and signs the document.",+ "docs_url": "https://www.docuseal.com/docs/api#list-all-submitters",+ "columns": {+ "id": "Unique identifier of the submitter.",+ "submission_id": "Identifier of the submission this submitter belongs to.",+ "uuid": "UUID of the submitter within the submission.",+ "email": "Email address of the submitter.",+ "slug": "Unique slug of the submitter, used in their signing link.",+ "sent_at": "Timestamp the signing request was sent to the submitter, or null.",+ "opened_at": "Timestamp the submitter opened the signing form, or null.",+ "completed_at": "Timestamp the submitter completed signing, or null.",+ "declined_at": "Timestamp the submitter declined to sign, or null.",+ "created_at": "Timestamp the submitter was created.",+ "updated_at": "Timestamp the submitter was last updated.",+ "name": "Name of the submitter.",+ "phone": "Phone number of the submitter.",+ "status": "Status of the submitter (e.g. awaiting, opened, completed, declined).",+ "role": "Role of the submitter as defined on the template.",+ "external_id": "Your application-specific unique identifier for the submitter.",+ "metadata": "Arbitrary metadata attached to the submitter.",+ "values": "Field values submitted by the submitter.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/docuseal/docuseal.py b/products/warehouse_sources/backend/temporal/data_imports/sources/docuseal/docuseal.pynew file mode 100644index 000000000000..f158ab48a347--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/docuseal/docuseal.py@@ -0,0 +1,182 @@+import dataclasses+from collections.abc import Iterator+from typing import Any+from urllib.parse import urlencode++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.batcher import Batcher+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+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.docuseal.settings import (+ DOCUSEAL_ENDPOINTS,+ DocusealEndpointConfig,+)++# DocuSeal runs two hosted regions on separate base URLs. There is no programmatic way to+# discover which region an account lives in, so the user picks it on the connection form.+DOCUSEAL_HOSTS: dict[str, str] = {+ "us": "https://api.docuseal.com",+ "eu": "https://api.docuseal.eu",+}+DEFAULT_REGION = "us"++# Max page size the API accepts (`limit`, capped server-side at 100).+PAGE_SIZE = 100++REQUEST_TIMEOUT_SECONDS = 60+++class DocusealRetryableError(Exception):+ pass+++class DocusealResumeConfig:+ # The `after` cursor (a record id) used to fetch the page we're currently streaming. We persist+ # *this* page's cursor (not the next page's) so a crash mid-page resumes by re-fetching the same+ # page rather than skipping past rows still buffered but not yet yielded — merge dedupes the+ # re-pulled rows on the primary key. `None` means "start from the first page".+ after: int | None = None+++def _base_url(region: str | None) -> str:+ return DOCUSEAL_HOSTS.get(region or DEFAULT_REGION, DOCUSEAL_HOSTS[DEFAULT_REGION])+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "X-Auth-Token": api_key,+ "Accept": "application/json",+ }+++def _build_url(base_url: str, path: str, params: dict[str, Any]) -> str:+ if not params:+ return f"{base_url}{path}"+ return f"{base_url}{path}?{urlencode(params)}"+++def validate_credentials(api_key: str, region: str | None) -> tuple[bool, str | None]:+ """Confirm the API token is genuine with one cheap, low-limit list request.++ DocuSeal issues a single account-wide token (no per-resource scopes), so probing any list+ endpoint is sufficient. A 401 means the token is wrong; anything else reachable counts as valid.+ """+ url = _build_url(_base_url(region), "/templates", {"limit": 1})+ try:+ response = make_tracked_session().get(url, headers=_get_headers(api_key), timeout=10)+ except Exception:+ return False, "Could not reach DocuSeal. Check your network and try again."++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid DocuSeal API key. Create a new key in your DocuSeal account settings and reconnect."+ return False, f"DocuSeal API returned an unexpected status ({response.status_code}) while validating credentials."+++@retry(+ retry=retry_if_exception_type((DocusealRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict[str, Any]:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise DocusealRetryableError(f"DocuSeal API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"DocuSeal API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def get_rows(+ api_key: str,+ region: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DocusealResumeConfig],+) -> Iterator[Any]:+ config = DOCUSEAL_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ base_url = _base_url(region)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)+ # One session reused across every page so urllib3 keeps the connection alive.+ session = make_tracked_session()++ # DocuSeal orders list responses by `id` descending (newest first) and paginates *backwards*:+ # `pagination.next` is the smallest id on the page, and passing it as `after` returns the next+ # page of older (smaller-id) records. There is no server-side time filter, so this is a full+ # walk newest -> oldest. Resume picks back up from the saved cursor.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ after: int | None = resume.after if resume is not None else None+ if resume is not None:+ logger.debug(f"DocuSeal: resuming {endpoint} from after={after}")++ while True:+ params: dict[str, Any] = {"limit": PAGE_SIZE}+ if after is not None:+ params["after"] = after++ data = _fetch_page(session, _build_url(base_url, config.path, params), headers, logger)+ rows = data.get("data", [])+ if not rows:+ break++ for row in rows:+ batcher.batch(row)+ if batcher.should_yield():+ yield batcher.get_table()+ # Save the cursor of the page we're on (not the next one) AFTER yielding, so a crash+ # re-fetches this page rather than skipping rows still buffered. Merge dedupes on the+ # primary key.+ resumable_source_manager.save_state(DocusealResumeConfig(after=after))++ next_cursor = data.get("pagination", {}).get("next")+ # A null `next` or a short page (< limit) both signal the end of the list. Either way we+ # stop without issuing a final empty request.+ if not next_cursor or len(rows) < PAGE_SIZE:+ break+ after = next_cursor++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def docuseal_source(+ api_key: str,+ region: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DocusealResumeConfig],+) -> SourceResponse:+ endpoint_config: DocusealEndpointConfig = DOCUSEAL_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ region=region,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=endpoint_config.primary_keys,+ # Rows arrive newest-first; declare it so the pipeline doesn't assume ascending order.+ sort_mode="desc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[endpoint_config.partition_key],+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/docuseal/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/docuseal/settings.pynew file mode 100644index 000000000000..53e09c7b2703--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/docuseal/settings.py@@ -0,0 +1,27 @@+from dataclasses import dataclass, field+++@dataclass+class DocusealEndpointConfig:+ name: str+ path: str+ # `created_at` is stable for the row's lifetime, so it's a safe datetime partition key.+ # (DocuSeal objects also carry `updated_at`, but that shifts on every edit and would+ # rewrite partitions each sync, so we never partition on it.)+ partition_key: str = "created_at"+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+++# DocuSeal exposes three top-level list endpoints. Each is a flat `{"data": [...],+# "pagination": {...}}` response paginated by record id (see docuseal.py). The API has no+# server-side timestamp filter and objects mutate over their lifetime (a submission walks+# pending -> completed -> declined), so every table is full refresh — an append-only sync keyed+# on the monotonic id would only ever capture new records and silently miss those status updates.+DOCUSEAL_ENDPOINTS: dict[str, DocusealEndpointConfig] = {+ "templates": DocusealEndpointConfig(name="templates", path="/templates"),+ "submissions": DocusealEndpointConfig(name="submissions", path="/submissions"),+ "submitters": DocusealEndpointConfig(name="submitters", path="/submitters"),+}++ENDPOINTS = tuple(DOCUSEAL_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/docuseal/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/docuseal/source.pyindex 848cf4da740c..db0460902cf9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/docuseal/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/docuseal/source.py@@ -3,28 +3,153 @@ from typing import castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.docuseal.docuseal import (+ DocusealResumeConfig,+ docuseal_source,+ validate_credentials as validate_docuseal_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.docuseal.settings import (+ DOCUSEAL_ENDPOINTS,+ ENDPOINTS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DocusealSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class DocusealSource(SimpleSource[DocusealSourceConfig]):+class DocusealSource(ResumableSource[DocusealSourceConfig, DocusealResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.DOCUSEAL+ @property+ def connection_host_fields(self) -> list[str]:+ # `region` picks the host the stored API key is sent to; retargeting it (us <-> eu) must+ # re-require the key so a preserved credential can't be replayed against a different host.+ return ["region"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.DOCUSEAL,category=DataWarehouseSourceCategory.SALES,- label="Docuseal",+ label="DocuSeal",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your DocuSeal API key to sync your templates, submissions, and submitters into the PostHog Data warehouse.++Create an API key under **Settings → API** in your [DocuSeal console](https://console.docuseal.com/api). The key has full account access — DocuSeal does not offer per-resource scopes.++Pick the region your DocuSeal account is hosted in. Self-hosted deployments are not supported yet.""",iconPath="/static/services/docuseal.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/docuseal",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="DocuSeal API key",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="Global (api.docuseal.com)", value="us"),+ SourceFieldSelectConfigOption(label="EU (api.docuseal.eu)", value="eu"),+ ],+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.docuseal.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # DocuSeal returns 401 for a missing/invalid/revoked token. Retrying can never fix a+ # credential problem, so stop the sync and surface an actionable message. Match the stable+ # status text plus base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.docuseal.com": "Your DocuSeal API key is invalid or has been revoked. Create a new key in your DocuSeal account settings, then reconnect.",+ "401 Client Error: Unauthorized for url: https://api.docuseal.eu": "Your DocuSeal API key is invalid or has been revoked. Create a new key in your DocuSeal account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.docuseal.com": "Your DocuSeal API key does not have access to this data. Check the key in your DocuSeal account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.docuseal.eu": "Your DocuSeal API key does not have access to this data. Check the key in your DocuSeal account settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: DocusealSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Full refresh only: DocuSeal has no server-side timestamp filter, and its records mutate+ # (submission status transitions), so neither incremental nor append-only sync would capture+ # updates correctly. See settings.py for the full reasoning.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ should_sync_default=DOCUSEAL_ENDPOINTS[endpoint].should_sync_default,+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: DocusealSourceConfig, team_id: int, schema_name: str | None = None+ ) -> tuple[bool, str | None]:+ return validate_docuseal_credentials(config.api_key, config.region)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DocusealResumeConfig]:+ return ResumableSourceManager[DocusealResumeConfig](inputs, DocusealResumeConfig)++ def source_for_pipeline(+ self,+ config: DocusealSourceConfig,+ resumable_source_manager: ResumableSourceManager[DocusealResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return docuseal_source(+ api_key=config.api_key,+ region=config.region,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/docuseal/tests/test_docuseal.py b/products/warehouse_sources/backend/temporal/data_imports/sources/docuseal/tests/test_docuseal.pynew file mode 100644index 000000000000..decb894886a1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/docuseal/tests/test_docuseal.py@@ -0,0 +1,241 @@+from typing import Any+from urllib.parse import parse_qs, urlparse++from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.docuseal import docuseal+from products.warehouse_sources.backend.temporal.data_imports.sources.docuseal.docuseal import (+ DEFAULT_REGION,+ DOCUSEAL_HOSTS,+ PAGE_SIZE,+ DocusealResumeConfig,+ _base_url,+ _build_url,+ docuseal_source,+ get_rows,+ validate_credentials,+)+++def _ok_json_response(payload: dict | list | None = None, status_code: int = 200) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.json.return_value = payload if payload is not None else {}+ response.raise_for_status = MagicMock()+ return response+++class _FakeResumableManager:+ def __init__(self, state: DocusealResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[DocusealResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> DocusealResumeConfig | None:+ return self._state++ def save_state(self, data: DocusealResumeConfig) -> None:+ self.saved.append(data)+++class TestBaseUrl:+ @parameterized.expand(+ [+ ("us", DOCUSEAL_HOSTS["us"]),+ ("eu", DOCUSEAL_HOSTS["eu"]),+ (None, DOCUSEAL_HOSTS[DEFAULT_REGION]),+ ("", DOCUSEAL_HOSTS[DEFAULT_REGION]),+ ("unknown", DOCUSEAL_HOSTS[DEFAULT_REGION]),+ ]+ )+ def test_picks_correct_base_url(self, region: str | None, expected: str) -> None:+ assert _base_url(region) == expected+++class TestBuildUrl:+ def test_no_params(self) -> None:+ assert _build_url("https://api.docuseal.com", "/templates", {}) == "https://api.docuseal.com/templates"++ def test_with_params_is_urlencoded(self) -> None:+ url = _build_url("https://api.docuseal.com", "/submissions", {"limit": 100, "after": 42})+ assert url == "https://api.docuseal.com/submissions?limit=100&after=42"+++class TestValidateCredentials:+ @patch.object(docuseal, "make_tracked_session")+ def test_returns_true_on_200(self, mock_session: MagicMock) -> None:+ mock_session.return_value.get.return_value = _ok_json_response({"data": []})++ success, error = validate_credentials("key", "us")++ assert success is True+ assert error is None+ called_url = mock_session.return_value.get.call_args.args[0]+ assert called_url == f"{DOCUSEAL_HOSTS['us']}/templates?limit=1"++ def test_probes_selected_region_host(self) -> None:+ with patch.object(docuseal, "make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _ok_json_response({"data": []})+ validate_credentials("key", "eu")+ called_url = mock_session.return_value.get.call_args.args[0]+ assert called_url.startswith(DOCUSEAL_HOSTS["eu"])++ @parameterized.expand(+ [+ (401, "invalid"),+ (500, "unexpected status"),+ ]+ )+ @patch.object(docuseal, "make_tracked_session")+ def test_returns_false_on_http_status(+ self, status_code: int, expected_substring: str, mock_session: MagicMock+ ) -> None:+ mock_session.return_value.get.return_value = _ok_json_response(status_code=status_code)++ success, error = validate_credentials("key", "us")++ assert success is False+ assert error is not None+ assert expected_substring.lower() in error.lower()++ @patch.object(docuseal, "make_tracked_session")+ def test_returns_false_on_network_error(self, mock_session: MagicMock) -> None:+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")++ success, error = validate_credentials("key", "us")++ assert success is False+ assert error is not None+ assert "could not reach docuseal" in error.lower()+++def _page(rows: list[dict[str, Any]], next_cursor: int | None) -> dict[str, Any]:+ return {"data": rows, "pagination": {"count": len(rows), "next": next_cursor, "prev": None}}+++def _rows(start_id: int, count: int) -> list[dict[str, Any]]:+ """`count` rows in DocuSeal's newest-first (descending id) order, starting at `start_id`."""+ return [{"id": start_id - offset, "created_at": "2026-01-01T00:00:00Z"} for offset in range(count)]+++class TestGetRows:+ @staticmethod+ def _run(+ manager: _FakeResumableManager,+ pages: list[dict[str, Any]],+ endpoint: str = "templates",+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:+ """Drive get_rows against a queue of page responses. Returns (rows, recorded_requests)."""+ queue = list(pages)+ recorded: list[dict[str, Any]] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict[str, Any]:+ query = parse_qs(urlparse(url).query)+ recorded.append(+ {+ "url": url,+ "after": int(query["after"][0]) if "after" in query else None,+ "limit": int(query["limit"][0]) if "limit" in query else None,+ }+ )+ return queue.pop(0)++ with patch.object(docuseal, "_fetch_page", side_effect=fake_fetch):+ rows: list[dict[str, Any]] = []+ for table in get_rows(+ api_key="tok",+ region="us",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(table.to_pylist())+ return rows, recorded++ def test_single_short_page_terminates_without_extra_request(self) -> None:+ manager = _FakeResumableManager()+ rows, recorded = self._run(manager, [_page(_rows(3, 3), next_cursor=1)])++ assert [r["id"] for r in rows] == [3, 2, 1]+ # A page shorter than the page size is the last one — no follow-up request.+ assert len(recorded) == 1+ assert recorded[0]["after"] is None+ assert recorded[0]["limit"] == PAGE_SIZE++ def test_walks_pages_using_after_cursor(self) -> None:+ manager = _FakeResumableManager()+ pages = [+ _page(_rows(300, PAGE_SIZE), next_cursor=201),+ _page(_rows(200, PAGE_SIZE), next_cursor=101),+ _page(_rows(100, 50), next_cursor=51),+ ]+ rows, recorded = self._run(manager, pages)++ assert len(rows) == 250+ assert [r["after"] for r in recorded] == [None, 201, 101]+ # Newest-first across the whole walk.+ assert rows[0]["id"] == 300+ assert rows[-1]["id"] == 51++ def test_stops_when_next_cursor_is_null(self) -> None:+ manager = _FakeResumableManager()+ # A full-size page whose `next` is null (empty next page) must still terminate.+ rows, recorded = self._run(manager, [_page(_rows(100, PAGE_SIZE), next_cursor=None)])++ assert len(rows) == PAGE_SIZE+ assert len(recorded) == 1++ def test_empty_first_page_yields_nothing(self) -> None:+ manager = _FakeResumableManager()+ rows, recorded = self._run(manager, [_page([], next_cursor=None)])++ assert rows == []+ assert len(recorded) == 1++ def test_resume_uses_saved_after_cursor(self) -> None:+ manager = _FakeResumableManager(DocusealResumeConfig(after=500))+ rows, recorded = self._run(manager, [_page(_rows(499, 2), next_cursor=498)])++ # First request must continue from the saved cursor, not start over.+ assert recorded[0]["after"] == 500+ assert [r["id"] for r in rows] == [499, 498]++ def test_saves_only_already_fetched_cursors_after_yield(self) -> None:+ # Force a mid-stream batch flush by exceeding the batcher's row threshold, then assert we never+ # persist a cursor we haven't fetched from yet (the "save current page, not next" invariant) —+ # otherwise a crash would skip rows still buffered.+ manager = _FakeResumableManager()+ pages = [+ _page(_rows(10000 - i * PAGE_SIZE, PAGE_SIZE), next_cursor=10000 - i * PAGE_SIZE - 99) for i in range(30)+ ]+ pages.append(_page(_rows(10000 - 30 * PAGE_SIZE, 10), next_cursor=1))+ rows, recorded = self._run(manager, pages)++ assert len(rows) == 30 * PAGE_SIZE + 10+ assert manager.saved, "expected at least one mid-stream save once the batch threshold was crossed"+ fetched_afters = {r["after"] for r in recorded}+ assert all(saved.after in fetched_afters for saved in manager.saved)+++class TestDocusealSourceResponse:+ @parameterized.expand(["templates", "submissions", "submitters"])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = docuseal_source(+ api_key="tok",+ region="us",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )++ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # Rows arrive newest-first, so the pipeline must not assume ascending order.+ assert response.sort_mode == "desc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/docuseal/tests/test_docuseal_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/docuseal/tests/test_docuseal_source.pynew file mode 100644index 000000000000..0bc46d727ff5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/docuseal/tests/test_docuseal_source.py@@ -0,0 +1,157 @@+from typing import cast++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.docuseal import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.docuseal.docuseal import DocusealResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.docuseal.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.docuseal.source import DocusealSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DocusealSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(api_key: str = "tok", region: str = "us") -> DocusealSourceConfig:+ return DocusealSourceConfig(api_key=api_key, region=region) # type: ignore[arg-type]+++class TestDocusealSourceConfig:+ def test_source_type(self) -> None:+ assert DocusealSource().source_type == ExternalDataSourceType.DOCUSEAL++ def test_visible_and_alpha(self) -> None:+ cfg = DocusealSource().get_source_config+ # A finished source ships visible (no unreleasedSource) and labelled alpha.+ assert cfg.unreleasedSource is None+ assert cfg.releaseStatus == ReleaseStatus.ALPHA+ assert cfg.category == DataWarehouseSourceCategory.SALES+ assert cfg.docsUrl == "https://posthog.com/docs/cdp/sources/docuseal"++ def test_exposes_api_key_and_region_fields(self) -> None:+ cfg = DocusealSource().get_source_config+ names = {f.name for f in cfg.fields}+ assert names == {"api_key", "region"}++ api_key_field = next(f for f in cfg.fields if f.name == "api_key")+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.required is True+ assert api_key_field.secret is True+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD++ region_field = next(f for f in cfg.fields if f.name == "region")+ assert isinstance(region_field, SourceFieldSelectConfig)+ assert region_field.required is True+ assert region_field.defaultValue == "us"+ assert {opt.value for opt in region_field.options} == {"us", "eu"}++ def test_region_is_a_connection_host_field(self) -> None:+ # `region` decides which host the stored API key is sent to, so changing it must force the+ # editor to re-enter the secret instead of replaying it against a different host.+ assert DocusealSource().connection_host_fields == ["region"]+++class TestDocusealSchemas:+ def test_lists_all_endpoints_as_full_refresh(self) -> None:+ schemas = {s.name: s for s in DocusealSource().get_schemas(_config(), team_id=1)}+ assert set(schemas) == set(ENDPOINTS)+ for schema in schemas.values():+ # No server-side time filter and mutable records -> full refresh only.+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_names_filter_subsets_schemas(self) -> None:+ schemas = DocusealSource().get_schemas(_config(), team_id=1, names=["submissions"])+ assert [s.name for s in schemas] == ["submissions"]++ def test_lists_tables_without_credentials_for_docs(self) -> None:+ source = DocusealSource()+ assert source.lists_tables_without_credentials is True+ tables = source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ for table in tables:+ assert table["sync_methods"] == ["Full refresh"]++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ descriptions = DocusealSource().get_canonical_descriptions()+ assert set(descriptions) == set(ENDPOINTS)+++class TestDocusealCredentials:+ @patch.object(source_module, "validate_docuseal_credentials", return_value=(True, None))+ def test_delegates_to_transport(self, mock_validate: MagicMock) -> None:+ ok, error = DocusealSource().validate_credentials(_config(region="eu"), team_id=1)+ assert ok is True+ assert error is None+ mock_validate.assert_called_once_with("tok", "eu")++ @patch.object(source_module, "validate_docuseal_credentials", return_value=(False, "Invalid DocuSeal API key."))+ def test_propagates_failure(self, _mock_validate: MagicMock) -> None:+ ok, error = DocusealSource().validate_credentials(_config(), team_id=1)+ assert ok is False+ assert error == "Invalid DocuSeal API key."+++class TestDocusealNonRetryableErrors:+ @parameterized.expand(+ [+ ("us_unauthorized", "401 Client Error: Unauthorized for url: https://api.docuseal.com/templates?limit=100"),+ ("eu_unauthorized", "401 Client Error: Unauthorized for url: https://api.docuseal.eu/submissions"),+ ("us_forbidden", "403 Client Error: Forbidden for url: https://api.docuseal.com/submitters"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = DocusealSource().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.docuseal.com/templates"),+ ("rate_limit", "429 Client Error: Too Many Requests for url: https://api.docuseal.com/submissions"),+ ("timeout", "HTTPSConnectionPool(host='api.docuseal.com', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = DocusealSource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestDocusealPipelineWiring:+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = DocusealSource().get_resumable_source_manager(MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is DocusealResumeConfig++ def test_source_for_pipeline_plumbs_inputs(self) -> None:+ captured: dict[str, object] = {}++ def fake_source(**kwargs: object) -> object:+ captured.update(kwargs)+ return "sentinel"++ inputs = MagicMock()+ inputs.schema_name = "submissions"+ manager = MagicMock()+ logger = MagicMock()+ inputs.logger = logger++ with patch.object(source_module, "docuseal_source", side_effect=fake_source) as mock_source:+ result = DocusealSource().source_for_pipeline(_config(region="eu"), manager, inputs)++ assert cast(object, result) == "sentinel"+ mock_source.assert_called_once()+ assert captured["api_key"] == "tok"+ assert captured["region"] == "eu"+ assert captured["endpoint"] == "submissions"+ assert captured["resumable_source_manager"] is manager+ assert captured["logger"] is loggerdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex bb4fe39f4c4a..dc13ef78ae76 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@@ -947,7 +947,8 @@ class DockerhubSourceConfig(config.Config):@config.configclass DocusealSourceConfig(config.Config):- pass+ api_key: str+ region: Literal["us", "eu"] = config.value(default="us")@config.config