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.

18.7 KB
Raw Blame
import dataclasses
from collections.abc import Iterator
from datetime import UTC, datetime, timedelta
from typing import Any, Optional
from urllib.parse import urlencode, urljoin

import requests
from structlog.types import FilteringBoundLogger
from tenacity import RetryCallState, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter

from products.warehouse_sources.sources.mention.settings import MENTION_ENDPOINTS
from products.warehouse_sources.sources.sdk import (
    ResumableSourceManager,
    SourceResponse,
    frozen,
    make_tracked_session,
    reach_safe_point,
    retry_with_deadline,
)

MENTION_HOST = "https://api.mention.net"
MENTION_BASE_URL = f"{MENTION_HOST}/api"
# Vendor API versions, sent verbatim on every request via the Accept-Version header
# (https://dev.mention.com/current/src/Changelog.html). Since 1.21 the alert resource returns an
# empty `stats` field unless a `stats` query parameter lists the counters to include; 1.19 returns
# them by default, so the alerts list request restores the documented counters under 1.21.
API_VERSION_1_19 = "1.19"
API_VERSION_1_21 = "1.21"
SUPPORTED_API_VERSIONS = (API_VERSION_1_19, API_VERSION_1_21)
DEFAULT_API_VERSION = API_VERSION_1_21
# Versions that return the alert `stats` object without an explicit request for it.
_STATS_BY_DEFAULT_VERSIONS = frozenset({API_VERSION_1_19})
# Counters the Mention changelog documents for the 1.21 `stats` query parameter; they map to the
# "mentions per folder and unread mention totals" the alerts schema exposes.
ALERT_STATS_PARAM = "mention_folders.inbox.total,unread_mentions.total"
# Mentions accept up to limit=1000; 100 keeps pages small while staying well inside the documented
# 3600 list calls per alert per 24h quota.
PAGE_SIZE = 100
REQUEST_TIMEOUT_SECONDS = 60
# Trailing window requested from the stats endpoint. Stats are bucketed by the day Mention fetched
# each mention, so recent days keep changing and the table is rebuilt on every sync.
STATS_LOOKBACK_DAYS = 365
STATS_DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.0"
# Cheap endpoint used to confirm an access token is genuine. The token is account-wide, so one
# probe validates access to every list endpoint.
DEFAULT_PROBE_PATH = "/accounts/me"


class MentionRetryableError(Exception):
    pass


@dataclasses.dataclass(frozen=False)
class MentionResumeConfig:
    # Remaining alert ids for the per-alert fan-out endpoints (current alert first). None means the
    # endpoint is not a fan-out one (or the alert list hasn't been captured yet).
    alert_ids: list[str] | None = None
    # Absolute URL of the next page to fetch, taken from the API's ``_links.more.href``. Cursor
    # pagination is deterministic, so a crashed full-refresh sync resumes from the page after the
    # last one yielded; merge dedupes the re-pulled page on the primary key.
    next_url: str | None = None


def _headers(access_token: str, api_version: str) -> dict[str, str]:
    return {
        "Authorization": f"Bearer {access_token}",
        "Accept": "application/json",
        "Accept-Version": api_version,
    }


def _list_url(path: str, limit: int | None = PAGE_SIZE, extra_params: dict[str, str] | None = None) -> str:
    params: dict[str, str | int] = {}
    if limit is not None:
        params["limit"] = limit
    if extra_params:
        params.update(extra_params)
    if not params:
        return f"{MENTION_BASE_URL}{path}"
    # ``safe=","`` keeps the comma-separated ``stats`` value readable rather than percent-encoded.
    return f"{MENTION_BASE_URL}{path}?{urlencode(params, safe=',')}"


def _alerts_list_url(account_id: str, api_version: str) -> str:
    # 1.21 empties the alert `stats` field unless the counters are requested explicitly.
    extra = None if api_version in _STATS_BY_DEFAULT_VERSIONS else {"stats": ALERT_STATS_PARAM}
    return _list_url(f"/accounts/{account_id}/alerts", extra_params=extra)


def _more_url(payload: dict[str, Any]) -> Optional[str]:
    # ``_links.more.href`` points at the next page of older items and is present only when more
    # exist. The href is host-relative (``/api/...``), so resolve it against the API host.
    links = payload.get("_links")
    if not isinstance(links, dict):
        return None
    more = links.get("more")
    if not (isinstance(more, dict) and isinstance(more.get("href"), str) and more["href"]):
        return None
    # urljoin honours an absolute href, so a tampered response could point the session (which
    # carries the bearer token in its default headers) at another host. Pin the resolved URL to
    # the Mention API before we ever fetch it.
    resolved = urljoin(MENTION_HOST, more["href"])
    if resolved != MENTION_BASE_URL and not resolved.startswith((f"{MENTION_BASE_URL}/", f"{MENTION_BASE_URL}?")):
        raise MentionRetryableError(f"Mention pagination URL {resolved!r} is not on the Mention API host")
    return resolved


def _safe_point_before_retry_wait(_state: RetryCallState) -> None:
    # Every request runs between pages: the rows before it are yielded, and no caller holds rows
    # while it fetches.
    reach_safe_point()


@retry_with_deadline(
    retry=retry_if_exception_type((MentionRetryableError, requests.ReadTimeout, requests.ConnectionError)),
    stop=stop_after_attempt(5),
    wait=wait_exponential_jitter(initial=1, max=30),
    before_sleep=_safe_point_before_retry_wait,
    reraise=True,
)
def _fetch_page(
    session: requests.Session,
    url: str,
    logger: FilteringBoundLogger,
) -> dict[str, Any]:
    # ``url`` is already absolute — either an initial list URL or a resolved ``_links.more`` href,
    # so we never re-send paging params (they're baked into the cursor URL).
    response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)

    if response.status_code == 429 or response.status_code >= 500:
        # 429 carries X-Rate-Limit-Reset (a unix timestamp); the per-alert quota window can be
        # hours long, so we back off briefly here and otherwise let the job-level retry policy
        # reschedule the sync.
        raise MentionRetryableError(f"Mention API error (retryable): status={response.status_code}, url={url}")

    if not response.ok:
        logger.error(f"Mention API error: status={response.status_code}, body={response.text}, url={url}")
        response.raise_for_status()

    data = response.json()
    if not isinstance(data, dict):
        raise MentionRetryableError(f"Mention returned an unexpected payload for {url}: {type(data).__name__}")

    return data


def _rows_from_payload(payload: dict[str, Any], key: str, url: str) -> list[dict[str, Any]]:
    rows = payload.get(key)
    if not isinstance(rows, list):
        raise MentionRetryableError(f"Mention returned an unexpected '{key}' field for {url}")
    return rows


def _unwrap_alert(item: dict[str, Any]) -> dict[str, Any]:
    # The docs state each listed alert "has the form it would if you did a get request on that
    # specific alert", whose body nests the object under ``alert`` — accept both shapes.
    inner = item.get("alert")
    return inner if isinstance(inner, dict) else item


def _get_account(session: requests.Session, logger: FilteringBoundLogger) -> dict[str, Any]:
    payload = _fetch_page(session, f"{MENTION_BASE_URL}/accounts/me", logger)
    account = payload.get("account")
    if not isinstance(account, dict) or account.get("id") is None:
        raise MentionRetryableError("Mention returned an unexpected payload for /accounts/me")
    return account


def _list_all_alert_ids(session: requests.Session, account_id: str, logger: FilteringBoundLogger) -> list[str]:
    alert_ids: list[str] = []
    url: Optional[str] = _list_url(f"/accounts/{account_id}/alerts")
    while url:
        payload = _fetch_page(session, url, logger)
        rows = [_unwrap_alert(row) for row in _rows_from_payload(payload, "alerts", url)]
        for row in rows:
            # ``id`` is the alert's primary key and the fan-out endpoints build their URLs from it,
            # so a missing id is a data error we surface rather than silently drop the alert.
            if row.get("id") is None:
                raise MentionRetryableError(f"Mention returned an alert without an id for {url}")
            alert_ids.append(str(row["id"]))
        url = None if not rows else _more_url(payload)
    return alert_ids


def _account_rows(session: requests.Session, logger: FilteringBoundLogger) -> Iterator[list[dict[str, Any]]]:
    yield [_get_account(session, logger)]


def _alert_rows(
    session: requests.Session,
    logger: FilteringBoundLogger,
    resume: MentionResumeConfig | None,
    resumable_source_manager: ResumableSourceManager[MentionResumeConfig],
    api_version: str,
) -> Iterator[list[dict[str, Any]]]:
    if resume and resume.next_url:
        url: Optional[str] = resume.next_url
        logger.debug(f"Mention: resuming alerts from cursor {url}")
    else:
        account_id = str(_get_account(session, logger)["id"])
        url = _alerts_list_url(account_id, api_version)

    while url:
        payload = _fetch_page(session, url, logger)
        rows = [_unwrap_alert(row) for row in _rows_from_payload(payload, "alerts", url)]

        # A missing ``_links.more`` marks the end of the collection. An empty page also terminates
        # defensively so a lingering cursor can never produce an infinite loop.
        next_url = _more_url(payload) if rows else None
        if next_url:
            resumable_source_manager.save_state(MentionResumeConfig(next_url=next_url))
        if rows:
            yield rows

        url = next_url


def _fan_out_alert_ids(
    session: requests.Session,
    account_id: str,
    logger: FilteringBoundLogger,
    resume: MentionResumeConfig | None,
) -> tuple[list[str], str | None]:
    if resume and resume.alert_ids is not None:
        logger.debug(
            f"Mention: resuming fan-out with {len(resume.alert_ids)} alerts remaining, cursor {resume.next_url}"
        )
        return list(resume.alert_ids), resume.next_url
    return _list_all_alert_ids(session, account_id, logger), None


def _alert_tag_rows(
    session: requests.Session,
    logger: FilteringBoundLogger,
    resume: MentionResumeConfig | None,
    resumable_source_manager: ResumableSourceManager[MentionResumeConfig],
) -> Iterator[list[dict[str, Any]]]:
    account_id = str(_get_account(session, logger)["id"])
    alert_ids, _ = _fan_out_alert_ids(session, account_id, logger, resume)

    while alert_ids:
        alert_id = alert_ids[0]
        # The tags endpoint is not paginated (its ``_links`` is an empty list in the docs).
        url = _list_url(f"/accounts/{account_id}/alerts/{alert_id}/tags", limit=None)
        payload = _fetch_page(session, url, logger)
        rows = _rows_from_payload(payload, "tags", url)
        for row in rows:
            row["alert_id"] = alert_id

        alert_ids = alert_ids[1:]
        resumable_source_manager.save_state(MentionResumeConfig(alert_ids=alert_ids))
        if rows:
            yield rows
        else:
            resumable_source_manager.safe_point()


def _paginated_alert_fan_out_rows(
    session: requests.Session,
    logger: FilteringBoundLogger,
    resume: MentionResumeConfig | None,
    resumable_source_manager: ResumableSourceManager[MentionResumeConfig],
    path: str,
    key: str,
) -> Iterator[list[dict[str, Any]]]:
    account_id = str(_get_account(session, logger)["id"])
    alert_ids, next_url = _fan_out_alert_ids(session, account_id, logger, resume)

    while alert_ids:
        alert_id = alert_ids[0]
        url: Optional[str] = next_url or _list_url(f"/accounts/{account_id}/alerts/{alert_id}/{path}")

        while url:
            payload = _fetch_page(session, url, logger)
            rows = _rows_from_payload(payload, key, url)
            for row in rows:
                row["alert_id"] = alert_id

            more = _more_url(payload) if rows else None
            if more:
                resumable_source_manager.save_state(MentionResumeConfig(alert_ids=alert_ids, next_url=more))
            else:
                resumable_source_manager.save_state(MentionResumeConfig(alert_ids=alert_ids[1:]))

            if rows:
                yield rows
            else:
                resumable_source_manager.safe_point()
            url = more

        alert_ids = alert_ids[1:]
        next_url = None


@frozen
class StatsWindow:
    start: str
    end: str


def _stats_window(now: datetime) -> StatsWindow:
    start = (now - timedelta(days=STATS_LOOKBACK_DAYS)).replace(hour=0, minute=0, second=0, microsecond=0)
    return StatsWindow(start=start.strftime(STATS_DATE_FORMAT), end=now.strftime(STATS_DATE_FORMAT))


def _stats_url(account_id: str, alert_id: str, window: StatsWindow) -> str:
    params = {
        "alerts[]": alert_id,
        "from": window.start,
        "to": window.end,
        "timezone": "UTC",
        "interval": "P1D",
        "tones_per_interval_stats": "true",
        "reach_per_interval_stats": "true",
    }
    return f"{MENTION_BASE_URL}/accounts/{account_id}/stats?{urlencode(params)}"


def _series(alert_stats: dict[str, Any], name: str) -> dict[str, Any]:
    series = alert_stats.get(name)
    data = series.get("data") if isinstance(series, dict) else None
    return data if isinstance(data, dict) else {}


def _daily_stats_rows(alert_id: str, alert_stats: dict[str, Any]) -> list[dict[str, Any]]:
    mentions = _series(alert_stats, "mentions_per_interval")
    tones = _series(alert_stats, "tones_per_interval")
    reach = {
        column: _series(alert_stats, f"{column}_per_interval")
        for column in ("direct_reach", "cumulative_reach", "domain_reach")
    }

    rows: list[dict[str, Any]] = []
    for date in sorted({*mentions, *tones, *(d for series in reach.values() for d in series)}):
        day_tones = tones.get(date)
        day_tones = day_tones if isinstance(day_tones, dict) else {}
        rows.append(
            {
                "alert_id": alert_id,
                "date": date,
                "mentions": mentions.get(date),
                # Tone keys are "-1", "0" and "1"; named columns are easier to query.
                "negative_mentions": day_tones.get("-1"),
                "neutral_mentions": day_tones.get("0"),
                "positive_mentions": day_tones.get("1"),
                **{column: series.get(date) for column, series in reach.items()},
            }
        )
    return rows


def _alert_daily_stats_rows(
    session: requests.Session,
    logger: FilteringBoundLogger,
    resume: MentionResumeConfig | None,
    resumable_source_manager: ResumableSourceManager[MentionResumeConfig],
) -> Iterator[list[dict[str, Any]]]:
    account_id = str(_get_account(session, logger)["id"])
    alert_ids, _ = _fan_out_alert_ids(session, account_id, logger, resume)
    window = _stats_window(datetime.now(UTC))

    while alert_ids:
        alert_id = alert_ids[0]
        url = _stats_url(account_id, alert_id, window)
        payload = _fetch_page(session, url, logger)
        if payload.get("partial"):
            # Mention is still generating the stats and asks callers to try again later.
            raise MentionRetryableError(f"Mention returned partial stats for alert {alert_id}")

        stats = payload.get("stats")
        alert_stats = stats.get(alert_id) if isinstance(stats, dict) else None
        rows = _daily_stats_rows(alert_id, alert_stats) if isinstance(alert_stats, dict) else []

        alert_ids = alert_ids[1:]
        resumable_source_manager.save_state(MentionResumeConfig(alert_ids=alert_ids))
        if rows:
            yield rows
        else:
            resumable_source_manager.safe_point()


def get_rows(
    access_token: str,
    endpoint: str,
    logger: FilteringBoundLogger,
    resumable_source_manager: ResumableSourceManager[MentionResumeConfig],
    api_version: str,
) -> Iterator[list[dict[str, Any]]]:
    session = make_tracked_session(headers=_headers(access_token, api_version), redact_values=(access_token,))
    resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None

    if endpoint == "accounts":
        yield from _account_rows(session, logger)
    elif endpoint == "alerts":
        yield from _alert_rows(session, logger, resume, resumable_source_manager, api_version)
    elif endpoint == "alert_tags":
        yield from _alert_tag_rows(session, logger, resume, resumable_source_manager)
    elif endpoint == "mentions":
        yield from _paginated_alert_fan_out_rows(
            session, logger, resume, resumable_source_manager, path="mentions", key="mentions"
        )
    elif endpoint == "alert_authors":
        yield from _paginated_alert_fan_out_rows(
            session, logger, resume, resumable_source_manager, path="authors", key="authors"
        )
    elif endpoint == "alert_tasks":
        yield from _paginated_alert_fan_out_rows(
            session, logger, resume, resumable_source_manager, path="tasks", key="tasks"
        )
    elif endpoint == "alert_daily_stats":
        yield from _alert_daily_stats_rows(session, logger, resume, resumable_source_manager)
    else:
        raise ValueError(f"Unknown Mention endpoint '{endpoint}'")


def mention_source(
    access_token: str,
    endpoint: str,
    logger: FilteringBoundLogger,
    resumable_source_manager: ResumableSourceManager[MentionResumeConfig],
    api_version: str,
) -> SourceResponse:
    config = MENTION_ENDPOINTS[endpoint]

    return SourceResponse(
        name=endpoint,
        items=lambda: get_rows(
            access_token=access_token,
            endpoint=endpoint,
            logger=logger,
            resumable_source_manager=resumable_source_manager,
            api_version=api_version,
        ),
        primary_keys=config.primary_keys,
        partition_count=1,
        partition_size=1,
    )


def check_access(
    access_token: str, path: str = DEFAULT_PROBE_PATH, api_version: str = DEFAULT_API_VERSION
) -> tuple[int, Optional[str]]:
    """Probe a single endpoint to validate the access token.

    Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
    connection problem, other HTTP status otherwise.
    """
    session = make_tracked_session(headers=_headers(access_token, api_version), redact_values=(access_token,))
    try:
        response = session.get(f"{MENTION_BASE_URL}{path}", timeout=15)
    except Exception as e:
        return 0, f"Could not connect to Mention: {e}"

    if response.status_code in (401, 403):
        return response.status_code, None

    if not response.ok:
        return response.status_code, f"Mention returned HTTP {response.status_code}"

    return 200, None


def validate_credentials(access_token: str, api_version: str = DEFAULT_API_VERSION) -> tuple[bool, str | None]:
    status, message = check_access(access_token, api_version=api_version)
    if status == 200:
        return True, None
    if status in (401, 403):
        return False, "Invalid Mention access token"
    return False, message or "Could not validate Mention access token"