Skip to the content

Capsid menu

app/lib/health/snapshot.server.ts

50 lines and 2 functions in DrDustinEdwards/dustinedwards-info, at commit 1590ba4 on 2026-10-24. This file on GitHub.

Functions

The functions of snapshot.server.ts
FunctionLinesComplexityCoveredCRAPMutation
writeHealthSnapshot16 to 332No data: no coverage report in this mapNo data: no coverage report in this mapNo data: no mutants in this code
readHealthTile39 to 532No data: no coverage report in this mapNo data: no coverage report in this mapNo data: no mutants in this code

Imports

It imports app/lib/error-message.mjs, app/lib/health/snapshot.mjs. Imported by app/routes/api.health.ts, app/routes/colophon.tsx.

Source

// A reader that could write would turn a cache miss on the busiest page back into a health run.

import {
  HEALTH_SNAPSHOT_KEY,
  healthTile,
  snapshotFromBody,
  type HealthTile,
} from "./snapshot.mjs";
import { errorMessage } from "~/lib/error-message.mjs";

/**
 * Never throws: bookkeeping must not cost the health endpoint its verdict. Awaited, not waitUntil, so
 * a caller reading this then the home page sees a consistent pair. No expiry: an aging "stale" beats
 * a "missing" that reads as misconfiguration.
 */
export async function writeHealthSnapshot(
  env: Env,
  body: { ok: boolean; checks: Array<{ ok: boolean }> },
  readAt: string,
): Promise<void> {
  try {
    await env.APP_KV.put(HEALTH_SNAPSHOT_KEY, JSON.stringify(snapshotFromBody(body, readAt)));
  } catch (error) {
    /* A snapshot write must never cost the caller their health verdict, but it is logged: an
     * unwritten snapshot ages the tile to "stale" and reads as a dead watchdog. */
    console.error(
      JSON.stringify({
        alert: "health-snapshot-write-failed",
        detail: errorMessage(error),
      }),
    );
  }
}

/**
 * A throw renders as `unreadable`, never as `missing`: the home page must render whatever KV is doing,
 * but a failed read is not the same fact as no snapshot having been written. It is logged.
 */
export async function readHealthTile(env: Env): Promise<HealthTile> {
  let stored: unknown;
  try {
    stored = await env.APP_KV.get(HEALTH_SNAPSHOT_KEY, "json");
  } catch (error) {
    console.error(
      JSON.stringify({
        alert: "health-snapshot-read-failed",
        detail: errorMessage(error),
      }),
    );
    return { state: "unreadable" };
  }
  return healthTile(stored, Date.now());
}