: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
"""Read-side client for the managed-warehouse control-plane org-teams API.
The control plane is duckgres (``DUCKGRES_API_URL``) unless ``HOGTOWER_API_URL`` is set,
in which case :mod:`products.managed_warehouse.backend.presentation.hogtower` serves the same reads
from hogtower's /api/v2 in the duckgres response shape.
The control plane is the source of truth for per-team managed-warehouse state.
This module exposes the CP rows as :class:`CPTeam` values plus a small process-local
TTL cache so hot paths (the v3 data-import sink schema resolution) don't issue one
HTTP call per batch.
Legacy-name semantics of a CP row: a non-NULL ``events_table_name`` /
``persons_table_name`` / ``schema_data_imports_name`` is a grandfathered explicit
pin; NULL means "derive from ``schema_name``". The derive rule here is the
TRANSITIONAL one — writers still produce the old suffix-derived layout, so for
every existing row it is byte-identical to the Django-side derivation:
* events: ``events_<schema_name>``
* persons: ``persons_<schema_name>``
* data-imports schema: ``posthog_data_imports_<schema_name>``
Do NOT change this to the future ``<schema_name>.events`` layout until the writers do.
Every fetcher returns ``None`` when the control plane is unreachable or answers
unusably — callers decide the failure posture (fail open, fail closed, or raise).
"""
from __future__ import annotations
import time
import logging
import threading
from collections.abc import Callable
from datetime import date
from functools import partial
from django.conf import settings
import requests as http_requests
from posthog.dataclasses import frozen
from posthog.security.outbound_proxy import internal_requests
from products.managed_warehouse.backend.facade.contracts import (
ManagedWarehouseTableNames,
ManagedWarehouseTeamMembership,
)
from products.managed_warehouse.backend.presentation import hogtower
logger = logging.getLogger(__name__)
# TTL for the process-local cache below. Monkeypatchable in tests; sized so sensor
# ticks and per-batch schema resolutions coalesce onto one CP call per minute.
CACHE_TTL_SECONDS: float = 60.0
@frozen
class CPTeam:
"""One duckgres control-plane org-team row."""
team_id: int
organization_id: str
schema_name: str
enabled: bool
backfill_enabled: bool
events_table_name: str | None
persons_table_name: str | None
schema_data_imports_name: str | None
earliest_event_date: date | None
data_imports_table_naming_version: str = "legacy_batch_v1"
@property
def resolved_events_table(self) -> str:
"""Events table name: the grandfathered pin, else the transitional derivation."""
return self.events_table_name or f"events_{self.schema_name}"
@property
def resolved_persons_table(self) -> str:
"""Persons table name: the grandfathered pin, else the transitional derivation."""
return self.persons_table_name or f"persons_{self.schema_name}"
@property
def resolved_groups_table(self) -> str:
return f"groups_{self.schema_name}"
@property
def resolved_data_imports_schema(self) -> str:
"""Data-imports schema: the grandfathered pin, else the transitional derivation."""
return self.schema_data_imports_name or f"posthog_data_imports_{self.schema_name}"
def to_membership(self) -> ManagedWarehouseTeamMembership:
return ManagedWarehouseTeamMembership(
team_id=self.team_id,
organization_id=self.organization_id,
schema_name=self.schema_name,
enabled=self.enabled,
backfill_enabled=self.backfill_enabled,
table_names=ManagedWarehouseTableNames(
events_table=self.resolved_events_table,
persons_table=self.resolved_persons_table,
groups_table=self.resolved_groups_table,
data_imports_schema=self.resolved_data_imports_schema,
),
earliest_event_date=self.earliest_event_date,
)
def _parse_earliest_event_date(raw: object) -> date | None:
if not raw:
return None
if isinstance(raw, date):
return raw
try:
return date.fromisoformat(str(raw))
except ValueError:
logger.warning("cp_teams_unparseable_earliest_event_date: %r", raw)
return None
def team_from_row(row: dict, *, organization_id: str | None = None) -> CPTeam | None:
"""Build a CPTeam from a raw API row, or None when the row is unusable."""
try:
team_id = int(row["team_id"]) # defensive: the API serializes ints, but coerce anyway
except (KeyError, TypeError, ValueError):
logger.warning("cp_teams_row_missing_team_id")
return None
schema_name = row.get("schema_name")
if not isinstance(schema_name, str) or not schema_name:
logger.warning("cp_teams_row_missing_schema_name (team_id=%s)", team_id)
return None
# Writes derive their URL from the org id, so a row without one is unusable — an
# empty org would send updates down /orgs//teams/... and fail silently every tick.
org = row.get("org_id") or organization_id
if not org:
logger.warning("cp_teams_row_missing_org_id (team_id=%s)", team_id)
return None
return CPTeam(
team_id=team_id,
organization_id=str(org),
schema_name=schema_name,
enabled=bool(row.get("enabled")),
backfill_enabled=bool(row.get("backfill_enabled")),
events_table_name=row.get("events_table_name") or None,
persons_table_name=row.get("persons_table_name") or None,
schema_data_imports_name=row.get("schema_data_imports_name") or None,
earliest_event_date=_parse_earliest_event_date(row.get("earliest_event_date")),
data_imports_table_naming_version=str(row.get("data_imports_table_naming_version") or "legacy_batch_v1"),
)
_cache_lock = threading.Lock()
_cache: dict[tuple[str, ...], tuple[float, list[dict]]] = {}
_cache_epoch = 0
_cache_generations: dict[tuple[str, ...], int] = {}
def clear_cache() -> None:
"""Drop every cached CP response (for tests and operational cache busts)."""
global _cache_epoch
with _cache_lock:
_cache.clear()
_cache_epoch += 1
def invalidate_org_cache(organization_id: str) -> None:
"""Drop cached rows affected by a mutation to one organization's teams."""
with _cache_lock:
for key in (("org_teams", str(organization_id)), ("all_teams",)):
_cache.pop(key, None)
_cache_generations[key] = _cache_generations.get(key, 0) + 1
def _cached_rows(
key: tuple[str, ...], fetch: Callable[[], list[dict] | None], *, use_cache: bool = True
) -> list[dict] | None:
"""Serve `key` from the TTL cache unless the caller requires a fresh CP read."""
with _cache_lock:
hit = _cache.get(key)
if use_cache and hit is not None and time.monotonic() - hit[0] < CACHE_TTL_SECONDS:
return hit[1]
generation = (_cache_epoch, _cache_generations.get(key, 0))
rows = fetch()
if rows is not None:
with _cache_lock:
if generation == (_cache_epoch, _cache_generations.get(key, 0)):
_cache[key] = (time.monotonic(), rows)
return rows
def _rows_from_response(response: http_requests.Response | hogtower.TranslatedResponse) -> list[dict] | None:
"""Extract the control-plane team payload without importing DRF presentation code."""
status_code = response.status_code
if not 200 <= status_code < 300:
return None
try:
data = response.json()
except ValueError:
return None
naming_version: object = None
if isinstance(data, dict):
naming_version = data.get("data_imports_table_naming_version")
data = data.get("teams")
if not isinstance(data, list):
return None
return [
{**row, "data_imports_table_naming_version": naming_version}
if isinstance(naming_version, str) and naming_version
else row
for row in data
if isinstance(row, dict)
]
def _fetch_rows(*, organization_id: str | None) -> list[dict] | None:
"""Read team rows directly from the control plane using the approved internal transport.
This deliberately mirrors the data-warehouse adapter's request construction and
fallback behavior, but returns only its private read-side payload rather than a
DRF ``Response``. The caller's cache remains responsible for retry behavior.
"""
send: Callable[[], http_requests.Response | hogtower.TranslatedResponse]
if hogtower.is_configured():
if organization_id is None:
send = partial(hogtower.request, "GET", "", "teams", timeout=30)
else:
send = partial(hogtower.request, "GET", organization_id, "/teams", timeout=30)
else:
base_url = getattr(settings, "DUCKGRES_API_URL", None)
if not base_url:
logger.warning("cp_teams_request_rejected_api_not_configured (organization_id=%s)", organization_id)
return None
if organization_id is None:
url = f"{base_url.rstrip('/')}/api/v1/teams"
else:
url = f"{base_url.rstrip('/')}/api/v1/orgs/{organization_id}/teams"
headers: dict[str, str] = {}
token = getattr(settings, "DUCKGRES_INTERNAL_SECRET", None)
if token:
headers["X-Duckgres-Internal-Secret"] = token
send = partial(internal_requests.request, "GET", url, json=None, params=None, headers=headers, timeout=30)
try:
response = send()
except http_requests.Timeout:
logger.warning("cp_teams_list_request_timed_out (organization_id=%s)", organization_id)
return None
except http_requests.ConnectionError:
logger.warning("cp_teams_list_request_unreachable (organization_id=%s)", organization_id)
return None
except Exception:
logger.exception("cp_teams_list_request_failed (organization_id=%s)", organization_id)
return None
if response.status_code >= 400:
logger.warning(
"cp_teams_list_request_error (organization_id=%s, status_code=%s, response_body=%s)",
organization_id,
response.status_code,
response.text[:500],
)
return _rows_from_response(response)
def _fetch_org_rows(organization_id: str) -> list[dict] | None:
return _fetch_rows(organization_id=organization_id)
def _fetch_all_rows() -> list[dict] | None:
return _fetch_rows(organization_id=None)
def _fetch_ready_warehouse_rows() -> list[dict] | None:
"""Read warehouses that can accept backfill connections from the discovery API."""
send: Callable[[], http_requests.Response | hogtower.TranslatedResponse]
if hogtower.is_configured():
send = partial(hogtower.request, "GET", "", "warehouses", timeout=30)
else:
base_url = getattr(settings, "DUCKGRES_API_URL", None)
if not base_url:
logger.warning("cp_teams_request_rejected_api_not_configured (resource=warehouses)")
return None
headers: dict[str, str] = {}
token = getattr(settings, "DUCKGRES_INTERNAL_SECRET", None)
if token:
headers["X-Duckgres-Internal-Secret"] = token
send = partial(
internal_requests.request,
"GET",
f"{base_url.rstrip('/')}/api/v1/warehouses",
json=None,
params=None,
headers=headers,
timeout=30,
)
try:
response = send()
except http_requests.Timeout:
logger.warning("cp_teams_list_request_timed_out (resource=warehouses)")
return None
except http_requests.ConnectionError:
logger.warning("cp_teams_list_request_unreachable (resource=warehouses)")
return None
except Exception:
logger.exception("cp_teams_list_request_failed (resource=warehouses)")
return None
if not 200 <= response.status_code < 300:
logger.warning(
"cp_teams_list_request_error (resource=warehouses, status_code=%s, response_body=%s)",
response.status_code,
response.text[:500],
)
return None
try:
data = response.json()
except ValueError:
return None
if not isinstance(data, dict) or not isinstance(data.get("warehouses"), list):
return None
return [row for row in data["warehouses"] if isinstance(row, dict) and row.get("state") == "ready"]
def _ready_warehouse_org_ids() -> set[str] | None:
rows = _cached_rows(("ready_warehouses",), _fetch_ready_warehouse_rows)
if rows is None:
return None
organization_ids: set[str] = set()
for row in rows:
organization_id = row.get("org_id")
if isinstance(organization_id, str) and organization_id:
organization_ids.add(organization_id)
else:
logger.warning("cp_teams_ready_warehouse_missing_org_id")
return organization_ids
def list_org_teams(organization_id: str, *, use_cache: bool = True) -> list[CPTeam] | None:
"""All CP team rows of an org, or None when the control plane can't answer."""
org_id = str(organization_id)
rows = _cached_rows(("org_teams", org_id), lambda: _fetch_org_rows(org_id), use_cache=use_cache)
if rows is None:
return None
teams = (team_from_row(row, organization_id=org_id) for row in rows)
return [team for team in teams if team is not None]
def get_team(organization_id: str, team_id: int) -> CPTeam | None:
"""The CP row for one team, or None when absent OR the control plane can't answer.
Callers that must distinguish "absent" from "unreachable" should use
:func:`list_org_teams` directly.
"""
teams = list_org_teams(organization_id)
if teams is None:
return None
wanted = int(team_id)
return next((team for team in teams if team.team_id == wanted), None)
def list_member_teams(*, use_cache: bool = True) -> list[CPTeam] | None:
"""Every CP team row across all orgs, or None when unreachable."""
rows = _cached_rows(("all_teams",), _fetch_all_rows, use_cache=use_cache)
if rows is None:
return None
teams = (team_from_row(row) for row in rows)
return [team for team in teams if team is not None]
def list_enabled_backfills() -> list[CPTeam] | None:
"""Backfill-enabled teams whose warehouses are ready, or None when either read is unavailable."""
teams = list_member_teams()
if teams is None:
return None
enabled_teams = [team for team in teams if team.backfill_enabled]
if not enabled_teams:
return []
ready_organization_ids = _ready_warehouse_org_ids()
if ready_organization_ids is None:
return None
return [team for team in enabled_teams if team.organization_id in ready_organization_ids]