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 boldsign import source (#66732)

Tom Owers6b8a53930c49
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 6cd48d07920d..84979146327c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -68,6 +68,7 @@ the row lists both.
| bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) |
| bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ |
| blogger | HTTP | requests | ✅ |
+| boldsign | HTTP | requests | ✅ |
| braintree | HTTP (GraphQL) | requests | ✅ |
| braze | HTTP | requests | ✅ |
| breezometer | HTTP | requests | ✅ |
@@ -329,7 +330,6 @@ doesn't conflict with concurrent PRs.
- bigcommerce
- bitly
- bluetally
-- boldsign
- box
- braintrust
- branch
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/boldsign/boldsign.py b/products/warehouse_sources/backend/temporal/data_imports/sources/boldsign/boldsign.py
new file mode 100644
index 000000000000..0117c430d555
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/boldsign/boldsign.py
@@ -0,0 +1,202 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+
+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.boldsign.settings import (
+ BOLDSIGN_ENDPOINTS,
+ BoldSignEndpointConfig,
+)
+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
+
+# BoldSign serves separate US and EU regional hosts; the account decides which one is live.
+BOLDSIGN_HOSTS = {
+ "us": "https://api.boldsign.com",
+ "eu": "https://api-eu.boldsign.com",
+}
+PAGE_SIZE = 100
+# Page-number access is capped at 10,000 records; document/list pages past it via NextCursor.
+RECORD_CURSOR_THRESHOLD = 10_000
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 5
+# Backstop against a non-advancing cursor looping forever (10k records / 100 per page ≈ 100 pages,
+# so this only trips on a genuinely misbehaving response).
+MAX_PAGES = 100_000
+
+
+class BoldSignRetryableError(Exception):
+ pass
+
+
+class BoldSignResumeConfig:
+ # Page-number position for standard pagination.
+ page: int = 1
+ # Set once we cross the 10,000-record page cap on document/list and switch to cursor paging.
+ # BoldSign describes this as an opaque value; the concrete type (int vs str) is unverified.
+ next_cursor: str | int | None = None
+ # Running total used to know when to switch to cursor paging.
+ records_fetched: int = 0
+
+
+def _base_url(region: str) -> str:
+ host = BOLDSIGN_HOSTS.get(region)
+ if host is None:
+ raise ValueError(f"Invalid BoldSign region: {region}")
+ return host
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "X-API-KEY": api_key,
+ "Accept": "application/json",
+ }
+
+
+@retry(
+ retry=retry_if_exception_type((BoldSignRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=2, max=90),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ response = session.get(url, headers=headers, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # 429 (account-level rate limit, 2000/hour prod) and transient 5xx are retried with backoff.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise BoldSignRetryableError(f"BoldSign API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"BoldSign API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def validate_credentials(region: str, api_key: str) -> tuple[bool, str | None]:
+ """Confirm the API key is genuine with one cheap, low-privilege list call."""
+ url = f"{_base_url(region)}/v1/document/list"
+ try:
+ response = make_tracked_session(redact_values=(api_key,)).get(
+ url,
+ headers=_get_headers(api_key),
+ params={"Page": 1, "PageSize": 1},
+ timeout=10,
+ )
+ except Exception as e:
+ # A network error (timeout, connection failure) is not an auth problem — surface the
+ # real cause instead of misreporting it as an invalid key and sending the user on a
+ # fruitless key-rotation hunt during a transient outage.
+ return False, f"Could not reach BoldSign: {e}"
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code in (401, 403):
+ return False, "Invalid BoldSign API key"
+ return False, f"Unexpected response from BoldSign (status {response.status_code})"
+
+
+def get_rows(
+ region: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BoldSignResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = BOLDSIGN_ENDPOINTS[endpoint]
+ url = f"{_base_url(region)}{config.path}"
+ headers = _get_headers(api_key)
+ session = make_tracked_session(redact_values=(api_key,))
+
+ if not config.paginated:
+ data = _fetch_page(session, url, headers, dict(config.extra_params), logger)
+ items = data.get(config.data_key) or []
+ if items:
+ yield items
+ return
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.page if resume is not None else 1
+ next_cursor = resume.next_cursor if resume is not None else None
+ records_fetched = resume.records_fetched if resume is not None else 0
+ if resume is not None:
+ logger.debug(f"BoldSign: resuming {endpoint} from page={page}, next_cursor={next_cursor}")
+
+ for _ in range(MAX_PAGES):
+ params: dict[str, Any] = dict(config.extra_params)
+ params["Page"] = page
+ params["PageSize"] = PAGE_SIZE
+ if next_cursor is not None:
+ params["NextCursor"] = next_cursor
+
+ data = _fetch_page(session, url, headers, params, logger)
+ items = data.get(config.data_key) or []
+ if not items:
+ break
+
+ yield items
+ records_fetched += len(items)
+
+ # A short page means we've reached the end.
+ if len(items) < PAGE_SIZE:
+ break
+
+ if records_fetched >= RECORD_CURSOR_THRESHOLD:
+ if not config.supports_cursor:
+ # Page-number access is capped at 10k and this endpoint can't cursor past it.
+ logger.warning(
+ f"BoldSign: {endpoint} reached the 10,000-record page-number cap; "
+ "remaining records are not synced (endpoint has no cursor pagination)."
+ )
+ break
+ last_cursor = items[-1].get("cursor")
+ # No (or non-advancing) cursor means we can't make progress; stop rather than loop.
+ if last_cursor is None or last_cursor == next_cursor:
+ break
+ next_cursor = last_cursor
+ page = 1
+ else:
+ page += 1
+
+ # Save AFTER yielding the page so a crash re-fetches from the next position and never
+ # skips a page; if we crash between the yield and this save, the prior state still points
+ # at the just-yielded page, which merge dedupes on the primary key.
+ resumable_source_manager.save_state(
+ BoldSignResumeConfig(page=page, next_cursor=next_cursor, records_fetched=records_fetched)
+ )
+
+
+def boldsign_source(
+ region: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BoldSignResumeConfig],
+) -> SourceResponse:
+ config: BoldSignEndpointConfig = BOLDSIGN_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ region=region,
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ # Full refresh only — BoldSign timestamps are int64 epoch values, not datetimes, so there
+ # is no stable datetime column to partition on.
+ partition_mode=None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/boldsign/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/boldsign/canonical_descriptions.py
new file mode 100644
index 000000000000..f09597fd2493
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/boldsign/canonical_descriptions.py
@@ -0,0 +1,120 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "documents": {
+ "description": "Signature documents sent from the account, including their status, signers, and lifecycle dates.",
+ "docs_url": "https://developers.boldsign.com/documents/list-documents/",
+ "columns": {
+ "documentId": "Unique identifier of the document.",
+ "messageTitle": "Title of the document shown to recipients.",
+ "status": "Current status of the document (e.g. InProgress, Completed, Declined, Revoked, Expired, Draft).",
+ "displayStatus": "Human-readable status label for display.",
+ "senderDetail": "Details of the user who sent the document.",
+ "ccDetails": "Recipients copied on the document.",
+ "signerDetails": "Recipients required to act on the document, with their roles and status.",
+ "createdDate": "Unix epoch timestamp for when the document was created.",
+ "activityDate": "Unix epoch timestamp of the most recent activity on the document.",
+ "activityBy": "Email of the user responsible for the most recent activity.",
+ "expiryDate": "Unix epoch timestamp for when the document expires.",
+ "scheduledSendTime": "Unix epoch timestamp for a scheduled send, if configured.",
+ "enableSigningOrder": "Whether recipients must sign in a defined order.",
+ "isDeleted": "Whether the document has been deleted.",
+ "inEditingMode": "Whether the document is currently being edited.",
+ "labels": "Labels applied to the document.",
+ "brandId": "Identifier of the brand applied to the document.",
+ "cursor": "Opaque pagination cursor used to page past the 10,000-record limit.",
+ },
+ },
+ "templates": {
+ "description": "Reusable document templates defined in the account.",
+ "docs_url": "https://developers.boldsign.com/templates/list-templates/",
+ "columns": {
+ "documentId": "Unique identifier of the template.",
+ "templateName": "Name of the template.",
+ "templateDescription": "Description of the template.",
+ "messageTitle": "Default title applied to documents created from the template.",
+ "status": "Current status of the template.",
+ "senderDetail": "Details of the user who owns the template.",
+ "ccDetails": "Recipients copied by default on documents from this template.",
+ "signerDetails": "Default signer roles configured on the template.",
+ "accessType": "Sharing/access type of the template (e.g. mine, shared).",
+ "isTemplate": "Always true for template records.",
+ "enableSigningOrder": "Whether recipients must sign in a defined order.",
+ "createdDate": "Unix epoch timestamp for when the template was created.",
+ "activityDate": "Unix epoch timestamp of the most recent activity on the template.",
+ "templateLabels": "Labels applied to the template.",
+ "brandId": "Identifier of the brand applied to the template.",
+ },
+ },
+ "users": {
+ "description": "Users belonging to the BoldSign account, including their team and role.",
+ "docs_url": "https://developers.boldsign.com/users/list-users/",
+ "columns": {
+ "userId": "Unique identifier of the user.",
+ "email": "Email address of the user.",
+ "firstName": "First name of the user.",
+ "lastName": "Last name of the user.",
+ "teamId": "Identifier of the team the user belongs to.",
+ "teamName": "Name of the team the user belongs to.",
+ "role": "Role assigned to the user.",
+ "userStatus": "Current status of the user (e.g. active, invited).",
+ "createdDate": "Unix epoch timestamp for when the user was created.",
+ "modifiedDate": "Unix epoch timestamp for when the user was last modified.",
+ },
+ },
+ "teams": {
+ "description": "Teams configured in the BoldSign account.",
+ "docs_url": "https://developers.boldsign.com/teams/list-teams/",
+ "columns": {
+ "teamId": "Unique identifier of the team.",
+ "teamName": "Name of the team.",
+ "createdDate": "Unix epoch timestamp for when the team was created.",
+ "modifiedDate": "Unix epoch timestamp for when the team was last modified.",
+ },
+ },
+ "contacts": {
+ "description": "Address-book contacts available when preparing documents.",
+ "docs_url": "https://developers.boldsign.com/contacts/list-contacts/",
+ "columns": {
+ "id": "Unique identifier of the contact.",
+ "name": "Full name of the contact.",
+ "email": "Email address of the contact.",
+ "companyName": "Company the contact belongs to.",
+ "jobTitle": "Job title of the contact.",
+ "phoneNumber": "Phone number of the contact.",
+ },
+ },
+ "sender_identities": {
+ "description": "Verified sender identities that documents can be sent on behalf of.",
+ "docs_url": "https://developers.boldsign.com/sender-identities/list-sender-identities/",
+ "columns": {
+ "id": "Unique identifier of the sender identity.",
+ "name": "Display name of the sender identity.",
+ "email": "Email address of the sender identity.",
+ "status": "Verification status of the sender identity.",
+ "createdBy": "Email of the user who created the sender identity.",
+ "approvedDate": "Date the sender identity was approved.",
+ "brandId": "Identifier of the brand associated with the sender identity.",
+ "redirectUrl": "Redirect URL configured for the sender identity.",
+ "locale": "Locale configured for the sender identity.",
+ },
+ },
+ "brands": {
+ "description": "Branding configurations (logos, colors, disclaimers) applied to documents.",
+ "docs_url": "https://developers.boldsign.com/brandings/list-brands/",
+ "columns": {
+ "brandId": "Unique identifier of the brand.",
+ "brandName": "Name of the brand.",
+ "brandLogo": "URL of the brand logo.",
+ "backgroundColor": "Background color used by the brand.",
+ "buttonColor": "Button color used by the brand.",
+ "buttonTextColor": "Button text color used by the brand.",
+ "emailDisplayName": "Display name shown on outgoing emails for the brand.",
+ "isDefault": "Whether this is the account's default brand.",
+ "redirectUrl": "Redirect URL configured for the brand.",
+ "documentTimeZone": "Time zone applied to documents using this brand.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/boldsign/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/boldsign/settings.py
new file mode 100644
index 000000000000..9e433612f4e2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/boldsign/settings.py
@@ -0,0 +1,71 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class BoldSignEndpointConfig:
+ name: str
+ path: str
+ # Most list endpoints wrap their rows in a `result` array; teams uses `results`.
+ data_key: str = "result"
+ primary_keys: list[str] = field(default_factory=lambda: ["documentId"])
+ # `brand/list` returns the full set in one response with no pagination params.
+ paginated: bool = True
+ # Only `document/list` exposes a `cursor` field + `NextCursor` param to page past the
+ # 10,000-record cap that page-number access is limited to. Other endpoints stay page-only.
+ supports_cursor: bool = False
+ # Static query params always sent for the endpoint (e.g. widening filters to "all").
+ extra_params: dict[str, str] = field(default_factory=dict)
+ should_sync_default: bool = True
+
+
+# Curated catalog of the BoldSign list endpoints a user is likely to sync. Cross-referenced
+# against the public Swagger (https://api.boldsign.com/swagger/v1/swagger.json). Every endpoint
+# is full refresh: the only server-side date filter BoldSign documents (document/list's
+# StartDate/EndDate with DateFilterType=SentBetween) filters on the document *transmit* date and
+# has no matching stable cursor field in the response, so there is no reliable incremental field.
+BOLDSIGN_ENDPOINTS: dict[str, BoldSignEndpointConfig] = {
+ "documents": BoldSignEndpointConfig(
+ name="documents",
+ path="/v1/document/list",
+ primary_keys=["documentId"],
+ supports_cursor=True,
+ ),
+ "templates": BoldSignEndpointConfig(
+ name="templates",
+ path="/v1/template/list",
+ primary_keys=["documentId"],
+ # Without TemplateType the API only returns the caller's own templates; "all" also
+ # surfaces templates shared with the account.
+ extra_params={"TemplateType": "all"},
+ ),
+ "users": BoldSignEndpointConfig(
+ name="users",
+ path="/v1/users/list",
+ primary_keys=["userId"],
+ ),
+ "teams": BoldSignEndpointConfig(
+ name="teams",
+ path="/v1/teams/list",
+ data_key="results",
+ primary_keys=["teamId"],
+ ),
+ "contacts": BoldSignEndpointConfig(
+ name="contacts",
+ path="/v1/contacts/list",
+ primary_keys=["id"],
+ extra_params={"ContactType": "AllContacts"},
+ ),
+ "sender_identities": BoldSignEndpointConfig(
+ name="sender_identities",
+ path="/v1/senderIdentities/list",
+ primary_keys=["id"],
+ ),
+ "brands": BoldSignEndpointConfig(
+ name="brands",
+ path="/v1/brand/list",
+ primary_keys=["brandId"],
+ paginated=False,
+ ),
+}
+
+ENDPOINTS = tuple(BOLDSIGN_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/boldsign/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/boldsign/source.py
index a40d8b1cc877..5bfb0f11db51 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/boldsign/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/boldsign/source.py
@@ -1,19 +1,44 @@
-from typing import cast
+from typing import Optional, cast
from 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.boldsign.boldsign import (
+ BoldSignResumeConfig,
+ boldsign_source,
+ validate_credentials as validate_boldsign_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.boldsign.settings import (
+ BOLDSIGN_ENDPOINTS,
+ ENDPOINTS,
+)
+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 BoldSignSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class BoldSignSource(SimpleSource[BoldSignSourceConfig]):
+class BoldSignSource(ResumableSource[BoldSignSourceConfig, BoldSignResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BOLDSIGN
@@ -24,7 +49,102 @@ class BoldSignSource(SimpleSource[BoldSignSourceConfig]):
name=SchemaExternalDataSourceType.BOLD_SIGN,
category=DataWarehouseSourceCategory.SALES,
label="BoldSign",
- iconPath="/static/services/boldsign.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your BoldSign API key to pull your eSignature documents, templates, and contacts into the PostHog Data warehouse.
+
+Create an API key in your [BoldSign account settings](https://app.boldsign.com/settings) under **API** → **API Key**. API keys carry all scopes by default.
+
+Pick the region your BoldSign account lives in — accounts are hosted on either the US (`api.boldsign.com`) or EU (`api-eu.boldsign.com`) host.""",
+ iconPath="/static/services/boldsign.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/boldsign",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldSelectConfig(
+ name="region",
+ label="Region",
+ required=True,
+ defaultValue="us",
+ options=[
+ SourceFieldSelectConfigOption(label="US", value="us"),
+ SourceFieldSelectConfigOption(label="EU", value="eu"),
+ ],
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.boldsign.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.
+ # Retrying can never satisfy a credential problem, so stop the sync. Match the stable
+ # status text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://api.boldsign.com": "Your BoldSign API key is invalid or has been revoked. Create a new key in your BoldSign account settings, then reconnect.",
+ "401 Client Error: Unauthorized for url: https://api-eu.boldsign.com": "Your BoldSign API key is invalid or has been revoked. Create a new key in your BoldSign account settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.boldsign.com": "Your BoldSign API key does not have permission to access this data. Check the key's permissions, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api-eu.boldsign.com": "Your BoldSign API key does not have permission to access this data. Check the key's permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: BoldSignSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ # BoldSign has no reliable server-side updated-since filter, so every table is
+ # full refresh (no incremental / append).
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ should_sync_default=BOLDSIGN_ENDPOINTS[endpoint].should_sync_default,
+ detected_primary_keys=BOLDSIGN_ENDPOINTS[endpoint].primary_keys,
+ )
+ 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: BoldSignSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_boldsign_credentials(config.region, config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BoldSignResumeConfig]:
+ return ResumableSourceManager[BoldSignResumeConfig](inputs, BoldSignResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BoldSignSourceConfig,
+ resumable_source_manager: ResumableSourceManager[BoldSignResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return boldsign_source(
+ region=config.region,
+ 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/boldsign/tests/test_boldsign.py b/products/warehouse_sources/backend/temporal/data_imports/sources/boldsign/tests/test_boldsign.py
new file mode 100644
index 000000000000..fd5ec008b3a2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/boldsign/tests/test_boldsign.py
@@ -0,0 +1,196 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.boldsign import boldsign
+from products.warehouse_sources.backend.temporal.data_imports.sources.boldsign.boldsign import (
+ BOLDSIGN_HOSTS,
+ PAGE_SIZE,
+ BoldSignResumeConfig,
+ _base_url,
+ _get_headers,
+ boldsign_source,
+ get_rows,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.boldsign.settings import BOLDSIGN_ENDPOINTS
+
+
+class _FakeResumableManager:
+ def __init__(self, state: BoldSignResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[BoldSignResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> BoldSignResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: BoldSignResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _collect(
+ manager: _FakeResumableManager, monkeypatch: Any, endpoint: str, responses: list[dict]
+) -> tuple[list[dict], list[dict[str, Any]]]:
+ """Run get_rows against a queue of canned API responses and flatten the yielded pages."""
+ calls: list[dict[str, Any]] = []
+ queue = list(responses)
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], params: dict[str, Any], logger: Any) -> dict:
+ calls.append({"url": url, "params": dict(params)})
+ return queue.pop(0)
+
+ monkeypatch.setattr(boldsign, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(boldsign, "make_tracked_session", lambda *a, **k: MagicMock())
+
+ rows: list[dict] = []
+ for page in get_rows(
+ region="us",
+ api_key="key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(page)
+ return rows, calls
+
+
+class TestBaseUrlAndHeaders:
+ @pytest.mark.parametrize(
+ "region, expected",
+ [
+ ("us", "https://api.boldsign.com"),
+ ("eu", "https://api-eu.boldsign.com"),
+ ],
+ )
+ def test_base_url_per_region(self, region: str, expected: str) -> None:
+ assert _base_url(region) == expected
+ assert BOLDSIGN_HOSTS[region] == expected
+
+ def test_base_url_rejects_unknown_region(self) -> None:
+ with pytest.raises(ValueError):
+ _base_url("apac")
+
+ def test_headers_use_api_key_header(self) -> None:
+ headers = _get_headers("secret")
+ assert headers["X-API-KEY"] == "secret"
+ assert headers["Accept"] == "application/json"
+
+
+class TestPagination:
+ def test_non_paginated_endpoint_makes_single_request(self, monkeypatch: Any) -> None:
+ responses = [{"result": [{"brandId": "B1"}, {"brandId": "B2"}]}]
+ rows, calls = _collect(_FakeResumableManager(), monkeypatch, "brands", responses)
+ assert rows == [{"brandId": "B1"}, {"brandId": "B2"}]
+ assert len(calls) == 1
+ assert "Page" not in calls[0]["params"]
+
+ def test_short_page_terminates_pagination(self, monkeypatch: Any) -> None:
+ # A page shorter than PAGE_SIZE is the last page.
+ responses = [{"result": [{"documentId": "D1"}]}]
+ rows, calls = _collect(_FakeResumableManager(), monkeypatch, "documents", responses)
+ assert rows == [{"documentId": "D1"}]
+ assert len(calls) == 1
+ assert calls[0]["params"]["Page"] == 1
+ assert calls[0]["params"]["PageSize"] == PAGE_SIZE
+
+ def test_full_page_advances_to_next_page(self, monkeypatch: Any) -> None:
+ full = [{"documentId": f"D{i}"} for i in range(PAGE_SIZE)]
+ responses = [{"result": full}, {"result": [{"documentId": "last"}]}]
+ rows, calls = _collect(_FakeResumableManager(), monkeypatch, "documents", responses)
+ assert len(rows) == PAGE_SIZE + 1
+ assert [c["params"]["Page"] for c in calls] == [1, 2]
+
+ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:
+ rows, calls = _collect(_FakeResumableManager(), monkeypatch, "documents", [{"result": []}])
+ assert rows == []
+ assert len(calls) == 1
+
+ def test_teams_uses_results_data_key(self, monkeypatch: Any) -> None:
+ responses = [{"results": [{"teamId": "T1"}]}]
+ rows, _ = _collect(_FakeResumableManager(), monkeypatch, "teams", responses)
+ assert rows == [{"teamId": "T1"}]
+
+ def test_templates_send_template_type_param(self, monkeypatch: Any) -> None:
+ responses = [{"result": [{"documentId": "T1"}]}]
+ _, calls = _collect(_FakeResumableManager(), monkeypatch, "templates", responses)
+ assert calls[0]["params"]["TemplateType"] == "all"
+
+
+class TestResume:
+ def test_saves_next_page_after_yielding_each_full_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ full = [{"documentId": f"D{i}"} for i in range(PAGE_SIZE)]
+ responses = [{"result": full}, {"result": [{"documentId": "tail"}]}]
+ _collect(manager, monkeypatch, "documents", responses)
+ # Only the page that had a full page of results (page 1) saves state, pointing at page 2.
+ assert [s.page for s in manager.saved] == [2]
+
+ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(BoldSignResumeConfig(page=5, next_cursor=None, records_fetched=400))
+ responses = [{"result": [{"documentId": "D5"}]}]
+ _, calls = _collect(manager, monkeypatch, "documents", responses)
+ assert calls[0]["params"]["Page"] == 5
+
+
+class TestCursorPagination:
+ def test_documents_switch_to_cursor_past_record_threshold(self, monkeypatch: Any) -> None:
+ # Fill exactly the 10k page-cap with full pages, then expect a NextCursor request.
+ boldsign_threshold_pages = boldsign.RECORD_CURSOR_THRESHOLD // PAGE_SIZE
+ full_pages = [
+ {"result": [{"documentId": f"D{p}-{i}", "cursor": p * PAGE_SIZE + i} for i in range(PAGE_SIZE)]}
+ for p in range(boldsign_threshold_pages)
+ ]
+ # One more page reached via cursor, then a short page to stop.
+ cursor_page = {"result": [{"documentId": "after-cursor", "cursor": 999999}]}
+ responses = [*full_pages, cursor_page]
+
+ _, calls = _collect(_FakeResumableManager(), monkeypatch, "documents", responses)
+
+ last_call = calls[-1]
+ assert "NextCursor" in last_call["params"]
+ # The cursor passed is the last record's cursor from the final full page.
+ expected_cursor = full_pages[-1]["result"][-1]["cursor"]
+ assert last_call["params"]["NextCursor"] == expected_cursor
+
+ def test_non_cursor_endpoint_stops_at_record_threshold(self, monkeypatch: Any) -> None:
+ # users/list has no cursor support, so it must stop at the 10k page cap rather than loop.
+ threshold_pages = boldsign.RECORD_CURSOR_THRESHOLD // PAGE_SIZE
+ full_pages = [{"result": [{"userId": f"U{p}-{i}"} for i in range(PAGE_SIZE)]} for p in range(threshold_pages)]
+ # Provide an extra page that should never be requested.
+ responses = [*full_pages, {"result": [{"userId": "should-not-fetch"}]}]
+
+ rows, calls = _collect(_FakeResumableManager(), monkeypatch, "users", responses)
+
+ assert len(calls) == threshold_pages
+ assert len(rows) == boldsign.RECORD_CURSOR_THRESHOLD
+
+
+class TestSourceResponse:
+ @pytest.mark.parametrize(
+ "endpoint, expected_pk",
+ [
+ ("documents", ["documentId"]),
+ ("templates", ["documentId"]),
+ ("users", ["userId"]),
+ ("teams", ["teamId"]),
+ ("contacts", ["id"]),
+ ("sender_identities", ["id"]),
+ ("brands", ["brandId"]),
+ ],
+ )
+ def test_primary_keys_per_endpoint(self, endpoint: str, expected_pk: list[str]) -> None:
+ response = boldsign_source(
+ region="us",
+ api_key="key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == expected_pk
+ # Full refresh: BoldSign timestamps are epoch ints, so no datetime partitioning.
+ assert response.partition_mode is None
+ assert response.primary_keys == BOLDSIGN_ENDPOINTS[endpoint].primary_keys
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/boldsign/tests/test_boldsign_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/boldsign/tests/test_boldsign_source.py
new file mode 100644
index 000000000000..8566f91a6898
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/boldsign/tests/test_boldsign_source.py
@@ -0,0 +1,156 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.boldsign.boldsign import BoldSignResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.boldsign.settings import (
+ BOLDSIGN_ENDPOINTS,
+ ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.boldsign.source import BoldSignSource
+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 BoldSignSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestBoldSignSource:
+ def setup_method(self):
+ self.source = BoldSignSource()
+ self.team_id = 123
+ self.config = BoldSignSourceConfig(api_key="key", region="us")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.BOLDSIGN
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "BoldSign"
+ assert config.label == "BoldSign"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/boldsign"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["api_key", "region"]
+
+ def test_api_key_field_is_secret_password(self):
+ config = self.source.get_source_config
+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.secret is True
+ assert api_key_field.required is True
+
+ def test_region_field_is_a_select_with_us_default(self):
+ config = self.source.get_source_config
+ region_field = next(f for f in config.fields if f.name == "region")
+ assert isinstance(region_field, SourceFieldSelectConfig)
+ assert region_field.defaultValue == "us"
+ assert {option.value for option in region_field.options} == {"us", "eu"}
+
+ def test_lists_tables_without_credentials(self):
+ # Static endpoint catalog (no I/O) so the public docs can render Supported tables.
+ assert self.source.lists_tables_without_credentials is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.boldsign.com/v1/document/list?Page=1",
+ "401 Client Error: Unauthorized for url: https://api-eu.boldsign.com/v1/template/list?Page=1",
+ "403 Client Error: Forbidden for url: https://api.boldsign.com/v1/users/list",
+ "403 Client Error: Forbidden for url: https://api-eu.boldsign.com/v1/teams/list",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "429 Client Error: Too Many Requests for url: https://api.boldsign.com/v1/document/list",
+ "500 Server Error: Internal Server Error for url: https://api.boldsign.com/v1/document/list",
+ "HTTPSConnectionPool(host='api.boldsign.com', port=443): Read timed out.",
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ ],
+ )
+ def test_non_retryable_errors_does_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)
+
+ def test_get_schemas_lists_every_endpoint(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ def test_get_schemas_are_full_refresh_only(self):
+ # BoldSign has no reliable updated-since cursor, so nothing supports incremental/append.
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert all(not schema.supports_incremental for schema in schemas)
+ assert all(not schema.supports_append for schema in schemas)
+ assert all(schema.incremental_fields == [] for schema in schemas)
+
+ def test_get_schemas_expose_primary_keys(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas["documents"].detected_primary_keys == ["documentId"]
+ assert schemas["teams"].detected_primary_keys == ["teamId"]
+ assert schemas["contacts"].detected_primary_keys == ["id"]
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["documents"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "documents"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self):
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ documents = next(t for t in tables if t["name"] == "documents")
+ assert documents["sync_methods"] == ["Full refresh"]
+ assert documents["primary_keys"] == ["documentId"]
+ assert documents["description"]
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ ((True, None), True, None),
+ ((False, "Invalid BoldSign API key"), False, "Invalid BoldSign API key"),
+ ((False, "Could not reach BoldSign: timed out"), False, "Could not reach BoldSign: timed out"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.boldsign.source.validate_boldsign_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("us", "key")
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is BoldSignResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.boldsign.source.boldsign_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_bs_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "documents"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_bs_source.assert_called_once()
+ kwargs = mock_bs_source.call_args.kwargs
+ assert kwargs["region"] == "us"
+ assert kwargs["api_key"] == "key"
+ assert kwargs["endpoint"] == "documents"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_canonical_descriptions_cover_every_endpoint(self):
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(BOLDSIGN_ENDPOINTS.keys())
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 99700c1785ff..5ef523b3f7f0 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
@@ -452,7 +452,8 @@ class BluetallySourceConfig(config.Config):
@config.config
class BoldSignSourceConfig(config.Config):
- pass
+ api_key: str
+ region: Literal["us", "eu"] = config.value(default="us")
@config.config