: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 instantly import source (#72659)
Tom Owersd9abf38642b9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex af5a0f5ca2ae..8a763b3e4c1c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -280,6 +280,7 @@ the row lists both.| inngest | HTTP | requests | ✅ || insightly | HTTP | requests | ✅ || instana | HTTP | requests | ✅ |+| instantly | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || instatus | HTTP | requests | ✅ || intercom | HTTP | requests + `rest_source.RESTClient` | ✅ || intruder | HTTP | requests | ✅ |@@ -765,7 +766,6 @@ doesn't conflict with concurrent PRs.- infor_nexus- insightful-- instantly- interzoid- jobber- judgeme_reviewsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/instantly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/instantly.pyindex 2b2891d1f335..8dea46219a37 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/instantly.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/instantly.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass InstantlySourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/canonical_descriptions.pynew file mode 100644index 000000000000..1c2240c34d16--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/canonical_descriptions.py@@ -0,0 +1,178 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "campaigns": {+ "description": "An email outreach campaign with its schedule, sequences, and sending settings.",+ "docs_url": "https://developer.instantly.ai/api-reference/campaign/list-campaign",+ "columns": {+ "id": "Unique identifier of the campaign (UUID).",+ "name": "Name of the campaign.",+ "status": "Campaign status: 0 Draft, 1 Active, 2 Paused, 3 Completed, 4 Running Subsequences, -99 Account Suspended, -1 Accounts Unhealthy, -2 Bounce Protect.",+ "timestamp_created": "When the campaign was created.",+ "timestamp_updated": "When the campaign was last updated.",+ "campaign_schedule": "Sending schedule configuration (start/end dates and per-day timing windows).",+ "sequences": "Email sequence steps and variants sent by the campaign.",+ "email_list": "Sending account email addresses used by the campaign.",+ "daily_limit": "Maximum number of emails the campaign sends per day.",+ "stop_on_reply": "Whether the campaign stops contacting a lead once they reply.",+ "is_evergreen": "Whether the campaign is an evergreen campaign that keeps running.",+ "organization": "Workspace (organization) the campaign belongs to.",+ "open_tracking": "Whether open tracking is enabled.",+ "link_tracking": "Whether link click tracking is enabled.",+ },+ },+ "accounts": {+ "description": "A sending email account connected to the workspace, including warmup status and limits.",+ "docs_url": "https://developer.instantly.ai/api-reference/account/list-account",+ "columns": {+ "email": "Email address of the sending account — the account's unique identifier.",+ "timestamp_created": "When the account was connected.",+ "timestamp_updated": "When the account was last updated.",+ "first_name": "First name configured on the account.",+ "last_name": "Last name configured on the account.",+ "organization": "Workspace (organization) the account belongs to.",+ "status": "Account status: 1 Active, 2 Paused, -1 Connection Error, -2 Soft Bounce Error, -3 Sending Error.",+ "warmup_status": "Warmup status: 0 Paused, 1 Active, -1 Banned, -2 Spam Folder Unknown, -3 Permanent Suspension.",+ "warmup": "Warmup configuration (daily limit, increment, reply rate).",+ "stat_warmup_score": "Latest warmup score of the account.",+ "daily_limit": "Maximum number of emails the account sends per day.",+ "provider_code": "Email provider: 1 Custom IMAP/SMTP, 2 Google, 3 Microsoft, 4 AWS.",+ "tracking_domain_name": "Custom tracking domain configured for the account.",+ },+ },+ "leads": {+ "description": "A lead (contact) in a campaign or lead list, with contact details and engagement counts.",+ "docs_url": "https://developer.instantly.ai/api-reference/lead/list-leads",+ "columns": {+ "id": "Unique identifier of the lead (UUID).",+ "timestamp_created": "When the lead was created.",+ "timestamp_updated": "When the lead was last updated.",+ "organization": "Workspace (organization) the lead belongs to.",+ "campaign": "Campaign the lead belongs to, if any.",+ "list_id": "Lead list the lead belongs to, if any.",+ "email": "Email address of the lead.",+ "first_name": "First name of the lead.",+ "last_name": "Last name of the lead.",+ "company_name": "Company the lead works at.",+ "company_domain": "Company website domain of the lead.",+ "status": "Lead status: 1 Active, 2 Paused, 3 Completed, -1 Bounced, -2 Unsubscribed, -3 Skipped.",+ "email_open_count": "Number of times the lead opened an email.",+ "email_reply_count": "Number of times the lead replied.",+ "email_click_count": "Number of times the lead clicked a tracked link.",+ "lt_interest_status": "Interest status: 1 Interested, 2 Meeting Booked, 3 Meeting Completed, 4 Won, -1 Not Interested, -2 Wrong Person, -3 Lost, 0 Out of Office.",+ "verification_status": "Email verification status: 1 Verified, 11 Pending, -1 Invalid, -2 Risky, -3 Catch All.",+ "timestamp_last_contact": "When the lead was last contacted.",+ "timestamp_last_reply": "When the lead last replied.",+ "payload": "Custom variables uploaded with the lead.",+ "upload_method": "How the lead was added: manual, api, or website-visitor.",+ },+ },+ "emails": {+ "description": "A sent or received email from campaigns and the unified inbox (Unibox).",+ "docs_url": "https://developer.instantly.ai/api-reference/email/list-email",+ "columns": {+ "id": "Unique identifier of the email (UUID).",+ "timestamp_created": "When the email record was created in Instantly.",+ "timestamp_email": "Timestamp carried by the email itself, as reported by the mail server.",+ "message_id": "Message-ID header assigned by the email server.",+ "subject": "Subject line of the email.",+ "body": "Email body with text and html variants.",+ "eaccount": "Sending account the email belongs to.",+ "from_address_email": "Sender email address.",+ "to_address_email_list": "Comma-separated list of recipient email addresses.",+ "campaign_id": "Campaign that sent the email, if any.",+ "lead": "Email address of the lead the email belongs to.",+ "thread_id": "Thread identifier shared by all emails in a conversation.",+ "ue_type": "Email type: 1 sent from a campaign, 2 received, 3 sent manually, 4 scheduled.",+ "is_unread": "Whether the email is unread in the Unibox.",+ "i_status": "Interest status assigned to the email's thread.",+ "content_preview": "Short text preview of the email content.",+ },+ },+ "lead_lists": {+ "description": "A lead list used to organize leads outside campaigns.",+ "docs_url": "https://developer.instantly.ai/api-reference/leadlist/list-lead-list",+ "columns": {+ "id": "Unique identifier of the lead list (UUID).",+ "name": "Name of the lead list.",+ "organization_id": "Workspace (organization) the list belongs to.",+ "timestamp_created": "When the lead list was created.",+ "has_enrichment_task": "Whether the list runs enrichment on new leads.",+ "owned_by": "User that owns the list.",+ },+ },+ "lead_labels": {+ "description": "A custom lead interest label configured in the workspace.",+ "docs_url": "https://developer.instantly.ai/api-reference/leadlabel/list-lead-label",+ "columns": {+ "id": "Unique identifier of the lead label (UUID).",+ "timestamp_created": "When the label was created.",+ },+ },+ "custom_tags": {+ "description": "A custom tag that can be assigned to campaigns and accounts.",+ "docs_url": "https://developer.instantly.ai/api-reference/customtag/list-custom-tag",+ "columns": {+ "id": "Unique identifier of the tag (UUID).",+ "timestamp_created": "When the tag was created.",+ },+ },+ "campaign_analytics": {+ "description": "Aggregate analytics for one campaign: sends, opens, replies, clicks, bounces, and opportunities.",+ "docs_url": "https://developer.instantly.ai/api-reference/campaign/get-campaigns-analytics",+ "columns": {+ "campaign_id": "Campaign the analytics row belongs to.",+ "campaign_name": "Name of the campaign.",+ "campaign_status": "Campaign status at the time of the request.",+ "campaign_is_evergreen": "Whether the campaign is an evergreen campaign.",+ "leads_count": "Total number of leads in the campaign.",+ "contacted_count": "Number of leads contacted.",+ "emails_sent_count": "Total number of emails sent.",+ "new_leads_contacted_count": "Number of leads contacted for the first time.",+ "open_count": "Total number of email opens.",+ "open_count_unique": "Number of unique leads that opened an email.",+ "reply_count": "Total number of replies.",+ "reply_count_unique": "Number of unique leads that replied.",+ "link_click_count": "Total number of tracked link clicks.",+ "link_click_count_unique": "Number of unique leads that clicked a link.",+ "bounced_count": "Number of bounced emails.",+ "unsubscribed_count": "Number of leads that unsubscribed.",+ "completed_count": "Number of leads that completed the sequence.",+ "total_opportunities": "Number of opportunities generated by the campaign.",+ "total_opportunity_value": "Total value of opportunities generated by the campaign.",+ },+ },+ "campaign_daily_analytics": {+ "description": "Workspace-wide daily campaign analytics: sends, opens, replies, and clicks per day.",+ "docs_url": "https://developer.instantly.ai/api-reference/campaign/get-daily-campaign-analytics",+ "columns": {+ "date": "Day the analytics row covers, in YYYY-MM-DD format.",+ "sent": "Total emails sent that day.",+ "contacted": "Unique contacts emailed that day.",+ "new_leads_contacted": "Leads reached for the first time that day.",+ "opened": "Total email opens that day.",+ "unique_opened": "Unique leads that opened an email that day.",+ "replies": "Total replies received that day.",+ "unique_replies": "Unique leads that replied that day.",+ "clicks": "Total tracked link clicks that day.",+ "unique_clicks": "Unique leads that clicked a link that day.",+ "opportunities": "Opportunities created that day.",+ },+ },+ "webhook_events": {+ "description": "Raw Instantly webhook event stream: sends, opens, replies, bounces, and lead status changes as they happen.",+ "docs_url": "https://developer.instantly.ai/guides/webhook-events",+ "columns": {+ "event_id": "Deterministic hash of the webhook payload, used as the primary key to de-duplicate redeliveries.",+ "event_type": "Event name, e.g. email_sent, email_opened, reply_received, lead_interested, or a custom label.",+ "timestamp": "When the event occurred.",+ "workspace": "Workspace (organization) the event belongs to.",+ "campaign_id": "Campaign the event belongs to, if any.",+ "campaign_name": "Name of the campaign the event belongs to.",+ "lead_email": "Email address of the lead the event relates to.",+ "email_account": "Sending account involved in the event.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/instantly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/instantly.pynew file mode 100644index 000000000000..7720739e6565--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/instantly.py@@ -0,0 +1,446 @@+import time+import hashlib+import secrets+import dataclasses+from datetime import datetime+from typing import Any, Optional++import orjson+import pyarrow as pa+import requests+from asgiref.sync import async_to_sync+from structlog.types import FilteringBoundLogger++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.utils import table_from_py_list+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ ExternalWebhookInfo,+ WebhookCreationResult,+ WebhookDeletionResult,+)+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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponseCursorPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ Endpoint,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.instantly.settings import (+ BASE_URL,+ DEFAULT_PAGE_SIZE,+ EMAILS_REQUEST_INTERVAL_SECONDS,+ INSTANTLY_ENDPOINTS,+ WEBHOOK_EVENTS_ENDPOINT,+ InstantlyEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 30+# Bounded walk of the webhook list when reconciling ours by URL — a workspace won't have+# thousands of webhooks, so this is a defensive cap, not an expected limit.+MAX_WEBHOOK_LIST_PAGES = 10++WEBHOOK_NAME = "PostHog data warehouse"+# Instantly deliveries are unsigned, but webhooks accept static custom headers — we attach a+# generated secret header on create and the webhook template verifies it on every delivery.+WEBHOOK_SECRET_HEADER = "x-posthog-webhook-secret"++WEBHOOK_PLAN_ERROR = (+ "Instantly rejected the webhook request because the workspace's plan does not include webhooks "+ "(Hypergrowth plan or above is required). You can keep syncing with scheduled pulls instead."+)+WEBHOOK_SCOPE_ERROR = (+ "Your Instantly API key is not allowed to manage webhooks. Use a key with the `webhooks:all` "+ "(or `all:all`) scope, or set the webhook up manually."+)+++class InstantlyResumeConfig:+ cursor: str+++class InstantlyCursorPaginator(JSONResponseCursorPaginator):+ """starting_after/next_starting_after cursor pagination.++ Stops on an empty page or a non-advancing cursor — the docs don't state whether the last+ page omits `next_starting_after` or returns it alongside zero items, so guard both.+ """++ def __init__(self, use_json_body: bool = False) -> None:+ if use_json_body:+ super().__init__(cursor_path="next_starting_after", cursor_param="starting_after", param_location="json")+ else:+ super().__init__(cursor_path="next_starting_after", cursor_param="starting_after", param_location="query")++ def update_state(self, response: requests.Response, data: Optional[list[Any]] = None) -> None:+ previous_cursor = self._cursor_value+ super().update_state(response, data)+ if not data or (self._cursor_value is not None and self._cursor_value == previous_cursor):+ self._has_next_page = False+++class InstantlyThrottledCursorPaginator(InstantlyCursorPaginator):+ """Cursor paginator that waits between pages, for the rate-limited emails endpoint."""++ def __init__(self, interval_seconds: float) -> None:+ super().__init__()+ self._interval_seconds = interval_seconds++ def update_request(self, request: requests.Request) -> None:+ super().update_request(request)+ if self._has_next_page:+ time.sleep(self._interval_seconds)+++def _format_incremental_timestamp(value: Any) -> str:+ if isinstance(value, datetime):+ return value.isoformat()+ return str(value)+++def _make_paginator(config: InstantlyEndpointConfig) -> InstantlyCursorPaginator:+ if config.name == "emails":+ return InstantlyThrottledCursorPaginator(EMAILS_REQUEST_INTERVAL_SECONDS)+ return InstantlyCursorPaginator(use_json_body=config.method == "POST")+++def get_resource(endpoint: str, should_use_incremental_field: bool) -> EndpointResource:+ config = INSTANTLY_ENDPOINTS[endpoint]++ endpoint_config: Endpoint = {+ "path": f"/api/v2{config.path}",+ "method": config.method,+ }+ if config.data_selector is not None:+ endpoint_config["data_selector"] = config.data_selector++ if config.pagination == "single":+ endpoint_config["paginator"] = "single_page"+ endpoint_config["params"] = dict(config.params)+ elif config.method == "POST":+ endpoint_config["paginator"] = _make_paginator(config)+ endpoint_config["json"] = {**config.params, "limit": DEFAULT_PAGE_SIZE}+ else:+ endpoint_config["paginator"] = _make_paginator(config)+ params: dict[str, Any] = {**config.params, "limit": DEFAULT_PAGE_SIZE}+ if config.supports_incremental and should_use_incremental_field:+ params["min_timestamp_created"] = {+ "type": "incremental",+ "cursor_path": "timestamp_created",+ "initial_value": "1970-01-01T00:00:00.000Z",+ "convert": _format_incremental_timestamp,+ }+ endpoint_config["params"] = params++ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ }+ if should_use_incremental_field+ else "replace",+ "endpoint": endpoint_config,+ "table_format": "delta",+ }+++def _webhook_events_table_transformer(table: pa.Table) -> pa.Table:+ """Stamp a deterministic `event_id` onto each webhook payload and de-dupe within the batch.++ Instantly webhook payloads carry no unique id, so the primary key is a content hash — a+ redelivered payload hashes identically and merges away instead of duplicating rows.+ """+ rows: list[dict[str, Any]] = []+ seen: set[str] = set()+ for raw_row in table.to_pylist():+ row = dict(raw_row)+ row.pop("event_id", None)+ event_id = hashlib.sha256(orjson.dumps(row, option=orjson.OPT_SORT_KEYS, default=str)).hexdigest()+ if event_id in seen:+ continue+ seen.add(event_id)+ row["event_id"] = event_id+ rows.append(row)+ return table_from_py_list(rows)+++def instantly_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[InstantlyResumeConfig],+ webhook_source_manager: Optional[WebhookSourceManager] = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ if endpoint == WEBHOOK_EVENTS_ENDPOINT:+ return _webhook_events_source(webhook_source_manager)++ config = INSTANTLY_ENDPOINTS[endpoint]++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": BASE_URL,+ "auth": {+ "type": "bearer",+ "token": api_key,+ },+ "headers": {+ "Accept": "application/json",+ "Content-Type": "application/json",+ },+ },+ "resource_defaults": {},+ "resources": [get_resource(endpoint, should_use_incremental_field)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"cursor": resume_config.cursor}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's a next page to resume to; the Redis TTL handles cleanup.+ if state and state.get("cursor"):+ resumable_source_manager.save_state(InstantlyResumeConfig(cursor=str(state["cursor"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value if should_use_incremental_field else None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=config.primary_keys,+ sort_mode="asc",+ partition_count=1 if config.partition_key else None,+ partition_size=1 if config.partition_key else None,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def _webhook_events_source(webhook_source_manager: Optional[WebhookSourceManager]) -> SourceResponse:+ webhook_enabled = (+ async_to_sync(webhook_source_manager.webhook_enabled)(webhook_only=True)+ if webhook_source_manager is not None+ else False+ )++ def items():+ if webhook_enabled and webhook_source_manager is not None:+ return webhook_source_manager.get_items(table_transformer=_webhook_events_table_transformer)+ # Webhook-only resource: there is no pull API for the event stream, so a sync without an+ # enabled webhook has nothing to fetch.+ return iter([])++ return SourceResponse(+ name=WEBHOOK_EVENTS_ENDPOINT,+ items=items,+ primary_keys=["event_id"],+ webhook_only=True,+ )+++def _make_session(api_key: str) -> requests.Session:+ return make_tracked_session(+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ redact_values=(api_key,),+ )+++def _probe_endpoint(session: requests.Session, endpoint: str) -> requests.Response:+ """Cheapest possible authenticated request against one endpoint's scope."""+ if endpoint == WEBHOOK_EVENTS_ENDPOINT:+ return session.get(f"{BASE_URL}/api/v2/webhooks", params={"limit": 1}, timeout=REQUEST_TIMEOUT_SECONDS)++ config = INSTANTLY_ENDPOINTS[endpoint]+ url = f"{BASE_URL}/api/v2{config.path}"+ if config.method == "POST":+ return session.post(url, json={"limit": 1}, timeout=REQUEST_TIMEOUT_SECONDS)+ if config.pagination == "single":+ # Analytics endpoints have no limit param; a one-day window keeps the probe cheap.+ params = {"start_date": "2024-01-01", "end_date": "2024-01-01", "exclude_total_leads_count": "true"}+ return session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)+ return session.get(url, params={"limit": 1}, timeout=REQUEST_TIMEOUT_SECONDS)+++def _error_message(response: requests.Response) -> str | None:+ try:+ message = response.json().get("message")+ return str(message) if message else None+ except Exception:+ return None+++def validate_credentials(api_key: str, schema_name: Optional[str] = None) -> tuple[bool, str | None]:+ """Probe the token (schema_name=None) or one endpoint's scope (schema_name set).++ At source-create a 403 is accepted: Instantly API keys are scope-gated per resource, and a+ key legitimately scoped to only the tables the user wants must not block the whole source.+ """+ if not api_key:+ return False, "Missing Instantly API key"++ session = _make_session(api_key)+ try:+ response = _probe_endpoint(session, schema_name or "campaigns")+ except Exception as e:+ return False, f"Could not connect to Instantly: {e}"++ if response.status_code == 401:+ return False, "Instantly rejected the API key. Check the key is correct and has not been revoked."+ if response.status_code == 402:+ return False, (+ "Your Instantly workspace does not have an active plan with API access "+ "(the API requires the Growth plan or above)."+ )+ if response.status_code == 403:+ if schema_name is None:+ return True, None+ message = _error_message(response)+ return False, (+ f"Your Instantly API key is missing the scope required for this table"+ f"{f': {message}' if message else '. Grant the matching read scope and try again.'}"+ )+ if not response.ok:+ return False, f"Instantly returned HTTP {response.status_code}"+ return True, None+++def get_endpoint_permissions(api_key: str, endpoints: list[str]) -> dict[str, str | None]:+ """Per-table scope status for the schema picker. Only a real denial counts as missing scope."""+ session = _make_session(api_key)+ permissions: dict[str, str | None] = {}+ for endpoint in endpoints:+ try:+ response = _probe_endpoint(session, endpoint)+ except Exception:+ # A network blip is not a permission denial.+ permissions[endpoint] = None+ continue+ if response.status_code in (401, 403):+ message = _error_message(response)+ permissions[endpoint] = message or "Your Instantly API key does not grant access to this table."+ else:+ permissions[endpoint] = None+ return permissions+++def _list_webhooks(session: requests.Session, logger: FilteringBoundLogger) -> list[dict[str, Any]]:+ webhooks: list[dict[str, Any]] = []+ starting_after: Optional[str] = None+ for _ in range(MAX_WEBHOOK_LIST_PAGES):+ params: dict[str, Any] = {"limit": DEFAULT_PAGE_SIZE}+ if starting_after:+ params["starting_after"] = starting_after+ response = session.get(f"{BASE_URL}/api/v2/webhooks", params=params, timeout=REQUEST_TIMEOUT_SECONDS)+ response.raise_for_status()+ data = response.json()+ items = data.get("items") if isinstance(data, dict) else data+ if not isinstance(items, list) or not items:+ break+ webhooks.extend(item for item in items if isinstance(item, dict))+ next_cursor = data.get("next_starting_after") if isinstance(data, dict) else None+ if not next_cursor or next_cursor == starting_after:+ break+ starting_after = next_cursor+ else:+ logger.warning(f"Instantly: webhook listing hit the {MAX_WEBHOOK_LIST_PAGES}-page cap; stopping")+ return webhooks+++def _find_webhook_by_url(+ session: requests.Session, webhook_url: str, logger: FilteringBoundLogger+) -> dict[str, Any] | None:+ return next((wh for wh in _list_webhooks(session, logger) if wh.get("target_hook_url") == webhook_url), None)+++def create_webhook(api_key: str, webhook_url: str, logger: FilteringBoundLogger) -> WebhookCreationResult:+ try:+ session = _make_session(api_key)+ secret = secrets.token_urlsafe(32)+ body = {+ "target_hook_url": webhook_url,+ "name": WEBHOOK_NAME,+ # all_events also covers custom label events.+ "event_type": "all_events",+ "headers": {WEBHOOK_SECRET_HEADER: secret},+ }++ existing = _find_webhook_by_url(session, webhook_url, logger)+ if existing is not None and existing.get("id") is not None:+ # A webhook for this URL already exists (e.g. a partial earlier setup) — reconcile it+ # with a fresh secret instead of creating a duplicate.+ response = session.patch(+ f"{BASE_URL}/api/v2/webhooks/{existing['id']}", json=body, timeout=REQUEST_TIMEOUT_SECONDS+ )+ else:+ response = session.post(f"{BASE_URL}/api/v2/webhooks", json=body, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 402:+ return WebhookCreationResult(success=False, error=WEBHOOK_PLAN_ERROR)+ if response.status_code in (401, 403):+ return WebhookCreationResult(success=False, error=WEBHOOK_SCOPE_ERROR)+ if not response.ok:+ raise Exception(f"Instantly webhook creation failed with HTTP {response.status_code}")+ return WebhookCreationResult(success=True, extra_inputs={"signing_secret": secret})+ except Exception as e:+ logger.exception(f"Instantly: failed to create webhook: {e}")+ return WebhookCreationResult(success=False, error=f"Failed to create Instantly webhook automatically: {e}")+++def get_external_webhook_info(api_key: str, webhook_url: str, logger: FilteringBoundLogger) -> ExternalWebhookInfo:+ try:+ session = _make_session(api_key)+ existing = _find_webhook_by_url(session, webhook_url, logger)+ if existing is None:+ return ExternalWebhookInfo(exists=False)+ # status: 1 = active, -1 = disabled after repeated delivery failures.+ status = "error" if existing.get("status") == -1 else "enabled"+ event_type = existing.get("event_type")+ return ExternalWebhookInfo(+ exists=True,+ url=existing.get("target_hook_url"),+ enabled_events=[event_type] if event_type else None,+ status=status,+ created_at=existing.get("timestamp_created"),+ )+ except Exception as e:+ return ExternalWebhookInfo(exists=False, error=f"Failed to check Instantly webhook: {e}")+++def delete_webhook(api_key: str, webhook_url: str, logger: FilteringBoundLogger) -> WebhookDeletionResult:+ try:+ session = _make_session(api_key)+ existing = _find_webhook_by_url(session, webhook_url, logger)+ if existing is None or existing.get("id") is None:+ # Nothing to delete — the desired end state already holds.+ return WebhookDeletionResult(success=True)++ response = session.delete(f"{BASE_URL}/api/v2/webhooks/{existing['id']}", timeout=REQUEST_TIMEOUT_SECONDS)+ if response.status_code in (401, 403):+ return WebhookDeletionResult(success=False, error=WEBHOOK_SCOPE_ERROR)+ if not response.ok:+ raise Exception(f"Instantly webhook deletion failed with HTTP {response.status_code}")+ return WebhookDeletionResult(success=True)+ except Exception as e:+ logger.exception(f"Instantly: failed to delete webhook: {e}")+ return WebhookDeletionResult(success=False, error=f"Failed to delete Instantly webhook: {e}")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/settings.pynew file mode 100644index 000000000000..ea3819b9f395--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/settings.py@@ -0,0 +1,115 @@+from dataclasses import dataclass, field+from typing import Any, Literal, Optional++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++BASE_URL = "https://api.instantly.ai"+API_VERSION = "v2"++# Most list endpoints cap `limit` at 100.+DEFAULT_PAGE_SIZE = 100++# GET /api/v2/emails is rate-limited to 20 requests/minute (other endpoints have looser,+# unpublished limits), so the emails stream self-throttles between pages.+EMAILS_REQUEST_INTERVAL_SECONDS = 3.0++# Webhook-fed event stream (no pull API — Instantly webhooks deliver event notifications,+# not full objects, so they get their own table instead of merging into the pull tables).+WEBHOOK_EVENTS_ENDPOINT = "webhook_events"+# All webhook deliveries route to the single webhook_events schema under this mapping key.+WEBHOOK_ROUTING_KEY = "event"+++@dataclass+class InstantlyEndpointConfig:+ name: str+ # Path under https://api.instantly.ai/api/v2.+ path: str+ method: Literal["GET", "POST"] = "GET"+ # "cursor": limit/starting_after pagination with a next_starting_after cursor in the body+ # (the leads endpoint carries both in the POST JSON body instead of the query string).+ # "single": one unpaginated response.+ pagination: Literal["cursor", "single"] = "cursor"+ # Where the row list lives in the response body; None means the body is a bare JSON array.+ data_selector: Optional[str] = "items"+ # Static request params (query string for GET, JSON body for POST).+ params: dict[str, Any] = field(default_factory=dict)+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation-time field for datetime partitioning. Never an updated_at-style field.+ partition_key: Optional[str] = "timestamp_created"+ # Only emails exposes a server-side timestamp filter (min_timestamp_created + sort_order=asc).+ supports_incremental: bool = False+ description: Optional[str] = None+++INSTANTLY_ENDPOINTS: dict[str, InstantlyEndpointConfig] = {+ "campaigns": InstantlyEndpointConfig(+ name="campaigns",+ path="/campaigns",+ description="Email outreach campaigns with their schedules, sequences, and sending settings.",+ ),+ "accounts": InstantlyEndpointConfig(+ name="accounts",+ path="/accounts",+ # Accounts have no `id` field — the mailbox email address is the identifier.+ primary_keys=["email"],+ description="Sending email accounts connected to the workspace, including warmup status and limits.",+ ),+ "leads": InstantlyEndpointConfig(+ name="leads",+ # Deliberate API deviation: listing leads is POST with a JSON body because the filter+ # arguments are too complex for query params.+ path="/leads/list",+ method="POST",+ description="Leads across campaigns and lead lists, with contact details and engagement counts.",+ ),+ "emails": InstantlyEndpointConfig(+ name="emails",+ path="/emails",+ # sort_order=asc keeps arrival order matching sort_mode="asc" so the incremental+ # watermark can checkpoint safely (the API defaults to newest-first).+ params={"sort_order": "asc"},+ supports_incremental=True,+ description="Sent and received emails from campaigns and the unified inbox (Unibox).",+ ),+ "lead_lists": InstantlyEndpointConfig(+ name="lead_lists",+ path="/lead-lists",+ description="Lead lists used to organize leads outside campaigns.",+ ),+ "lead_labels": InstantlyEndpointConfig(+ name="lead_labels",+ path="/lead-labels",+ description="Custom lead interest labels configured in the workspace.",+ ),+ "custom_tags": InstantlyEndpointConfig(+ name="custom_tags",+ path="/custom-tags",+ description="Custom tags that can be assigned to campaigns and accounts.",+ ),+ "campaign_analytics": InstantlyEndpointConfig(+ name="campaign_analytics",+ path="/campaigns/analytics",+ pagination="single",+ data_selector=None,+ primary_keys=["campaign_id"],+ partition_key=None,+ description="Aggregate per-campaign analytics: sends, opens, replies, clicks, bounces, and opportunities.",+ ),+ "campaign_daily_analytics": InstantlyEndpointConfig(+ name="campaign_daily_analytics",+ path="/campaigns/analytics/daily",+ pagination="single",+ data_selector=None,+ primary_keys=["date"],+ partition_key=None,+ description="Workspace-wide daily campaign analytics: sends, opens, replies, and clicks per day.",+ ),+}++ENDPOINTS = tuple(INSTANTLY_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ "emails": [incremental_field("timestamp_created")],+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/source.pyindex 4135fd1cc2c7..54afa238e9c2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/source.py@@ -1,21 +1,76 @@-from typing import cast+from typing import TYPE_CHECKING, Optional, cast++import structlog++if TYPE_CHECKING:+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDCfrom 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 (+ ExternalWebhookInfo,+ FieldType,+ ResumableSource,+ WebhookCreationResult,+ WebhookDeletionResult,+ WebhookSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.instantly import (InstantlySourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.instantly.instantly import (+ InstantlyResumeConfig,+ create_webhook as create_instantly_webhook,+ delete_webhook as delete_instantly_webhook,+ get_endpoint_permissions as get_instantly_endpoint_permissions,+ get_external_webhook_info as get_instantly_webhook_info,+ instantly_source,+ validate_credentials as validate_instantly_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.instantly.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ INSTANTLY_ENDPOINTS,+ WEBHOOK_EVENTS_ENDPOINT,+ WEBHOOK_ROUTING_KEY,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+# Webhook management calls run in the API request path where no job logger exists.+logger = structlog.get_logger(__name__)+@SourceRegistry.register-class InstantlySource(SimpleSource[InstantlySourceConfig]):+class InstantlySource(+ ResumableSource[InstantlySourceConfig, InstantlyResumeConfig],+ WebhookSource[InstantlySourceConfig],+):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = ("v2",)+ default_version = "v2"+ api_docs_url = "https://developer.instantly.ai/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.INSTANTLY@@ -26,7 +81,156 @@ class InstantlySource(SimpleSource[InstantlySourceConfig]):name=SchemaExternalDataSourceType.INSTANTLY,category=DataWarehouseSourceCategory.SALES,label="Instantly",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Sync campaigns, leads, emails, sending accounts, and analytics from Instantly into the PostHog Data warehouse.++Create an API key under **Settings → Integrations → API keys** in Instantly. The API requires the Growth plan or above.++API keys are scope-gated: the key needs a read scope for every table you sync (`all:read` covers everything; narrower keys like `campaigns:read`, `leads:read`, `emails:read`, or `accounts:read` work for their own tables). The optional webhook event stream additionally needs `webhooks:all` and the Hypergrowth plan or above.""",iconPath="/static/services/instantly.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/instantly",+ keywords=["cold email", "email outreach", "sales engagement", "instantly.ai"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ webhookSetupCaption="""To set up the webhook manually:++1. In Instantly, go to **Settings → Integrations → Webhooks** (or use the API) and create a webhook+2. Set the target URL to the webhook URL shown below and the event type to **All events**+3. Add a custom header named `x-posthog-webhook-secret` with a value of your choosing, and paste the same value into the webhook secret field below++Instantly webhooks require the Hypergrowth plan or above, and automatic creation needs an API key with the `webhooks:all` (or `all:all`) scope.""",+ webhookFields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="signing_secret",+ label="Webhook secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.instantly.ai": "Instantly rejected your API key. Check the key is correct and has not been revoked, then reconnect.",+ "402 Client Error: Payment Required for url: https://api.instantly.ai": "Your Instantly workspace does not have an active plan with API access (the API requires the Growth plan or above).",+ "403 Client Error: Forbidden for url: https://api.instantly.ai": "Your Instantly API key does not have the scope required for this table. Grant the matching read scope (or use an `all:read` key), then reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.instantly.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ @property+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:+ from products.warehouse_sources.backend.temporal.data_imports.sources.instantly.webhook_template import ( # noqa: PLC0415+ template,+ )++ return template++ @property+ def webhook_resource_map(self) -> dict[str, str]:+ return {WEBHOOK_EVENTS_ENDPOINT: WEBHOOK_ROUTING_KEY}++ def get_schemas(+ self,+ config: InstantlySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names=None,+ descriptions={+ name: config_.description for name, config_ in INSTANTLY_ENDPOINTS.items() if config_.description+ },+ )+ schemas.append(+ SourceSchema(+ name=WEBHOOK_EVENTS_ENDPOINT,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ supports_webhooks=True,+ webhook_only=True,+ description=(+ "Raw Instantly webhook event stream (sends, opens, replies, bounces, lead status "+ "changes). Requires the webhook to be enabled — Hypergrowth plan or above."+ ),+ )+ )+ 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: InstantlySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_instantly_credentials(config.api_key, schema_name)++ def get_endpoint_permissions(+ self, config: InstantlySourceConfig, team_id: int, endpoints: list[str]+ ) -> dict[str, str | None]:+ return get_instantly_endpoint_permissions(config.api_key, endpoints)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[InstantlyResumeConfig]:+ return ResumableSourceManager[InstantlyResumeConfig](inputs, InstantlyResumeConfig)++ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:+ return WebhookSourceManager(inputs, inputs.logger)++ def create_webhook(self, config: InstantlySourceConfig, webhook_url: str, team_id: int) -> WebhookCreationResult:+ return create_instantly_webhook(config.api_key, webhook_url, logger)++ def get_external_webhook_info(+ self, config: InstantlySourceConfig, webhook_url: str, team_id: int+ ) -> ExternalWebhookInfo:+ return get_instantly_webhook_info(config.api_key, webhook_url, logger)++ def delete_webhook(self, config: InstantlySourceConfig, webhook_url: str, team_id: int) -> WebhookDeletionResult:+ return delete_instantly_webhook(config.api_key, webhook_url, logger)++ def source_for_pipeline(+ self,+ config: InstantlySourceConfig,+ resumable_source_manager: ResumableSourceManager[InstantlyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name != WEBHOOK_EVENTS_ENDPOINT and inputs.schema_name not in INSTANTLY_ENDPOINTS:+ raise ValueError(f"Unknown Instantly schema '{inputs.schema_name}'")++ return instantly_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ webhook_source_manager=self.get_webhook_source_manager(inputs),+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/tests/test_instantly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/tests/test_instantly.pynew file mode 100644index 000000000000..a3c8ce1c9ff0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/tests/test_instantly.py@@ -0,0 +1,337 @@+from collections.abc import Iterable+from datetime import UTC, datetime++import pytest+from unittest import mock++from requests import Request++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.utils import table_from_py_list+from products.warehouse_sources.backend.temporal.data_imports.sources.instantly.instantly import (+ WEBHOOK_PLAN_ERROR,+ WEBHOOK_SECRET_HEADER,+ InstantlyCursorPaginator,+ InstantlyResumeConfig,+ InstantlyThrottledCursorPaginator,+ _format_incremental_timestamp,+ _webhook_events_table_transformer,+ create_webhook,+ delete_webhook,+ get_endpoint_permissions,+ get_resource,+ instantly_source,+ validate_credentials,+)++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.instantly.instantly"+++def _response(body=None, status_code=200):+ response = mock.MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body+ return response+++def _endpoint_config(resource) -> dict:+ endpoint = resource["endpoint"]+ assert isinstance(endpoint, dict)+ return endpoint+++class TestInstantly:+ def test_paginator_follows_next_starting_after_in_query(self):+ paginator = InstantlyCursorPaginator()+ request = Request(method="GET", url="https://api.instantly.ai/api/v2/campaigns", params={"limit": 100})+ items = [{"id": "a"}]++ paginator.update_state(_response({"items": items, "next_starting_after": "cur-1"}), items)+ paginator.update_request(request)++ assert paginator.has_next_page+ assert request.params["starting_after"] == "cur-1"++ def test_paginator_follows_cursor_in_json_body_for_post_endpoints(self):+ paginator = InstantlyCursorPaginator(use_json_body=True)+ request = Request(method="POST", url="https://api.instantly.ai/api/v2/leads/list", json={"limit": 100})+ items = [{"id": "a"}]++ paginator.update_state(_response({"items": items, "next_starting_after": "cur-1"}), items)+ paginator.update_request(request)++ assert request.json["starting_after"] == "cur-1"+ assert "starting_after" not in (request.params or {})++ @pytest.mark.parametrize(+ "body,data",+ [+ # Empty page, even with a cursor still present.+ ({"items": [], "next_starting_after": "cur-1"}, []),+ # No cursor in the body.+ ({"items": [{"id": "a"}]}, [{"id": "a"}]),+ ],+ )+ def test_paginator_stops(self, body, data):+ paginator = InstantlyCursorPaginator()++ paginator.update_state(_response(body), data)++ assert not paginator.has_next_page++ def test_paginator_stops_on_non_advancing_cursor(self):+ # If the API echoed the same cursor forever we'd otherwise refetch the same page endlessly.+ paginator = InstantlyCursorPaginator()+ items = [{"id": "a"}]++ paginator.update_state(_response({"items": items, "next_starting_after": "cur-1"}), items)+ assert paginator.has_next_page+ paginator.update_state(_response({"items": items, "next_starting_after": "cur-1"}), items)++ assert not paginator.has_next_page++ def test_paginator_resume_state_roundtrip(self):+ paginator = InstantlyCursorPaginator()+ items = [{"id": "a"}]+ paginator.update_state(_response({"items": items, "next_starting_after": "cur-9"}), items)++ state = paginator.get_resume_state()+ assert state == {"cursor": "cur-9"}++ resumed = InstantlyCursorPaginator()+ resumed.set_resume_state(state)+ request = Request(method="GET", url="https://api.instantly.ai/api/v2/campaigns", params={})+ resumed.init_request(request)++ assert request.params["starting_after"] == "cur-9"++ @mock.patch(f"{MODULE}.time.sleep")+ def test_throttled_paginator_waits_only_between_pages(self, mock_sleep):+ paginator = InstantlyThrottledCursorPaginator(3.0)+ request = Request(method="GET", url="https://api.instantly.ai/api/v2/emails", params={})+ items = [{"id": "a"}]++ paginator.update_state(_response({"items": items, "next_starting_after": "cur-1"}), items)+ paginator.update_request(request)+ assert mock_sleep.call_count == 1++ paginator.update_state(_response({"items": items}), items)+ paginator.update_request(request)+ assert mock_sleep.call_count == 1++ def test_emails_resource_sends_incremental_filter_only_when_enabled(self):+ incremental = get_resource("emails", True)+ full_refresh = get_resource("emails", False)++ incremental_params = _endpoint_config(incremental)["params"]+ assert incremental_params["min_timestamp_created"]["type"] == "incremental"+ assert incremental_params["min_timestamp_created"]["cursor_path"] == "timestamp_created"+ # sort_order=asc keeps arrival order matching sort_mode="asc" for watermark checkpointing.+ assert incremental_params["sort_order"] == "asc"+ assert incremental["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}++ assert "min_timestamp_created" not in _endpoint_config(full_refresh)["params"]+ assert full_refresh["write_disposition"] == "replace"++ def test_leads_resource_is_post_with_json_body(self):+ endpoint = _endpoint_config(get_resource("leads", False))++ assert endpoint["method"] == "POST"+ assert endpoint["json"] == {"limit": 100}+ assert "params" not in endpoint++ def test_analytics_resources_are_single_page_bare_arrays(self):+ endpoint = _endpoint_config(get_resource("campaign_analytics", False))++ assert endpoint["paginator"] == "single_page"+ assert "data_selector" not in endpoint++ @pytest.mark.parametrize(+ "value,expected",+ [+ (datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), "2026-01-02T03:04:05+00:00"),+ ("2026-01-02T03:04:05.000Z", "2026-01-02T03:04:05.000Z"),+ ],+ )+ def test_format_incremental_timestamp(self, value, expected):+ assert _format_incremental_timestamp(value) == expected++ @pytest.mark.parametrize(+ "endpoint,expected_primary_keys,expected_partition_mode",+ [+ ("campaigns", ["id"], "datetime"),+ ("accounts", ["email"], "datetime"),+ ("campaign_analytics", ["campaign_id"], None),+ ],+ )+ @mock.patch(f"{MODULE}.rest_api_resource")+ def test_source_response_per_endpoint(+ self, mock_resource, endpoint, expected_primary_keys, expected_partition_mode+ ):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False++ response = instantly_source(+ api_key="key",+ endpoint=endpoint,+ team_id=1,+ job_id="job",+ resumable_source_manager=manager,+ )++ assert response.name == endpoint+ assert response.primary_keys == expected_primary_keys+ assert response.partition_mode == expected_partition_mode++ @mock.patch(f"{MODULE}.rest_api_resource")+ def test_resume_state_seeds_paginator_and_saves_after_batches(self, mock_resource):+ manager = mock.MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = InstantlyResumeConfig(cursor="saved-cursor")++ instantly_source(+ api_key="key",+ endpoint="campaigns",+ team_id=1,+ job_id="job",+ resumable_source_manager=manager,+ )++ kwargs = mock_resource.call_args.kwargs+ assert kwargs["initial_paginator_state"] == {"cursor": "saved-cursor"}++ save_checkpoint = kwargs["resume_hook"]+ save_checkpoint({"cursor": "next-cursor"})+ manager.save_state.assert_called_once_with(InstantlyResumeConfig(cursor="next-cursor"))++ # A None/exhausted state must not clobber the checkpoint.+ save_checkpoint(None)+ assert manager.save_state.call_count == 1++ def test_webhook_events_source_is_webhook_only_and_empty_without_webhook(self):+ webhook_manager = mock.MagicMock()+ webhook_manager.webhook_enabled = mock.AsyncMock(return_value=False)++ response = instantly_source(+ api_key="key",+ endpoint="webhook_events",+ team_id=1,+ job_id="job",+ resumable_source_manager=mock.MagicMock(),+ webhook_source_manager=webhook_manager,+ )++ assert response.webhook_only is True+ assert response.primary_keys == ["event_id"]+ items = response.items()+ assert isinstance(items, Iterable)+ assert list(items) == []++ def test_webhook_events_transformer_stamps_event_id_and_dedupes(self):+ payload = {"event_type": "email_sent", "lead_email": "[email protected]", "timestamp": "2026-01-01T00:00:00Z"}+ other = {"event_type": "reply_received", "lead_email": "[email protected]", "timestamp": "2026-01-02T00:00:00Z"}+ table = table_from_py_list([dict(payload), dict(payload), dict(other)])++ result = _webhook_events_table_transformer(table)+ rows = result.to_pylist()++ assert len(rows) == 2+ assert all(row["event_id"] for row in rows)+ # Redelivered payloads hash to the same id so delta merge collapses them across syncs too.+ rerun = _webhook_events_table_transformer(table_from_py_list([dict(payload)])).to_pylist()+ assert rerun[0]["event_id"] == rows[0]["event_id"]++ @pytest.mark.parametrize(+ "status_code,schema_name,expected_valid",+ [+ (200, None, True),+ (401, None, False),+ (402, None, False),+ # A 403 at source-create means a valid but scoped key — must not block the source.+ (403, None, True),+ (403, "emails", False),+ (200, "emails", True),+ ],+ )+ @mock.patch(f"{MODULE}._probe_endpoint")+ @mock.patch(f"{MODULE}._make_session")+ def test_validate_credentials_status_mapping(+ self, mock_session, mock_probe, status_code, schema_name, expected_valid+ ):+ mock_probe.return_value = _response({"message": "Forbidden"}, status_code=status_code)++ valid, error = validate_credentials("key", schema_name)++ assert valid is expected_valid+ assert (error is None) is expected_valid++ @mock.patch(f"{MODULE}._probe_endpoint")+ @mock.patch(f"{MODULE}._make_session")+ def test_get_endpoint_permissions_flags_only_real_denials(self, mock_session, mock_probe):+ def probe(session, endpoint):+ if endpoint == "emails":+ return _response({"message": "Missing scope: emails:read"}, status_code=403)+ if endpoint == "leads":+ raise ConnectionError("boom")+ return _response({"items": []}, status_code=200)++ mock_probe.side_effect = probe++ permissions = get_endpoint_permissions("key", ["campaigns", "emails", "leads"])++ assert permissions["campaigns"] is None+ assert permissions["emails"] == "Missing scope: emails:read"+ # A network blip is not a permission denial.+ assert permissions["leads"] is None++ @mock.patch(f"{MODULE}._find_webhook_by_url", return_value=None)+ @mock.patch(f"{MODULE}._make_session")+ def test_create_webhook_subscribes_all_events_with_secret_header(self, mock_session, mock_find):+ session = mock_session.return_value+ session.post.return_value = _response({"id": "wh-1"}, status_code=200)++ result = create_webhook("key", "https://ph/webhook", mock.MagicMock())++ assert result.success is True+ body = session.post.call_args.kwargs["json"]+ assert body["target_hook_url"] == "https://ph/webhook"+ assert body["event_type"] == "all_events"+ secret = body["headers"][WEBHOOK_SECRET_HEADER]+ assert result.extra_inputs == {"signing_secret": secret}++ @mock.patch(f"{MODULE}._find_webhook_by_url", return_value={"id": "wh-1", "target_hook_url": "https://ph/webhook"})+ @mock.patch(f"{MODULE}._make_session")+ def test_create_webhook_reconciles_existing_webhook_instead_of_duplicating(self, mock_session, mock_find):+ session = mock_session.return_value+ session.patch.return_value = _response({"id": "wh-1"}, status_code=200)++ result = create_webhook("key", "https://ph/webhook", mock.MagicMock())++ assert result.success is True+ session.post.assert_not_called()+ assert "/webhooks/wh-1" in session.patch.call_args.args[0]++ @mock.patch(f"{MODULE}._find_webhook_by_url", return_value=None)+ @mock.patch(f"{MODULE}._make_session")+ def test_create_webhook_surfaces_plan_gating(self, mock_session, mock_find):+ session = mock_session.return_value+ session.post.return_value = _response({"message": "Workspace does not have an active paid plan"}, 402)++ result = create_webhook("key", "https://ph/webhook", mock.MagicMock())++ assert result.success is False+ assert result.error == WEBHOOK_PLAN_ERROR++ @mock.patch(f"{MODULE}._find_webhook_by_url")+ @mock.patch(f"{MODULE}._make_session")+ def test_delete_webhook_is_idempotent(self, mock_session, mock_find):+ session = mock_session.return_value+ mock_find.return_value = None++ assert delete_webhook("key", "https://ph/webhook", mock.MagicMock()).success is True+ session.delete.assert_not_called()++ mock_find.return_value = {"id": "wh-1"}+ session.delete.return_value = _response(None, status_code=200)+ assert delete_webhook("key", "https://ph/webhook", mock.MagicMock()).success is True+ assert "/webhooks/wh-1" in session.delete.call_args.args[0]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/tests/test_instantly_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/tests/test_instantly_source.pynew file mode 100644index 000000000000..4080cbc85ebf--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/tests/test_instantly_source.py@@ -0,0 +1,110 @@+import pytest+from unittest import mock++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.instantly import (+ InstantlySourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.instantly.instantly import InstantlyResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.instantly.settings import (+ ENDPOINTS,+ WEBHOOK_EVENTS_ENDPOINT,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.instantly.source import InstantlySource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestInstantlySource:+ def setup_method(self):+ self.source = InstantlySource()+ self.team_id = 123+ self.config = InstantlySourceConfig(api_key="test-key")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.INSTANTLY++ def test_source_is_released_and_visible(self):+ config = self.source.get_source_config++ assert config.name.value == "Instantly"+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.category is not None++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")++ assert key_field.type == SourceFieldInputConfigType.PASSWORD+ assert key_field.secret is True+ assert key_field.required is True++ def test_get_schemas_only_emails_supports_incremental(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == {*ENDPOINTS, WEBHOOK_EVENTS_ENDPOINT}+ # Only /emails exposes a server-side timestamp filter (min_timestamp_created); everything+ # else must ship full refresh.+ assert {schema.name for schema in schemas if schema.supports_incremental} == {"emails"}++ def test_get_schemas_webhook_events_is_webhook_only(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ webhook_schema = next(schema for schema in schemas if schema.name == WEBHOOK_EVENTS_ENDPOINT)++ assert webhook_schema.webhook_only is True+ assert webhook_schema.supports_webhooks is True+ assert not any(schema.supports_webhooks for schema in schemas if schema.name != WEBHOOK_EVENTS_ENDPOINT)++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["leads", WEBHOOK_EVENTS_ENDPOINT])+ assert {schema.name for schema in schemas} == {"leads", WEBHOOK_EVENTS_ENDPOINT}++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.instantly.source.validate_instantly_credentials"+ )+ def test_validate_credentials_plumbs_config(self, mock_validate):+ mock_validate.return_value = (True, None)++ assert self.source.validate_credentials(self.config, self.team_id, schema_name="emails") == (True, None)+ mock_validate.assert_called_once_with("test-key", "emails")++ 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 InstantlyResumeConfig++ def test_webhook_resource_map_routes_all_events_to_webhook_events(self):+ assert self.source.webhook_resource_map == {WEBHOOK_EVENTS_ENDPOINT: "event"}++ def test_webhook_template_present_with_required_inputs(self):+ template = self.source.webhook_template++ assert template is not None+ assert template.type == "warehouse_source_webhook"+ input_keys = {schema_input["key"] for schema_input in template.inputs_schema or []}+ assert {"signing_secret", "bypass_secret_check", "schema_mapping", "source_id"} <= input_keys++ def test_source_for_pipeline_rejects_unknown_schema(self):+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_real_table"++ with pytest.raises(ValueError, match="Unknown Instantly schema"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.instantly.ai/api/v2/campaigns?limit=100",+ "402 Client Error: Payment Required for url: https://api.instantly.ai/api/v2/emails",+ "403 Client Error: Forbidden for url: https://api.instantly.ai/api/v2/leads/list",+ ],+ )+ def test_non_retryable_errors_match_permanent_failures(self, observed_error):+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ def test_non_retryable_errors_do_not_match_transient_failures(self):+ transient = "HTTP 429 for https://api.instantly.ai/api/v2/emails"+ assert not any(key in transient for key in self.source.get_non_retryable_errors())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/webhook_template.pynew file mode 100644index 000000000000..58d1f95c586f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instantly/webhook_template.py@@ -0,0 +1,112 @@+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC++# Instantly does not sign webhook deliveries, but it does send static custom headers configured+# on the webhook. `create_webhook` attaches a generated secret in the x-posthog-webhook-secret+# header, which this template verifies. Manually created webhooks must configure the same header,+# or enable the bypass toggle.+template: HogFunctionTemplateDC = HogFunctionTemplateDC(+ status="alpha",+ free=False,+ type="warehouse_source_webhook",+ id="template-warehouse-source-instantly",+ name="Instantly warehouse source webhook",+ description="Receive Instantly webhook events for data warehouse ingestion",+ icon_url="/static/services/instantly.png",+ category=["Data warehouse"],+ code_language="hog",+ code="""\+if (request.method != 'POST') {+ return {+ 'httpResponse': {+ 'status': 405,+ 'body': 'Method not allowed'+ }+ }+}++if (not inputs.bypass_secret_check) {+ if (empty(inputs.signing_secret)) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Webhook secret not configured',+ }+ }+ }++ let providedSecret := request.headers['x-posthog-webhook-secret']++ if (empty(providedSecret) or providedSecret != inputs.signing_secret) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Bad webhook secret',+ }+ }+ }+}++let eventType := request.body.event_type++if (empty(eventType)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'No event_type found, skipping'+ }+ }+}++// Every Instantly event (including custom label events) lands in the single+// webhook_events table.+let schemaId := inputs.schema_mapping?.['event']++if (empty(schemaId)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'No schema mapping for events, skipping'+ }+ }+}++produceToWarehouseWebhooks(request.body, schemaId)""",+ inputs_schema=[+ {+ "type": "string",+ "key": "signing_secret",+ "label": "Webhook secret",+ "required": False,+ "secret": True,+ "hidden": False,+ "description": "Shared secret sent by Instantly in the x-posthog-webhook-secret header, used to verify the delivery came from your webhook",+ },+ {+ "type": "boolean",+ "key": "bypass_secret_check",+ "label": "Bypass secret check",+ "description": "If set, the x-posthog-webhook-secret header will not be checked. Only use this for manually created webhooks without the secret header configured.",+ "default": False,+ "required": False,+ "secret": False,+ },+ {+ "type": "json",+ "key": "schema_mapping",+ "label": "Schema mapping",+ "description": "Maps Instantly webhook events to ExternalDataSchema IDs",+ "required": True,+ "secret": False,+ "hidden": True,+ },+ {+ "type": "string",+ "key": "source_id",+ "label": "Source ID",+ "description": "The ExternalDataSource ID this webhook is associated with",+ "required": True,+ "secret": False,+ "hidden": True,+ },+ ],+)