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(data-warehouse): implement better_stack import source (#71154)

Tom Owersf0049aa9c87c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index fde66048628b..f4e7af34a308 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -74,6 +74,7 @@ the row lists both.
| bamboohr | HTTP | requests | ✅ |
| baseten | HTTP | requests | ✅ |
| beamer | HTTP | requests | ✅ |
+| better_stack | HTTP | requests | ✅ |
| bigmailer | HTTP | requests | ✅ |
| bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) |
| bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ |
@@ -557,7 +558,6 @@ doesn't conflict with concurrent PRs.
- babelforce
- backblaze
- basecamp
-- better_stack
- bettermode
- bigcommerce
- bitbucket
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
new file mode 100644
index 000000000000..dd6de37420c9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/better_stack.py
@@ -0,0 +1,242 @@
+import time
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode, urlsplit
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.better_stack.settings import (
+ BETTER_STACK_BASE_URL,
+ BETTER_STACK_ENDPOINTS,
+ BetterStackEndpointConfig,
+)
+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.resumable import ResumableSourceManager
+
+REQUEST_TIMEOUT_SECONDS = 60
+# Better Stack publishes no fixed quota — 429s carry a Retry-After header; cap how long we honor it.
+MAX_RETRY_AFTER_SECONDS = 60
+
+
+class BetterStackRetryableError(Exception):
+ pass
+
+
+class BetterStackUntrustedURLError(Exception):
+ pass
+
+
+def _validate_pagination_url(url: str) -> str:
+ """Pin every authenticated request to the Better Stack API origin.
+
+ Both resumed `next_url` values (loaded from Redis) and upstream `pagination.next` URLs are
+ followed verbatim with the customer's bearer token. Validating the scheme, host, and `/api/`
+ path prefix keeps a poisoned resume state or a hostile upstream response from retargeting the
+ 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/")
+ if not is_trusted:
+ raise BetterStackUntrustedURLError(f"Refusing to follow pagination URL outside {BETTER_STACK_BASE_URL}/")
+ return url
+
+
+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
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {api_token}"}
+
+
+def _build_url(base_url: str, params: dict[str, Any]) -> str:
+ if not params:
+ return base_url
+ return f"{base_url}?{urlencode(params)}"
+
+
+def _format_from_date(value: Any) -> str:
+ """Format an incremental cursor value as the YYYY-MM-DD date the incidents `from` filter takes."""
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return aware.astimezone(UTC).date().isoformat()
+ if isinstance(value, date):
+ return value.isoformat()
+ return str(value)
+
+
+def _clamp_future_value_to_now(value: Any) -> Any:
+ """Cap a future datetime/date cursor at now — asking for incidents newer than now is a no-op,
+ so clamping keeps the filter sane if a future-dated record ever pushes the cursor forward."""
+ now = datetime.now(UTC)
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return now if aware > now else value
+ if isinstance(value, date):
+ return now.date() if value > now.date() else value
+ return value
+
+
+def _build_initial_params(
+ config: BetterStackEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"per_page": config.page_size}
+
+ if config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value:
+ # The `from` filter is date-granular, so we re-fetch the watermark's whole day; merge on
+ # the primary key dedupes the overlap.
+ value = _clamp_future_value_to_now(db_incremental_field_last_value)
+ params["from"] = _format_from_date(value)
+
+ return params
+
+
+def _flatten_item(item: dict[str, Any]) -> dict[str, Any]:
+ """Flatten a JSON:API resource object's `attributes` into the root and keep `id`/`type`."""
+ flattened = {k: v for k, v in item.items() if k != "attributes"}
+ attributes = item.get("attributes")
+ if isinstance(attributes, dict):
+ flattened.update(attributes)
+ return flattened
+
+
+def _fetch_page_once(
+ session: requests.Session, page_url: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> dict:
+ response = session.get(page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429:
+ # Better Stack signals rate limiting with a Retry-After header; honor it before tenacity's
+ # exponential backoff kicks in.
+ retry_after = response.headers.get("Retry-After")
+ if retry_after is not None:
+ try:
+ sleep_seconds = int(retry_after)
+ except ValueError:
+ # Per RFC 7231, Retry-After may be an HTTP-date instead of a seconds count. We don't
+ # parse the date; fall back to the cap so we still back off rather than hammering.
+ sleep_seconds = MAX_RETRY_AFTER_SECONDS
+ time.sleep(min(sleep_seconds, MAX_RETRY_AFTER_SECONDS))
+ raise BetterStackRetryableError(f"Better Stack API rate limited: status=429, url={page_url}")
+
+ if response.status_code >= 500:
+ raise BetterStackRetryableError(
+ f"Better Stack API error (retryable): status={response.status_code}, url={page_url}"
+ )
+
+ if not response.ok:
+ logger.error(f"Better Stack API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+# Kept separate from `_fetch_page_once` so tests can exercise the request handling without
+# tenacity's retry waits.
+_fetch_page = retry(
+ retry=retry_if_exception_type((BetterStackRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)(_fetch_page_once)
+
+
+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
+ path = config.path if config else "/v2/monitors"
+ url = _build_url(f"{BETTER_STACK_BASE_URL}{path}", {"per_page": 1})
+ try:
+ response = make_tracked_session(capture=False).get(url, headers=_get_headers(api_token), timeout=10)
+ except Exception:
+ return None
+ return response.status_code
+
+
+def get_rows(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BetterStackResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[Any]:
+ config = BETTER_STACK_ENDPOINTS[endpoint]
+ headers = _get_headers(api_token)
+ # One session reused across pages so urllib3 keeps the connection alive.
+ # 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)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.next_url:
+ url = _validate_pagination_url(resume.next_url)
+ logger.debug(f"Better Stack: resuming {endpoint} from URL: {url}")
+ else:
+ params = _build_initial_params(config, should_use_incremental_field, db_incremental_field_last_value)
+ url = _build_url(f"{BETTER_STACK_BASE_URL}{config.path}", params)
+
+ while True:
+ data = _fetch_page(session, url, headers, logger)
+
+ items = data.get("data", [])
+ next_url = data.get("pagination", {}).get("next")
+ if next_url:
+ next_url = _validate_pagination_url(next_url)
+
+ if items:
+ # Yield one page at a time as a list[dict]; the pipeline buffers and batches for us.
+ yield [_flatten_item(item) for item in items]
+
+ if not next_url:
+ break
+
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it — merge
+ # dedupes on the primary key. Advance the URL before the next fetch to avoid re-looping it.
+ resumable_source_manager.save_state(BetterStackResumeConfig(next_url=next_url))
+ url = next_url
+
+
+def better_stack_source(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ 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]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ 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",
+ )
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
new file mode 100644
index 000000000000..cb359c550aa1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/canonical_descriptions.py
@@ -0,0 +1,115 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS = "https://betterstack.com/docs/uptime/api/getting-started-with-uptime-api/"
+
+# Descriptions are sourced from Better Stack's public Uptime API reference. Partial coverage is
+# fine — any endpoint, column, or table-level description not listed here falls back to LLM
+# enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "incidents": {
+ "description": "Downtime and alert incidents recorded by Better Stack, with their cause, acknowledgement, and resolution timeline.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the incident.",
+ "name": "Name of the monitor or heartbeat the incident belongs to.",
+ "url": "URL of the checked resource the incident relates to.",
+ "cause": "What caused the incident (e.g. a status code, timeout, or missed heartbeat).",
+ "started_at": "When the incident started.",
+ "acknowledged_at": "When the incident was acknowledged.",
+ "acknowledged_by": "Who acknowledged the incident.",
+ "resolved_at": "When the incident was resolved.",
+ "resolved_by": "Who or what resolved the incident.",
+ "response_content": "Response content captured when the incident was detected.",
+ },
+ },
+ "monitors": {
+ "description": "Uptime monitors configured in Better Stack, with their check settings and current status.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the monitor.",
+ "url": "URL or host the monitor checks.",
+ "pronounceable_name": "Human-readable name of the monitor.",
+ "monitor_type": "Type of check the monitor performs (e.g. status, keyword, ping, tcp).",
+ "monitor_group_id": "Identifier of the monitor group this monitor belongs to.",
+ "status": "Current status of the monitor (e.g. up, down, paused, validating).",
+ "check_frequency": "How often the monitor runs, in seconds.",
+ "last_checked_at": "When the monitor was last checked.",
+ "paused_at": "When the monitor was paused, if it is paused.",
+ "created_at": "When the monitor was created.",
+ "updated_at": "When the monitor was last updated.",
+ },
+ },
+ "monitor_groups": {
+ "description": "Groups used to organize uptime monitors.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the monitor group.",
+ "name": "Name of the monitor group.",
+ "sort_index": "Position of the group when sorting groups.",
+ "created_at": "When the group was created.",
+ "updated_at": "When the group was last updated.",
+ },
+ },
+ "heartbeats": {
+ "description": "Heartbeat (cron/background job) checks configured in Better Stack.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the heartbeat.",
+ "name": "Name of the heartbeat.",
+ "url": "URL the monitored service pings to report the heartbeat.",
+ "period": "Expected interval between heartbeats, in seconds.",
+ "grace": "Additional grace period before an incident is raised, in seconds.",
+ "heartbeat_group_id": "Identifier of the heartbeat group this heartbeat belongs to.",
+ "status": "Current status of the heartbeat.",
+ "paused_at": "When the heartbeat was paused, if it is paused.",
+ "created_at": "When the heartbeat was created.",
+ "updated_at": "When the heartbeat was last updated.",
+ },
+ },
+ "heartbeat_groups": {
+ "description": "Groups used to organize heartbeat checks.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the heartbeat group.",
+ "name": "Name of the heartbeat group.",
+ "sort_index": "Position of the group when sorting groups.",
+ "created_at": "When the group was created.",
+ "updated_at": "When the group was last updated.",
+ },
+ },
+ "status_pages": {
+ "description": "Public status pages hosted on Better Stack.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the status page.",
+ "company_name": "Company name shown on the status page.",
+ "company_url": "Company website linked from the status page.",
+ "subdomain": "Better Stack subdomain the status page is served on.",
+ "custom_domain": "Custom domain the status page is served on, if configured.",
+ "timezone": "Timezone used to display times on the status page.",
+ "history": "Number of days of incident history shown on the status page.",
+ "created_at": "When the status page was created.",
+ "updated_at": "When the status page was last updated.",
+ },
+ },
+ "on_calls": {
+ "description": "On-call calendars defining who is on call and when.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the on-call calendar.",
+ "name": "Name of the on-call calendar.",
+ },
+ },
+ "escalation_policies": {
+ "description": "Escalation policies describing how incidents are escalated to team members.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the escalation policy.",
+ "name": "Name of the escalation policy.",
+ "repeat_count": "How many times the escalation steps are repeated.",
+ "repeat_delay": "Delay between escalation repeats, in seconds.",
+ },
+ },
+}
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
new file mode 100644
index 000000000000..3458114fe3bf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/settings.py
@@ -0,0 +1,92 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+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"
+
+
+@dataclass
+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).
+ supports_incremental: bool = False
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable field to partition by — a creation/start timestamp, never `updated_at`.
+ partition_key: Optional[str] = None
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Documented default is 50 everywhere; standard v2 collections accept up to 250, the v3
+ # incidents endpoint caps at 50.
+ page_size: int = 50
+ should_sync_default: bool = True
+
+
+_STARTED_AT: list[IncrementalField] = [
+ {
+ "label": "started_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "started_at",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+]
+
+# 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.
+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.
+ "incidents": BetterStackEndpointConfig(
+ name="incidents",
+ path="/v3/incidents",
+ supports_incremental=True,
+ incremental_fields=_STARTED_AT,
+ partition_key="started_at",
+ page_size=50,
+ ),
+ "monitors": BetterStackEndpointConfig(
+ name="monitors",
+ path="/v2/monitors",
+ partition_key="created_at",
+ page_size=250,
+ ),
+ "monitor_groups": BetterStackEndpointConfig(
+ name="monitor_groups",
+ path="/v2/monitor-groups",
+ page_size=250,
+ ),
+ "heartbeats": BetterStackEndpointConfig(
+ name="heartbeats",
+ path="/v2/heartbeats",
+ partition_key="created_at",
+ page_size=250,
+ ),
+ "heartbeat_groups": BetterStackEndpointConfig(
+ name="heartbeat_groups",
+ path="/v2/heartbeat-groups",
+ page_size=250,
+ ),
+ "status_pages": BetterStackEndpointConfig(
+ name="status_pages",
+ path="/v2/status-pages",
+ page_size=250,
+ ),
+ # Small configuration collections — page size left at the documented default of 50 since
+ # their maximums aren't documented.
+ "on_calls": BetterStackEndpointConfig(
+ name="on_calls",
+ path="/v2/on-calls",
+ ),
+ "escalation_policies": BetterStackEndpointConfig(
+ name="escalation_policies",
+ path="/v2/policies",
+ ),
+}
+
+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 bf0b6e84ad0b..85226942119e 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
@@ -1,19 +1,45 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.better_stack.better_stack import (
+ BetterStackResumeConfig,
+ better_stack_source,
+ probe_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.better_stack.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.better_stack.settings import (
+ BETTER_STACK_ENDPOINTS,
+ ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BetterStackSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class BetterStackSource(SimpleSource[BetterStackSourceConfig]):
+class BetterStackSource(ResumableSource[BetterStackSourceConfig, BetterStackResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BETTERSTACK
@@ -24,7 +50,97 @@ class BetterStackSource(SimpleSource[BetterStackSourceConfig]):
name=SchemaExternalDataSourceType.BETTER_STACK,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Better Stack",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Better Stack API token to automatically pull your uptime monitoring and incident data into the PostHog Data warehouse.
+
+You can create an Uptime API token in your [Better Stack dashboard](https://uptime.betterstack.com) under Integrations → API tokens. A team-scoped token syncs that team's data; a global token spans all teams.""",
iconPath="/static/services/better_stack.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/better-stack",
+ keywords=["betterstack", "better uptime"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # 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.
+ "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.",
+ }
+
+ def get_schemas(
+ self,
+ config: BetterStackSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = BETTER_STACK_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint_config.supports_incremental,
+ supports_append=endpoint_config.supports_incremental,
+ incremental_fields=endpoint_config.incremental_fields,
+ should_sync_default=endpoint_config.should_sync_default,
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: BetterStackSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ status = probe_credentials(config.api_token, schema_name)
+
+ if status == 200:
+ return True, None
+ # At source-create (schema_name is None) a 403 means the token is genuine but scoped away
+ # from the probe resource — accept it; per-endpoint scope is checked when configuring a schema.
+ if status == 403 and schema_name is None:
+ return True, None
+ if status == 401:
+ return False, "Your Better Stack API token is invalid or has been revoked."
+ if status == 403:
+ return False, "Your Better Stack API token does not have access to this resource."
+ return False, "Could not validate your Better Stack API token. Please check the token and try again."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BetterStackResumeConfig]:
+ return ResumableSourceManager[BetterStackResumeConfig](inputs, BetterStackResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BetterStackSourceConfig,
+ resumable_source_manager: ResumableSourceManager[BetterStackResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return better_stack_source(
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
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
new file mode 100644
index 000000000000..11a7190d3210
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/tests/test_better_stack.py
@@ -0,0 +1,271 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+from freezegun import freeze_time
+from unittest import mock
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.better_stack import better_stack
+from products.warehouse_sources.backend.temporal.data_imports.sources.better_stack.better_stack import (
+ BetterStackResumeConfig,
+ BetterStackUntrustedURLError,
+ _build_initial_params,
+ _fetch_page_once,
+ _flatten_item,
+ _format_from_date,
+ _validate_pagination_url,
+ get_rows,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.better_stack.settings import (
+ BETTER_STACK_ENDPOINTS,
+)
+
+
+class TestFormatFromDate:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04"),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04"),
+ ("date_value", date(2026, 3, 4), "2026-03-04"),
+ ("string_passthrough", "2026-03-04", "2026-03-04"),
+ ]
+ )
+ def test_formats_as_date_only(self, _name: str, value: object, expected: str) -> None:
+ # Better Stack's `from` filter takes YYYY-MM-DD, not a full timestamp.
+ assert _format_from_date(value) == expected
+
+
+class TestBuildInitialParams:
+ def test_incremental_endpoint_filters_from_watermark_date(self) -> None:
+ params = _build_initial_params(
+ BETTER_STACK_ENDPOINTS["incidents"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ )
+ assert params == {"per_page": 50, "from": "2026-03-04"}
+
+ def test_incremental_first_sync_has_no_filter(self) -> None:
+ params = _build_initial_params(
+ BETTER_STACK_ENDPOINTS["incidents"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ )
+ assert params == {"per_page": 50}
+
+ @freeze_time("2026-06-15T12:00:00Z")
+ def test_future_cursor_is_clamped(self) -> None:
+ params = _build_initial_params(
+ BETTER_STACK_ENDPOINTS["incidents"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2027, 2, 5, tzinfo=UTC),
+ )
+ assert params["from"] == "2026-06-15"
+
+ def test_full_refresh_endpoint_never_filters(self) -> None:
+ params = _build_initial_params(
+ BETTER_STACK_ENDPOINTS["monitors"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ )
+ assert params == {"per_page": 250}
+
+
+class TestFlattenItem:
+ def test_attributes_hoisted_to_root_and_id_type_kept(self) -> None:
+ item = {
+ "id": "123",
+ "type": "incident",
+ "attributes": {"name": "API", "cause": "Status 500", "started_at": "2026-01-01T00:00:00Z"},
+ }
+ assert _flatten_item(item) == {
+ "id": "123",
+ "type": "incident",
+ "name": "API",
+ "cause": "Status 500",
+ "started_at": "2026-01-01T00:00:00Z",
+ }
+
+ def test_missing_attributes_is_safe(self) -> None:
+ assert _flatten_item({"id": "123", "type": "incident"}) == {"id": "123", "type": "incident"}
+
+
+class TestFetchPage:
+ def test_429_honors_retry_after_and_raises_retryable(self) -> None:
+ response = MagicMock(status_code=429, headers={"Retry-After": "7"})
+ session = MagicMock()
+ session.get.return_value = response
+ with mock.patch.object(better_stack.time, "sleep") as sleep:
+ try:
+ # Call the undecorated function so tenacity doesn't retry 5 times in the test.
+ _fetch_page_once(session, "https://uptime.betterstack.com/api/v2/monitors", {}, MagicMock())
+ raise AssertionError("expected BetterStackRetryableError")
+ except better_stack.BetterStackRetryableError:
+ pass
+ sleep.assert_called_once_with(7)
+
+ def test_429_retry_after_is_capped(self) -> None:
+ response = MagicMock(status_code=429, headers={"Retry-After": "3600"})
+ session = MagicMock()
+ session.get.return_value = response
+ with mock.patch.object(better_stack.time, "sleep") as sleep:
+ try:
+ _fetch_page_once(session, "https://uptime.betterstack.com/api/v2/monitors", {}, MagicMock())
+ raise AssertionError("expected BetterStackRetryableError")
+ except better_stack.BetterStackRetryableError:
+ pass
+ sleep.assert_called_once_with(better_stack.MAX_RETRY_AFTER_SECONDS)
+
+ def test_429_http_date_retry_after_falls_back_to_cap(self) -> None:
+ # RFC 7231 allows Retry-After to be an HTTP-date; we can't int() it, so we still back off.
+ response = MagicMock(status_code=429, headers={"Retry-After": "Wed, 21 Oct 2015 07:28:00 GMT"})
+ session = MagicMock()
+ session.get.return_value = response
+ with mock.patch.object(better_stack.time, "sleep") as sleep:
+ try:
+ _fetch_page_once(session, "https://uptime.betterstack.com/api/v2/monitors", {}, MagicMock())
+ raise AssertionError("expected BetterStackRetryableError")
+ except better_stack.BetterStackRetryableError:
+ pass
+ sleep.assert_called_once_with(better_stack.MAX_RETRY_AFTER_SECONDS)
+
+
+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"
+ assert _validate_pagination_url(url) == url
+
+ @parameterized.expand(
+ [
+ ("other_host", "https://evil.example.com/api/v3/incidents"),
+ ("http_downgrade", "http://uptime.betterstack.com/api/v3/incidents"),
+ ("userinfo_confusion", "https://[email protected]/api/v3/incidents"),
+ ("wrong_path", "https://uptime.betterstack.com/steal-token"),
+ ]
+ )
+ def test_off_origin_urls_are_refused(self, _name: str, url: str) -> None:
+ # A poisoned resume state or hostile response must not retarget the bearer-token request.
+ try:
+ _validate_pagination_url(url)
+ raise AssertionError("expected BetterStackUntrustedURLError")
+ except BetterStackUntrustedURLError:
+ pass
+
+
+class _FakeResumableManager:
+ def __init__(self, state: BetterStackResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[BetterStackResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> BetterStackResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: BetterStackResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(manager: _FakeResumableManager, monkeypatch: Any, pages: dict[str, Any], **kwargs: Any) -> list[dict]:
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:
+ return pages[url]
+
+ monkeypatch.setattr(better_stack, "_fetch_page", fake_fetch)
+
+ rows: list[dict] = []
+ for page in get_rows(
+ api_token="bs_test",
+ endpoint="incidents",
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ ):
+ rows.extend(page)
+ return rows
+
+ def test_follows_pagination_next_and_flattens(self, monkeypatch: Any) -> None:
+ first = "https://uptime.betterstack.com/api/v3/incidents?per_page=50"
+ second = "https://uptime.betterstack.com/api/v3/incidents?page=2&per_page=50"
+ pages = {
+ first: {
+ "data": [{"id": "1", "type": "incident", "attributes": {"cause": "Timeout"}}],
+ "pagination": {"next": second},
+ },
+ second: {
+ "data": [{"id": "2", "type": "incident", "attributes": {"cause": "Status 500"}}],
+ "pagination": {"next": None},
+ },
+ }
+ rows = self._collect(_FakeResumableManager(), monkeypatch, pages)
+ assert rows == [
+ {"id": "1", "type": "incident", "cause": "Timeout"},
+ {"id": "2", "type": "incident", "cause": "Status 500"},
+ ]
+
+ def test_saves_state_after_each_page_except_the_last(self, monkeypatch: Any) -> None:
+ first = "https://uptime.betterstack.com/api/v3/incidents?per_page=50"
+ second = "https://uptime.betterstack.com/api/v3/incidents?page=2&per_page=50"
+ pages = {
+ first: {"data": [{"id": "1", "attributes": {}}], "pagination": {"next": second}},
+ second: {"data": [{"id": "2", "attributes": {}}], "pagination": {"next": None}},
+ }
+ manager = _FakeResumableManager()
+ self._collect(manager, monkeypatch, pages)
+ # State saved once (pointing at the second page) so a crash re-yields that page; nothing
+ # is saved after the final page (no next link).
+ assert [s.next_url for s in manager.saved] == [second]
+
+ def test_resumes_from_saved_next_url(self, monkeypatch: Any) -> None:
+ resume_url = "https://uptime.betterstack.com/api/v3/incidents?page=3&per_page=50"
+ pages = {resume_url: {"data": [{"id": "9", "attributes": {"cause": "Z"}}], "pagination": {"next": None}}}
+ manager = _FakeResumableManager(BetterStackResumeConfig(next_url=resume_url))
+ rows = self._collect(manager, monkeypatch, pages)
+ # Starts at the resumed URL, not the freshly-built first page.
+ assert rows == [{"id": "9", "cause": "Z"}]
+
+ def test_empty_collection_yields_nothing(self, monkeypatch: Any) -> None:
+ first = "https://uptime.betterstack.com/api/v3/incidents?per_page=50"
+ pages = {first: {"data": [], "pagination": {"next": None}}}
+ rows = self._collect(_FakeResumableManager(), monkeypatch, pages)
+ assert rows == []
+
+ def test_off_origin_next_url_is_refused(self, monkeypatch: Any) -> None:
+ first = "https://uptime.betterstack.com/api/v3/incidents?per_page=50"
+ pages = {
+ first: {
+ "data": [{"id": "1", "attributes": {}}],
+ "pagination": {"next": "https://evil.example.com/api/v3/incidents?page=2"},
+ }
+ }
+ try:
+ self._collect(_FakeResumableManager(), monkeypatch, pages)
+ raise AssertionError("expected BetterStackUntrustedURLError")
+ except BetterStackUntrustedURLError:
+ pass
+
+ def test_poisoned_resume_url_is_refused(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(BetterStackResumeConfig(next_url="https://evil.example.com/api/v3/incidents"))
+ try:
+ self._collect(manager, monkeypatch, pages={})
+ raise AssertionError("expected BetterStackUntrustedURLError")
+ except BetterStackUntrustedURLError:
+ pass
+
+
+class TestProbeCredentials:
+ @parameterized.expand([("ok", 200), ("unauthorized", 401), ("forbidden", 403)])
+ def test_returns_status_code(self, _name: str, status_code: int) -> None:
+ session = MagicMock()
+ session.get.return_value = MagicMock(status_code=status_code)
+ with mock.patch.object(better_stack, "make_tracked_session", return_value=session):
+ assert better_stack.probe_credentials("bs_test", "incidents") == status_code
+
+ def test_connection_failure_returns_none(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = Exception("boom")
+ with mock.patch.object(better_stack, "make_tracked_session", return_value=session):
+ assert better_stack.probe_credentials("bs_test") is None
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
new file mode 100644
index 000000000000..f0a5e374664d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/tests/test_better_stack_source.py
@@ -0,0 +1,177 @@
+from unittest import mock
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.better_stack import (
+ source as better_stack_source_module,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.better_stack.better_stack import (
+ BetterStackResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.better_stack.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.better_stack.source import BetterStackSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestBetterStackSourceConfig:
+ def test_source_type(self) -> None:
+ assert BetterStackSource().source_type == ExternalDataSourceType.BETTERSTACK
+
+ def test_config_basics(self) -> None:
+ config = BetterStackSource().get_source_config
+ assert config.label == "Better Stack"
+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source ships visible — the scaffold's unreleasedSource flag must stay gone.
+ assert not config.unreleasedSource
+
+ def test_single_password_api_token_field(self) -> None:
+ fields = BetterStackSource().get_source_config.fields
+ assert len(fields) == 1
+ field = fields[0]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.name == "api_token"
+ assert field.required is True
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+
+
+class TestBetterStackGetSchemas:
+ def test_returns_every_endpoint(self) -> None:
+ schemas = BetterStackSource().get_schemas(MagicMock(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @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),
+ ]
+ )
+ def test_incremental_support_matches_settings(self, endpoint: str, expected_incremental: 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 bool(schema.incremental_fields) is expected_incremental
+
+ def test_names_filter(self) -> None:
+ schemas = BetterStackSource().get_schemas(MagicMock(), team_id=1, names=["incidents", "monitors"])
+ assert {s.name for s in schemas} == {"incidents", "monitors"}
+
+
+class TestBetterStackValidateCredentials:
+ @parameterized.expand(
+ [
+ # (probe status, schema_name, expected_ok)
+ ("ok", 200, None, True),
+ ("ok_for_schema", 200, "incidents", True),
+ # A 403 at source-create is a genuine token scoped away from the probe resource — accept it.
+ ("forbidden_at_create_accepted", 403, None, True),
+ # A 403 while configuring a specific schema means no access to that resource — reject.
+ ("forbidden_for_schema_rejected", 403, "incidents", False),
+ ("unauthorized_rejected", 401, None, False),
+ ("connection_failure_rejected", None, None, False),
+ ("unexpected_status_rejected", 500, None, False),
+ ]
+ )
+ def test_status_mapping(
+ self, _name: str, probe_status: int | None, schema_name: str | None, expected_ok: bool
+ ) -> None:
+ with mock.patch.object(better_stack_source_module, "probe_credentials", return_value=probe_status):
+ ok, error = BetterStackSource().validate_credentials(
+ MagicMock(api_token="bs_test"), team_id=1, schema_name=schema_name
+ )
+ assert ok is expected_ok
+ assert (error is None) is expected_ok
+
+
+class TestBetterStackNonRetryableErrors:
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "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"),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:
+ non_retryable = BetterStackSource().get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ (
+ "rate_limited",
+ "429 Client Error: Too Many Requests for url: https://uptime.betterstack.com/api/v3/incidents",
+ ),
+ (
+ "server_error",
+ "500 Server Error: Internal Server Error for url: https://uptime.betterstack.com/api/v2/monitors",
+ ),
+ ("read_timeout", "HTTPSConnectionPool(host='uptime.betterstack.com', port=443): Read timed out."),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:
+ non_retryable = BetterStackSource().get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable)
+
+
+class TestBetterStackResumableAndPipeline:
+ def test_resumable_manager_bound_to_resume_config(self) -> None:
+ manager = BetterStackSource().get_resumable_source_manager(MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is BetterStackResumeConfig
+
+ @parameterized.expand(
+ [
+ # 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"),
+ # 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"),
+ ]
+ )
+ def test_source_for_pipeline_per_endpoint(
+ self, endpoint: 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
+ response = BetterStackSource().source_for_pipeline(
+ MagicMock(api_token="bs_test"), resumable_source_manager=MagicMock(), inputs=inputs
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ assert response.partition_keys == expected_keys
+ assert response.partition_mode == expected_mode
+ assert response.sort_mode == expected_sort
+
+
+class TestBetterStackCanonicalDescriptions:
+ def test_descriptions_keyed_by_endpoint_name(self) -> None:
+ descriptions = BetterStackSource().get_canonical_descriptions()
+ # Every documented key must be a real endpoint so enrichment binds to the right table.
+ assert set(descriptions).issubset(set(ENDPOINTS))
+ assert "incidents" in descriptions
+ assert descriptions["incidents"]["columns"]["id"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index f7494e4970a8..c7e00195ce65 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -490,7 +490,7 @@ class BeamerSourceConfig(config.Config):
@config.config
class BetterStackSourceConfig(config.Config):
- pass
+ api_token: str
@config.config