← back to Stayclaim

src/app/api/pastdoor-health/route.ts

55 lines

/**
 * /api/pastdoor-health — liveness check + per-host smoke test surface.
 *
 * Was at /api/health but renamed 2026-05-04: nginx on Kamatera routes
 * /api/health/* to Site Factory (per `feedback_pastdoor_route_collisions.md`).
 * The old path was unreachable — every health probe was hitting Site Factory.
 *
 * Update deploy-pastdoor.sh and smoke-test.sh to call this URL.
 */
import { NextResponse } from 'next/server';
import { headers } from 'next/headers';
import { siteForHost } from '@/lib/site';
import { pool } from '@/lib/db';

export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';

export async function GET() {
  const h = await headers();
  const host = h.get('x-pastdoor-host') || h.get('host');
  const surface = siteForHost(host);

  let dbOk = false;
  let dbLatencyMs = -1;
  try {
    const t0 = Date.now();
    await Promise.race([
      pool.query('SELECT 1'),
      new Promise((_, reject) =>
        setTimeout(() => reject(new Error('db health timeout')), 2000),
      ),
    ]);
    dbLatencyMs = Date.now() - t0;
    dbOk = true;
  } catch (err) {
    console.error('pastdoor-health db check failed', err);
    dbOk = false;
  }

  return NextResponse.json(
    {
      ok: dbOk,
      host,
      surface: {
        key: surface.key,
        domain: surface.domain,
        brand: surface.brandName,
      },
      db: { ok: dbOk, latency_ms: dbLatencyMs },
      timestamp: new Date().toISOString(),
    },
    { status: dbOk ? 200 : 503 },
  );
}