import { randomUUID } from 'node:crypto'; import { FastifyAdapter, NestFastifyApplication, } from '@nestjs/platform-fastify'; const requestIdHeader = 'x-request-id'; const instanceIdHeader = 'x-instance-id'; const instanceId = process.env.INSTANCE_ID?.trim() || randomUUID(); // Two parallel readiness rounds: 2 * (1s request timeout + 2s interval), // plus one second for the upstream reload. Keep below the public hook's 10s limit. export const DRAIN_DELAY_MS = 7000; export class DrainingFastifyAdapter extends FastifyAdapter { private draining = false; private closing?: Promise; private httpClosing?: Promise; constructor(private readonly drainDelayMs: number) { super({ requestIdHeader, genReqId: () => randomUUID() }); this.getInstance().addHook('onSend', (_request, reply, payload, done) => { // An already active request may finish after Fastify starts closing. // Finish its response, then close its keep-alive socket as well. if (this.httpClosing) void reply.header('connection', 'close'); done(null, payload); }); } get isDraining(): boolean { return this.draining; } override beforeClose(): Promise { return (this.closing ??= this.drainAndClose()); } override close(): Promise { return (this.httpClosing ??= super.close()); } private async drainAndClose(): Promise { this.draining = true; if (this.drainDelayMs > 0) { await new Promise((resolve) => setTimeout(resolve, this.drainDelayMs)); } // Nest awaits beforeClose before destroying Prisma/Redis providers. // Fastify first stops new connections and finishes active HTTP requests. await this.close(); } } export function createFastifyAdapter(drainDelayMs = 0): DrainingFastifyAdapter { return new DrainingFastifyAdapter(drainDelayMs); } export function exposeRequestIdHeader(app: NestFastifyApplication): void { app .getHttpAdapter() .getInstance() .addHook('onRequest', (request, reply, done) => { void reply.header(requestIdHeader, request.id); void reply.header(instanceIdHeader, instanceId); done(); }); }