diff --git a/docs/MONITORING.md b/docs/MONITORING.md index e79294a..b7f663f 100644 --- a/docs/MONITORING.md +++ b/docs/MONITORING.md @@ -47,12 +47,21 @@ Suggested schedule: every 1–5 minutes. Alert on consecutive failures (e.g. 2). ## Protect the route from amplification -`createStorePingCheck` performs a real write plus a read on every call — that is -the point, a connectivity ping would lie. It also means each request to the -public route costs one storage write against a metered backend. Hosts SHOULD put -rate limiting (or a short response cache, a few seconds) in front of the route, -or expose the store ping only on a route scraped by trusted monitors. This -package deliberately owns no rate limiter. +`createStorePingCheck` performs a real write plus a read for each probe +execution — that is the point, a connectivity ping would lie. It also means +requests to the public route can cost storage writes against a metered backend. +Hosts SHOULD put rate limiting (or a short response cache, a few seconds) in +front of the route, or expose the store ping only on a route scraped by trusted +monitors. This package deliberately owns no rate limiter. + +Construct `createStorePingCheck` once at the composition root and reuse that +check for every request. Concurrent calls to one check share the same in-flight +round trip and its reported latency. By default, each constructed check receives +its own probe record id, so replicas using the same health collection do not +overwrite one another. A verified row is conditionally removed after the round +trip. Pass an explicit `id` when a host needs a stable key, and keep that id +distinct among simultaneously running replicas. Earlier releases used `ping` as +the default; pass `id: "ping"` to retain that key intentionally. `degraded` still returns HTTP 200 with `ok: true`. If you want to page on degraded storage/logging, add a JSON assertion on `$.status` or a log monitor diff --git a/packages/health/README.md b/packages/health/README.md index 52e22a1..26125fe 100644 --- a/packages/health/README.md +++ b/packages/health/README.md @@ -40,6 +40,14 @@ logged through the injected `Logger` only, never placed in the public body. A check must settle, though: `runHealthChecks` imposes no deadline of its own, so bound your own I/O the way `createStorePingCheck` bounds its `timeoutMs`. -`createStorePingCheck` writes and reads on every call, so a host serving it on a -public route SHOULD rate limit or briefly cache that route — see +`createStorePingCheck` performs a write-and-read round trip for each probe +execution, so a host serving it on a public route SHOULD rate limit or briefly +cache that route — see [`docs/MONITORING.md`](https://github.com/pegma-dev/health/blob/main/docs/MONITORING.md). +Construct the check once at the composition root and reuse it for every health +request. Concurrent callers share one execution and its `latencyMs`. The default +record id is unique to that check instance, which keeps replicas from sharing a +probe row, and a verified row is conditionally removed after the round trip. +Pass an explicit `id` when the host needs a stable key; keep that id distinct +among simultaneously running replicas. Earlier releases used `ping` as the +default, so pass `id: "ping"` to retain that key intentionally. diff --git a/packages/health/src/index.test.ts b/packages/health/src/index.test.ts index 62effed..bce8f5c 100644 --- a/packages/health/src/index.test.ts +++ b/packages/health/src/index.test.ts @@ -1,6 +1,6 @@ -import { fixedClock, type Logger } from "@pegma/spine"; +import { fixedClock, type Clock, type Logger } from "@pegma/spine"; import { createMemoryStore } from "@pegma/storage-core"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { createDetailCheck, @@ -11,6 +11,7 @@ import { toHealthResponse, type CheckResult, type HealthCheck, + type HealthProbeRecord, } from "./index.js"; import type { Store } from "@pegma/storage-core"; @@ -24,6 +25,14 @@ const NOW = "2026-07-27T21:00:00.000Z"; const SECRET_SHAPED_MESSAGE = "AccountName=example;AccountKey=PLACEHOLDER_NOT_A_REAL_KEY"; +function deferred() { + let resolve!: (value: T | PromiseLike) => void; + const promise = new Promise((settle) => { + resolve = settle; + }); + return { promise, resolve }; +} + function failingCheck( name: string, status: CheckResult["status"], @@ -57,6 +66,20 @@ describe("createDetailCheck", () => { }); describe("createStorePingCheck", () => { + it("constructs when Web Crypto is unavailable", async () => { + vi.stubGlobal("crypto", undefined); + try { + const check = createStorePingCheck({ + store: createMemoryStore(), + collection: healthProbeCollection, + clock: fixedClock(NOW), + }); + await expect(check.run()).resolves.toMatchObject({ status: "ok" }); + } finally { + vi.unstubAllGlobals(); + } + }); + it("round-trips a probe write through an injected store", async () => { const store = createMemoryStore(); const check = createStorePingCheck({ @@ -70,22 +93,247 @@ describe("createStorePingCheck", () => { const stored = await store .collection(healthProbeCollection) - .get({ partition: "__health__", id: "ping" }); - expect(stored).toEqual({ - id: "ping", + .list("__health__"); + expect(stored).toEqual([]); + }); + + it("honors an explicit probe id", async () => { + let stored: HealthProbeRecord | null = null; + let observed: HealthProbeRecord | null = null; + const store = { + collection() { + return { + async getVersioned() { + return stored === null ? null : { value: stored, version: "1" }; + }, + async insertIfAbsent(value: HealthProbeRecord) { + stored = value; + observed = value; + return { inserted: true, value }; + }, + async putIfUnchanged() { + return false; + }, + async deleteIfUnchanged() { + stored = null; + return true; + }, + }; + }, + } as unknown as Store; + const check = createStorePingCheck({ + store, + collection: healthProbeCollection, + clock: fixedClock(NOW), + id: "replica-a", + }); + + await expect(check.run()).resolves.toMatchObject({ status: "ok" }); + expect(observed).toEqual({ + id: "replica-a", partition: "__health__", probedAt: NOW, }); }); + it("coalesces concurrent calls on one check instance", async () => { + const writeStarted = deferred(); + let stored: HealthProbeRecord | null = null; + let writeCalls = 0; + let nowCalls = 0; + const clock: Clock = { + now() { + nowCalls += 1; + return nowCalls === 1 ? NOW : "2026-07-27T21:00:01.000Z"; + }, + }; + const store = { + collection() { + return { + async getVersioned() { + return stored === null ? null : { value: stored, version: "1" }; + }, + async insertIfAbsent(value: HealthProbeRecord) { + writeCalls += 1; + await writeStarted.promise; + stored = value; + return { inserted: true, value }; + }, + async putIfUnchanged() { + return false; + }, + async deleteIfUnchanged() { + stored = null; + return true; + }, + }; + }, + } as unknown as Store; + const check = createStorePingCheck({ + store, + collection: healthProbeCollection, + clock, + }); + + const first = check.run(); + const second = check.run(); + expect(second).toBe(first); + writeStarted.resolve(); + + await expect(Promise.all([first, second])).resolves.toMatchObject([ + { status: "ok" }, + { status: "ok" }, + ]); + expect(writeCalls).toBe(1); + expect(nowCalls).toBe(1); + }); + + it("isolates separate check instances sharing one store", async () => { + const firstWrite = deferred(); + const records = new Map< + string, + { value: HealthProbeRecord; version: string } + >(); + const observedIds = new Set(); + let writeCalls = 0; + const store = { + collection() { + return { + async getVersioned(key: { readonly id: string }) { + return records.get(key.id) ?? null; + }, + async insertIfAbsent(value: HealthProbeRecord) { + writeCalls += 1; + observedIds.add(value.id); + records.set(value.id, { value, version: String(writeCalls) }); + if (writeCalls === 1) { + await firstWrite.promise; + } else { + firstWrite.resolve(); + } + return { inserted: true, value }; + }, + async putIfUnchanged() { + return false; + }, + async deleteIfUnchanged(key: { readonly id: string }) { + return records.delete(key.id); + }, + }; + }, + } as unknown as Store; + const first = createStorePingCheck({ + store, + collection: healthProbeCollection, + clock: fixedClock(NOW), + }); + const second = createStorePingCheck({ + store, + collection: healthProbeCollection, + clock: fixedClock("2026-07-27T21:00:01.000Z"), + }); + + const results = await Promise.all([first.run(), second.run()]); + + expect(results).toMatchObject([{ status: "ok" }, { status: "ok" }]); + expect(observedIds.size).toBe(2); + for (const id of observedIds) { + expect(id).toMatch(/^ping-/); + } + }); + + it("recovers while an earlier timed-out write is still pending", async () => { + vi.useFakeTimers(); + const slowWrite = deferred(); + let stored: { value: HealthProbeRecord; version: string } | null = null; + let writeCalls = 0; + let version = 0; + let nowCalls = 0; + const clock: Clock = { + now() { + nowCalls += 1; + return nowCalls === 1 + ? NOW + : nowCalls === 2 + ? "2026-07-27T21:00:01.000Z" + : "2026-07-27T21:00:02.000Z"; + }, + }; + const store = { + collection() { + return { + async getVersioned() { + return stored; + }, + async insertIfAbsent(value: HealthProbeRecord) { + writeCalls += 1; + if (writeCalls === 1) { + await slowWrite.promise; + } + if (stored !== null) { + return { inserted: false, value: stored.value }; + } + version += 1; + stored = { value, version: String(version) }; + return { inserted: true, value }; + }, + async putIfUnchanged(value: HealthProbeRecord, expected: string) { + if (stored?.version !== expected) { + return false; + } + version += 1; + stored = { value, version: String(version) }; + return true; + }, + async deleteIfUnchanged( + _key: { readonly id: string }, + expected: string, + ) { + if (stored?.version !== expected) { + return false; + } + stored = null; + return true; + }, + }; + }, + } as unknown as Store; + const check = createStorePingCheck({ + store, + collection: healthProbeCollection, + clock, + id: "replica-a", + timeoutMs: 5, + }); + + try { + const timedOut = check.run(); + await vi.advanceTimersByTimeAsync(5); + await expect(timedOut).resolves.toMatchObject({ + status: "fail", + detail: { reason: "store_ping_timeout" }, + }); + + await expect(check.run()).resolves.toMatchObject({ status: "ok" }); + expect(writeCalls).toBe(2); + + slowWrite.resolve(); + await Promise.resolve(); + await expect(check.run()).resolves.toMatchObject({ status: "ok" }); + expect(nowCalls).toBe(3); + } finally { + vi.useRealTimers(); + } + }); + it("fails when the store rejects writes", async () => { const brokenStore = { collection() { return { - async get() { + async getVersioned() { return null; }, - async put() { + async insertIfAbsent() { throw new Error("tables unavailable"); }, }; @@ -101,14 +349,53 @@ describe("createStorePingCheck", () => { expect(result.detail).toEqual({ reason: "store_ping_failed" }); }); + it("bounds repeated conditional write conflicts", async () => { + const existing: HealthProbeRecord = { + id: "replica-a", + partition: "__health__", + probedAt: NOW, + }; + let reads = 0; + let writes = 0; + const store = { + collection() { + return { + async getVersioned() { + reads += 1; + return { value: existing, version: "unchanged" }; + }, + async putIfUnchanged() { + writes += 1; + return false; + }, + }; + }, + } as unknown as Store; + const check = createStorePingCheck({ + store, + collection: healthProbeCollection, + clock: fixedClock(NOW), + id: "replica-a", + }); + + const result = await check.run(); + + expect(result).toMatchObject({ + status: "fail", + detail: { reason: "store_ping_failed" }, + }); + expect(reads).toBe(3); + expect(writes).toBe(3); + }); + it("never leaks the store error message into public detail", async () => { const brokenStore = { collection() { return { - async get() { + async getVersioned() { return null; }, - async put() { + async insertIfAbsent() { throw new Error(SECRET_SHAPED_MESSAGE); }, }; @@ -125,14 +412,15 @@ describe("createStorePingCheck", () => { }); it("reports a timeout as its own enumerated reason", async () => { + vi.useFakeTimers(); const hangingStore = { collection() { return { - async get() { + async getVersioned() { return null; }, - put() { - return new Promise(() => { + insertIfAbsent() { + return new Promise(() => { // never settles }); }, @@ -145,9 +433,60 @@ describe("createStorePingCheck", () => { clock: fixedClock(NOW), timeoutMs: 5, }); - const result = await check.run(); - expect(result.status).toBe("fail"); - expect(result.detail).toEqual({ reason: "store_ping_timeout" }); + try { + const pending = check.run(); + await vi.advanceTimersByTimeAsync(5); + const result = await pending; + expect(result.status).toBe("fail"); + expect(result.detail).toEqual({ reason: "store_ping_timeout" }); + } finally { + vi.useRealTimers(); + } + }); + + it("uses one timeout budget across storage operations", async () => { + vi.useFakeTimers(); + let stored: HealthProbeRecord | null = null; + const store = { + collection() { + return { + getVersioned() { + return new Promise((resolve) => { + setTimeout(() => resolve(null), 3); + }); + }, + insertIfAbsent(value: HealthProbeRecord) { + return new Promise<{ inserted: true; value: HealthProbeRecord }>( + (resolve) => { + setTimeout(() => { + stored = value; + resolve({ inserted: true, value }); + }, 3); + }, + ); + }, + }; + }, + } as unknown as Store; + const check = createStorePingCheck({ + store, + collection: healthProbeCollection, + clock: fixedClock(NOW), + timeoutMs: 5, + }); + + try { + const pending = check.run(); + await vi.advanceTimersByTimeAsync(5); + await expect(pending).resolves.toMatchObject({ + status: "fail", + latencyMs: 5, + detail: { reason: "store_ping_timeout" }, + }); + expect(stored).toBeNull(); + } finally { + vi.useRealTimers(); + } }); }); diff --git a/packages/health/src/index.ts b/packages/health/src/index.ts index d7cd110..b4edb63 100644 --- a/packages/health/src/index.ts +++ b/packages/health/src/index.ts @@ -57,9 +57,11 @@ export interface HealthProbeRecord { } const DEFAULT_PARTITION = "__health__"; -const DEFAULT_PROBE_ID = "ping"; +const DEFAULT_PROBE_ID_PREFIX = "ping-"; const DEFAULT_TIMEOUT_MS = 5_000; +const MAX_PROBE_WRITE_ATTEMPTS = 3; const MAX_LOGGED_ERROR_CHARS = 300; +let fallbackProbeId = 0; /** Marks a probe that exceeded its own timeout rather than rejecting. */ class ProbeTimeoutError extends Error {} @@ -130,7 +132,7 @@ export interface StorePingCheckOptions { readonly collection: CollectionDefinition; /** Defaults to `__health__`. */ readonly partitionKey?: string; - /** Defaults to `ping`. */ + /** Defaults to a unique id for this check instance. */ readonly id?: string; /** Defaults to `storage`. */ readonly name?: string; @@ -139,6 +141,16 @@ export interface StorePingCheckOptions { readonly clock?: Clock; } +function createDefaultProbeId(): string { + const randomUUID = globalThis.crypto?.randomUUID; + if (typeof randomUUID === "function") { + return `${DEFAULT_PROBE_ID_PREFIX}${randomUUID.call(globalThis.crypto)}`; + } + + fallbackProbeId += 1; + return `${DEFAULT_PROBE_ID_PREFIX}${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${fallbackProbeId.toString(36)}`; +} + /** * Put-then-get round-trip against an injected Store. Proves the storage layer * accepts writes and returns them — not merely that a TCP port is open. @@ -148,50 +160,122 @@ export function createStorePingCheck( ): HealthCheck { const name = options.name ?? "storage"; const partition = options.partitionKey ?? DEFAULT_PARTITION; - const id = options.id ?? DEFAULT_PROBE_ID; + const id = options.id ?? createDefaultProbeId(); const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; const clock = options.clock ?? systemClock; const probes = options.store.collection(options.collection); + let inFlight: Promise | undefined; - return { - name, - async run() { - const started = Date.now(); - try { - const probedAt = clock.now(); - const record: HealthProbeRecord = { id, partition, probedAt }; - await withTimeout(probes.put(record), timeoutMs); - const got = await withTimeout(probes.get({ partition, id }), timeoutMs); - if (got === null || got.probedAt !== probedAt) { - return { - status: "fail", - latencyMs: Date.now() - started, - detail: { reason: "round_trip_mismatch" }, - }; + async function writeProbe( + record: HealthProbeRecord, + deadline: number, + ): Promise { + const key = { partition, id }; + for (let attempt = 0; attempt < MAX_PROBE_WRITE_ATTEMPTS; attempt += 1) { + const current = await withinDeadline( + () => probes.getVersioned(key), + deadline, + ); + if (current === null) { + const result = await withinDeadline( + () => probes.insertIfAbsent(record), + deadline, + ); + if (result.inserted) { + return; } - return { - status: "ok", - latencyMs: Date.now() - started, - }; - } catch (error) { - // Never surface the underlying error text: store adapter messages - // routinely embed account names, URLs, and request ids, and this detail - // is served on a public endpoint. Report an enumerated reason instead. + } else { + const written = await withinDeadline( + () => probes.putIfUnchanged(record, current.version), + deadline, + ); + if (written) { + return; + } + } + } + throw new Error("health probe write attempts exhausted"); + } + + async function runProbe(): Promise { + const started = Date.now(); + const deadline = started + timeoutMs; + try { + const probedAt = clock.now(); + const record: HealthProbeRecord = { id, partition, probedAt }; + await writeProbe(record, deadline); + const got = await withinDeadline( + () => probes.getVersioned({ partition, id }), + deadline, + ); + if (got === null || got.value.probedAt !== probedAt) { return { status: "fail", latencyMs: Date.now() - started, - detail: { - reason: - error instanceof ProbeTimeoutError - ? "store_ping_timeout" - : "store_ping_failed", - }, + detail: { reason: "round_trip_mismatch" }, }; } + + try { + await withinDeadline( + () => probes.deleteIfUnchanged({ partition, id }, got.version), + deadline, + ); + } catch { + // Cleanup is best effort. The verified round trip remains valid, and a + // later conditional write can safely reuse this check instance's row. + } + return { + status: "ok", + latencyMs: Date.now() - started, + }; + } catch (error) { + // Never surface the underlying error text: store adapter messages + // routinely embed account names, URLs, and request ids, and this detail + // is served on a public endpoint. Report an enumerated reason instead. + return { + status: "fail", + latencyMs: Date.now() - started, + detail: { + reason: + error instanceof ProbeTimeoutError + ? "store_ping_timeout" + : "store_ping_failed", + }, + }; + } + } + + return { + name, + run() { + if (inFlight !== undefined) { + return inFlight; + } + + const attempt = runProbe(); + inFlight = attempt; + void attempt.finally(() => { + if (inFlight === attempt) { + inFlight = undefined; + } + }); + return attempt; }, }; } +function withinDeadline( + operation: () => Promise, + deadline: number, +): Promise { + const remainingMs = deadline - Date.now(); + if (remainingMs <= 0) { + return Promise.reject(new ProbeTimeoutError("probe deadline elapsed")); + } + return withTimeout(operation(), remainingMs); +} + function withTimeout(promise: Promise, timeoutMs: number): Promise { return new Promise((resolve, reject) => { const timer = setTimeout(() => {