feat(status): add system status footer powered by Uptime Kuma

Replace the static "All systems normal" indicator in the Footer with a dynamic SystemStatus component backed by an internal API route and a server-side fetch of Uptime Kuma's public status/heartbeat endpoints. The light is rendered on first paint (correct without JS) and refreshed every minute, pausing when the tab is hidden.

- src/lib/status.ts: fetches and reduces Uptime Kuma data to one state
  (up/degraded/down/maintenance/unknown), with in-process caching and stale detection
- src/pages/api/status.ts: exposes a small snapshot to the browser, avoiding CORS issues and the ~200 KB heartbeat payload
- src/components/SystemStatus.astro: renders the light server-side and keeps it current client-side
- README.md: documents the feature and optional environment variables (STATUS_PAGE_URL, STATUS_PAGE_SLUG, STATUS_WATCH_GROUPS, STATUS_CACHE_TTL_SECONDS, STATUS_TIMEOUT_SECONDS, STATUS_STALE_AFTER_SECONDS)
- Tests for the summarization logic covering outage, degraded, and maintenance scenarios
This commit is contained in:
spaghet committed 2026-11-05 16:51:46 -05:00
1 parent ab6cd7c162
commit 480259a4eb
6 files changed
+686 -8

No files matched your search

+28
View File
@@ -21,6 +21,34 @@ This website is built using Astro with the following key components:
- **Projects**: Showcasing my various projects and contributions
- **Work Experience**: Professional background and career history
- **Legal**: Privacy policy and terms of service
- **System status**: The footer light is powered by Uptime Kuma (see below)
## System Status Footer
The "All systems normal" light in the footer reflects the public Uptime Kuma
status page at [uptime.spaghet.io/status/public](https://uptime.spaghet.io/status/public).
- `src/lib/status.ts` fetches Uptime Kuma's public status-page and heartbeat
APIs server-side, reduces them to one state (`up`, `degraded`, `down`,
`maintenance`, `unknown`) and caches the result in-process.
- `src/pages/api/status.ts` exposes that small snapshot to the browser. Uptime
Kuma sends no CORS headers outside dev mode and its heartbeat payload is
~200 KB, so the browser never talks to it directly.
- `src/components/SystemStatus.astro` renders the light server-side (correct on
first paint and with JS disabled) and then refreshes it every minute, pausing
while the tab is hidden.
Optional environment variables (all have working defaults):
| Variable | Default | Purpose |
| --- | --- | --- |
| `STATUS_PAGE_URL` | `https://uptime.spaghet.io` | Uptime Kuma origin |
| `STATUS_PAGE_SLUG` | `public` | Status page slug |
| `STATUS_WATCH_GROUPS` | *(all groups)* | Comma-separated group names that drive the light, e.g. `"Critical Services,Database Services"` |
| `STATUS_CACHE_TTL_SECONDS` | `60` | Server-side cache lifetime |
| `STATUS_TIMEOUT_SECONDS` | `4` | Upstream request timeout |
| `STATUS_STALE_AFTER_SECONDS` | `900` | Treat the light as unknown once beats stop arriving |
## Technologies Used
+7 -8
View File
@@ -1,7 +1,12 @@
---
import { SITE, SOCIALS } from "@consts"
import Container from "@components/Container.astro"
// Remove unused storage import
import SystemStatus from "@components/SystemStatus.astro"
import { getSystemStatus } from "@lib/status"
// Rendered server-side so the light is correct in the first paint (and with JS
// off); SystemStatus then keeps it current from /api/status.
const statusSnapshot = await getSystemStatus()
---
<footer class="relative bg-white dark:bg-black">
@@ -31,13 +36,7 @@ import Container from "@components/Container.astro"
{SITE.TITLE}
</a>
</div>
<div class="flex gap-2 justify-center sm:justify-end items-center">
<span class="relative flex h-3 w-3">
<span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-300"></span>
<span class="relative inline-flex rounded-full h-3 w-3 bg-green-500"></span>
</span>
All systems normal
</div>
<SystemStatus snapshot={statusSnapshot} />
</div>
</Container>
</section>
+172
View File
@@ -0,0 +1,172 @@
---
import type { StatusSnapshot } from "@lib/status"
interface Props {
snapshot: StatusSnapshot
}
const { snapshot } = Astro.props
// Refresh cadence for the browser. The server already caches Uptime Kuma for a
// minute, so polling faster than that only adds requests without new signal.
const REFRESH_MS = 60_000
function details(s: StatusSnapshot): string {
const { total, up, down, pending, maintenance } = s.summary
if (s.state === "unknown") {
return s.reason === "stale"
? "Uptime Kuma has not reported recently"
: "Status could not be read"
}
const parts = [`${up}/${total} monitors up`]
if (down > 0) parts.push(`${down} down`)
if (pending > 0) parts.push(`${pending} pending`)
if (maintenance > 0) parts.push(`${maintenance} in maintenance`)
if (s.incidents > 0) parts.push(`${s.incidents} incident${s.incidents === 1 ? "" : "s"}`)
return parts.join(", ")
}
const state = snapshot.state
const label = snapshot.label
const detailsText = details(snapshot)
---
<a
href={snapshot.statusPageUrl}
target="_blank"
rel="noopener noreferrer"
class="status group flex gap-2 justify-center sm:justify-end items-center hover:text-black dark:hover:text-white"
data-status-root
data-status={state}
data-refresh-ms={REFRESH_MS}
data-checked-at={snapshot.checkedAt}
aria-label={`System status: ${label}. ${detailsText}. Open status page`}
title={detailsText}
>
<span class="relative flex h-3 w-3" aria-hidden="true">
<span class="ping animate-ping absolute inline-flex h-full w-full rounded-full"></span>
<span class="core relative inline-flex rounded-full h-3 w-3"></span>
</span>
<span data-status-label>{label}</span>
</a>
<style>
/* Colours hang off data-status so the client script only has to flip one
attribute; Tailwind cannot generate classes built at runtime anyway. */
.status {
transition: color 300ms ease-in-out;
}
.core {
background-color: #22c55e;
transition: background-color 300ms ease-in-out;
}
.ping {
background-color: #86efac;
}
[data-status="degraded"] .core {
background-color: #f59e0b;
}
[data-status="degraded"] .ping {
background-color: #fcd34d;
}
[data-status="down"] .core {
background-color: var(--color-marinara);
}
[data-status="down"] .ping {
background-color: var(--color-spaghetti-dark-red);
}
[data-status="maintenance"] .core {
background-color: #4962bd;
}
[data-status="maintenance"] .ping {
background-color: #93a5e0;
}
[data-status="unknown"] .core {
background-color: #9ca3af;
}
[data-status="unknown"] .ping {
display: none;
}
@media (prefers-reduced-motion: reduce) {
.ping {
display: none;
}
}
</style>
<script>
const root = document.querySelector<HTMLElement>("[data-status-root]")
const labelNode = root?.querySelector<HTMLElement>("[data-status-label]")
if (root && labelNode) {
const refreshMs = Number(root.dataset.refreshMs) || 60_000
let timer: ReturnType<typeof setInterval> | null = null
const render = (snapshot: {
state: string
label: string
summary?: { up: number; total: number }
}) => {
root.dataset.status = snapshot.state
labelNode.textContent = snapshot.label
const details = snapshot.summary
? `${snapshot.summary.up}/${snapshot.summary.total} monitors up`
: ""
root.title = details || snapshot.label
root.setAttribute(
"aria-label",
`System status: ${snapshot.label}. ${details}. Open status page`
)
}
const refresh = async () => {
try {
const response = await fetch("/api/status", {
headers: { accept: "application/json" },
cache: "default",
})
if (!response.ok) throw new Error(`status endpoint returned ${response.status}`)
render(await response.json())
} catch {
// The site's own route failed (or Uptime Kuma is unreachable). Say so
// rather than leaving a confident green light on a dead stack.
root.dataset.status = "unknown"
labelNode.textContent = "Status unavailable"
}
}
const start = () => {
if (timer !== null) return
timer = setInterval(refresh, refreshMs)
}
const stop = () => {
if (timer === null) return
clearInterval(timer)
timer = null
}
// A background tab should not burn requests; refresh the moment it is seen.
document.addEventListener("visibilitychange", () => {
if (document.hidden) stop()
else {
void refresh()
start()
}
})
// No immediate fetch when the server just rendered the state. Prerendered
// routes (blog posts, legal pages) bake the build-time snapshot, so compare
// timestamps and refresh straight away if what we were handed is old.
const checkedAt = Date.parse(root.dataset.checkedAt ?? "")
if (Number.isNaN(checkedAt) || Date.now() - checkedAt > refreshMs) void refresh()
start()
}
</script>
+160
View File
@@ -0,0 +1,160 @@
// src/lib/__tests__/status.test.ts
import { describe, it, expect } from "vitest"
import { parseBeatTime, summarize, monitorsInGroups, BEAT, type KumaHeartbeat } from "@lib/status"
const NOW = Date.parse("2026-11-05T21:00:00.000Z")
function beat(status: number, minutesAgo = 0): KumaHeartbeat {
const time = new Date(NOW - minutesAgo * 60_000)
const pad = (n: number, width = 2) => String(n).padStart(width, "0")
// Kuma emits naive UTC strings with millisecond precision.
const stamp =
`${time.getUTCFullYear()}-${pad(time.getUTCMonth() + 1)}-${pad(time.getUTCDate())} ` +
`${pad(time.getUTCHours())}:${pad(time.getUTCMinutes())}:${pad(time.getUTCSeconds())}` +
`.${pad(time.getUTCMilliseconds(), 3)}`
return { status, time: stamp, ping: 12 }
}
function list(...beats: KumaHeartbeat[]) {
return beats
}
describe("parseBeatTime", () => {
it("should read Kuma's naive timestamp as UTC, not local time", () => {
expect(parseBeatTime("2026-11-05 21:00:00.000")).toBe(NOW)
})
it("should accept an already-offset timestamp without double-applying UTC", () => {
expect(parseBeatTime("2026-11-05T21:00:00.000Z")).toBe(NOW)
})
it("should return null for a malformed timestamp", () => {
expect(parseBeatTime("not a time")).toBeNull()
expect(parseBeatTime("")).toBeNull()
})
})
describe("monitorsInGroups", () => {
const groups = [
{ name: "Critical Services", monitorList: [{ id: 75 }, { id: 36 }] },
{ name: "Game Servers", monitorList: [{ id: 89 }] },
]
it("should return null when no narrowing is configured", () => {
expect(monitorsInGroups(groups, [])).toBeNull()
})
it("should collect the monitor ids of the named groups, case-insensitively", () => {
const ids = monitorsInGroups(groups, ["critical services"])
expect(ids).not.toBeNull()
expect([...ids!].sort()).toEqual(["36", "75"])
})
it("should return an empty set when no group matches, so the caller reports unknown", () => {
expect(monitorsInGroups(groups, ["Nonexistent"])).toEqual(new Set<string>())
})
it("should tolerate a missing group list", () => {
expect(monitorsInGroups(null, ["Critical Services"])).toEqual(new Set<string>())
})
})
describe("summarize", () => {
it("should report all systems normal when every monitor's last beat is up", () => {
const snapshot = summarize({
now: NOW,
heartbeatList: {
"1": list(beat(BEAT.UP, 3), beat(BEAT.UP, 2), beat(BEAT.UP, 1)),
"2": list(beat(BEAT.UP, 1)),
},
})
expect(snapshot.state).toBe("up")
expect(snapshot.label).toBe("All systems normal")
expect(snapshot.summary).toEqual({ total: 2, up: 2, down: 0, pending: 0, maintenance: 0 })
})
it("should judge only the newest beat of each monitor", () => {
const snapshot = summarize({
now: NOW,
heartbeatList: {
// Recovered: an older down must not keep the footer red.
"1": list(beat(BEAT.DOWN, 9), beat(BEAT.UP, 1)),
// Regressed: an older up must not keep the footer green.
"2": list(beat(BEAT.UP, 9), beat(BEAT.DOWN, 1)),
},
})
expect(snapshot.state).toBe("degraded")
expect(snapshot.label).toBe("Partial outage")
expect(snapshot.summary).toEqual({ total: 2, up: 1, down: 1, pending: 0, maintenance: 0 })
})
it("should report a major outage when no monitor is up", () => {
const snapshot = summarize({
now: NOW,
heartbeatList: { "1": list(beat(BEAT.DOWN, 1)), "2": list(beat(BEAT.DOWN, 1)) },
})
expect(snapshot.state).toBe("down")
expect(snapshot.label).toBe("Major outage")
})
it("should treat a pending monitor as degraded rather than normal", () => {
const snapshot = summarize({
now: NOW,
heartbeatList: { "1": list(beat(BEAT.UP, 1)), "2": list(beat(BEAT.PENDING, 1)) },
})
expect(snapshot.state).toBe("degraded")
})
it("should surface maintenance ahead of outages, matching Uptime Kuma", () => {
const snapshot = summarize({
now: NOW,
heartbeatList: { "1": list(beat(BEAT.DOWN, 1)), "2": list(beat(BEAT.MAINTENANCE, 1)) },
})
expect(snapshot.state).toBe("maintenance")
expect(snapshot.label).toBe("Under maintenance")
})
it("should degrade the label when an incident is open even if every beat is up", () => {
const snapshot = summarize({
now: NOW,
incidents: [{ id: 1, name: "Plex down", is_public: true }],
heartbeatList: { "1": list(beat(BEAT.UP, 1)) },
})
expect(snapshot.state).toBe("degraded")
expect(snapshot.incidents).toBe(1)
})
it("should report unknown when the status page exposes no monitors", () => {
const snapshot = summarize({ now: NOW, heartbeatList: {} })
expect(snapshot.state).toBe("unknown")
expect(snapshot.reason).toBe("no-monitors")
expect(snapshot.label).toBe("Status unavailable")
})
it("should report unknown when the newest beat is older than the stale window", () => {
const snapshot = summarize({
now: NOW,
staleAfterMs: 900_000,
heartbeatList: { "1": list(beat(BEAT.UP, 20)) },
})
expect(snapshot.state).toBe("unknown")
expect(snapshot.reason).toBe("stale")
})
it("should tolerate a missing heartbeatList without throwing", () => {
const snapshot = summarize({ now: NOW, heartbeatList: null })
expect(snapshot.state).toBe("unknown")
expect(snapshot.summary.total).toBe(0)
})
it("should expose the newest beat time and the status page link for the footer", () => {
const snapshot = summarize({
now: NOW,
statusPageUrl: "https://uptime.spaghet.io/status/public",
heartbeatList: { "1": list(beat(BEAT.UP, 5)), "2": list(beat(BEAT.UP, 1)) },
})
expect(snapshot.lastBeatAt).toBe(new Date(NOW - 60_000).toISOString())
expect(snapshot.checkedAt).toBe(new Date(NOW).toISOString())
expect(snapshot.statusPageUrl).toBe("https://uptime.spaghet.io/status/public")
})
})
+295
View File
@@ -0,0 +1,295 @@
/**
* Reads the public Uptime Kuma status page (https://uptime.spaghet.io/status/public)
* and reduces it to the single "is everything fine?" signal the footer shows.
*
* Two endpoints matter:
* GET /api/status-page/:slug -> config, incidents, monitor groups (~5 KB)
* GET /api/status-page/heartbeat/:slug -> last 100 beats per monitor (~200 KB)
*
* The heartbeat payload is far too heavy to hand to the browser, and Uptime Kuma
* only sends CORS headers in dev mode, so everything here runs server-side and the
* browser talks to our own /api/status route instead. Results are cached in-process
* (Uptime Kuma caches the heartbeat route for 1 minute anyway) and concurrent
* requests share one in-flight fetch so a busy page never stampedes the Kuma box.
*/
/** Beat statuses as defined by Uptime Kuma's `src/util.ts`. */
export const BEAT = {
DOWN: 0,
UP: 1,
PENDING: 2,
MAINTENANCE: 3,
} as const
export type SystemState = "up" | "degraded" | "down" | "maintenance" | "unknown"
export type UnknownReason = "no-monitors" | "stale" | "http-error" | "fetch-failed"
export interface KumaHeartbeat {
status: number
/** Naive server timestamp, e.g. "2026-11-05 21:05:09.655" (UTC). */
time: string
ping?: number | null
msg?: string
}
export interface StatusSnapshot {
state: SystemState
/** Footer copy, e.g. "All systems normal". */
label: string
summary: {
total: number
up: number
down: number
pending: number
maintenance: number
}
incidents: number
/** ISO timestamp of when the upstream data was read. */
checkedAt: string
/** Newest beat timestamp seen, ISO. Useful for spotting a paused Kuma. */
lastBeatAt: string | null
reason?: UnknownReason
statusPageUrl: string
}
const LABELS: Record<SystemState, string> = {
up: "All systems normal",
degraded: "Partial outage",
down: "Major outage",
maintenance: "Under maintenance",
unknown: "Status unavailable",
}
interface StatusConfig {
base: string
slug: string
pageUrl: string
apiUrl: string
heartbeatUrl: string
cacheTtlMs: number
timeoutMs: number
staleAfterMs: number
/** Group names that count toward the footer light. Empty = every group. */
watchGroups: string[]
}
function envInt(name: string, fallback: number): number {
const raw = process.env[name]
if (raw === undefined || raw === "") return fallback
const parsed = Number.parseInt(raw, 10)
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback
}
export function statusConfig(): StatusConfig {
const base = (process.env.STATUS_PAGE_URL ?? "https://uptime.spaghet.io").replace(/\/+$/, "")
const slug = process.env.STATUS_PAGE_SLUG ?? "public"
return {
base,
slug,
pageUrl: `${base}/status/${slug}`,
apiUrl: `${base}/api/status-page/${slug}`,
heartbeatUrl: `${base}/api/status-page/heartbeat/${slug}`,
cacheTtlMs: envInt("STATUS_CACHE_TTL_SECONDS", 60) * 1000,
timeoutMs: envInt("STATUS_TIMEOUT_SECONDS", 4) * 1000,
// A monitor that has not reported in this long means Kuma itself is idle or
// the beat loop died, so the last known "up" can no longer be trusted.
staleAfterMs: envInt("STATUS_STALE_AFTER_SECONDS", 900) * 1000,
// Opt-in narrowing, e.g. STATUS_WATCH_GROUPS="Critical Services,Database Services"
// so a hobby game server cannot turn the footer red.
watchGroups: (process.env.STATUS_WATCH_GROUPS ?? "")
.split(",")
.map((name) => name.trim())
.filter(Boolean),
}
}
/**
* Kuma stores beat times as naive UTC strings. `new Date("...")` would parse them
* in the runtime's local zone, so pin the offset explicitly.
*/
export function parseBeatTime(time: string): number | null {
if (!time) return null
const normalized = /(?:Z|[+-]\d{2}:?\d{2})$/.test(time)
? time
: `${time.replace(" ", "T")}Z`
const ms = Date.parse(normalized)
return Number.isNaN(ms) ? null : ms
}
/**
* Pure reduction of the upstream payloads into one state. Mirrors Uptime Kuma's
* own `overallStatus()` computed property: maintenance wins immediately, any
* non-up beat degrades the page, and zero up beats means a total outage.
*/
export function summarize(input: {
incidents?: unknown[] | null
heartbeatList?: Record<string, KumaHeartbeat[]> | null
now?: number
staleAfterMs?: number
statusPageUrl?: string
}): StatusSnapshot {
const now = input.now ?? Date.now()
const staleAfterMs = input.staleAfterMs ?? 900_000
const heartbeatList = input.heartbeatList ?? {}
const incidents = Array.isArray(input.incidents) ? input.incidents : []
const summary = { total: 0, up: 0, down: 0, pending: 0, maintenance: 0 }
let newestBeatMs: number | null = null
for (const beats of Object.values(heartbeatList)) {
const last = beats?.[beats.length - 1]
if (!last) continue
summary.total += 1
if (last.status === BEAT.UP) summary.up += 1
else if (last.status === BEAT.DOWN) summary.down += 1
else if (last.status === BEAT.PENDING) summary.pending += 1
else if (last.status === BEAT.MAINTENANCE) summary.maintenance += 1
const beatMs = parseBeatTime(last.time)
if (beatMs !== null && (newestBeatMs === null || beatMs > newestBeatMs)) newestBeatMs = beatMs
}
let state: SystemState
let reason: UnknownReason | undefined
if (summary.total === 0) {
state = "unknown"
reason = "no-monitors"
} else if (newestBeatMs !== null && now - newestBeatMs > staleAfterMs) {
state = "unknown"
reason = "stale"
} else if (summary.maintenance > 0) {
state = "maintenance"
} else if (summary.up === 0) {
state = "down"
} else if (summary.down > 0 || summary.pending > 0 || incidents.length > 0) {
state = "degraded"
} else {
state = "up"
}
return {
state,
label: LABELS[state],
summary,
incidents: incidents.length,
checkedAt: new Date(now).toISOString(),
lastBeatAt: newestBeatMs === null ? null : new Date(newestBeatMs).toISOString(),
...(reason ? { reason } : {}),
statusPageUrl: input.statusPageUrl ?? "https://uptime.spaghet.io/status/public",
}
}
function snapshotForError(statusPageUrl: string, reason: UnknownReason): StatusSnapshot {
const empty = summarize({ heartbeatList: {}, statusPageUrl })
return { ...empty, state: "unknown", label: LABELS.unknown, reason }
}
async function fetchJson(url: string, timeoutMs: number): Promise<unknown> {
const response = await fetch(url, {
signal: AbortSignal.timeout(timeoutMs),
headers: { accept: "application/json", "user-agent": "spaghet.io-status/1.0" },
})
if (!response.ok) throw new Error(`Uptime Kuma returned ${response.status} for ${url}`)
return response.json()
}
/**
* Monitor ids belonging to the named groups (case-insensitive). Used when
* STATUS_WATCH_GROUPS narrows the footer light to a subset of the status page.
* Returns null when no narrowing is configured, so callers can skip filtering.
*/
export function monitorsInGroups(
publicGroupList: Array<{ name?: string; monitorList?: Array<{ id: number | string }> }> | null | undefined,
watchGroups: string[]
): Set<string> | null {
if (watchGroups.length === 0) return null
const wanted = new Set(watchGroups.map((name) => name.toLowerCase()))
const ids = new Set<string>()
for (const group of publicGroupList ?? []) {
if (!wanted.has(String(group?.name ?? "").toLowerCase())) continue
for (const monitor of group.monitorList ?? []) ids.add(String(monitor.id))
}
return ids
}
async function readUpstream(config: StatusConfig): Promise<StatusSnapshot> {
// The heartbeat route carries no incident info, and the page route carries no
// beats, so both are needed. They are independent, so fetch them together.
const [page, heartbeat] = await Promise.all([
fetchJson(config.apiUrl, config.timeoutMs) as Promise<{
incidents?: unknown[]
publicGroupList?: Array<{ name?: string; monitorList?: Array<{ id: number }> }>
}>,
fetchJson(config.heartbeatUrl, config.timeoutMs) as Promise<{
heartbeatList?: Record<string, KumaHeartbeat[]>
}>,
])
const heartbeatList = heartbeat?.heartbeatList ?? {}
const allowed = monitorsInGroups(page?.publicGroupList, config.watchGroups)
const scoped = allowed
? Object.fromEntries(Object.entries(heartbeatList).filter(([id]) => allowed.has(id)))
: heartbeatList
return summarize({
incidents: page?.incidents,
heartbeatList: scoped,
staleAfterMs: config.staleAfterMs,
statusPageUrl: config.pageUrl,
})
}
let cached: { snapshot: StatusSnapshot; expiresAt: number } | null = null
let inFlight: Promise<StatusSnapshot> | null = null
async function load(config: StatusConfig): Promise<StatusSnapshot> {
try {
const snapshot = await readUpstream(config)
cached = { snapshot, expiresAt: Date.now() + config.cacheTtlMs }
return snapshot
} catch (error: unknown) {
const reason: UnknownReason =
error instanceof Error && /returned \d{3}/.test(error.message) ? "http-error" : "fetch-failed"
if (process.env.NODE_ENV !== "test") {
console.error("[status] Uptime Kuma unreachable:", error instanceof Error ? error.message : error)
}
// Never throw at a caller: an unreachable Kuma becomes an honest "unknown"
// so the footer degrades instead of 500ing every page render.
const fallback = snapshotForError(config.pageUrl, reason)
cached = { snapshot: fallback, expiresAt: Date.now() + config.cacheTtlMs }
return fallback
} finally {
inFlight = null
}
}
/**
* Cached, single-flight view of the status page.
*
* A page render never waits on Uptime Kuma twice: the first request fetches, and
* while that is in flight everyone else joins it. Once a snapshot exists, an
* expired cache serves the previous value immediately and refreshes in the
* background (stale-while-revalidate), which keeps TTFB flat even if Kuma is slow.
*/
export async function getSystemStatus(opts: { force?: boolean } = {}): Promise<StatusSnapshot> {
const config = statusConfig()
if (inFlight) return inFlight
if (cached) {
const fresh = cached.expiresAt > Date.now()
if (!opts.force) {
if (fresh) return cached.snapshot
// Expired: serve the previous value and revalidate behind it.
inFlight = load(config)
void inFlight
return cached.snapshot
}
}
inFlight = load(config)
return inFlight
}
+24
View File
@@ -0,0 +1,24 @@
import type { APIRoute } from "astro"
import { getSystemStatus } from "@lib/status"
export const prerender = false
/**
* Footer-safe view of the Uptime Kuma status page: one small JSON document,
* server-fetched and cached, so the browser never has to (and can't) reach the
* Kuma API directly — it sends no CORS headers outside dev.
*/
export const GET: APIRoute = async ({ url }) => {
const force = url.searchParams.get("refresh") === "1"
const snapshot = await getSystemStatus({ force })
return new Response(JSON.stringify(snapshot), {
status: 200,
headers: {
"content-type": "application/json; charset=utf-8",
// The server already caches upstream, so keep the browser cache short and
// let the footer's own timer drive refreshes.
"cache-control": "public, max-age=30, stale-while-revalidate=120",
},
})
}