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(better_stack): sync monitor availability, latency, people and incident comments (#99808)

Tom Owers536ea309f1a3
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 ebebef3d742f..345086ae0248 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
@@ -776,14 +776,14 @@ Diffed against: <https://api.bettermode.com/ (live GraphQL introspection of quer
## BetterStack — gaps
-Today (8): `escalation_policies`, `heartbeat_groups`, `heartbeats`, `incidents`, `monitor_groups`, `monitors`, `on_calls`, `status_pages`
+Today (13): `escalation_policies`, `heartbeat_groups`, `heartbeats`, `incident_comments`, `incidents`, `monitor_availability`, `monitor_groups`, `monitor_response_times`, `monitors`, `on_calls`, `roles`, `status_pages`, `team_members`
Diffed against: <https://betterstack.com/docs/uptime/api/getting-started-with-uptime-api/>
-- [ ] `GET monitor availability summary (/api/v2/monitors/{id}/sla)` — uptime percentage and total downtime per monitor - the product's headline metric, and not derivable from the monitors table (high)
-- [ ] `GET monitor response times (/api/v2/monitors/{id}/response-times)` — latency time series per monitor and region; the other core performance metric (high)
-- [ ] `GET /api/v2/team-members (and /api/v2/roles)` — lookup resolving the user IDs referenced by incidents, on-call calendars and escalation policies (high)
-- [ ] `GET incident comments (/api/v2/incidents/{id}/comments)` — acknowledgement and resolution commentary - the timeline behind incident MTTA/MTTR (high)
+- [x] `GET monitor availability summary (/api/v2/monitors/{id}/sla)` — uptime percentage and total downtime per monitor - the product's headline metric, and not derivable from the monitors table (high)
+- [x] `GET monitor response times (/api/v2/monitors/{id}/response-times)` — latency time series per monitor and region; the other core performance metric (high)
+- [x] `GET /api/v2/team-members (and /api/v2/roles)` — lookup resolving the user IDs referenced by incidents, on-call calendars and escalation policies (high)
+- [x] `GET incident comments (/api/v2/incidents/{id}/comments)` — acknowledgement and resolution commentary - the timeline behind incident MTTA/MTTR (high)
- [ ] `GET on-call calendar events and rotation` — who was actually on call and when; on_calls only carries the calendar definitions (high)
- [ ] `GET heartbeat availability summary` — the heartbeat equivalent of the monitor SLA summary (medium)
- [ ] `GET severities and severity groups (/api/v2/severities)` — call-routing severity lookup resolving the severity referenced on incidents (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/better_stack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/better_stack.py
index 6e81fa629ce9..fd3b433badf4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/better_stack.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/better_stack.py
@@ -1,6 +1,6 @@
import dataclasses
from datetime import UTC, date, datetime
-from typing import Any, Optional
+from typing import Any, Optional, cast
from urllib.parse import urlsplit
from requests import Response
@@ -15,13 +15,20 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
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.paginators import (
JSONResponsePaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+_TRUSTED_HOSTS = {"uptime.betterstack.com", "betterstack.com"}
+
class BetterStackUntrustedURLError(Exception):
pass
@@ -36,15 +43,18 @@ def _validate_pagination_url(url: str) -> str:
request at another host and leaking the token (SSRF). Returns the URL unchanged when trusted.
"""
parts = urlsplit(url)
- is_trusted = parts.scheme == "https" and parts.netloc == "uptime.betterstack.com" and parts.path.startswith("/api/")
+ is_trusted = parts.scheme == "https" and parts.netloc in _TRUSTED_HOSTS and parts.path.startswith("/api/")
if not is_trusted:
- raise BetterStackUntrustedURLError(f"Refusing to follow pagination URL outside {BETTER_STACK_BASE_URL}/")
+ raise BetterStackUntrustedURLError("Refusing to follow a pagination URL outside the Better Stack API")
return url
class BetterStackPaginator(JSONResponsePaginator):
- """Follows the response's `pagination.next` URL, refusing any URL off the Better Stack origin —
- whether it arrived in a response body or was seeded from saved resume state."""
+ """Follows the response's `pagination.next` URL, refusing any URL off a Better Stack origin —
+ whether it arrived in a response body or was seeded from saved resume state.
+
+ Unpaginated collections (roles, incident comments) and the single-object monitor endpoints
+ carry no `pagination` key, so the first response is also the last."""
def __init__(self) -> None:
super().__init__(next_url_path="pagination.next")
@@ -60,12 +70,16 @@ class BetterStackPaginator(JSONResponsePaginator):
_validate_pagination_url(self._next_url)
[email protected](frozen=True)
class BetterStackResumeConfig:
# Full next-page URL from the response's `pagination.next` field (null on the last page). It
# carries the page, per_page, and any `from` filter, so following it preserves the incremental
# window on every page.
next_url: str | None = None
+ # Framework fan-out resume state for the parent-scoped endpoints, opaque to this source and
+ # passed straight back to the fan-out helper:
+ # {"completed": [child_path, ...], "current": child_path | None, "child_state": {...} | None}.
+ fanout_state: dict[str, Any] | None = None
def _format_from_date(value: Any) -> str:
@@ -115,48 +129,101 @@ def _flatten_item(item: dict[str, Any]) -> dict[str, Any]:
return flattened
+def _explode_response_times(item: dict[str, Any]) -> list[dict[str, Any]]:
+ """Explode a monitor's nested latency series into one row per region measurement.
+
+ The response is a single object holding `regions[].response_times[]`, so flattening it the
+ usual way would produce one row per monitor with the whole series buried in a list. `id` and
+ `type` are dropped: `id` repeats the monitor id already carried by `monitor_id`, and naming a
+ measurement row after its monitor would read as the row's own key.
+ """
+ attributes = item.get("attributes") or {}
+ carried = {k: v for k, v in item.items() if k not in ("attributes", "id", "type")}
+ rows: list[dict[str, Any]] = []
+ for region in attributes.get("regions") or []:
+ region_name = region.get("region")
+ for measurement in region.get("response_times") or []:
+ rows.append({**carried, "region": region_name, **measurement})
+ return rows
+
+
+def _no_request_window(_cursor_path: str) -> None:
+ """Report that a fan-out child takes no server-side time filter.
+
+ Neither child endpoint accepts one, so there is no cursor to bind a request window to. The
+ child still merges on its primary key, which is what lets the parent listing bound the
+ request set instead.
+ """
+ return None
+
+
+def _client_config(api_token: str, base_url: str) -> ClientConfig:
+ return {
+ "base_url": base_url,
+ # Auth (Bearer) goes through the framework auth config so its value is redacted from logs.
+ "auth": {"type": "bearer", "token": api_token},
+ # capture=False: incident `response_content` and monitor URLs can carry arbitrary
+ # secrets the name-based scrubbers can't recognise, so keep them out of HTTP samples.
+ "session": make_tracked_session(capture=False, redact_values=(api_token,)),
+ "paginator": BetterStackPaginator(),
+ }
+
+
def probe_credentials(api_token: str, endpoint: str | None = None) -> int | None:
"""Cheap probe of a Better Stack collection. Returns the HTTP status code, or None on a
connection failure. Probes the given endpoint's path when set, else the monitors collection."""
config = BETTER_STACK_ENDPOINTS.get(endpoint) if endpoint else None
+ if config is not None and config.fanout is not None:
+ # A fan-out child's path is parent-scoped and has no collection of its own, so the
+ # reachable thing to probe is the parent the child is enumerated from.
+ config = BETTER_STACK_ENDPOINTS[config.fanout.parent_name]
+ base_url = config.base_url if config else BETTER_STACK_BASE_URL
path = config.path if config else "/v2/monitors"
_ok, status = validate_via_probe(
lambda: make_tracked_session(capture=False, redact_values=(api_token,)),
- f"{BETTER_STACK_BASE_URL}{path}?per_page=1",
+ f"{base_url}{path}?per_page=1",
headers={"Authorization": f"Bearer {api_token}"},
)
return status
-def better_stack_source(
+def _source_response(config: BetterStackEndpointConfig, items: Any) -> SourceResponse:
+ return SourceResponse(
+ name=config.name,
+ items=lambda: items,
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ # Neither the incidents endpoint nor the fan-out children guarantee an ascending order —
+ # incidents documents no sort param, and a fan-out walks parent by parent. Declaring
+ # "desc" commits the incremental watermark once at the end of a successful sync, which is
+ # safe for any arrival order, instead of checkpointing it per batch.
+ sort_mode="desc" if config.incremental_fields else "asc",
+ )
+
+
+def _top_level_source(
api_token: str,
- endpoint: str,
+ config: BetterStackEndpointConfig,
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[BetterStackResumeConfig],
- should_use_incremental_field: bool = False,
- db_incremental_field_last_value: Optional[Any] = None,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
) -> SourceResponse:
- config = BETTER_STACK_ENDPOINTS[endpoint]
-
- params = _build_initial_params(config, should_use_incremental_field, db_incremental_field_last_value)
-
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": BETTER_STACK_BASE_URL,
- # Auth (Bearer) goes through the framework auth config so its value is redacted from logs.
- "auth": {"type": "bearer", "token": api_token},
- # capture=False: incident `response_content` and monitor URLs can carry arbitrary
- # secrets the name-based scrubbers can't recognise, so keep them out of HTTP samples.
- "session": make_tracked_session(capture=False, redact_values=(api_token,)),
- "paginator": BetterStackPaginator(),
- },
+ "client": _client_config(api_token, config.base_url),
"resources": [
{
- "name": endpoint,
+ "name": config.name,
"endpoint": {
"path": config.path,
- "params": params,
+ "params": _build_initial_params(
+ config, should_use_incremental_field, db_incremental_field_last_value
+ ),
# A missing `data` key is treated as an empty page (matching the API's
# envelope, which always carries `data`), so no data_selector_required here.
"data_selector": "data",
@@ -179,26 +246,99 @@ def better_stack_source(
if state and state.get("next_url"):
resumable_source_manager.save_state(BetterStackResumeConfig(next_url=state["next_url"]))
- resource = rest_api_resource(
- rest_config,
- team_id,
- job_id,
- db_incremental_field_last_value if should_use_incremental_field else None,
- resume_hook=save_checkpoint,
- initial_paginator_state=initial_paginator_state,
+ return _source_response(
+ config,
+ rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value if should_use_incremental_field else None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ ),
)
- return SourceResponse(
- name=endpoint,
- items=lambda: resource,
- primary_keys=config.primary_keys,
- partition_count=1,
- partition_size=1,
- partition_mode="datetime" if config.partition_key else None,
- partition_format="week" if config.partition_key else None,
- partition_keys=[config.partition_key] if config.partition_key else None,
- # The incidents endpoint documents no sort param and its default ordering is unverified, so
- # declare "desc": the incremental watermark is committed once at the end of a successful
- # sync (safe for any arrival order) instead of checkpointed per batch.
- sort_mode="desc" if config.supports_incremental else "asc",
+
+def _fanout_source(
+ api_token: str,
+ config: BetterStackEndpointConfig,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[BetterStackResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+) -> SourceResponse:
+ """Walk a parent collection, then fetch this endpoint once per parent row."""
+ assert config.fanout is not None
+ parent_config = BETTER_STACK_ENDPOINTS[config.fanout.parent_name]
+ # The parent listing carries whatever server-side date filter it supports, floored by THIS
+ # endpoint's watermark. For incident comments that means a sync only re-walks incidents that
+ # started on or after the newest comment already collected: a comment posted later against an
+ # older incident is picked up by a full refresh, not by the next incremental run. The
+ # alternative — re-walking every incident ever recorded, one request each — costs more every
+ # sync than the data it re-reads is worth.
+ fanout = dataclasses.replace(
+ config.fanout,
+ parent_params={
+ **_build_initial_params(parent_config, should_use_incremental_field, db_incremental_field_last_value),
+ **config.fanout.parent_params,
+ },
+ )
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and resume.fanout_state:
+ initial_paginator_state = resume.fanout_state
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ resumable_source_manager.save_state(BetterStackResumeConfig(fanout_state=state))
+
+ resource = cast(
+ Resource,
+ build_dependent_resource(
+ endpoint_configs=BETTER_STACK_ENDPOINTS,
+ child_endpoint=config.name,
+ fanout=fanout,
+ client_config=_client_config(api_token, config.base_url),
+ 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_config_factory=_no_request_window,
+ # None of the child endpoints take a page-size param; the parent's rides in
+ # `parent_params` above.
+ page_size_param=None,
+ parent_endpoint_extra={"paginator": BetterStackPaginator(), "data_selector": "data"},
+ child_endpoint_extra={"paginator": BetterStackPaginator(), "data_selector": "data"},
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ ),
+ )
+ # Added after the helper's own parent-field rename, so the renamed `monitor_id`/`incident_id`
+ # is already on the row when these run.
+ resource.add_map(_explode_response_times if config.name == "monitor_response_times" else _flatten_item)
+ return _source_response(config, resource)
+
+
+def better_stack_source(
+ api_token: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[BetterStackResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = BETTER_STACK_ENDPOINTS[endpoint]
+ build = _fanout_source if config.fanout is not None else _top_level_source
+ return build(
+ api_token,
+ config,
+ team_id,
+ job_id,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/canonical_descriptions.py
index cb359c550aa1..2a67e90f3a85 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/canonical_descriptions.py
@@ -41,6 +41,33 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"updated_at": "When the monitor was last updated.",
},
},
+ "monitor_availability": {
+ "description": "Availability summary per monitor: uptime percentage and downtime totals over the monitor's lifetime.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Identifier of the monitor the summary covers.",
+ "monitor_id": "Identifier of the monitor the summary covers.",
+ "availability": "Percentage of time the monitor was up.",
+ "total_downtime": "Total time the monitor was down, in seconds.",
+ "number_of_incidents": "Number of incidents recorded for the monitor.",
+ "longest_incident": "Duration of the longest incident, in seconds.",
+ "average_incident": "Average incident duration, in seconds.",
+ },
+ },
+ "monitor_response_times": {
+ "description": "Response time measurements per monitor and checking region, covering the last 24 hours of each sync.",
+ "docs_url": _DOCS,
+ "columns": {
+ "monitor_id": "Identifier of the monitor the measurement belongs to.",
+ "region": "Region the check was run from (e.g. us, eu).",
+ "at": "When the check ran.",
+ "response_time": "Total time to complete the request, in seconds.",
+ "name_lookup_time": "Time spent resolving DNS, in seconds.",
+ "connection_time": "Time spent establishing the connection, in seconds.",
+ "tls_handshake_time": "Time spent on the TLS handshake, in seconds.",
+ "data_transfer_time": "Time spent transferring the response body, in seconds.",
+ },
+ },
"monitor_groups": {
"description": "Groups used to organize uptime monitors.",
"docs_url": _DOCS,
@@ -94,6 +121,19 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"updated_at": "When the status page was last updated.",
},
},
+ "incident_comments": {
+ "description": "Comments posted on an incident, including acknowledgement and resolution notes, with the incident they belong to.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the comment.",
+ "incident_id": "Identifier of the incident the comment was posted on.",
+ "content": "Text of the comment.",
+ "user_id": "Identifier of the team member who posted the comment, absent for comments posted through the API.",
+ "user_email": "Email address of the team member who posted the comment.",
+ "created_at": "When the comment was posted.",
+ "updated_at": "When the comment was last edited.",
+ },
+ },
"on_calls": {
"description": "On-call calendars defining who is on call and when.",
"docs_url": _DOCS,
@@ -112,4 +152,28 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"repeat_delay": "Delay between escalation repeats, in seconds.",
},
},
+ "team_members": {
+ "description": "People in the Better Stack team, including pending invitations, resolving the user ids referenced by incidents and on-call schedules.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the team member or invitation.",
+ "type": "Whether the row is an accepted team member or a pending invitation.",
+ "email": "Email address of the team member.",
+ "first_name": "First name of the team member.",
+ "last_name": "Last name of the team member.",
+ "role": "Role the member holds in the team (e.g. admin, responder, member, or custom).",
+ "mobile_app_platforms": "Mobile platforms the member has the Better Stack app installed on.",
+ "created_at": "When the member joined the team.",
+ "invited_at": "When the invitation was sent, for pending invitations.",
+ },
+ },
+ "roles": {
+ "description": "Roles available in the organization, both built-in and custom, resolving the role names carried on team members.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the role.",
+ "name": "Display name of the role.",
+ "role": "System identifier of the role, or `custom` for user-defined roles.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/settings.py
index 3458114fe3bf..7ddad911a69c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/settings.py
@@ -1,20 +1,36 @@
from dataclasses import dataclass, field
from typing import Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseAction
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
# Better Stack Uptime API. Standard collections live under /v2; incidents moved to /v3 (the /v2
# incidents route still exists, but /v3 is the documented current version). Confirmed against the
# live API: real routes return 401 on a bad token, unknown routes return 404.
BETTER_STACK_BASE_URL = "https://uptime.betterstack.com/api"
+# Team members and organization roles are account-level, so Better Stack serves them from the main
+# host rather than the Uptime subdomain. Confirmed the same way: the Uptime host 404s both routes
+# while this one returns 401 on a bad token.
+BETTER_STACK_ORG_BASE_URL = "https://betterstack.com/api"
+# A parent row deleted between the parent listing and the child fetch 404s. Skip that parent
+# instead of failing the whole fan-out.
+_SKIP_MISSING_PARENT: list[ResponseAction] = [{"status_code": 404, "action": "ignore"}]
-@dataclass
+
+@dataclass(frozen=True)
class BetterStackEndpointConfig:
name: str
path: str
- # Only True where Better Stack exposes a genuine server-side date filter. Today that's the
- # incidents endpoint's `from`/`to` params (YYYY-MM-DD, by incident start date).
+ # Host serving this resource. Defaults to the Uptime API.
+ base_url: str = BETTER_STACK_BASE_URL
+ # Only True where Better Stack exposes a genuine server-side date filter on this endpoint's
+ # own request. Today that's the incidents endpoint's `from`/`to` params (YYYY-MM-DD, by
+ # incident start date). A fan-out child leaves this False even when it tracks a cursor — its
+ # request set is bounded through the parent listing instead.
supports_incremental: bool = False
incremental_fields: list[IncrementalField] = field(default_factory=list)
# Stable field to partition by — a creation/start timestamp, never `updated_at`.
@@ -24,21 +40,39 @@ class BetterStackEndpointConfig:
# incidents endpoint caps at 50.
page_size: int = 50
should_sync_default: bool = True
+ # Set where the resource only exists per parent row (e.g. /monitors/{monitor_id}/sla).
+ fanout: Optional[DependentEndpointConfig] = None
+
+ @property
+ def default_incremental_field(self) -> str | None:
+ return self.incremental_fields[0]["field"] if self.incremental_fields else None
+
+def _datetime_field(name: str) -> list[IncrementalField]:
+ return [
+ {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ]
-_STARTED_AT: list[IncrementalField] = [
- {
- "label": "started_at",
- "type": IncrementalFieldType.DateTime,
- "field": "started_at",
- "field_type": IncrementalFieldType.DateTime,
- }
-]
+
+_MONITOR_FANOUT = DependentEndpointConfig(
+ parent_name="monitors",
+ resolve_param="monitor_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "monitor_id"},
+ child_response_actions=_SKIP_MISSING_PARENT,
+)
# Endpoint catalog — the streams a reliability team actually wants from an uptime/incident
-# platform: monitors and heartbeats (plus their groups), incident history, on-call calendars,
-# escalation policies, and status pages. Every path was confirmed to be a real route against the
-# live API.
+# platform: monitors and heartbeats (plus their groups), monitor availability and latency,
+# incident history and commentary, on-call calendars, escalation policies, status pages, and the
+# people lookups the rest of them reference. Every path was confirmed to be a real route against
+# the live API.
BETTER_STACK_ENDPOINTS: dict[str, BetterStackEndpointConfig] = {
# Incident history is the high-volume stream — incremental via the server-side `from` date
# filter on the incident start date.
@@ -46,16 +80,55 @@ BETTER_STACK_ENDPOINTS: dict[str, BetterStackEndpointConfig] = {
name="incidents",
path="/v3/incidents",
supports_incremental=True,
- incremental_fields=_STARTED_AT,
+ incremental_fields=_datetime_field("started_at"),
partition_key="started_at",
page_size=50,
),
+ # Acknowledgement and resolution commentary, one request per incident. The endpoint returns
+ # every comment at once (no pagination, no time filter), so it merges on its primary key and
+ # bounds its request set through the incidents listing instead.
+ "incident_comments": BetterStackEndpointConfig(
+ name="incident_comments",
+ path="/v2/incidents/{incident_id}/comments",
+ incremental_fields=_datetime_field("created_at"),
+ partition_key="created_at",
+ primary_keys=["incident_id", "id"],
+ should_sync_default=False,
+ fanout=DependentEndpointConfig(
+ parent_name="incidents",
+ resolve_param="incident_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "incident_id"},
+ child_response_actions=_SKIP_MISSING_PARENT,
+ ),
+ ),
"monitors": BetterStackEndpointConfig(
name="monitors",
path="/v2/monitors",
partition_key="created_at",
page_size=250,
),
+ # Uptime percentage and downtime totals per monitor — the product's headline metric, which
+ # the monitors table does not carry. One row per monitor, recomputed every sync.
+ "monitor_availability": BetterStackEndpointConfig(
+ name="monitor_availability",
+ path="/v2/monitors/{monitor_id}/sla",
+ primary_keys=["monitor_id"],
+ fanout=_MONITOR_FANOUT,
+ ),
+ # Latency time series per monitor and region. Better Stack only serves the last 24 hours and
+ # takes no time filter, so each sync re-reads that window and merges it onto the history
+ # already collected; appending would duplicate the overlap.
+ "monitor_response_times": BetterStackEndpointConfig(
+ name="monitor_response_times",
+ path="/v2/monitors/{monitor_id}/response-times",
+ incremental_fields=_datetime_field("at"),
+ partition_key="at",
+ primary_keys=["monitor_id", "region", "at"],
+ should_sync_default=False,
+ fanout=_MONITOR_FANOUT,
+ ),
"monitor_groups": BetterStackEndpointConfig(
name="monitor_groups",
path="/v2/monitor-groups",
@@ -87,6 +160,21 @@ BETTER_STACK_ENDPOINTS: dict[str, BetterStackEndpointConfig] = {
name="escalation_policies",
path="/v2/policies",
),
+ # People lookups resolving the user ids incidents, on-call calendars and escalation policies
+ # reference. Both are account-level, so they live on the other host.
+ "team_members": BetterStackEndpointConfig(
+ name="team_members",
+ path="/v2/team-members",
+ base_url=BETTER_STACK_ORG_BASE_URL,
+ # The collection mixes accepted members with pending invitations, whose ids come from
+ # separate id spaces — `type` keeps two rows from collapsing onto one key.
+ primary_keys=["id", "type"],
+ ),
+ "roles": BetterStackEndpointConfig(
+ name="roles",
+ path="/v2/roles",
+ base_url=BETTER_STACK_ORG_BASE_URL,
+ ),
}
ENDPOINTS = tuple(BETTER_STACK_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/source.py
index 7c9178e2ca95..0c71bd297510 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/source.py
@@ -85,8 +85,15 @@ You can create an Uptime API token in your [Better Stack dashboard](https://upti
# 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.
# No retry can satisfy a credential problem. Match the stable status text + base host,
# not the per-request path/query.
+ # Team members and roles are served from betterstack.com rather than the Uptime
+ # subdomain, so both hosts need an entry.
"401 Client Error: Unauthorized for url: https://uptime.betterstack.com": "Your Better Stack API token is invalid or has been revoked. Create a new Uptime API token in your Better Stack dashboard, then reconnect.",
"403 Client Error: Forbidden for url: https://uptime.betterstack.com": "Your Better Stack API token does not have access to this resource. Check the token's team scope in your Better Stack dashboard, then reconnect.",
+ "401 Client Error: Unauthorized for url: https://betterstack.com": "Your Better Stack API token is invalid or has been revoked. Create a new Uptime API token in your Better Stack dashboard, then reconnect.",
+ "403 Client Error: Forbidden for url: https://betterstack.com": "Your Better Stack API token does not have access to this resource. Check the token's team scope in your Better Stack dashboard, then reconnect.",
+ # Team members are listed per team, so a token spanning several teams cannot resolve
+ # which one to read and no retry will change that.
+ "422 Client Error: Unprocessable Entity for url: https://betterstack.com/api/v2/team-members": "Team members can only be synced with a team-scoped Uptime API token. Create one for the team you want to sync in your Better Stack dashboard, then reconnect.",
}
def get_schemas(
@@ -102,6 +109,14 @@ You can create an Uptime API token in your [Better Stack dashboard](https://upti
ENDPOINTS,
{name: endpoint_config.incremental_fields for name, endpoint_config in BETTER_STACK_ENDPOINTS.items()},
names,
+ # Fan-out children re-request each parent's whole child collection every sync, because
+ # neither child endpoint takes a server-side time filter. Appending that would
+ # duplicate every row the previous sync wrote, so they only offer incremental merge.
+ merge_only=[
+ name
+ for name, endpoint_config in BETTER_STACK_ENDPOINTS.items()
+ if endpoint_config.fanout is not None and endpoint_config.incremental_fields
+ ],
should_sync_default={
name: endpoint_config.should_sync_default for name, endpoint_config in BETTER_STACK_ENDPOINTS.items()
},
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/tests/test_better_stack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/tests/test_better_stack.py
index 3e9d2673aa48..bb21a7132279 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/tests/test_better_stack.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/tests/test_better_stack.py
@@ -13,12 +13,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.better_sta
BETTER_STACK_BASE_URL,
BetterStackResumeConfig,
BetterStackUntrustedURLError,
+ _explode_response_times,
_flatten_item,
_format_from_date,
_validate_pagination_url,
better_stack_source,
probe_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.better_stack.settings import (
+ BETTER_STACK_ORG_BASE_URL,
+)
# better_stack builds its own capture=False session and passes it into the RESTClient.
SESSION_PATCH = (
@@ -115,8 +119,14 @@ class TestFlattenItem:
class TestValidatePaginationUrl:
- def test_api_origin_url_is_returned_unchanged(self) -> None:
- url = "https://uptime.betterstack.com/api/v3/incidents?page=2&per_page=50"
+ @parameterized.expand(
+ [
+ ("uptime_host", "https://uptime.betterstack.com/api/v3/incidents?page=2&per_page=50"),
+ # Team members paginate on the account-level host.
+ ("org_host", "https://betterstack.com/api/v2/team-members?page=2"),
+ ]
+ )
+ def test_api_origin_url_is_returned_unchanged(self, _name: str, url: str) -> None:
assert _validate_pagination_url(url) == url
@parameterized.expand(
@@ -347,3 +357,239 @@ class TestBearerAuth:
prepared.headers = {}
auths[0](prepared)
assert prepared.headers["Authorization"] == "Bearer bs_test"
+
+
+def _object_response(data: dict[str, Any] | list[dict[str, Any]]) -> Response:
+ """An unpaginated response: the single-object monitor endpoints and the comments collection
+ carry no `pagination` key at all."""
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps({"data": data}).encode()
+ return resp
+
+
+class TestExplodeResponseTimes:
+ def test_one_row_per_region_measurement(self) -> None:
+ rows = _explode_response_times(
+ {
+ "id": "270985",
+ "type": "monitor_response_times",
+ "monitor_id": "270985",
+ "attributes": {
+ "regions": [
+ {
+ "region": "us",
+ "response_times": [
+ {"at": "2026-04-03T11:00:57.000Z", "response_time": 0.47273},
+ {"at": "2026-04-03T11:03:57.000Z", "response_time": 0.51},
+ ],
+ },
+ {"region": "eu", "response_times": [{"at": "2026-04-03T11:00:59.000Z", "response_time": 0.19}]},
+ ]
+ },
+ }
+ )
+
+ # `id`/`type` are dropped: `id` only repeats the monitor id, which `monitor_id` carries.
+ assert rows == [
+ {"monitor_id": "270985", "region": "us", "at": "2026-04-03T11:00:57.000Z", "response_time": 0.47273},
+ {"monitor_id": "270985", "region": "us", "at": "2026-04-03T11:03:57.000Z", "response_time": 0.51},
+ {"monitor_id": "270985", "region": "eu", "at": "2026-04-03T11:00:59.000Z", "response_time": 0.19},
+ ]
+
+ @parameterized.expand([("no_regions", {}), ("empty_regions", {"regions": []}), ("null_regions", {"regions": None})])
+ def test_monitor_without_measurements_yields_no_rows(self, _name: str, attributes: dict[str, Any]) -> None:
+ assert _explode_response_times({"id": "1", "monitor_id": "1", "attributes": attributes}) == []
+
+
+class TestOrganizationHost:
+ @parameterized.expand([("team_members", "/v2/team-members"), ("roles", "/v2/roles")])
+ @mock.patch(SESSION_PATCH)
+ def test_account_level_endpoints_use_the_org_host(self, endpoint: str, path: str, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response([{"id": "101", "type": "team_member", "attributes": {}}])])
+
+ _rows(_source(endpoint=endpoint))
+
+ # The Uptime subdomain 404s both routes; they are served from betterstack.com.
+ assert snapshots[0]["url"] == f"{BETTER_STACK_ORG_BASE_URL}{path}"
+
+
+class TestFanout:
+ @mock.patch(SESSION_PATCH)
+ def test_monitor_availability_fetched_per_monitor(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response([{"id": "1", "type": "monitor", "attributes": {}}, {"id": "2", "attributes": {}}]),
+ _object_response({"id": "1", "type": "monitor_sla", "attributes": {"availability": 99.98}}),
+ _object_response({"id": "2", "type": "monitor_sla", "attributes": {"availability": 100.0}}),
+ ],
+ )
+
+ rows = _rows(_source(endpoint="monitor_availability"))
+
+ assert rows == [
+ {"id": "1", "type": "monitor_sla", "monitor_id": "1", "availability": 99.98},
+ {"id": "2", "type": "monitor_sla", "monitor_id": "2", "availability": 100.0},
+ ]
+ assert snapshots[0]["url"] == f"{BETTER_STACK_BASE_URL}/v2/monitors"
+ assert snapshots[0]["params"] == {"per_page": 250}
+ assert [s["url"] for s in snapshots[1:]] == [
+ f"{BETTER_STACK_BASE_URL}/v2/monitors/1/sla",
+ f"{BETTER_STACK_BASE_URL}/v2/monitors/2/sla",
+ ]
+ # The child endpoints take no page-size param, so none is sent.
+ assert snapshots[1]["params"] == {}
+
+ @mock.patch(SESSION_PATCH)
+ def test_response_times_rows_carry_their_monitor(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response([{"id": "7", "attributes": {}}]),
+ _object_response(
+ {
+ "id": "7",
+ "type": "monitor_response_times",
+ "attributes": {
+ "regions": [{"region": "eu", "response_times": [{"at": "2026-04-03T11:00:59.000Z"}]}]
+ },
+ }
+ ),
+ ],
+ )
+
+ assert _rows(_source(endpoint="monitor_response_times")) == [
+ {"monitor_id": "7", "region": "eu", "at": "2026-04-03T11:00:59.000Z"}
+ ]
+
+ @mock.patch(SESSION_PATCH)
+ def test_incident_comments_carry_their_incident(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response([{"id": "55", "type": "incident", "attributes": {}}]),
+ _object_response(
+ [
+ {
+ "id": "123",
+ "type": "incident_comment",
+ "attributes": {"id": 123, "content": "ack", "created_at": "2026-06-03T12:10:28.357Z"},
+ }
+ ]
+ ),
+ ],
+ )
+
+ rows = _rows(_source(endpoint="incident_comments"))
+
+ # `incident_id` is what makes the primary key unique across every incident's comments.
+ assert rows == [
+ {
+ "id": 123,
+ "type": "incident_comment",
+ "incident_id": "55",
+ "content": "ack",
+ "created_at": "2026-06-03T12:10:28.357Z",
+ }
+ ]
+ assert snapshots[1]["url"] == f"{BETTER_STACK_BASE_URL}/v2/incidents/55/comments"
+
+ @parameterized.expand(
+ [
+ # The comment watermark floors the incidents walk, so a sync only re-fetches comments
+ # for incidents that started on or after the newest comment already collected.
+ (
+ "incremental_bounds_the_incidents_walk",
+ True,
+ datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ {"per_page": 50, "from": "2026-03-04"},
+ ),
+ ("first_sync_walks_every_incident", True, None, {"per_page": 50}),
+ ("full_refresh_walks_every_incident", False, datetime(2026, 3, 4, tzinfo=UTC), {"per_page": 50}),
+ ]
+ )
+ @mock.patch(SESSION_PATCH)
+ def test_incident_comments_parent_window(
+ self, _name: str, should_use_incremental_field: bool, last_value: Any, expected: dict[str, Any], MockSession
+ ) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response([])])
+
+ _rows(
+ _source(
+ endpoint="incident_comments",
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=last_value,
+ )
+ )
+
+ assert snapshots[0]["params"] == expected
+
+ @mock.patch(SESSION_PATCH)
+ def test_fanout_state_is_saved_and_resumed_per_parent(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response([{"id": "1", "attributes": {}}, {"id": "2", "attributes": {}}]),
+ _object_response({"id": "1", "attributes": {"availability": 99.0}}),
+ _object_response({"id": "2", "attributes": {"availability": 98.0}}),
+ ],
+ )
+
+ manager = _make_manager()
+ _rows(_source(endpoint="monitor_availability", manager=manager))
+
+ saved = manager.save_state.call_args.args[0].fanout_state
+ assert saved["completed"] == ["/v2/monitors/1/sla", "/v2/monitors/2/sla"]
+
+ # A rerun seeded with that state skips both parents and issues no child request.
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response([{"id": "1", "attributes": {}}, {"id": "2", "attributes": {}}])])
+ resumed = _make_manager(BetterStackResumeConfig(fanout_state=saved))
+
+ assert _rows(_source(endpoint="monitor_availability", manager=resumed)) == []
+ assert len(snapshots) == 1
+
+ @mock.patch(SESSION_PATCH)
+ def test_deleted_parent_is_skipped_not_fatal(self, MockSession) -> None:
+ session = MockSession.return_value
+ gone = Response()
+ gone.status_code = 404
+ gone._content = b'{"errors":"Resource with provided ID was not found"}'
+ _wire(
+ session,
+ [
+ _response([{"id": "1", "attributes": {}}, {"id": "2", "attributes": {}}]),
+ gone,
+ _object_response({"id": "2", "attributes": {"availability": 98.0}}),
+ ],
+ )
+
+ # A monitor deleted between the listing and its SLA fetch must not fail the whole sync.
+ assert _rows(_source(endpoint="monitor_availability")) == [{"id": "2", "monitor_id": "2", "availability": 98.0}]
+
+
+class TestProbeCredentialsForFanoutEndpoints:
+ @parameterized.expand(
+ [
+ ("monitor_availability", f"{BETTER_STACK_BASE_URL}/v2/monitors?per_page=1"),
+ ("monitor_response_times", f"{BETTER_STACK_BASE_URL}/v2/monitors?per_page=1"),
+ ("incident_comments", f"{BETTER_STACK_BASE_URL}/v3/incidents?per_page=1"),
+ ("team_members", f"{BETTER_STACK_ORG_BASE_URL}/v2/team-members?per_page=1"),
+ ]
+ )
+ @mock.patch(SESSION_PATCH)
+ def test_probes_a_reachable_collection(self, endpoint: str, expected_url: str, MockSession) -> None:
+ session = MockSession.return_value
+ session.get.return_value = mock.MagicMock(status_code=200)
+
+ probe_credentials("bs_test", endpoint)
+
+ # A fan-out child has no collection of its own, so its parent is probed instead.
+ assert session.get.call_args.args[0] == expected_url
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/tests/test_better_stack_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/tests/test_better_stack_source.py
index d1c1b30889b2..1dda300c41bc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/tests/test_better_stack_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/tests/test_better_stack_source.py
@@ -25,22 +25,31 @@ class TestBetterStackSourceConfig:
class TestBetterStackGetSchemas:
@parameterized.expand(
[
- # Only incidents has a server-side date filter; everything else is full refresh.
- ("incidents", True),
- ("monitors", False),
- ("monitor_groups", False),
- ("heartbeats", False),
- ("heartbeat_groups", False),
- ("status_pages", False),
- ("on_calls", False),
- ("escalation_policies", False),
+ # (endpoint, supports_incremental, supports_append)
+ # Incidents has a server-side date filter, so appending only ever adds newer rows.
+ ("incidents", True, True),
+ # Fan-out children re-read each parent's whole child collection every sync, so they
+ # merge on the primary key and must not offer append.
+ ("incident_comments", True, False),
+ ("monitor_response_times", True, False),
+ # Everything else is full refresh.
+ ("monitors", False, False),
+ ("monitor_availability", False, False),
+ ("monitor_groups", False, False),
+ ("heartbeats", False, False),
+ ("heartbeat_groups", False, False),
+ ("status_pages", False, False),
+ ("on_calls", False, False),
+ ("escalation_policies", False, False),
+ ("team_members", False, False),
+ ("roles", False, False),
]
)
- def test_incremental_support_matches_settings(self, endpoint: str, expected_incremental: bool) -> None:
+ def test_sync_modes_match_settings(self, endpoint: str, expected_incremental: bool, expected_append: bool) -> None:
schemas = {s.name: s for s in BetterStackSource().get_schemas(MagicMock(), team_id=1)}
schema = schemas[endpoint]
assert schema.supports_incremental is expected_incremental
- assert schema.supports_append is expected_incremental
+ assert schema.supports_append is expected_append
assert bool(schema.incremental_fields) is expected_incremental
@@ -78,6 +87,18 @@ class TestBetterStackNonRetryableErrors:
"401 Client Error: Unauthorized for url: https://uptime.betterstack.com/api/v2/monitors?per_page=250",
),
("forbidden", "403 Client Error: Forbidden for url: https://uptime.betterstack.com/api/v3/incidents"),
+ # Team members and roles are served from the account-level host, which needs its own
+ # entries — the Uptime-host patterns don't match a URL on it.
+ ("org_host_unauthorized", "401 Client Error: Unauthorized for url: https://betterstack.com/api/v2/roles"),
+ (
+ "org_host_forbidden",
+ "403 Client Error: Forbidden for url: https://betterstack.com/api/v2/team-members?per_page=50",
+ ),
+ # A multi-team token can't resolve which team's members to list.
+ (
+ "team_members_needs_a_team_scoped_token",
+ "422 Client Error: Unprocessable Entity for url: https://betterstack.com/api/v2/team-members?per_page=50",
+ ),
]
)
def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:
@@ -105,29 +126,45 @@ class TestBetterStackNonRetryableErrors:
class TestBetterStackResumableAndPipeline:
@parameterized.expand(
[
+ # (endpoint, primary keys, partition keys, partition mode, sort mode)
# Incidents partition on the stable started_at; ordering is unverified so the watermark
# commits at end of sync (sort_mode="desc").
- ("incidents", ["started_at"], "datetime", "desc"),
- ("monitors", ["created_at"], "datetime", "asc"),
- ("heartbeats", ["created_at"], "datetime", "asc"),
+ ("incidents", ["id"], ["started_at"], "datetime", "desc"),
+ ("monitors", ["id"], ["created_at"], "datetime", "asc"),
+ ("heartbeats", ["id"], ["created_at"], "datetime", "asc"),
+ # Fan-out rows arrive parent by parent, so their watermark commits at end of sync too.
+ # Their keys carry the parent id, without which every parent's rows collide.
+ ("incident_comments", ["incident_id", "id"], ["created_at"], "datetime", "desc"),
+ ("monitor_response_times", ["monitor_id", "region", "at"], ["at"], "datetime", "desc"),
+ ("monitor_availability", ["monitor_id"], None, None, "asc"),
+ # Members and pending invitations draw ids from separate spaces.
+ ("team_members", ["id", "type"], None, None, "asc"),
+ ("roles", ["id"], None, None, "asc"),
# Small collections whose timestamp columns aren't confirmed don't partition.
- ("monitor_groups", None, None, "asc"),
- ("status_pages", None, None, "asc"),
- ("on_calls", None, None, "asc"),
- ("escalation_policies", None, None, "asc"),
+ ("monitor_groups", ["id"], None, None, "asc"),
+ ("status_pages", ["id"], None, None, "asc"),
+ ("on_calls", ["id"], None, None, "asc"),
+ ("escalation_policies", ["id"], None, None, "asc"),
]
)
def test_source_for_pipeline_per_endpoint(
- self, endpoint: str, expected_keys: list[str] | None, expected_mode: str | None, expected_sort: str
+ self,
+ endpoint: str,
+ expected_primary_keys: list[str],
+ expected_keys: list[str] | None,
+ expected_mode: str | None,
+ expected_sort: str,
) -> None:
inputs = MagicMock()
inputs.schema_name = endpoint
inputs.should_use_incremental_field = False
+ manager = MagicMock()
+ manager.can_resume.return_value = False
response = BetterStackSource().source_for_pipeline(
- MagicMock(api_token="bs_test"), resumable_source_manager=MagicMock(), inputs=inputs
+ MagicMock(api_token="bs_test"), resumable_source_manager=manager, inputs=inputs
)
assert response.name == endpoint
- assert response.primary_keys == ["id"]
+ assert response.primary_keys == expected_primary_keys
assert response.partition_keys == expected_keys
assert response.partition_mode == expected_mode
assert response.sort_mode == expected_sort