: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 heyreach import source (#107255)
Tom Owers2acc599d68f8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 20df2d6a9593..26bc99498e72 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -359,6 +359,7 @@ the row lists both.| heroku | HTTP | requests | ✅ || hetzner | HTTP | requests | ✅ || hex | HTTP | requests + `rest_source.RESTClient` | ✅ |+| heyreach | HTTP | requests + `rest_source.RESTClient` | ✅ || hibob | HTTP | requests | ✅ || hightouch | HTTP | requests + `rest_source.RESTClient` | ✅ || hitpay | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -1119,7 +1120,6 @@ doesn't conflict with concurrent PRs.- heap- hetzner- heygen-- heyreach- hibob- high_level- hivebritediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/heyreach.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/heyreach.pyindex 87eaf002ac53..243d63e40a0d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/heyreach.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/heyreach.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass HeyReachSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/heyreach/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/heyreach/canonical_descriptions.pynew file mode 100644index 000000000000..c088de2e3777--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/heyreach/canonical_descriptions.py@@ -0,0 +1,128 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_API_DOCS_URL = "https://documenter.getpostman.com/view/23808049/2sA2xb5F75"++_LEAD_PROFILE_COLUMNS = {+ "profileUrl": "URL of the lead's LinkedIn profile.",+ "firstName": "The lead's first name.",+ "lastName": "The lead's last name.",+ "headline": "The lead's LinkedIn headline.",+ "location": "The lead's location, as shown on LinkedIn.",+ "companyName": "Name of the company the lead works at.",+ "companyUrl": "URL of the company's LinkedIn page.",+ "position": "The lead's job title at their current company.",+ "connections": "Number of LinkedIn connections the lead has.",+ "followers": "Number of LinkedIn followers the lead has.",+ "emailAddress": "The lead's email address, when known.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "campaigns": {+ "description": "An outreach campaign: a sequence of LinkedIn actions sent to a list of leads from one or more sender accounts.",+ "docs_url": _API_DOCS_URL,+ "columns": {+ "id": "Unique identifier for the campaign.",+ "name": "Name of the campaign.",+ "creationTime": "When the campaign was created.",+ "status": "Campaign status (DRAFT, IN_PROGRESS, PAUSED, FINISHED, CANCELED, FAILED, STARTING).",+ "campaignAccountIds": "Identifiers of the LinkedIn sender accounts attached to the campaign.",+ "linkedInUserListId": "Identifier of the lead list the campaign targets.",+ "linkedInUserListName": "Name of the lead list the campaign targets.",+ "progressStats": "Counts of leads by progress state (total, in progress, pending, finished, failed).",+ },+ },+ "campaign_leads": {+ "description": "A lead enrolled in a campaign, with their progress through the sequence and connection/message outcomes.",+ "docs_url": _API_DOCS_URL,+ "columns": {+ "id": "Unique identifier for the lead's enrollment in the campaign.",+ "campaignId": "Identifier of the campaign the lead is enrolled in.",+ "linkedInUserProfile": "The lead's LinkedIn profile (name, headline, company, profile URL).",+ "creationTime": "When the lead was added to the campaign.",+ "lastActionTime": "When the campaign last executed an action for this lead.",+ "failedTime": "When the lead failed in the sequence, when applicable.",+ "leadCampaignStatus": "Progress through the sequence (Pending, InSequence, Finished, Paused, Failed).",+ "leadConnectionStatus": "Connection outcome (None, ConnectionSent, ConnectionAccepted).",+ "leadMessageStatus": "Messaging outcome (None, MessageSent, MessageReply).",+ "linkedInSenderId": "Identifier of the LinkedIn sender account working this lead.",+ "linkedInSenderFullName": "Full name of the LinkedIn sender account working this lead.",+ },+ },+ "conversations": {+ "description": "A LinkedIn inbox conversation between one of your sender accounts and a correspondent, including recent messages.",+ "docs_url": _API_DOCS_URL,+ "columns": {+ "id": "LinkedIn thread identifier for the conversation.",+ "linkedInAccountId": "Identifier of the sender account that owns the conversation.",+ "read": "Whether the conversation has been read.",+ "groupChat": "Whether the conversation is a group chat.",+ "lastMessageAt": "When the last message in the conversation was sent.",+ "lastMessageText": "Text of the last message in the conversation.",+ "lastMessageSender": "Who sent the last message (ME or the correspondent).",+ "totalMessages": "Number of messages in the conversation.",+ "campaignId": "Identifier of the campaign the conversation originated from, when applicable.",+ "correspondentProfile": "LinkedIn profile of the other participant.",+ "messages": "Messages in the conversation, each with a timestamp, body, and sender.",+ },+ },+ "linkedin_accounts": {+ "description": "A LinkedIn sender account connected to HeyReach, with its auth state and daily action limits.",+ "docs_url": _API_DOCS_URL,+ "columns": {+ "id": "Unique identifier for the LinkedIn account.",+ "emailAddress": "Email address the LinkedIn account signs in with.",+ "firstName": "First name on the LinkedIn account.",+ "lastName": "Last name on the LinkedIn account.",+ "isActive": "Whether the account is active in HeyReach.",+ "activeCampaigns": "Number of campaigns the account is currently sending for.",+ "authIsValid": "Whether the account's LinkedIn session is still valid.",+ "profileUrl": "URL of the account's LinkedIn profile.",+ "accountLimits": "Daily limits for connection requests, messages, InMails, profile views, and other actions.",+ },+ },+ "lists": {+ "description": "A lead or company list used to target campaigns.",+ "docs_url": _API_DOCS_URL,+ "columns": {+ "id": "Unique identifier for the list.",+ "name": "Name of the list.",+ "listType": "Whether the list holds leads (USER_LIST) or companies (COMPANY_LIST).",+ "totalItemsCount": "Number of items in the list.",+ "creationTime": "When the list was created.",+ "campaignIds": "Identifiers of the campaigns using the list.",+ },+ },+ "list_leads": {+ "description": "A lead belonging to a lead list, with their LinkedIn profile details.",+ "docs_url": _API_DOCS_URL,+ "columns": {+ "listId": "Identifier of the list the lead belongs to.",+ **_LEAD_PROFILE_COLUMNS,+ "tags": "Tags applied to the lead.",+ "customFields": "Custom fields set on the lead.",+ },+ },+ "overall_stats": {+ "description": "Daily outreach totals across all sender accounts and campaigns.",+ "docs_url": _API_DOCS_URL,+ "columns": {+ "date": "Day the stats cover.",+ "profileViews": "Profile views performed that day.",+ "postLikes": "Post likes performed that day.",+ "follows": "Follows performed that day.",+ "messagesSent": "Messages sent that day.",+ "totalMessageStarted": "Message threads started that day.",+ "totalMessageReplies": "Replies received to messages that day.",+ "inmailMessagesSent": "InMail messages sent that day.",+ "totalInmailStarted": "InMail threads started that day.",+ "totalInmailReplies": "Replies received to InMails that day.",+ "connectionsSent": "Connection requests sent that day.",+ "connectionsAccepted": "Connection requests accepted that day.",+ "messageReplyRate": "Replies received divided by message threads started.",+ "inMailReplyRate": "InMail replies received divided by InMail threads started.",+ "connectionAcceptanceRate": "Connections accepted divided by connection requests sent.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/heyreach/heyreach.py b/products/warehouse_sources/backend/temporal/data_imports/sources/heyreach/heyreach.pynew file mode 100644index 000000000000..7f2ce238ed21--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/heyreach/heyreach.py@@ -0,0 +1,255 @@+from collections.abc import Callable, Iterable, Iterator+from datetime import UTC, datetime+from functools import partial+from typing import Any, Optional++from dateutil import parser++from posthog.dataclasses import frozen++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.auth import APIKeyAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ OffsetPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.heyreach.settings import (+ ENDPOINTS,+ HEYREACH_BASE_URL,+ PAGE_SIZE,+ REQUEST_TIMEOUT_SECONDS,+ HeyReachEndpointConfig,+)++# HeyReach launched in 2021, so this start date covers every account's full stats history.+STATS_START_DATE = "2020-01-01T00:00:00.000Z"++AUTH_HEADER = "X-API-KEY"+++@frozen+class HeyReachResumeConfig:+ offset: int+++def _offset_paginator() -> OffsetPaginator:+ # Every HeyReach list endpoint is POST with `offset`/`limit` in the JSON body and a+ # `{"totalCount": n, "items": [...]}` envelope.+ return OffsetPaginator(+ limit=PAGE_SIZE,+ offset_param="offset",+ limit_param="limit",+ total_path="totalCount",+ param_location="json",+ )+++def _make_client(api_key: str) -> RESTClient:+ return RESTClient(+ base_url=HEYREACH_BASE_URL,+ auth=APIKeyAuth(api_key=api_key, name=AUTH_HEADER, location="header"),+ request_timeout=REQUEST_TIMEOUT_SECONDS,+ # Pin every request to HEYREACH_BASE_URL's host and refuse redirects: the API key+ # rides a custom header, so a spoofed pagination target or a cross-origin 3xx must+ # not carry that credential off-host (SSRF).+ allowed_hosts=[],+ allow_redirects=False,+ # HeyReach responses carry raw LinkedIn outreach content (inbox messages, lead+ # custom fields) that a generic scrubber can't redact, so keep it out of the shared+ # HTTP sample bucket. Requests stay metered and logged.+ capture=False,+ )+++def _rest_config(api_key: str, endpoint_config: HeyReachEndpointConfig) -> RESTAPIConfig:+ return {+ "client": {+ "base_url": HEYREACH_BASE_URL,+ "request_timeout": REQUEST_TIMEOUT_SECONDS,+ "auth": {+ "type": "api_key",+ "name": AUTH_HEADER,+ "api_key": api_key,+ "location": "header",+ },+ "paginator": _offset_paginator(),+ # Same SSRF pinning as _make_client: the API key rides a header, so pagination+ # can't be redirected off-host.+ "allowed_hosts": [],+ "allow_redirects": False,+ # Same sample-capture exclusion as _make_client: these endpoints return the same+ # raw LinkedIn outreach content.+ "capture": False,+ },+ "resource_defaults": {},+ "resources": [+ {+ "name": endpoint_config.name,+ "table_name": endpoint_config.name,+ "write_disposition": "replace",+ "endpoint": {+ "method": "POST",+ "path": endpoint_config.path,+ "json": dict(endpoint_config.request_body),+ "data_selector": "items",+ },+ "table_format": "delta",+ }+ ],+ }+++def _top_level_rows(+ api_key: str,+ endpoint_config: HeyReachEndpointConfig,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[HeyReachResumeConfig],+):+ 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 = {"offset": resume_config.offset}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state and state.get("offset"):+ resumable_source_manager.save_state(HeyReachResumeConfig(offset=int(state["offset"])))++ return rest_api_resource(+ _rest_config(api_key, endpoint_config),+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+++def _fanout_rows(api_key: str, endpoint_config: HeyReachEndpointConfig) -> Iterator[list[dict[str, Any]]]:+ fanout = endpoint_config.fanout+ assert fanout is not None+ parent_config = ENDPOINTS[fanout.parent]+ client = _make_client(api_key)++ for parent_page in client.paginate(+ path=parent_config.path,+ method="post",+ json={**parent_config.request_body, **fanout.parent_body},+ paginator=_offset_paginator(),+ data_selector="items",+ ):+ for parent_row in parent_page:+ parent_id = parent_row.get("id")+ if parent_id is None:+ continue+ for child_page in client.paginate(+ path=endpoint_config.path,+ method="post",+ json={**endpoint_config.request_body, fanout.body_param: parent_id},+ paginator=_offset_paginator(),+ data_selector="items",+ ):+ # An API-provided field of the same name wins over the injected parent id.+ rows = [{fanout.body_param: parent_id, **row} for row in child_page]+ if rows:+ yield rows+++def _overall_stats_rows(api_key: str, endpoint_config: HeyReachEndpointConfig) -> Iterator[list[dict[str, Any]]]:+ client = _make_client(api_key)+ body = {+ # Empty arrays mean "all senders" / "all campaigns".+ "accountIds": [],+ "campaignIds": [],+ "startDate": STATS_START_DATE,+ "endDate": datetime.now(tz=UTC).isoformat(),+ }+ # The endpoint returns everything in one response; the selector resolves the day-keyed+ # `byDayStats` object, which paginate wraps as a single-element page.+ for page in client.paginate(+ path=endpoint_config.path,+ method="post",+ json=body,+ data_selector="byDayStats",+ ):+ for by_day in page:+ rows = [{"date": parser.parse(day), **(stats or {})} for day, stats in (by_day or {}).items()]+ if rows:+ yield rows+++def _build_response(endpoint_config: HeyReachEndpointConfig, items: Callable[[], Iterable[Any]]) -> SourceResponse:+ return SourceResponse(+ name=endpoint_config.name,+ items=items,+ primary_keys=list(endpoint_config.primary_keys),+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )+++def heyreach_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[HeyReachResumeConfig],+) -> SourceResponse:+ endpoint_config = ENDPOINTS.get(endpoint)+ if endpoint_config is None:+ raise ValueError(f"HeyReach endpoint does not exist: {endpoint}")++ if endpoint_config.daily_stats:+ return _build_response(endpoint_config, partial(_overall_stats_rows, api_key, endpoint_config))++ if endpoint_config.fanout is not None:+ # Fan-out runs restart from the first parent on resume: the parent set can change+ # between attempts, so an offset into it is not a stable cursor.+ return _build_response(endpoint_config, partial(_fanout_rows, api_key, endpoint_config))++ resource = _top_level_rows(api_key, endpoint_config, team_id, job_id, resumable_source_manager)+ return _build_response(endpoint_config, lambda: resource)+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ # A non-ASCII key can't be encoded into the request header (requests uses latin-1),+ # which would otherwise surface a raw UnicodeEncodeError to the user.+ if not api_key.isascii():+ return (+ False,+ "Your HeyReach API key contains an unsupported character (for example an invisible one "+ "pasted from another app). Retype it by hand and try again.",+ )++ # allow_redirects=False: the key rides a custom header, which requests would replay to a+ # cross-origin redirect target.+ is_valid, status = validate_via_probe(+ lambda: make_tracked_session(headers={AUTH_HEADER: api_key}, redact_values=(api_key,)),+ f"{HEYREACH_BASE_URL}/auth/CheckApiKey",+ timeout=REQUEST_TIMEOUT_SECONDS,+ allow_redirects=False,+ )++ if is_valid:+ return True, None+ if status in (401, 403):+ return (+ False,+ "HeyReach rejected the API key. Create a new key in HeyReach under "+ "Settings > Integrations > HeyReach API and try again.",+ )+ if status is None:+ return False, "Couldn't reach HeyReach to check the API key. Try again in a few minutes."+ return (+ False,+ f"HeyReach returned an unexpected status ({status}) while checking the API key. Try again in a few minutes.",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/heyreach/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/heyreach/settings.pynew file mode 100644index 000000000000..dfb336e7fe2d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/heyreach/settings.py@@ -0,0 +1,100 @@+from dataclasses import field+from typing import Any++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.types import IncrementalField++HEYREACH_BASE_URL = "https://api.heyreach.io/api/public"+# Documented maximum page size for the paginated list endpoints.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+++@frozen+class HeyReachFanoutConfig:+ """Per-parent child endpoint.++ HeyReach child endpoints take the parent id in the POST body, and the shared declarative+ fan-out only resolves path params, so these endpoints run through a hand-rolled iterator.+ """++ # Endpoint name of the parent listing; the parent row's `id` is bound into child requests.+ parent: str+ # Body key carrying the parent id on child requests; also the column injected into child rows,+ # since the API does not echo the parent id back.+ body_param: str+ parent_body: dict[str, Any] = field(default_factory=dict)+++@frozen+class HeyReachEndpointConfig:+ name: str+ path: str+ primary_keys: list[str]+ partition_key: str | None = None+ request_body: dict[str, Any] = field(default_factory=dict)+ fanout: HeyReachFanoutConfig | None = None+ # The endpoint returns one `byDayStats` object instead of the paginated `items` envelope,+ # and is reshaped into one row per day.+ daily_stats: bool = False+++ENDPOINTS: dict[str, HeyReachEndpointConfig] = {+ "campaigns": HeyReachEndpointConfig(+ name="campaigns",+ path="/campaign/GetAll",+ primary_keys=["id"],+ partition_key="creationTime",+ ),+ "campaign_leads": HeyReachEndpointConfig(+ name="campaign_leads",+ path="/campaign/GetLeadsFromCampaign",+ # Lead-in-campaign ids look globally unique, but the API does not document that,+ # so the campaign id stays in the key.+ primary_keys=["campaignId", "id"],+ partition_key="creationTime",+ fanout=HeyReachFanoutConfig(parent="campaigns", body_param="campaignId"),+ ),+ "conversations": HeyReachEndpointConfig(+ name="conversations",+ path="/inbox/GetConversationsV2",+ # Conversation ids are LinkedIn thread ids; scope them by the owning sender account.+ primary_keys=["linkedInAccountId", "id"],+ request_body={"filters": {}},+ ),+ "linkedin_accounts": HeyReachEndpointConfig(+ name="linkedin_accounts",+ path="/li_account/GetAll",+ primary_keys=["id"],+ ),+ "lists": HeyReachEndpointConfig(+ name="lists",+ path="/list/GetAll",+ primary_keys=["id"],+ partition_key="creationTime",+ ),+ "list_leads": HeyReachEndpointConfig(+ name="list_leads",+ path="/list/GetLeadsFromList",+ # Leads carry no numeric id; the LinkedIn profile URL is their identity.+ primary_keys=["listId", "profileUrl"],+ fanout=HeyReachFanoutConfig(+ parent="lists",+ body_param="listId",+ # Company lists serve companies through a different endpoint (GetCompaniesFromList),+ # so only lead lists are fanned out.+ parent_body={"listType": "USER_LIST"},+ ),+ ),+ "overall_stats": HeyReachEndpointConfig(+ name="overall_stats",+ path="/stats/GetOverallStats",+ primary_keys=["date"],+ daily_stats=True,+ ),+}++# No list endpoint accepts a created-after filter we could verify server-side,+# so every endpoint is full refresh.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/heyreach/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/heyreach/source.pyindex caa266591654..28ef316dce2a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/heyreach/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/heyreach/source.py@@ -1,28 +1,129 @@-from typing import cast+from typing import Optional, cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.heyreach import (HeyReachSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.heyreach.heyreach import (+ HeyReachResumeConfig,+ heyreach_source,+ validate_credentials as validate_heyreach_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.heyreach.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class HeyReachSource(SimpleSource[HeyReachSourceConfig]):+class HeyReachSource(ResumableSource[HeyReachSourceConfig, HeyReachResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog, safe for public docs+ api_docs_url = "https://documenter.getpostman.com/view/23808049/2sA2xb5F75"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.HEYREACH+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.heyreach.io": (+ "HeyReach rejected the API key. Create a new key in HeyReach under "+ "Settings > Integrations > HeyReach API and update this source."+ ),+ "403 Client Error: Forbidden for url: https://api.heyreach.io": (+ "Your HeyReach API key does not have access to this data. Create a new key in "+ "HeyReach under Settings > Integrations > HeyReach API and update this source."+ ),+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.heyreach.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: HeyReachSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: HeyReachSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_heyreach_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HeyReachResumeConfig]:+ return ResumableSourceManager[HeyReachResumeConfig](inputs, HeyReachResumeConfig)++ def source_for_pipeline(+ self,+ config: HeyReachSourceConfig,+ resumable_source_manager: ResumableSourceManager[HeyReachResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return heyreach_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,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=ExternalDataSourceType.HEYREACH,category=DataWarehouseSourceCategory.SALES,label="HeyReach",+ caption=(+ "Import campaigns, leads, LinkedIn sender accounts, inbox conversations, and daily "+ "outreach stats from HeyReach. Create an API key in HeyReach under "+ "Settings > Integrations > HeyReach API."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/heyreach",iconPath="/static/services/heyreach.png",keywords=["linkedin outreach", "sales engagement", "heyreach"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/heyreach/tests/test_heyreach.py b/products/warehouse_sources/backend/temporal/data_imports/sources/heyreach/tests/test_heyreach.pynew file mode 100644index 000000000000..0b3f8e19a36d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/heyreach/tests/test_heyreach.py@@ -0,0 +1,250 @@+import json+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++import requests+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.heyreach.heyreach import (+ STATS_START_DATE,+ HeyReachResumeConfig,+ heyreach_source,+ validate_credentials,+)++_REST_CLIENT_SESSION = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client"+ ".make_tracked_session"+)+_HEYREACH_SESSION = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.heyreach.heyreach.make_tracked_session"+)+++def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ return resp+++def _drive(+ endpoint: str, manager: MagicMock, responses: list[Response]+) -> tuple[list[tuple[str, dict[str, Any]]], list[Any]]:+ # Returns (sent, batches) where sent is a list of (url, json_body) captured at send time.+ # The Request object is mutated in place by the paginator between pages, so bodies are+ # copied per send instead of read back from call_args_list.+ sent: list[tuple[str, dict[str, Any]]] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent.append((request.url, dict(request.json or {})))+ return next(response_iter)++ with patch(_REST_CLIENT_SESSION) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ response = heyreach_source(+ api_key="test-key",+ endpoint=endpoint,+ team_id=1,+ job_id="test_job",+ resumable_source_manager=manager,+ )+ batches = list(cast(Iterable[Any], response.items()))+ return sent, batches+++def _fresh_manager(can_resume: bool = False) -> MagicMock:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = can_resume+ return manager+++class TestTopLevelEndpoints:+ def test_fresh_run_pages_by_total_count_and_saves_offsets(self) -> None:+ manager = _fresh_manager()+ responses = [+ _make_http_response({"totalCount": 150, "items": [{"id": i} for i in range(100)]}),+ _make_http_response({"totalCount": 150, "items": [{"id": i} for i in range(100, 150)]}),+ ]++ sent, _ = _drive("campaigns", manager, responses)++ assert [body.get("offset") for _, body in sent] == [0, 100]+ assert all(body.get("limit") == 100 for _, body in sent)+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [HeyReachResumeConfig(offset=100)]++ def test_resume_seeds_paginator_with_saved_offset(self) -> None:+ manager = _fresh_manager(can_resume=True)+ manager.load_state.return_value = HeyReachResumeConfig(offset=100)+ responses = [+ _make_http_response({"totalCount": 101, "items": [{"id": 100}]}),+ ]++ sent, _ = _drive("campaigns", manager, responses)++ assert [body.get("offset") for _, body in sent] == [100]+ manager.load_state.assert_called_once()++ def test_conversations_request_carries_required_filters_object(self) -> None:+ # GetConversationsV2 rejects requests without a `filters` object in the body.+ manager = _fresh_manager()+ responses = [+ _make_http_response({"totalCount": 1, "items": [{"id": "thread-1", "linkedInAccountId": 7}]}),+ ]++ sent, _ = _drive("conversations", manager, responses)++ url, body = sent[0]+ assert url.endswith("/inbox/GetConversationsV2")+ assert body["filters"] == {}+ assert body["offset"] == 0+++class TestFanoutEndpoints:+ def test_campaign_leads_fans_out_per_campaign_and_injects_campaign_id(self) -> None:+ responses = [+ _make_http_response({"totalCount": 2, "items": [{"id": 1}, {"id": 2}]}),+ _make_http_response({"totalCount": 1, "items": [{"id": 11, "leadCampaignStatus": "Finished"}]}),+ _make_http_response({"totalCount": 1, "items": [{"id": 21, "leadCampaignStatus": "Pending"}]}),+ ]++ sent, batches = _drive("campaign_leads", _fresh_manager(), responses)++ paths = [url.split("/api/public")[1] for url, _ in sent]+ assert paths == [+ "/campaign/GetAll",+ "/campaign/GetLeadsFromCampaign",+ "/campaign/GetLeadsFromCampaign",+ ]+ assert [body.get("campaignId") for _, body in sent[1:]] == [1, 2]+ assert all(body.get("offset") == 0 and body.get("limit") == 100 for _, body in sent)++ rows = [row for batch in batches for row in batch]+ assert rows == [+ {"campaignId": 1, "id": 11, "leadCampaignStatus": "Finished"},+ {"campaignId": 2, "id": 21, "leadCampaignStatus": "Pending"},+ ]++ def test_list_leads_only_fans_out_lead_lists_and_skips_parents_without_id(self) -> None:+ responses = [+ _make_http_response({"totalCount": 2, "items": [{"id": 5}, {"name": "row without id"}]}),+ _make_http_response({"totalCount": 0, "items": []}),+ ]++ sent, batches = _drive("list_leads", _fresh_manager(), responses)++ parent_url, parent_body = sent[0]+ assert parent_url.endswith("/list/GetAll")+ # Company lists serve companies via a different endpoint, so the parent listing is+ # restricted to lead lists.+ assert parent_body["listType"] == "USER_LIST"+ # Only the parent with an id produces a child request, and an empty child page yields no batch.+ assert len(sent) == 2+ assert sent[1][1]["listId"] == 5+ assert batches == []+++class TestOverallStats:+ @pytest.mark.parametrize(+ ("payload", "expected_days"),+ [+ (+ {+ "byDayStats": {+ "2024-12-17T00:00:00Z": {"messagesSent": 5, "connectionsSent": 10},+ "2024-12-18T00:00:00Z": {"messagesSent": 2, "connectionsSent": 0},+ },+ "overallStats": {"messagesSent": 7},+ },+ 2,+ ),+ ({"overallStats": {"messagesSent": 7}}, 0),+ ({"byDayStats": None}, 0),+ ],+ )+ def test_yields_one_row_per_day(self, payload: dict[str, Any], expected_days: int) -> None:+ responses = [_make_http_response(payload)]++ sent, batches = _drive("overall_stats", _fresh_manager(), responses)+ rows = [row for batch in batches for row in batch]++ assert len(rows) == expected_days+ if rows:+ assert rows[0]["messagesSent"] == 5+ assert rows[0]["date"].isoformat() == "2024-12-17T00:00:00+00:00"++ url, body = sent[0]+ assert url.endswith("/stats/GetOverallStats")+ assert body["startDate"] == STATS_START_DATE+ assert body["accountIds"] == []+ assert body["campaignIds"] == []+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ ("status_code", "expected_valid", "expected_fragment"),+ [+ (200, True, None),+ (401, False, "HeyReach rejected the API key"),+ (403, False, "HeyReach rejected the API key"),+ (500, False, "unexpected status (500)"),+ ],+ )+ def test_maps_status_to_user_message(+ self, status_code: int, expected_valid: bool, expected_fragment: str | None+ ) -> None:+ with patch(_HEYREACH_SESSION) as MockSession:+ mock_session = MockSession.return_value+ mock_session.get.return_value = _make_http_response({}, status_code=status_code)++ valid, message = validate_credentials("test-key")++ assert valid is expected_valid+ if expected_fragment is None:+ assert message is None+ else:+ assert expected_fragment in (message or "")++ def test_transport_error_reports_unreachable_instead_of_raising(self) -> None:+ # A DNS failure or timeout during the probe must not raise out of validate_credentials+ # and fail source creation with a stack trace.+ with patch(_HEYREACH_SESSION) as MockSession:+ MockSession.return_value.get.side_effect = requests.ConnectionError("dns failure")++ valid, message = validate_credentials("test-key")++ assert valid is False+ assert "Couldn't reach HeyReach" in (message or "")++ def test_non_ascii_key_fails_without_a_request(self) -> None:+ # A non-latin-1 key can't be encoded into the X-API-KEY header; the raw+ # UnicodeEncodeError must never surface to the user.+ with patch(_HEYREACH_SESSION) as MockSession:+ valid, message = validate_credentials("bad中key")++ assert valid is False+ assert "Retype it by hand" in (message or "")+ MockSession.assert_not_called()+++class TestUnknownEndpoint:+ def test_unknown_endpoint_raises(self) -> None:+ with pytest.raises(ValueError, match="HeyReach endpoint does not exist"):+ heyreach_source(+ api_key="test-key",+ endpoint="does_not_exist",+ team_id=1,+ job_id="test_job",+ resumable_source_manager=_fresh_manager(),+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/heyreach/tests/test_heyreach_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/heyreach/tests/test_heyreach_source.pynew file mode 100644index 000000000000..ea82b89258f8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/heyreach/tests/test_heyreach_source.py@@ -0,0 +1,37 @@+import pytest++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.heyreach.source import HeyReachSource+++class TestHeyReachSourceErrorClassification:+ @pytest.mark.parametrize(+ ("status_code", "reason"),+ [+ (401, "Unauthorized"),+ (403, "Forbidden"),+ ],+ )+ def test_auth_http_errors_match_a_non_retryable_pattern(self, status_code: int, reason: str) -> None:+ # Verifies the raise_for_status message shape the patterns rely on, so a requests+ # formatting change or a wrong pattern prefix surfaces here instead of as an+ # endlessly retrying job.+ mock_response = requests.Response()+ mock_response.status_code = status_code+ mock_response.url = "https://api.heyreach.io/api/public/campaign/GetAll"+ mock_response.reason = reason++ with pytest.raises(requests.HTTPError) as exc_info:+ mock_response.raise_for_status()++ non_retryable_errors = HeyReachSource().get_non_retryable_errors()+ assert any(pattern in str(exc_info.value) for pattern in non_retryable_errors)++ def test_transient_server_errors_stay_retryable(self) -> None:+ error_message = (+ "500 Server Error: Internal Server Error for url: https://api.heyreach.io/api/public/campaign/GetAll"+ )++ non_retryable_errors = HeyReachSource().get_non_retryable_errors()+ assert not any(pattern in error_message for pattern in non_retryable_errors)