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 uptimerobot import source (#71170)

Tom Owerse8c639340f76
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 8c6eef359a1b..ae6eaa072128 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -497,6 +497,7 @@ the row lists both.
| unleash | HTTP | requests | ✅ |
| unstructured | HTTP | requests | ✅ |
| upstash | HTTP | requests | ✅ |
+| uptimerobot | HTTP | requests | ✅ |
| vantage | HTTP | requests | ✅ |
| vapi | HTTP | requests | ✅ |
| vellum | HTTP | requests | ✅ |
@@ -960,7 +961,6 @@ doesn't conflict with concurrent PRs.
- tyntec_sms
- uppromote
- uptick
-- uptimerobot
- us_census
- usersnap
- uservoice
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 aab199ec6a67..52da6a9c9828 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
@@ -4504,7 +4504,7 @@ class UptickSourceConfig(config.Config):
@config.config
class UptimerobotSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uptimerobot/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uptimerobot/canonical_descriptions.py
new file mode 100644
index 000000000000..67faa9fa3f5f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uptimerobot/canonical_descriptions.py
@@ -0,0 +1,84 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://uptimerobot.com/api/"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "monitors": {
+ "description": "A monitored endpoint (website, ping, port, keyword, or heartbeat check) with its current status and uptime ratios.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier of the monitor.",
+ "friendly_name": "Display name given to the monitor.",
+ "url": "The URL or IP address being monitored.",
+ "type": "Monitor type: 1 = HTTP(S), 2 = keyword, 3 = ping, 4 = port, 5 = heartbeat.",
+ "sub_type": "For port monitors, the service checked: 1 = HTTP, 2 = HTTPS, 3 = FTP, 4 = SMTP, 5 = POP3, 6 = IMAP, 99 = custom port.",
+ "keyword_type": "For keyword monitors, whether the check alerts when the keyword exists (1) or does not exist (2).",
+ "keyword_value": "For keyword monitors, the keyword searched for in the response body.",
+ "port": "For port monitors, the port number checked.",
+ "interval": "Interval between checks, in seconds.",
+ "status": "Current status: 0 = paused, 1 = not checked yet, 2 = up, 8 = seems down, 9 = down.",
+ "create_datetime": "Unix timestamp of when the monitor was created.",
+ "custom_uptime_ratio": "Dash-separated uptime ratios for the last 1, 7, 30, and 365 days (e.g. 100.000-99.987-99.998-99.999).",
+ "all_time_uptime_ratio": "Uptime ratio since the monitor was created, as a percentage.",
+ },
+ },
+ "monitor_logs": {
+ "description": "Up/down/pause event log entries for each monitor, one row per event.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "monitor_id": "Identifier of the monitor the log entry belongs to.",
+ "type": "Event type: 1 = down, 2 = up, 98 = monitor started, 99 = monitor paused.",
+ "datetime": "Unix timestamp of when the event occurred.",
+ "duration": "Duration of the event state, in seconds.",
+ "reason": "Reason for the event, with a code and human-readable detail (e.g. HTTP status or timeout).",
+ },
+ },
+ "response_times": {
+ "description": "Response-time samples recorded for each monitor's checks.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "monitor_id": "Identifier of the monitor the sample belongs to.",
+ "datetime": "Unix timestamp of when the response time was recorded.",
+ "value": "Response time in milliseconds.",
+ },
+ },
+ "alert_contacts": {
+ "description": "Contacts notified when a monitor changes state (email, SMS, webhook, Slack, etc.).",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier of the alert contact.",
+ "friendly_name": "Display name given to the alert contact.",
+ "type": "Contact channel: 1 = SMS, 2 = email, 3 = Twitter, 5 = webhook, 6 = Pushbullet, 7 = Zapier, 9 = Pushover, 11 = Slack, and other integration types.",
+ "status": "Contact status: 0 = not activated, 1 = paused, 2 = active.",
+ "value": "The contact's destination for plain channels: email address (type 2), phone number (type 1), or handle (type 3). Webhook and integration values embed secret tokens, so they're redacted to null — only these plain-destination types are synced.",
+ },
+ },
+ "maintenance_windows": {
+ "description": "Scheduled maintenance windows during which monitors pause and alerts are suppressed.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier of the maintenance window.",
+ "friendly_name": "Display name given to the maintenance window.",
+ "type": "Recurrence: 1 = once, 2 = daily, 3 = weekly, 4 = monthly.",
+ "value": "For weekly/monthly windows, the days it applies to (e.g. 2-4-5 for Tuesday, Thursday, Friday).",
+ "start_time": "Start time of the window (Unix timestamp for one-off windows, HH:mm for recurring ones).",
+ "duration": "Duration of the maintenance window, in minutes.",
+ "status": "Window status: 0 = paused, 1 = active.",
+ },
+ },
+ "status_pages": {
+ "description": "Public status pages (PSPs) that display the status of selected monitors.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier of the status page.",
+ "friendly_name": "Display name given to the status page.",
+ "standard_url": "The default stats.uptimerobot.com URL of the status page.",
+ "custom_url": "Custom domain configured for the status page, if any.",
+ "monitors": "Monitors shown on the status page (0 means all monitors).",
+ "sort": "Sort order of monitors on the page: 1 = friendly name (a-z), 2 = friendly name (z-a), 3 = status (up-down-paused), 4 = status (down-up-paused).",
+ "status": "Status page status: 0 = paused, 1 = active.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uptimerobot/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uptimerobot/settings.py
new file mode 100644
index 000000000000..0d7a048c13ca
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uptimerobot/settings.py
@@ -0,0 +1,115 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# UptimeRobot v2 caps `limit` at 50 on every paginated list endpoint.
+PAGE_LIMIT = 50
+
+# UptimeRobot rejects response-time windows wider than 7 days, so history is walked in 7-day chunks.
+RESPONSE_TIMES_WINDOW_DAYS = 7
+# First response_times sync walks back this far. Free plans only retain recent response times, so a
+# deeper backfill would mostly fetch empty windows; merge dedupes any overlap on later runs.
+RESPONSE_TIMES_INITIAL_LOOKBACK_DAYS = 30
+
+
+def _datetime_incremental_fields() -> list[IncrementalField]:
+ # UptimeRobot timestamps are Unix epoch seconds (integers) named `datetime`.
+ return [
+ {
+ "label": "datetime",
+ "type": IncrementalFieldType.DateTime,
+ "field": "datetime",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ]
+
+
+@dataclass
+class UptimeRobotEndpointConfig:
+ name: str
+ # v2 API method (e.g. "getMonitors"). Every v2 call is a form-encoded POST with the api_key in
+ # the body — there are no plain GET endpoints.
+ method: str
+ # Key in the response JSON holding the row list ("monitors", "alert_contacts", "mwindows", "psps").
+ response_key: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Stable datetime-ish field to partition by (Unix epoch int). None disables partitioning.
+ partition_key: Optional[str] = None
+ partition_format: Literal["month", "week", "day"] = "month"
+ supports_incremental: bool = False
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Extra form params sent on every request for this endpoint.
+ extra_params: dict[str, str | int] = field(default_factory=dict)
+ # Fan-out endpoints materialize a nested per-monitor list ("logs" / "response_times") from
+ # getMonitors as one row per entry, keyed back to the monitor id.
+ monitor_list_key: Optional[Literal["logs", "response_times"]] = None
+ # Redact the `value` of credential-bearing alert contacts (webhook/integration URLs and tokens).
+ redact_alert_contact_values: bool = False
+
+
+UPTIMEROBOT_ENDPOINTS: dict[str, UptimeRobotEndpointConfig] = {
+ # Small table (one row per monitor) with mutable status/uptime-ratio fields and no server-side
+ # updated-since filter — full refresh every run.
+ "monitors": UptimeRobotEndpointConfig(
+ name="monitors",
+ method="getMonitors",
+ response_key="monitors",
+ partition_key="create_datetime",
+ extra_params={
+ # Adds `custom_uptime_ratio` (dash-separated 1/7/30/365-day ratios) and
+ # `all_time_uptime_ratio` columns for SLA reporting.
+ "custom_uptime_ratios": "1-7-30-365",
+ "all_time_uptime_ratio": 1,
+ },
+ ),
+ # Up/down/pause event log entries nested under each monitor. Entries are immutable and carry a
+ # Unix `datetime`, which doubles as the incremental cursor and a stable partition key.
+ "monitor_logs": UptimeRobotEndpointConfig(
+ name="monitor_logs",
+ method="getMonitors",
+ response_key="monitors",
+ monitor_list_key="logs",
+ primary_keys=["monitor_id", "datetime", "type"],
+ partition_key="datetime",
+ supports_incremental=True,
+ incremental_fields=_datetime_incremental_fields(),
+ extra_params={"logs": 1},
+ ),
+ # Response-time samples nested under each monitor; immutable {datetime, value} pairs fetched in
+ # 7-day windows. Higher volume than logs, so partition by week.
+ "response_times": UptimeRobotEndpointConfig(
+ name="response_times",
+ method="getMonitors",
+ response_key="monitors",
+ monitor_list_key="response_times",
+ primary_keys=["monitor_id", "datetime"],
+ partition_key="datetime",
+ partition_format="week",
+ supports_incremental=True,
+ incremental_fields=_datetime_incremental_fields(),
+ extra_params={"response_times": 1},
+ ),
+ "alert_contacts": UptimeRobotEndpointConfig(
+ name="alert_contacts",
+ method="getAlertContacts",
+ response_key="alert_contacts",
+ redact_alert_contact_values=True,
+ ),
+ "maintenance_windows": UptimeRobotEndpointConfig(
+ name="maintenance_windows",
+ method="getMWindows",
+ response_key="mwindows",
+ ),
+ "status_pages": UptimeRobotEndpointConfig(
+ name="status_pages",
+ method="getPSPs",
+ response_key="psps",
+ ),
+}
+
+ENDPOINTS = tuple(UPTIMEROBOT_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in UPTIMEROBOT_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uptimerobot/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uptimerobot/source.py
index f40a3f9a226d..161e4dce86a3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/uptimerobot/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uptimerobot/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.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 UptimerobotSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.uptimerobot.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ RESPONSE_TIMES_INITIAL_LOOKBACK_DAYS,
+ UPTIMEROBOT_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.uptimerobot.uptimerobot import (
+ AUTH_ERROR_PREFIX,
+ UptimeRobotResumeConfig,
+ uptimerobot_source,
+ validate_credentials as validate_uptimerobot_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class UptimerobotSource(SimpleSource[UptimerobotSourceConfig]):
+class UptimerobotSource(ResumableSource[UptimerobotSourceConfig, UptimeRobotResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.UPTIMEROBOT
@@ -24,7 +50,98 @@ class UptimerobotSource(SimpleSource[UptimerobotSourceConfig]):
name=SchemaExternalDataSourceType.UPTIMEROBOT,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="UptimeRobot",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your UptimeRobot API key to pull your uptime monitoring data into the PostHog Data warehouse.
+
+Use your account's **read-only API key**, created under [Integrations & API](https://dashboard.uptimerobot.com/integrations) in your UptimeRobot dashboard. Monitor-specific API keys only grant access to a single monitor, so the alert contacts, maintenance windows, and status pages tables won't sync with one.""",
iconPath="/static/services/uptimerobot.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/uptimerobot",
+ keywords=["uptime", "monitoring"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="ur1234567-...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.uptimerobot.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # UptimeRobot returns HTTP 200 with an in-body error for bad credentials; the transport
+ # raises with this stable prefix when the API rejects the key. Retrying can never fix a
+ # credential problem, so stop the sync.
+ AUTH_ERROR_PREFIX: "Your UptimeRobot API key is invalid or has been revoked. Create a new read-only API key under Integrations & API in your UptimeRobot dashboard, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: UptimerobotSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _description(endpoint: str) -> str | None:
+ if endpoint == "monitor_logs":
+ return "Up/down/pause event history per monitor. Incremental syncs only fetch logs newer than the last synced event"
+ if endpoint == "response_times":
+ return (
+ f"Response-time samples per monitor, fetched in 7-day windows. "
+ f"Only syncs the last {RESPONSE_TIMES_INITIAL_LOOKBACK_DAYS} days on initial sync"
+ )
+ return None
+
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = UPTIMEROBOT_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint_config.supports_incremental,
+ supports_append=endpoint_config.supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ description=_description(endpoint),
+ )
+
+ 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: UptimerobotSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_uptimerobot_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[UptimeRobotResumeConfig]:
+ return ResumableSourceManager[UptimeRobotResumeConfig](inputs, UptimeRobotResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: UptimerobotSourceConfig,
+ resumable_source_manager: ResumableSourceManager[UptimeRobotResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return uptimerobot_source(
+ api_key=config.api_key,
+ 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/uptimerobot/tests/test_uptimerobot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uptimerobot/tests/test_uptimerobot.py
new file mode 100644
index 000000000000..cecc3afd696a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uptimerobot/tests/test_uptimerobot.py
@@ -0,0 +1,510 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.uptimerobot import uptimerobot
+from products.warehouse_sources.backend.temporal.data_imports.sources.uptimerobot.settings import (
+ PAGE_LIMIT,
+ RESPONSE_TIMES_INITIAL_LOOKBACK_DAYS,
+ UPTIMEROBOT_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.uptimerobot.uptimerobot import (
+ AUTH_ERROR_PREFIX,
+ UptimeRobotAPIError,
+ UptimeRobotAuthError,
+ UptimeRobotResumeConfig,
+ UptimeRobotRetryableError,
+ _next_offset,
+ _post,
+ _scrub_alert_contact,
+ _to_unix_timestamp,
+ get_rows,
+ uptimerobot_source,
+)
+
+_DAY = 86400
+
+
+class TestToUnixTimestamp:
+ @parameterized.expand(
+ [
+ ("int_epoch", 1750000000, 1750000000),
+ ("float_epoch", 1750000000.9, 1750000000),
+ ("aware_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), 1772593094),
+ ("naive_datetime_treated_as_utc", datetime(2026, 3, 4, 2, 58, 14), 1772593094),
+ ("date_value", date(2026, 3, 4), 1772582400),
+ ("numeric_string", "1750000000", 1750000000),
+ ("iso_string", "2026-03-04T02:58:14+00:00", 1772593094),
+ ("iso_string_z_suffix", "2026-03-04T02:58:14Z", 1772593094),
+ ("junk_string", "not-a-date", None),
+ ("empty_string", "", None),
+ ("none_value", None, None),
+ ("bool_value", True, None),
+ ]
+ )
+ def test_coercion(self, _name: str, value: Any, expected: int | None) -> None:
+ assert _to_unix_timestamp(value) == expected
+
+
+class TestScrubAlertContact:
+ @parameterized.expand(
+ [
+ # Credential-bearing channels: value is a URL/token that could forge notifications.
+ ("webhook", 5, "https://hooks.example.com/abc?token=s3cret", None),
+ ("slack", 11, "https://hooks.slack.com/services/T/B/xox", None),
+ ("unknown_integration", 99, "https://integration.example.com/tok", None),
+ # Fail closed when the type is missing or non-numeric.
+ ("missing_type", None, "https://hooks.example.com/abc?token=s3cret", None),
+ ("non_numeric_type", "webhook", "https://hooks.example.com/abc?token=s3cret", None),
+ # Plain destinations: kept for analytical use.
+ ("sms", 1, "+15551234567", "+15551234567"),
+ ("twitter", 3, "@statuspage", "@statuspage"),
+ ]
+ )
+ def test_value_redacted_unless_plain_destination(
+ self, _name: str, contact_type: Any, value: str, expected_value: str | None
+ ) -> None:
+ row: dict[str, Any] = {"id": 1, "friendly_name": "on-call", "status": 2, "value": value}
+ if contact_type is not None:
+ row["type"] = contact_type
+
+ scrubbed = _scrub_alert_contact(row)
+
+ assert scrubbed["value"] == expected_value
+ # Non-secret metadata is always preserved.
+ assert scrubbed["id"] == 1
+ assert scrubbed["friendly_name"] == "on-call"
+ assert scrubbed["status"] == 2
+
+ def test_row_without_value_is_untouched(self) -> None:
+ row = {"id": 1, "type": 5}
+ assert _scrub_alert_contact(row) == row
+
+
+class TestNextOffset:
+ @parameterized.expand(
+ [
+ ("nested_more_pages", {"pagination": {"offset": 0, "limit": 50, "total": 120}}, 0, 50, 50),
+ ("nested_exhausted", {"pagination": {"offset": 100, "limit": 50, "total": 120}}, 100, 20, None),
+ ("nested_exact_boundary", {"pagination": {"offset": 50, "limit": 50, "total": 100}}, 50, 50, None),
+ # getAlertContacts puts offset/limit/total at the top level, as strings.
+ ("top_level_strings_more", {"offset": "0", "limit": "50", "total": "70"}, 0, 50, 50),
+ ("top_level_strings_exhausted", {"offset": "50", "limit": "50", "total": "70"}, 50, 20, None),
+ ("missing_metadata_full_page", {}, 0, PAGE_LIMIT, PAGE_LIMIT),
+ ("missing_metadata_partial_page", {}, 0, 5, None),
+ ]
+ )
+ def test_next_offset(
+ self, _name: str, payload: dict, requested_offset: int, page_len: int, expected: int | None
+ ) -> None:
+ assert _next_offset(payload, requested_offset, page_len) == expected
+
+
+def _response(status_code: int = 200, payload: dict | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = payload if payload is not None else {}
+ return response
+
+
+class TestPost:
+ def _call(self, response: MagicMock) -> dict:
+ session = MagicMock()
+ session.post.return_value = response
+ # Call the undecorated function so tenacity's exponential backoff doesn't sleep in tests.
+ return _post.__wrapped__(session, "getMonitors", {"api_key": "k"}, MagicMock()) # type: ignore[attr-defined]
+
+ def test_ok_payload_returned(self) -> None:
+ payload = {"stat": "ok", "monitors": [{"id": 1}]}
+ assert self._call(_response(payload=payload)) == payload
+
+ def test_invalid_api_key_raises_auth_error(self) -> None:
+ # Verified against the live API: bad keys return HTTP 200 with an in-body error.
+ payload = {
+ "stat": "fail",
+ "error": {"type": "invalid_parameter", "parameter_name": "api_key", "message": "api_key is invalid."},
+ }
+ with pytest.raises(UptimeRobotAuthError, match=AUTH_ERROR_PREFIX):
+ self._call(_response(payload=payload))
+
+ def test_other_in_body_error_raises_api_error(self) -> None:
+ payload = {"stat": "fail", "error": {"type": "invalid_parameter", "parameter_name": "offset"}}
+ with pytest.raises(UptimeRobotAPIError):
+ self._call(_response(payload=payload))
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 502)])
+ def test_transient_statuses_raise_retryable(self, _name: str, status_code: int) -> None:
+ with pytest.raises(UptimeRobotRetryableError):
+ self._call(_response(status_code=status_code))
+
+
+class _FakeResumableManager:
+ def __init__(self, state: UptimeRobotResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[UptimeRobotResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> UptimeRobotResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: UptimeRobotResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _patch_post(monkeypatch: Any, responder: Any) -> list[dict]:
+ requests_made: list[dict] = []
+
+ def fake_post(session: Any, method: str, data: dict, logger: Any) -> dict:
+ requests_made.append({"method": method, **data})
+ return responder(method, data)
+
+ monkeypatch.setattr(uptimerobot, "_post", fake_post)
+ monkeypatch.setattr(uptimerobot, "make_tracked_session", lambda: MagicMock())
+ return requests_made
+
+
+def _collect(manager: _FakeResumableManager, endpoint: str, **kwargs: Any) -> list[dict]:
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_key="key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ ):
+ rows.extend(batch)
+ return rows
+
+
+class TestTopLevelRows:
+ def test_paginates_until_total_reached(self, monkeypatch: Any) -> None:
+ def responder(method: str, data: dict) -> dict:
+ offset = data["offset"]
+ if offset == 0:
+ return {
+ "stat": "ok",
+ "pagination": {"offset": 0, "limit": 50, "total": 51},
+ "monitors": [{"id": n} for n in range(50)],
+ }
+ return {
+ "stat": "ok",
+ "pagination": {"offset": 50, "limit": 50, "total": 51},
+ "monitors": [{"id": 50}],
+ }
+
+ requests_made = _patch_post(monkeypatch, responder)
+ rows = _collect(_FakeResumableManager(), "monitors")
+
+ assert [r["id"] for r in rows] == list(range(51))
+ assert [r["offset"] for r in requests_made] == [0, 50]
+
+ def test_saves_resume_state_after_yield_only_when_more_pages(self, monkeypatch: Any) -> None:
+ def responder(method: str, data: dict) -> dict:
+ offset = data["offset"]
+ total = {"offset": offset, "limit": 50, "total": 60}
+ rows = [{"id": offset}]
+ return {"stat": "ok", "pagination": total, "monitors": rows}
+
+ _patch_post(monkeypatch, responder)
+ manager = _FakeResumableManager()
+ _collect(manager, "monitors")
+
+ # Saved once (before fetching page 2), never after the final page.
+ assert manager.saved == [UptimeRobotResumeConfig(offset=50)]
+
+ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:
+ def responder(method: str, data: dict) -> dict:
+ return {
+ "stat": "ok",
+ "pagination": {"offset": data["offset"], "limit": 50, "total": 100},
+ "monitors": [{"id": data["offset"]}],
+ }
+
+ requests_made = _patch_post(monkeypatch, responder)
+ _collect(_FakeResumableManager(UptimeRobotResumeConfig(offset=50)), "monitors")
+
+ assert requests_made[0]["offset"] == 50
+
+ def test_alert_contacts_top_level_string_pagination_terminates(self, monkeypatch: Any) -> None:
+ def responder(method: str, data: dict) -> dict:
+ assert method == "getAlertContacts"
+ return {
+ "stat": "ok",
+ "offset": "0",
+ "limit": "50",
+ "total": "2",
+ "alert_contacts": [{"id": "1"}, {"id": "2"}],
+ }
+
+ requests_made = _patch_post(monkeypatch, responder)
+ rows = _collect(_FakeResumableManager(), "alert_contacts")
+
+ assert [r["id"] for r in rows] == ["1", "2"]
+ assert len(requests_made) == 1
+
+ def test_monitor_credentials_are_stripped_from_rows(self, monkeypatch: Any) -> None:
+ # getMonitors echoes back the monitored endpoint's HTTP Basic Auth credentials and custom
+ # request headers; these must never reach the warehouse where any project member with read
+ # access could recover them.
+ def responder(method: str, data: dict) -> dict:
+ return {
+ "stat": "ok",
+ "pagination": {"offset": 0, "limit": 50, "total": 1},
+ "monitors": [
+ {
+ "id": 1,
+ "friendly_name": "prod",
+ "http_username": "svc",
+ "http_password": "hunter2",
+ "custom_http_headers": {"Authorization": "Bearer tok"},
+ }
+ ],
+ }
+
+ _patch_post(monkeypatch, responder)
+ rows = _collect(_FakeResumableManager(), "monitors")
+
+ assert rows == [{"id": 1, "friendly_name": "prod"}]
+
+ def test_alert_contact_webhook_value_is_redacted_end_to_end(self, monkeypatch: Any) -> None:
+ # Wiring guard: the alert_contacts endpoint must apply the credential scrubber, so a webhook
+ # URL embedding a secret token never reaches the warehouse where any project member with read
+ # access could recover and abuse it. The type matrix is covered by TestScrubAlertContact.
+ def responder(method: str, data: dict) -> dict:
+ return {
+ "stat": "ok",
+ "offset": "0",
+ "limit": "50",
+ "total": "1",
+ "alert_contacts": [
+ {"id": 1, "friendly_name": "on-call", "type": 5, "status": 2, "value": "https://h/x?t=s3cret"}
+ ],
+ }
+
+ _patch_post(monkeypatch, responder)
+ rows = _collect(_FakeResumableManager(), "alert_contacts")
+
+ assert rows == [{"id": 1, "friendly_name": "on-call", "type": 5, "status": 2, "value": None}]
+
+ def test_monitors_request_includes_uptime_ratio_params(self, monkeypatch: Any) -> None:
+ def responder(method: str, data: dict) -> dict:
+ return {"stat": "ok", "pagination": {"offset": 0, "limit": 50, "total": 0}, "monitors": []}
+
+ requests_made = _patch_post(monkeypatch, responder)
+ rows = _collect(_FakeResumableManager(), "monitors")
+
+ assert rows == []
+ assert requests_made[0]["custom_uptime_ratios"] == "1-7-30-365"
+ assert requests_made[0]["all_time_uptime_ratio"] == 1
+
+
+class TestMonitorLogRows:
+ def _responder(self, method: str, data: dict) -> dict:
+ return {
+ "stat": "ok",
+ "pagination": {"offset": 0, "limit": 50, "total": 2},
+ "monitors": [
+ {
+ "id": 1,
+ "logs": [
+ {"type": 1, "datetime": 100, "duration": 60},
+ {"type": 2, "datetime": 200, "duration": 0},
+ ],
+ },
+ {"id": 2, "logs": [{"type": 98, "datetime": 300, "duration": 0}]},
+ ],
+ }
+
+ def test_flattens_logs_with_monitor_id(self, monkeypatch: Any) -> None:
+ requests_made = _patch_post(monkeypatch, self._responder)
+ rows = _collect(_FakeResumableManager(), "monitor_logs")
+
+ assert rows == [
+ {"type": 1, "datetime": 100, "duration": 60, "monitor_id": 1},
+ {"type": 2, "datetime": 200, "duration": 0, "monitor_id": 1},
+ {"type": 98, "datetime": 300, "duration": 0, "monitor_id": 2},
+ ]
+ assert requests_made[0]["logs"] == 1
+ # No watermark -> no server-side log window params.
+ assert "logs_start_date" not in requests_made[0]
+
+ def test_incremental_filters_client_side_and_sends_window(self, monkeypatch: Any) -> None:
+ requests_made = _patch_post(monkeypatch, self._responder)
+ rows = _collect(
+ _FakeResumableManager(),
+ "monitor_logs",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=200,
+ )
+
+ # Free plans ignore logs_start_date and return every retained log; rows at or before the
+ # watermark must be dropped client-side.
+ assert rows == [{"type": 98, "datetime": 300, "duration": 0, "monitor_id": 2}]
+ assert requests_made[0]["logs_start_date"] == 200
+ assert "logs_end_date" in requests_made[0]
+
+ def test_monitor_without_logs_key_yields_nothing(self, monkeypatch: Any) -> None:
+ def responder(method: str, data: dict) -> dict:
+ return {
+ "stat": "ok",
+ "pagination": {"offset": 0, "limit": 50, "total": 1},
+ "monitors": [{"id": 1}],
+ }
+
+ _patch_post(monkeypatch, responder)
+ assert _collect(_FakeResumableManager(), "monitor_logs") == []
+
+
+class TestResponseTimeRows:
+ NOW = 1_760_000_000
+
+ def _patch_now(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(uptimerobot.time, "time", lambda: self.NOW)
+
+ def _responder(self, method: str, data: dict) -> dict:
+ start = data["response_times_start_date"]
+ return {
+ "stat": "ok",
+ "pagination": {"offset": 0, "limit": 50, "total": 1},
+ "monitors": [{"id": 7, "response_times": [{"datetime": start + 10, "value": 123}]}],
+ }
+
+ def test_walks_seven_day_windows_from_watermark(self, monkeypatch: Any) -> None:
+ self._patch_now(monkeypatch)
+ watermark = self.NOW - 10 * _DAY
+ requests_made = _patch_post(monkeypatch, self._responder)
+
+ rows = _collect(
+ _FakeResumableManager(),
+ "response_times",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ )
+
+ windows = [(r["response_times_start_date"], r["response_times_end_date"]) for r in requests_made]
+ assert windows == [
+ (watermark, watermark + 7 * _DAY),
+ (watermark + 7 * _DAY, self.NOW),
+ ]
+ assert rows == [
+ {"datetime": watermark + 10, "value": 123, "monitor_id": 7},
+ {"datetime": watermark + 7 * _DAY + 10, "value": 123, "monitor_id": 7},
+ ]
+
+ def test_first_sync_starts_at_initial_lookback(self, monkeypatch: Any) -> None:
+ self._patch_now(monkeypatch)
+ requests_made = _patch_post(monkeypatch, self._responder)
+
+ _collect(_FakeResumableManager(), "response_times")
+
+ expected_start = self.NOW - RESPONSE_TIMES_INITIAL_LOOKBACK_DAYS * _DAY
+ assert requests_made[0]["response_times_start_date"] == expected_start
+ assert requests_made[0]["response_times"] == 1
+
+ def test_saves_window_state_between_windows(self, monkeypatch: Any) -> None:
+ self._patch_now(monkeypatch)
+ watermark = self.NOW - 10 * _DAY
+ _patch_post(monkeypatch, self._responder)
+ manager = _FakeResumableManager()
+
+ _collect(
+ manager,
+ "response_times",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ )
+
+ assert UptimeRobotResumeConfig(offset=0, window_start=watermark + 7 * _DAY) in manager.saved
+
+ def test_resumes_from_saved_window(self, monkeypatch: Any) -> None:
+ self._patch_now(monkeypatch)
+ watermark = self.NOW - 10 * _DAY
+ resume_window = watermark + 7 * _DAY
+ requests_made = _patch_post(monkeypatch, self._responder)
+
+ _collect(
+ _FakeResumableManager(UptimeRobotResumeConfig(offset=0, window_start=resume_window)),
+ "response_times",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ )
+
+ # The completed first window is not re-fetched.
+ assert requests_made[0]["response_times_start_date"] == resume_window
+
+ def test_rows_at_or_before_watermark_are_dropped(self, monkeypatch: Any) -> None:
+ self._patch_now(monkeypatch)
+ watermark = self.NOW - _DAY
+
+ def responder(method: str, data: dict) -> dict:
+ return {
+ "stat": "ok",
+ "pagination": {"offset": 0, "limit": 50, "total": 1},
+ "monitors": [
+ {
+ "id": 7,
+ "response_times": [
+ {"datetime": watermark, "value": 1},
+ {"datetime": watermark + 5, "value": 2},
+ ],
+ }
+ ],
+ }
+
+ _patch_post(monkeypatch, responder)
+ rows = _collect(
+ _FakeResumableManager(),
+ "response_times",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ )
+
+ assert rows == [{"datetime": watermark + 5, "value": 2, "monitor_id": 7}]
+
+
+class TestSourceResponseWiring:
+ @parameterized.expand(
+ [
+ ("monitors", ["id"], "asc"),
+ ("monitor_logs", ["monitor_id", "datetime", "type"], "desc"),
+ ("response_times", ["monitor_id", "datetime"], "desc"),
+ ("alert_contacts", ["id"], "asc"),
+ ("maintenance_windows", ["id"], "asc"),
+ ("status_pages", ["id"], "asc"),
+ ]
+ )
+ def test_primary_keys_and_sort_mode(self, endpoint: str, primary_keys: list[str], sort_mode: str) -> None:
+ response = uptimerobot_source(
+ api_key="key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ # Fan-out endpoints must defer the incremental watermark to job end ("desc"): batches
+ # aggregate across monitor pages and time windows, so per-batch maxima aren't safe.
+ assert response.sort_mode == sort_mode
+
+ def test_every_declared_endpoint_builds_a_response(self) -> None:
+ for endpoint in UPTIMEROBOT_ENDPOINTS:
+ response = uptimerobot_source(
+ api_key="key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ config = UPTIMEROBOT_ENDPOINTS[endpoint]
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uptimerobot/tests/test_uptimerobot_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uptimerobot/tests/test_uptimerobot_source.py
new file mode 100644
index 000000000000..52688f5fabff
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uptimerobot/tests/test_uptimerobot_source.py
@@ -0,0 +1,151 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import UptimerobotSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.uptimerobot.settings import (
+ ENDPOINTS,
+ UPTIMEROBOT_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.uptimerobot.source import UptimerobotSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.uptimerobot.uptimerobot import (
+ UptimeRobotResumeConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_INCREMENTAL_ENDPOINTS = {"monitor_logs", "response_times"}
+_FULL_REFRESH_ENDPOINTS = {"monitors", "alert_contacts", "maintenance_windows", "status_pages"}
+
+
+class TestUptimerobotSource:
+ def setup_method(self):
+ self.source = UptimerobotSource()
+ self.team_id = 123
+ self.config = UptimerobotSourceConfig(api_key="ur123-key")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.UPTIMEROBOT
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Uptimerobot"
+ assert config.label == "UptimeRobot"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/uptimerobot.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/uptimerobot"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_api_key_field_is_secret_password(self):
+ config = self.source.get_source_config
+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.secret is True
+ assert api_key_field.required is True
+
+ def test_non_retryable_errors_match_transport_auth_failure(self):
+ # UptimeRobot signals a bad key in-body over HTTP 200; the transport raises with this message.
+ observed_error = "UptimeRobot API key was rejected: api_key is invalid."
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "UptimeRobot API error (retryable): status=429, method=getMonitors",
+ "UptimeRobot API error (invalid_parameter): offset is invalid.",
+ "HTTPSConnectionPool(host='api.uptimerobot.com', port=443): Read timed out.",
+ ],
+ )
+ def test_non_retryable_errors_do_not_match_transient(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas_match_endpoints_with_correct_sync_modes(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert set(schemas) == set(ENDPOINTS)
+ for name in _INCREMENTAL_ENDPOINTS:
+ assert schemas[name].supports_incremental is True
+ assert schemas[name].supports_append is True
+ assert [f["field"] for f in schemas[name].incremental_fields] == ["datetime"]
+ for name in _FULL_REFRESH_ENDPOINTS:
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].supports_append is False
+ assert schemas[name].incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["monitors"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "monitors"
+
+ def test_lists_tables_without_credentials_publishes_catalog(self):
+ # Static endpoint catalog (no I/O) — the public docs table list should render.
+ assert self.source.lists_tables_without_credentials is True
+ documented = self.source.get_documented_tables()
+ assert {table["name"] for table in documented} == set(ENDPOINTS)
+
+ def test_canonical_descriptions_cover_every_endpoint(self):
+ canonical = self.source.get_canonical_descriptions()
+ assert set(canonical) == set(UPTIMEROBOT_ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ ((True, None), True, None),
+ ((False, "Invalid UptimeRobot API key"), False, "Invalid UptimeRobot API key"),
+ ((False, "Could not connect to UptimeRobot"), False, "Could not connect to UptimeRobot"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.uptimerobot.source.validate_uptimerobot_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with("ur123-key")
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert manager._data_class is UptimeRobotResumeConfig
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.uptimerobot.source.uptimerobot_source"
+ )
+ def test_source_for_pipeline_plumbs_arguments(self, mock_uptimerobot_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "monitor_logs"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1750000000
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_uptimerobot_source.assert_called_once()
+ kwargs = mock_uptimerobot_source.call_args.kwargs
+ assert kwargs["api_key"] == "ur123-key"
+ assert kwargs["endpoint"] == "monitor_logs"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["db_incremental_field_last_value"] == 1750000000
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.uptimerobot.source.uptimerobot_source"
+ )
+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_uptimerobot_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "monitors"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = 1750000000
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_uptimerobot_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uptimerobot/uptimerobot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uptimerobot/uptimerobot.py
new file mode 100644
index 000000000000..99a2c156a88d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uptimerobot/uptimerobot.py
@@ -0,0 +1,400 @@
+import time
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+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.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.uptimerobot.settings import (
+ PAGE_LIMIT,
+ RESPONSE_TIMES_INITIAL_LOOKBACK_DAYS,
+ RESPONSE_TIMES_WINDOW_DAYS,
+ UPTIMEROBOT_ENDPOINTS,
+ UptimeRobotEndpointConfig,
+)
+
+UPTIMEROBOT_BASE_URL = "https://api.uptimerobot.com/v2"
+
+# Stable prefix for credential failures — matched by `get_non_retryable_errors` on the source class.
+AUTH_ERROR_PREFIX = "UptimeRobot API key was rejected"
+
+# getMonitors echoes back the monitor's configuration, including the HTTP Basic Auth credentials
+# used to reach the monitored endpoint (`http_username`/`http_password`) and any custom request
+# headers, which routinely carry bearer tokens or API keys. None of these have analytical value and
+# all would let a project member with warehouse read access recover live credentials, so they're
+# stripped from every row defensively regardless of endpoint.
+_SENSITIVE_FIELDS: frozenset[str] = frozenset({"http_username", "http_password", "custom_http_headers"})
+
+# Alert-contact channel types whose `value` is a plain destination (phone number, email address, or
+# handle) rather than a secret. Every other type — webhook (5), Slack (11), Zapier (7), Pushover
+# (9), and the growing list of integration channels — puts a URL or token in `value` that a project
+# member with warehouse read access could use to forge notifications, so we redact it. Keyed on the
+# numeric `type`; unknown or missing types fail closed (redacted).
+_ALERT_CONTACT_PLAINTEXT_VALUE_TYPES: frozenset[int] = frozenset({1, 2, 3})
+
+
+def _scrub_sensitive(row: dict[str, Any]) -> dict[str, Any]:
+ if _SENSITIVE_FIELDS.isdisjoint(row):
+ return row
+ return {key: value for key, value in row.items() if key not in _SENSITIVE_FIELDS}
+
+
+def _scrub_alert_contact(row: dict[str, Any]) -> dict[str, Any]:
+ """Redact the `value` of credential-bearing alert contacts (webhook/integration channels)."""
+ if "value" not in row:
+ return row
+ try:
+ contact_type = int(row["type"])
+ except (KeyError, TypeError, ValueError):
+ contact_type = -1
+ if contact_type in _ALERT_CONTACT_PLAINTEXT_VALUE_TYPES:
+ return row
+ return {**row, "value": None}
+
+
+class UptimeRobotRetryableError(Exception):
+ pass
+
+
+class UptimeRobotAuthError(Exception):
+ pass
+
+
+class UptimeRobotAPIError(Exception):
+ pass
+
+
+class UptimeRobotResumeConfig:
+ # Next 0-indexed row offset to fetch within the current listing.
+ offset: int = 0
+ # response_times only: Unix start of the 7-day window being fetched. None for other endpoints.
+ window_start: int | None = None
+
+
+def _to_unix_timestamp(value: Any) -> int | None:
+ """Coerce an incremental cursor (int epoch, datetime, date, or numeric string) to Unix seconds."""
+ if value is None:
+ return None
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, int):
+ return value
+ if isinstance(value, float):
+ return int(value)
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return int(aware.timestamp())
+ if isinstance(value, date):
+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())
+ if isinstance(value, str):
+ stripped = value.strip()
+ if not stripped:
+ return None
+ try:
+ return int(float(stripped))
+ except ValueError:
+ try:
+ return int(datetime.fromisoformat(stripped.replace("Z", "+00:00")).timestamp())
+ except ValueError:
+ return None
+ return None
+
+
+@retry(
+ retry=retry_if_exception_type((UptimeRobotRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _post(session: requests.Session, method: str, data: dict[str, Any], logger: FilteringBoundLogger) -> dict[str, Any]:
+ """Call a v2 API method. Every v2 endpoint is a form-encoded POST with the api_key in the body.
+
+ UptimeRobot returns HTTP 200 even for failures and signals errors in-body via
+ ``{"stat": "fail", "error": {...}}``, so both layers are checked here.
+ """
+ url = f"{UPTIMEROBOT_BASE_URL}/{method}"
+ response = session.post(url, data=data, timeout=60)
+
+ # Rate limits are plan-based (free: 10 req/min); 429 carries a Retry-After header. Back off and
+ # retry rather than failing the sync. Transient 5xx are retryable too.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise UptimeRobotRetryableError(
+ f"UptimeRobot API error (retryable): status={response.status_code}, method={method}"
+ )
+
+ if not response.ok:
+ logger.error(f"UptimeRobot API error: status={response.status_code}, body={response.text}, method={method}")
+ response.raise_for_status()
+
+ payload = response.json()
+ if payload.get("stat") != "ok":
+ error = payload.get("error") or {}
+ message = error.get("message") or str(error)
+ # Invalid/missing keys surface as {"type": "invalid_parameter", "parameter_name": "api_key"}
+ # (verified against the live API); monitor-scoped keys hitting non-monitor endpoints report
+ # api_key errors too.
+ if "api_key" in str(error.get("parameter_name") or "") or "api_key" in str(message):
+ raise UptimeRobotAuthError(f"{AUTH_ERROR_PREFIX}: {message}")
+ raise UptimeRobotAPIError(f"UptimeRobot API error ({error.get('type')}): {message}")
+
+ return payload
+
+
+def _form_data(api_key: str, config: UptimeRobotEndpointConfig, offset: int) -> dict[str, Any]:
+ return {
+ "api_key": api_key,
+ "format": "json",
+ "offset": offset,
+ "limit": PAGE_LIMIT,
+ **config.extra_params,
+ }
+
+
+def _next_offset(payload: dict[str, Any], requested_offset: int, page_len: int) -> int | None:
+ """Compute the next page offset, or None when the listing is exhausted.
+
+ Most endpoints nest {offset, limit, total} under "pagination"; getAlertContacts returns them at
+ the top level, and the docs show them as strings there — coerce defensively.
+ """
+ pagination = payload.get("pagination")
+ if not isinstance(pagination, dict):
+ pagination = payload
+ try:
+ offset = int(pagination.get("offset", requested_offset))
+ limit = int(pagination.get("limit", PAGE_LIMIT))
+ total = int(pagination["total"])
+ except (KeyError, TypeError, ValueError):
+ # No usable pagination metadata — assume more pages only if this one came back full.
+ return requested_offset + page_len if page_len >= PAGE_LIMIT else None
+
+ next_offset = offset + limit
+ return next_offset if next_offset < total else None
+
+
+def _get_top_level_rows(
+ session: requests.Session,
+ api_key: str,
+ config: UptimeRobotEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[UptimeRobotResumeConfig],
+ resume: UptimeRobotResumeConfig | None,
+) -> Iterator[list[dict[str, Any]]]:
+ offset = resume.offset if resume is not None else 0
+ if offset:
+ logger.debug(f"UptimeRobot: resuming {config.name} from offset {offset}")
+
+ while True:
+ payload = _post(session, config.method, _form_data(api_key, config, offset), logger)
+ raw_rows = payload.get(config.response_key) or []
+ next_offset = _next_offset(payload, offset, len(raw_rows))
+
+ rows = [_scrub_sensitive(row) for row in raw_rows]
+ if config.redact_alert_contact_values:
+ rows = [_scrub_alert_contact(row) for row in rows]
+ if rows:
+ yield rows
+ if next_offset is None:
+ break
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it — merge
+ # dedupes on the primary key.
+ resumable_source_manager.save_state(UptimeRobotResumeConfig(offset=next_offset))
+ offset = next_offset
+
+
+def _flatten_monitor_rows(
+ monitors: list[dict[str, Any]], list_key: str, min_exclusive_ts: int | None
+) -> list[dict[str, Any]]:
+ """Flatten each monitor's nested list ("logs" / "response_times") into rows keyed by monitor_id."""
+ rows: list[dict[str, Any]] = []
+ for monitor in monitors:
+ for entry in monitor.get(list_key) or []:
+ if min_exclusive_ts is not None:
+ entry_ts = _to_unix_timestamp(entry.get("datetime"))
+ if entry_ts is not None and entry_ts <= min_exclusive_ts:
+ continue
+ rows.append(_scrub_sensitive({**entry, "monitor_id": monitor.get("id")}))
+ return rows
+
+
+def _get_monitor_log_rows(
+ session: requests.Session,
+ api_key: str,
+ config: UptimeRobotEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[UptimeRobotResumeConfig],
+ resume: UptimeRobotResumeConfig | None,
+ last_value_ts: int | None,
+) -> Iterator[list[dict[str, Any]]]:
+ offset = resume.offset if resume is not None else 0
+ if offset:
+ logger.debug(f"UptimeRobot: resuming {config.name} from offset {offset}")
+
+ extra: dict[str, Any] = {}
+ if last_value_ts is not None:
+ # logs_start_date/logs_end_date are documented as paid-plan-only; free plans return every
+ # retained log regardless, so the client-side filter in _flatten_monitor_rows keeps those
+ # syncs correct. Retention is bounded (~2 months on free), so the fallback stays cheap.
+ extra["logs_start_date"] = last_value_ts
+ extra["logs_end_date"] = int(time.time())
+
+ while True:
+ payload = _post(session, config.method, {**_form_data(api_key, config, offset), **extra}, logger)
+ monitors = payload.get(config.response_key) or []
+ next_offset = _next_offset(payload, offset, len(monitors))
+
+ rows = _flatten_monitor_rows(monitors, "logs", last_value_ts)
+ if rows:
+ yield rows
+ if next_offset is None:
+ break
+ resumable_source_manager.save_state(UptimeRobotResumeConfig(offset=next_offset))
+ offset = next_offset
+
+
+def _get_response_time_rows(
+ session: requests.Session,
+ api_key: str,
+ config: UptimeRobotEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[UptimeRobotResumeConfig],
+ resume: UptimeRobotResumeConfig | None,
+ last_value_ts: int | None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk response-time history in 7-day windows (the API's max range per request), paginating
+ monitors within each window. Window boundaries overlap by one second's worth of samples at most;
+ merge dedupes on [monitor_id, datetime]."""
+ now_ts = int(time.time())
+ window_seconds = RESPONSE_TIMES_WINDOW_DAYS * 86400
+
+ start_ts = last_value_ts if last_value_ts is not None else now_ts - RESPONSE_TIMES_INITIAL_LOOKBACK_DAYS * 86400
+
+ window_start = start_ts
+ offset = 0
+ if resume is not None and resume.window_start is not None:
+ window_start = resume.window_start
+ offset = resume.offset
+ logger.debug(f"UptimeRobot: resuming {config.name} from window_start={window_start}, offset={offset}")
+
+ while window_start < now_ts:
+ window_end = min(window_start + window_seconds, now_ts)
+ extra = {"response_times_start_date": window_start, "response_times_end_date": window_end}
+
+ while True:
+ payload = _post(session, config.method, {**_form_data(api_key, config, offset), **extra}, logger)
+ monitors = payload.get(config.response_key) or []
+ next_offset = _next_offset(payload, offset, len(monitors))
+
+ rows = _flatten_monitor_rows(monitors, "response_times", last_value_ts)
+ if rows:
+ yield rows
+ if next_offset is None:
+ break
+ resumable_source_manager.save_state(UptimeRobotResumeConfig(offset=next_offset, window_start=window_start))
+ offset = next_offset
+
+ window_start = window_end
+ offset = 0
+ if window_start < now_ts:
+ resumable_source_manager.save_state(UptimeRobotResumeConfig(offset=0, window_start=window_start))
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[UptimeRobotResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = UPTIMEROBOT_ENDPOINTS[endpoint]
+ session = make_tracked_session()
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ last_value_ts = (
+ _to_unix_timestamp(db_incremental_field_last_value)
+ if should_use_incremental_field and config.supports_incremental
+ else None
+ )
+
+ if config.monitor_list_key == "response_times":
+ yield from _get_response_time_rows(
+ session, api_key, config, logger, resumable_source_manager, resume, last_value_ts
+ )
+ elif config.monitor_list_key == "logs":
+ yield from _get_monitor_log_rows(
+ session, api_key, config, logger, resumable_source_manager, resume, last_value_ts
+ )
+ else:
+ yield from _get_top_level_rows(session, api_key, config, logger, resumable_source_manager, resume)
+
+
+def uptimerobot_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[UptimeRobotResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = UPTIMEROBOT_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ 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,
+ # Fan-out endpoints aggregate rows across monitor pages (and, for response_times, time
+ # windows), so batch order isn't globally ascending. "desc" defers the incremental
+ # watermark to successful job end, where the max over the whole run is safe.
+ sort_mode="desc" if config.monitor_list_key else "asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format=config.partition_format if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ """Probe getMonitors with limit=1 to confirm the key is genuine.
+
+ getMonitors is the one endpoint every key type (main, read-only, monitor-specific) can call, so
+ a passing probe never blocks a legitimately scoped key. Returns ``(ok, error_message)``.
+ """
+ try:
+ response = make_tracked_session().post(
+ f"{UPTIMEROBOT_BASE_URL}/getMonitors",
+ data={"api_key": api_key, "format": "json", "limit": 1},
+ timeout=10,
+ )
+ except Exception:
+ return False, "Could not connect to UptimeRobot"
+
+ if response.status_code != 200:
+ return False, f"UptimeRobot returned an unexpected status code ({response.status_code})"
+
+ try:
+ payload = response.json()
+ except ValueError:
+ return False, "UptimeRobot returned an unexpected response"
+
+ if payload.get("stat") == "ok":
+ return True, None
+
+ error = payload.get("error") or {}
+ if "api_key" in str(error.get("parameter_name") or "") or "api_key" in str(error.get("message") or ""):
+ return False, "Invalid UptimeRobot API key"
+ return False, error.get("message") or "Could not validate UptimeRobot credentials"