: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement cronitor import source (#71208)
Tom Owers72727ea4a1a7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 4f31ab92ece4..9ed851bdb0e4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -145,6 +145,7 @@ the row lists both.| coupa | HTTP | requests | ✅ || coveralls | HTTP | requests | ✅ || crates_io | HTTP | requests | ✅ |+| cronitor | HTTP | requests | ✅ || crunchbase | HTTP | requests | ✅ || culture_amp | HTTP | requests | ✅ || cursor | HTTP | requests | ✅ |@@ -622,7 +623,6 @@ doesn't conflict with concurrent PRs.- cosmosdb- couchbase- criteo-- cronitor- curve- dagster_cloud- databricksdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/canonical_descriptions.pynew file mode 100644index 000000000000..6916f0e43ad7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/canonical_descriptions.py@@ -0,0 +1,53 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "monitors": {+ "description": "A Cronitor monitor: a cron job, heartbeat, or uptime check, with its configuration and current read-only state.",+ "docs_url": "https://cronitor.io/docs/monitor-api",+ "columns": {+ "key": "Unique identifier of the monitor, used in API URLs.",+ "name": "Display name of the monitor. Defaults to the key.",+ "type": "Monitor type, e.g. job, check, or heartbeat.",+ "schedule": "The schedule the monitor is expected to run on (e.g. a cron expression).",+ "created": "ISO 8601 timestamp of when the monitor was created.",+ "passing": "Whether the monitor is currently passing its assertions.",+ "running": "Whether the job is currently running (job monitors only).",+ "paused": "Whether alerting for the monitor is paused.",+ "disabled": "Whether the monitor is disabled.",+ "initialized": "Whether the monitor has received telemetry at least once.",+ "group": "Key of the group the monitor belongs to.",+ "next_expected_at": "Timestamp of when the next telemetry event is expected per the schedule.",+ "latest_event": "The most recent telemetry event, with stamp, state, message, and duration.",+ "latest_issue": "The most recent issue (alert) raised for the monitor, if any.",+ "assertions": "The assertions evaluated against the monitor's telemetry.",+ "notify": "Alert notification configuration for the monitor.",+ "tags": "Tags attached to the monitor.",+ },+ },+ "invocations": {+ "description": "Recent invocations (runs) of each job monitor, from the monitor detail's latest_invocations. A snapshot of recent history, refreshed each sync.",+ "docs_url": "https://cronitor.io/docs/monitor-api",+ "columns": {+ "monitor_key": "Key of the monitor this invocation belongs to.",+ "series": "Series identifier linking the run and complete telemetry events of one invocation.",+ "started_at": "When the job run started.",+ "ended_at": "When the job run completed, if it has.",+ "duration": "Total duration of the run in milliseconds.",+ },+ },+ "metrics": {+ "description": "Time-series reliability metrics per monitor, from the Metrics API. One row per monitor, dimension, and timestamp.",+ "docs_url": "https://cronitor.io/docs/metrics-api",+ "columns": {+ "monitor_key": "Key of the monitor the data point belongs to.",+ "dimension": "Dimension the data point is grouped by, e.g. env:production.",+ "stamp": "Unix timestamp of the data point.",+ "duration_p50": "Median run duration in the interval, in milliseconds.",+ "duration_p90": "90th-percentile run duration in the interval, in milliseconds.",+ "success_rate": "Share of runs in the interval that completed successfully.",+ "run_count": "Number of runs recorded in the interval.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/cronitor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/cronitor.pynew file mode 100644index 000000000000..71bd068454f4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/cronitor.py@@ -0,0 +1,397 @@+import time+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import quote, urlencode, urlsplit, urlunsplit++import requests+from dateutil import parser+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.cronitor.settings import (+ BASE_URL,+ CRONITOR_ENDPOINTS,+ METRICS_FIELDS,+ METRICS_MAX_LOOKBACK_SECONDS,+ METRICS_MAX_MONITORS_PER_REQUEST,+ METRICS_MIN_WINDOW_SECONDS,+ METRICS_WINDOW_SECONDS,+ PAGE_SIZE,+)+++class CronitorRetryableError(Exception):+ pass+++class CronitorResumeConfig:+ # monitors: next 1-indexed page to fetch.+ page: int | None = None+ # invocations: stable key bookmark of the next monitor to fan out into (not a positional+ # index, so monitors added/removed between a crash and the retry can't shift the resume point).+ monitor_key: str | None = None+ # metrics: Unix start of the next time window to fetch.+ window_start: int | None = None+++def _build_url(path: str, params: list[tuple[str, Any]] | dict[str, Any]) -> str:+ if not params:+ return f"{BASE_URL}{path}"+ return f"{BASE_URL}{path}?{urlencode(params)}"+++def _coerce_epoch(value: Any) -> int | None:+ """Normalize a cursor value (epoch number, datetime, date, or string) to a Unix int."""+ if value is None or isinstance(value, bool):+ return None+ if isinstance(value, int | 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):+ try:+ return int(float(value))+ except ValueError:+ pass+ try:+ parsed = parser.parse(value)+ except (ValueError, OverflowError):+ return None+ aware = parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)+ return int(aware.timestamp())+ return None+++@retry(+ retry=retry_if_exception_type((CronitorRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch(session: requests.Session, url: str, api_key: str, logger: FilteringBoundLogger) -> Any:+ # HTTP Basic auth: API key as the username, empty password.+ response = session.get(url, auth=(api_key, ""), headers={"Accept": "application/json"}, timeout=60)++ # Cronitor rate limits with 429 (exact limits undocumented); transient 5xx are retryable too.+ if response.status_code == 429 or response.status_code >= 500:+ raise CronitorRetryableError(f"Cronitor API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # 404s are expected in places (deleted monitor mid-fan-out, empty metrics window) and+ # handled by the caller; anything else is a real failure.+ log = logger.warning if response.status_code == 404 else logger.error+ log(f"Cronitor API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++# HTTP-check monitors carry the outbound request config Cronitor uses to probe an endpoint, and+# that config can embed credentials (bearer tokens, API keys, session cookies, secrets in the+# POST body). Drop those wholesale before a row is persisted so they never land in the queryable+# warehouse table where any project member could read them back.+_SENSITIVE_REQUEST_FIELDS = ("headers", "cookies", "body")+++def _sanitize_url(url: str) -> str:+ """Reduce a check URL to just scheme + host/port so no embedded credential can survive.++ Userinfo (``user:pass@``), the query string, and the fragment obviously carry tokens, but the+ path does too — Slack incoming webhooks and other tokenized callback endpoints put the secret+ in a path segment. There's no way to tell a credential-bearing path apart from a benign one, so+ drop the path entirely and keep only scheme and host/port: enough to say *which* endpoint is+ monitored without persisting anything secret.+ """+ try:+ parts = urlsplit(url)+ except ValueError:+ return ""+ if not parts.hostname:+ # No scheme/host to anchor on (relative or malformed) — nothing safe to keep.+ return ""+ netloc = parts.hostname if parts.port is None else f"{parts.hostname}:{parts.port}"+ return urlunsplit((parts.scheme, netloc, "", "", ""))+++def _redact_monitor(monitor: dict[str, Any]) -> dict[str, Any]:+ request = monitor.get("request")+ if not isinstance(request, dict):+ return monitor+ redacted_request = {key: value for key, value in request.items() if key not in _SENSITIVE_REQUEST_FIELDS}+ url = redacted_request.get("url")+ if isinstance(url, str):+ redacted_request["url"] = _sanitize_url(url)+ if redacted_request == request:+ return monitor+ return {**monitor, "request": redacted_request}+++def _fetch_monitors_page(+ session: requests.Session, api_key: str, logger: FilteringBoundLogger, page: int+) -> tuple[list[dict[str, Any]], bool]:+ """Fetch one page of the monitors list, returning (rows, has_more).++ Sort by creation time so the page walk stays stable if monitors are added mid-sync. The list+ envelope documents no total count, so a short page signals the end.+ """+ url = _build_url("/monitors", {"page": page, "pageSize": PAGE_SIZE, "sort": "created"})+ data = _fetch(session, url, api_key, logger)+ monitors = data.get("monitors") if isinstance(data, dict) else data+ if not isinstance(monitors, list):+ return [], False+ rows = [_redact_monitor(monitor) for monitor in monitors if isinstance(monitor, dict)]+ return rows, len(rows) >= PAGE_SIZE+++def _get_monitor_rows(+ session: requests.Session,+ api_key: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CronitorResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.page if resume is not None and resume.page else 1+ if page > 1:+ logger.debug(f"Cronitor: resuming monitors from page {page}")++ while True:+ rows, has_more = _fetch_monitors_page(session, api_key, logger, page)+ if not rows:+ break+ yield rows+ if not has_more:+ break+ page += 1+ # 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(CronitorResumeConfig(page=page))+++def _list_monitor_keys(session: requests.Session, api_key: str, logger: FilteringBoundLogger) -> list[str]:+ keys: list[str] = []+ page = 1+ while True:+ rows, has_more = _fetch_monitors_page(session, api_key, logger, page)+ keys.extend(str(monitor["key"]) for monitor in rows if monitor.get("key"))+ if not has_more:+ return keys+ page += 1+++def _get_invocation_rows(+ session: requests.Session,+ api_key: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CronitorResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Fan out over every monitor, materializing its recent invocations as rows.++ The API exposes no paginated invocation history — only the `latest_invocations` returned by the+ monitor detail with `?withInvocations=true` — so this is a full-refresh snapshot of each+ monitor's recent runs. Long-term trends come from the metrics endpoint instead.+ """+ monitor_keys = _list_monitor_keys(session, api_key, logger)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = monitor_keys+ if resume is not None and resume.monitor_key is not None and resume.monitor_key in monitor_keys:+ remaining = monitor_keys[monitor_keys.index(resume.monitor_key) :]+ logger.debug(f"Cronitor: resuming invocations from monitor {resume.monitor_key}")++ for index, monitor_key in enumerate(remaining):+ url = _build_url(f"/monitors/{quote(monitor_key, safe='')}", {"withInvocations": "true"})+ try:+ data = _fetch(session, url, api_key, logger)+ except requests.HTTPError as exc:+ # A monitor deleted between enumeration and this fetch 404s. Skip it rather than+ # failing the whole sync; any other HTTP error is re-raised.+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"Cronitor: monitor {monitor_key} not found while fetching invocations, skipping")+ data = None+ else:+ raise++ if isinstance(data, dict):+ rows: list[dict[str, Any]] = []+ for invocation in data.get("latest_invocations") or []:+ if not isinstance(invocation, dict):+ continue+ row = {**invocation, "monitor_key": monitor_key}+ # `series` is part of the primary key; coalesce so the merge key is never null.+ row["series"] = row.get("series") or ""+ rows.append(row)+ if rows:+ yield rows++ # Advance the bookmark AFTER this monitor's rows are yielded so a crash re-yields them —+ # merge dedupes on the primary key.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(CronitorResumeConfig(monitor_key=remaining[index + 1]))+++def _flatten_metrics_response(data: Any) -> list[dict[str, Any]]:+ """Flatten the nested metrics response (monitor key -> dimension -> data points) into rows."""+ monitors = data.get("monitors") if isinstance(data, dict) else None+ if not isinstance(monitors, dict):+ return []+ rows: list[dict[str, Any]] = []+ for monitor_key, dimensions in monitors.items():+ if not isinstance(dimensions, dict):+ continue+ for dimension, points in dimensions.items():+ if not isinstance(points, list):+ continue+ for point in points:+ if not isinstance(point, dict):+ continue+ # Coerce the stamp to a Unix int so the integer cursor and datetime partitioning+ # both work regardless of whether the API returns it as int or float.+ stamp = _coerce_epoch(point.get("stamp"))+ if stamp is None:+ continue+ rows.append({**point, "monitor_key": monitor_key, "dimension": dimension, "stamp": stamp})+ return rows+++def _get_metric_rows(+ session: requests.Session,+ api_key: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CronitorResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ """Walk time windows over the metrics API, batching monitors up to the per-request cap."""+ monitor_keys = _list_monitor_keys(session, api_key, logger)+ if not monitor_keys:+ return++ now = int(time.time())+ floor = now - METRICS_MAX_LOOKBACK_SECONDS++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.window_start is not None:+ start = resume.window_start+ logger.debug(f"Cronitor: resuming metrics from window start {start}")+ else:+ last_value = _coerce_epoch(db_incremental_field_last_value) if should_use_incremental_field else None+ start = last_value if last_value is not None else floor+ # A single request's span is capped at one year, and older data points aren't retrievable+ # through a window that old anyway — clamp the walk to the max lookback.+ start = max(start, floor)++ while start < now:+ end = min(start + METRICS_WINDOW_SECONDS, now)+ # The API rejects windows narrower than an hour; widen backwards and let merge dedupe+ # the re-pulled points.+ window_start = min(start, end - METRICS_MIN_WINDOW_SECONDS)++ for batch_index in range(0, len(monitor_keys), METRICS_MAX_MONITORS_PER_REQUEST):+ batch = monitor_keys[batch_index : batch_index + METRICS_MAX_MONITORS_PER_REQUEST]+ params: list[tuple[str, Any]] = [("monitor", key) for key in batch]+ params.extend(("field", metric_field) for metric_field in METRICS_FIELDS)+ params.extend([("start", window_start), ("end", end)])+ try:+ data = _fetch(session, _build_url("/metrics", params), api_key, logger)+ except requests.HTTPError as exc:+ # The metrics API 404s when no monitor in the batch has data for the window.+ if exc.response is not None and exc.response.status_code == 404:+ continue+ raise+ rows = _flatten_metrics_response(data)+ if rows:+ yield rows++ if end >= now:+ break+ start = end+ # Save AFTER the window's batches are yielded so a crash re-fetches the whole window+ # rather than skipping part of it — merge dedupes on the primary key.+ resumable_source_manager.save_state(CronitorResumeConfig(window_start=start))+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CronitorResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ # One session reused across every request so urllib3 keeps the connection alive.+ # capture=False: raw monitor responses embed request cookies, bodies, and credential-bearing+ # URLs that only `_redact_monitor` strips (after sampling would have run), so keep them out of+ # HTTP sample capture entirely.+ session = make_tracked_session(capture=False)++ if endpoint == "monitors":+ yield from _get_monitor_rows(session, api_key, logger, resumable_source_manager)+ elif endpoint == "invocations":+ yield from _get_invocation_rows(session, api_key, logger, resumable_source_manager)+ elif endpoint == "metrics":+ yield from _get_metric_rows(+ session,+ api_key,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ else:+ raise ValueError(f"Unknown Cronitor endpoint: {endpoint}")+++def cronitor_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CronitorResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = CRONITOR_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,+ sort_mode=config.sort_mode,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" 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, int | None]:+ """Probe the monitors list to confirm the key is genuine.++ Returns ``(ok, status_code)``; ``status_code`` is ``None`` on a transport error.+ """+ url = _build_url("/monitors", {"page": 1, "pageSize": 1})+ try:+ # capture=False for the same reason as the sync session: the probe returns a monitor whose+ # request config can carry credentials the generic sampler would not redact.+ response = make_tracked_session(capture=False).get(+ url, auth=(api_key, ""), headers={"Accept": "application/json"}, timeout=10+ )+ except Exception:+ return False, None+ return response.status_code == 200, response.status_codediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/settings.pynew file mode 100644index 000000000000..f813e90c3d6a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/settings.py@@ -0,0 +1,70 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++BASE_URL = "https://cronitor.io/api"++# The monitors list paginates with `page`/`pageSize`; the docs publish no maximum, so stay on a+# conservative size and stop on the first short page.+PAGE_SIZE = 50++# Metrics API constraints from the public docs: at most 50 monitor keys per request, and the+# start/end span must be between one hour and one year.+METRICS_MAX_MONITORS_PER_REQUEST = 50+METRICS_MIN_WINDOW_SECONDS = 3600+METRICS_MAX_LOOKBACK_SECONDS = 365 * 24 * 3600+# Chunk backfills into 30-day windows so a crash mid-backfill only re-fetches one window.+METRICS_WINDOW_SECONDS = 30 * 24 * 3600++# Metric fields verified against the public Metrics API docs. The API documents more (fail_count,+# complete_count, duration_p99, ...) but some may be plan-gated, so start with the core set.+METRICS_FIELDS = ("duration_p50", "duration_p90", "success_rate", "run_count")+++@dataclass+class CronitorEndpointConfig:+ name: str+ primary_keys: list[str]+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable field to partition by. None when the endpoint has no reliably parseable timestamp.+ partition_key: Optional[str] = None+ sort_mode: Literal["asc", "desc"] = "asc"+++CRONITOR_ENDPOINTS: dict[str, CronitorEndpointConfig] = {+ "monitors": CronitorEndpointConfig(+ name="monitors",+ primary_keys=["key"],+ # The list has no updated-since/created-since filter, so it's full refresh only.+ partition_key="created",+ ),+ "invocations": CronitorEndpointConfig(+ name="invocations",+ # `series` links a run/complete telemetry pair, but the docs don't state its uniqueness+ # scope, so include the monitor key and start time to keep the key unique table-wide.+ primary_keys=["monitor_key", "series", "started_at"],+ ),+ "metrics": CronitorEndpointConfig(+ name="metrics",+ primary_keys=["monitor_key", "dimension", "stamp"],+ incremental_fields=[+ {+ "label": "stamp",+ "type": IncrementalFieldType.DateTime,+ "field": "stamp",+ "field_type": IncrementalFieldType.Integer,+ },+ ],+ partition_key="stamp",+ # Rows are yielded per monitor batch per window, so stamps are not globally ascending;+ # desc persists the incremental watermark only once the job completes.+ sort_mode="desc",+ ),+}++ENDPOINTS = tuple(CRONITOR_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CRONITOR_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/source.pyindex 04b350102b44..7f96f756accc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/source.py@@ -1,19 +1,43 @@-from typing import cast+from typing import Optional, castfrom 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.cronitor.cronitor import (+ CronitorResumeConfig,+ cronitor_source,+ validate_credentials as validate_cronitor_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cronitor.settings import (+ CRONITOR_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CronitorSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CronitorSource(SimpleSource[CronitorSourceConfig]):+class CronitorSource(ResumableSource[CronitorSourceConfig, CronitorResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CRONITOR@@ -24,7 +48,92 @@ class CronitorSource(SimpleSource[CronitorSourceConfig]):name=SchemaExternalDataSourceType.CRONITOR,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Cronitor",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Import your Cronitor monitors, their recent job invocations, and time-series reliability metrics into the PostHog Data warehouse.++Create an API key with the `monitor:read` scope under **Settings → API keys** in your Cronitor account, and enter it here.""",iconPath="/static/services/cronitor.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/cronitor",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.cronitor.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # 401/403 surface as a requests HTTPError when `_fetch` calls `raise_for_status()`.+ # Retrying can never fix a credential/scope problem, so fail the sync. Match the stable+ # status text, not the per-request path.+ "401 Client Error: Unauthorized": "Your Cronitor API key is invalid or has been revoked. Create a new key in your Cronitor account's API settings, then reconnect.",+ "403 Client Error: Forbidden": "Your Cronitor API key is missing the monitor:read scope needed to sync this data. Update the key's scopes, then reconnect.",+ }++ def get_schemas(+ self,+ config: CronitorSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ supports_incremental = len(CRONITOR_ENDPOINTS[endpoint].incremental_fields) > 0+ return SourceSchema(+ name=endpoint,+ supports_incremental=supports_incremental,+ supports_append=supports_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(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: CronitorSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ ok, status_code = validate_cronitor_credentials(config.api_key)+ if ok:+ return True, None+ if status_code in (401, 403):+ return False, "Invalid Cronitor API key. Make sure the key has the monitor:read scope."+ return False, "Could not connect to Cronitor with the provided API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CronitorResumeConfig]:+ return ResumableSourceManager[CronitorResumeConfig](inputs, CronitorResumeConfig)++ def source_for_pipeline(+ self,+ config: CronitorSourceConfig,+ resumable_source_manager: ResumableSourceManager[CronitorResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return cronitor_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/cronitor/tests/test_cronitor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/tests/test_cronitor.pynew file mode 100644index 000000000000..77c71b0ec2cd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/tests/test_cronitor.py@@ -0,0 +1,404 @@+from datetime import UTC, date, datetime+from types import SimpleNamespace+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.cronitor import cronitor+from products.warehouse_sources.backend.temporal.data_imports.sources.cronitor.cronitor import (+ CronitorResumeConfig,+ _coerce_epoch,+ _flatten_metrics_response,+ cronitor_source,+ get_rows,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cronitor.settings import (+ METRICS_MIN_WINDOW_SECONDS,+ PAGE_SIZE,+)++NOW = 1_750_000_000+++class _FakeResumableManager:+ def __init__(self, state: CronitorResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[CronitorResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> CronitorResumeConfig | None:+ return self._state++ def save_state(self, data: CronitorResumeConfig) -> None:+ self.saved.append(data)+++def _http_404() -> requests.HTTPError:+ response = MagicMock()+ response.status_code = 404+ return requests.HTTPError(response=response)+++def _patch_fetch(monkeypatch: Any, responses: dict[str, Any]) -> list[str]:+ fetched: list[str] = []++ def fake_fetch(session: Any, url: str, api_key: str, logger: Any) -> Any:+ fetched.append(url)+ result = responses[url]+ if isinstance(result, Exception):+ raise result+ return result++ monkeypatch.setattr(cronitor, "_fetch", fake_fetch)+ return fetched+++def _freeze_now(monkeypatch: Any) -> None:+ monkeypatch.setattr(cronitor, "time", SimpleNamespace(time=lambda: NOW))+++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+++def _monitors_url(page: int) -> str:+ return f"https://cronitor.io/api/monitors?page={page}&pageSize={PAGE_SIZE}&sort=created"+++def _monitors_page(count: int, prefix: str = "job") -> dict[str, Any]:+ return {"monitors": [{"key": f"{prefix}-{i}", "created": "2026-01-01T00:00:00Z"} for i in range(count)]}+++class TestCoerceEpoch:+ @parameterized.expand(+ [+ ("int", 1712000000, 1712000000),+ ("float", 1712000000.5, 1712000000),+ ("numeric_string", "1712000000", 1712000000),+ ("aware_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), 1772593094),+ ("naive_datetime_is_utc", datetime(2026, 3, 4, 2, 58, 14), 1772593094),+ ("date_value", date(2026, 3, 4), 1772582400),+ ("iso_string", "2026-03-04T02:58:14Z", 1772593094),+ ("none", None, None),+ ("bool_is_not_a_cursor", True, None),+ ("garbage_string", "not-a-date", None),+ ]+ )+ def test_coerce(self, _name: str, value: Any, expected: int | None) -> None:+ assert _coerce_epoch(value) == expected+++class TestMonitors:+ def test_paginates_until_short_page(self, monkeypatch: Any) -> None:+ responses = {+ _monitors_url(1): _monitors_page(PAGE_SIZE),+ _monitors_url(2): _monitors_page(3, prefix="tail"),+ }+ fetched = _patch_fetch(monkeypatch, responses)+ manager = _FakeResumableManager()+ rows = _collect(manager, "monitors")++ assert len(rows) == PAGE_SIZE + 3+ # A short page signals the end — no extra empty-page request.+ assert fetched == list(responses)+ # State is saved only while more pages remain, and only after the page was yielded.+ assert manager.saved == [CronitorResumeConfig(page=2)]++ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:+ responses = {_monitors_url(3): _monitors_page(1)}+ fetched = _patch_fetch(monkeypatch, responses)+ rows = _collect(_FakeResumableManager(CronitorResumeConfig(page=3)), "monitors")++ assert len(rows) == 1+ assert fetched == [_monitors_url(3)]++ def test_unexpected_envelope_yields_nothing(self, monkeypatch: Any) -> None:+ _patch_fetch(monkeypatch, {_monitors_url(1): {"detail": "something unexpected"}})+ assert _collect(_FakeResumableManager(), "monitors") == []++ def test_sensitive_request_config_is_redacted(self, monkeypatch: Any) -> None:+ # HTTP-check monitors embed the outbound request config, which can carry credentials:+ # auth headers/cookies/body are dropped wholesale, and the check URL is reduced to scheme+ # + host/port so no userinfo, query string, or path segment can persist a token.+ monitor: dict[str, Any] = {+ "key": "check-a",+ "created": "2026-01-01T00:00:00Z",+ "request": {+ "url": "https://user:[email protected]:8443/health?token=secret#frag",+ "method": "GET",+ "headers": {"Authorization": "Bearer super-secret"},+ "cookies": {"session": "secret-cookie"},+ "body": "api_key=secret",+ },+ }+ _patch_fetch(monkeypatch, {_monitors_url(1): {"monitors": [monitor]}})+ rows = _collect(_FakeResumableManager(), "monitors")++ assert len(rows) == 1+ assert rows[0]["request"] == {"url": "https://example.com:8443", "method": "GET"}+ # The original response dict must not be mutated in place.+ assert "headers" in monitor["request"]+ assert monitor["request"]["url"] == "https://user:[email protected]:8443/health?token=secret#frag"++ def test_tokenized_url_path_is_not_persisted(self, monkeypatch: Any) -> None:+ # Slack incoming webhooks (and similar callback endpoints) embed the secret in a path+ # segment, so the path must be dropped, not just the query string.+ monitor: dict[str, Any] = {+ "key": "slack-check",+ "request": {"url": "https://hooks.slack.com/services/T00000/B00000/XXXXsecretXXXX"},+ }+ _patch_fetch(monkeypatch, {_monitors_url(1): {"monitors": [monitor]}})+ rows = _collect(_FakeResumableManager(), "monitors")++ assert rows[0]["request"] == {"url": "https://hooks.slack.com"}++ def test_monitor_without_request_config_is_untouched(self, monkeypatch: Any) -> None:+ # A monitor with no request config has nothing to redact and passes through unchanged.+ monitors = [{"key": "job-a", "created": "2026-01-01T00:00:00Z"}]+ _patch_fetch(monkeypatch, {_monitors_url(1): {"monitors": monitors}})+ rows = _collect(_FakeResumableManager(), "monitors")++ assert rows == monitors+++class TestInvocations:+ def _detail_url(self, key: str) -> str:+ return f"https://cronitor.io/api/monitors/{key}?withInvocations=true"++ def test_fans_out_and_tags_rows_with_monitor_key(self, monkeypatch: Any) -> None:+ responses = {+ _monitors_url(1): {"monitors": [{"key": "job-a"}, {"key": "job-b"}]},+ self._detail_url("job-a"): {+ "key": "job-a",+ "latest_invocations": [+ {"series": "s1", "started_at": 1712000000.1, "ended_at": 1712000060.2, "duration": 60100},+ # A run missing `series` must still get a non-null merge key.+ {"started_at": 1712003600.0},+ ],+ },+ self._detail_url("job-b"): {"key": "job-b", "latest_invocations": []},+ }+ _patch_fetch(monkeypatch, responses)+ manager = _FakeResumableManager()+ rows = _collect(manager, "invocations")++ assert [(r["monitor_key"], r["series"]) for r in rows] == [("job-a", "s1"), ("job-a", "")]+ # Bookmark advanced to the next monitor after job-a's rows were yielded.+ assert manager.saved == [CronitorResumeConfig(monitor_key="job-b")]++ def test_deleted_monitor_is_skipped_and_sync_continues(self, monkeypatch: Any) -> None:+ responses = {+ _monitors_url(1): {"monitors": [{"key": "gone"}, {"key": "job-b"}]},+ self._detail_url("gone"): _http_404(),+ self._detail_url("job-b"): {+ "key": "job-b",+ "latest_invocations": [{"series": "s2", "started_at": 1712000000}],+ },+ }+ _patch_fetch(monkeypatch, responses)+ rows = _collect(_FakeResumableManager(), "invocations")++ assert [r["monitor_key"] for r in rows] == ["job-b"]++ def test_resumes_from_monitor_key_bookmark(self, monkeypatch: Any) -> None:+ responses = {+ _monitors_url(1): {"monitors": [{"key": "job-a"}, {"key": "job-b"}, {"key": "job-c"}]},+ self._detail_url("job-b"): {"key": "job-b", "latest_invocations": [{"series": "s2", "started_at": 1}]},+ self._detail_url("job-c"): {"key": "job-c", "latest_invocations": [{"series": "s3", "started_at": 2}]},+ }+ fetched = _patch_fetch(monkeypatch, responses)+ rows = _collect(_FakeResumableManager(CronitorResumeConfig(monitor_key="job-b")), "invocations")++ # job-a was already processed before the crash; only job-b onwards is re-fetched.+ assert [r["monitor_key"] for r in rows] == ["job-b", "job-c"]+ assert self._detail_url("job-a") not in fetched+++class TestFlattenMetricsResponse:+ def test_flattens_and_coerces_stamp_to_int(self) -> None:+ data = {+ "monitors": {+ "job-a": {+ "env:production": [+ {"stamp": 1712000000.0, "duration_p50": 1250, "success_rate": 98.5, "run_count": 24},+ {"stamp": 1712003600, "run_count": 0},+ ],+ "env:staging": [{"stamp": 1712000000, "run_count": 1}],+ },+ }+ }++ rows = _flatten_metrics_response(data)++ assert [(r["monitor_key"], r["dimension"], r["stamp"]) for r in rows] == [+ ("job-a", "env:production", 1712000000),+ ("job-a", "env:production", 1712003600),+ ("job-a", "env:staging", 1712000000),+ ]+ assert all(isinstance(r["stamp"], int) for r in rows)+ assert rows[0]["duration_p50"] == 1250++ @parameterized.expand(+ [+ ("empty", {}),+ ("null_monitors", {"monitors": None}),+ ("point_without_stamp", {"monitors": {"job-a": {"env:production": [{"run_count": 1}]}}}),+ ]+ )+ def test_malformed_responses_yield_no_rows(self, _name: str, data: Any) -> None:+ assert _flatten_metrics_response(data) == []+++class TestMetrics:+ def _run(self, monkeypatch: Any, manager: _FakeResumableManager, **kwargs: Any) -> tuple[list[dict], list[str]]:+ _freeze_now(monkeypatch)+ monkeypatch.setattr(cronitor, "_list_monitor_keys", lambda session, api_key, logger: self.monitor_keys)+ fetched: list[str] = []++ def fake_fetch(session: Any, url: str, api_key: str, logger: Any) -> Any:+ fetched.append(url)+ return {"monitors": {}}++ monkeypatch.setattr(cronitor, "_fetch", fake_fetch)+ rows = _collect(manager, "metrics", **kwargs)+ return rows, fetched++ def setup_method(self) -> None:+ self.monitor_keys = ["job-a", "job-b"]++ def test_incremental_sync_requests_window_from_watermark(self, monkeypatch: Any) -> None:+ watermark = NOW - 3 * 3600+ _, fetched = self._run(+ monkeypatch,+ _FakeResumableManager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )++ assert len(fetched) == 1+ params = parse_qs(urlparse(fetched[0]).query)+ assert params["monitor"] == ["job-a", "job-b"]+ assert params["field"] == ["duration_p50", "duration_p90", "success_rate", "run_count"]+ assert params["start"] == [str(watermark)]+ assert params["end"] == [str(NOW)]++ def test_sub_hour_window_is_widened_to_api_minimum(self, monkeypatch: Any) -> None:+ # The API rejects spans under an hour; the re-pulled overlap is deduped on the primary key.+ _, fetched = self._run(+ monkeypatch,+ _FakeResumableManager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=NOW - 60,+ )++ params = parse_qs(urlparse(fetched[0]).query)+ assert params["start"] == [str(NOW - METRICS_MIN_WINDOW_SECONDS)]+ assert params["end"] == [str(NOW)]++ def test_backfill_walks_windows_and_checkpoints_after_each(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(cronitor, "METRICS_WINDOW_SECONDS", 3600)+ manager = _FakeResumableManager()+ _, fetched = self._run(+ monkeypatch,+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=NOW - 3 * 3600,+ )++ starts = [parse_qs(urlparse(url).query)["start"][0] for url in fetched]+ assert starts == [str(NOW - 3 * 3600), str(NOW - 2 * 3600), str(NOW - 3600)]+ # A checkpoint lands after each completed window except the last, so a crash resumes+ # mid-backfill instead of restarting from the watermark.+ assert manager.saved == [+ CronitorResumeConfig(window_start=NOW - 2 * 3600),+ CronitorResumeConfig(window_start=NOW - 3600),+ ]++ def test_resumes_from_saved_window_start(self, monkeypatch: Any) -> None:+ _, fetched = self._run(+ monkeypatch,+ _FakeResumableManager(CronitorResumeConfig(window_start=NOW - 2 * 3600)),+ should_use_incremental_field=True,+ db_incremental_field_last_value=NOW - 300 * 24 * 3600,+ )++ # The saved window wins over the (older) watermark.+ assert parse_qs(urlparse(fetched[0]).query)["start"] == [str(NOW - 2 * 3600)]++ def test_full_refresh_starts_at_max_lookback(self, monkeypatch: Any) -> None:+ _, fetched = self._run(monkeypatch, _FakeResumableManager(), should_use_incremental_field=False)++ first_start = int(parse_qs(urlparse(fetched[0]).query)["start"][0])+ assert first_start == NOW - 365 * 24 * 3600++ def test_monitors_are_batched_per_request_cap(self, monkeypatch: Any) -> None:+ self.monitor_keys = [f"job-{i}" for i in range(60)]+ _, fetched = self._run(+ monkeypatch,+ _FakeResumableManager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=NOW - 2 * 3600,+ )++ monitor_counts = [len(parse_qs(urlparse(url).query)["monitor"]) for url in fetched]+ assert monitor_counts == [50, 10]++ def test_empty_window_404_is_skipped(self, monkeypatch: Any) -> None:+ _freeze_now(monkeypatch)+ monkeypatch.setattr(cronitor, "_list_monitor_keys", lambda session, api_key, logger: ["job-a"])++ def fake_fetch(session: Any, url: str, api_key: str, logger: Any) -> Any:+ raise _http_404()++ monkeypatch.setattr(cronitor, "_fetch", fake_fetch)+ rows = _collect(+ _FakeResumableManager(),+ "metrics",+ should_use_incremental_field=True,+ db_incremental_field_last_value=NOW - 2 * 3600,+ )++ assert rows == []+++class TestSourceResponse:+ @parameterized.expand(+ [+ ("monitors", ["key"], "asc"),+ ("invocations", ["monitor_key", "series", "started_at"], "asc"),+ # Metrics rows aren't globally stamp-ascending (batched per monitor group per window),+ # so desc defers the watermark to job end.+ ("metrics", ["monitor_key", "dimension", "stamp"], "desc"),+ ]+ )+ def test_primary_keys_and_sort_mode(self, endpoint: str, primary_keys: list[str], sort_mode: str) -> None:+ response = cronitor_source(+ api_key="key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )++ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.sort_mode == sort_mode++ def test_unknown_endpoint_raises(self) -> None:+ with pytest.raises(KeyError):+ cronitor_source(api_key="key", endpoint="nope", logger=MagicMock(), resumable_source_manager=MagicMock())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/tests/test_cronitor_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/tests/test_cronitor_source.pynew file mode 100644index 000000000000..a9dac0d8b371--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/tests/test_cronitor_source.py@@ -0,0 +1,152 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.cronitor.cronitor import CronitorResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.cronitor.settings import (+ CRONITOR_ENDPOINTS,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cronitor.source import CronitorSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CronitorSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++# Only the metrics API exposes a server-side time filter (start/end); everything else is full refresh.+_INCREMENTAL_ENDPOINTS = {"metrics"}+_FULL_REFRESH_ENDPOINTS = {"monitors", "invocations"}+++class TestCronitorSource:+ def setup_method(self):+ self.source = CronitorSource()+ self.team_id = 123+ self.config = CronitorSourceConfig(api_key="key")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.CRONITOR++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Cronitor"+ assert config.label == "Cronitor"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/cronitor.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/cronitor"++ 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++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://cronitor.io/api/monitors?page=1&pageSize=50&sort=created",+ "403 Client Error: Forbidden for url: https://cronitor.io/api/metrics?monitor=job-a",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ 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",+ [+ "429 Client Error: Too Many Requests for url: https://cronitor.io/api/monitors",+ "500 Server Error: Internal Server Error for url: https://cronitor.io/api/monitors",+ "HTTPSConnectionPool(host='cronitor.io', 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] == ["stamp"]+ 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=["metrics"])+ assert len(schemas) == 1+ assert schemas[0].name == "metrics"++ 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(CRONITOR_ENDPOINTS)++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ ((True, 200), True, None),+ ((False, 401), False, "Invalid Cronitor API key. Make sure the key has the monitor:read scope."),+ ((False, 403), False, "Invalid Cronitor API key. Make sure the key has the monitor:read scope."),+ ((False, None), False, "Could not connect to Cronitor with the provided API key"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cronitor.source.validate_cronitor_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("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 CronitorResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.cronitor.source.cronitor_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_cronitor_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "metrics"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = 1712000000+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_cronitor_source.assert_called_once()+ kwargs = mock_cronitor_source.call_args.kwargs+ assert kwargs["api_key"] == "key"+ assert kwargs["endpoint"] == "metrics"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["db_incremental_field_last_value"] == 1712000000++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.cronitor.source.cronitor_source")+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_cronitor_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "monitors"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = 1712000000++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_cronitor_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex d1d5285f2093..c6fef4b4e327 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@@ -1073,7 +1073,7 @@ class CriteoSourceConfig(config.Config):@config.configclass CronitorSourceConfig(config.Config):- pass+ api_key: str@config.config