Files
mtusi2026lab3/src/common/http/fastify-adapter.ts
T
qrtx 24f32c3fbe feat(api): implement persistent messaging and graceful draining
Add shared sessions, cached message history and transactional idempotency backed by PostgreSQL. Return readiness 503 during draining and finish in-flight requests before closing dependencies.
2026-10-29 11:46:28 +03:00

67 lines
2.1 KiB
TypeScript

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<void>;
private httpClosing?: Promise<undefined>;
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<void> {
return (this.closing ??= this.drainAndClose());
}
override close(): Promise<undefined> {
return (this.httpClosing ??= super.close());
}
private async drainAndClose(): Promise<void> {
this.draining = true;
if (this.drainDelayMs > 0) {
await new Promise<void>((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();
});
}