Skip to content

: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.

5.8 KB
Raw Blame
from dataclasses import field
from typing import Any

from products.warehouse_sources.sources.sdk import (
    DependentEndpointConfig,
    IncrementalField,
    IncrementalFieldType,
    ResponseAction,
    SortMode,
    frozen,
)


@frozen
class ButtondownEndpointConfig:
    name: str
    path: str
    primary_keys: list[str] = field(default_factory=lambda: ["id"])
    # Server-side "created on/after" filter, when the endpoint has one. Only endpoints that expose
    # it advertise incremental sync; the rest are full refresh.
    incremental_start_param: str | None = None
    # Value passed as `?ordering=`. Only set where the API documents `creation_date` as an accepted
    # ordering value, so pagination walks a stable, monotonic column.
    ordering: str | None = None
    # Only consulted on incremental syncs: "asc" lets the pipeline checkpoint the watermark after
    # every batch, so it is safe only where the request forces ascending order. Endpoints whose
    # order we cannot force stay "desc", which defers the commit to the end of a successful job.
    sort_mode: SortMode = "desc"
    partition_key: str | None = "creation_date"
    # Set for per-subscriber endpoints, which are fetched once for every row of /subscribers.
    fanout: DependentEndpointConfig | None = None
    # Structural requirements of `FanoutEndpointLike`. Fan-out children are full refresh, and
    # Buttondown takes no page-size param, so the fan-out passes `page_size_param=None`.
    incremental_fields: list[Any] = field(default_factory=list)
    default_incremental_field: str | None = None
    page_size: int = 100


# A subscriber deleted between the parent listing and its child fetch 404s. Skip that subscriber
# rather than failing the whole fan-out.
_SKIP_DELETED_SUBSCRIBER: list[ResponseAction] = [{"status_code": 404, "action": "ignore"}]


def _per_subscriber(parent_key_name: str) -> DependentEndpointConfig:
    return DependentEndpointConfig(
        parent_name="subscribers",
        resolve_param="id_or_email",
        resolve_field="id",
        include_from_parent=["id"],
        parent_field_renames={"id": parent_key_name},
        child_response_actions=_SKIP_DELETED_SUBSCRIBER,
    )


BUTTONDOWN_ENDPOINTS: dict[str, ButtondownEndpointConfig] = {
    "automations": ButtondownEndpointConfig(name="automations", path="/automations", sort_mode="asc"),
    "comments": ButtondownEndpointConfig(name="comments", path="/comments", ordering="creation_date", sort_mode="asc"),
    "emails": ButtondownEndpointConfig(
        name="emails",
        path="/emails",
        incremental_start_param="creation_date__start",
        ordering="creation_date",
        sort_mode="asc",
    ),
    "events": ButtondownEndpointConfig(name="events", path="/events", ordering="creation_date", sort_mode="asc"),
    "forms": ButtondownEndpointConfig(name="forms", path="/forms", ordering="creation_date", sort_mode="asc"),
    # /notes documents no `ordering` param and no date filter.
    "notes": ButtondownEndpointConfig(name="notes", path="/notes"),
    "prices": ButtondownEndpointConfig(name="prices", path="/prices", sort_mode="asc", partition_key=None),
    # `ordering` is documented on /subscribers but its accepted values are not enumerated, and an
    # unrecognized value falls back to the default `-creation_date` rather than erroring. Rather
    # than risk declaring an ascending sort the API silently ignores, take the documented default
    # (newest first) and keep the watermark on the end-of-job commit path.
    "subscribers": ButtondownEndpointConfig(
        name="subscribers", path="/subscribers", incremental_start_param="date__start"
    ),
    # /survey_responses has no `ordering` param at all, so row order is undocumented.
    "survey_responses": ButtondownEndpointConfig(
        name="survey_responses", path="/survey_responses", incremental_start_param="creation_date__start"
    ),
    "surveys": ButtondownEndpointConfig(name="surveys", path="/surveys", ordering="creation_date", sort_mode="asc"),
    "tags": ButtondownEndpointConfig(name="tags", path="/tags", sort_mode="asc"),
    # The per-subscriber endpoints take only `page`, so they are full refresh. The parent subscriber
    # id is part of each key, because the vendor documents no table-wide uniqueness for these ids.
    "automation_attempts": ButtondownEndpointConfig(
        name="automation_attempts",
        path="/subscribers/{id_or_email}/automations",
        primary_keys=["subscriber_id", "id"],
        partition_key="execution_date",
        fanout=_per_subscriber("subscriber_id"),
    ),
    # Each row is a subscriber that the parent subscriber referred.
    "referrals": ButtondownEndpointConfig(
        name="referrals",
        path="/subscribers/{id_or_email}/referrals",
        primary_keys=["referrer_subscriber_id", "id"],
        fanout=_per_subscriber("referrer_subscriber_id"),
    ),
    "stripe_subscriptions": ButtondownEndpointConfig(
        name="stripe_subscriptions",
        path="/subscribers/{id_or_email}/stripe-subscriptions",
        primary_keys=["subscriber_id", "subscription_id"],
        fanout=_per_subscriber("subscriber_id"),
    ),
}

ENDPOINTS = tuple(BUTTONDOWN_ENDPOINTS.keys())

# Only endpoints with a real server-side "created on/after" filter. Everything else stays full
# refresh: /events and /comments carry a `creation_date` but expose no date filter, so an
# "incremental" sync there would still page through the entire history on every run.
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
    name: [
        {
            "label": "creation_date",
            "type": IncrementalFieldType.DateTime,
            "field": "creation_date",
            "field_type": IncrementalFieldType.DateTime,
        }
    ]
    for name, config in BUTTONDOWN_ENDPOINTS.items()
    if config.incremental_start_param is not None
}