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 reply_io import source (#69373)

Tom Owers0023f9c7b0e9
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 9e67752a08a4..8328dd76929a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -295,6 +295,7 @@ the row lists both.
| reddit_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
| redshift | DB protocol | psycopg (Postgres-compatible) | ➖ |
| rentcast | HTTP | requests | ✅ |
+| reply_io | HTTP | requests | ✅ |
| resend | HTTP | requests | ✅ |
| retently | HTTP | requests | ✅ |
| revenuecat | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
@@ -664,7 +665,6 @@ doesn't conflict with concurrent PRs.
- redis
- referralhero
- repairshopr
-- reply_io
- retail_express
- revolut_merchant
- ringcentral
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 83868d7389cd..8f75f5c02c58 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
@@ -2876,7 +2876,7 @@ class RepairshoprSourceConfig(config.Config):
@config.config
class ReplyIoSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/canonical_descriptions.py
new file mode 100644
index 000000000000..67fc51b48496
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/canonical_descriptions.py
@@ -0,0 +1,186 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Reply API v3 docs (https://docs.reply.io/api-reference).
+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "contacts": {
+ "description": "A prospect (person) in your Reply account, with profile, ownership, opt-out state, and the sequences and lists they belong to.",
+ "docs_url": "https://docs.reply.io/api-reference/contacts/list-all-contacts",
+ "columns": {
+ "id": "Unique ID of the contact.",
+ "email": "Primary email address.",
+ "domain": "Email domain, derived from the email address.",
+ "firstName": "First name.",
+ "lastName": "Last name.",
+ "phone": "Phone number.",
+ "title": "Job title.",
+ "company": "Organization name.",
+ "companySize": "Organization employee count range.",
+ "industry": "Business sector.",
+ "city": "City of residence.",
+ "state": "State or province.",
+ "country": "Country.",
+ "timeZoneId": "Timezone identifier.",
+ "linkedInUrl": "LinkedIn profile URL.",
+ "linkedInSalesNavigatorUrl": "LinkedIn Sales Navigator URL.",
+ "linkedInRecruiterUrl": "LinkedIn Recruiter URL.",
+ "phoneStatus": "Phone validation status.",
+ "notes": "Free-text notes on the contact.",
+ "ownerUserId": "ID of the user who owns this contact.",
+ "accountId": "ID of the account (company) this contact belongs to.",
+ "isOptedOut": "Whether the contact has opted out of communications.",
+ "callStatus": "Contact-level call status (none, toCall, called).",
+ "meetingStatus": "Contact-level meeting status (none, meetingBooked).",
+ "addingDate": "Date the contact was added.",
+ "createdAt": "Creation timestamp.",
+ "lastModifiedAt": "Last modification timestamp.",
+ "customFields": "User-defined custom field key/value pairs.",
+ "sequences": "Sequences the contact is enrolled in, with per-sequence status and step.",
+ "lists": "Contact lists the contact belongs to.",
+ },
+ },
+ "contact_lists": {
+ "description": "A named list used to group contacts in Reply.",
+ "docs_url": "https://docs.reply.io/api-reference/contact-lists/list-contact-lists",
+ "columns": {
+ "id": "Unique identifier of the contact list.",
+ "name": "Contact list name.",
+ "isShared": "Whether the contact list is shared across the team.",
+ },
+ },
+ "accounts": {
+ "description": "An account (company/organization) that contacts belong to in Reply.",
+ "docs_url": "https://docs.reply.io/api-reference/accounts/list-accounts",
+ "columns": {
+ "id": "Unique identifier of the account.",
+ "ownerUserId": "ID of the user who owns this account.",
+ "name": "Account name.",
+ "description": "Optional description of the account.",
+ "domainName": "Primary domain name.",
+ "domainSecondary": "Secondary domain name.",
+ "industry": "Industry of the company.",
+ "companySize": "Company size range.",
+ "country": "Country of the company.",
+ "state": "State or province.",
+ "city": "City.",
+ "timeZoneId": "Time zone identifier.",
+ "linkedInUrl": "LinkedIn profile URL.",
+ "phone": "Phone number.",
+ "twitterUrl": "Twitter profile URL.",
+ "logoUrl": "Company logo URL.",
+ "email": "Contact email address.",
+ "stage": "Current stage of the account.",
+ "linkedProspectsCount": "Number of contacts linked to this account.",
+ "createdDate": "Date when the account was created.",
+ "lastActivityDate": "Date of the last activity on this account.",
+ },
+ },
+ "account_lists": {
+ "description": "A named list used to group accounts (companies) in Reply.",
+ "docs_url": "https://docs.reply.io/api-reference/account-lists/list-account-lists",
+ "columns": {
+ "id": "Unique identifier of the account list.",
+ "name": "Account list name.",
+ },
+ },
+ "custom_fields": {
+ "description": "A user-defined custom field available on contacts in Reply.",
+ "docs_url": "https://docs.reply.io/api-reference/custom-fields/list-all-custom-fields",
+ "columns": {
+ "id": "Custom field ID.",
+ "title": "Custom field name.",
+ "fieldType": "Custom field type.",
+ "metadata": "Optional metadata for the field (e.g. dropdown options).",
+ "orgWide": "Whether the field is shared across the organization.",
+ },
+ },
+ "sequences": {
+ "description": "A multichannel outreach sequence (email, LinkedIn, calls, tasks) in Reply.",
+ "docs_url": "https://docs.reply.io/api-reference",
+ "columns": {
+ "id": "Unique identifier for the sequence.",
+ "ownerUserId": "ID of the user who owns the sequence.",
+ "name": "Name of the sequence.",
+ "created": "Sequence creation timestamp.",
+ "status": "Current status of the sequence.",
+ "isArchived": "Whether the sequence is archived.",
+ "health": "Overall health status of the sequence (whether it can operate normally or needs attention).",
+ },
+ },
+ "tasks": {
+ "description": "A manual task (to-do, call, meeting, LinkedIn action, manual email) assigned to a team member in Reply.",
+ "docs_url": "https://docs.reply.io/api-reference",
+ "columns": {
+ "id": "Task ID.",
+ "taskType": "Task type (toDo, call, meeting, linkedIn, manualEmail, sms, whatsApp).",
+ "status": "Task status (new, finished, cancelled, archived, sequenceDetached).",
+ "linkedInTaskType": "LinkedIn action subtype (message, connect, inMail, viewProfile).",
+ "assignedUserId": "ID of the user this task is assigned to.",
+ "contact": "Summary of the associated contact, if any.",
+ "startAt": "Task start time.",
+ "dueTo": "Task due time.",
+ "finishedAt": "When the task was completed; null for active tasks.",
+ "isScheduled": "Whether the task is scheduled for automatic execution.",
+ "sequenceId": "Sequence ID if this task was created by a sequence.",
+ "sequenceStepId": "Sequence step ID if this task was created by a sequence.",
+ },
+ },
+ "email_templates": {
+ "description": "An email template used in sequences and one-off outreach in Reply.",
+ "docs_url": "https://docs.reply.io/api-reference/email-templates/list-email-templates",
+ "columns": {
+ "id": "Unique identifier for the email template.",
+ "name": "Name of the email template.",
+ "subject": "Email subject line.",
+ "body": "HTML body of the email template.",
+ "folderId": "ID of the folder containing this template.",
+ "folderType": "Type of the folder (personal or shared).",
+ "attachments": "Attachments associated with the template.",
+ },
+ },
+ "email_template_folders": {
+ "description": "A folder used to organize email templates in Reply.",
+ "docs_url": "https://docs.reply.io/api-reference/email-templates/list-email-template-folders",
+ "columns": {
+ "id": "Unique identifier for the folder.",
+ "name": "Name of the folder.",
+ "folderType": "Type of the folder (personal or shared).",
+ "isDefault": "Whether this is a default folder.",
+ },
+ },
+ "email_accounts": {
+ "description": "An email account connected to Reply for sending and receiving.",
+ "docs_url": "https://docs.reply.io/api-reference/email-accounts/list-email-accounts",
+ "columns": {
+ "id": "Unique identifier for the email account.",
+ "ownerUserId": "ID of the user who owns this email account.",
+ "email": "The email address.",
+ "senderName": "The name displayed as sender in recipient inboxes.",
+ "emailAccountType": "Provider type (custom, gmail, outlook, exchange, exchangeOnPremise).",
+ "isDefault": "Whether this is the user's default email account.",
+ "dailyLimit": "Maximum number of emails that can be sent per day.",
+ "connectionStatus": "Current connection status (unknown, connected, disconnected).",
+ "tags": "Tag names associated with this email account.",
+ },
+ },
+ "inbox_threads": {
+ "description": "A conversation thread in Reply's unified inbox, aggregated across channels.",
+ "docs_url": "https://docs.reply.io/api-reference",
+ "columns": {
+ "id": "Unique identifier of the thread.",
+ "channel": "Channel the thread belongs to.",
+ "isRead": "Whether the thread has been read.",
+ "subject": "Subject of the last message in the thread (email only).",
+ "bodyPreview": "Truncated body of the last message in the thread.",
+ "lastActivityDate": "When the thread last had activity.",
+ "isLastMessagePlanned": "True when the last message is a scheduled outbound message not yet sent.",
+ "contact": "Contact party on the other end of the thread.",
+ "sequence": "Sequence associated with the thread, if any.",
+ "category": "Category assigned to the thread.",
+ "hasMeetingIntent": "Whether the thread has been flagged as showing meeting intent.",
+ "status": "Aggregated thread state, derived from the latest message.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/reply_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/reply_io.py
new file mode 100644
index 000000000000..ec50320ffeac
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/reply_io.py
@@ -0,0 +1,263 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, datetime
+from email.utils import parsedate_to_datetime
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.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.reply_io.settings import REPLY_IO_ENDPOINTS
+
+REPLY_IO_BASE_URL = "https://api.reply.io/v3"
+# List endpoints accept `top` up to 1000 (default 25); the largest page minimises round trips
+# against Reply's 100 requests/minute rate limit.
+PAGE_SIZE = 1000
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 5
+# Reply's 429s carry a Retry-After header (their rate window is per minute / per hour). Cap the
+# in-function wait so a long window doesn't pin a worker; Temporal retries the whole activity
+# later from saved page state if the attempts exhaust.
+MAX_RETRY_AFTER_SECONDS = 120
+
+
+class ReplyIoRetryableError(Exception):
+ def __init__(self, message: str, retry_after: float | None = None) -> None:
+ super().__init__(message)
+ self.retry_after = retry_after
+
+
+class ReplyIoResumeConfig:
+ # Reply paginates with `top`/`skip` offsets. A crashed full-refresh sync resumes from the
+ # offset after the last yielded page; merge dedupes any re-pulled rows on `id`.
+ skip: int = 0
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}
+
+
+def _parse_retry_after(value: str | None) -> Optional[float]:
+ # Retry-After is either delta-seconds or an HTTP-date (RFC 7231).
+ if not value:
+ return None
+ value = value.strip()
+ try:
+ return max(0.0, float(value))
+ except ValueError:
+ pass
+ try:
+ retry_at = parsedate_to_datetime(value)
+ except (TypeError, ValueError):
+ return None
+ if retry_at.tzinfo is None:
+ retry_at = retry_at.replace(tzinfo=UTC)
+ return max(0.0, (retry_at - datetime.now(UTC)).total_seconds())
+
+
+_backoff = wait_exponential_jitter(initial=2, max=60)
+
+
+def _wait_reply_io(retry_state: RetryCallState) -> float:
+ # Prefer the server's own backoff instruction on rate limits; fall back to exponential
+ # jitter when the header is absent (429 without one, or a 5xx).
+ exc = retry_state.outcome.exception() if retry_state.outcome is not None else None
+ if isinstance(exc, ReplyIoRetryableError) and exc.retry_after is not None:
+ return min(exc.retry_after, MAX_RETRY_AFTER_SECONDS)
+ return _backoff(retry_state)
+
+
+@retry(
+ retry=retry_if_exception_type((ReplyIoRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=_wait_reply_io,
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ path: str,
+ skip: int,
+ limit: int,
+ logger: FilteringBoundLogger,
+) -> tuple[list[dict[str, Any]], bool]:
+ response = session.get(
+ f"{REPLY_IO_BASE_URL}{path}",
+ params={"top": limit, "skip": skip},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise ReplyIoRetryableError(
+ f"Reply API error (retryable): status={response.status_code}, path={path}",
+ retry_after=_parse_retry_after(response.headers.get("Retry-After")),
+ )
+
+ if not response.ok:
+ logger.error(f"Reply API error: status={response.status_code}, body={response.text}, path={path}")
+ response.raise_for_status()
+
+ data = response.json()
+ # Paginated list endpoints wrap rows in {"items": [...], "hasMore": bool}.
+ if not isinstance(data, dict) or not isinstance(data.get("items"), list):
+ raise ReplyIoRetryableError(f"Reply returned an unexpected payload for {path}: {type(data).__name__}")
+
+ items: list[dict[str, Any]] = data["items"]
+ has_more = bool(data.get("hasMore"))
+ return items, has_more
+
+
+@retry(
+ retry=retry_if_exception_type((ReplyIoRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=_wait_reply_io,
+ reraise=True,
+)
+def _fetch_all(
+ session: requests.Session,
+ path: str,
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ # Small catalog endpoints (custom fields, template folders) return a bare, unpaginated array.
+ response = session.get(f"{REPLY_IO_BASE_URL}{path}", timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise ReplyIoRetryableError(
+ f"Reply API error (retryable): status={response.status_code}, path={path}",
+ retry_after=_parse_retry_after(response.headers.get("Retry-After")),
+ )
+
+ if not response.ok:
+ logger.error(f"Reply API error: status={response.status_code}, body={response.text}, path={path}")
+ response.raise_for_status()
+
+ data = response.json()
+ if not isinstance(data, list):
+ raise ReplyIoRetryableError(f"Reply returned an unexpected payload for {path}: {type(data).__name__}")
+ return data
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ReplyIoResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = REPLY_IO_ENDPOINTS[endpoint]
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+
+ if not config.paginated:
+ items = _fetch_all(session, config.path, logger)
+ if items:
+ yield items
+ return
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ skip = resume.skip if resume else 0
+ if resume and resume.skip:
+ logger.debug(f"Reply.io: resuming {endpoint} from offset {skip}")
+
+ while True:
+ items, has_more = _fetch_page(session, config.path, skip, PAGE_SIZE, logger)
+ if items:
+ yield items
+
+ if not has_more or not items:
+ break
+
+ # Advance by the rows actually received, not PAGE_SIZE — robust to a server-side page cap.
+ skip += len(items)
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are
+ # persisted); merge dedupes any re-pulled rows on the primary key.
+ resumable_source_manager.save_state(ReplyIoResumeConfig(skip=skip))
+
+
+def reply_io_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ReplyIoResumeConfig],
+) -> SourceResponse:
+ config = REPLY_IO_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,
+ partition_size=1,
+ )
+
+
+def check_access(api_key: str, path: str, paginated: bool = False) -> tuple[int, Optional[str]]:
+ """Probe an endpoint with the smallest possible request.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+ try:
+ response = session.get(
+ f"{REPLY_IO_BASE_URL}{path}",
+ params={"top": 1} if paginated else None,
+ timeout=15,
+ )
+ except Exception as e:
+ return 0, f"Could not connect to Reply: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Reply returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(api_key: str, endpoint: Optional[str] = None) -> tuple[bool, str | None]:
+ """Validate the API key against `/whoami` (needs no scope), or a specific endpoint's scope."""
+ if endpoint is not None:
+ config = REPLY_IO_ENDPOINTS[endpoint]
+ status, message = check_access(api_key, config.path, paginated=config.paginated)
+ if status == 403:
+ return False, f"Your Reply API key is missing the `{config.scope}` scope"
+ else:
+ status, message = check_access(api_key, "/whoami")
+
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid Reply API key"
+ return False, message or "Could not validate Reply API key"
+
+
+def check_endpoint_permissions(api_key: str, endpoints: list[str]) -> dict[str, str | None]:
+ """Per-table scope status for the schema picker. ``None`` = reachable, str = why not.
+
+ Endpoints sharing a scope share one probe, so the whole check costs at most one request per
+ distinct scope. Only a real 403 counts as a missing scope — throttles, 5xx, and network blips
+ are reported as reachable so a transient error never blocks the picker.
+ """
+ verdict_by_scope: dict[str, str | None] = {}
+ results: dict[str, str | None] = {}
+ for name in endpoints:
+ config = REPLY_IO_ENDPOINTS.get(name)
+ if config is None:
+ results[name] = None
+ continue
+ if config.scope not in verdict_by_scope:
+ status, _ = check_access(api_key, config.path, paginated=config.paginated)
+ verdict_by_scope[config.scope] = (
+ f"Your Reply API key is missing the `{config.scope}` scope" if status == 403 else None
+ )
+ results[name] = verdict_by_scope[config.scope]
+ return results
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/settings.py
new file mode 100644
index 000000000000..1329611fca87
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/settings.py
@@ -0,0 +1,40 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class ReplyIoEndpointConfig:
+ name: str
+ path: str
+ # Scope the endpoint requires, per the Reply API docs (a broader scope that includes it also works).
+ scope: str
+ # Most list endpoints paginate with `top`/`skip` and wrap rows in {"items": [...], "hasMore": bool};
+ # a few small catalogs return a bare, unpaginated JSON array.
+ paginated: bool = True
+ # Reply object IDs are unique per resource within an account, so `id` is a safe primary key.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+# Reply API v3 list endpoints (https://docs.reply.io/api-reference). All are full refresh only:
+# no list endpoint exposes a server-side created/updated timestamp filter, so there is no
+# incremental cursor to advance.
+REPLY_IO_ENDPOINTS: dict[str, ReplyIoEndpointConfig] = {
+ "contacts": ReplyIoEndpointConfig(name="contacts", path="/contacts", scope="contacts:read"),
+ "contact_lists": ReplyIoEndpointConfig(name="contact_lists", path="/contact-lists", scope="contacts:read"),
+ "accounts": ReplyIoEndpointConfig(name="accounts", path="/contact-accounts", scope="contacts:read"),
+ "account_lists": ReplyIoEndpointConfig(name="account_lists", path="/contact-account-lists", scope="contacts:read"),
+ "custom_fields": ReplyIoEndpointConfig(
+ name="custom_fields", path="/custom-fields", scope="contacts:read", paginated=False
+ ),
+ "sequences": ReplyIoEndpointConfig(name="sequences", path="/sequences", scope="sequences:read"),
+ "tasks": ReplyIoEndpointConfig(name="tasks", path="/tasks", scope="tasks:read"),
+ "email_templates": ReplyIoEndpointConfig(name="email_templates", path="/email-templates", scope="sequences:read"),
+ "email_template_folders": ReplyIoEndpointConfig(
+ name="email_template_folders", path="/email-template-folders", scope="sequences:read", paginated=False
+ ),
+ "email_accounts": ReplyIoEndpointConfig(name="email_accounts", path="/email-accounts", scope="channels:read"),
+ "inbox_threads": ReplyIoEndpointConfig(name="inbox_threads", path="/inbox/threads", scope="inbox:read"),
+}
+
+ENDPOINTS = tuple(REPLY_IO_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/source.py
index fe2d625f6dd3..753510e64a30 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/source.py
@@ -1,19 +1,43 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ReplyIoSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.reply_io.reply_io import (
+ ReplyIoResumeConfig,
+ check_endpoint_permissions,
+ reply_io_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.reply_io.settings import (
+ ENDPOINTS,
+ REPLY_IO_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ReplyIoSource(SimpleSource[ReplyIoSourceConfig]):
+class ReplyIoSource(ResumableSource[ReplyIoSourceConfig, ReplyIoResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.REPLYIO
@@ -24,7 +48,95 @@ class ReplyIoSource(SimpleSource[ReplyIoSourceConfig]):
name=SchemaExternalDataSourceType.REPLY_IO,
category=DataWarehouseSourceCategory.SALES,
label="Reply.io",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Reply API key to pull your sales engagement data into the PostHog Data warehouse.
+
+You can create an API key under **Settings → API Keys** in [Reply](https://run.reply.io). To sync every table the key needs the `contacts:read`, `sequences:read`, `tasks:read`, `channels:read`, and `inbox:read` scopes (or broader scopes that include them) — tables whose scope is missing can be deselected in the table picker.
+""",
iconPath="/static/services/reply_io.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/reply-io",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
unreleasedSource=True,
)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.reply_io.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.reply.io": "Your Reply API key is invalid or has been revoked. Generate a new key under Settings → API Keys in Reply, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.reply.io": "Your Reply API key does not have the scope this table requires. Grant the missing scope to the key, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: ReplyIoSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every endpoint is full refresh only — Reply's v3 list endpoints expose no server-side
+ # created/updated timestamp filter, so there is no incremental cursor to advance.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ 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: ReplyIoSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # At source-create (schema_name=None) we probe `/whoami`, which needs no scope — one cheap
+ # request confirms the token is genuine without blocking on per-table scopes. With a
+ # schema_name we probe that endpoint so a missing scope surfaces by name.
+ endpoint = schema_name if schema_name in REPLY_IO_ENDPOINTS else None
+ return validate_credentials(config.api_key, endpoint=endpoint)
+
+ def get_endpoint_permissions(
+ self, config: ReplyIoSourceConfig, team_id: int, endpoints: list[str]
+ ) -> dict[str, str | None]:
+ return check_endpoint_permissions(config.api_key, endpoints)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ReplyIoResumeConfig]:
+ return ResumableSourceManager[ReplyIoResumeConfig](inputs, ReplyIoResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ReplyIoSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ReplyIoResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in REPLY_IO_ENDPOINTS:
+ raise ValueError(f"Unknown Reply.io schema '{inputs.schema_name}'")
+
+ return reply_io_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/reply_io/tests/test_reply_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/tests/test_reply_io.py
new file mode 100644
index 000000000000..fc1e650f25a5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/tests/test_reply_io.py
@@ -0,0 +1,327 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.reply_io import reply_io
+from products.warehouse_sources.backend.temporal.data_imports.sources.reply_io.reply_io import (
+ MAX_RETRY_AFTER_SECONDS,
+ PAGE_SIZE,
+ ReplyIoResumeConfig,
+ ReplyIoRetryableError,
+ _parse_retry_after,
+ _wait_reply_io,
+ check_access,
+ check_endpoint_permissions,
+ get_rows,
+ reply_io_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.reply_io.settings import (
+ ENDPOINTS,
+ REPLY_IO_ENDPOINTS,
+)
+
+# Call the undecorated functions so the tenacity retry/backoff wrappers don't slow failure-path tests.
+_fetch_page_unwrapped = reply_io._fetch_page.__wrapped__ # type: ignore[attr-defined]
+_fetch_all_unwrapped = reply_io._fetch_all.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: ReplyIoResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[ReplyIoResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> ReplyIoResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: ReplyIoResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _page(start_id: int, count: int) -> list[dict]:
+ return [{"id": start_id + i} for i in range(count)]
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: dict[int, tuple[list[dict], bool]],
+ endpoint: str = "contacts",
+ ) -> list[dict]:
+ def fake_fetch(session: Any, path: str, skip: int, limit: int, logger: Any) -> tuple[list[dict], bool]:
+ return pages[skip]
+
+ monkeypatch.setattr(reply_io, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(reply_io, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_key="reply-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_single_page_hasmore_false_yields_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {0: ([{"id": 1}, {"id": 2}], False)})
+ assert rows == [{"id": 1}, {"id": 2}]
+ # hasMore is false, so we stop without persisting resume state.
+ assert manager.saved == []
+
+ def test_follows_offset_pagination_until_hasmore_false(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages: dict[int, tuple[list[dict], bool]] = {
+ 0: (_page(0, PAGE_SIZE), True),
+ PAGE_SIZE: ([{"id": 9999}], False),
+ }
+ rows = self._collect(manager, monkeypatch, pages)
+ assert len(rows) == PAGE_SIZE + 1
+ # State is saved after the first page (offset advances by the page length), then we stop.
+ assert [s.skip for s in manager.saved] == [PAGE_SIZE]
+
+ def test_offset_advances_by_rows_received_not_page_size(self, monkeypatch: Any) -> None:
+ # If the server caps pages below our requested `top`, advancing by PAGE_SIZE would skip rows.
+ manager = _FakeResumableManager()
+ pages: dict[int, tuple[list[dict], bool]] = {
+ 0: (_page(0, 100), True),
+ 100: (_page(100, 40), False),
+ }
+ rows = self._collect(manager, monkeypatch, pages)
+ assert len(rows) == 140
+ assert [s.skip for s in manager.saved] == [100]
+
+ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(ReplyIoResumeConfig(skip=200))
+ # The initial (skip=0) page must never be fetched on resume.
+ rows = self._collect(manager, monkeypatch, {200: ([{"id": 201}], False)})
+ assert rows == [{"id": 201}]
+
+ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {0: ([], False)})
+ assert rows == []
+ assert manager.saved == []
+
+ @parameterized.expand([("custom_fields",), ("email_template_folders",)])
+ def test_unpaginated_endpoint_fetches_once_without_state(self, endpoint: str) -> None:
+ response = MagicMock()
+ response.status_code = 200
+ response.ok = True
+ response.json.return_value = [{"id": 1}, {"id": 2}]
+ session = MagicMock()
+ session.get.return_value = response
+ manager = _FakeResumableManager()
+
+ with patch(f"{reply_io.__name__}.make_tracked_session", return_value=session):
+ rows = [
+ row
+ for batch in get_rows(
+ api_key="reply-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ )
+ for row in batch
+ ]
+
+ assert rows == [{"id": 1}, {"id": 2}]
+ assert session.get.call_count == 1
+ # Bare-array endpoints take no pagination params and never persist resume state.
+ assert "params" not in session.get.call_args.kwargs
+ assert manager.saved == []
+
+
+class TestFetchPage:
+ def _session_returning(self, status_code: int, body: Any = None, headers: dict | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else {"items": [], "hasMore": False}
+ response.text = ""
+ response.headers = headers or {}
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(ReplyIoRetryableError):
+ _fetch_page_unwrapped(session, "/contacts", 0, PAGE_SIZE, MagicMock())
+
+ def test_rate_limit_carries_retry_after_header(self) -> None:
+ session = self._session_returning(429, headers={"Retry-After": "42"})
+ with pytest.raises(ReplyIoRetryableError) as exc_info:
+ _fetch_page_unwrapped(session, "/contacts", 0, PAGE_SIZE, MagicMock())
+ assert exc_info.value.retry_after == 42.0
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, "/contacts", 0, PAGE_SIZE, MagicMock())
+
+ def test_success_returns_items_and_hasmore(self) -> None:
+ session = self._session_returning(200, {"items": [{"id": 1}], "hasMore": True})
+ items, has_more = _fetch_page_unwrapped(session, "/contacts", 0, PAGE_SIZE, MagicMock())
+ assert items == [{"id": 1}]
+ assert has_more is True
+
+ @parameterized.expand(
+ [
+ ("bare_array_body", [{"id": 1}]),
+ ("missing_items_key", {"hasMore": False}),
+ ]
+ )
+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:
+ session = self._session_returning(200, body)
+ with pytest.raises(ReplyIoRetryableError):
+ _fetch_page_unwrapped(session, "/contacts", 0, PAGE_SIZE, MagicMock())
+
+ def test_sends_top_and_skip_params(self) -> None:
+ session = self._session_returning(200)
+ _fetch_page_unwrapped(session, "/tasks", 250, PAGE_SIZE, MagicMock())
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] == {"top": PAGE_SIZE, "skip": 250}
+
+ def test_fetch_all_rejects_non_array_body(self) -> None:
+ session = self._session_returning(200, {"items": []})
+ with pytest.raises(ReplyIoRetryableError):
+ _fetch_all_unwrapped(session, "/custom-fields", MagicMock())
+
+
+class TestRetryAfter:
+ @parameterized.expand(
+ [
+ ("delta_seconds", "42", 42.0),
+ ("zero_floor", "-5", 0.0),
+ ("garbage", "not-a-date", None),
+ ("missing", None, None),
+ ]
+ )
+ def test_parse_retry_after(self, _name: str, value: str | None, expected: float | None) -> None:
+ assert _parse_retry_after(value) == expected
+
+ def test_wait_prefers_server_retry_after_capped(self) -> None:
+ state = MagicMock()
+ state.outcome.exception.return_value = ReplyIoRetryableError("throttled", retry_after=10_000.0)
+ assert _wait_reply_io(state) == MAX_RETRY_AFTER_SECONDS
+
+ state.outcome.exception.return_value = ReplyIoRetryableError("throttled", retry_after=7.0)
+ assert _wait_reply_io(state) == 7.0
+
+
+class TestCredentials:
+ @staticmethod
+ def _session(response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ return session
+
+ @staticmethod
+ def _response(status: int) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ return response
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, None),
+ ("unauthorized", 401, False, "Invalid Reply API key"),
+ ("forbidden", 403, False, "Invalid Reply API key"),
+ ("server_error", 500, False, "Reply returned HTTP 500"),
+ ]
+ )
+ @patch(f"{reply_io.__name__}.make_tracked_session")
+ def test_validate_credentials_at_source_create(
+ self,
+ _name: str,
+ status: int,
+ expected_valid: bool,
+ expected_message: str | None,
+ mock_session: MagicMock,
+ ) -> None:
+ mock_session.return_value = self._session(self._response(status))
+ assert validate_credentials("reply-key") == (expected_valid, expected_message)
+
+ @patch(f"{reply_io.__name__}.make_tracked_session")
+ def test_validate_credentials_for_endpoint_names_missing_scope(self, mock_session: MagicMock) -> None:
+ mock_session.return_value = self._session(self._response(403))
+ valid, message = validate_credentials("reply-key", endpoint="sequences")
+ assert valid is False
+ assert message == "Your Reply API key is missing the `sequences:read` scope"
+
+ @patch(f"{reply_io.__name__}.make_tracked_session")
+ def test_check_access_connection_error_maps_to_zero(self, mock_session: MagicMock) -> None:
+ mock_session.return_value = self._session(requests.ConnectionError("boom"))
+ status, message = check_access("reply-key", "/whoami")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+
+class TestEndpointPermissions:
+ @patch(f"{reply_io.__name__}.check_access")
+ def test_endpoints_sharing_a_scope_share_one_probe(self, mock_access: MagicMock) -> None:
+ mock_access.return_value = (200, None)
+ results = check_endpoint_permissions("reply-key", list(ENDPOINTS))
+ assert results == dict.fromkeys(ENDPOINTS)
+ distinct_scopes = {config.scope for config in REPLY_IO_ENDPOINTS.values()}
+ assert mock_access.call_count == len(distinct_scopes)
+
+ @patch(f"{reply_io.__name__}.check_access")
+ def test_missing_scope_marks_every_endpoint_behind_it(self, mock_access: MagicMock) -> None:
+ def by_path(api_key: str, path: str, paginated: bool = False) -> tuple[int, None]:
+ return (403, None) if path == REPLY_IO_ENDPOINTS["contacts"].path else (200, None)
+
+ mock_access.side_effect = by_path
+ results = check_endpoint_permissions("reply-key", list(ENDPOINTS))
+ denied = {name for name, reason in results.items() if reason is not None}
+ assert denied == {name for name, config in REPLY_IO_ENDPOINTS.items() if config.scope == "contacts:read"}
+ assert results["contacts"] == "Your Reply API key is missing the `contacts:read` scope"
+
+ @parameterized.expand([("throttled", 429), ("server_error", 500), ("connection_error", 0)])
+ @patch(f"{reply_io.__name__}.check_access")
+ def test_transient_errors_do_not_block_the_picker(self, _name: str, status: int, mock_access: MagicMock) -> None:
+ mock_access.return_value = (status, None)
+ results = check_endpoint_permissions("reply-key", ["contacts"])
+ assert results == {"contacts": None}
+
+ @patch(f"{reply_io.__name__}.check_access")
+ def test_unknown_endpoint_reported_reachable_without_probe(self, mock_access: MagicMock) -> None:
+ results = check_endpoint_permissions("reply-key", ["not_a_table"])
+ assert results == {"not_a_table": None}
+ mock_access.assert_not_called()
+
+
+class TestReplyIoSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = reply_io_source(
+ api_key="reply-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ # Most Reply resources expose no stable creation timestamp, so we don't partition.
+ assert response.partition_mode is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/tests/test_reply_io_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/tests/test_reply_io_source.py
new file mode 100644
index 000000000000..ecb3f6fd2aeb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/tests/test_reply_io_source.py
@@ -0,0 +1,138 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ReplyIoSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.reply_io.reply_io import ReplyIoResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.reply_io.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.reply_io.source import ReplyIoSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestReplyIoSource:
+ def setup_method(self) -> None:
+ self.source = ReplyIoSource()
+ self.team_id = 123
+ self.config = ReplyIoSourceConfig(api_key="reply-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.REPLYIO
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "ReplyIo"
+ assert config.label == "Reply.io"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/reply-io"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_no_connection_host_fields(self) -> None:
+ # The only field is the secret API key; the base URL is hardcoded, so there is no non-secret
+ # field an editor could retarget to reuse a preserved key against another host.
+ assert self.source.connection_host_fields == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["contacts"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "contacts"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.reply.io/v3/contacts?top=1000"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.reply.io/v3/sequences?top=1000"),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.reply.io/v3/contacts"),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.reply.io/v3/tasks"),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("source_create_probes_whoami", None, None),
+ ("known_schema_probes_its_endpoint", "contacts", "contacts"),
+ ("unknown_schema_falls_back_to_whoami", "not_a_table", None),
+ ]
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.reply_io.source.validate_credentials")
+ def test_validate_credentials_delegates(
+ self, _name: str, schema_name: str | None, expected_endpoint: str | None, mock_validate: mock.MagicMock
+ ) -> None:
+ mock_validate.return_value = (True, None)
+ result = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
+ mock_validate.assert_called_once_with("reply-key", endpoint=expected_endpoint)
+ assert result == (True, None)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.reply_io.source.check_endpoint_permissions"
+ )
+ def test_get_endpoint_permissions_delegates(self, mock_check: mock.MagicMock) -> None:
+ mock_check.return_value = {"contacts": None}
+ result = self.source.get_endpoint_permissions(self.config, self.team_id, ["contacts"])
+ mock_check.assert_called_once_with("reply-key", ["contacts"])
+ assert result == {"contacts": None}
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is ReplyIoResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.reply_io.source.reply_io_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "contacts"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "reply-key"
+ assert kwargs["endpoint"] == "contacts"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown Reply.io schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)