Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/db/src/database-reachable.ts
T
2026-07-08 16:15:37 +02:00

49 lines
1.9 KiB
TypeScript

/**
* Shared reachability probe for opt-in Postgres integration suites.
*
* The integration tests in this package gate on a non-sentinel DATABASE_URL
* being set. That is insufficient for the CI "Workspace package tests" job
* (`pnpm -r test`): it injects a localhost DATABASE_URL but runs no Postgres
* service, so gating on the URL alone makes those suites connect and fail with
* `PrismaClientKnownRequestError P1001` instead of skipping. This helper
* confirms the server is actually usable by running a trivial `SELECT 1` with
* the package's own client factory, so local runs with a real DB still execute
* while CI-without-DB skips. Mirrors the inline probe in
* `apps/worker/src/jobs/workflow-trigger-e2e.test.ts`.
*/
import { createDbClient } from "./client.server.js";
/** Host:port label for logs — never includes credentials. */
export function databaseTargetLabel(url: string): string {
try {
const parsed = new URL(url);
return `${parsed.hostname}:${parsed.port || "5432"}`;
} catch {
return "configured database";
}
}
/**
* Usability probe for the configured Postgres URL. Any connection problem
* (unreachable / auth failure / missing database / timeout) resolves to
* "not reachable". `onError` is silenced so the probe stays quiet on the skip
* path.
*/
export async function isDatabaseReachable(url: string, timeoutMs = 4_000): Promise<boolean> {
const probe = createDbClient({ connectionString: url, onError: () => undefined });
// The query promise resolves to true/false and never rejects, so the losing
// race branch can't surface as an unhandled rejection.
const query = probe.$queryRaw`SELECT 1`.then(
() => true,
() => false
);
const timeout = new Promise<boolean>((resolve) => {
setTimeout(() => resolve(false), timeoutMs).unref?.();
});
try {
return await Promise.race([query, timeout]);
} finally {
await probe.$disconnect().catch(() => undefined);
}
}