: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
from collections.abc import Callable, Iterable, Iterator
from datetime import UTC, datetime, timedelta
from functools import partial
from typing import Any, Optional
from dateutil import parser
from products.warehouse_sources.sources.heyreach.settings import (
ENDPOINTS,
HEYREACH_BASE_URL,
PAGE_SIZE,
REQUEST_TIMEOUT_SECONDS,
HeyReachEndpointConfig,
HeyReachFanoutConfig,
)
from products.warehouse_sources.sources.sdk import (
APIKeyAuth,
BasePaginator,
OffsetPaginator,
PageNumberPaginator,
RESTAPIConfig,
RESTClient,
ResumableSourceManager,
SourceResponse,
frozen,
make_tracked_session,
rest_api_resource,
validate_via_probe,
)
# 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"
STATS_BATCH_SIZE = 1000
@frozen
class HeyReachResumeConfig:
offset: int
@frozen
class StatsWindow:
start_date: str
end_date: str
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 _child_paginator(endpoint_config: HeyReachEndpointConfig) -> BasePaginator:
if endpoint_config.page_number_pagination:
# The response carries a row count, not a page count, so paging stops at the first empty page.
return PageNumberPaginator(base_page=0, page_param="pageNumber", param_location="json")
return _offset_paginator()
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 _parent_ids(client: RESTClient, fanout: HeyReachFanoutConfig) -> Iterator[Any]:
parent_config = ENDPOINTS[fanout.parent]
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 not None:
yield parent_id
def _fanout_rows(api_key: str, endpoint_config: HeyReachEndpointConfig) -> Iterator[list[dict[str, Any]]]:
fanout = endpoint_config.fanout
assert fanout is not None
client = _make_client(api_key)
for parent_id in _parent_ids(client, fanout):
for child_page in client.paginate(
path=endpoint_config.path,
method="post",
json={**endpoint_config.request_body, fanout.body_param: parent_id},
paginator=_child_paginator(endpoint_config),
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 _stats_windows(window_days: int | None) -> Iterator[StatsWindow]:
now = datetime.now(tz=UTC)
if window_days is None:
yield StatsWindow(start_date=STATS_START_DATE, end_date=now.isoformat())
return
start = parser.parse(STATS_START_DATE)
step = timedelta(days=window_days)
while start < now:
# endDate is inclusive, so each window stops 1 ms before the next one starts.
end = min(start + step - timedelta(milliseconds=1), now)
yield StatsWindow(
start_date=start.isoformat(timespec="milliseconds"),
end_date=end.isoformat(timespec="milliseconds"),
)
start += step
def _stats_window_rows(
client: RESTClient,
endpoint_config: HeyReachEndpointConfig,
resumable_source_manager: ResumableSourceManager[HeyReachResumeConfig],
filters: dict[str, list[Any]],
injected: dict[str, Any],
) -> Iterator[list[dict[str, Any]]]:
for window in _stats_windows(endpoint_config.stats_window_days):
body = {
# Empty arrays mean "all senders" / "all campaigns".
"accountIds": [],
"campaignIds": [],
**filters,
"startDate": window.start_date,
"endDate": window.end_date,
}
# 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: list[dict[str, Any]] = []
for day, stats in (by_day or {}).items():
date = parser.parse(day)
# The by-campaign breakdown maps each day to a list of per-campaign stats.
for entry in stats if isinstance(stats, list) else [stats]:
# The request filter is the source of truth for the injected ids, so they
# win over a field of the same name in the response.
rows.append({"date": date, **(entry or {}), **injected})
if len(rows) >= STATS_BATCH_SIZE:
yield rows
rows = []
if rows:
yield rows
# Windows before the account or sender existed return no rows; nothing is buffered or staged here.
resumable_source_manager.safe_point()
def _daily_stats_rows(
api_key: str,
endpoint_config: HeyReachEndpointConfig,
resumable_source_manager: ResumableSourceManager[HeyReachResumeConfig],
) -> Iterator[list[dict[str, Any]]]:
client = _make_client(api_key)
fanout = endpoint_config.fanout
if fanout is None:
yield from _stats_window_rows(client, endpoint_config, resumable_source_manager, {}, {})
return
# The response does not echo the filter back, so each parent id is injected into its rows.
column = fanout.row_column or fanout.body_param
for parent_id in _parent_ids(client, fanout):
yield from _stats_window_rows(
client,
endpoint_config,
resumable_source_manager,
{fanout.body_param: [parent_id]},
{column: parent_id},
)
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(_daily_stats_rows, api_key, endpoint_config, resumable_source_manager)
)
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.",
)