| 1 | export async function probe(url, clientKey, managementKey) { |
| 2 | const checks = []; |
| 3 | for (const [path, key, expected] of [ |
| 4 | ["/v1/models", null, 401], |
| 5 | ["/v1/models", clientKey, 200], |
| 6 | ["/v0/management/version", managementKey, 200], |
| 7 | ]) { |
| 8 | const started = performance.now(); |
| 9 | let status = null; |
| 10 | let requestId = null; |
| 11 | let ok = false; |
| 12 | try { |
| 13 | const response = await fetch(new URL(path, url), { |
| 14 | headers: key ? { Authorization: `Bearer ${key}` } : {}, |
| 15 | redirect: "manual", |
| 16 | signal: AbortSignal.timeout(10_000), |
| 17 | }); |
| 18 | status = response.status; |
| 19 | const id = response.headers.get("x-request-id"); |
| 20 | if (/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(id ?? "")) requestId = id; |
| 21 | const body = await response.json(); |
| 22 | ok = status === expected && requestId !== null && (expected === 401 |
| 23 | ? typeof body.error === "string" |
| 24 | : path === "/v1/models" |
| 25 | ? body.object === "list" && Array.isArray(body.data) |
| 26 | : typeof body.version === "string"); |
| 27 | } catch {} |
| 28 | checks.push({ path, authenticated: key !== null, status, requestId, ok, |
| 29 | elapsedMs: Math.round(performance.now() - started) }); |
| 30 | } |
| 31 | return checks; |
| 32 | } |
| 33 | |
| 34 | if (import.meta.main) { |
| 35 | const { SUBSTATION_URL: url, SUBSTATION_CLIENT_KEY: clientKey, SUBSTATION_MANAGEMENT_KEY: managementKey } = process.env; |
| 36 | if (!url || !clientKey || !managementKey) throw new Error("Substation monitor configuration is incomplete"); |
| 37 | for (;;) { |
| 38 | const checks = await probe(url, clientKey, managementKey); |
| 39 | const ok = checks.every(check => check.ok); |
| 40 | console.log(JSON.stringify({ event: "substation-probe", level: ok ? "info" : "error", checks })); |
| 41 | if (process.argv.includes("--once")) { |
| 42 | process.exitCode = ok ? 0 : 1; |
| 43 | break; |
| 44 | } |
| 45 | await Bun.sleep(60_000); |
| 46 | } |
| 47 | } |