: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
import dataclasses
from collections.abc import Iterable
from datetime import UTC, date, datetime
from typing import Any, Optional, cast
from urllib.parse import parse_qs, urlencode, urlsplit
from requests import Request, Response
from requests.auth import HTTPBasicAuth
from products.warehouse_sources.sources.aircall.settings import AIRCALL_ENDPOINTS, PAGE_SIZE, AircallEndpointConfig
from products.warehouse_sources.sources.sdk import (
BasePaginator,
ClientConfig,
RESTAPIConfig,
ResumableSourceManager,
SinglePagePaginator,
SourceResponse,
build_dependent_resource,
make_tracked_session,
rest_api_resource,
validate_via_probe,
)
AIRCALL_BASE_URL = "https://api.aircall.io/v1"
# Aircall refuses to serve any record past the 10,000th of a single query and answers with a
# 400. It keeps advertising a `meta.next_page_link` across that boundary, so the link cannot be
# followed blindly: the offset it points at has to be range-checked first.
MAX_RECORDS_PER_QUERY = 10_000
class AircallTruncationError(Exception):
"""Raised when a capped window cannot advance, so the rest of it is unreachable.
Aircall serves at most 10,000 records per query. The paginator moves past that cap by
re-anchoring `from` on the latest cursor value seen. When every record in the filled window
shares the boundary timestamp, the cursor cannot move, the next window would repeat the same
query, and the remaining records are lost. Failing here surfaces that loss as a failed sync
instead of letting the run report success with missing data.
"""
@dataclasses.dataclass(frozen=False)
class AircallResumeConfig:
next_url: str
def _to_epoch(value: Any) -> Optional[int]:
"""Coerce an incremental cursor value to a UNIX timestamp for Aircall's `from` filter.
Aircall stores and filters timestamps as epoch seconds, so the persisted watermark is
already an int in the common case; datetimes are accepted defensively.
"""
if value is None:
return None
if isinstance(value, bool):
return None
if isinstance(value, int):
return value
if isinstance(value, float):
return int(value)
if isinstance(value, datetime):
dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
return int(dt.timestamp())
if isinstance(value, date):
return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())
try:
return int(value)
except (TypeError, ValueError):
return None
def _build_url(path: str, params: dict[str, Any]) -> str:
clean_params = {key: value for key, value in params.items() if value is not None}
if not clean_params:
return f"{AIRCALL_BASE_URL}{path}"
return f"{AIRCALL_BASE_URL}{path}?{urlencode(clean_params)}"
def _reaches_record_cap(url: str) -> bool:
"""Whether `url` asks Aircall for a record at or past the 10,000th of the current query.
Aircall's own next-page links carry `page` and `per_page`, so the offset a link starts at is
`(page - 1) * per_page`. Requesting a link whose offset lands on or past the cap returns a
400 that kills the extraction, which is why the link is range-checked instead of followed.
"""
query = parse_qs(urlsplit(url).query)
try:
page = int(query["page"][0])
per_page = int(query.get("per_page", [str(PAGE_SIZE)])[0])
except (KeyError, IndexError, ValueError):
# A link carrying no usable page number cannot be range-checked here. The paginator's
# record counter is the backstop for that case.
return False
return (page - 1) * per_page >= MAX_RECORDS_PER_QUERY
def _build_params(config: AircallEndpointConfig, from_value: Optional[int]) -> dict[str, Any]:
params: dict[str, Any] = {"per_page": PAGE_SIZE} if config.paginated else {}
# Ascending creation order keeps already-fetched pages stable and lets the incremental
# watermark advance monotonically. `from` filters on the resource creation date.
if config.incremental_fields or config.reanchor_field:
params["order"] = "asc"
if from_value is not None:
params["from"] = from_value
return params
class AircallPaginator(BasePaginator):
"""Follows Aircall's `meta.next_page_link` chain, re-anchoring around the 10k cap.
On a capped endpoint (calls/contacts) the paginator re-anchors the `from` query param to the
latest value of the cursor field seen so far and starts a fresh chain, so records beyond
Aircall's hard 10k-record-per-query cap are still fetched. Reaching the cap is itself a
re-anchor trigger, because Aircall goes on advertising a next page past the cap and then
rejects that page with a 400: waiting for the page chain to end would never re-anchor the
tables that actually need it. The end of a page chain re-anchors too, since a chain that ends
at the cap boundary is indistinguishable from one that ends because the window is exhausted.
When many records share the boundary timestamp the cursor cannot advance, so a fresh window
would repeat the same query forever. The paginator raises `AircallTruncationError` there
rather than loop or drop the rest of the window silently.
"""
def __init__(
self,
config: AircallEndpointConfig,
cursor_field: Optional[str],
from_value: Optional[int],
) -> None:
super().__init__()
self._config = config
self._cursor_field = cursor_field
self._from_value = from_value
# Latest value of the cursor field seen across the whole run.
self._max_cursor: Optional[int] = None
self._next_url: Optional[str] = None
# Records consumed since the current `from` window opened. Backs up the per-link range
# check for a next-page link that carries no page number.
self._window_records = 0
def init_request(self, request: Request) -> None:
# Apply a seeded resume URL to the first request so a resumed run starts at the
# saved next-page link rather than the base path.
if self._next_url is not None:
request.url = self._next_url
request.params = {}
def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
items = data or []
self._window_records += len(items)
if self._cursor_field is not None and items:
page_max = max(
(
cursor
for cursor in (_to_epoch(item.get(self._cursor_field)) for item in items)
if cursor is not None
),
default=None,
)
if page_max is not None and (self._max_cursor is None or page_max > self._max_cursor):
self._max_cursor = page_max
try:
body = response.json()
except Exception:
body = None
next_url = ((body or {}).get("meta") or {}).get("next_page_link") if isinstance(body, dict) else None
capped = self._config.reanchor_field is not None and (
self._window_records >= MAX_RECORDS_PER_QUERY or (next_url is not None and _reaches_record_cap(next_url))
)
if next_url and not capped:
self._next_url = next_url
self._has_next_page = True
return
# Either the page chain ended or the next page Aircall offered would be rejected for
# crossing the cap. Both call for the same move on a capped endpoint: anchor `from` on
# the latest cursor value seen and open a fresh window.
if (
self._config.reanchor_field is not None
and self._max_cursor is not None
and (self._from_value is None or self._max_cursor > self._from_value)
):
self._from_value = self._max_cursor
self._window_records = 0
self._next_url = _build_url(self._config.path, _build_params(self._config, self._from_value))
self._has_next_page = True
return
if capped:
# A window that fills the cap without its cursor advancing cannot be moved forward,
# because the next window would open on the same timestamp and return the same
# records. Fail rather than drop the rest of the window silently: a warning-only stop
# let the run finalize as complete with missing data, which is invisible to the user.
raise AircallTruncationError(
f"Aircall {self._config.path}: {self._config.reanchor_field} did not advance past "
f"{self._from_value} within the {MAX_RECORDS_PER_QUERY}-record query limit, so the "
"rest of this window cannot be fetched. The sync stopped to avoid losing data."
)
self._has_next_page = False
def update_request(self, request: Request) -> None:
if self._next_url is not None:
request.url = self._next_url
# The next-page URL is self-contained — it already carries every query param
# needed. Drop the original params so they aren't re-appended each page.
request.params = {}
def get_resume_state(self) -> Optional[dict[str, Any]]:
return {"next_url": self._next_url} if self._has_next_page and self._next_url is not None else None
def set_resume_state(self, state: dict[str, Any]) -> None:
next_url = state.get("next_url")
if next_url is not None:
self._next_url = next_url
self._has_next_page = True
def validate_credentials(api_id: str, api_token: str) -> bool:
"""Confirm the API key pair is valid. /v1/ping is a cheap authenticated probe."""
ok, _status = validate_via_probe(
lambda: make_tracked_session(redact_values=(api_token,)),
f"{AIRCALL_BASE_URL}/ping",
headers={"Accept": "application/json"},
auth=HTTPBasicAuth(api_id, api_token),
)
return ok
def _client_config(api_id: str, api_token: str, paginator: BasePaginator) -> ClientConfig:
return {
"base_url": AIRCALL_BASE_URL,
"headers": {"Accept": "application/json"},
# Basic auth via the framework so the token is redacted from logs.
"auth": {"type": "http_basic", "username": api_id, "password": api_token},
"paginator": paginator,
}
def _fanout_source(
api_id: str,
api_token: str,
endpoint: str,
team_id: int,
job_id: str,
) -> SourceResponse:
"""Fan a per-call or per-campaign sub-resource out over its parent list.
The parent list is re-fetched each sync (there is no incremental filter on the child
sub-resources), so the parent keeps its own paginator. For calls that paginator pages past the
10k cap. A child that returns one object per parent needs a single-page paginator, while a
paginated child follows its own next-page links. The parent and child therefore run different
paginators, set per endpoint rather than on the shared client.
"""
config = AIRCALL_ENDPOINTS[endpoint]
assert config.fanout is not None
parent_config = AIRCALL_ENDPOINTS[config.fanout.parent_name]
parent_paginator = AircallPaginator(parent_config, parent_config.reanchor_field, from_value=None)
child_paginator: BasePaginator = (
AircallPaginator(config, cursor_field=None, from_value=None) if config.paginated else SinglePagePaginator()
)
dependent_resource = cast(
Iterable[Any],
build_dependent_resource(
endpoint_configs=AIRCALL_ENDPOINTS,
child_endpoint=endpoint,
fanout=config.fanout,
client_config=_client_config(api_id, api_token, SinglePagePaginator()),
path_format_values={},
team_id=team_id,
job_id=job_id,
# The child has no server-side time filter, so this fan-out is always full refresh.
db_incremental_field_last_value=None,
should_use_incremental_field=False,
page_size_param="per_page",
parent_endpoint_extra={"paginator": parent_paginator, "data_selector": parent_config.data_key},
child_endpoint_extra={"paginator": child_paginator, "data_selector": config.data_key},
),
)
return SourceResponse(
name=endpoint,
items=lambda: dependent_resource,
primary_keys=[config.primary_key],
# Child rows arrive in the parent's order, which is ascending only for a parent walked
# by its re-anchor field (calls by started_at). The campaigns list has no documented order.
sort_mode="asc" if parent_config.reanchor_field else None,
partition_count=1,
partition_size=1,
)
def aircall_source(
api_id: str,
api_token: str,
endpoint: str,
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[AircallResumeConfig],
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
incremental_field: str | None = None,
) -> SourceResponse:
config = AIRCALL_ENDPOINTS[endpoint]
if config.fanout is not None:
return _fanout_source(api_id, api_token, endpoint, team_id, job_id)
cursor_field = incremental_field or config.reanchor_field
from_value = _to_epoch(db_incremental_field_last_value) if should_use_incremental_field else None
rest_config: RESTAPIConfig = {
"client": {
"base_url": AIRCALL_BASE_URL,
"headers": {"Accept": "application/json"},
# Basic auth via the framework so the token is redacted from logs.
"auth": {"type": "http_basic", "username": api_id, "password": api_token},
"paginator": AircallPaginator(config, cursor_field, from_value),
},
"resources": [
{
"name": endpoint,
"endpoint": {
"path": config.path,
# A missing data key is tolerated (treated as an empty page), matching
# Aircall's occasional key-less bodies — so no data_selector_required.
"data_selector": config.data_key,
"params": _build_params(config, from_value),
},
}
],
}
initial_paginator_state: Optional[dict[str, Any]] = None
if resumable_source_manager.can_resume():
resume = resumable_source_manager.load_state()
if resume is not None:
initial_paginator_state = {"next_url": resume.next_url}
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
# Persist only while a next page (or re-anchored window) remains; save AFTER a page is
# yielded so a crash re-yields the last page (merge dedupes) rather than skipping it.
if state and state.get("next_url"):
resumable_source_manager.save_state(AircallResumeConfig(next_url=str(state["next_url"])))
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_key],
sort_mode="asc",
partition_count=1,
partition_size=1,
partition_mode="datetime" if config.partition_key else None,
partition_format="week" if config.partition_key else None,
partition_keys=[config.partition_key] if config.partition_key else None,
)