Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions src/providers/grafana/runtime.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { describe, expect, it, vi } from "vitest";

interface GrafanaFetchMock {
fetcher: typeof fetch;
urls: string[];
}

function createGrafanaFetchMock(handler: (url: URL) => Response): GrafanaFetchMock {
const urls: string[] = [];
const fetcher = (async (input: RequestInfo | URL): Promise<Response> => {
const url = new URL(input instanceof Request ? input.url : String(input));
urls.push(url.toString());
return handler(url);
}) as typeof fetch;
return { fetcher, urls };
}

function jsonResponse(value: unknown, status = 200): Response {
return new Response(JSON.stringify(value), {
status,
headers: { "content-type": "application/json" },
});
}

describe("Grafana App Platform API version discovery", () => {
it("prefers v1 and caches a successfully discovered version", async () => {
vi.resetModules();
const { grafanaActionHandlers } = await import("./runtime.ts");
let discoveryRequests = 0;
const mock = createGrafanaFetchMock((url) => {
if (url.pathname === "/apis/folder.grafana.app") {
discoveryRequests += 1;
return jsonResponse({
versions: [{ version: "v0alpha1" }, { version: "v1beta1" }, { version: "v1" }],
});
}
return jsonResponse({ items: [], metadata: {} });
});
const context = {
baseUrl: "https://grafana-v1.example",
apiKey: "test-token",
fetcher: mock.fetcher,
};

await grafanaActionHandlers.list_folders({}, context);
await grafanaActionHandlers.list_folders({}, context);

expect(discoveryRequests).toBe(1);
expect(mock.urls).toEqual([
"https://grafana-v1.example/apis/folder.grafana.app",
"https://grafana-v1.example/apis/folder.grafana.app/v1/namespaces/default/folders",
"https://grafana-v1.example/apis/folder.grafana.app/v1/namespaces/default/folders",
]);
});

it("retries discovery after a failure instead of caching the v1 fallback", async () => {
vi.resetModules();
const { grafanaActionHandlers } = await import("./runtime.ts");
let discoveryRequests = 0;
const mock = createGrafanaFetchMock((url) => {
if (url.pathname === "/apis/folder.grafana.app") {
discoveryRequests += 1;
if (discoveryRequests === 1) {
return jsonResponse({ message: "temporary failure" }, 500);
}
return jsonResponse({ versions: [{ version: "v1beta1" }] });
}
if (url.pathname.includes("/v1beta1/")) {
return jsonResponse({ items: [], metadata: {} });
}
return jsonResponse({ message: "unsupported version" }, 404);
});
const context = {
baseUrl: "https://grafana-v1beta1.example",
apiKey: "test-token",
fetcher: mock.fetcher,
};

await expect(grafanaActionHandlers.list_folders({}, context)).rejects.toThrow("unsupported version");
await expect(grafanaActionHandlers.list_folders({}, context)).resolves.toMatchObject({ folders: [] });

expect(discoveryRequests).toBe(2);
expect(mock.urls).toEqual([
"https://grafana-v1beta1.example/apis/folder.grafana.app",
"https://grafana-v1beta1.example/apis/folder.grafana.app/v1/namespaces/default/folders",
"https://grafana-v1beta1.example/apis/folder.grafana.app",
"https://grafana-v1beta1.example/apis/folder.grafana.app/v1beta1/namespaces/default/folders",
]);
});
});
93 changes: 81 additions & 12 deletions src/providers/grafana/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,28 @@ import {
const defaultNamespace = "default";
const grafanaDefaultRequestTimeoutMs = 30_000;
const folderParentAnnotation = "grafana.app/folder";
const grafanaDefaultApiVersion = "v1";
const grafanaApiVersionCacheMaxEntries = 256;

type GrafanaAppResource = "folders" | "dashboards";

const grafanaAppApiGroups: Record<GrafanaAppResource, string> = {
folders: "folder.grafana.app",
dashboards: "dashboard.grafana.app",
};

// Grafana's App Platform API groups are versioned and the set of served versions
// differs per Grafana release, e.g.
// Grafana 12.1 dashboard.grafana.app -> v1beta1, v0alpha1, v2alpha1
// Grafana 12.4 dashboard.grafana.app -> v1beta1, v0alpha1, v2beta1, v2alpha1
// Grafana 13.0 dashboard.grafana.app -> v1, ...
// Requesting a version the server does not serve returns a Kubernetes-style 404
// ("the server could not find the requested resource"), so the version has to be
// discovered instead of hardcoded. Only versions from the v1 lineage are listed:
// the v2 lineage uses a different resource schema and is not interchangeable here.
const grafanaApiVersionPreference: readonly string[] = [grafanaDefaultApiVersion, "v1beta1", "v0alpha1"];

const grafanaApiVersionCache = new Map<string, string>();
const grafanaApiMetadataUrl = "https://grafana.com/docs/grafana/latest/developers/http_api/auth/#service-account-token";

type GrafanaRequestPhase = "validate" | "execute";
Expand Down Expand Up @@ -134,7 +156,7 @@ async function executeListFolders(input: Record<string, unknown>, context: Grafa
});

const payload = await grafanaRequestJson(
apiPath(input, "folders"),
await apiPath(input, "folders", { ...context, phase: "execute" }),
{ method: "GET", query },
{
...context,
Expand All @@ -153,7 +175,7 @@ async function executeListFolders(input: Record<string, unknown>, context: Grafa

async function executeGetFolder(input: Record<string, unknown>, context: GrafanaContext): Promise<unknown> {
const payload = await grafanaRequestJson(
`${apiPath(input, "folders")}/${encodePathSegment(requireString(input.uid, "uid"))}`,
`${await apiPath(input, "folders", { ...context, phase: "execute" })}/${encodePathSegment(requireString(input.uid, "uid"))}`,
{ method: "GET" },
{ ...context, phase: "execute" },
);
Expand All @@ -162,7 +184,7 @@ async function executeGetFolder(input: Record<string, unknown>, context: Grafana

async function executeCreateFolder(input: Record<string, unknown>, context: GrafanaContext): Promise<unknown> {
const payload = await grafanaRequestJson(
apiPath(input, "folders"),
await apiPath(input, "folders", { ...context, phase: "execute" }),
{ method: "POST", body: folderRequestBody(input) },
{ ...context, phase: "execute" },
);
Expand All @@ -172,7 +194,7 @@ async function executeCreateFolder(input: Record<string, unknown>, context: Graf
async function executeUpdateFolder(input: Record<string, unknown>, context: GrafanaContext): Promise<unknown> {
const uid = requireString(input.uid, "uid");
const payload = await grafanaRequestJson(
`${apiPath(input, "folders")}/${encodePathSegment(uid)}`,
`${await apiPath(input, "folders", { ...context, phase: "execute" })}/${encodePathSegment(uid)}`,
{ method: "PUT", body: folderRequestBody(input, uid) },
{ ...context, phase: "execute" },
);
Expand All @@ -181,7 +203,7 @@ async function executeUpdateFolder(input: Record<string, unknown>, context: Graf

async function executeDeleteFolder(input: Record<string, unknown>, context: GrafanaContext): Promise<unknown> {
const payload = await grafanaRequestJson(
`${apiPath(input, "folders")}/${encodePathSegment(requireString(input.uid, "uid"))}`,
`${await apiPath(input, "folders", { ...context, phase: "execute" })}/${encodePathSegment(requireString(input.uid, "uid"))}`,
{ method: "DELETE" },
{ ...context, phase: "execute" },
);
Expand Down Expand Up @@ -222,7 +244,7 @@ async function executeSearchDashboards(input: Record<string, unknown>, context:

async function executeGetDashboard(input: Record<string, unknown>, context: GrafanaContext): Promise<unknown> {
const payload = await grafanaRequestJson(
`${apiPath(input, "dashboards")}/${encodePathSegment(requireString(input.uid, "uid"))}`,
`${await apiPath(input, "dashboards", { ...context, phase: "execute" })}/${encodePathSegment(requireString(input.uid, "uid"))}`,
{ method: "GET" },
{ ...context, phase: "execute" },
);
Expand All @@ -231,7 +253,7 @@ async function executeGetDashboard(input: Record<string, unknown>, context: Graf

async function executeCreateDashboard(input: Record<string, unknown>, context: GrafanaContext): Promise<unknown> {
const payload = await grafanaRequestJson(
apiPath(input, "dashboards"),
await apiPath(input, "dashboards", { ...context, phase: "execute" }),
{ method: "POST", body: dashboardRequestBody(input) },
{ ...context, phase: "execute" },
);
Expand All @@ -241,7 +263,7 @@ async function executeCreateDashboard(input: Record<string, unknown>, context: G
async function executeUpdateDashboard(input: Record<string, unknown>, context: GrafanaContext): Promise<unknown> {
const uid = requireString(input.uid, "uid");
const payload = await grafanaRequestJson(
`${apiPath(input, "dashboards")}/${encodePathSegment(uid)}`,
`${await apiPath(input, "dashboards", { ...context, phase: "execute" })}/${encodePathSegment(uid)}`,
{ method: "PUT", body: dashboardRequestBody(input, uid) },
{ ...context, phase: "execute" },
);
Expand All @@ -250,7 +272,7 @@ async function executeUpdateDashboard(input: Record<string, unknown>, context: G

async function executeDeleteDashboard(input: Record<string, unknown>, context: GrafanaContext): Promise<unknown> {
const payload = await grafanaRequestJson(
`${apiPath(input, "dashboards")}/${encodePathSegment(requireString(input.uid, "uid"))}`,
`${await apiPath(input, "dashboards", { ...context, phase: "execute" })}/${encodePathSegment(requireString(input.uid, "uid"))}`,
{ method: "DELETE" },
{ ...context, phase: "execute" },
);
Expand Down Expand Up @@ -427,10 +449,57 @@ function extractGrafanaErrorMessage(payload: unknown): string | undefined {
);
}

function apiPath(input: Record<string, unknown>, resource: "folders" | "dashboards"): string {
async function resolveGrafanaApiVersion(
group: string,
context: GrafanaContext & { phase: GrafanaRequestPhase },
): Promise<string> {
const cacheKey = `${context.baseUrl}|${group}`;
const cached = grafanaApiVersionCache.get(cacheKey);
if (cached !== undefined) {
return cached;
}
Comment on lines +452 to +460

try {
const payload = await grafanaRequestJson(`/apis/${group}`, { method: "GET" }, context);
const record = optionalRecord(payload) ?? {};
const served = new Set(
objectArrayOrEmpty(record.versions)
.map((entry) => optionalString(entry.version))
.filter((version): version is string => version !== undefined),
);
const match = grafanaApiVersionPreference.find((version) => served.has(version));
if (match !== undefined) {
cacheGrafanaApiVersion(cacheKey, match);
return match;
}
} catch {
// Discovery is best-effort. Falling back to the newest known version keeps the
// previous behaviour for servers that do not expose the discovery endpoint.
}

return grafanaDefaultApiVersion;
}

function cacheGrafanaApiVersion(cacheKey: string, version: string): void {
grafanaApiVersionCache.delete(cacheKey);
if (grafanaApiVersionCache.size >= grafanaApiVersionCacheMaxEntries) {
const oldestKey = grafanaApiVersionCache.keys().next().value;
if (oldestKey !== undefined) {
grafanaApiVersionCache.delete(oldestKey);
}
}
grafanaApiVersionCache.set(cacheKey, version);
}

async function apiPath(
input: Record<string, unknown>,
resource: GrafanaAppResource,
context: GrafanaContext & { phase: GrafanaRequestPhase },
): Promise<string> {
const namespace = optionalString(input.namespace) ?? defaultNamespace;
const group = resource === "folders" ? "folder.grafana.app/v1" : "dashboard.grafana.app/v1";
return `/apis/${group}/namespaces/${encodePathSegment(namespace)}/${resource}`;
const group = grafanaAppApiGroups[resource];
const version = await resolveGrafanaApiVersion(group, context);
return `/apis/${group}/${version}/namespaces/${encodePathSegment(namespace)}/${resource}`;
}

function folderRequestBody(input: Record<string, unknown>, fallbackUid?: string): Record<string, unknown> {
Expand Down
Loading