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.

23.5 KB
Raw Blame
import time
import hashlib
import datetime
import dataclasses
from collections.abc import AsyncIterable, Callable, Iterable, Iterator
from typing import Any, Optional, cast

from django.core.cache import cache

import orjson
import pyarrow as pa
import requests
import structlog
from asgiref.sync import async_to_sync
from requests import Request, Response
from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
from tenacity.stop import stop_base

from products.warehouse_sources.sources.sdk import (
    BasePaginator,
    BearerTokenAuth,
    EndpointResource,
    RESTAPIConfig,
    ResumableSourceManager,
    SortMode,
    SourceResponse,
    WebhookSourceManager,
    make_tracked_session,
    rest_api_resource,
    slack_request,
)
from products.warehouse_sources.sources.sdk.internals import table_from_py_list
from products.warehouse_sources.sources.slack.settings import ENDPOINTS, messages_endpoint_config

logger = structlog.get_logger(__name__)


@dataclasses.dataclass
class SlackResumeConfig:
    channel_id: str
    next_cursor: str
    oldest_ts: str | None = None


class SlackRetryableError(Exception):
    def __init__(self, message: str, retry_after: int | None = None):
        super().__init__(message)
        self.retry_after = retry_after


def _wait_with_retry_after(retry_state: RetryCallState) -> float:
    exception = retry_state.outcome and retry_state.outcome.exception()
    if isinstance(exception, SlackRetryableError) and exception.retry_after is not None:
        return float(exception.retry_after)
    return wait_exponential_jitter(initial=1, max=30)(retry_state)


@retry(
    retry=retry_if_exception_type(
        (SlackRetryableError, requests.exceptions.ConnectionError, requests.exceptions.Timeout)
    ),
    stop=stop_after_attempt(5),
    wait=_wait_with_retry_after,
    reraise=True,
)
def _slack_get(url: str, **kwargs: Any) -> requests.Response:
    response = slack_request(
        "GET",
        url,
        source="warehouse",
        endpoint=url.rsplit("/", 1)[-1],
        app_id="warehouse_source",
        session=make_tracked_session(),
        **kwargs,
    )
    if response.status_code == 429:
        retry_after = int(response.headers.get("Retry-After", 1))
        logger.warning("Slack API rate limited", url=url, retry_after=retry_after)
        raise SlackRetryableError("Slack: rate limited", retry_after=retry_after)
    if response.status_code >= 500:
        raise SlackRetryableError(f"Slack: server error {response.status_code}")
    return response


@retry(
    retry=retry_if_exception_type(
        (SlackRetryableError, requests.exceptions.ConnectionError, requests.exceptions.Timeout)
    ),
    stop=stop_after_attempt(5),
    wait=_wait_with_retry_after,
    reraise=True,
)
def _slack_post(url: str, **kwargs: Any) -> requests.Response:
    response = slack_request(
        "POST",
        url,
        source="warehouse",
        endpoint=url.rsplit("/", 1)[-1],
        app_id="warehouse_source",
        session=make_tracked_session(),
        **kwargs,
    )
    if response.status_code == 429:
        retry_after = int(response.headers.get("Retry-After", 1))
        logger.warning("Slack API rate limited", url=url, retry_after=retry_after)
        raise SlackRetryableError("Slack: rate limited", retry_after=retry_after)
    if response.status_code >= 500:
        raise SlackRetryableError(f"Slack: server error {response.status_code}")
    return response


class SlackCursorPaginator(BasePaginator):
    def update_state(self, response: Response, data: list[Any] | None = None) -> None:
        res = response.json()

        self._next_cursor = None

        if not res or not res.get("ok"):
            error = (res or {}).get("error", "unknown_error")
            raise Exception(f"Slack API error: {error}")

        next_cursor = res.get("response_metadata", {}).get("next_cursor", "")

        if next_cursor:
            self._next_cursor = next_cursor
            self._has_next_page = True
        else:
            self._has_next_page = False

    def update_request(self, request: Request) -> None:
        if self._next_cursor:
            request.params = {**(request.params or {}), "cursor": self._next_cursor}


def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResource:
    if name == "$users":
        return {
            "name": "$users",
            "table_name": "$users",
            "write_disposition": "replace",
            "endpoint": {
                "data_selector": "members",
                "path": "users.list",
                "params": {
                    "limit": 999,
                },
            },
            "table_format": "delta",
        }

    raise ValueError(f"Unknown Slack resource: {name}")


_CHANNELS_PAGE_SIZE = 200
_CHANNELS_MAX_PAGES = 50


def _fetch_channels_page(
    url: str, access_token: str, params: dict[str, Any]
) -> tuple[list[dict[str, Any]], str | None]:
    headers = {"Authorization": f"Bearer {access_token}"}
    response = _slack_get(url, headers=headers, params=params, timeout=10)
    response.raise_for_status()
    data = response.json()

    if not data.get("ok"):
        error = data.get("error", "unknown_error")
        raise Exception(f"Slack API error fetching channels: {error}")

    next_cursor = data.get("response_metadata", {}).get("next_cursor", "") or None
    return data.get("channels", []), next_cursor


def _fetch_channels_by_type(
    access_token: str, channel_type: str, authed_user: str | None = None
) -> list[dict[str, Any]]:
    # For private channels, use users.conversations scoped to the installer so we only
    # surface channels the installer is in.
    use_users_conversations = channel_type == "private_channel"
    url = (
        "https://slack.com/api/users.conversations"
        if use_users_conversations
        else "https://slack.com/api/conversations.list"
    )
    channels: list[dict[str, Any]] = []
    cursor: str | None = None

    for _ in range(_CHANNELS_MAX_PAGES):
        params: dict[str, Any] = {
            "types": channel_type,
            "limit": _CHANNELS_PAGE_SIZE,
            "exclude_archived": "false",
        }
        if use_users_conversations and authed_user:
            params["user"] = authed_user
        if cursor:
            params["cursor"] = cursor

        page, cursor = _fetch_channels_page(url, access_token, params)
        channels.extend(page)
        if cursor is None:
            break
    else:
        logger.warning(
            "Slack channel page cap reached; some channels may be missing",
            channel_type=channel_type,
            max_pages=_CHANNELS_MAX_PAGES,
        )

    return channels


def _fetch_all_channels(access_token: str, authed_user: str | None = None) -> list[dict[str, Any]]:
    # Fetch public and private separately — Slack's conversations.list pagination is buggy
    # when public and private types are requested in a single call.
    public = _fetch_channels_by_type(access_token, "public_channel")
    private = _fetch_channels_by_type(access_token, "private_channel", authed_user)
    return public + private


_CHANNELS_CACHE_TTL_SECONDS = 300


def _channels_cache_key(cache_id: str) -> str:
    # Keyed on a stable per-workspace identity — the Integration row PK for the legacy OAuth path,
    # or a hash of the bring-your-own bot token for the manual path (see `manual_cache_id`). Mirrors
    # the convention used by the HogFunctions Slack channel-list cache in posthog.api.integration.
    return f"@dwh/slack/{cache_id}/channels"


def manual_cache_id(access_token: str) -> str:
    """Stable channel-cache identity for a bring-your-own bot token.

    The manual auth path has no Integration row to key the cache on, so we derive a short,
    non-reversible id from the token. It only scopes a 5-minute channel-list cache, so a token
    rotation harmlessly starts a fresh cache entry rather than serving another workspace's data.
    """
    return hashlib.sha256(access_token.encode()).hexdigest()[:16]


def auth_test_user_id(access_token: str) -> str | None:
    """Return the user id `auth.test` reports for a token, or None if the call fails.

    Used by the manual auth path to scope private-channel discovery. For a bot token this is the
    bot's own user id; `users.conversations` then returns the private channels the bot is a member
    of. A failed/invalid token yields None (discovery falls back to unscoped), and credential
    validation surfaces the error separately.
    """
    url = "https://slack.com/api/auth.test"
    headers = {"Authorization": f"Bearer {access_token}"}
    try:
        response = _slack_get(url, headers=headers, timeout=10)
        response.raise_for_status()
        data = response.json()
        if data.get("ok"):
            return data.get("user_id")
    except Exception:
        logger.warning("Slack auth.test failed while resolving authed user", exc_info=True)
    return None


def _fetch_all_channels_cached(
    cache_id: str,
    access_token: str,
    authed_user: str | None = None,
    force_refresh: bool = False,
) -> list[dict[str, Any]]:
    """Cached wrapper around `_fetch_all_channels`.

    Slack's `conversations.list` is Tier 2 (~20 req/min). Workspaces with thousands of
    channels exhaust that budget in a single discovery pass, so callers that don't
    strictly need fresh data should go through this wrapper. Callers that need fresh
    data (e.g. the user-triggered `refresh_schemas` action) should pass
    ``force_refresh=True`` — the upstream call still happens, but the previous value
    stays in cache until the new one is written, so concurrent readers don't pile up
    on a missing key.
    """
    cache_key = _channels_cache_key(cache_id)
    if not force_refresh:
        cached = cache.get(cache_key)
        if cached is not None:
            return cached
    channels = _fetch_all_channels(access_token, authed_user)
    cache.set(cache_key, channels, _CHANNELS_CACHE_TTL_SECONDS)
    return channels


def _fetch_messages_page(
    access_token: str,
    channel_id: str,
    oldest_ts: str | None,
    cursor: str | None,
) -> tuple[list[dict[str, Any]], str | None]:
    """Fetch a single page of messages for a channel. Returns (messages, next_cursor)."""
    url = "https://slack.com/api/conversations.history"
    headers = {"Authorization": f"Bearer {access_token}"}

    params: dict[str, Any] = {
        "channel": channel_id,
        "limit": 999,
    }
    if oldest_ts:
        params["oldest"] = oldest_ts
    if cursor:
        params["cursor"] = cursor

    response = _slack_get(url, headers=headers, params=params, timeout=10)
    response.raise_for_status()
    data = response.json()

    if not data.get("ok"):
        error = data.get("error", "unknown_error")
        raise Exception(f"Slack API error fetching messages for channel {channel_id}: {error}")

    messages = data.get("messages", [])
    for msg in messages:
        msg["channel_id"] = channel_id

    next_cursor = data.get("response_metadata", {}).get("next_cursor", "") or None
    return messages, next_cursor


def _fetch_thread_replies(
    access_token: str,
    channel_id: str,
    thread_ts: str,
) -> Iterator[dict[str, Any]]:
    """Fetch replies for a single thread, excluding the parent message."""
    has_more = True
    cursor: str | None = None
    url = "https://slack.com/api/conversations.replies"
    headers = {"Authorization": f"Bearer {access_token}"}

    while has_more:
        params: dict[str, Any] = {
            "channel": channel_id,
            "ts": thread_ts,
            "limit": 999,
        }
        if cursor:
            params["cursor"] = cursor

        response = _slack_get(url, headers=headers, params=params, timeout=10)
        response.raise_for_status()
        data = response.json()

        if not data.get("ok"):
            error = data.get("error", "unknown_error")
            if error == "thread_not_found":
                logger.info("Thread not found, skipping", channel_id=channel_id, thread_ts=thread_ts)
                return
            raise Exception(f"Slack API error fetching thread replies for {channel_id}/{thread_ts}: {error}")

        for msg in data.get("messages", []):
            # conversations.replies includes the parent message — skip it since it was already yielded by the channel messages page
            if msg.get("ts") == thread_ts and msg.get("thread_ts") == thread_ts:
                continue
            msg["channel_id"] = channel_id
            yield msg

        cursor = data.get("response_metadata", {}).get("next_cursor", "") or None
        has_more = cursor is not None


def get_channels(
    cache_id: str,
    access_token: str,
    authed_user: str | None = None,
    force_refresh: bool = False,
) -> list[dict[str, str]]:
    """Return channel id + name pairs for all accessible channels."""
    return [
        {"id": ch["id"], "name": ch["name"]}
        for ch in _fetch_all_channels_cached(cache_id, access_token, authed_user, force_refresh=force_refresh)
    ]


class _StopBeforeDeadline(stop_base):
    def __init__(self, deadline: float) -> None:
        self.deadline = deadline

    def __call__(self, retry_state: RetryCallState) -> bool:
        return time.monotonic() + (retry_state.upcoming_sleep or 0) >= self.deadline


# conversations.join errors that mean "nothing to do for this channel" rather than a real failure.
_SKIP_JOIN_ERRORS = {"already_in_channel", "is_archived", "method_not_supported_for_channel_type"}


def _join_public_channels(access_token: str, channels: list[dict[str, Any]], deadline: float | None = None) -> int:
    """Join every public channel the bot isn't already in, so their message events reach the webhook.

    ``conversations.join`` only works for public channels — private channels must be invited manually.
    Joins are idempotent (``already_in_channel`` is a no-op) and archived channels are skipped. A
    missing ``channels:join`` scope is surfaced immediately, since it means auto-join can never work.
    Stops once ``time.monotonic()`` passes ``deadline``; a later pass joins the rest.
    Returns the number of channels newly joined.
    """
    url = "https://slack.com/api/conversations.join"
    headers = {"Authorization": f"Bearer {access_token}"}
    post = _slack_post
    if deadline is not None:
        # A rate-limited join waits out Slack's Retry-After, which alone can outlast the budget.
        post = cast(Any, _slack_post).retry_with(stop=stop_after_attempt(5) | _StopBeforeDeadline(deadline))
    joined = 0
    for ch in channels:
        if ch.get("is_private") or ch.get("is_archived") or ch.get("is_member"):
            continue
        if deadline is not None and time.monotonic() >= deadline:
            logger.info("Slack auto-join stopped at its time budget", joined=joined)
            break
        try:
            response = post(url, headers=headers, data={"channel": ch["id"]}, timeout=10)
        except (SlackRetryableError, requests.exceptions.ConnectionError, requests.exceptions.Timeout):
            if deadline is None:
                raise
            logger.info("Slack auto-join stopped before its time budget ran out", joined=joined)
            break
        response.raise_for_status()
        data = response.json()
        if data.get("ok"):
            joined += 1
            continue
        error = data.get("error", "unknown_error")
        if error == "missing_scope":
            raise Exception("missing_scope: your Slack app needs the channels:join scope to auto-join public channels.")
        if error not in _SKIP_JOIN_ERRORS:
            logger.warning("Slack conversations.join failed", channel_id=ch.get("id"), error=error)
    if joined:
        logger.info("Slack auto-joined public channels", joined=joined)
    return joined


def join_public_channels(
    access_token: str,
    cache_id: str,
    authed_user: str | None = None,
    time_budget_seconds: float | None = None,
) -> int:
    """Auto-join all public channels the bot isn't in yet (see ``_join_public_channels``)."""
    deadline = time.monotonic() + time_budget_seconds if time_budget_seconds is not None else None
    channels = _fetch_all_channels_cached(cache_id, access_token, authed_user)
    return _join_public_channels(access_token, channels, deadline)


def _add_timestamp(msg: dict[str, Any]) -> dict[str, Any]:
    ts = msg.get("ts")
    if ts:
        msg["timestamp"] = datetime.datetime.fromtimestamp(float(ts), tz=datetime.UTC).isoformat()
    return msg


def _channel_messages_generator(
    access_token: str,
    channel_id: str,
    resumable_source_manager: ResumableSourceManager[SlackResumeConfig],
    oldest_ts: str | None = None,
) -> Iterator[dict[str, Any]]:
    cursor: str | None = None
    effective_oldest_ts = oldest_ts

    # Only honor state scoped to this channel — guards against reuse of a job_id across schemas.
    resume_config = resumable_source_manager.load_state()
    if resume_config is not None and resume_config.channel_id == channel_id:
        cursor = resume_config.next_cursor
        effective_oldest_ts = resume_config.oldest_ts

    has_more = True
    while has_more:
        messages, next_cursor = _fetch_messages_page(
            access_token, channel_id, oldest_ts=effective_oldest_ts, cursor=cursor
        )

        for msg in messages:
            yield _add_timestamp(msg)
            if msg.get("reply_count", 0) > 0:
                for reply in _fetch_thread_replies(access_token, channel_id, msg["ts"]):
                    yield _add_timestamp(reply)

        cursor = next_cursor
        has_more = cursor is not None

        if cursor is not None:
            # Checkpoint: all messages on this page and their thread replies have been yielded.
            # On resume we start from next_cursor, so no duplication of parent messages.
            resumable_source_manager.save_state(
                SlackResumeConfig(
                    channel_id=channel_id,
                    next_cursor=cursor,
                    oldest_ts=effective_oldest_ts,
                )
            )


def _webhook_table_transformer(table: pa.Table) -> pa.Table:
    if "event" not in table.column_names:
        return table_from_py_list([])
    event_col = table.column("event").to_pylist()

    # Deduplicate by (ts, channel) — Slack retries delivery on timeout, so the same
    # message event can arrive more than once within a single sync batch.
    seen: set[tuple[str, str]] = set()
    rows = []
    for event_data in event_col:
        if event_data is None:
            continue
        event: dict[str, Any] = orjson.loads(event_data) if isinstance(event_data, (str, bytes)) else dict(event_data)
        channel = event.get("channel", "")
        ts = event.get("ts")
        # The warehouse partitions on `timestamp`, so a row without `ts` is unusable.
        # Slack guarantees every `message.channels` / `message.groups` event carries one,
        # so a missing value indicates a malformed payload or upstream change — surface
        # it loudly rather than write rows that can never be queried correctly.
        if not ts:
            raise ValueError(f"Slack webhook event for channel {channel!r} is missing required `ts`")
        key = (ts, channel)
        if key in seen:
            continue
        seen.add(key)
        event["channel_id"] = channel
        event["timestamp"] = datetime.datetime.fromtimestamp(float(ts), tz=datetime.UTC).isoformat()
        rows.append(event)
    return table_from_py_list(rows)


def slack_source(
    access_token: str,
    cache_id: str,
    endpoint: str,
    team_id: int,
    job_id: str,
    webhook_source_manager: WebhookSourceManager,
    resumable_source_manager: ResumableSourceManager[SlackResumeConfig],
    should_use_incremental_field: bool = False,
    db_incremental_field_last_value: Optional[Any] = None,
    incremental_field: str | None = None,
    channel_id: str | None = None,
    authed_user: str | None = None,
) -> SourceResponse:
    items: Callable[[], Iterable[Any] | AsyncIterable[Any]]
    sort_mode: SortMode = "asc"
    webhook_only = False

    if endpoint == "$channels":
        # Bypass rest_api_resource: Slack's conversations.list pagination is buggy when
        # public+private types are mixed, so we walk public and private separately and
        # scope private channels to the installer (matches get_schemas behavior).
        endpoint_config = ENDPOINTS[endpoint]
        items = lambda: iter(_fetch_all_channels_cached(cache_id, access_token, authed_user))
    elif endpoint in ENDPOINTS:
        # $users — served via the generic REST framework
        endpoint_config = ENDPOINTS[endpoint]
        config: RESTAPIConfig = {
            "client": {
                "base_url": "https://slack.com/api/",
                "auth": BearerTokenAuth(token=access_token),
                "paginator": SlackCursorPaginator(),
            },
            "resource_defaults": {
                "write_disposition": "replace",
            },
            "resources": [get_resource(endpoint, should_use_incremental_field)],
        }

        resource = rest_api_resource(config, team_id, job_id, None)
        items = lambda: resource
    else:
        # Per-channel message endpoint.
        #
        # Slack channel tables are webhook-only: we deliberately skip the historical
        # `conversations.history` / `conversations.replies` backfill. That backfill makes one
        # `conversations.replies` request per threaded message, which fans out into tens of
        # thousands of rate-limited requests on workspaces with many channels and threads.
        # Passing `webhook_only=True` activates webhook mode from the very first sync and keeps
        # a requested pipeline reset from wiping the table (the same pattern the Customer.io
        # webhook tables use). Until the webhook is configured and delivering events, the table
        # stays empty rather than backfilling history.
        endpoint_config = messages_endpoint_config()
        sort_mode = "desc"
        webhook_only = True

        if channel_id is None:
            raise Exception(f"channel_not_found: {endpoint}")

        webhook_enabled = async_to_sync(webhook_source_manager.webhook_enabled)(webhook_only=True)

        def channel_items() -> Iterable[Any] | AsyncIterable[Any]:
            if webhook_enabled:
                return webhook_source_manager.get_items(table_transformer=_webhook_table_transformer)
            return iter([])

        items = channel_items

    return SourceResponse(
        name=endpoint,
        items=items,
        primary_keys=endpoint_config.primary_keys,
        partition_keys=endpoint_config.partition_keys,
        partition_mode=endpoint_config.partition_mode,
        partition_format=endpoint_config.partition_format,
        sort_mode=sort_mode,
        webhook_only=webhook_only,
    )


def validate_credentials(access_token: str) -> tuple[bool, str | None]:
    """Check a Slack token via ``auth.test``.

    Returns ``(is_valid, error_code)``. On rejection ``error_code`` is Slack's own error
    (for example ``invalid_auth`` or ``missing_scope``) so the caller can explain the exact
    problem instead of a generic "invalid credentials". It is ``None`` when the check couldn't
    complete (network error or an exhausted rate-limit/5xx retry), letting the caller tell a
    rejected token apart from an unreachable Slack.
    """
    url = "https://slack.com/api/auth.test"
    headers = {"Authorization": f"Bearer {access_token}"}

    try:
        response = _slack_get(url, headers=headers, timeout=10)
        response.raise_for_status()
        data = response.json()
    except Exception:
        return False, None

    if data.get("ok", False):
        return True, None
    return False, data.get("error") or None