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): add grafana team members, orgs and dashboard versions tables (#109928)

Tom Owersc92896b0469b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 4863a860f5a0..8d19dba74c9f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -3784,14 +3784,14 @@ Diffed against: <https://developers.gorgias.com/llms.txt>
## Grafana — gaps
-Today (8): `alert_rules`, `annotations`, `dashboards`, `datasources`, `folders`, `service_accounts`, `teams`, `users`
+Today (11): `alert_rules`, `annotations`, `dashboard_versions`, `dashboards`, `datasources`, `folders`, `orgs`, `service_accounts`, `team_members`, `teams`, `users`
Diffed against: <https://raw.githubusercontent.com/grafana/grafana/main/public/openapi3.json>
-- [ ] `teams/{team_id}/members` — team membership join - we sync teams and users but nothing connecting them (high)
-- [ ] `org/users (and orgs/{org_id}/users)` — org membership plus role, the other half of the identity model we already sync (high)
-- [ ] `orgs` — lookup resolving the org_id carried on dashboards, users, teams and datasources (high)
-- [ ] `dashboards/uid/{uid}/versions` — dashboard change history - who changed what and when, the main governance question (medium)
+- [x] `teams/{team_id}/members` — team membership join - we sync teams and users but nothing connecting them (high)
+- [x] `org/users (and orgs/{org_id}/users)` — org membership plus role, the other half of the identity model we already sync (high) — already synced as `users` (`/api/org/users`); `orgs/{org_id}/users` only repeats it per org for server admins
+- [x] `orgs` — lookup resolving the org_id carried on dashboards, users, teams and datasources (high)
+- [x] `dashboards/uid/{uid}/versions` — dashboard change history - who changed what and when, the main governance question (medium)
- [ ] `library-elements` — reusable panels referenced by dashboards; needed to resolve panel definitions that are not inline (medium)
- [ ] `query-history` — records of explored queries, the usage-analytics table for Explore adoption (medium)
- [ ] `access-control/roles and access-control/{resource}/{resourceID}` — RBAC role definitions and resource permissions, resolving who can see which dashboards/folders (medium)
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
index de0b7370cf92..db2e4c4c2b83 100644
--- 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
@@ -24,6 +24,22 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"isDeleted": "Whether the dashboard has been soft-deleted.",
},
},
+ "dashboard_versions": {
+ "description": "Saved versions of each dashboard (one row per dashboard version), with who saved it and when.",
+ "docs_url": "https://grafana.com/docs/grafana/latest/developers/http_api/dashboard_versions/",
+ "columns": {
+ "id": "Internal numeric identifier of the dashboard version.",
+ "uid": "Unique identifier of the dashboard this version belongs to.",
+ "dashboardId": "Internal numeric identifier of the dashboard (deprecated in Grafana in favor of uid).",
+ "version": "Version number, unique within the dashboard.",
+ "parentVersion": "Version this version was saved from; 0 for the initial save.",
+ "restoredFrom": "Version this version was restored from, when it was created by a restore.",
+ "created": "Timestamp when this version was saved.",
+ "createdBy": "Login of the user or service account that saved this version.",
+ "message": "Save message entered for this version.",
+ "data": "Full dashboard JSON model as of this version. Older Grafana releases leave it empty in the version list.",
+ },
+ },
"folders": {
"description": "Dashboard folders in the organization.",
"docs_url": "https://grafana.com/docs/grafana/latest/developers/http_api/folder/",
@@ -45,6 +61,32 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"memberCount": "Number of members in the team.",
},
},
+ "team_members": {
+ "description": "Membership of users in teams (one row per user per team).",
+ "docs_url": "https://grafana.com/docs/grafana/latest/developers/http_api/team/",
+ "columns": {
+ "orgId": "ID of the organization the team belongs to.",
+ "teamId": "Internal numeric identifier of the team.",
+ "teamUID": "Unique identifier of the team.",
+ "userId": "Internal numeric identifier of the member user.",
+ "userUID": "Unique identifier of the member user.",
+ "login": "Login handle of the member user.",
+ "email": "Email address of the member user.",
+ "name": "Display name of the member user.",
+ "avatarUrl": "Relative URL of the member's avatar image.",
+ "labels": "Labels attached to the membership.",
+ "permission": "Permission level of the member in the team (0 = member, 4 = admin).",
+ "auth_module": "Authentication module the membership was synced from, if any.",
+ },
+ },
+ "orgs": {
+ "description": "Organizations on the Grafana instance.",
+ "docs_url": "https://grafana.com/docs/grafana/latest/developers/http_api/org/",
+ "columns": {
+ "id": "Internal numeric identifier of the organization; matches orgId on other tables.",
+ "name": "Name of the organization.",
+ },
+ },
"users": {
"description": "Users with membership in the organization.",
"docs_url": "https://grafana.com/docs/grafana/latest/developers/http_api/org/",
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
index d1dceeed30e0..b37b4cb365ab 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/grafana.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/grafana.py
@@ -3,10 +3,10 @@ import json
import time
import base64
import dataclasses
-from collections.abc import Iterator
+from collections.abc import Generator, Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional
-from urllib.parse import urlencode, urlparse
+from urllib.parse import quote, urlencode, urlparse
import requests
from structlog.types import FilteringBoundLogger
@@ -21,6 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.grafana.settings import (
ANNOTATIONS_LIMIT,
+ DASHBOARD_VERSIONS_PAGE_SIZE,
DEFAULT_PAGE_SIZE,
GRAFANA_ENDPOINTS,
GrafanaEndpointConfig,
@@ -110,10 +111,14 @@ class GrafanaAuth:
password: Optional[str] = dataclasses.field(default=None, repr=False)
[email protected](frozen=True)
class GrafanaResumeConfig:
- # Next page to fetch for page-number endpoints. None for the other pagination styles.
+ # Next page to fetch for page-number endpoints (the parent page for fan-out endpoints). None
+ # for the other pagination styles.
next_page: int | None = None
+ # Fan-out endpoints only: index within the `next_page` parent page of the next parent to fetch
+ # children for.
+ next_parent_index: 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
@@ -299,6 +304,22 @@ def _permission_error_from_response(response: requests.Response) -> str:
return "Your Grafana credentials lack the permissions needed to access this data."
[email protected](frozen=False)
+class _WalkBudget:
+ """Request and wall-clock budget shared by a fan-out walk's parent and child requests."""
+
+ max_requests: int
+ deadline: float
+ requests: int = 0
+
+ def spend(self) -> None:
+ self.requests += 1
+
+ @property
+ def exhausted(self) -> bool:
+ return self.requests >= self.max_requests or time.monotonic() > self.deadline
+
+
def _to_epoch_ms(value: Any) -> int:
"""Coerce an incremental cursor value into epoch milliseconds."""
if isinstance(value, bool):
@@ -428,12 +449,33 @@ 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
+ params["page"] = config.first_page
elif config.pagination == "time_window":
params.update({"from": 0, "to": 1, "limit": 1})
+ elif config.pagination == "continue_token":
+ params["limit"] = 1
return params
+def _probe(
+ session: requests.Session, url: str, headers: dict[str, str], read_body: bool = False
+) -> tuple[str | None, Any]:
+ """Return (reason the credentials can't reach `url`, parsed body when requested and reachable)."""
+ # stream=True so a hostile host can't buffer an unbounded probe body; bodies are only read
+ # (bounded) for a 403's scope message or a fan-out parent's first row.
+ with session.get(url, headers=headers, timeout=10, allow_redirects=False, stream=True) as response:
+ if response.status_code == 401:
+ return "Your Grafana credentials are invalid or expired.", None
+ if response.status_code == 403:
+ return _permission_error_from_response(response), None
+ if read_body and response.status_code == 200:
+ try:
+ return None, _read_json_bounded(response)
+ except ValueError:
+ return None, None
+ return None, None
+
+
def get_endpoint_permissions(
host: str,
auth: GrafanaAuth,
@@ -454,20 +496,31 @@ def get_endpoint_permissions(
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
+ if config.fan_out is None:
+ results[endpoint], _ = _probe(
+ session, f"{base_url}{config.path}?{urlencode(_probe_params(config))}", headers
+ )
+ continue
+ # A child needs its own permission (e.g. `dashboards:write` for versions), so probe it
+ # through the first parent the credentials can list.
+ parent = GRAFANA_ENDPOINTS[config.fan_out.parent]
+ reason, data = _probe(
+ session, f"{base_url}{parent.path}?{urlencode(_probe_params(parent))}", headers, read_body=True
+ )
+ parents = _extract_items(data, parent.data_key)
+ parent_id = parents[0].get(config.fan_out.parent_field) if parents else None
+ if reason is not None or parent_id is None:
+ results[endpoint] = reason
+ continue
+ child_path = config.path.format(parent_id=quote(str(parent_id), safe=""))
+ child_params = _probe_params(config)
+ child_url = (
+ f"{base_url}{child_path}?{urlencode(child_params)}" if child_params else f"{base_url}{child_path}"
+ )
+ results[endpoint], _ = _probe(session, child_url, headers)
except requests.exceptions.RequestException:
results[endpoint] = None
- continue
return results
@@ -479,8 +532,8 @@ def _get_paged_rows(
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:
+ page = resume.next_page if resume is not None and resume.next_page is not None else config.first_page
+ if page > config.first_page:
logger.debug(f"Grafana: resuming {config.name} from page {page}")
pages_this_run = 0
@@ -588,6 +641,110 @@ def _get_annotation_rows(
resumable_source_manager.save_state(GrafanaResumeConfig(annotations_from_ms=window_to))
+def _get_child_rows(
+ fetch: Any,
+ base_url: str,
+ config: GrafanaEndpointConfig,
+ parent_id: Any,
+ budget: _WalkBudget,
+ logger: FilteringBoundLogger,
+) -> Generator[list[dict[str, Any]], None, bool]:
+ """Yield one parent's child rows. Returns False when the budget cut the walk short."""
+ assert config.fan_out is not None
+ child_field = config.fan_out.child_field
+ url = f"{base_url}{config.path.format(parent_id=quote(str(parent_id), safe=''))}"
+ continue_token = ""
+ start = 0
+ while True:
+ if budget.exhausted:
+ return False
+ params: dict[str, Any] = {**config.params}
+ if config.pagination == "continue_token":
+ params["limit"] = DASHBOARD_VERSIONS_PAGE_SIZE
+ if continue_token:
+ params["continueToken"] = continue_token
+ elif start:
+ params["start"] = start
+ budget.spend()
+ try:
+ data = fetch(f"{url}?{urlencode(params)}" if params else url)
+ except requests.HTTPError as e:
+ # The parent was deleted between listing it and fetching its children.
+ if e.response is not None and e.response.status_code == 404:
+ logger.debug(f"Grafana: {config.name} parent {parent_id} not found, skipping")
+ return True
+ raise
+
+ if config.pagination != "continue_token":
+ items = _extract_items(data, config.data_key)
+ has_more = False
+ elif isinstance(data, list):
+ # Grafana releases before unified storage return a bare array and page by `start` offset.
+ items = _extract_items(data, None)
+ has_more = len(items) >= DASHBOARD_VERSIONS_PAGE_SIZE
+ else:
+ items = _extract_items(data, config.data_key)
+ continue_token = str(data.get("continueToken") or "") if isinstance(data, dict) else ""
+ has_more = bool(continue_token)
+
+ if items:
+ yield [{child_field: parent_id, **row} for row in items]
+ if not items or not has_more:
+ return True
+ start += len(items)
+
+
+def _get_fan_out_rows(
+ fetch: Any,
+ base_url: str,
+ config: GrafanaEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[GrafanaResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ assert config.fan_out is not None
+ fan_out = config.fan_out
+ parent = GRAFANA_ENDPOINTS[fan_out.parent]
+
+ 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 parent.first_page
+ start_index = resume.next_parent_index if resume is not None and resume.next_parent_index is not None else 0
+ if page > parent.first_page or start_index > 0:
+ logger.debug(f"Grafana: resuming {config.name} from {fan_out.parent} page {page}, index {start_index}")
+
+ # Shared across parent and child requests: a host returning endless parent pages or child
+ # continue tokens would otherwise occupy this worker without end. The resume state saved
+ # after each parent lets the next sync continue from there.
+ budget = _WalkBudget(max_requests=MAX_PAGES_PER_RUN, deadline=time.monotonic() + MAX_WALK_SECONDS)
+ while not budget.exhausted:
+ params = {**parent.params, parent.page_size_param: DEFAULT_PAGE_SIZE, "page": page}
+ budget.spend()
+ parents = _extract_items(fetch(f"{base_url}{parent.path}?{urlencode(params)}"), parent.data_key)
+
+ cut_short = False
+ for index in range(start_index, len(parents)):
+ parent_id = parents[index].get(fan_out.parent_field)
+ if parent_id is not None:
+ completed = yield from _get_child_rows(fetch, base_url, config, parent_id, budget, logger)
+ if not completed:
+ # Leave the cursor on this parent so the next sync re-fetches its children
+ # (merge dedupes on the primary key) instead of skipping the rest.
+ resumable_source_manager.save_state(GrafanaResumeConfig(next_page=page, next_parent_index=index))
+ cut_short = True
+ break
+ resumable_source_manager.save_state(GrafanaResumeConfig(next_page=page, next_parent_index=index + 1))
+ # Many parents have no children (an empty team), so rows can be far apart.
+ resumable_source_manager.safe_point()
+ if cut_short:
+ break
+ if len(parents) < DEFAULT_PAGE_SIZE:
+ return
+ page += 1
+ start_index = 0
+ resumable_source_manager.save_state(GrafanaResumeConfig(next_page=page, next_parent_index=0))
+
+ logger.warning(f"Grafana: {config.name} hit the per-run request or wall-clock budget; resuming on the next sync")
+
+
def get_rows(
host: str,
auth: GrafanaAuth,
@@ -610,7 +767,9 @@ def get_rows(
session = make_tracked_session(retry=NO_ADAPTER_RETRY, redact_values=_redact_values(auth))
fetch = _make_fetch(session, headers, logger)
- if config.pagination == "page":
+ if config.fan_out is not None:
+ yield from _get_fan_out_rows(fetch, base_url, config, resumable_source_manager, logger)
+ elif 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(
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
index bc26c86bb1c7..3acdcfc53b0e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/settings.py
@@ -12,23 +12,42 @@ DEFAULT_PAGE_SIZE = 1000
# a silently-capped limit would make the window walk think a saturated window was complete.
ANNOTATIONS_LIMIT = 1000
-PaginationStyle = Literal["page", "time_window", "none"]
+# Each dashboard version carries the full dashboard JSON in `data`, so pages stay small to keep a
+# response well under MAX_RESPONSE_BYTES even for large dashboards.
+DASHBOARD_VERSIONS_PAGE_SIZE = 50
+PaginationStyle = Literal["page", "time_window", "continue_token", "none"]
-@dataclass
+
+@dataclass(frozen=True)
+class GrafanaFanOutConfig:
+ # Page-paginated endpoint whose rows drive the fan-out.
+ parent: str
+ # Parent row field substituted into the child path's `{parent_id}` placeholder.
+ parent_field: str
+ # Child row field that holds the parent identifier. Filled from the parent when the response
+ # omits it, so the composite primary key is never null.
+ child_field: str
+
+
+@dataclass(frozen=True)
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.
+ # annotations from/to epoch-ms walk; "continue_token": the dashboard versions walk;
+ # "none": one request returns the whole collection.
pagination: PaginationStyle = "none"
page_size_param: str = "limit"
+ # Number of the first page for "page" pagination; `/api/orgs` counts pages from 0.
+ first_page: int = 1
# 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)
+ fan_out: GrafanaFanOutConfig | None = None
GRAFANA_ENDPOINTS: dict[str, GrafanaEndpointConfig] = {
@@ -39,6 +58,15 @@ GRAFANA_ENDPOINTS: dict[str, GrafanaEndpointConfig] = {
params={"type": "dash-db"},
primary_keys=["uid"],
),
+ # `version` is only unique within a dashboard, and `uid` on a version row is the dashboard's uid.
+ "dashboard_versions": GrafanaEndpointConfig(
+ name="dashboard_versions",
+ path="/api/dashboards/uid/{parent_id}/versions",
+ pagination="continue_token",
+ data_key="versions",
+ fan_out=GrafanaFanOutConfig(parent="dashboards", parent_field="uid", child_field="uid"),
+ primary_keys=["uid", "version"],
+ ),
"folders": GrafanaEndpointConfig(
name="folders",
path="/api/folders",
@@ -53,11 +81,27 @@ GRAFANA_ENDPOINTS: dict[str, GrafanaEndpointConfig] = {
data_key="teams",
primary_keys=["id"],
),
+ "team_members": GrafanaEndpointConfig(
+ name="team_members",
+ path="/api/teams/{parent_id}/members",
+ fan_out=GrafanaFanOutConfig(parent="teams", parent_field="id", child_field="teamId"),
+ primary_keys=["teamId", "userId"],
+ ),
"users": GrafanaEndpointConfig(
name="users",
path="/api/org/users",
primary_keys=["userId"],
),
+ # Lists every organization on the instance, so Grafana only serves it to a server admin
+ # authenticating with basic auth. Service account tokens are org-scoped and get a 403.
+ "orgs": GrafanaEndpointConfig(
+ name="orgs",
+ path="/api/orgs",
+ pagination="page",
+ page_size_param="perpage",
+ first_page=0,
+ primary_keys=["id"],
+ ),
"datasources": GrafanaEndpointConfig(
name="datasources",
path="/api/datasources",
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 1085e2990c1f..7a312dc9f429 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
@@ -54,9 +54,9 @@ class GrafanaSource(ResumableSource[GrafanaSourceConfig, GrafanaResumeConfig]):
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`).
+Create a service account token under **Administration > Users and access > Service accounts** in your Grafana instance. A Viewer role covers most tables; users, teams, team members, data sources, service accounts, and alert rules need extra read permissions (`users:read`, `teams:read`, `teams.permissions:read`, `datasources:read`, `serviceaccounts:read`, `alert.provisioning:read`). Grafana only shows dashboard versions to accounts that can edit the dashboard (`dashboards:write`), such as the Editor role.
-Self-hosted Grafana OSS can alternatively authenticate with a username and password. Grafana Cloud only supports service account tokens.""",
+Self-hosted Grafana OSS can alternatively authenticate with a username and password. Grafana Cloud only supports service account tokens. The organizations table lists every organization on the instance, so it needs a Grafana server admin username and password.""",
iconPath="/static/services/grafana.png",
docsUrl="https://posthog.com/docs/cdp/sources/grafana",
fields=cast(
@@ -179,6 +179,10 @@ Self-hosted Grafana OSS can alternatively authenticate with a username and passw
)
if endpoint == "dashboards":
return "Dashboard metadata from the search API; does not include panel definitions"
+ if endpoint == "dashboard_versions":
+ return "Saved versions of every dashboard. Needs permission to edit dashboards"
+ if endpoint == "orgs":
+ return "Every organization on the instance. Needs a Grafana server admin username and password"
return None
# Only annotations expose a server-side time filter (from/to); every other endpoint is
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
index 2770c9434d01..76556aa9dd0a 100644
--- 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
@@ -11,6 +11,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.grafana im
from products.warehouse_sources.backend.temporal.data_imports.sources.grafana.grafana import (
ANNOTATIONS_LIMIT,
BASIC_AUTH,
+ DASHBOARD_VERSIONS_PAGE_SIZE,
DEFAULT_PAGE_SIZE,
MAX_RESPONSE_BYTES,
TOKEN_AUTH,
@@ -85,6 +86,9 @@ class FakeResumableManager:
self.saved.append(state)
self.state = state
+ def safe_point(self) -> None:
+ pass
+
def _patch_session(session: mock.MagicMock):
return mock.patch.object(grafana_module, "make_tracked_session", return_value=session)
@@ -305,14 +309,29 @@ class TestGetEndpointPermissions:
def get(url, **kwargs):
if "/api/teams/search" in url:
return _response(status_code=403, json_data={"message": "Permissions needed: teams:read"})
+ if "/api/dashboards/uid/d1/versions" in url:
+ return _response(status_code=403, json_data={"message": "Permissions needed: dashboards:write"})
+ if "/api/search" in url:
+ return _response(status_code=200, json_data=[{"uid": "d1"}])
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"])
+ results = get_endpoint_permissions(
+ "https://x.grafana.net",
+ _token_auth(),
+ None,
+ 1,
+ ["dashboards", "teams", "team_members", "dashboard_versions"],
+ )
assert results["dashboards"] is None
assert results["teams"] is not None and "teams:read" in results["teams"]
+ # A fan-out child is unreachable when its parent is, and otherwise needs its own permission,
+ # so it is probed through a real parent id, never through its unresolved `{parent_id}` path.
+ assert results["team_members"] == results["teams"]
+ assert results["dashboard_versions"] is not None and "dashboards:write" in results["dashboard_versions"]
+ assert all("{" not in call.args[0] for call in session.get.call_args_list)
def test_network_blip_is_not_a_missing_scope(self):
session = mock.MagicMock()
@@ -374,6 +393,10 @@ class TestPagedRows:
assert batches == [[{"id": 7}]]
assert _query(session.get.call_args.args[0])["perpage"] == str(DEFAULT_PAGE_SIZE)
+ def test_orgs_pages_from_zero(self):
+ _, session, _ = self._run("orgs", [[{"id": 1}]])
+ assert _query(session.get.call_args.args[0])["page"] == "0"
+
def test_resumes_from_saved_page(self):
manager = FakeResumableManager(GrafanaResumeConfig(next_page=3))
batches, session, _ = self._run("dashboards", [[{"uid": "d1"}]], manager=manager)
@@ -429,6 +452,123 @@ class TestPagedRows:
assert manager.saved[-1].next_page == 3
+class TestFanOutRows:
+ def _run(
+ self,
+ endpoint: str,
+ responses_by_path: dict[str, list[Any]],
+ manager: FakeResumableManager | None = None,
+ ):
+ manager = manager or FakeResumableManager()
+ remaining = {path: list(responses) for path, responses in responses_by_path.items()}
+ session = mock.MagicMock()
+
+ def get(url, **kwargs):
+ response = remaining[urlparse(url).path].pop(0)
+ return response if isinstance(response, mock.MagicMock) else _response(json_data=response)
+
+ session.get.side_effect = get
+ 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]
+ )
+ )
+ urls = [call.args[0] for call in session.get.call_args_list]
+ return batches, urls, manager
+
+ def test_team_members_fan_out_and_fill_missing_team_id(self):
+ batches, urls, _ = self._run(
+ "team_members",
+ {
+ "/api/teams/search": [{"teams": [{"id": 1}, {"id": 2}], "totalCount": 2}],
+ "/api/teams/1/members": [[{"userId": 10}]],
+ "/api/teams/2/members": [[{"userId": 11, "teamId": 2}]],
+ },
+ )
+ assert batches == [[{"teamId": 1, "userId": 10}], [{"teamId": 2, "userId": 11}]]
+ assert [urlparse(url).path for url in urls] == [
+ "/api/teams/search",
+ "/api/teams/1/members",
+ "/api/teams/2/members",
+ ]
+
+ def test_dashboard_versions_follow_continue_token(self):
+ batches, urls, _ = self._run(
+ "dashboard_versions",
+ {
+ "/api/search": [[{"uid": "d1"}]],
+ "/api/dashboards/uid/d1/versions": [
+ {"versions": [{"version": 3}], "continueToken": "tok"},
+ {"versions": [{"version": 2}], "continueToken": ""},
+ ],
+ },
+ )
+ assert batches == [[{"uid": "d1", "version": 3}], [{"uid": "d1", "version": 2}]]
+ assert _query(urls[1]) == {"limit": str(DASHBOARD_VERSIONS_PAGE_SIZE)}
+ assert _query(urls[2]) == {"limit": str(DASHBOARD_VERSIONS_PAGE_SIZE), "continueToken": "tok"}
+
+ def test_dashboard_versions_legacy_array_pages_by_offset(self):
+ full_page = [{"uid": "d1", "version": v} for v in range(DASHBOARD_VERSIONS_PAGE_SIZE)]
+ batches, urls, _ = self._run(
+ "dashboard_versions",
+ {
+ "/api/search": [[{"uid": "d1"}]],
+ "/api/dashboards/uid/d1/versions": [full_page, [{"uid": "d1", "version": 999}]],
+ },
+ )
+ assert len(batches) == 2
+ assert "start" not in _query(urls[1])
+ assert _query(urls[2])["start"] == str(DASHBOARD_VERSIONS_PAGE_SIZE)
+
+ def test_skips_parent_deleted_mid_sync(self):
+ not_found = _response(status_code=404, text="not found")
+ not_found.raise_for_status.side_effect = requests.HTTPError(response=not_found)
+ batches, _, _ = self._run(
+ "dashboard_versions",
+ {
+ "/api/search": [[{"uid": "gone"}, {"uid": "d2"}]],
+ "/api/dashboards/uid/gone/versions": [not_found],
+ "/api/dashboards/uid/d2/versions": [{"versions": [{"version": 1}], "continueToken": ""}],
+ },
+ )
+ assert batches == [[{"uid": "d2", "version": 1}]]
+
+ def test_resumes_from_saved_parent_index(self):
+ manager = FakeResumableManager(GrafanaResumeConfig(next_page=2, next_parent_index=1))
+ batches, urls, _ = self._run(
+ "team_members",
+ {
+ "/api/teams/search": [{"teams": [{"id": 1}, {"id": 2}]}],
+ "/api/teams/2/members": [[{"userId": 11}]],
+ },
+ manager=manager,
+ )
+ assert _query(urls[0])["page"] == "2"
+ assert batches == [[{"teamId": 2, "userId": 11}]]
+
+ def test_budget_cut_leaves_cursor_on_unfinished_parent(self):
+ # A host handing out continue tokens forever must not loop without end, and the parent it
+ # cut short must be re-fetched on the next sync rather than skipped.
+ endless = [{"versions": [{"version": v}], "continueToken": f"t{v}"} for v in range(10)]
+ with mock.patch.object(grafana_module, "MAX_PAGES_PER_RUN", 3):
+ _, urls, manager = self._run(
+ "dashboard_versions",
+ {"/api/search": [[{"uid": "d1"}, {"uid": "d2"}]], "/api/dashboards/uid/d1/versions": endless},
+ )
+ assert len(urls) == 3
+ assert manager.saved[-1] == GrafanaResumeConfig(next_page=1, next_parent_index=0)
+
+
class TestAnnotationRows:
def _run(
self,