mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-06 10:44:23 +00:00
feat(server): add last-resort error handlers, a draining readiness probe and proxy keep-alive
Three small gaps in how the process behaves at its edges: - An unhandled rejection or uncaught exception crashed the process with the stack on stderr only. index.ts now logs it to trek.log and runs the same orderly shutdown a SIGTERM gets, exiting with 1; a second fatal error during that shutdown exits at once. - /api/health/ready kept answering 200 while a SIGTERM was draining the process, so an orchestrator sent traffic for another probe period. A shutdown now marks the new ReadinessService first (and Nest's own shutdown hook marks it too), and the probe answers 503 from then on. - Node closes an idle keep-alive connection after 5 seconds while reverse proxies keep upstream connections for about a minute, which shows up as intermittent 502s. The server now keeps them for 65 seconds, configurable through HTTP_KEEP_ALIVE_TIMEOUT_MS (owned by the httpConfig token), with the headers timeout one second above.
This commit is contained in:
@@ -8,7 +8,15 @@
|
||||
* each side touches. A value that pre-container code needs, or that tests
|
||||
* mutate mid-lifetime, belongs in derive.ts instead.
|
||||
*/
|
||||
import { parseBool } from './parsers';
|
||||
import { parseBool, positiveIntOr } from './parsers';
|
||||
|
||||
/**
|
||||
* Longer than the idle timeout of the common reverse proxies and load
|
||||
* balancers (60 s), so the proxy closes an idle upstream connection before
|
||||
* Node does. The other way round the proxy reuses a socket Node just closed
|
||||
* and answers that request with a 502.
|
||||
*/
|
||||
export const DEFAULT_KEEP_ALIVE_TIMEOUT_MS = 65_000;
|
||||
import type { RawEnv } from './derive';
|
||||
|
||||
/** What the pre-init Express layer and the HTTP server freeze when buildApp() runs. */
|
||||
@@ -20,6 +28,8 @@ export function deriveHttpBoot(raw: RawEnv) {
|
||||
trustProxyRaw: raw.TRUST_PROXY,
|
||||
trustProxy: Number.isFinite(trustProxyHops) ? trustProxyHops : 1,
|
||||
hstsIncludeSubdomains: parseBool(raw.HSTS_INCLUDE_SUBDOMAINS) === true,
|
||||
/** How long the HTTP server keeps an idle keep-alive connection open. */
|
||||
keepAliveTimeoutMs: positiveIntOr(raw.HTTP_KEEP_ALIVE_TIMEOUT_MS, DEFAULT_KEEP_ALIVE_TIMEOUT_MS),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -79,6 +79,9 @@ export const envSchema = z.object({
|
||||
FORCE_HTTPS: boolStr,
|
||||
HSTS_INCLUDE_SUBDOMAINS: boolStr,
|
||||
TRUST_PROXY: integer(0, 2 ** 31, 'must be an integer (number of trusted proxy hops)'),
|
||||
// Capped below Node's 300 s request timeout, which the headers timeout (one
|
||||
// second above this) has to stay under.
|
||||
HTTP_KEEP_ALIVE_TIMEOUT_MS: integer(1_000, 290_000, 'must be a whole number of milliseconds between 1000 and 290000'),
|
||||
ALLOW_INTERNAL_NETWORK: boolStr,
|
||||
ALLOW_LINK_LOCAL_IPS: optionalWith(
|
||||
(v) => parseLinkLocalAllowList(v).invalid.length === 0,
|
||||
|
||||
+16
-2
@@ -79,6 +79,19 @@ export function getHttpServer(): nodeHttp.Server {
|
||||
return boundHttpServer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep-alive behind a reverse proxy. Node's default is to drop an idle
|
||||
* keep-alive connection after 5 s, while proxies keep their upstream
|
||||
* connections for about a minute: a proxy that reuses a socket Node has just
|
||||
* closed answers that request with a 502, intermittently and with nothing in
|
||||
* TREK's log. The headers timeout stays above the keep-alive one, so a
|
||||
* connection waiting for its next request is never cut by the wrong timer.
|
||||
*/
|
||||
export function applyProxyTimeouts(server: nodeHttp.Server, keepAliveTimeoutMs: number): void {
|
||||
server.keepAliveTimeout = keepAliveTimeoutMs;
|
||||
server.headersTimeout = keepAliveTimeoutMs + 1_000;
|
||||
}
|
||||
|
||||
export async function buildApp(): Promise<INestApplication> {
|
||||
// rawBody keeps the unparsed request bytes on req.rawBody so a plugin webhook
|
||||
// route can verify a provider's HMAC signature over the exact payload (the
|
||||
@@ -106,12 +119,13 @@ export async function buildApp(): Promise<INestApplication> {
|
||||
// boot succeeds, the gateway logs as registered, every test passes, and no
|
||||
// browser can connect. Callers take the server from getHttpServer() below.
|
||||
boundHttpServer = nodeHttp.createServer(instance);
|
||||
app.useWebSocketAdapter(new TrekWsAdapter(boundHttpServer, orm));
|
||||
// ConfigModule.forRoot's load factories already ran inside NestFactory.create,
|
||||
// so the boot-stable snapshot is resolvable here, BEFORE app.init() — this is
|
||||
// so the boot-stable snapshot is resolvable here, BEFORE app.init(); this is
|
||||
// the one bridge that lets the pre-init Express layer consume the validated
|
||||
// config instead of reading process.env itself.
|
||||
const http = app.get<ConfigType<typeof httpConfig>>(httpConfig.KEY);
|
||||
applyProxyTimeouts(boundHttpServer, http.keepAliveTimeoutMs);
|
||||
app.useWebSocketAdapter(new TrekWsAdapter(boundHttpServer, orm));
|
||||
// Same pre-init bridge: a self-hosted routing engine has to be named in connect-src, or
|
||||
// the browser blocks every request to it without an error the app could report. Both
|
||||
// engines go through the same door — the second one answers the avoidance questions
|
||||
|
||||
+26
-5
@@ -18,7 +18,9 @@ import type { DatabaseLifecycle } from './nest/database/database-lifecycle.servi
|
||||
import { getAppUrl, getMcpSafeUrl, readEnv } from './app-config';
|
||||
import { resolveDataPaths } from './app-config/data-paths';
|
||||
import { resolveDbPath } from './db/db-path';
|
||||
import { flushLogFileSync } from './nest/audit/audit-log.logger';
|
||||
import { flushLogFileSync, logError } from './nest/audit/audit-log.logger';
|
||||
import { ReadinessService } from './nest/health/readiness.service';
|
||||
import { createFatalHandler } from './shutdown';
|
||||
|
||||
// data/tmp is the driver-agnostic global scratch dir (restore-upload spool,
|
||||
// mirror stream staging) and stays boot-created here. Driver-owned roots — the
|
||||
@@ -171,9 +173,13 @@ bootstrap().catch((err) => {
|
||||
// in short, #2193: nothing here could ever release a WebSocket, so `docker
|
||||
// stop` always ended in SIGKILL and exit 137.
|
||||
let shuttingDown = false;
|
||||
function shutdown(signal: string): void {
|
||||
// A second signal — the SIGINT that follows a Ctrl-C, or an impatient
|
||||
// orchestrator sending SIGTERM twice — must not start a second teardown on
|
||||
// Raised by a fatal error even when a signal's shutdown is already running, so
|
||||
// the process still leaves with a failure code the orchestrator can see.
|
||||
let exitCode = 0;
|
||||
function shutdown(signal: string, code = 0): void {
|
||||
exitCode = Math.max(exitCode, code);
|
||||
// A second signal (the SIGINT that follows a Ctrl-C, or an impatient
|
||||
// orchestrator sending SIGTERM twice) must not start a second teardown on
|
||||
// top of the first one.
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
@@ -198,7 +204,11 @@ function shutdown(signal: string): void {
|
||||
},
|
||||
logInfo: sLogInfo,
|
||||
logError: sLogError,
|
||||
exit: (code: number) => process.exit(code),
|
||||
// Readiness answers 503 from here on; strict: false because the provider
|
||||
// lives in HealthModule, not in the root module.
|
||||
markDraining: () => nestApp?.get(ReadinessService, { strict: false }).markDraining(),
|
||||
exitCode,
|
||||
exit: (code: number) => process.exit(Math.max(code, exitCode)),
|
||||
}).catch((err: unknown) => {
|
||||
// Fire-and-forget would make this an unhandled rejection, which on Node 22
|
||||
// is a crash — a worse ending than the one we are here to fix.
|
||||
@@ -212,5 +222,16 @@ function shutdown(signal: string): void {
|
||||
// synchronously here: an 'exit' listener cannot wait for a promise.
|
||||
process.on('exit', () => flushLogFileSync());
|
||||
|
||||
// Last-resort handlers. Node would crash on either anyway, printing the stack
|
||||
// to stderr only; this way it lands in trek.log first, and the process goes
|
||||
// through the same orderly shutdown as on SIGTERM before it exits with 1.
|
||||
const onFatal = createFatalHandler({
|
||||
logError,
|
||||
shutdown: (reason, code) => shutdown(reason, code),
|
||||
exit: (code) => process.exit(code),
|
||||
});
|
||||
process.on('unhandledRejection', (reason) => onFatal('Unhandled promise rejection', reason));
|
||||
process.on('uncaughtException', (error) => onFatal('Uncaught exception', error));
|
||||
|
||||
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
||||
process.on('SIGINT', () => shutdown('SIGINT'));
|
||||
|
||||
@@ -5,6 +5,7 @@ import { KitineraryExtractorService } from '../booking-import/kitinerary-extract
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { Public } from '../auth/public.decorator';
|
||||
import { ReadinessService } from './readiness.service';
|
||||
|
||||
/** Exposes the container probe and the server feature flags consumed by the
|
||||
* frontend to show/hide optional UI. */
|
||||
@@ -15,6 +16,7 @@ export class FeaturesController {
|
||||
private readonly extractor: KitineraryExtractorService,
|
||||
private readonly addons: AddonsService,
|
||||
private readonly maintenance: MaintenanceRepository,
|
||||
private readonly readiness: ReadinessService,
|
||||
) {}
|
||||
|
||||
/** The container/uptime probe. The forced-HTTPS redirect and HSTS exempt this
|
||||
@@ -28,13 +30,18 @@ export class FeaturesController {
|
||||
|
||||
/**
|
||||
* The readiness probe: 503 while the database does not answer (a restore
|
||||
* swapping it, a boot still migrating), so an orchestrator stops sending
|
||||
* traffic without killing the process. Liveness stays on the plain probe
|
||||
* above, which a long restore must not fail.
|
||||
* swapping it, a boot still migrating) and once a shutdown has started, so
|
||||
* an orchestrator stops sending traffic without killing the process.
|
||||
* Liveness stays on the plain probe above, which a long restore must not
|
||||
* fail.
|
||||
*/
|
||||
@Get('ready')
|
||||
async ready(@Res() res: Response): Promise<void> {
|
||||
res.setHeader('Cache-Control', 'no-store, must-revalidate');
|
||||
if (this.readiness.isDraining()) {
|
||||
res.status(503).json({ status: 'unavailable' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await this.maintenance.ping();
|
||||
res.json({ status: 'ready' });
|
||||
|
||||
@@ -3,6 +3,7 @@ import { FeaturesController } from './features.controller';
|
||||
import { KitineraryExtractorModule } from '../booking-import/kitinerary-extractor.module';
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
import { MaintenanceModule } from '../database/maintenance.module';
|
||||
import { ReadinessService } from './readiness.service';
|
||||
|
||||
/** Server capability reporting. `GET /api/health/features` tells the client which
|
||||
* optional server-side features are usable, so it can hide the affordances it
|
||||
@@ -12,5 +13,7 @@ import { MaintenanceModule } from '../database/maintenance.module';
|
||||
@Module({
|
||||
imports: [KitineraryExtractorModule, AddonsModule, MaintenanceModule],
|
||||
controllers: [FeaturesController],
|
||||
providers: [ReadinessService],
|
||||
exports: [ReadinessService],
|
||||
})
|
||||
export class HealthModule {}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Injectable, type BeforeApplicationShutdown } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* Whether this process still wants traffic. It stops wanting it the moment a
|
||||
* shutdown starts: index.ts marks it before the drain begins, and Nest's own
|
||||
* shutdown hook marks it too, for a close that does not come through
|
||||
* index.ts. The readiness probe answers 503 from then on, so an orchestrator
|
||||
* moves traffic away during the drain instead of one probe period later.
|
||||
*/
|
||||
@Injectable()
|
||||
export class ReadinessService implements BeforeApplicationShutdown {
|
||||
private draining = false;
|
||||
|
||||
markDraining(): void {
|
||||
this.draining = true;
|
||||
}
|
||||
|
||||
isDraining(): boolean {
|
||||
return this.draining;
|
||||
}
|
||||
|
||||
beforeApplicationShutdown(): void {
|
||||
this.markDraining();
|
||||
}
|
||||
}
|
||||
+49
-3
@@ -32,6 +32,13 @@ export interface ShutdownDeps {
|
||||
logInfo: (message: string) => void;
|
||||
logError: (message: string) => void;
|
||||
exit: (code: number) => void;
|
||||
/**
|
||||
* Flip readiness to "not ready" before anything else, so the probe sends
|
||||
* traffic elsewhere for the whole drain rather than one probe period later.
|
||||
*/
|
||||
markDraining?: () => void;
|
||||
/** The code a completed shutdown exits with: 0 for a signal, 1 after a fatal error. */
|
||||
exitCode?: number;
|
||||
/** How long a socket may take the polite way out before it is destroyed. */
|
||||
drainMs?: number;
|
||||
/** Last-resort exit, deliberately below Docker's 10s stop grace. */
|
||||
@@ -92,8 +99,8 @@ export const FORCED_EXIT_MS = 5_000;
|
||||
export async function runShutdown(signal: string, deps: ShutdownDeps): Promise<void> {
|
||||
const {
|
||||
server, closeNestApp, getWsClients, closeMcpSessions, closeDb,
|
||||
logInfo, logError, exit,
|
||||
drainMs = SOCKET_DRAIN_MS, forcedMs = FORCED_EXIT_MS,
|
||||
logInfo, logError, exit, markDraining,
|
||||
exitCode = 0, drainMs = SOCKET_DRAIN_MS, forcedMs = FORCED_EXIT_MS,
|
||||
} = deps;
|
||||
|
||||
logInfo(`${signal} received — shutting down gracefully...`);
|
||||
@@ -108,6 +115,8 @@ export async function runShutdown(signal: string, deps: ShutdownDeps): Promise<v
|
||||
}
|
||||
};
|
||||
|
||||
if (markDraining) guard('markDraining', markDraining);
|
||||
|
||||
let finished = false;
|
||||
/** The single exit path, so the DB is closed exactly once and never skipped. */
|
||||
const finish = (code: number, message: string): void => {
|
||||
@@ -169,5 +178,42 @@ export async function runShutdown(signal: string, deps: ShutdownDeps): Promise<v
|
||||
}
|
||||
clearTimeout(drain);
|
||||
clearTimeout(forced);
|
||||
finish(0, 'Shutdown complete');
|
||||
finish(exitCode, 'Shutdown complete');
|
||||
}
|
||||
|
||||
/** What the last-resort handlers need, handed in like the shutdown itself. */
|
||||
export interface FatalDeps {
|
||||
logError: (message: string) => void;
|
||||
/** Start the orderly shutdown with this reason and exit code. */
|
||||
shutdown: (reason: string, exitCode: number) => void;
|
||||
exit: (code: number) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The handler behind `process.on('unhandledRejection')` and
|
||||
* `process.on('uncaughtException')`.
|
||||
*
|
||||
* Node would crash on either anyway, with the stack on stderr only. This
|
||||
* writes it to the app log first, then runs the same orderly shutdown a
|
||||
* SIGTERM gets (sockets released, database closed, bounded by the forced
|
||||
* exit) and leaves with exit code 1, so the orchestrator restarts the
|
||||
* process. A second fatal error while that shutdown runs stops the process
|
||||
* at once: whatever is failing is failing the shutdown too.
|
||||
*/
|
||||
export function createFatalHandler(deps: FatalDeps): (kind: string, error: unknown) => void {
|
||||
let fired = false;
|
||||
return (kind, error) => {
|
||||
const detail = error instanceof Error ? (error.stack ?? error.message) : String(error);
|
||||
try {
|
||||
deps.logError(`${kind}: ${detail}`);
|
||||
} catch {
|
||||
// Logging is best effort here: the exit below must happen regardless.
|
||||
}
|
||||
if (fired) {
|
||||
deps.exit(1);
|
||||
return;
|
||||
}
|
||||
fired = true;
|
||||
deps.shutdown(kind, 1);
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user