A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!
TypeScript agent-skillsaidsh-pluginhacktoberfestjavascriptmcp-serverreactresume-builderself-hostedtypescript
fix: allow slower storage health checks (#3639)
Amruth Pillaid84852161368
diff --git a/.env.example b/.env.exampleindex 041315985..ebf97d91f 100644--- a/.env.example+++ b/.env.example@@ -88,6 +88,9 @@ SMTP_SECURE="false"# Backend defaults to S3 when all credentials are present, otherwise local.# Vercel defaults to private Blob; Workers uses native R2. Explicit selection: local, s3, blob, r2.# STORAGE_BACKEND="local"+# Total storage health-check deadline, including both S3 PUT and DELETE requests.+# Set external probe timeouts higher than this value (milliseconds).+# STORAGE_HEALTHCHECK_TIMEOUT_MS="5000"# Cloudflare Workers uses CLOUDFLARE=1 and native STORAGE_BACKEND="r2" bindings.# Configure it through wrangler.jsonc and Wrangler secrets, not this Docker environment template.# BLOB_READ_WRITE_TOKEN=""diff --git a/apps/server/src/http/health.test.ts b/apps/server/src/http/health.test.tsindex 103c1f75b..60d9b6036 100644--- a/apps/server/src/http/health.test.ts+++ b/apps/server/src/http/health.test.ts@@ -1,24 +1,88 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-const { execute, healthcheck, ping } = vi.hoisted(() => ({ execute: vi.fn(), healthcheck: vi.fn(), ping: vi.fn() }));+const { execute, healthcheck, ping, env } = vi.hoisted(() => ({+ execute: vi.fn(),+ healthcheck: vi.fn(),+ ping: vi.fn(),+ env: { STORAGE_HEALTHCHECK_TIMEOUT_MS: 5_000 },+}));vi.mock("@reactive-resume/db/client", () => ({ db: { execute } }));vi.mock("@reactive-resume/api/features/storage", () => ({ getStorageService: () => ({ healthcheck }) }));vi.mock("@reactive-resume/db/redis", () => ({ getRedis: () => ({ ping }) }));+vi.mock("@reactive-resume/env/server", () => ({ env }));import { handleHealth } from "./health";-describe("health failure reporting", () => {+beforeEach(() => {+ execute.mockResolvedValue([]);+ healthcheck.mockResolvedValue({ status: "healthy" });+ ping.mockResolvedValue("PONG");+ env.STORAGE_HEALTHCHECK_TIMEOUT_MS = 5_000;+});++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+});++describe("health check timeouts", () => {beforeEach(() => {- execute.mockResolvedValue([]);- healthcheck.mockResolvedValue({ status: "healthy" });- ping.mockResolvedValue("PONG");+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] });+ vi.spyOn(console, "warn").mockImplementation(() => {});});- afterEach(() => {- vi.restoreAllMocks();+ it.each([+ { timeout: 5_000, latency: 2_200 },+ { timeout: 7_000, latency: 6_000 },+ ])("accepts working storage taking $latency ms within its $timeout ms deadline", async ({ timeout, latency }) => {+ env.STORAGE_HEALTHCHECK_TIMEOUT_MS = timeout;+ healthcheck.mockImplementationOnce(+ () => new Promise((resolve) => setTimeout(() => resolve({ status: "healthy", type: "s3" }), latency)),+ );++ const pending = handleHealth();+ await vi.advanceTimersByTimeAsync(latency);+ const response = await pending;++ expect(response.status).toBe(200);+ expect((await response.json()).storage).toMatchObject({ status: "healthy", type: "s3", latencyMs: latency });});+ it.each([5_000, 7_000])("fails stalled storage only after its configured %i ms deadline", async (timeout) => {+ env.STORAGE_HEALTHCHECK_TIMEOUT_MS = timeout;+ healthcheck.mockImplementationOnce(() => new Promise(() => {}));+ const settled = vi.fn();+ const pending = handleHealth().then((response) => {+ settled();+ return response;+ });++ await vi.advanceTimersByTimeAsync(timeout - 1);+ expect(settled).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ const response = await pending;++ expect(response.status).toBe(503);+ expect((await response.json()).storage).toEqual({+ status: "unhealthy",+ error: "Storage health check failed.",+ latencyMs: timeout,+ });+ });++ it.each(["database", "redis"])("retains the 1500 ms deadline for stalled %s", async (dependency) => {+ ({ database: execute, redis: ping })[dependency]?.mockImplementationOnce(() => new Promise(() => {}));+ const pending = handleHealth();+ await vi.advanceTimersByTimeAsync(1_500);+ const response = await pending;++ expect(response.status).toBe(503);+ expect((await response.json())[dependency]).toMatchObject({ status: "unhealthy", latencyMs: 1_500 });+ });+});++describe("health failure reporting", () => {it.each(["database", "storage", "redis"])("keeps thrown %s error details in server logs only", async (dependency) => {const detail = "Connection failed for private-user at internal.example:5432";const warn = vi.spyOn(console, "warn").mockImplementation(() => {});diff --git a/apps/server/src/http/health.ts b/apps/server/src/http/health.tsindex d51da9f9b..d0f9f943a 100644--- a/apps/server/src/http/health.ts+++ b/apps/server/src/http/health.ts@@ -3,6 +3,7 @@ import { withTimeout } from "es-toolkit";import { getStorageService } from "@reactive-resume/api/features/storage";import { db } from "@reactive-resume/db/client";import { getRedis } from "@reactive-resume/db/redis";+import { env } from "@reactive-resume/env/server";import { appVersion } from "../app-version";const HEALTHCHECK_TIMEOUT_MS = 1_500;@@ -14,12 +15,12 @@ type CheckResult = {[key: string]: unknown;};-// ponytail: es-toolkit withTimeout takes a fn, not a promise — call site passes check (not check())-async function runCheck(check: () => Promise<object>): Promise<CheckResult> {+/** Bound each dependency check and retain failure diagnostics for server-side logging. */+async function runCheck(check: () => Promise<object>, timeoutMs = HEALTHCHECK_TIMEOUT_MS): Promise<CheckResult> {const startedAt = performance.now();try {- const data = await withTimeout(check, HEALTHCHECK_TIMEOUT_MS);+ const data = await withTimeout(check, timeoutMs);const latencyMs = Math.round(performance.now() - startedAt);const result = data as { status?: string };if (result.status === "unhealthy") return { ...(data as object), status: "unhealthy", latencyMs };@@ -53,11 +54,12 @@ async function checkDatabase() {const checkStorage = () => getStorageService().healthcheck();+/** Report dependency readiness while keeping internal failure details in server logs. */export async function handleHealth() {const redisClient = getRedis();const [database, storage, redis] = await Promise.all([runCheck(checkDatabase),- runCheck(checkStorage),+ runCheck(checkStorage, env.STORAGE_HEALTHCHECK_TIMEOUT_MS),redisClient? runCheck(async () => {await redisClient.ping();diff --git a/docs/self-hosting/environment-variables.mdx b/docs/self-hosting/environment-variables.mdxindex 7906f3a94..7f07379b4 100644--- a/docs/self-hosting/environment-variables.mdx+++ b/docs/self-hosting/environment-variables.mdx@@ -111,19 +111,20 @@ instead, so you can still copy verification links from there.Uploads such as profile pictures, files attached to applications and Assistant attachments are stored in one of threebackends.-| Variable | Default | Description |-| ----------------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `STORAGE_BACKEND` | automatic | `local`, `s3`, `blob` or `r2` (Workers only). When unset: `r2` on Cloudflare Workers; otherwise `s3` if `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY` and `S3_BUCKET` are all set, `blob` on Vercel and `local` elsewhere. |-| `LOCAL_STORAGE_PATH` | `/app/data` in the image | Folder for local uploads. Must be an absolute path. In a source checkout it defaults to `data/` in the repository. The server checks that it is writable at startup and refuses to start if it is not. |-| `S3_ACCESS_KEY_ID` | unset | Access key for S3 or an S3-compatible service. |-| `S3_SECRET_ACCESS_KEY` | unset | Secret key. |-| `S3_BUCKET` | unset | Bucket name. The bucket can stay private: the app reads objects with its own credentials and serves them itself. |-| `S3_REGION` | `us-east-1` | Bucket region. |-| `S3_ENDPOINT` | AWS | Endpoint for non-AWS services, for example `https://<account>.r2.cloudflarestorage.com` or `http://seaweedfs:8333`. |-| `S3_FORCE_PATH_STYLE` | `false` | `true` for path-style addresses (`https://endpoint/bucket`), which MinIO and SeaweedFS need. `false` for virtual-hosted addresses (`https://bucket.endpoint`), used by AWS S3 and Cloudflare R2. |-| `BLOB_READ_WRITE_TOKEN` | unset | Vercel Blob token. On Vercel it is injected when you connect a Blob store. |-| `BLOB_STORE_ID` | unset | Vercel Blob store ID, when the token alone does not identify the store. |-| `DEPLOYMENT_NAMESPACE` | `default` | Prefix for Redis keys and Blob paths, so several instances can share one Redis or Blob store without mixing data. Letters, numbers, `.`, `_` and `-` only. On Vercel it is `production`, or the branch address on previews. |+| Variable | Default | Description |+| -------------------------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `STORAGE_BACKEND` | automatic | `local`, `s3`, `blob` or `r2` (Workers only). When unset: `r2` on Cloudflare Workers; otherwise `s3` if `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY` and `S3_BUCKET` are all set, `blob` on Vercel and `local` elsewhere. |+| `STORAGE_HEALTHCHECK_TIMEOUT_MS` | `5000` | Total storage check deadline for `/api/health`, in milliseconds. Includes both S3 PUT and DELETE requests. Increase for slower storage; set your external probe timeout higher than this value. |+| `LOCAL_STORAGE_PATH` | `/app/data` in the image | Folder for local uploads. Must be an absolute path. In a source checkout it defaults to `data/` in the repository. The server checks that it is writable at startup and refuses to start if it is not. |+| `S3_ACCESS_KEY_ID` | unset | Access key for S3 or an S3-compatible service. |+| `S3_SECRET_ACCESS_KEY` | unset | Secret key. |+| `S3_BUCKET` | unset | Bucket name. The bucket can stay private: the app reads objects with its own credentials and serves them itself. |+| `S3_REGION` | `us-east-1` | Bucket region. |+| `S3_ENDPOINT` | AWS | Endpoint for non-AWS services, for example `https://<account>.r2.cloudflarestorage.com` or `http://seaweedfs:8333`. |+| `S3_FORCE_PATH_STYLE` | `false` | `true` for path-style addresses (`https://endpoint/bucket`), which MinIO and SeaweedFS need. `false` for virtual-hosted addresses (`https://bucket.endpoint`), used by AWS S3 and Cloudflare R2. |+| `BLOB_READ_WRITE_TOKEN` | unset | Vercel Blob token. On Vercel it is injected when you connect a Blob store. |+| `BLOB_STORE_ID` | unset | Vercel Blob store ID, when the token alone does not identify the store. |+| `DEPLOYMENT_NAMESPACE` | `default` | Prefix for Redis keys and Blob paths, so several instances can share one Redis or Blob store without mixing data. Letters, numbers, `.`, `_` and `-` only. On Vercel it is `production`, or the branch address on previews. |<Note>Assistant attachments stay private with every backend. Local storage writes them in a separate namespace that publicdiff --git a/docs/self-hosting/kubernetes.mdx b/docs/self-hosting/kubernetes.mdxindex 1e474d444..50fa25d8a 100644--- a/docs/self-hosting/kubernetes.mdx+++ b/docs/self-hosting/kubernetes.mdx@@ -198,13 +198,14 @@ spec:path: /api/healthport: httpperiodSeconds: 5+ timeoutSeconds: 6failureThreshold: 60readinessProbe:httpGet:path: /api/healthport: httpperiodSeconds: 10- timeoutSeconds: 5+ timeoutSeconds: 6resources:requests:cpu: 250m@@ -317,6 +318,11 @@ rate limits.- There is deliberately no liveness probe on `/api/health`. Restarting the app doesn't fix a database or storageoutage. If the server process itself exits, Kubernetes restarts the container anyway.+Storage checks have a 5-second deadline by default, including both S3 PUT and DELETE requests. For slower storage,+set `STORAGE_HEALTHCHECK_TIMEOUT_MS` (milliseconds) in the app Secret. Set both probes' `timeoutSeconds` (seconds)+above that duration (for example, `STORAGE_HEALTHCHECK_TIMEOUT_MS=10000` and `timeoutSeconds: 11`). Database and+Redis checks keep their 1.5-second deadlines.+See [Check the health endpoint](/self-hosting/docker#check-the-health-endpoint) for the response format. To call ityourself:diff --git a/packages/env/src/server.test.ts b/packages/env/src/server.test.tsindex 914b3bfe7..d4f1bbb00 100644--- a/packages/env/src/server.test.ts+++ b/packages/env/src/server.test.ts@@ -13,6 +13,7 @@ beforeEach(() => {"AI_API_KEY","AI_BASE_URL","REDIS_URL",+ "STORAGE_HEALTHCHECK_TIMEOUT_MS",])vi.stubEnv(name, undefined);});@@ -45,6 +46,24 @@ describe("server web access configuration", () => {});});+describe("storage health check timeout", () => {+ it.each([undefined, ""])("defaults to 5000 ms when unset or blank (%s)", async (value) => {+ vi.stubEnv("STORAGE_HEALTHCHECK_TIMEOUT_MS", value);+ expect((await import("./server")).env.STORAGE_HEALTHCHECK_TIMEOUT_MS).toBe(5_000);+ });++ it("accepts a custom timeout in milliseconds", async () => {+ vi.stubEnv("STORAGE_HEALTHCHECK_TIMEOUT_MS", "7000");+ expect((await import("./server")).env.STORAGE_HEALTHCHECK_TIMEOUT_MS).toBe(7_000);+ });++ it.each(["0", "-1", "1.5", "not-a-number", "2147483648"])("rejects invalid timer duration %s", async (value) => {+ vi.stubEnv("STORAGE_HEALTHCHECK_TIMEOUT_MS", value);+ vi.spyOn(console, "error").mockImplementation(() => {});+ await expect(import("./server")).rejects.toThrow("Invalid environment variables");+ });+});+describe("redis url userinfo", () => {it.each(["redis://localhost:6379",diff --git a/packages/env/src/server.ts b/packages/env/src/server.tsindex c6f906043..a8a144d0b 100644--- a/packages/env/src/server.ts+++ b/packages/env/src/server.ts@@ -133,6 +133,7 @@ export const env = createEnv({// Storage (Optional)STORAGE_BACKEND: z.enum(["local", "s3", "blob", "r2"]),+ STORAGE_HEALTHCHECK_TIMEOUT_MS: z.coerce.number().int().positive().max(2_147_483_647).default(5_000),BLOB_READ_WRITE_TOKEN: z.string().min(1).optional(),BLOB_STORE_ID: z.string().min(1).optional(),DEPLOYMENT_NAMESPACE: z.string().regex(/^[a-zA-Z0-9._-]+$/),diff --git a/turbo.json b/turbo.jsonindex b59c41d45..b8b5e427e 100644--- a/turbo.json+++ b/turbo.json@@ -92,6 +92,7 @@"POSTGRES_*","KV_URL","STORAGE_BACKEND",+ "STORAGE_HEALTHCHECK_TIMEOUT_MS","BLOB_*","DEPLOYMENT_NAMESPACE","ALLOW_PREVIEW_MIGRATIONS",@@ -134,6 +135,7 @@"POSTGRES_*","KV_URL","STORAGE_BACKEND",+ "STORAGE_HEALTHCHECK_TIMEOUT_MS","BLOB_*","DEPLOYMENT_NAMESPACE","ALLOW_PREVIEW_MIGRATIONS",@@ -177,6 +179,7 @@"POSTGRES_*","KV_URL","STORAGE_BACKEND",+ "STORAGE_HEALTHCHECK_TIMEOUT_MS","BLOB_*","DEPLOYMENT_NAMESPACE","ALLOW_PREVIEW_MIGRATIONS",@@ -220,6 +223,7 @@"POSTGRES_*","KV_URL","STORAGE_BACKEND",+ "STORAGE_HEALTHCHECK_TIMEOUT_MS","BLOB_*","DEPLOYMENT_NAMESPACE","ALLOW_PREVIEW_MIGRATIONS",@@ -322,6 +326,7 @@"POSTGRES_URL_NON_POOLING","KV_URL","STORAGE_BACKEND",+ "STORAGE_HEALTHCHECK_TIMEOUT_MS","BLOB_READ_WRITE_TOKEN","BLOB_STORE_ID","DEPLOYMENT_NAMESPACE",