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 grafana import source (#71210)

Tom Owers8a028154ffd7
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 f1c2bec1a5f2..8c6eef359a1b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -228,6 +228,7 @@ the row lists both.
| google_pagespeed_insights | HTTP | requests | ✅ |
| google_sheets | HTTP (vendor SDK) | gspread | ✅ |
| google_webfonts | HTTP | requests | ✅ |
+| grafana | HTTP | requests | ✅ |
| granola | HTTP | requests | ✅ |
| gorgias | HTTP | requests | ✅ |
| greenhouse | HTTP | requests | ✅ |
@@ -706,7 +707,6 @@ doesn't conflict with concurrent PRs.
- google_forms
- google_tasks
- google_workspace_admin_reports
-- grafana
- greythr
- growthbook
- gumloop
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 740fd9695c04..aab199ec6a67 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
@@ -73,6 +73,14 @@ class GoogleAdsIsMccAccountConfig(config.Config):
enabled: bool = config.value(converter=config.str_to_bool, default=False)
+class GrafanaAuthMethodConfig(config.Config):
+ selection: Literal["token", "basic"] = "token"
+ token: str | None = None
+ username: str | None = None
+ password: str | None = None
+
+
@config.config
class HubspotCustomPropertiesConfig(config.Config):
enabled: bool = config.value(converter=config.str_to_bool, default=False)
@@ -1868,7 +1876,9 @@ class GorgiasSourceConfig(config.Config):
@config.config
class GrafanaSourceConfig(config.Config):
- pass
+ host: str
+ auth_method: GrafanaAuthMethodConfig
+ org_id: str | None = None
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/canonical_descriptions.py
new file mode 100644
index 000000000000..de0b7370cf92
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/canonical_descriptions.py
@@ -0,0 +1,134 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "dashboards": {
+ "description": "Dashboard metadata from the Grafana search API (one row per dashboard, without panel definitions).",
+ "docs_url": "https://grafana.com/docs/grafana/latest/developers/http_api/folder_dashboard_search/",
+ "columns": {
+ "id": "Internal numeric identifier of the dashboard (deprecated in Grafana in favor of uid).",
+ "uid": "Unique identifier of the dashboard, stable across the organization.",
+ "orgId": "ID of the organization the dashboard belongs to.",
+ "title": "Title of the dashboard.",
+ "uri": "Legacy URI of the dashboard.",
+ "url": "Relative URL to view the dashboard.",
+ "slug": "URL-friendly slug of the dashboard title.",
+ "type": "Search result type; always dash-db for dashboards.",
+ "tags": "Tags assigned to the dashboard.",
+ "isStarred": "Whether the dashboard is starred by the authenticated user.",
+ "folderId": "Internal numeric identifier of the containing folder (deprecated in favor of folderUid).",
+ "folderUid": "Unique identifier of the containing folder.",
+ "folderTitle": "Title of the containing folder.",
+ "folderUrl": "Relative URL of the containing folder.",
+ "isDeleted": "Whether the dashboard has been soft-deleted.",
+ },
+ },
+ "folders": {
+ "description": "Dashboard folders in the organization.",
+ "docs_url": "https://grafana.com/docs/grafana/latest/developers/http_api/folder/",
+ "columns": {
+ "id": "Internal numeric identifier of the folder (deprecated in Grafana in favor of uid).",
+ "uid": "Unique identifier of the folder, stable across the organization.",
+ "title": "Title of the folder.",
+ },
+ },
+ "teams": {
+ "description": "Teams in the organization.",
+ "docs_url": "https://grafana.com/docs/grafana/latest/developers/http_api/team/",
+ "columns": {
+ "id": "Internal numeric identifier of the team.",
+ "orgId": "ID of the organization the team belongs to.",
+ "name": "Name of the team.",
+ "email": "Contact email of the team.",
+ "avatarUrl": "URL of the team's avatar image.",
+ "memberCount": "Number of members in the team.",
+ },
+ },
+ "users": {
+ "description": "Users with membership in the organization.",
+ "docs_url": "https://grafana.com/docs/grafana/latest/developers/http_api/org/",
+ "columns": {
+ "orgId": "ID of the organization the membership belongs to.",
+ "userId": "Internal numeric identifier of the user.",
+ "email": "Email address of the user.",
+ "name": "Display name of the user.",
+ "login": "Login handle of the user.",
+ "role": "Role of the user within the organization (Viewer, Editor, or Admin).",
+ "lastSeenAt": "Timestamp of the user's last activity.",
+ },
+ },
+ "datasources": {
+ "description": "Data source connections configured in the organization. Secure fields (passwords, secrets) are never returned by the Grafana API.",
+ "docs_url": "https://grafana.com/docs/grafana/latest/developers/http_api/data_source/",
+ "columns": {
+ "id": "Internal numeric identifier of the data source (deprecated in Grafana in favor of uid).",
+ "uid": "Unique identifier of the data source, stable across the organization.",
+ "orgId": "ID of the organization the data source belongs to.",
+ "name": "Name of the data source.",
+ "type": "Data source plugin type (e.g. prometheus, loki, postgres).",
+ "typeName": "Human-readable name of the data source plugin type.",
+ "url": "URL of the upstream system the data source connects to.",
+ "access": "Access mode: proxy (server-side) or direct (browser).",
+ "database": "Database name used by the data source, when applicable.",
+ "basicAuth": "Whether the data source authenticates upstream with basic auth.",
+ "isDefault": "Whether this is the organization's default data source.",
+ "jsonData": "Non-secret plugin-specific configuration.",
+ "readOnly": "Whether the data source is provisioned and read-only in the UI.",
+ },
+ },
+ "service_accounts": {
+ "description": "Service accounts in the organization (machine identities used for API access).",
+ "docs_url": "https://grafana.com/docs/grafana/latest/developers/http_api/serviceaccount/",
+ "columns": {
+ "id": "Internal numeric identifier of the service account.",
+ "orgId": "ID of the organization the service account belongs to.",
+ "name": "Display name of the service account.",
+ "login": "Login handle of the service account.",
+ "role": "Role of the service account within the organization.",
+ "isDisabled": "Whether the service account is disabled.",
+ "tokens": "Number of API tokens issued for the service account.",
+ "avatarUrl": "URL of the service account's avatar image.",
+ },
+ },
+ "alert_rules": {
+ "description": "Grafana-managed alert rules, as exposed by the alert provisioning API.",
+ "docs_url": "https://grafana.com/docs/grafana/latest/developers/http_api/alerting_provisioning/",
+ "columns": {
+ "id": "Internal numeric identifier of the alert rule.",
+ "uid": "Unique identifier of the alert rule, stable across the organization.",
+ "orgID": "ID of the organization the alert rule belongs to.",
+ "folderUID": "Unique identifier of the folder containing the alert rule.",
+ "ruleGroup": "Name of the rule group the alert rule belongs to.",
+ "title": "Title of the alert rule.",
+ "condition": "refId of the query or expression used as the alert condition.",
+ "data": "Queries and expressions evaluated by the alert rule.",
+ "noDataState": "State the alert enters when the query returns no data.",
+ "execErrState": "State the alert enters when rule evaluation fails.",
+ "for": "Duration the condition must be breached before the alert fires.",
+ "annotations": "Key-value annotations attached to the alert rule.",
+ "labels": "Key-value labels attached to the alert rule.",
+ "isPaused": "Whether evaluation of the alert rule is paused.",
+ "updated": "Timestamp when the alert rule was last updated.",
+ },
+ },
+ "annotations": {
+ "description": "User- and API-created annotations (points or regions marked on dashboards). Alert state history entries are excluded because the Grafana API returns them without a stable identifier.",
+ "docs_url": "https://grafana.com/docs/grafana/latest/developers/http_api/annotations/",
+ "columns": {
+ "id": "Unique numeric identifier of the annotation.",
+ "dashboardUID": "Unique identifier of the dashboard the annotation is attached to; empty for organization annotations.",
+ "panelId": "ID of the panel the annotation is attached to, when applicable.",
+ "userUID": "Unique identifier of the user or service account that created the annotation.",
+ "time": "Start time of the annotation as an epoch-millisecond timestamp.",
+ "timeEnd": "End time of the annotation as an epoch-millisecond timestamp (equals time for point annotations).",
+ "created": "Epoch-millisecond timestamp when the annotation was created.",
+ "updated": "Epoch-millisecond timestamp when the annotation was last updated.",
+ "text": "Text content of the annotation.",
+ "tags": "Tags assigned to the annotation.",
+ "login": "Login handle of the user or service account that created the annotation.",
+ "email": "Email of the user that created the annotation.",
+ "data": "Additional structured data attached to the annotation.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/grafana.py b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/grafana.py
new file mode 100644
index 000000000000..1780234608ad
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/grafana.py
@@ -0,0 +1,665 @@
+import re
+import json
+import time
+import base64
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode, urlparse
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from urllib3.util.retry import Retry
+
+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.mixins import _is_host_safe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.grafana.settings import (
+ ANNOTATIONS_LIMIT,
+ DEFAULT_PAGE_SIZE,
+ GRAFANA_ENDPOINTS,
+ GrafanaEndpointConfig,
+)
+
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+
+# Disable urllib3 adapter-level retries on every Grafana session. The default policy honors an
+# attacker-controlled ``Retry-After`` on 429/503 (urllib3 will sleep for up to hours inside a single
+# ``session.get``), which sits below and would defeat the bounded response/walk deadlines. Retries for
+# the sync fetch are handled by ``_make_fetch``'s Tenacity policy with bounded jitter/backoff instead.
+NO_ADAPTER_RETRY = Retry(total=0)
+
+# Every Grafana list endpoint here is paginated (DEFAULT_PAGE_SIZE / ANNOTATIONS_LIMIT rows), so a
+# well-behaved response body is small. This ceiling exists only to stop a malicious or misconfigured
+# host from exhausting an import worker's memory with an unbounded (or Content-Length-less, chunked)
+# body — requests buffers the whole body otherwise.
+MAX_RESPONSE_BYTES = 64 * 1024 * 1024
+
+# Total wall-clock budget for downloading one response body. The socket timeout only caps inactivity
+# between chunks, so a host that trickles bytes just under that timeout could occupy a worker
+# indefinitely; this bounds the whole read regardless of how the bytes are paced.
+MAX_RESPONSE_READ_SECONDS = 120
+
+HOST_NOT_ALLOWED_ERROR = "Grafana host is not allowed"
+
+TOKEN_AUTH = "token"
+BASIC_AUTH = "basic"
+
+# Below this window width, stop bisecting a saturated annotations window and accept truncation:
+# more than ANNOTATIONS_LIMIT annotations inside one minute can't be separated by the from/to
+# filter's millisecond granularity in a bounded number of requests.
+MIN_ANNOTATION_WINDOW_MS = 60 * 1000
+
+# Per-run request budgets. A customer-controlled host can keep returning full pages (or saturated
+# annotation windows) forever, so an unbounded loop would occupy an import worker indefinitely.
+# Both walks are resumable, so on hitting the budget we persist the next position and return — the
+# next scheduled sync continues from there instead of any one run running without end. Sized well
+# above what a real Grafana instance needs in a single sync.
+MAX_PAGES_PER_RUN = 10_000
+MAX_ANNOTATION_REQUESTS_PER_RUN = 10_000
+
+# Wall-clock budget for one walk. The request budgets alone still let a hostile host occupy a
+# worker for days by stalling every response just under the socket timeout (10,000 requests × ~60s
+# ≈ the one-week Temporal activity timeout), so each walk also stops at this deadline and resumes
+# from its saved position on the next sync. A real instance pages back-to-back and finishes a full
+# 10,000-request walk in well under an hour, so legitimate syncs never hit this.
+MAX_WALK_SECONDS = 2 * 60 * 60
+
+# Loopback hosts where plaintext HTTP carries no network-exposure risk (local dev / self-hosted on
+# the same box). Every other host is forced to HTTPS so credentials never traverse a network in
+# cleartext.
+LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"}
+
+
+class GrafanaRetryableError(Exception):
+ pass
+
+
+class GrafanaHostNotAllowedError(Exception):
+ pass
+
+
+class GrafanaAuthError(Exception):
+ """Raised when credentials are missing or malformed. Deterministic — retrying never fixes
+ it — so it surfaces via get_non_retryable_errors."""
+
+ pass
+
+
+class GrafanaResponseTooLargeError(Exception):
+ """A response body exceeded the size or time budget for a single request. Deterministic for a
+ given host config — not retried — so it fails the request fast instead of buffering forever."""
+
+ pass
+
+
+class GrafanaAuth:
+ # "token" sends a service account token as an Authorization: Bearer header (works on both
+ # Grafana Cloud and self-hosted); "basic" sends HTTP Basic credentials (self-hosted OSS only —
+ # Grafana Cloud rejects basic auth on the HTTP API).
+ method: str
+ token: Optional[str] = None
+ username: Optional[str] = None
+ password: Optional[str] = None
+
+
+class GrafanaResumeConfig:
+ # Next page to fetch for page-number endpoints. None for the other pagination styles.
+ next_page: int | None = None
+ # Lower bound (epoch ms) of the next annotations window to fetch. Windows are processed in
+ # ascending order, so everything before this boundary has already been yielded.
+ annotations_from_ms: int | None = None
+
+
+def _with_default_scheme(host: str) -> str:
+ host = host.strip()
+ if not re.match(r"^https?://", host, flags=re.IGNORECASE):
+ host = f"https://{host}"
+ return host
+
+
+def has_embedded_credentials(host: str) -> bool:
+ """Whether the URL carries userinfo (``https://user:pass@host``).
+
+ The host field is stored as non-secret config, so credentials embedded in it would be
+ visible to anyone who can view the source configuration — reject them at validation.
+ """
+ try:
+ parsed = urlparse(_with_default_scheme(host))
+ return bool(parsed.username or parsed.password)
+ except ValueError:
+ return False
+
+
+def normalize_host(host: str) -> str:
+ """Turn whatever the user typed into a bare instance base URL (scheme + host, no path).
+
+ Accepts ``https://yourstack.grafana.net``, ``yourstack.grafana.net``,
+ ``https://yourstack.grafana.net/api`` and returns ``https://yourstack.grafana.net``.
+ Defaults to https when no scheme is given, and forces a plaintext ``http://`` host to
+ ``https://`` so credentials are never sent over the network in cleartext — except for
+ loopback hosts (local dev / self-hosted on the same box), which are left untouched.
+ """
+ parsed = urlparse(_with_default_scheme(host))
+ scheme = parsed.scheme.lower()
+ hostname = (parsed.hostname or "").lower()
+ if scheme == "http" and hostname not in LOOPBACK_HOSTS:
+ scheme = "https"
+ # Rebuild netloc from hostname + port only: drops any trailing path (e.g. "/api") and any
+ # userinfo — URL-embedded credentials must never be persisted or sent (see
+ # has_embedded_credentials, which rejects them at validation as well).
+ if ":" in hostname: # a bare IPv6 address needs its brackets back
+ hostname = f"[{hostname}]"
+ netloc = f"{hostname}:{parsed.port}" if parsed.port else hostname
+ return f"{scheme}://{netloc}"
+
+
+def _hostname(host: str) -> str:
+ return (urlparse(normalize_host(host)).hostname or "").lower()
+
+
+def _resolve_auth_headers(auth: GrafanaAuth, org_id: Optional[str] = None) -> dict[str, str]:
+ headers: dict[str, str] = {"Accept": "application/json"}
+
+ if auth.method == TOKEN_AUTH:
+ if not auth.token:
+ raise GrafanaAuthError("Missing Grafana service account token")
+ headers["Authorization"] = f"Bearer {auth.token}"
+ else:
+ if not auth.username or not auth.password:
+ raise GrafanaAuthError("Missing Grafana username or password")
+ encoded = base64.b64encode(f"{auth.username}:{auth.password}".encode()).decode()
+ headers["Authorization"] = f"Basic {encoded}"
+
+ if org_id and str(org_id).strip():
+ headers["X-Grafana-Org-Id"] = str(org_id).strip()
+
+ return headers
+
+
+def _redact_values(auth: GrafanaAuth) -> tuple[str, ...]:
+ """Credential strings to value-mask in any captured data-request sample, on top of the
+ name-based header/body scrubbers — defense-in-depth in case a credential ever echoes into
+ a response body."""
+ if auth.method == TOKEN_AUTH:
+ return (auth.token,) if auth.token else ()
+ return tuple(v for v in (auth.username, auth.password) if v)
+
+
+def _connection_error_message(error: Exception) -> str:
+ """Translate a low-level requests connection failure into a short, actionable message.
+
+ requests surfaces these as host-revealing blobs; returning that verbatim leaks the
+ customer's host/IP and tells them nothing they can act on.
+ """
+ text = str(error).lower()
+ if isinstance(error, requests.exceptions.SSLError):
+ return (
+ "Couldn't establish a secure (TLS) connection to your Grafana instance. "
+ "Check that the instance URL is correct and its TLS certificate is valid."
+ )
+ if isinstance(error, requests.exceptions.Timeout):
+ return (
+ "Connecting to your Grafana instance timed out. "
+ "Check that the instance URL is correct and reachable from the public internet."
+ )
+ if isinstance(error, requests.exceptions.ConnectionError) and (
+ "name or service not known" in text or "nodename nor servname" in text or "failed to resolve" in text
+ ):
+ return (
+ "Couldn't resolve the Grafana host. "
+ "Check that the instance URL is spelled correctly and reachable from the public internet."
+ )
+ return (
+ "Couldn't connect to your Grafana instance. "
+ "Check that the instance URL is correct and reachable from the public internet."
+ )
+
+
+def _read_body_bounded(response: requests.Response) -> bytes:
+ """Download a streamed response body under a hard size and time budget.
+
+ Must be called on a response fetched with ``stream=True`` so nothing is buffered before these
+ caps apply. Rejects an oversized declared ``Content-Length`` up front, then reads chunk by
+ chunk, aborting if the running total exceeds MAX_RESPONSE_BYTES or the read outlasts
+ MAX_RESPONSE_READ_SECONDS. A customer-controlled host can otherwise return an arbitrarily large
+ body or trickle one forever, exhausting or indefinitely occupying an import worker.
+ """
+ declared = response.headers.get("Content-Length")
+ if declared is not None:
+ try:
+ if int(declared) > MAX_RESPONSE_BYTES:
+ raise GrafanaResponseTooLargeError(
+ f"Grafana response Content-Length {declared} exceeds the {MAX_RESPONSE_BYTES}-byte limit"
+ )
+ except ValueError:
+ pass # unparseable header — fall through to the streamed cap below
+
+ deadline = time.monotonic() + MAX_RESPONSE_READ_SECONDS
+ chunks: list[bytes] = []
+ total = 0
+ for chunk in response.iter_content(chunk_size=64 * 1024):
+ total += len(chunk)
+ if total > MAX_RESPONSE_BYTES:
+ raise GrafanaResponseTooLargeError(f"Grafana response exceeded the {MAX_RESPONSE_BYTES}-byte limit")
+ if time.monotonic() > deadline:
+ raise GrafanaResponseTooLargeError(
+ f"Reading the Grafana response exceeded the {MAX_RESPONSE_READ_SECONDS}s limit"
+ )
+ chunks.append(chunk)
+ return b"".join(chunks)
+
+
+def _read_json_bounded(response: requests.Response) -> Any:
+ """Read a streamed response body under the size/time budget, then parse it as JSON."""
+ body = _read_body_bounded(response)
+ if not body:
+ return None
+ return json.loads(body)
+
+
+def _extract_items(data: Any, data_key: str | None) -> list[dict[str, Any]]:
+ """Normalize Grafana's two list shapes into a flat list of records.
+
+ Most list endpoints return a bare JSON array; the search-style endpoints
+ (``/api/teams/search``, ``/api/serviceaccounts/search``) wrap it, e.g.
+ ``{"teams": [...], "totalCount": N}``.
+ """
+ if data_key is not None:
+ if isinstance(data, dict) and isinstance(data.get(data_key), list):
+ return [item for item in data[data_key] if isinstance(item, dict)]
+ return []
+ if isinstance(data, list):
+ return [item for item in data if isinstance(item, dict)]
+ return []
+
+
+def _permission_error_from_response(response: requests.Response) -> str:
+ """Build a short scope message from a Grafana 403 body.
+
+ Grafana names the missing scope, e.g. ``{"message": "You'll need additional permissions to
+ perform this action. Permissions needed: teams:read"}`` — surface that instead of the raw body.
+ """
+ try:
+ data = _read_json_bounded(response)
+ message = data.get("message", "") if isinstance(data, dict) else ""
+ except Exception:
+ message = ""
+ match = re.search(r"Permissions needed:\s*([\w:.*-]+)", message)
+ if match:
+ return f"Your Grafana credentials are missing the `{match.group(1)}` permission."
+ return "Your Grafana credentials lack the permissions needed to access this data."
+
+
+def _to_epoch_ms(value: Any) -> int:
+ """Coerce an incremental cursor value into epoch milliseconds."""
+ if isinstance(value, bool):
+ return 0
+ 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() * 1000)
+ if isinstance(value, date):
+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp() * 1000)
+ if isinstance(value, str):
+ try:
+ return int(value)
+ except ValueError:
+ return 0
+ return 0
+
+
+def _check_host(host: str, team_id: int) -> None:
+ # Re-check at run time (not just source-create) in case the host was edited or now resolves to
+ # an internal address (SSRF / DNS rebinding). Only enforced on cloud.
+ host_ok, host_err = _is_host_safe(_hostname(host), team_id)
+ if not host_ok:
+ raise GrafanaHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)
+
+
+def _make_fetch(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger):
+ @retry(
+ retry=retry_if_exception_type((GrafanaRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def fetch(url: str) -> Any:
+ # Don't follow redirects: a customer-controlled host could 3xx to an internal address,
+ # bypassing the host check (SSRF). stream=True keeps the body off the wire until the bounded
+ # readers apply the size/time budget; the `with` releases the connection on every path.
+ with session.get(
+ url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False, stream=True
+ ) as response:
+ if response.status_code == 429 or response.status_code >= 500:
+ raise GrafanaRetryableError(f"Grafana API error (retryable): status={response.status_code}, url={url}")
+ if response.is_redirect or response.is_permanent_redirect:
+ raise GrafanaHostNotAllowedError(
+ f"Grafana API returned an unexpected redirect (status={response.status_code}); refusing to follow it"
+ )
+ if not response.ok:
+ body = _read_body_bounded(response).decode("utf-8", "replace")
+ logger.error(f"Grafana API error: status={response.status_code}, body={body}, url={url}")
+ response.raise_for_status()
+
+ return _read_json_bounded(response)
+
+ return fetch
+
+
+def validate_credentials(
+ host: str,
+ auth: GrafanaAuth,
+ org_id: Optional[str] = None,
+ team_id: Optional[int] = None,
+ schema_name: Optional[str] = None,
+) -> tuple[bool, str | None]:
+ """Confirm the credentials are genuine with a cheap ``/api/org`` probe.
+
+ The host is customer-controlled, so we block internal/private addresses (SSRF, cloud only)
+ and refuse to follow redirects. A 403 means the token is genuine but under-scoped for the
+ probe — let source creation through (per-endpoint scope is reported separately via
+ ``get_endpoint_permissions``) and only fail when a specific ``schema_name`` is being checked.
+ """
+ if has_embedded_credentials(host):
+ return False, (
+ "Remove the username and password from the instance URL. Use the authentication method fields instead."
+ )
+
+ try:
+ base_url = normalize_host(host)
+ except Exception:
+ return False, "Invalid Grafana host"
+
+ hostname = _hostname(host)
+ if not hostname or not re.match(r"^[A-Za-z0-9.\-]+$", hostname):
+ return False, "Invalid Grafana host"
+
+ if team_id is not None:
+ host_ok, host_err = _is_host_safe(hostname, team_id)
+ if not host_ok:
+ return False, host_err or HOST_NOT_ALLOWED_ERROR
+
+ try:
+ headers = _resolve_auth_headers(auth, org_id)
+ except GrafanaAuthError as e:
+ return False, str(e)
+
+ session = make_tracked_session(retry=NO_ADAPTER_RETRY, redact_values=_redact_values(auth))
+ # stream=True so a hostile host can't buffer an unbounded probe body into the worker; the body
+ # is only read (bounded) when a 403 needs its scope message.
+ try:
+ with session.get(
+ f"{base_url}/api/org", headers=headers, timeout=10, allow_redirects=False, stream=True
+ ) as response:
+ if response.is_redirect or response.is_permanent_redirect:
+ return False, HOST_NOT_ALLOWED_ERROR
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, "Invalid Grafana credentials"
+ if response.status_code == 403:
+ if schema_name is None:
+ return True, None
+ return False, _permission_error_from_response(response)
+
+ # The host responded but not in a way we recognise — often it isn't a Grafana instance
+ # at all (e.g. a proxy or hosting-provider error page). Surface the status only; never
+ # echo the raw response body, which can carry arbitrary upstream content.
+ return (
+ False,
+ f"Grafana returned an unexpected response (HTTP {response.status_code}). "
+ "Check that the instance URL points to your Grafana instance.",
+ )
+ except requests.exceptions.RequestException as e:
+ return False, _connection_error_message(e)
+
+
+def _probe_params(config: GrafanaEndpointConfig) -> dict[str, Any]:
+ params: dict[str, Any] = {**config.params}
+ if config.pagination == "page":
+ params[config.page_size_param] = 1
+ params["page"] = 1
+ elif config.pagination == "time_window":
+ params.update({"from": 0, "to": 1, "limit": 1})
+ return params
+
+
+def get_endpoint_permissions(
+ host: str,
+ auth: GrafanaAuth,
+ org_id: Optional[str],
+ team_id: int,
+ endpoints: list[str],
+) -> dict[str, str | None]:
+ """Probe each endpoint with a minimal request; ``None`` when reachable, a short reason when
+ the credentials lack its scope. Only a definitive denial (401/403) counts as unreachable —
+ throttles, 5xx, and network blips must not mark a table as needing extra scopes."""
+ base_url = normalize_host(host)
+ headers = _resolve_auth_headers(auth, org_id)
+ session = make_tracked_session(retry=NO_ADAPTER_RETRY, redact_values=_redact_values(auth))
+
+ results: dict[str, str | None] = {}
+ for endpoint in endpoints:
+ config = GRAFANA_ENDPOINTS.get(endpoint)
+ if config is None:
+ results[endpoint] = None
+ continue
+ url = f"{base_url}{config.path}?{urlencode(_probe_params(config))}"
+ try:
+ # stream=True so a hostile host can't buffer an unbounded probe body; only a 403's scope
+ # message is read (bounded) below.
+ with session.get(url, headers=headers, timeout=10, allow_redirects=False, stream=True) as response:
+ if response.status_code == 401:
+ results[endpoint] = "Your Grafana credentials are invalid or expired."
+ elif response.status_code == 403:
+ results[endpoint] = _permission_error_from_response(response)
+ else:
+ results[endpoint] = None
+ except requests.exceptions.RequestException:
+ results[endpoint] = None
+ continue
+ return results
+
+
+def _get_paged_rows(
+ fetch: Any,
+ base_url: str,
+ config: GrafanaEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[GrafanaResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.next_page if resume is not None and resume.next_page is not None else 1
+ if page > 1:
+ logger.debug(f"Grafana: resuming {config.name} from page {page}")
+
+ pages_this_run = 0
+ deadline = time.monotonic() + MAX_WALK_SECONDS
+ while True:
+ params = {**config.params, config.page_size_param: DEFAULT_PAGE_SIZE, "page": page}
+ data = fetch(f"{base_url}{config.path}?{urlencode(params)}")
+ items = _extract_items(data, config.data_key)
+
+ if items:
+ yield items
+
+ if len(items) < DEFAULT_PAGE_SIZE:
+ break
+
+ page += 1
+ pages_this_run += 1
+ # Save AFTER yielding so a crash re-yields the last page (merge dedupes on the primary
+ # key) rather than skipping it.
+ resumable_source_manager.save_state(GrafanaResumeConfig(next_page=page))
+
+ if pages_this_run >= MAX_PAGES_PER_RUN or time.monotonic() > deadline:
+ # A host returning full pages forever — or stalling each response just under the socket
+ # timeout — would otherwise occupy this worker without end; the resume state saved above
+ # lets the next sync pick up from this page.
+ logger.warning(
+ f"Grafana: {config.name} hit the per-run page or wall-clock budget; "
+ f"resuming from page {page} on the next sync"
+ )
+ return
+
+
+def _get_annotation_rows(
+ fetch: Any,
+ base_url: str,
+ config: GrafanaEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[GrafanaResumeConfig],
+ logger: FilteringBoundLogger,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk ``/api/annotations`` in ascending epoch-ms windows, bisecting adaptively.
+
+ The endpoint only exposes ``from``/``to``/``limit`` — no cursor — and on Grafana Cloud the
+ ``limit`` semantics across its composite annotation store are unreliable, so a window is only
+ trusted when it returns fewer rows than the limit; a saturated window is split in half until
+ it fits (or bottoms out at MIN_ANNOTATION_WINDOW_MS, where truncation is logged). Starting
+ from one [start, now] window means a sparse history costs a handful of requests while dense
+ bursts get subdivided as needed.
+ """
+ now_ms = int(datetime.now(UTC).timestamp() * 1000)
+
+ start_ms = 0
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ # Inclusive lower bound: rows at exactly the watermark are re-fetched and deduped on merge.
+ start_ms = max(0, _to_epoch_ms(db_incremental_field_last_value))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.annotations_from_ms is not None:
+ start_ms = max(start_ms, resume.annotations_from_ms)
+ logger.debug(f"Grafana: resuming annotations from {start_ms}")
+
+ if start_ms >= now_ms:
+ return
+
+ # LIFO stack of [from, to] windows with the oldest on top, so rows stream oldest-window-first
+ # and the resume boundary only ever moves forward.
+ windows: list[tuple[int, int]] = [(start_ms, now_ms)]
+ requests_this_run = 0
+ deadline = time.monotonic() + MAX_WALK_SECONDS
+ while windows:
+ if requests_this_run >= MAX_ANNOTATION_REQUESTS_PER_RUN or time.monotonic() > deadline:
+ # A host that saturates every window — or stalls each response just under the socket
+ # timeout — would otherwise fan out without end; the resume boundary saved below lets
+ # the next sync continue from the last completed window.
+ logger.warning(
+ "Grafana: annotations hit the per-run request or wall-clock budget; "
+ "resuming from the last saved boundary on the next sync"
+ )
+ return
+ window_from, window_to = windows.pop()
+ params = {**config.params, "from": window_from, "to": window_to, "limit": ANNOTATIONS_LIMIT}
+ items = _extract_items(fetch(f"{base_url}{config.path}?{urlencode(params)}"), config.data_key)
+ requests_this_run += 1
+
+ if len(items) >= ANNOTATIONS_LIMIT:
+ if window_to - window_from > MIN_ANNOTATION_WINDOW_MS:
+ mid = (window_from + window_to) // 2
+ # Halves share the `mid` boundary because from/to inclusivity isn't documented;
+ # a row at exactly `mid` is fetched twice and deduped on merge rather than skipped.
+ windows.append((mid, window_to))
+ windows.append((window_from, mid))
+ continue
+ logger.warning(
+ f"Grafana: annotations window [{window_from}, {window_to}] returned {len(items)} rows at the "
+ f"response limit and can't be split further; some annotations in this window may be missing"
+ )
+
+ if items:
+ yield items
+
+ # Save AFTER yielding so a crash re-yields this window (merge dedupes on the primary key)
+ # rather than skipping it. The stack is ascending, so everything before window_to is done.
+ if windows:
+ resumable_source_manager.save_state(GrafanaResumeConfig(annotations_from_ms=window_to))
+
+
+def get_rows(
+ host: str,
+ auth: GrafanaAuth,
+ org_id: Optional[str],
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ team_id: int,
+ resumable_source_manager: ResumableSourceManager[GrafanaResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = GRAFANA_ENDPOINTS[endpoint]
+ base_url = normalize_host(host)
+
+ _check_host(host, team_id)
+
+ headers = _resolve_auth_headers(auth, org_id)
+ # One session reused across every page so urllib3 keeps the connection alive instead of
+ # re-handshaking per request.
+ session = make_tracked_session(retry=NO_ADAPTER_RETRY, redact_values=_redact_values(auth))
+ fetch = _make_fetch(session, headers, logger)
+
+ if config.pagination == "page":
+ yield from _get_paged_rows(fetch, base_url, config, resumable_source_manager, logger)
+ elif config.pagination == "time_window":
+ yield from _get_annotation_rows(
+ fetch,
+ base_url,
+ config,
+ resumable_source_manager,
+ logger,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ else:
+ url = f"{base_url}{config.path}"
+ if config.params:
+ url = f"{url}?{urlencode(config.params)}"
+ items = _extract_items(fetch(url), config.data_key)
+ if items:
+ yield items
+
+
+def grafana_source(
+ host: str,
+ auth: GrafanaAuth,
+ org_id: Optional[str],
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ team_id: int,
+ resumable_source_manager: ResumableSourceManager[GrafanaResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = GRAFANA_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ host=host,
+ auth=auth,
+ org_id=org_id,
+ endpoint=endpoint,
+ logger=logger,
+ team_id=team_id,
+ 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,
+ # Annotations stream oldest-window-first but rows inside each window arrive newest-first,
+ # so the stream isn't globally ascending; "desc" defers the incremental watermark commit
+ # to successful job end instead of corrupting it with per-batch checkpoints.
+ sort_mode="desc" if config.pagination == "time_window" else "asc",
+ partition_count=1,
+ partition_size=1,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/settings.py
new file mode 100644
index 000000000000..bc26c86bb1c7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/settings.py
@@ -0,0 +1,103 @@
+from dataclasses import dataclass, field
+from typing import Literal
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# `/api/search` accepts a limit of up to 5000; the teams / service-accounts search endpoints
+# default `perpage` to 1000. 1000 everywhere keeps individual responses comfortably sized.
+DEFAULT_PAGE_SIZE = 1000
+
+# Verified against a live instance: `/api/annotations` honors limits of at least 1000.
+# The documented default is 100, so anything above that must be confirmed to actually apply —
+# a silently-capped limit would make the window walk think a saturated window was complete.
+ANNOTATIONS_LIMIT = 1000
+
+PaginationStyle = Literal["page", "time_window", "none"]
+
+
+@dataclass
+class GrafanaEndpointConfig:
+ name: str
+ path: str
+ # "page": page-number pagination (`page` + a page-size param); "time_window": the
+ # annotations from/to epoch-ms walk; "none": one request returns the whole collection.
+ pagination: PaginationStyle = "none"
+ page_size_param: str = "limit"
+ # Key holding the rows when the response is wrapped (e.g. {"teams": [...], "totalCount": N});
+ # None when the endpoint returns a bare JSON array.
+ data_key: str | None = None
+ params: dict[str, str] = field(default_factory=dict)
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+
+
+GRAFANA_ENDPOINTS: dict[str, GrafanaEndpointConfig] = {
+ "dashboards": GrafanaEndpointConfig(
+ name="dashboards",
+ path="/api/search",
+ pagination="page",
+ params={"type": "dash-db"},
+ primary_keys=["uid"],
+ ),
+ "folders": GrafanaEndpointConfig(
+ name="folders",
+ path="/api/folders",
+ pagination="page",
+ primary_keys=["uid"],
+ ),
+ "teams": GrafanaEndpointConfig(
+ name="teams",
+ path="/api/teams/search",
+ pagination="page",
+ page_size_param="perpage",
+ data_key="teams",
+ primary_keys=["id"],
+ ),
+ "users": GrafanaEndpointConfig(
+ name="users",
+ path="/api/org/users",
+ primary_keys=["userId"],
+ ),
+ "datasources": GrafanaEndpointConfig(
+ name="datasources",
+ path="/api/datasources",
+ primary_keys=["uid"],
+ ),
+ "service_accounts": GrafanaEndpointConfig(
+ name="service_accounts",
+ path="/api/serviceaccounts/search",
+ pagination="page",
+ page_size_param="perpage",
+ data_key="serviceAccounts",
+ primary_keys=["id"],
+ ),
+ "alert_rules": GrafanaEndpointConfig(
+ name="alert_rules",
+ path="/api/v1/provisioning/alert-rules",
+ primary_keys=["uid"],
+ ),
+ # Restricted to user/API-created annotations (`type=annotation`): alert-state history rows
+ # returned by the same endpoint carry no `id` at all (only a repeating `alertId`), so they
+ # have no usable primary key and are excluded.
+ "annotations": GrafanaEndpointConfig(
+ name="annotations",
+ path="/api/annotations",
+ pagination="time_window",
+ params={"type": "annotation"},
+ primary_keys=["id"],
+ incremental_fields=[
+ {
+ "label": "time",
+ "type": IncrementalFieldType.Integer,
+ "field": "time",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ ),
+}
+
+ENDPOINTS = tuple(GRAFANA_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in GRAFANA_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/source.py
index 779029ce392f..ac02c8ee5ceb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/source.py
@@ -1,19 +1,49 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-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 GrafanaSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.grafana.grafana import (
+ BASIC_AUTH,
+ HOST_NOT_ALLOWED_ERROR,
+ TOKEN_AUTH,
+ GrafanaAuth,
+ GrafanaResumeConfig,
+ get_endpoint_permissions as get_grafana_endpoint_permissions,
+ grafana_source,
+ validate_credentials as validate_grafana_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.grafana.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class GrafanaSource(SimpleSource[GrafanaSourceConfig]):
+class GrafanaSource(ResumableSource[GrafanaSourceConfig, GrafanaResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.GRAFANA
@@ -24,7 +54,179 @@ class GrafanaSource(SimpleSource[GrafanaSourceConfig]):
name=SchemaExternalDataSourceType.GRAFANA,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Grafana",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Grafana instance URL and credentials to pull your Grafana metadata (dashboards, folders, alert rules, annotations, and more) into the PostHog Data warehouse.
+
+Create a service account token under **Administration > Users and access > Service accounts** in your Grafana instance. A Viewer role covers most tables; users, teams, data sources, service accounts, and alert rules need extra read permissions (`users:read`, `teams:read`, `datasources:read`, `serviceaccounts:read`, `alert.provisioning:read`).
+
+Self-hosted Grafana OSS can alternatively authenticate with a username and password. Grafana Cloud only supports service account tokens.""",
iconPath="/static/services/grafana.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/grafana",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="host",
+ label="Instance URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="https://yourstack.grafana.net",
+ secret=False,
+ ),
+ SourceFieldSelectConfig(
+ name="auth_method",
+ label="Authentication method",
+ required=True,
+ defaultValue=TOKEN_AUTH,
+ options=[
+ SourceFieldSelectConfigOption(
+ label="Service account token",
+ value=TOKEN_AUTH,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="token",
+ label="Service account token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="glsa_...",
+ secret=True,
+ ),
+ ],
+ ),
+ ),
+ SourceFieldSelectConfigOption(
+ label="Username & password (self-hosted only)",
+ value=BASIC_AUTH,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="username",
+ label="Username",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="admin",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="password",
+ label="Password",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="org_id",
+ label="Organization ID (optional, multi-org instances only)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="1",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.grafana.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "Missing Grafana service account token": "No Grafana service account token is configured. Update the source configuration and reconnect.",
+ "Missing Grafana username or password": "No Grafana username or password is configured. Update the source configuration and reconnect.",
+ "401 Client Error": "Your Grafana credentials are invalid or expired. Create a new service account token and reconnect.",
+ "403 Client Error": "Your Grafana credentials lack the permissions needed to sync this data. Grant the required read permissions and reconnect.",
+ HOST_NOT_ALLOWED_ERROR: "The Grafana host is not allowed. Please use your instance's public URL.",
+ }
+
+ def _build_auth(self, config: GrafanaSourceConfig) -> GrafanaAuth:
+ return GrafanaAuth(
+ method=config.auth_method.selection,
+ token=config.auth_method.token,
+ username=config.auth_method.username,
+ password=config.auth_method.password,
+ )
+
+ def get_schemas(
+ self,
+ config: GrafanaSourceConfig,
+ 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 == "annotations":
+ return (
+ "User- and API-created annotations. Alert state history entries are not "
+ "included (they have no stable identifier in the Grafana API)"
+ )
+ if endpoint == "dashboards":
+ return "Dashboard metadata from the search API; does not include panel definitions"
+ return None
+
+ # Only annotations expose a server-side time filter (from/to); every other endpoint is
+ # config/metadata with no updated-since cursor, so those are full refresh only. The
+ # incremental annotation walk re-fetches rows at the watermark, so merge (not append) is
+ # the only safe incremental mode.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ description=_description(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: GrafanaSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_grafana_credentials(config.host, self._build_auth(config), config.org_id, team_id, schema_name)
+
+ def get_endpoint_permissions(
+ self, config: GrafanaSourceConfig, team_id: int, endpoints: list[str]
+ ) -> dict[str, str | None]:
+ return get_grafana_endpoint_permissions(
+ config.host, self._build_auth(config), config.org_id, team_id, endpoints
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GrafanaResumeConfig]:
+ return ResumableSourceManager[GrafanaResumeConfig](inputs, GrafanaResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: GrafanaSourceConfig,
+ resumable_source_manager: ResumableSourceManager[GrafanaResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return grafana_source(
+ host=config.host,
+ auth=self._build_auth(config),
+ org_id=config.org_id,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ team_id=inputs.team_id,
+ 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/grafana/tests/test_grafana.py b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/tests/test_grafana.py
new file mode 100644
index 000000000000..2770c9434d01
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/tests/test_grafana.py
@@ -0,0 +1,622 @@
+import json
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.grafana import grafana as grafana_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.grafana.grafana import (
+ ANNOTATIONS_LIMIT,
+ BASIC_AUTH,
+ DEFAULT_PAGE_SIZE,
+ MAX_RESPONSE_BYTES,
+ TOKEN_AUTH,
+ GrafanaAuth,
+ GrafanaAuthError,
+ GrafanaResponseTooLargeError,
+ GrafanaResumeConfig,
+ _extract_items,
+ _permission_error_from_response,
+ _read_body_bounded,
+ _resolve_auth_headers,
+ get_endpoint_permissions,
+ get_rows,
+ grafana_source,
+ normalize_host,
+ validate_credentials,
+)
+
+
+def _response(
+ *,
+ status_code: int = 200,
+ json_data: Any = None,
+ text: str = "",
+ headers: dict[str, str] | None = None,
+ body_chunks: list[bytes] | None = None,
+) -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.ok = 200 <= status_code < 400
+ response.is_redirect = status_code in (302, 303, 307)
+ response.is_permanent_redirect = status_code in (301, 308)
+ response.text = text
+ response.json.return_value = json_data
+ # The source reads bodies via response.iter_content (stream=True), not response.json().
+ if body_chunks is not None:
+ chunks = body_chunks
+ elif json_data is not None:
+ chunks = [json.dumps(json_data).encode()]
+ elif text:
+ chunks = [text.encode()]
+ else:
+ chunks = []
+ response.iter_content.return_value = chunks
+ response.headers = headers or {}
+ # Responses are consumed inside a `with` block, so the mock must behave as a context manager.
+ response.__enter__.return_value = response
+ response.__exit__.return_value = False
+ return response
+
+
+def _token_auth() -> GrafanaAuth:
+ return GrafanaAuth(method=TOKEN_AUTH, token="glsa_secret")
+
+
+def _basic_auth() -> GrafanaAuth:
+ return GrafanaAuth(method=BASIC_AUTH, username="admin", password="hunter2")
+
+
+class FakeResumableManager:
+ def __init__(self, state: GrafanaResumeConfig | None = None):
+ self.state = state
+ self.saved: list[GrafanaResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self.state is not None
+
+ def load_state(self) -> GrafanaResumeConfig | None:
+ return self.state
+
+ def save_state(self, state: GrafanaResumeConfig) -> None:
+ self.saved.append(state)
+ self.state = state
+
+
+def _patch_session(session: mock.MagicMock):
+ return mock.patch.object(grafana_module, "make_tracked_session", return_value=session)
+
+
+def _query(url: str) -> dict[str, str]:
+ return {k: v[0] for k, v in parse_qs(urlparse(url).query).items()}
+
+
+class TestNormalizeHost:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("https://yourstack.grafana.net", "https://yourstack.grafana.net"),
+ ("yourstack.grafana.net", "https://yourstack.grafana.net"),
+ ("https://yourstack.grafana.net/", "https://yourstack.grafana.net"),
+ ("https://yourstack.grafana.net/api", "https://yourstack.grafana.net"),
+ (" yourstack.grafana.net ", "https://yourstack.grafana.net"),
+ ("http://localhost:3000", "http://localhost:3000"),
+ ("http://127.0.0.1:3000", "http://127.0.0.1:3000"),
+ # Plaintext HTTP to a remote host is upgraded to HTTPS so credentials aren't sent in the clear.
+ ("http://grafana.mycompany.com", "https://grafana.mycompany.com"),
+ ("HTTP://grafana.mycompany.com/api", "https://grafana.mycompany.com"),
+ # URL-embedded credentials are stripped so they're never persisted or sent.
+ ("https://admin:[email protected]", "https://grafana.mycompany.com"),
+ ("https://admin:[email protected]:3000/api", "https://grafana.mycompany.com:3000"),
+ ],
+ )
+ def test_normalize_host(self, raw, expected):
+ assert normalize_host(raw) == expected
+
+
+class TestResolveAuthHeaders:
+ def test_token_auth_sends_bearer(self):
+ headers = _resolve_auth_headers(_token_auth())
+ assert headers["Authorization"] == "Bearer glsa_secret"
+
+ def test_basic_auth_sends_base64_credentials(self):
+ headers = _resolve_auth_headers(_basic_auth())
+ # base64("admin:hunter2")
+ assert headers["Authorization"] == "Basic YWRtaW46aHVudGVyMg=="
+
+ def test_org_id_header_set_when_provided(self):
+ headers = _resolve_auth_headers(_token_auth(), org_id="2")
+ assert headers["X-Grafana-Org-Id"] == "2"
+
+ @pytest.mark.parametrize("org_id", [None, "", " "])
+ def test_org_id_header_omitted_when_blank(self, org_id):
+ headers = _resolve_auth_headers(_token_auth(), org_id=org_id)
+ assert "X-Grafana-Org-Id" not in headers
+
+ @pytest.mark.parametrize(
+ "auth",
+ [
+ GrafanaAuth(method=TOKEN_AUTH, token=None),
+ GrafanaAuth(method=BASIC_AUTH, username="admin", password=None),
+ GrafanaAuth(method=BASIC_AUTH, username=None, password="pw"),
+ ],
+ )
+ def test_missing_credentials_raise_auth_error(self, auth):
+ with pytest.raises(GrafanaAuthError):
+ _resolve_auth_headers(auth)
+
+
+class TestExtractItems:
+ @pytest.mark.parametrize(
+ "data, data_key, expected",
+ [
+ ([{"id": 1}, {"id": 2}], None, [{"id": 1}, {"id": 2}]),
+ ([{"id": 1}, "skip-me", 5], None, [{"id": 1}]),
+ ({"teams": [{"id": 1}], "totalCount": 1}, "teams", [{"id": 1}]),
+ ({"totalCount": 0}, "teams", []),
+ (None, None, []),
+ ("nonsense", None, []),
+ ({"teams": "nonsense"}, "teams", []),
+ ],
+ )
+ def test_extract_items(self, data, data_key, expected):
+ assert _extract_items(data, data_key) == expected
+
+
+class TestBoundedResponseReading:
+ def test_streamed_body_over_limit_raises(self):
+ # A host with no (or a lying) Content-Length can still stream an unbounded body; the running
+ # byte total must abort the read rather than buffer it all into the worker.
+ oversized = [b"x" * (1024 * 1024)] * (MAX_RESPONSE_BYTES // (1024 * 1024) + 1)
+ response = _response(body_chunks=oversized)
+ with pytest.raises(GrafanaResponseTooLargeError):
+ _read_body_bounded(response)
+
+ def test_oversized_content_length_rejected_before_reading_body(self):
+ response = _response(headers={"Content-Length": str(MAX_RESPONSE_BYTES + 1)}, body_chunks=[b"ignored"])
+ with pytest.raises(GrafanaResponseTooLargeError):
+ _read_body_bounded(response)
+ response.iter_content.assert_not_called()
+
+ def test_reads_body_within_limit(self):
+ response = _response(body_chunks=[b'{"a"', b": 1}"])
+ assert _read_body_bounded(response) == b'{"a": 1}'
+
+
+class TestPermissionErrorParsing:
+ def test_parses_named_scope_from_403_body(self):
+ response = _response(
+ status_code=403,
+ json_data={
+ "message": "You'll need additional permissions to perform this action. Permissions needed: teams:read"
+ },
+ )
+ assert "teams:read" in _permission_error_from_response(response)
+
+ def test_falls_back_to_generic_message(self):
+ response = _response(status_code=403, json_data={"message": "Access denied"})
+ message = _permission_error_from_response(response)
+ assert "permission" in message.lower()
+ assert "Access denied" not in message
+
+
+class TestValidateCredentials:
+ def test_valid_credentials(self):
+ session = mock.MagicMock()
+ session.get.return_value = _response(status_code=200, json_data={"id": 1, "name": "Main Org."})
+ with _patch_session(session):
+ assert validate_credentials("https://x.grafana.net", _token_auth()) == (True, None)
+ assert session.get.call_args.args[0] == "https://x.grafana.net/api/org"
+ assert session.get.call_args.kwargs["allow_redirects"] is False
+
+ def test_invalid_credentials(self):
+ session = mock.MagicMock()
+ session.get.return_value = _response(status_code=401, json_data={"message": "Unauthorized"})
+ with _patch_session(session):
+ valid, msg = validate_credentials("https://x.grafana.net", _token_auth())
+ assert valid is False
+ assert msg == "Invalid Grafana credentials"
+
+ def test_403_passes_at_source_create_but_fails_for_schema(self):
+ # An under-scoped (but genuine) token must not block source creation — per-endpoint scope
+ # is reported separately — yet must fail a per-schema check.
+ session = mock.MagicMock()
+ session.get.return_value = _response(
+ status_code=403,
+ json_data={"message": "You'll need additional permissions. Permissions needed: orgs:read"},
+ )
+ with _patch_session(session):
+ assert validate_credentials("https://x.grafana.net", _token_auth()) == (True, None)
+
+ valid, msg = validate_credentials("https://x.grafana.net", _token_auth(), schema_name="teams")
+ assert valid is False
+ assert msg is not None and "orgs:read" in msg
+
+ def test_rejects_redirect_response(self):
+ session = mock.MagicMock()
+ session.get.return_value = _response(status_code=302)
+ with _patch_session(session):
+ valid, msg = validate_credentials("https://x.grafana.net", _token_auth())
+ assert valid is False
+ assert msg == grafana_module.HOST_NOT_ALLOWED_ERROR
+
+ def test_blocks_unsafe_host(self):
+ session = mock.MagicMock()
+ with (
+ mock.patch.object(grafana_module, "_is_host_safe", return_value=(False, "internal address")),
+ _patch_session(session),
+ ):
+ valid, msg = validate_credentials("https://10.0.0.1", _token_auth(), team_id=99)
+ assert valid is False
+ assert msg == "internal address"
+ session.get.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "host",
+ ["https://admin:[email protected]", "admin:[email protected]"],
+ )
+ def test_rejects_url_embedded_credentials(self, host):
+ # The host field is stored as non-secret config, so a password embedded in the URL would
+ # be exposed to anyone who can view the source configuration.
+ session = mock.MagicMock()
+ with _patch_session(session):
+ valid, msg = validate_credentials(host, _token_auth())
+ assert valid is False
+ assert msg is not None
+ assert "hunter2" not in msg
+ session.get.assert_not_called()
+
+ def test_missing_token_surfaces_before_probe(self):
+ session = mock.MagicMock()
+ with _patch_session(session):
+ valid, msg = validate_credentials("https://x.grafana.net", GrafanaAuth(method=TOKEN_AUTH, token=None))
+ assert valid is False
+ assert msg == "Missing Grafana service account token"
+ session.get.assert_not_called()
+
+ def test_connection_error_does_not_leak_host(self):
+ raw = "HTTPSConnectionPool(host='203.0.113.10', port=443): Max retries exceeded"
+ session = mock.MagicMock()
+ session.get.side_effect = requests.exceptions.ConnectionError(raw)
+ with _patch_session(session):
+ valid, msg = validate_credentials("https://x.grafana.net", _token_auth())
+ assert valid is False
+ assert msg is not None
+ assert "203.0.113.10" not in msg
+ assert "HTTPSConnectionPool" not in msg
+
+ def test_unexpected_status_does_not_leak_response_body(self):
+ leaked_body = '{"error": "SENTINEL_UPSTREAM_BODY"}'
+ session = mock.MagicMock()
+ session.get.return_value = _response(status_code=404, json_data={"error": "x"}, text=leaked_body)
+ with _patch_session(session):
+ valid, msg = validate_credentials("https://x.grafana.net", _token_auth())
+ assert valid is False
+ assert msg is not None
+ assert "SENTINEL_UPSTREAM_BODY" not in msg
+ assert "404" in msg
+
+
+class TestGetEndpointPermissions:
+ def test_maps_status_codes_to_reasons(self):
+ def get(url, **kwargs):
+ if "/api/teams/search" in url:
+ return _response(status_code=403, json_data={"message": "Permissions needed: teams:read"})
+ return _response(status_code=200, json_data=[])
+
+ session = mock.MagicMock()
+ session.get.side_effect = get
+ with _patch_session(session):
+ results = get_endpoint_permissions("https://x.grafana.net", _token_auth(), None, 1, ["dashboards", "teams"])
+ assert results["dashboards"] is None
+ assert results["teams"] is not None and "teams:read" in results["teams"]
+
+ def test_network_blip_is_not_a_missing_scope(self):
+ session = mock.MagicMock()
+ session.get.side_effect = requests.exceptions.ConnectionError("boom")
+ with _patch_session(session):
+ results = get_endpoint_permissions("https://x.grafana.net", _token_auth(), None, 1, ["dashboards"])
+ assert results == {"dashboards": None}
+
+
+class TestPagedRows:
+ def _run(self, endpoint: str, responses: list[Any], manager: FakeResumableManager | None = None):
+ manager = manager or FakeResumableManager()
+ session = mock.MagicMock()
+ session.get.side_effect = [_response(status_code=200, json_data=r) for r in responses]
+ with (
+ _patch_session(session),
+ mock.patch.object(grafana_module, "_is_host_safe", return_value=(True, None)),
+ ):
+ batches = list(
+ get_rows(
+ host="https://x.grafana.net",
+ auth=_token_auth(),
+ org_id=None,
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ team_id=1,
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ )
+ )
+ return batches, session, manager
+
+ def test_stops_after_partial_page(self):
+ full_page = [{"uid": f"d{i}"} for i in range(DEFAULT_PAGE_SIZE)]
+ partial_page = [{"uid": "last"}]
+ batches, session, manager = self._run("dashboards", [full_page, partial_page])
+
+ assert len(batches) == 2
+ assert batches[1] == partial_page
+ assert session.get.call_count == 2
+ assert _query(session.get.call_args_list[0].args[0])["page"] == "1"
+ assert _query(session.get.call_args_list[1].args[0])["page"] == "2"
+ # Resume state advances only past completed full pages, so a crash re-yields (never skips).
+ assert [s.next_page for s in manager.saved] == [2]
+
+ def test_empty_first_page_yields_nothing(self):
+ batches, session, _ = self._run("folders", [[]])
+ assert batches == []
+ assert session.get.call_count == 1
+
+ def test_dashboards_search_params(self):
+ batches, session, _ = self._run("dashboards", [[{"uid": "d1"}]])
+ query = _query(session.get.call_args.args[0])
+ assert query["type"] == "dash-db"
+ assert query["limit"] == str(DEFAULT_PAGE_SIZE)
+ assert urlparse(session.get.call_args.args[0]).path == "/api/search"
+
+ def test_wrapped_endpoint_extracts_rows(self):
+ batches, session, _ = self._run("teams", [{"teams": [{"id": 7}], "totalCount": 1}])
+ assert batches == [[{"id": 7}]]
+ assert _query(session.get.call_args.args[0])["perpage"] == str(DEFAULT_PAGE_SIZE)
+
+ def test_resumes_from_saved_page(self):
+ manager = FakeResumableManager(GrafanaResumeConfig(next_page=3))
+ batches, session, _ = self._run("dashboards", [[{"uid": "d1"}]], manager=manager)
+ assert _query(session.get.call_args.args[0])["page"] == "3"
+
+ def test_unpaginated_endpoint_single_request(self):
+ batches, session, _ = self._run("datasources", [[{"uid": "ds1"}, {"uid": "ds2"}]])
+ assert batches == [[{"uid": "ds1"}, {"uid": "ds2"}]]
+ assert session.get.call_count == 1
+ assert "page" not in _query(session.get.call_args.args[0])
+
+ def test_stops_at_per_run_page_budget(self):
+ # A host returning full pages forever must not loop without end; the run stops at the budget
+ # and leaves resume state so the next sync continues.
+ full_page = [{"uid": f"d{i}"} for i in range(DEFAULT_PAGE_SIZE)]
+ with mock.patch.object(grafana_module, "MAX_PAGES_PER_RUN", 3):
+ batches, session, manager = self._run("dashboards", [full_page] * 6)
+ assert session.get.call_count == 3
+ assert manager.saved[-1].next_page == 4
+
+ def test_stops_at_wall_clock_deadline_despite_full_pages(self):
+ # The request budget alone still lets a host stall each successful response just under the
+ # socket timeout for days; the walk must stop at the wall-clock deadline and leave resume
+ # state so the next sync continues.
+ full_page = [{"uid": f"d{i}"} for i in range(DEFAULT_PAGE_SIZE)]
+ clock = {"now": 0.0}
+ session = mock.MagicMock()
+
+ def slow_get(url, **kwargs):
+ clock["now"] += grafana_module.MAX_WALK_SECONDS / 2 + 1
+ return _response(status_code=200, json_data=full_page)
+
+ session.get.side_effect = slow_get
+ manager = FakeResumableManager()
+ with (
+ _patch_session(session),
+ mock.patch.object(grafana_module, "_is_host_safe", return_value=(True, None)),
+ mock.patch.object(grafana_module.time, "monotonic", new=lambda: clock["now"]),
+ ):
+ batches = list(
+ get_rows(
+ host="https://x.grafana.net",
+ auth=_token_auth(),
+ org_id=None,
+ endpoint="dashboards",
+ logger=mock.MagicMock(),
+ team_id=1,
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ )
+ )
+ assert session.get.call_count == 2
+ assert len(batches) == 2
+ assert manager.saved[-1].next_page == 3
+
+
+class TestAnnotationRows:
+ def _run(
+ self,
+ get_side_effect,
+ manager: FakeResumableManager | None = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ ):
+ manager = manager or FakeResumableManager()
+ session = mock.MagicMock()
+ session.get.side_effect = get_side_effect
+ with (
+ _patch_session(session),
+ mock.patch.object(grafana_module, "_is_host_safe", return_value=(True, None)),
+ ):
+ batches = list(
+ get_rows(
+ host="https://x.grafana.net",
+ auth=_token_auth(),
+ org_id=None,
+ endpoint="annotations",
+ logger=mock.MagicMock(),
+ team_id=1,
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+ )
+ return batches, session, manager
+
+ def test_single_unsaturated_window(self):
+ rows = [{"id": 1, "time": 100}, {"id": 2, "time": 50}]
+ batches, session, manager = self._run([_response(status_code=200, json_data=rows)])
+
+ assert batches == [rows]
+ assert session.get.call_count == 1
+ query = _query(session.get.call_args.args[0])
+ assert query["type"] == "annotation"
+ assert query["from"] == "0"
+ assert query["limit"] == str(ANNOTATIONS_LIMIT)
+ # Final window completes the walk — no resume state to leave behind.
+ assert manager.saved == []
+
+ def test_saturated_window_bisects_oldest_first(self):
+ saturated = [{"id": i, "time": i} for i in range(ANNOTATIONS_LIMIT)]
+ left_rows = [{"id": 1, "time": 10}]
+ right_rows = [{"id": 2, "time": 20}]
+ calls: list[tuple[int, int]] = []
+
+ def get(url, **kwargs):
+ query = _query(url)
+ window = (int(query["from"]), int(query["to"]))
+ calls.append(window)
+ if len(calls) == 1:
+ return _response(status_code=200, json_data=saturated)
+ return _response(status_code=200, json_data=left_rows if len(calls) == 2 else right_rows)
+
+ batches, _, manager = self._run(get)
+
+ assert batches == [left_rows, right_rows]
+ first_from, first_to = calls[0]
+ mid = (first_from + first_to) // 2
+ # Halves cover the full original window (sharing the mid boundary) and run oldest-first.
+ assert calls[1] == (first_from, mid)
+ assert calls[2] == (mid, first_to)
+ # After the older half yields, the resume boundary advances to its upper bound.
+ assert [s.annotations_from_ms for s in manager.saved] == [mid]
+
+ def test_incremental_watermark_becomes_from_param(self):
+ batches, session, _ = self._run(
+ [_response(status_code=200, json_data=[{"id": 3, "time": 1700000000500}])],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1700000000000,
+ )
+ assert _query(session.get.call_args.args[0])["from"] == "1700000000000"
+
+ def test_full_refresh_ignores_watermark(self):
+ batches, session, _ = self._run(
+ [_response(status_code=200, json_data=[])],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ assert _query(session.get.call_args.args[0])["from"] == "0"
+
+ def test_resumes_from_saved_boundary(self):
+ manager = FakeResumableManager(GrafanaResumeConfig(annotations_from_ms=5_000_000))
+ batches, session, _ = self._run([_response(status_code=200, json_data=[])], manager=manager)
+ assert _query(session.get.call_args.args[0])["from"] == "5000000"
+
+ def test_future_watermark_fetches_nothing(self):
+ # A watermark at/past "now" leaves no window to walk; the sync must no-op, not error.
+ far_future_ms = 4102444800000 # 2100-01-01
+ batches, session, _ = self._run(
+ [],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=far_future_ms,
+ )
+ assert batches == []
+ session.get.assert_not_called()
+
+ def test_stops_at_per_run_request_budget(self):
+ # A host that saturates every window would fan out without end; the run stops at the budget.
+ saturated = [{"id": i, "time": i} for i in range(ANNOTATIONS_LIMIT)]
+
+ def get(url, **kwargs):
+ return _response(status_code=200, json_data=saturated)
+
+ with mock.patch.object(grafana_module, "MAX_ANNOTATION_REQUESTS_PER_RUN", 3):
+ _, session, _ = self._run(get)
+ assert session.get.call_count == 3
+
+ def test_stops_at_wall_clock_deadline_despite_saturated_windows(self):
+ # The request budget alone still lets a host stall each successful (saturated) response just
+ # under the socket timeout for days; the walk must stop at the wall-clock deadline.
+ saturated = [{"id": i, "time": i} for i in range(ANNOTATIONS_LIMIT)]
+ clock = {"now": 0.0}
+
+ def slow_get(url, **kwargs):
+ clock["now"] += grafana_module.MAX_WALK_SECONDS / 2 + 1
+ return _response(status_code=200, json_data=saturated)
+
+ with mock.patch.object(grafana_module.time, "monotonic", new=lambda: clock["now"]):
+ batches, session, _ = self._run(slow_get)
+ assert session.get.call_count == 2
+ assert batches == []
+
+
+class TestGrafanaSourceResponse:
+ @pytest.mark.parametrize(
+ "endpoint, primary_keys, sort_mode",
+ [
+ ("dashboards", ["uid"], "asc"),
+ ("folders", ["uid"], "asc"),
+ ("teams", ["id"], "asc"),
+ ("users", ["userId"], "asc"),
+ ("datasources", ["uid"], "asc"),
+ ("service_accounts", ["id"], "asc"),
+ ("alert_rules", ["uid"], "asc"),
+ ("annotations", ["id"], "desc"),
+ ],
+ )
+ def test_response_shape(self, endpoint, primary_keys, sort_mode):
+ response = grafana_source(
+ host="https://x.grafana.net",
+ auth=_token_auth(),
+ org_id=None,
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ team_id=1,
+ resumable_source_manager=FakeResumableManager(), # type: ignore[arg-type]
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ assert response.sort_mode == sort_mode
+
+
+class TestSessionRetriesDisabled:
+ # A hostile Grafana host can answer 429/503 with a huge Retry-After. urllib3's default adapter
+ # policy honors it and sleeps for hours inside a single session.get, underneath and defeating the
+ # bounded response/walk deadlines. Every session must disable adapter retries so _make_fetch's
+ # own Tenacity policy (bounded jitter/backoff) is the only retry mechanism.
+ @pytest.mark.parametrize(
+ "invoke",
+ [
+ lambda: validate_credentials("https://x.grafana.net", _token_auth()),
+ lambda: get_endpoint_permissions("https://x.grafana.net", _token_auth(), None, 1, ["dashboards"]),
+ lambda: list(
+ get_rows(
+ host="https://x.grafana.net",
+ auth=_token_auth(),
+ org_id=None,
+ endpoint="folders",
+ logger=mock.MagicMock(),
+ team_id=1,
+ resumable_source_manager=FakeResumableManager(), # type: ignore[arg-type]
+ )
+ ),
+ ],
+ )
+ def test_sessions_disable_adapter_retries(self, invoke):
+ session = mock.MagicMock()
+ session.get.return_value = _response(status_code=200, json_data=[])
+ with (
+ mock.patch.object(grafana_module, "make_tracked_session", return_value=session) as patched,
+ mock.patch.object(grafana_module, "_is_host_safe", return_value=(True, None)),
+ ):
+ invoke()
+ assert patched.call_count >= 1
+ for call in patched.call_args_list:
+ retry = call.kwargs.get("retry")
+ assert retry is not None and retry.total == 0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/tests/test_grafana_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/tests/test_grafana_source.py
new file mode 100644
index 000000000000..865dc2d59abc
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/tests/test_grafana_source.py
@@ -0,0 +1,186 @@
+from typing import Literal
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (
+ GrafanaAuthMethodConfig,
+ GrafanaSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.grafana.grafana import (
+ BASIC_AUTH,
+ TOKEN_AUTH,
+ GrafanaAuth,
+ GrafanaResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.grafana.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.grafana.source import GrafanaSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config(selection: Literal["token", "basic"] = "token", **auth_kwargs) -> GrafanaSourceConfig:
+ return GrafanaSourceConfig(
+ host="https://yourstack.grafana.net",
+ auth_method=GrafanaAuthMethodConfig(selection=selection, **auth_kwargs),
+ )
+
+
+class TestGrafanaSource:
+ def setup_method(self):
+ self.source = GrafanaSource()
+ self.team_id = 123
+ self.config = _config(token="glsa_secret")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.GRAFANA
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Grafana"
+ assert config.label == "Grafana"
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/grafana.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/grafana"
+
+ host_field, auth_field, org_id_field = config.fields
+ assert isinstance(host_field, SourceFieldInputConfig)
+ assert host_field.name == "host"
+ assert host_field.secret is False
+
+ assert isinstance(auth_field, SourceFieldSelectConfig)
+ assert auth_field.name == "auth_method"
+ assert [o.value for o in auth_field.options] == [TOKEN_AUTH, BASIC_AUTH]
+
+ assert isinstance(org_id_field, SourceFieldInputConfig)
+ assert org_id_field.name == "org_id"
+ assert org_id_field.required is False
+
+ def test_credential_fields_are_secret(self):
+ auth_field = self.source.get_source_config.fields[1]
+ assert isinstance(auth_field, SourceFieldSelectConfig)
+ secret_field_names = {
+ f.name
+ for option in auth_field.options
+ for f in (option.fields or [])
+ if isinstance(f, SourceFieldInputConfig) and f.secret
+ }
+ assert secret_field_names == {"token", "password"}
+
+ @pytest.mark.parametrize(
+ "expected_key",
+ [
+ "401 Client Error",
+ "403 Client Error",
+ "Missing Grafana service account token",
+ "Missing Grafana username or password",
+ ],
+ )
+ def test_non_retryable_errors(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_returns_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_only_annotations_support_incremental(self):
+ # Only /api/annotations exposes a server-side time filter; everything else must stay
+ # full refresh so a sync never silently skips changed rows.
+ for schema in self.source.get_schemas(self.config, self.team_id):
+ if schema.name == "annotations":
+ assert schema.supports_incremental is True
+ assert [f["field"] for f in schema.incremental_fields] == ["time"]
+ else:
+ assert schema.supports_incremental is False
+ assert schema.incremental_fields == []
+ assert schema.supports_append is False
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["dashboards"])
+ assert [s.name for s in schemas] == ["dashboards"]
+
+ def test_get_schemas_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "selection, auth_kwargs, expected",
+ [
+ (TOKEN_AUTH, {"token": "glsa_x"}, ("glsa_x", None, None)),
+ (BASIC_AUTH, {"username": "admin", "password": "pw"}, (None, "admin", "pw")),
+ ],
+ )
+ def test_build_auth(self, selection, auth_kwargs, expected):
+ auth = self.source._build_auth(_config(selection, **auth_kwargs))
+ assert isinstance(auth, GrafanaAuth)
+ assert auth.method == selection
+ assert (auth.token, auth.username, auth.password) == expected
+
+ @pytest.mark.parametrize("mock_return", [(True, None), (False, "Invalid Grafana credentials")])
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.grafana.source.validate_grafana_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return):
+ mock_validate.return_value = mock_return
+
+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="dashboards")
+
+ assert result == mock_return
+ args = mock_validate.call_args.args
+ assert args[0] == self.config.host
+ assert isinstance(args[1], GrafanaAuth)
+ assert args[2] == self.config.org_id
+ assert args[3] == self.team_id
+ assert args[4] == "dashboards"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.grafana.source.grafana_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_grafana_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "annotations"
+ inputs.team_id = 42
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1784131261208
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_grafana_source.assert_called_once()
+ kwargs = mock_grafana_source.call_args.kwargs
+ assert kwargs["host"] == "https://yourstack.grafana.net"
+ assert isinstance(kwargs["auth"], GrafanaAuth)
+ assert kwargs["endpoint"] == "annotations"
+ assert kwargs["team_id"] == 42
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1784131261208
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.grafana.source.grafana_source")
+ def test_source_for_pipeline_drops_watermark_for_full_refresh(self, mock_grafana_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "annotations"
+ inputs.team_id = 42
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = 1784131261208
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_grafana_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ 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 GrafanaResumeConfig
+
+ def test_canonical_descriptions_cover_endpoints(self):
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(ENDPOINTS)
+
+ def test_documented_tables_render_without_credentials(self):
+ # The public docs endpoint calls get_schemas with a credential-free placeholder config;
+ # any I/O or config access in get_schemas would break the posthog.com table catalog.
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ annotations = next(t for t in tables if t["name"] == "annotations")
+ assert "Incremental" in annotations["sync_methods"]