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.

feat(warehouse_sources): add Ably channels, messages, and presence tables (#97643)

Tom Owers173985bb6274
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index c3be7feb1697..d85c04425a3a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -21,14 +21,14 @@ each is the auditing agent's reasoning and occasionally over-claims, so re-deriv
## Ably — **thin**
-Today (1): `Stats`
+Today (4): `ChannelMessages`, `Channels`, `Presence`, `Stats`
Diffed against: <https://raw.githubusercontent.com/ably/open-specs/main/definitions/platform-v1.yaml>
- [ ] `apps (Control API GET /accounts/{account_id}/apps)` — lookup table resolving the app IDs every Stats row is scoped to (high)
-- [ ] `channels (GET /channels)` — channel enumeration with per-channel occupancy/connection/publisher counts (high)
-- [ ] `channel messages history (GET /channels/{channel_id}/messages)` — the actual message event stream, not just aggregated stats (high)
-- [ ] `presence (GET /channels/{channel_id}/presence)` — current members per channel for concurrency analysis (medium)
+- [x] `channels (GET /channels)` — channel enumeration with per-channel occupancy/connection/publisher counts (high)
+- [x] `channel messages history (GET /channels/{channel_id}/messages)` — the actual message event stream, not just aggregated stats (high)
+- [x] `presence (GET /channels/{channel_id}/presence)` — current members per channel for concurrency analysis (medium)
- [ ] `presence history (GET /channels/{channel_id}/presence/history)` — enter/leave transition history per channel (medium)
- [ ] `push device registrations (GET /push/deviceRegistrations)` — device inventory backing push delivery stats (medium)
- [ ] `push channel subscriptions (GET /push/channelSubscriptions)` — membership table linking devices to channels (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/ably.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/ably.py
index 1ae01a6f62c7..92563396e90c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/ably.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/ably.py
@@ -1,22 +1,34 @@
import time
-import dataclasses
+from collections.abc import Callable, Iterable, Iterator
from datetime import UTC, datetime
from typing import Any, Optional
+from urllib.parse import quote
from requests.exceptions import RequestException
-from products.warehouse_sources.backend.temporal.data_imports.sources.ably.settings import BASE_URL, MAX_LIMIT
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.ably.settings import (
+ ABLY_ENDPOINTS,
+ BASE_URL,
+ AblyEndpointConfig,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
Endpoint,
EndpointResource,
IncrementalConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
# Ably REST protocol version, sent via the `X-Ably-Version` header. The legacy label
# (`UNVERSIONED_API_VERSION`, "v1") predates this source declaring a version and maps to *no*
@@ -39,9 +51,14 @@ def version_header(api_version: str) -> dict[str, str]:
return {"X-Ably-Version": value} if value else {}
+@frozen
class AblyResumeConfig:
- next_url: str
+ # `/stats` and `/channels` are flat listings, so their resume state is the next page URL.
+ next_url: Optional[str] = None
+ # Channel-scoped endpoints fan out over `/channels`, whose resume state is the shape
+ # `build_dependent_resource` checkpoints: which parents finished and where the current one
+ # stopped.
+ fanout_state: Optional[dict[str, Any]] = None
def split_api_key(api_key: str) -> tuple[str, str]:
@@ -81,47 +98,146 @@ def _parse_interval_start(interval_id: Optional[str]) -> Optional[datetime]:
return None
-def get_resource(unit: str, should_use_incremental_field: bool) -> EndpointResource:
- endpoint: Endpoint = {
- "path": "/stats",
- "paginator": "header_link",
- "params": {
- "unit": unit,
- "direction": "forwards",
- "limit": MAX_LIMIT,
+def _add_channel_path(row: dict[str, Any]) -> dict[str, Any]:
+ """Derive the path segment the channel-scoped endpoints are addressed by.
+
+ Ably channel names commonly carry separators (`chat:room1`, `user/42/inbox`), and the
+ fan-out substitutes the value into `/channels/{channel_id}/...` with `str.format`, which
+ escapes nothing. An unencoded `/` would address a different path, so encode every reserved
+ character here.
+ """
+ channel_id = row.get("channelId")
+ if isinstance(channel_id, str):
+ row["channel_path"] = quote(channel_id, safe="")
+ return row
+
+
+def _add_message_time(row: dict[str, Any]) -> dict[str, Any]:
+ """Derive an ISO datetime from the Unix ms `timestamp`, because partitioning wants an actual
+ datetime-typed column. The raw `timestamp` stays as the incremental cursor, since that is the
+ unit Ably's `start`/`end` history params take."""
+ timestamp = row.get("timestamp")
+ row["message_time"] = (
+ datetime.fromtimestamp(timestamp / 1000, tz=UTC).isoformat() if isinstance(timestamp, int) else None
+ )
+ return row
+
+
+# Applied per row on the fan-out children, which build their resource through the shared helper
+# and so cannot carry a resource-level `data_map` of their own.
+_CHILD_ROW_MAPS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {
+ "ChannelMessages": _add_message_time,
+}
+
+
+def _map_pages(
+ pages: Iterable[list[dict[str, Any]]], mapper: Callable[[dict[str, Any]], dict[str, Any]]
+) -> Iterator[list[dict[str, Any]]]:
+ for page in pages:
+ yield [mapper(row) for row in page]
+
+
+def _incremental_window(cursor_path: str) -> IncrementalConfig:
+ """Both incremental endpoints take a Unix-ms `start`/`end` pair and count from the epoch.
+
+ Ably has no open-ended "everything since X" mode, so every request needs an explicit end.
+ Bind it to "now" at request-build time (this function runs fresh each sync) rather than
+ relying on the vendor's own end-of-window default.
+ """
+ return {
+ "cursor_path": cursor_path,
+ "start_param": "start",
+ "end_param": "end",
+ "initial_value": "0",
+ "end_value": str(int(time.time() * 1000)),
+ }
+
+
+def _client_config(api_key: str, api_version: str) -> ClientConfig:
+ username, password = split_api_key(api_key)
+ return {
+ "base_url": BASE_URL,
+ "headers": version_header(api_version),
+ "auth": {
+ "type": "http_basic",
+ "username": username,
+ "password": password,
},
+ # Pin every request to BASE_URL's host and refuse redirects: the Basic auth header
+ # carries the Ably key, so a spoofed `Link: rel="next"` target or a cross-origin 3xx
+ # must not carry that credential off-host (SSRF). `allowed_hosts=[]` means "same host
+ # as base_url only" and also pins paginator and resume URLs.
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ "paginator": "header_link",
+ }
+
+
+# Applied as a resource-level `data_map` on the top-level endpoints that derive columns.
+_TOP_LEVEL_ROW_MAPS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {
+ "Stats": _add_interval_start,
+}
+
+
+def get_resource(
+ endpoint: str,
+ unit: str,
+ should_use_incremental_field: bool,
+ incremental_field: Optional[str] = None,
+) -> EndpointResource:
+ """Builds a top-level (non-fan-out) resource. Channel-scoped endpoints fan out from
+ `Channels` and are built via `build_dependent_resource` in `ably_source`."""
+ config = ABLY_ENDPOINTS[endpoint]
+
+ params: dict[str, Any] = {"limit": config.page_size, **config.params}
+ if endpoint == "Stats":
+ params["unit"] = unit
+
+ endpoint_config: Endpoint = {
+ "path": config.path,
+ "paginator": "header_link",
+ "params": params,
"data_selector_required": True,
}
- if should_use_incremental_field:
- incremental_config: IncrementalConfig = {
- "start_param": "start",
- "end_param": "end",
- "initial_value": "0",
- # Ably has no open-ended "everything since X" mode — every request needs an
- # explicit end. Bound it to "now" at request-build time (this function runs
- # fresh each sync) rather than relying on the vendor's own end-of-window default.
- "end_value": str(int(time.time() * 1000)),
- }
- endpoint["incremental"] = incremental_config
+ use_merge = should_use_incremental_field and bool(config.incremental_fields)
+ if use_merge:
+ endpoint_config["incremental"] = _incremental_window(
+ incremental_field or config.default_incremental_field or "id"
+ )
- return {
- "name": "Stats",
- "table_name": "stats",
- "write_disposition": {
- "disposition": "merge",
- "strategy": "upsert",
- }
- if should_use_incremental_field
- else "replace",
- "endpoint": endpoint,
+ resource: EndpointResource = {
+ "name": config.name,
+ "table_name": config.table_name,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if use_merge else "replace",
+ "endpoint": endpoint_config,
"table_format": "delta",
- "data_map": _add_interval_start,
}
+ row_map = _TOP_LEVEL_ROW_MAPS.get(endpoint)
+ if row_map is not None:
+ resource["data_map"] = row_map
+ return resource
+
+
+def _make_source_response(
+ config: AblyEndpointConfig,
+ items: Callable[[], Iterable[Any]],
+ column_hints: Optional[dict[str, Any]] = None,
+) -> SourceResponse:
+ return SourceResponse(
+ name=config.name,
+ items=items,
+ primary_keys=config.primary_key,
+ column_hints=column_hints,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ sort_mode=config.sort_mode,
+ )
def ably_source(
api_key: str,
+ endpoint: str,
unit: str,
team_id: int,
job_id: str,
@@ -129,55 +245,81 @@ def ably_source(
db_incremental_field_last_value: Optional[Any],
api_version: str,
should_use_incremental_field: bool = False,
-):
- username, password = split_api_key(api_key)
+ incremental_field: Optional[str] = None,
+) -> SourceResponse:
+ endpoint_config = ABLY_ENDPOINTS.get(endpoint)
+ if endpoint_config is None:
+ raise ValueError(f"Unknown Ably endpoint: {endpoint}")
- config: RESTAPIConfig = {
- "client": {
- "base_url": BASE_URL,
- "headers": version_header(api_version),
- "auth": {
- "type": "http_basic",
- "username": username,
- "password": password,
- },
- # Pin every request to BASE_URL's host and refuse redirects: the Basic auth header
- # carries the Ably key, so a spoofed `Link: rel="next"` target or a cross-origin 3xx
- # must not carry that credential off-host (SSRF). `allowed_hosts=[]` means "same host
- # as base_url only" and also pins paginator and resume URLs.
- "allowed_hosts": [],
- "allow_redirects": False,
- "paginator": "header_link",
- },
- "resource_defaults": {
- "write_disposition": {
- "disposition": "merge",
- "strategy": "upsert",
- }
- if should_use_incremental_field
- else "replace",
- },
- "resources": [get_resource(unit, should_use_incremental_field)],
- }
+ client_config = _client_config(api_key, api_version)
+ resume_state = _load_resume_state(resumable_source_manager)
+
+ if endpoint_config.fanout is not None:
+ child = build_dependent_resource(
+ endpoint_configs=ABLY_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=endpoint_config.fanout,
+ client_config=client_config,
+ parent_data_map=_add_channel_path,
+ parent_endpoint_extra={"data_selector_required": True},
+ child_endpoint_extra={"data_selector_required": True},
+ child_params_extra=dict(endpoint_config.params),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ incremental_config_factory=_incremental_window,
+ resume_hook=lambda state: _save_fanout_state(resumable_source_manager, state),
+ initial_paginator_state=resume_state.fanout_state if resume_state else None,
+ )
+ row_map = _CHILD_ROW_MAPS.get(endpoint)
- initial_paginator_state: Optional[dict[str, Any]] = None
- if resumable_source_manager.can_resume():
- resume_config = resumable_source_manager.load_state()
- if resume_config is not None:
- initial_paginator_state = {"next_url": resume_config.next_url}
+ def child_items() -> Iterable[Any]:
+ return _map_pages(child, row_map) if row_map else child
- def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
- if state and state.get("next_url"):
- resumable_source_manager.save_state(AblyResumeConfig(next_url=str(state["next_url"])))
+ return _make_source_response(endpoint_config, child_items)
- return rest_api_resource(
+ config: RESTAPIConfig = {
+ "client": client_config,
+ "resource_defaults": {},
+ "resources": [get_resource(endpoint, unit, should_use_incremental_field, incremental_field)],
+ }
+
+ resource = rest_api_resource(
config,
team_id,
job_id,
db_incremental_field_last_value,
- resume_hook=save_checkpoint,
- initial_paginator_state=initial_paginator_state,
+ resume_hook=lambda state: _save_next_url(resumable_source_manager, state),
+ initial_paginator_state=(
+ {"next_url": resume_state.next_url} if resume_state and resume_state.next_url else None
+ ),
)
+ return _make_source_response(endpoint_config, lambda: resource, resource.column_hints)
+
+
+def _load_resume_state(
+ resumable_source_manager: ResumableSourceManager[AblyResumeConfig],
+) -> Optional[AblyResumeConfig]:
+ if not resumable_source_manager.can_resume():
+ return None
+ return resumable_source_manager.load_state()
+
+
+def _save_next_url(
+ resumable_source_manager: ResumableSourceManager[AblyResumeConfig], state: Optional[dict[str, Any]]
+) -> None:
+ if state and state.get("next_url"):
+ resumable_source_manager.save_state(AblyResumeConfig(next_url=str(state["next_url"])))
+
+
+def _save_fanout_state(
+ resumable_source_manager: ResumableSourceManager[AblyResumeConfig], state: Optional[dict[str, Any]]
+) -> None:
+ if state:
+ resumable_source_manager.save_state(AblyResumeConfig(fanout_state=state))
def validate_credentials(api_key: str, api_version: str) -> tuple[bool, str | None]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/canonical_descriptions.py
index 074e2678e1cb..fdbf2691fcdf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/canonical_descriptions.py
@@ -1,7 +1,7 @@
"""Canonical, documentation-sourced descriptions for Ably endpoints and columns.
-Sourced from the official Ably REST API reference (https://ably.com/docs/api/rest-api#stats and
-https://ably.com/docs/metadata-stats/stats). Keyed by the resource names in `settings.py`
+Sourced from the official Ably REST API reference (https://ably.com/docs/api/rest-api) and the
+Ably platform OpenAPI definition. Keyed by the resource names in `settings.py`
`ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced Ably table. Columns absent
here fall back to LLM enrichment.
"""
@@ -34,4 +34,47 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"pushNotifications": "Count of push notifications sent, broken down by outcome (succeeded/failed/invalid).",
},
},
+ "Channels": {
+ "description": "Metadata for every channel currently active in the Ably app, including "
+ "the occupancy counts of connections attached to it.",
+ "docs_url": "https://ably.com/docs/metadata-stats/metadata/rest",
+ "columns": {
+ "channelId": "Name of the channel, including its namespace qualifier if it has one.",
+ "region": "Region the reported activity was observed in, when the record is region-scoped.",
+ "isGlobalMaster": "Whether this region coordinates the channel globally.",
+ "status": "Channel status: whether the channel is active, and its occupancy breakdown.",
+ },
+ },
+ "ChannelMessages": {
+ "description": "Messages published to a channel and retained by Ably's history feature. "
+ "Ably keeps messages for two minutes unless persistence is enabled for the channel.",
+ "docs_url": "https://ably.com/docs/storage-history/history",
+ "columns": {
+ "id": "Unique identifier for the message. A publisher can supply its own for idempotent publishing.",
+ "channel_id": "Name of the channel the message was published to.",
+ "name": "Event name the message was published under, if the publisher set one.",
+ "data": "Message payload, encoded as described by `encoding`.",
+ "encoding": "Transformations still to apply to `data`. Usually empty.",
+ "clientId": "Client ID of the publisher, for identified clients.",
+ "connectionId": "Connection ID of the publisher.",
+ "timestamp": "Time Ably received the message, as milliseconds since the epoch.",
+ "message_time": "UTC time Ably received the message, derived from `timestamp`.",
+ "extras": "Extra fields carried with the message, such as push notification payloads.",
+ },
+ },
+ "Presence": {
+ "description": "Members currently present on each channel, one row per member.",
+ "docs_url": "https://ably.com/docs/presence-occupancy/presence",
+ "columns": {
+ "id": "Unique identifier Ably assigned to this presence update.",
+ "channel_id": "Name of the channel the member is present on.",
+ "action": "Presence event this record represents: ABSENT, PRESENT, ENTER, LEAVE, or UPDATE.",
+ "data": "Presence payload the member entered with, if any.",
+ "clientId": "Client ID of the member.",
+ "connectionId": "Connection ID the member is present through.",
+ "timestamp": "Time Ably received the presence update, as milliseconds since the epoch.",
+ "encoding": "Transformations still to apply to `data`. Usually empty.",
+ "extras": "Extra fields carried with the presence update.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/settings.py
index a787a3fc9482..0c79f60dc68b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/settings.py
@@ -1,38 +1,131 @@
-from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+from dataclasses import field
+from typing import Literal
-ENDPOINTS = ("Stats",)
+from posthog.dataclasses import frozen
-PRIMARY_KEYS: dict[str, list[str]] = {
- # `intervalId` is unique within a single granularity (`unit`), but the source only ever
- # syncs one selected unit at a time — `unit` is included defensively in case that changes.
- "Stats": ["unit", "intervalId"],
-}
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-# `interval_start_ms` (Unix ms) is derived from `intervalId` (see `_add_interval_start` in
-# ably.py) — Ably's own `intervalId` is a granularity-dependent string ("2024-01-15:14:05" for
-# minute, "2024-01-15:14" for hour, etc), not directly usable as the `start`/`end` stats params,
-# which take Unix ms. Using the same unit here means the watermark from one sync feeds straight
-# back into the next sync's `start` param with no reformatting.
-INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
- "Stats": [
- {
- "label": "Interval start",
- "type": IncrementalFieldType.DateTime,
- "field": "interval_start_ms",
- "field_type": IncrementalFieldType.Integer,
- },
- ],
-}
+BASE_URL = "https://main.realtime.ably.net"
-# `interval_start` (ISO datetime string, also derived from `intervalId`) is used for partitioning
-# instead of `interval_start_ms` — partitioning wants an actual datetime-typed column.
-PARTITION_KEY = "interval_start"
+# Ably caps page size at 1000 (default 100) on /stats, /channels, history and presence.
+MAX_LIMIT = 1000
# https://ably.com/docs/api/rest-api#stats
STATS_UNITS = ("minute", "hour", "day", "month")
DEFAULT_STATS_UNIT = "hour"
-# Ably caps /stats page size at 1000 (default 100).
-MAX_LIMIT = 1000
+# `by=value` makes `/channels` return `ChannelDetails` objects instead of bare name strings.
+# The details are what the table is worth syncing for, and the fan-out reads `channelId` from
+# them.
+CHANNEL_LIST_PARAMS = {"by": "value"}
-BASE_URL = "https://main.realtime.ably.net"
+# Every channel-scoped endpoint hangs off `/channels/{channel_id}/...`, so the channel
+# enumeration is the parent they fan out from. `channel_path` is the percent-encoded name that
+# `_add_channel_path` in ably.py derives, because Ably channel names can contain `/` and `:`.
+CHANNEL_FANOUT = DependentEndpointConfig(
+ parent_name="Channels",
+ resolve_param="channel_id",
+ resolve_field="channel_path",
+ include_from_parent=["channelId"],
+ parent_field_renames={"channelId": "channel_id"},
+ parent_params=CHANNEL_LIST_PARAMS,
+)
+
+
+@frozen
+class AblyEndpointConfig:
+ name: str
+ path: str
+ table_name: str
+ params: dict[str, str] = field(default_factory=dict)
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: str | None = None
+ partition_key: str | None = None
+ primary_key: list[str] = field(default_factory=lambda: ["id"])
+ page_size: int = MAX_LIMIT
+ sort_mode: Literal["asc", "desc"] = "asc"
+ fanout: DependentEndpointConfig | None = None
+
+
+ABLY_ENDPOINTS: dict[str, AblyEndpointConfig] = {
+ "Stats": AblyEndpointConfig(
+ name="Stats",
+ path="/stats",
+ table_name="stats",
+ # `direction=forwards` because Ably's stats and history endpoints both default to
+ # newest-first, which would walk the incremental watermark backwards.
+ params={"direction": "forwards"},
+ # `interval_start_ms` (Unix ms) is derived from `intervalId` (see `_add_interval_start` in
+ # ably.py) because Ably's own `intervalId` is a granularity-dependent string
+ # ("2024-01-15:14:05" for minute, "2024-01-15:14" for hour, etc), not directly usable as
+ # the `start`/`end` stats params, which take Unix ms. Using the same unit here means the
+ # watermark from one sync feeds straight back into the next sync's `start` param with no
+ # reformatting.
+ incremental_fields=[
+ {
+ "label": "Interval start",
+ "type": IncrementalFieldType.DateTime,
+ "field": "interval_start_ms",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ default_incremental_field="interval_start_ms",
+ # `interval_start` (ISO datetime string, also derived from `intervalId`) is used for
+ # partitioning instead of `interval_start_ms`, because partitioning wants an actual
+ # datetime-typed column.
+ partition_key="interval_start",
+ # `intervalId` is unique within a single granularity (`unit`), but the source only ever
+ # syncs one selected unit at a time. `unit` is included defensively in case that changes.
+ primary_key=["unit", "intervalId"],
+ ),
+ "Channels": AblyEndpointConfig(
+ name="Channels",
+ path="/channels",
+ table_name="channels",
+ params=CHANNEL_LIST_PARAMS,
+ # A channel is listed only while it is active and its occupancy counts describe that
+ # moment, so there is no timestamp to sync incrementally from. Each run replaces the
+ # snapshot.
+ primary_key=["channelId"],
+ ),
+ "ChannelMessages": AblyEndpointConfig(
+ name="ChannelMessages",
+ path="/channels/{channel_id}/messages",
+ table_name="channel_messages",
+ params={"direction": "forwards"},
+ # `timestamp` is Unix ms, the same unit the `start`/`end` history params take.
+ incremental_fields=[
+ {
+ "label": "Timestamp",
+ "type": IncrementalFieldType.DateTime,
+ "field": "timestamp",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ default_incremental_field="timestamp",
+ # ISO datetime derived from `timestamp` by `_add_message_time` in ably.py.
+ partition_key="message_time",
+ # Ably documents the message id as unique per publish, but a publisher can supply its own
+ # id for idempotent publishing, so uniqueness is only guaranteed within a channel.
+ primary_key=["channel_id", "id"],
+ fanout=CHANNEL_FANOUT,
+ ),
+ "Presence": AblyEndpointConfig(
+ name="Presence",
+ path="/channels/{channel_id}/presence",
+ table_name="presence",
+ # Members currently present, which the API exposes with no time filter. Each run replaces
+ # the snapshot.
+ primary_key=["channel_id", "id"],
+ fanout=CHANNEL_FANOUT,
+ ),
+}
+
+ENDPOINTS = tuple(ABLY_ENDPOINTS)
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in ABLY_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/source.py
index 46c325ee65b8..ecb64dbe0525 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/source.py
@@ -22,8 +22,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.ably.setti
DEFAULT_STATS_UNIT,
ENDPOINTS,
INCREMENTAL_FIELDS,
- PARTITION_KEY,
- PRIMARY_KEYS,
STATS_UNITS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
@@ -61,8 +59,8 @@ class AblySource(ResumableSource[AblySourceConfig, AblyResumeConfig]):
def get_non_retryable_errors(self) -> dict[str, str | None]:
return {
- "401 Client Error": "Ably authentication failed. Please check your API key.",
- "403 Client Error": "Ably authentication failed. Please check your API key.",
+ "401 Client Error": "Ably rejected your API key. Check that the key is valid and has the capability this table needs.",
+ "403 Client Error": "Ably rejected your API key. Check that the key is valid and has the capability this table needs.",
}
def get_canonical_descriptions(self) -> CanonicalDescriptions:
@@ -101,8 +99,9 @@ class AblySource(ResumableSource[AblySourceConfig, AblyResumeConfig]):
resumable_source_manager: ResumableSourceManager[AblyResumeConfig],
inputs: SourceInputs,
) -> SourceResponse:
- resource = ably_source(
+ return ably_source(
api_key=config.api_key,
+ endpoint=inputs.schema_name,
unit=config.unit,
team_id=inputs.team_id,
job_id=inputs.job_id,
@@ -112,15 +111,7 @@ class AblySource(ResumableSource[AblySourceConfig, AblyResumeConfig]):
db_incremental_field_last_value=inputs.db_incremental_field_last_value
if inputs.should_use_incremental_field
else None,
- )
- return SourceResponse(
- name=resource.name,
- items=lambda: resource,
- primary_keys=PRIMARY_KEYS.get(inputs.schema_name, ["id"]),
- column_hints=resource.column_hints,
- partition_mode="datetime",
- partition_keys=[PARTITION_KEY],
- sort_mode="asc",
+ incremental_field=inputs.incremental_field,
)
@property
@@ -131,7 +122,10 @@ class AblySource(ResumableSource[AblySourceConfig, AblyResumeConfig]):
keywords=["realtime", "pubsub", "messaging"],
label="Ably",
caption="Enter your Ably app API key, created in the [Ably dashboard](https://ably.com/dashboard). "
- "The key must include both the key ID and secret (`app-id.key-id:key-secret`).",
+ "The key must include both the key ID and secret (`app-id.key-id:key-secret`).\n\n"
+ "Each table needs a capability on the key: `stats` for Stats, `channel-metadata` for "
+ "Channels and Presence, and `history` for Channel messages. Message history also needs "
+ "persistence turned on for the channel, otherwise Ably keeps messages for two minutes.",
docsUrl="https://posthog.com/docs/cdp/sources/ably",
iconPath="/static/services/ably.png",
releaseStatus=ReleaseStatus.ALPHA,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably.py
index 21d537e88e0d..63cc95f2fbec 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably.py
@@ -1,5 +1,6 @@
import json
-from typing import Any
+from collections.abc import Iterable
+from typing import Any, cast
import pytest
from unittest.mock import MagicMock, patch
@@ -10,7 +11,9 @@ from requests.exceptions import ConnectionError as RequestsConnectionError
from products.warehouse_sources.backend.temporal.data_imports.sources.ably.ably import (
ABLY_VERSION_2,
AblyResumeConfig,
+ _add_channel_path,
_add_interval_start,
+ _add_message_time,
_parse_interval_start,
ably_source,
get_resource,
@@ -20,6 +23,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.ably.ably
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import UNVERSIONED_API_VERSION
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+
+
+def _pages(response: SourceResponse) -> list[list[dict[str, Any]]]:
+ # SourceResponse.items is typed for async sources too; every Ably endpoint is synchronous.
+ return list(cast(Iterable[list[dict[str, Any]]], response.items()))
class TestVersionHeader:
@@ -93,7 +102,7 @@ class TestAddIntervalStart:
class TestGetResource:
def test_full_refresh_has_no_incremental_params(self) -> None:
- resource = get_resource("hour", should_use_incremental_field=False)
+ resource = get_resource("Stats", "hour", should_use_incremental_field=False)
endpoint = resource["endpoint"]
assert isinstance(endpoint, dict)
assert "incremental" not in endpoint
@@ -104,7 +113,7 @@ class TestGetResource:
assert params["direction"] == "forwards"
def test_incremental_sets_start_and_end_params(self) -> None:
- resource = get_resource("day", should_use_incremental_field=True)
+ resource = get_resource("Stats", "day", should_use_incremental_field=True)
endpoint = resource["endpoint"]
assert isinstance(endpoint, dict)
incremental = endpoint["incremental"]
@@ -117,6 +126,47 @@ class TestGetResource:
assert end_value is not None and int(end_value) > 1_700_000_000_000
assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
+ def test_channels_asks_for_details_and_never_merges(self) -> None:
+ # `by=value` is what makes /channels return objects instead of bare name strings, and the
+ # endpoint has no time filter, so an incremental sync request must still write a replace.
+ resource = get_resource("Channels", "hour", should_use_incremental_field=True)
+ endpoint = resource["endpoint"]
+ assert isinstance(endpoint, dict)
+ params = endpoint["params"]
+ assert isinstance(params, dict)
+ assert params["by"] == "value"
+ assert "incremental" not in endpoint
+ assert resource["write_disposition"] == "replace"
+
+
+class TestAddChannelPath:
+ @pytest.mark.parametrize(
+ ("channel_id", "expected"),
+ [
+ ("plain-channel", "plain-channel"),
+ # Ably channel names routinely carry these separators; an unencoded `/` would address
+ # a different path once substituted into /channels/{channel_id}/messages.
+ ("chat:room1", "chat%3Aroom1"),
+ ("user/42/inbox", "user%2F42%2Finbox"),
+ ("with space", "with%20space"),
+ ],
+ )
+ def test_percent_encodes_reserved_characters(self, channel_id: str, expected: str) -> None:
+ assert _add_channel_path({"channelId": channel_id})["channel_path"] == expected
+
+ def test_missing_channel_id_adds_nothing(self) -> None:
+ # The fan-out raises its own error naming the missing field; don't bind an empty path.
+ assert "channel_path" not in _add_channel_path({"status": {}})
+
+
+class TestAddMessageTime:
+ def test_derives_iso_datetime_from_unix_ms(self) -> None:
+ assert _add_message_time({"timestamp": 1705327200000})["message_time"] == "2024-01-15T14:00:00+00:00"
+
+ @pytest.mark.parametrize("timestamp", [None, "1705327200000"])
+ def test_missing_or_non_numeric_timestamp_sets_none(self, timestamp: Any) -> None:
+ assert _add_message_time({"timestamp": timestamp})["message_time"] is None
+
def _make_http_response(body: list[dict[str, Any]], *, next_url: str | None = None, status_code: int = 200) -> Response:
resp = Response()
@@ -149,8 +199,9 @@ class TestAblySourceResumeBehavior:
mock_session.prepare_request.side_effect = lambda req: req
mock_session.send.side_effect = fake_send
- resource = ably_source(
+ response = ably_source(
api_key="app.key:secret",
+ endpoint="Stats",
unit="hour",
team_id=123,
job_id="test_job",
@@ -159,7 +210,7 @@ class TestAblySourceResumeBehavior:
api_version=ABLY_VERSION_2,
should_use_incremental_field=should_use_incremental_field,
)
- pages = list(resource)
+ pages = _pages(response)
return sent_urls, pages
def test_fresh_run_follows_link_header_and_saves_state(self) -> None:
@@ -213,6 +264,170 @@ class TestAblySourceResumeBehavior:
manager.load_state.assert_not_called()
+class TestChannelFanout:
+ """End-to-end behaviour of the channel-scoped endpoints, which fan out over ``/channels``."""
+
+ def _drive(
+ self,
+ endpoint: str,
+ responses: list[Response],
+ *,
+ manager: MagicMock | None = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ ) -> tuple[list[tuple[str, dict[str, Any]]], list[dict[str, Any]]]:
+ if manager is None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ requests: list[tuple[str, dict[str, Any]]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ requests.append((request.url, dict(request.params)))
+ return next(response_iter)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ response = ably_source(
+ api_key="app.key:secret",
+ endpoint=endpoint,
+ unit="hour",
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ api_version=ABLY_VERSION_2,
+ should_use_incremental_field=should_use_incremental_field,
+ )
+ rows = [row for page in _pages(response) for row in page]
+ return requests, rows
+
+ def test_child_path_uses_the_encoded_channel_name(self) -> None:
+ # An unencoded `/` in the channel name would address a different Ably endpoint.
+ requests, rows = self._drive(
+ "ChannelMessages",
+ [
+ _make_http_response([{"channelId": "user/42/inbox", "status": {"isActive": True}}]),
+ _make_http_response([{"id": "msg-1", "timestamp": 1705327200000}]),
+ ],
+ )
+
+ assert [url for url, _ in requests] == [
+ "https://main.realtime.ably.net/channels",
+ "https://main.realtime.ably.net/channels/user%2F42%2Finbox/messages",
+ ]
+ assert rows[0]["channel_id"] == "user/42/inbox"
+ assert rows[0]["message_time"] == "2024-01-15T14:00:00+00:00"
+
+ def test_message_history_is_windowed_and_ordered_forwards(self) -> None:
+ # Ably history defaults to newest-first, which would walk the watermark backwards, and
+ # every request needs an explicit end because there is no open-ended "since X" mode.
+ requests, _ = self._drive(
+ "ChannelMessages",
+ [
+ _make_http_response([{"channelId": "chat", "status": {"isActive": True}}]),
+ _make_http_response([{"id": "msg-1", "timestamp": 1705327200000}]),
+ ],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1705327100000,
+ )
+
+ _, child_params = requests[1]
+ assert child_params["direction"] == "forwards"
+ assert child_params["start"] == 1705327100000
+ assert int(child_params["end"]) > 1_700_000_000_000
+
+ def test_presence_sends_no_time_window_on_an_incremental_run(self) -> None:
+ # Presence reports who is present now and exposes no time filter, so an incremental
+ # request must not grow start/end params the API would reject or ignore.
+ requests, rows = self._drive(
+ "Presence",
+ [
+ _make_http_response([{"channelId": "chat", "status": {"isActive": True}}]),
+ _make_http_response([{"id": "pres-1", "clientId": "alice", "action": "PRESENT"}]),
+ ],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1705327100000,
+ )
+
+ _, child_params = requests[1]
+ assert "start" not in child_params
+ assert "end" not in child_params
+ assert rows[0]["channel_id"] == "chat"
+
+ def test_parent_listing_asks_for_channel_details(self) -> None:
+ requests, _ = self._drive(
+ "Presence",
+ [
+ _make_http_response([{"channelId": "chat", "status": {"isActive": True}}]),
+ _make_http_response([]),
+ ],
+ )
+
+ assert requests[0][1]["by"] == "value"
+
+ def test_checkpoint_records_each_finished_channel(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ self._drive(
+ "Presence",
+ [
+ _make_http_response([{"channelId": "a"}, {"channelId": "b"}]),
+ _make_http_response([{"id": "pres-a"}]),
+ _make_http_response([{"id": "pres-b"}]),
+ ],
+ manager=manager,
+ )
+
+ saved = [call.args[0].fanout_state["completed"] for call in manager.save_state.call_args_list]
+ assert saved[-1] == ["/channels/a/presence", "/channels/b/presence"]
+
+ def test_resume_skips_channels_already_finished(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = AblyResumeConfig(
+ fanout_state={"completed": ["/channels/a/presence"], "current": None, "child_state": None}
+ )
+
+ requests, rows = self._drive(
+ "Presence",
+ [
+ _make_http_response([{"channelId": "a"}, {"channelId": "b"}]),
+ _make_http_response([{"id": "pres-b"}]),
+ ],
+ manager=manager,
+ )
+
+ assert [url for url, _ in requests] == [
+ "https://main.realtime.ably.net/channels",
+ "https://main.realtime.ably.net/channels/b/presence",
+ ]
+ assert [row["id"] for row in rows] == ["pres-b"]
+
+
+class TestUnknownEndpoint:
+ def test_raises_rather_than_syncing_the_wrong_table(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ with pytest.raises(ValueError, match="Unknown Ably endpoint: Nope"):
+ ably_source(
+ api_key="app.key:secret",
+ endpoint="Nope",
+ unit="hour",
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=None,
+ api_version=ABLY_VERSION_2,
+ )
+
+
def _make_redirect_response(location: str, status_code: int = 302) -> Response:
resp = Response()
resp.status_code = status_code
@@ -242,8 +457,9 @@ class TestAblyHostPinningAndRedirects:
mock_session.prepare_request.side_effect = lambda req: req
mock_session.send.side_effect = fake_send
- resource = ably_source(
+ response = ably_source(
api_key="app.key:secret",
+ endpoint="Stats",
unit="hour",
team_id=123,
job_id="test_job",
@@ -251,7 +467,7 @@ class TestAblyHostPinningAndRedirects:
db_incremental_field_last_value=None,
api_version=ABLY_VERSION_2,
)
- list(resource)
+ _pages(response)
def test_off_origin_next_link_is_rejected_before_sending(self) -> None:
# A spoofed `Link: rel="next"` pointing off Ably's host must be refused before the
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably_source.py
index 5b7b24753aae..fbecc5333673 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably_source.py
@@ -52,42 +52,37 @@ class TestAblySource:
assert ok is False
assert error is not None and "malformed" in error.lower()
- def test_source_for_pipeline_plumbs_config_and_returns_expected_response_shape(self):
+ @pytest.mark.parametrize(
+ ("schema_name", "primary_keys", "partition_keys"),
+ [
+ ("Stats", ["unit", "intervalId"], ["interval_start"]),
+ ("Channels", ["channelId"], None),
+ # The channel-scoped tables aggregate rows from every channel, so the channel has to
+ # be part of the key; a bare `id` would multi-match on merge.
+ ("ChannelMessages", ["channel_id", "id"], ["message_time"]),
+ ("Presence", ["channel_id", "id"], None),
+ ],
+ )
+ def test_source_for_pipeline_shapes_the_response_per_schema(self, schema_name, primary_keys, partition_keys):
config = AblySourceConfig(api_key="app.key:secret", unit="day")
inputs = MagicMock(
team_id=self.team_id,
job_id="job-1",
- schema_name="Stats",
+ schema_name=schema_name,
api_version="2",
- should_use_incremental_field=True,
- db_incremental_field_last_value=1700000000000,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ incremental_field=None,
)
manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.ably.source.ably_source"
- ) as mock_ably_source:
- mock_resource = MagicMock(name="Stats", column_hints={"interval_start": "timestamp"})
- mock_resource.name = "Stats"
- mock_ably_source.return_value = mock_resource
+ response = self.source.source_for_pipeline(config, manager, inputs)
- response = self.source.source_for_pipeline(config, manager, inputs)
-
- mock_ably_source.assert_called_once_with(
- api_key="app.key:secret",
- unit="day",
- team_id=self.team_id,
- job_id="job-1",
- resumable_source_manager=manager,
- api_version="2",
- should_use_incremental_field=True,
- db_incremental_field_last_value=1700000000000,
- )
-
- assert response.name == "Stats"
- assert response.primary_keys == ["unit", "intervalId"]
- assert response.partition_mode == "datetime"
- assert response.partition_keys == ["interval_start"]
+ assert response.name == schema_name
+ assert response.primary_keys == primary_keys
+ assert response.partition_keys == partition_keys
+ assert response.partition_mode == ("datetime" if partition_keys else None)
assert response.sort_mode == "asc"
@pytest.mark.parametrize(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py
index 9b2e2008d825..c71775664514 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py
@@ -23,11 +23,22 @@ logger = structlog.get_logger(__name__)
class FanoutEndpointLike(Protocol):
- name: str
- path: str
- incremental_fields: list[Any]
- default_incremental_field: str | None
- page_size: int
+ # Read-only members, because the helper only reads them and a mutable protocol attribute
+ # would exclude a frozen endpoint-config dataclass. A plain attribute still satisfies these.
+ @property
+ def name(self) -> str: ...
+
+ @property
+ def path(self) -> str: ...
+
+ @property
+ def incremental_fields(self) -> list[Any]: ...
+
+ @property
+ def default_incremental_field(self) -> str | None: ...
+
+ @property
+ def page_size(self) -> int: ...
@dataclass(frozen=True)
@@ -99,6 +110,7 @@ def build_dependent_resource(
parent_endpoint_extra: Endpoint | None = None,
child_endpoint_extra: Endpoint | None = None,
child_params_extra: dict[str, Any] | None = None,
+ parent_data_map: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
page_size_param: str | None = "limit",
resume_hook: Callable[[dict[str, Any] | None], None] | None = None,
initial_paginator_state: dict[str, Any] | None = None,
@@ -139,6 +151,13 @@ def build_dependent_resource(
"table_format": "delta",
}
+ if parent_data_map is not None:
+ # Parent transforms run before the child transformer reads the page, so a resolve_field
+ # the parent rows do not carry can be derived here. `process_parent_data_item` binds the
+ # path with `str.format`, which applies no escaping, so a vendor whose ids can contain
+ # `/` must percent-encode them through this hook.
+ parent_resource["data_map"] = parent_data_map
+
if warehouse_parent:
if not source_id:
raise ValueError("source_id is required when a fan-out reads its parent from the warehouse")