: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 typing import Any, Optional
from urllib.parse import urlencode
from products.warehouse_sources.sources.bluetally.settings import BLUETALLY_ENDPOINTS
from products.warehouse_sources.sources.sdk import (
OffsetPaginator,
RESTAPIConfig,
ResumableSourceManager,
SinglePagePaginator,
SourceResponse,
make_tracked_session,
rest_api_resource,
validate_via_probe,
)
BLUETALLY_BASE_URL = "https://app.bluetallyapp.com/api/v1"
# BlueTally caps a single response at 1000 rows; using the max minimizes requests against the
# 10,000-requests-per-hour budget.
PAGE_SIZE = 1000
@dataclasses.dataclass(frozen=False)
class BluetallyResumeConfig:
# Offset of the next page to fetch. BlueTally paginates with limit/offset, so persisting the
# offset is all we need to pick a full-refresh sync back up after a heartbeat timeout.
offset: int = 0
def bluetally_source(
api_key: str,
endpoint: str,
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[BluetallyResumeConfig],
tenant_id: Optional[str] = None,
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
config = BLUETALLY_ENDPOINTS[endpoint]
params: dict[str, Any] = {}
if config.sort:
# Sorting on `created_at` ascending keeps offset pagination stable even as new rows are
# appended mid-sync.
params["sort"] = config.sort
params["order"] = "asc"
if tenant_id and config.accepts_tenant_id:
params["tenant_id"] = tenant_id
rest_config: RESTAPIConfig = {
"client": {
"base_url": BLUETALLY_BASE_URL,
# Auth (Bearer) is supplied via the framework auth config so its value is redacted from
# logged URLs and captured HTTP samples; only the non-secret Accept header is set here.
"headers": {"Accept": "application/json"},
"auth": {"type": "bearer", "token": api_key},
# BlueTally reports no total anywhere; termination is short/empty page (OffsetPaginator default).
"paginator": OffsetPaginator(limit=PAGE_SIZE, total_path=None)
if config.paginated
else SinglePagePaginator(),
},
"resources": [
{
"name": endpoint,
"endpoint": {
"path": config.path,
"params": params,
"data_selector": config.data_selector,
# The rows always arrive as a JSON array, bare or under `data_selector`. A 200
# that doesn't carry one (wrapped payload, proxy HTML, …) is a permanent
# API-contract violation — fail loud instead of syncing the stray object as a row.
"data_selector_required": True,
},
}
],
}
# Only offset pagination has a position worth persisting; a single-page endpoint is one request.
initial_paginator_state: Optional[dict[str, Any]] = None
if config.paginated and resumable_source_manager.can_resume():
resume = resumable_source_manager.load_state()
if resume is not None:
initial_paginator_state = {"offset": resume.offset}
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
# Persist only when a next page remains; saved AFTER a page is yielded so a crash re-runs
# from the last persisted offset rather than skipping ahead (merge dedupes re-pulled rows).
if state and state.get("offset") is not None:
resumable_source_manager.save_state(BluetallyResumeConfig(offset=int(state["offset"])))
resource = rest_api_resource(
rest_config,
team_id,
job_id,
db_incremental_field_last_value,
resume_hook=save_checkpoint if config.paginated else None,
initial_paginator_state=initial_paginator_state,
)
return SourceResponse(
name=endpoint,
items=lambda: resource,
primary_keys=config.primary_keys,
partition_count=1,
partition_size=1,
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,
# We request `sort=created_at&order=asc`, so rows arrive oldest-first. Endpoints that take
# no sort parameter make no ordering guarantee, so they declare none.
sort_mode="asc" if config.sort else None,
column_hints=resource.column_hints,
)
def validate_credentials(api_key: str, tenant_id: str | None = None, endpoint: str = "assets") -> bool:
config = BLUETALLY_ENDPOINTS[endpoint]
query: dict[str, Any] = {}
if config.paginated:
query["limit"] = 1
if tenant_id and config.accepts_tenant_id:
query["tenant_id"] = tenant_id
url = f"{BLUETALLY_BASE_URL}{config.path}"
if query:
url = f"{url}?{urlencode(query)}"
ok, _status = validate_via_probe(
lambda: make_tracked_session(redact_values=(api_key,)),
url,
headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
)
return ok