01MVP 标识01MVP
包文档基础设施服务健康检查

健康检查

系统健康检查框架,监控应用和基础设施状态

概述

@mono/health 提供可扩展的健康检查框架,支持数据库连接、外部服务、自定义检查,并生成标准 HTTP 响应。

安装

pnpm add @mono/health

实战示例

1. 基础健康检查 API

app/api/health/route.ts
import { checkHealth, createDbChecker, healthResponse } from "@mono/health";
import { prisma } from "@/lib/db";

export async function GET() {
  const result = await checkHealth({
    checkers: [
      createDbChecker(() => prisma.$queryRaw`SELECT 1`),
    ],
  });
  return healthResponse(result);
}

export async function HEAD() {
  return new Response(null, { status: 200 });
}

2. 多服务检查

app/api/health/route.ts
import { checkHealth, createDbChecker, createChecker, healthResponse } from "@mono/health";

export async function GET() {
  const result = await checkHealth({
    checkers: [
      createDbChecker(() => prisma.$queryRaw`SELECT 1`),
      createChecker("redis", async () => {
        const redis = getRedisClient();
        await redis.ping();
      }),
      createChecker("storage", async () => {
        const res = await fetch(process.env.S3_ENDPOINT + "/health");
        if (!res.ok) throw new Error("Storage unavailable");
      }),
    ],
    timeout: 3000,
  });
  return healthResponse(result);
}

3. 监控集成

lib/monitoring.ts
import { checkHealth, createDbChecker } from "@mono/health";

export async function runHealthCheck() {
  const result = await checkHealth({
    checkers: [
      createDbChecker(() => prisma.$queryRaw`SELECT 1`),
    ],
  });

  if (result.status === "unhealthy") {
    // 发送告警
    await sendAlert({
      title: "服务不健康",
      details: JSON.stringify(result.checks, null, 2),
      memory: result.system?.memory,
    });
  }

  return result;
}

4. 自定义检查器

import { createChecker } from "@mono/health";

// 检查外部 API
const apiChecker = createChecker("external-api", async () => {
  const res = await fetch("https://api.stripe.com/v1/health");
  if (!res.ok) throw new Error(`Stripe API: ${res.status}`);
});

// 检查磁盘空间
const diskChecker = createChecker("disk", async () => {
  const { execSync } = await import("child_process");
  const usage = execSync("df -h / | tail -1").toString();
  const percent = parseInt(usage.match(/(\d+)%/)?.[1] || "0");
  if (percent > 90) throw new Error(`Disk usage: ${percent}%`);
});

API 参考

checkHealth(options?)

参数类型默认值说明
includeSystembooleantrue包含系统信息
timeoutnumber5000每个检查的超时(ms)
checkersHealthChecker[][]检查器列表

HealthCheckResult

字段类型说明
status"healthy" | "degraded" | "unhealthy"整体状态
timestampstringISO 8601 时间戳
uptimenumber运行时间(秒)
checksRecord<string, CheckResult>各检查结果
systemSystemInfo系统信息(可选)

healthResponse(result)

将结果转为 HTTP Response。healthy 返回 200,其他返回 503。

最佳实践

建议为健康检查端点设置独立的超时,避免检查本身导致请求超时。

  1. HEAD 方法 — 添加 HEAD 处理器用于轻量级存活探针
  2. 超时设置 — 每个检查器设置合理超时,默认 5 秒
  3. 缓存控制healthResponse 自动添加 no-cache 头
  4. 告警集成 — 结合 cron 或监控服务定期检查

相关文档