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(warehouse): add intercom data warehouse source (#57519)

Marcus Hof025b0455b3c1
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index df74e7ddb66f..d0cf4a9f2818 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -417,7 +417,7 @@ class InstagramSourceConfig(config.Config):
@config.config
class IntercomSourceConfig(config.Config):
- pass
+ intercom_integration_id: int = config.value(converter=config.str_to_int)
@config.config
diff --git a/posthog/temporal/data_imports/sources/intercom/intercom.py b/posthog/temporal/data_imports/sources/intercom/intercom.py
new file mode 100644
index 000000000000..eed4fa595b9b
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/intercom/intercom.py
@@ -0,0 +1,357 @@
+from collections.abc import AsyncIterable, Callable, Iterable, Iterator
+from typing import Any, Optional
+
+from requests import Request, Response, Session
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.rest_source import RESTAPIConfig, rest_api_resource
+from posthog.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
+ JSONResponseCursorPaginator,
+ JSONResponsePaginator,
+ SinglePagePaginator,
+)
+from posthog.temporal.data_imports.sources.common.rest_source.typing import Endpoint, EndpointResource
+from posthog.temporal.data_imports.sources.intercom.settings import INTERCOM_ENDPOINTS, IntercomEndpointConfig
+
+INTERCOM_API_BASE = "https://api.intercom.io"
+INTERCOM_API_VERSION = "2.13"
+
+
+def _default_headers() -> dict[str, str]:
+ return {
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ "Intercom-Version": INTERCOM_API_VERSION,
+ }
+
+
+def _auth_headers(access_token: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {access_token}", **_default_headers()}
+
+
+def _make_intercom_session(access_token: str) -> Session:
+ """Build a tracked session with Intercom auth + default headers baked in.
+
+ Reusing one session across the many requests a sync makes lets urllib3
+ keep the underlying TCP+TLS connection alive — the substream generators
+ (one GET per parent row) are the main beneficiary.
+ """
+ return make_tracked_session(headers=_auth_headers(access_token))
+
+
+class IntercomSearchPaginator(BasePaginator):
+ """Paginator for Intercom POST `/<resource>/search` endpoints.
+
+ Intercom's search APIs put the pagination cursor in the request body
+ (``pagination.starting_after``) rather than the query string, so the
+ standard ``JSONResponseCursorPaginator`` — which writes to
+ ``request.params`` — doesn't fit. The next cursor is read from
+ ``pages.next.starting_after`` in the response, the same shape the list
+ endpoints use.
+ """
+
+ def __init__(self) -> None:
+ super().__init__()
+ self._next_cursor: Optional[str] = None
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ try:
+ payload = response.json()
+ except Exception:
+ self._has_next_page = False
+ self._next_cursor = None
+ return
+ next_block = (payload.get("pages") or {}).get("next") or {}
+ cursor = next_block.get("starting_after") if isinstance(next_block, dict) else None
+ if cursor:
+ self._next_cursor = cursor
+ self._has_next_page = True
+ else:
+ self._next_cursor = None
+ self._has_next_page = False
+
+ def update_request(self, request: Request) -> None:
+ if self._next_cursor is None or request.json is None:
+ return
+ pagination = request.json.setdefault("pagination", {})
+ pagination["starting_after"] = self._next_cursor
+
+
+def _build_search_body(
+ cfg: IntercomEndpointConfig,
+ incremental_field: str,
+ db_incremental_field_last_value: Optional[Any],
+) -> dict[str, Any]:
+ """Build the POST body for Intercom's ``/<resource>/search`` endpoints.
+
+ ``value: 0`` is the historical-backfill case (matches every record);
+ once we have a watermark from a prior sync we filter ``<field> > <ts>``.
+ Sorting ascending on the same field so the cursor advances monotonically
+ — without it Intercom returns by relevance and the watermark we persist
+ would be meaningless.
+ """
+ cursor_value = int(db_incremental_field_last_value) if db_incremental_field_last_value is not None else 0
+ return {
+ "query": {"field": incremental_field, "operator": ">", "value": cursor_value},
+ "pagination": {"per_page": cfg.page_size},
+ "sort": {"field": incremental_field, "order": "ascending"},
+ }
+
+
+def _build_paginator(cfg: IntercomEndpointConfig) -> BasePaginator:
+ if cfg.paginator_kind == "search":
+ return IntercomSearchPaginator()
+ if cfg.paginator_kind == "cursor":
+ return JSONResponseCursorPaginator(
+ cursor_path="pages.next.starting_after",
+ cursor_param="starting_after",
+ )
+ if cfg.paginator_kind == "next_url":
+ return JSONResponsePaginator(next_url_path="pages.next")
+ return SinglePagePaginator()
+
+
+def get_resource(
+ name: str,
+ should_use_incremental_field: bool,
+ incremental_field: str | None,
+ db_incremental_field_last_value: Optional[Any],
+) -> EndpointResource:
+ cfg = INTERCOM_ENDPOINTS[name]
+
+ endpoint: Endpoint = {
+ "path": cfg.path,
+ "data_selector": cfg.data_selector,
+ "paginator": _build_paginator(cfg),
+ }
+
+ if cfg.method == "POST":
+ endpoint["method"] = "POST"
+
+ if cfg.paginator_kind == "search":
+ # Even in full-refresh mode the search endpoints need a query body;
+ # `value: 0` matches every record. Default to "updated_at" (the only
+ # cursor Intercom search endpoints support) when no field is passed.
+ endpoint["json"] = _build_search_body(cfg, incremental_field or "updated_at", db_incremental_field_last_value)
+ elif cfg.method == "POST" and cfg.paginator_kind in ("cursor", "next_url"):
+ # POST list endpoints (`/companies/list`) take `per_page` in the body.
+ # The next-URL paginator preserves the POST method and body when it
+ # follows `pages.next`, so the body just needs to be set once.
+ endpoint["json"] = {"per_page": cfg.page_size}
+ elif cfg.paginator_kind in ("cursor", "next_url"):
+ params: dict[str, Any] = {"per_page": cfg.page_size, **cfg.extra_params}
+ if cfg.incremental_query_param:
+ # Intercom's `/admins/activity_logs` returns a much smaller default
+ # window when called without `created_at_after`, so we always set
+ # the param. `0` matches every record (Unix epoch start).
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ params[cfg.incremental_query_param] = int(db_incremental_field_last_value)
+ else:
+ params[cfg.incremental_query_param] = 0
+ endpoint["params"] = params
+ elif cfg.paginator_kind == "single" and cfg.extra_params:
+ endpoint["params"] = dict(cfg.extra_params)
+
+ # Upsert on incremental syncs so updates to existing rows replace the
+ # prior version instead of appending duplicates. Full-refresh endpoints
+ # stay on replace.
+ is_incremental = should_use_incremental_field and (
+ cfg.paginator_kind == "search" or cfg.incremental_query_param is not None
+ )
+ write_disposition: Any = {"disposition": "merge", "strategy": "upsert"} if is_incremental else "replace"
+
+ return {
+ "name": cfg.name,
+ "table_name": cfg.name,
+ "write_disposition": write_disposition,
+ "endpoint": endpoint,
+ "table_format": "delta",
+ }
+
+
+def _intercom_get(session: Session, path_or_url: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
+ url = path_or_url if path_or_url.startswith("http") else f"{INTERCOM_API_BASE}{path_or_url}"
+ response = session.get(url, params=params, timeout=30)
+ response.raise_for_status()
+ return response.json()
+
+
+def _intercom_post(session: Session, path: str, body: dict[str, Any]) -> dict[str, Any]:
+ response = session.post(f"{INTERCOM_API_BASE}{path}", json=body, timeout=30)
+ response.raise_for_status()
+ return response.json()
+
+
+def _iter_conversations(
+ session: Session,
+ incremental_field: str,
+ db_incremental_field_last_value: Optional[Any],
+) -> Iterator[dict[str, Any]]:
+ """Walk `POST /conversations/search` honoring the same `updated_at >`
+ server-side filter the conversations endpoint uses, so substreams only
+ refetch parents whose timestamp advanced."""
+ body = _build_search_body(INTERCOM_ENDPOINTS["conversations"], incremental_field, db_incremental_field_last_value)
+ while True:
+ payload = _intercom_post(session, "/conversations/search", body)
+ yield from (payload.get("conversations") or [])
+ next_block = (payload.get("pages") or {}).get("next") or {}
+ cursor = next_block.get("starting_after") if isinstance(next_block, dict) else None
+ if not cursor:
+ return
+ body["pagination"]["starting_after"] = cursor
+
+
+def _conversation_parts_generator(
+ session: Session,
+ incremental_field: str,
+ db_incremental_field_last_value: Optional[Any],
+) -> Iterator[dict[str, Any]]:
+ """Yield each conversation part. Parents are server-filtered by
+ `updated_at >`; the part rows themselves carry their own `updated_at`,
+ so the pipeline's cursor watermark advances per-part. `conversation_id`
+ is injected onto each row for joinability."""
+ for conv in _iter_conversations(session, incremental_field, db_incremental_field_last_value):
+ full = _intercom_get(session, f"/conversations/{conv['id']}")
+ parts = (full.get("conversation_parts") or {}).get("conversation_parts") or []
+ for part in parts:
+ part["conversation_id"] = conv["id"]
+ yield part
+
+
+def _iter_companies(session: Session) -> Iterator[dict[str, Any]]:
+ """Walk `POST /companies/list` page by page (no server-side timestamp
+ filter — full refresh)."""
+ body: dict[str, Any] = {"per_page": INTERCOM_ENDPOINTS["companies"].page_size}
+ next_url: str | None = None
+ while True:
+ if next_url is None:
+ payload = _intercom_post(session, "/companies/list", body)
+ else:
+ # `pages.next` is a full URL; the framework follows it as GET, but
+ # /companies/list is POST. Empirically Intercom honors GET on the
+ # `pages.next` URL too — same response shape — so we use GET to
+ # avoid having to re-build the body with the embedded cursor.
+ payload = _intercom_get(session, next_url)
+ yield from (payload.get("data") or [])
+ next_url = (payload.get("pages") or {}).get("next")
+ if not next_url:
+ return
+
+
+def _company_segments_generator(session: Session) -> Iterator[dict[str, Any]]:
+ """Walk all companies and yield each attached segment with `company_id`
+ injected. Full refresh — Intercom has no server-side timestamp filter on
+ either parent or child."""
+ for company in _iter_companies(session):
+ payload = _intercom_get(session, f"/companies/{company['id']}/segments")
+ for seg in payload.get("data", []) or []:
+ seg["company_id"] = company["id"]
+ yield seg
+
+
+def _substream_items(
+ session: Session,
+ endpoint: str,
+ incremental_field: str | None,
+ db_incremental_field_last_value: Optional[Any],
+) -> Iterator[dict[str, Any]]:
+ if endpoint == "conversation_parts":
+ if not incremental_field:
+ # Substream still works without an incremental field — we just
+ # walk every conversation. `updated_at` is the only declared
+ # cursor, so default to it for the parent search filter.
+ incremental_field = "updated_at"
+ return _conversation_parts_generator(session, incremental_field, db_incremental_field_last_value)
+ if endpoint == "company_segments":
+ return _company_segments_generator(session)
+ raise ValueError(f"Unknown Intercom substream endpoint: {endpoint}")
+
+
+def validate_credentials(access_token: str, schema_name: str | None = None) -> tuple[bool, str | None]:
+ """Validate an Intercom access token by hitting `/me`.
+
+ Works identically with OAuth-issued access tokens and Personal Access
+ Tokens — both flow as `Authorization: Bearer …`.
+
+ At source-create (``schema_name is None``) we accept 403 — the token
+ is genuine but the workspace hasn't granted scope for ``/me``. The
+ user can still grant scope per-endpoint downstream. Per-schema calls
+ (``schema_name`` set) re-raise 403 so the missing-scope error
+ surfaces against the specific table the user tried to use.
+ """
+ if not access_token:
+ return False, "Missing Intercom access token"
+
+ try:
+ response = _make_intercom_session(access_token).get(
+ f"{INTERCOM_API_BASE}/me",
+ timeout=10,
+ )
+ except Exception as e:
+ return False, str(e)
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, "Your Intercom access token is invalid or expired. Please reconnect."
+ if response.status_code == 403:
+ if schema_name is None:
+ return True, None
+ return False, "Your Intercom access token is missing required scopes. Please reconnect."
+ return False, f"HTTP {response.status_code}: {response.text[:200]}"
+
+
+def intercom_source(
+ access_token: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ should_use_incremental_field: bool = False,
+ incremental_field: str | None = None,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ cfg = INTERCOM_ENDPOINTS[endpoint]
+ items: Callable[[], Iterable[Any] | AsyncIterable[Any]]
+
+ if cfg.paginator_kind == "substream":
+ # One session built here is reused across the parent walk and every
+ # per-row child fetch, so urllib3 keeps the connection alive instead
+ # of re-handshaking per request.
+ session = _make_intercom_session(access_token)
+ items = lambda: _substream_items(session, endpoint, incremental_field, db_incremental_field_last_value)
+ else:
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": INTERCOM_API_BASE,
+ "auth": {
+ "type": "bearer",
+ "token": access_token,
+ },
+ "headers": _default_headers(),
+ },
+ "resource_defaults": {},
+ "resources": [
+ get_resource(
+ endpoint,
+ should_use_incremental_field,
+ incremental_field,
+ db_incremental_field_last_value,
+ )
+ ],
+ }
+ resource = rest_api_resource(config, team_id, job_id, db_incremental_field_last_value)
+ items = lambda: resource
+
+ return SourceResponse(
+ name=endpoint,
+ items=items,
+ primary_keys=cfg.primary_keys,
+ partition_keys=[cfg.partition_key],
+ partition_mode=cfg.partition_mode,
+ partition_format=cfg.partition_format,
+ partition_count=cfg.partition_count,
+ partition_size=cfg.partition_size,
+ sort_mode=cfg.sort_mode,
+ )
diff --git a/posthog/temporal/data_imports/sources/intercom/settings.py b/posthog/temporal/data_imports/sources/intercom/settings.py
new file mode 100644
index 000000000000..6edfea396155
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/intercom/settings.py
@@ -0,0 +1,257 @@
+from dataclasses import dataclass, field
+from typing import Literal
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import PartitionFormat
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+PaginatorKind = Literal["single", "cursor", "next_url", "search", "substream"]
+PartitionMode = Literal["md5", "datetime"]
+HttpMethod = Literal["GET", "POST"]
+SortMode = Literal["asc", "desc"]
+
+
+@dataclass
+class IntercomEndpointConfig:
+ name: str
+ path: str
+ data_selector: str
+ paginator_kind: PaginatorKind
+ method: HttpMethod = "GET"
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ partition_key: str = "created_at"
+ partition_mode: PartitionMode = "datetime"
+ partition_format: PartitionFormat | None = "week"
+ partition_count: int = 1
+ partition_size: int = 1
+ page_size: int = 150
+ sort_mode: SortMode = "asc"
+ extra_params: dict[str, str] = field(default_factory=dict)
+ # Query-string param Intercom expects for the cursor filter (e.g. "created_at_after"
+ # on /admins/activity_logs). Only set on endpoints that filter via query params.
+ incremental_query_param: str | None = None
+ # Substream wiring — when set, this endpoint is fetched per-row of `parent_endpoint`.
+ parent_endpoint: str | None = None
+
+
+# Endpoint contracts validated against the live Intercom REST API (version 2.13).
+# Selectors, pagination shape, and partition keys reflect what the API actually
+# returns — not the docs.
+#
+# Real-incremental endpoints (server-side filter honored): contacts, conversations,
+# tickets, activity_logs, conversation_parts (via parent). Everything else is
+# full-refresh because Intercom either has no server filter (companies, segments,
+# company_segments — Airbyte/Stitch sync these "incrementally" but actually walk
+# every page each run) or no timestamp at all (data_attributes).
+INTERCOM_ENDPOINTS: dict[str, IntercomEndpointConfig] = {
+ "admins": IntercomEndpointConfig(
+ name="admins",
+ path="/admins",
+ data_selector="admins",
+ paginator_kind="single",
+ partition_key="id",
+ partition_mode="md5",
+ partition_format=None,
+ ),
+ "teams": IntercomEndpointConfig(
+ name="teams",
+ path="/teams",
+ data_selector="teams",
+ paginator_kind="single",
+ partition_key="id",
+ partition_mode="md5",
+ partition_format=None,
+ ),
+ "tags": IntercomEndpointConfig(
+ name="tags",
+ path="/tags",
+ data_selector="data",
+ paginator_kind="single",
+ partition_key="id",
+ partition_mode="md5",
+ partition_format=None,
+ ),
+ "segments": IntercomEndpointConfig(
+ name="segments",
+ path="/segments",
+ data_selector="segments",
+ paginator_kind="single",
+ ),
+ "companies": IntercomEndpointConfig(
+ # `POST /companies/list` is the only paginated company-listing
+ # endpoint that's stable in 2.13. `GET /companies` requires a filter
+ # param (it's the "Retrieve Companies" lookup, returns 400 without
+ # one), and `/companies/scroll` only allows one open cursor per
+ # workspace at a time so concurrent or quickly-retried syncs collide.
+ # The next-URL pagination shape matches the other list endpoints
+ # (`pages.next` is a full URL); the framework follows it by mutating
+ # `request.url` while preserving the POST method and body.
+ # per_page max is 60 here, not 150 — Intercom rejects larger values
+ # with `parameter_invalid: Per Page is too big`.
+ name="companies",
+ path="/companies/list",
+ data_selector="data",
+ paginator_kind="next_url",
+ method="POST",
+ page_size=60,
+ ),
+ "contacts": IntercomEndpointConfig(
+ name="contacts",
+ path="/contacts/search",
+ data_selector="data",
+ paginator_kind="search",
+ method="POST",
+ partition_key="created_at",
+ ),
+ "conversations": IntercomEndpointConfig(
+ name="conversations",
+ path="/conversations/search",
+ data_selector="conversations",
+ paginator_kind="search",
+ method="POST",
+ partition_key="created_at",
+ ),
+ "tickets": IntercomEndpointConfig(
+ # `POST /tickets/search` mirrors contacts/conversations: it accepts
+ # the same `{"field":"updated_at","operator":">","value":<ts>}` body
+ # filter and the same cursor pagination shape.
+ name="tickets",
+ path="/tickets/search",
+ data_selector="tickets",
+ paginator_kind="search",
+ method="POST",
+ partition_key="created_at",
+ ),
+ "articles": IntercomEndpointConfig(
+ name="articles",
+ path="/articles",
+ data_selector="data",
+ paginator_kind="next_url",
+ ),
+ "activity_logs": IntercomEndpointConfig(
+ # `GET /admins/activity_logs?created_at_after=<unix_ts>` is honored
+ # server-side (verified with future-date probe). The endpoint sorts
+ # descending by `created_at` and ignores any `?sort=` param, so
+ # SourceResponse declares `sort_mode="desc"` to match.
+ name="activity_logs",
+ path="/admins/activity_logs",
+ data_selector="activity_logs",
+ paginator_kind="next_url",
+ partition_key="created_at",
+ sort_mode="desc",
+ incremental_query_param="created_at_after",
+ ),
+ "company_attributes": IntercomEndpointConfig(
+ # `GET /data_attributes?model=company` — built-in plus custom
+ # company-level attributes. No `id`/timestamp on rows; primary key
+ # is `name` (unique within a model).
+ name="company_attributes",
+ path="/data_attributes",
+ data_selector="data",
+ paginator_kind="single",
+ primary_keys=["name"],
+ partition_key="name",
+ partition_mode="md5",
+ partition_format=None,
+ extra_params={"model": "company"},
+ ),
+ "contact_attributes": IntercomEndpointConfig(
+ name="contact_attributes",
+ path="/data_attributes",
+ data_selector="data",
+ paginator_kind="single",
+ primary_keys=["name"],
+ partition_key="name",
+ partition_mode="md5",
+ partition_format=None,
+ extra_params={"model": "contact"},
+ ),
+ "conversation_parts": IntercomEndpointConfig(
+ # Substream of `conversations`: walk the same `POST /conversations/search`
+ # query (so the parent's `updated_at >` filter is server-honored), then
+ # fetch `GET /conversations/{id}` for each parent and yield each part.
+ # Effectively real-incremental — only conversations whose `updated_at`
+ # advanced are refetched. Each yielded part carries `conversation_id`.
+ name="conversation_parts",
+ path="",
+ data_selector="",
+ paginator_kind="substream",
+ parent_endpoint="conversations",
+ partition_key="created_at",
+ ),
+ "company_segments": IntercomEndpointConfig(
+ # Substream of `companies`. Intercom doesn't expose a server-side
+ # filter on either parent or child, so this is full-refresh (matches
+ # the new "fake incremental → full refresh" rule). Each yielded
+ # segment carries `company_id`.
+ name="company_segments",
+ path="",
+ data_selector="",
+ paginator_kind="substream",
+ parent_endpoint="companies",
+ primary_keys=["company_id", "id"],
+ partition_key="id",
+ partition_mode="md5",
+ partition_format=None,
+ ),
+}
+
+ENDPOINTS = tuple(INTERCOM_ENDPOINTS.keys())
+
+
+# Endpoints that support incremental sync via a server-honored filter on the
+# request itself — verified empirically against the live API:
+# - contacts/conversations/tickets: POST /<resource>/search accepts
+# `{"field":"updated_at","operator":">","value":<unix_ts>}` in the body.
+# - activity_logs: GET /admins/activity_logs?created_at_after=<unix_ts>.
+# - conversation_parts: child of conversations; the parent's `updated_at >`
+# filter is server-honored, so parents whose timestamp didn't advance
+# aren't refetched.
+#
+# Companies, segments, and company_segments are intentionally excluded: their
+# list endpoints don't accept a timestamp filter, and a "client-side cursor"
+# that walks every page each run is identical in API cost to a full refresh.
+#
+# `field_type=Integer` because Intercom returns Unix epoch seconds, not ISO.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "contacts": [
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.Integer,
+ }
+ ],
+ "conversations": [
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.Integer,
+ }
+ ],
+ "tickets": [
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.Integer,
+ }
+ ],
+ "activity_logs": [
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.Integer,
+ }
+ ],
+ "conversation_parts": [
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.Integer,
+ }
+ ],
+}
diff --git a/posthog/temporal/data_imports/sources/intercom/source.py b/posthog/temporal/data_imports/sources/intercom/source.py
index 1f7e608f7b79..3b59dffabbe8 100644
--- a/posthog/temporal/data_imports/sources/intercom/source.py
+++ b/posthog/temporal/data_imports/sources/intercom/source.py
@@ -2,28 +2,111 @@ from typing import cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldOauthConfig,
)
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.sources.common.mixins import OAuthMixin
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import IntercomSourceConfig
+from posthog.temporal.data_imports.sources.intercom.intercom import (
+ intercom_source,
+ validate_credentials as validate_intercom_credentials,
+)
+from posthog.temporal.data_imports.sources.intercom.settings import INCREMENTAL_FIELDS, INTERCOM_ENDPOINTS
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class IntercomSource(SimpleSource[IntercomSourceConfig]):
+class IntercomSource(SimpleSource[IntercomSourceConfig], OAuthMixin):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.INTERCOM
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your Intercom connection is invalid or expired. Please reconnect it.",
+ "403 Client Error": "Your Intercom connection is missing required scopes. Please update permissions and reconnect.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.INTERCOM,
- label="Intercom",
+ caption="Select an existing Intercom workspace to link to PostHog or create a new connection",
iconPath="/static/services/intercom.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/intercom",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldOauthConfig(
+ name="intercom_integration_id",
+ label="Intercom workspace",
+ required=True,
+ kind="intercom",
+ ),
+ ],
+ ),
+ featureFlag="dwh_intercom",
+ releaseStatus=ReleaseStatus.ALPHA,
+ )
+
+ def get_schemas(
+ self,
+ config: IntercomSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ ) -> list[SourceSchema]:
+ schemas = []
+ for endpoint_config in INTERCOM_ENDPOINTS.values():
+ incremental_fields = INCREMENTAL_FIELDS.get(endpoint_config.name, [])
+ supports_incremental = bool(incremental_fields)
+ schemas.append(
+ SourceSchema(
+ name=endpoint_config.name,
+ supports_incremental=supports_incremental,
+ supports_append=supports_incremental,
+ incremental_fields=incremental_fields,
+ )
+ )
+ 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: IntercomSourceConfig, team_id: int, schema_name: str | None = None
+ ) -> tuple[bool, str | None]:
+ try:
+ integration = self.get_oauth_integration(config.intercom_integration_id, team_id)
+ except ValueError as e:
+ return False, str(e)
+
+ if not integration.access_token:
+ return False, "Intercom integration has no access token. Please reconnect."
+
+ return validate_intercom_credentials(integration.access_token, schema_name=schema_name)
+
+ def source_for_pipeline(self, config: IntercomSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ integration = self.get_oauth_integration(config.intercom_integration_id, inputs.team_id)
+
+ if not integration.access_token:
+ raise ValueError(f"Intercom access token not found for job {inputs.job_id}")
+
+ return intercom_source(
+ access_token=integration.access_token,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ incremental_field=inputs.incremental_field if inputs.should_use_incremental_field else None,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)