forked from mtusi2026/mtusi2026lab5
feat(attachments): add durable Kafka image processing
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import type { OpenAPIObject } from '@nestjs/swagger';
|
||||
import { completeApiDocument } from './api-document';
|
||||
|
||||
const contract = JSON.parse(
|
||||
readFileSync(join(__dirname, '../../contracts/openapi.json'), 'utf8'),
|
||||
) as OpenAPIObject;
|
||||
|
||||
describe('published OpenAPI document', () => {
|
||||
const generated: OpenAPIObject = {
|
||||
openapi: '3.0.0',
|
||||
info: { title: 'Messenger API', version: '1.4.0' },
|
||||
paths: {
|
||||
'/': { get: { responses: { 200: { description: 'Root endpoint' } } } },
|
||||
},
|
||||
components: { schemas: {} },
|
||||
};
|
||||
for (const [path, item] of Object.entries(contract.paths)) {
|
||||
generated.paths[path] = {};
|
||||
for (const method of ['get', 'post', 'delete'] as const) {
|
||||
if (item[method]) generated.paths[path][method] = { responses: {} };
|
||||
}
|
||||
}
|
||||
const document = completeApiDocument(generated, contract);
|
||||
|
||||
it('documents every contract operation, including all response headers and binary schemas', () => {
|
||||
expect(document.openapi).toBe(contract.openapi);
|
||||
for (const [path, item] of Object.entries(contract.paths)) {
|
||||
for (const method of ['get', 'post', 'delete'] as const) {
|
||||
if (!item[method]) continue;
|
||||
expect(document.paths[path][method]).toEqual({
|
||||
...item[method],
|
||||
security: item[method].security ?? contract.security ?? [],
|
||||
});
|
||||
}
|
||||
}
|
||||
expect(document.components?.schemas).toMatchObject(
|
||||
contract.components!.schemas!,
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves extra endpoints and leaves the generated document unchanged', () => {
|
||||
expect(document.paths['/']).toEqual(generated.paths['/']);
|
||||
expect(generated.openapi).toBe('3.0.0');
|
||||
expect(
|
||||
generated.paths['/api/v1/attachments/{attachment_id}'].get?.responses,
|
||||
).toEqual({});
|
||||
});
|
||||
|
||||
it('does not advertise contract endpoints missing from the application', () => {
|
||||
const missing = structuredClone(generated);
|
||||
delete missing.paths['/api/v1/attachments/{attachment_id}'];
|
||||
expect(() => completeApiDocument(missing, contract)).toThrow(
|
||||
'Contract endpoint is not implemented',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { OpenAPIObject } from '@nestjs/swagger';
|
||||
|
||||
/** Keep the published API documentation aligned with the lab's normative contract. */
|
||||
export function completeApiDocument(
|
||||
generated: OpenAPIObject,
|
||||
contract: OpenAPIObject,
|
||||
): OpenAPIObject {
|
||||
const paths = { ...generated.paths };
|
||||
const methods = [
|
||||
'get',
|
||||
'put',
|
||||
'post',
|
||||
'delete',
|
||||
'options',
|
||||
'head',
|
||||
'patch',
|
||||
'trace',
|
||||
] as const;
|
||||
for (const [path, item] of Object.entries(contract.paths)) {
|
||||
paths[path] = { ...item };
|
||||
for (const method of methods) {
|
||||
const operation = item[method];
|
||||
if (operation) {
|
||||
if (!generated.paths[path]?.[method]) {
|
||||
throw new Error(
|
||||
`Contract endpoint is not implemented: ${method.toUpperCase()} ${path}`,
|
||||
);
|
||||
}
|
||||
paths[path][method] = {
|
||||
...generated.paths[path]?.[method],
|
||||
...operation,
|
||||
security: operation.security ?? contract.security ?? [],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
...generated,
|
||||
openapi: contract.openapi,
|
||||
info: { ...generated.info, version: contract.info.version },
|
||||
paths,
|
||||
components: {
|
||||
...generated.components,
|
||||
...contract.components,
|
||||
schemas: {
|
||||
...generated.components?.schemas,
|
||||
...contract.components?.schemas,
|
||||
},
|
||||
securitySchemes: {
|
||||
...generated.components?.securitySchemes,
|
||||
...contract.components?.securitySchemes,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import {
|
||||
HttpException,
|
||||
HttpExceptionOptions,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
|
||||
export class ApiException extends HttpException {
|
||||
constructor(
|
||||
status: HttpStatus,
|
||||
code: string,
|
||||
message: string,
|
||||
options?: HttpExceptionOptions,
|
||||
) {
|
||||
super({ code, message }, status, options);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import type { FastifyReply, FastifyRequest } from 'fastify';
|
||||
import { Prisma } from '../../generated/prisma/client';
|
||||
import { ApiException } from '../exceptions/api.exception';
|
||||
import { AuthException } from '../../Auth/auth.exception';
|
||||
|
||||
interface ExceptionPayload {
|
||||
code?: unknown;
|
||||
}
|
||||
|
||||
const defaultCodes: Partial<Record<HttpStatus, string>> = {
|
||||
[HttpStatus.BAD_REQUEST]: 'invalid_request',
|
||||
[HttpStatus.UNAUTHORIZED]: 'unauthorized',
|
||||
[HttpStatus.FORBIDDEN]: 'forbidden',
|
||||
[HttpStatus.NOT_FOUND]: 'not_found',
|
||||
[HttpStatus.CONFLICT]: 'conflict',
|
||||
[HttpStatus.PAYLOAD_TOO_LARGE]: 'payload_too_large',
|
||||
[HttpStatus.UNSUPPORTED_MEDIA_TYPE]: 'unsupported_media_type',
|
||||
[HttpStatus.TOO_MANY_REQUESTS]: 'rate_limited',
|
||||
[HttpStatus.SERVICE_UNAVAILABLE]: 'unavailable',
|
||||
};
|
||||
|
||||
const defaultMessages: Partial<Record<HttpStatus, string>> = {
|
||||
[HttpStatus.BAD_REQUEST]: 'Некорректный запрос',
|
||||
[HttpStatus.UNAUTHORIZED]: 'Требуется авторизация',
|
||||
[HttpStatus.FORBIDDEN]: 'Доступ запрещён',
|
||||
[HttpStatus.NOT_FOUND]: 'Ресурс не найден',
|
||||
[HttpStatus.METHOD_NOT_ALLOWED]: 'Метод не поддерживается',
|
||||
[HttpStatus.CONFLICT]: 'Конфликт данных',
|
||||
[HttpStatus.PAYLOAD_TOO_LARGE]: 'Тело запроса слишком большое',
|
||||
[HttpStatus.UNSUPPORTED_MEDIA_TYPE]: 'Неподдерживаемый формат данных',
|
||||
[HttpStatus.TOO_MANY_REQUESTS]: 'Слишком много запросов',
|
||||
[HttpStatus.INTERNAL_SERVER_ERROR]: 'Внутренняя ошибка сервера',
|
||||
[HttpStatus.SERVICE_UNAVAILABLE]: 'Сервис временно недоступен',
|
||||
};
|
||||
|
||||
const databaseUnavailableCodes = new Set([
|
||||
'P1000',
|
||||
'P1001',
|
||||
'P1002',
|
||||
'P1008',
|
||||
'P1017',
|
||||
'P2024',
|
||||
'P2037',
|
||||
'ECONNREFUSED',
|
||||
'ECONNRESET',
|
||||
'ETIMEDOUT',
|
||||
'EPIPE',
|
||||
'ENOTFOUND',
|
||||
'EAI_AGAIN',
|
||||
'EACCES',
|
||||
'08000',
|
||||
'08001',
|
||||
'08003',
|
||||
'08004',
|
||||
'08006',
|
||||
'53300',
|
||||
'57P01',
|
||||
'57P02',
|
||||
'57P03',
|
||||
'57014',
|
||||
]);
|
||||
const driverTimeoutMessages = [
|
||||
'Query read timeout',
|
||||
'timeout exceeded when trying to connect',
|
||||
'Connection terminated unexpectedly',
|
||||
'Connection terminated due to connection timeout',
|
||||
];
|
||||
|
||||
function databaseUnavailable(exception: unknown): boolean {
|
||||
if (exception instanceof Prisma.PrismaClientInitializationError) return true;
|
||||
if (exception instanceof HttpException || !(exception instanceof Error))
|
||||
return false;
|
||||
const error = exception as Error & { code?: unknown };
|
||||
if (
|
||||
typeof error.code === 'string' &&
|
||||
databaseUnavailableCodes.has(error.code)
|
||||
)
|
||||
return true;
|
||||
if (exception instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
const originalCode = exception.meta?.code;
|
||||
if (
|
||||
typeof originalCode === 'string' &&
|
||||
databaseUnavailableCodes.has(originalCode)
|
||||
)
|
||||
return true;
|
||||
const adapter = exception.meta?.driverAdapterError;
|
||||
if (adapter !== null && typeof adapter === 'object' && 'cause' in adapter) {
|
||||
const cause = adapter.cause;
|
||||
if (cause !== null && typeof cause === 'object') {
|
||||
if ('kind' in cause && cause.kind === 'ConnectionClosed') return true;
|
||||
if (
|
||||
'originalCode' in cause &&
|
||||
typeof cause.originalCode === 'string' &&
|
||||
databaseUnavailableCodes.has(cause.originalCode)
|
||||
)
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return driverTimeoutMessages.some((message) =>
|
||||
exception.message.includes(message),
|
||||
);
|
||||
}
|
||||
|
||||
@Catch()
|
||||
export class AllExceptionsFilter implements ExceptionFilter {
|
||||
catch(exception: unknown, host: ArgumentsHost): void {
|
||||
if (databaseUnavailable(exception)) {
|
||||
exception = new ApiException(
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
'unavailable',
|
||||
'База данных недоступна',
|
||||
);
|
||||
}
|
||||
const context = host.switchToHttp();
|
||||
const request = context.getRequest<FastifyRequest>();
|
||||
const response = context.getResponse<FastifyReply>();
|
||||
if (exception instanceof AuthException) {
|
||||
void response.header('WWW-Authenticate', exception.challenge);
|
||||
}
|
||||
|
||||
const status =
|
||||
exception instanceof HttpException
|
||||
? exception.getStatus()
|
||||
: exception instanceof Error &&
|
||||
'statusCode' in exception &&
|
||||
typeof exception.statusCode === 'number' &&
|
||||
[400, 413, 415].includes(exception.statusCode)
|
||||
? exception.statusCode
|
||||
: HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
const payload =
|
||||
exception instanceof HttpException ? exception.getResponse() : undefined;
|
||||
if (status === HttpStatus.TOO_MANY_REQUESTS)
|
||||
void response.header('Retry-After', '1');
|
||||
const { code, message } = this.extractError(status, payload);
|
||||
const requestId = request.id;
|
||||
|
||||
if (status >= HttpStatus.INTERNAL_SERVER_ERROR) {
|
||||
request.log.error(
|
||||
{ err: exception, status, requestId },
|
||||
'Request failed',
|
||||
);
|
||||
}
|
||||
|
||||
void response.status(status).send({
|
||||
error: { code, message, request_id: requestId },
|
||||
});
|
||||
}
|
||||
|
||||
private extractError(
|
||||
status: HttpStatus,
|
||||
payload: string | object | undefined,
|
||||
): { code: string; message: string } {
|
||||
if (status === HttpStatus.INTERNAL_SERVER_ERROR) {
|
||||
return {
|
||||
code: 'internal_error',
|
||||
message: defaultMessages[status] ?? 'Ошибка сервера',
|
||||
};
|
||||
}
|
||||
|
||||
const body = (
|
||||
payload !== null && typeof payload === 'object' ? payload : {}
|
||||
) as ExceptionPayload;
|
||||
|
||||
return {
|
||||
code:
|
||||
typeof body.code === 'string'
|
||||
? body.code
|
||||
: (defaultCodes[status] ?? 'http_error'),
|
||||
message:
|
||||
defaultMessages[status] ??
|
||||
(status >= HttpStatus.INTERNAL_SERVER_ERROR
|
||||
? 'Ошибка сервера'
|
||||
: 'Ошибка запроса'),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { IncomingMessage } from 'node:http';
|
||||
import { PassThrough } from 'node:stream';
|
||||
import { setImmediate as tick } from 'node:timers/promises';
|
||||
import { drainRejectedBody } from './drain-rejected-body';
|
||||
|
||||
describe('bounded discard of rejected upload bodies', () => {
|
||||
it('waits for the complete body before releasing the error response', async () => {
|
||||
const body = new PassThrough();
|
||||
const done = jest.fn();
|
||||
const result = new Promise<boolean>((resolve) =>
|
||||
drainRejectedBody(
|
||||
body as unknown as IncomingMessage,
|
||||
100,
|
||||
1000,
|
||||
(consumed) => {
|
||||
done(consumed);
|
||||
resolve(consumed);
|
||||
},
|
||||
),
|
||||
);
|
||||
body.write('first');
|
||||
await tick();
|
||||
expect(done).not.toHaveBeenCalled();
|
||||
body.end('last');
|
||||
expect(await result).toBe(true);
|
||||
expect(body.readableEnded).toBe(true);
|
||||
expect(done).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('stops draining beyond its byte budget', async () => {
|
||||
const body = new PassThrough();
|
||||
try {
|
||||
const result = new Promise<boolean>((resolve) =>
|
||||
drainRejectedBody(body as unknown as IncomingMessage, 4, 1000, resolve),
|
||||
);
|
||||
body.write('12345');
|
||||
expect(await result).toBe(false);
|
||||
expect(body.isPaused()).toBe(true);
|
||||
} finally {
|
||||
body.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
it('releases a stalled rejected request when its remaining deadline expires', async () => {
|
||||
const body = new PassThrough();
|
||||
try {
|
||||
const result = new Promise<boolean>((resolve) =>
|
||||
drainRejectedBody(body as unknown as IncomingMessage, 100, 25, resolve),
|
||||
);
|
||||
expect(await result).toBe(false);
|
||||
expect(body.isPaused()).toBe(true);
|
||||
} finally {
|
||||
body.destroy();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { IncomingMessage } from 'node:http';
|
||||
|
||||
/** Discard a bounded remainder before sending an early 413 through a streaming proxy. */
|
||||
export function drainRejectedBody(
|
||||
raw: IncomingMessage,
|
||||
maxBytes: number,
|
||||
timeoutMs: number,
|
||||
done: (consumed: boolean) => void,
|
||||
) {
|
||||
let received = 0;
|
||||
let finished = false;
|
||||
const finish = (consumed: boolean) => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
clearTimeout(timer);
|
||||
raw.removeListener('data', onData);
|
||||
raw.removeListener('end', onEnd);
|
||||
raw.removeListener('aborted', onAborted);
|
||||
raw.removeListener('error', onAborted);
|
||||
raw.removeListener('close', onClose);
|
||||
done(consumed);
|
||||
};
|
||||
const onData = (chunk: Buffer) => {
|
||||
received += chunk.length;
|
||||
if (received > maxBytes) {
|
||||
raw.pause();
|
||||
finish(false);
|
||||
}
|
||||
};
|
||||
const onEnd = () => finish(true);
|
||||
const onAborted = () => finish(false);
|
||||
const onClose = () => finish(raw.readableEnded);
|
||||
const timer = setTimeout(() => {
|
||||
raw.pause();
|
||||
finish(false);
|
||||
}, timeoutMs);
|
||||
timer.unref();
|
||||
raw.on('data', onData);
|
||||
raw.once('end', onEnd);
|
||||
raw.once('aborted', onAborted);
|
||||
raw.once('error', onAborted);
|
||||
raw.once('close', onClose);
|
||||
raw.resume();
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { request } from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { DrainingFastifyAdapter } from './fastify-adapter';
|
||||
|
||||
describe('upload body deadline over real HTTP', () => {
|
||||
it('returns 408 for a client that keeps sending and never invokes the handler', async () => {
|
||||
const adapter = new DrainingFastifyAdapter(0, 1000);
|
||||
const server = adapter.getInstance();
|
||||
let calls = 0;
|
||||
server.post('/api/v1/chats/:chat_id/attachments', () => {
|
||||
calls++;
|
||||
return {};
|
||||
});
|
||||
await server.listen({ host: '127.0.0.1', port: 0 });
|
||||
let timer: ReturnType<typeof setInterval> | undefined;
|
||||
let watchdog: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
const port = (server.server.address() as AddressInfo).port;
|
||||
const result = await new Promise<{
|
||||
status?: number;
|
||||
body: string;
|
||||
id?: string;
|
||||
}>((resolve, reject) => {
|
||||
const client = request(
|
||||
{
|
||||
host: '127.0.0.1',
|
||||
port,
|
||||
method: 'POST',
|
||||
path: '/api/v1/chats/test/attachments',
|
||||
headers: { 'content-type': 'image/png', 'content-length': '10000' },
|
||||
},
|
||||
(response) => {
|
||||
clearInterval(timer);
|
||||
clearTimeout(watchdog);
|
||||
let body = '';
|
||||
response.on('data', (part: Buffer) => {
|
||||
body += part.toString();
|
||||
});
|
||||
response.on('end', () => {
|
||||
client.destroy();
|
||||
resolve({
|
||||
status: response.statusCode,
|
||||
body,
|
||||
id: response.headers['x-request-id'] as string,
|
||||
});
|
||||
});
|
||||
response.on('error', reject);
|
||||
},
|
||||
);
|
||||
client.on('error', reject);
|
||||
watchdog = setTimeout(
|
||||
() => client.destroy(new Error('deadline did not fire')),
|
||||
7000,
|
||||
);
|
||||
client.write('partial');
|
||||
timer = setInterval(() => client.write('x'), 100);
|
||||
});
|
||||
expect(result.status).toBe(408);
|
||||
expect(result.id).toBeTruthy();
|
||||
expect(JSON.parse(result.body)).toMatchObject({
|
||||
error: { code: 'invalid_request', request_id: result.id },
|
||||
});
|
||||
expect(calls).toBe(0);
|
||||
} finally {
|
||||
clearInterval(timer);
|
||||
clearTimeout(watchdog);
|
||||
await server.close();
|
||||
}
|
||||
}, 15000);
|
||||
|
||||
it('clears the reception deadline before a completed body is processed', async () => {
|
||||
const adapter = new DrainingFastifyAdapter(0, 1000);
|
||||
const server = adapter.getInstance();
|
||||
server.post('/api/v1/chats/:chat_id/attachments', async () => {
|
||||
await delay(1200);
|
||||
return { stored: true };
|
||||
});
|
||||
try {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/chats/test/attachments',
|
||||
headers: { 'content-type': 'image/png' },
|
||||
payload: Buffer.from('complete'),
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json()).toEqual({ stored: true });
|
||||
} finally {
|
||||
await server.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,175 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { MAX_UPLOAD_BYTES } from '../../Attachment/attachment.service';
|
||||
import { profileUpload } from './upload-memory-profile';
|
||||
import { drainRejectedBody } from './drain-rejected-body';
|
||||
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>;
|
||||
private readonly uploadDeadlines = new WeakMap<object, number>();
|
||||
|
||||
constructor(
|
||||
private readonly drainDelayMs: number,
|
||||
uploadBodyTimeoutMs = Number(process.env.UPLOAD_BODY_TIMEOUT_MS ?? 15000),
|
||||
) {
|
||||
super({ requestIdHeader, genReqId: () => randomUUID() });
|
||||
this.getInstance().addHook('onRequest', (request, reply, done) => {
|
||||
const path = request.routeOptions.url;
|
||||
const mode =
|
||||
request.method !== 'POST'
|
||||
? undefined
|
||||
: path === '/api/v1/chats/:chat_id/attachments'
|
||||
? 'proxy'
|
||||
: path ===
|
||||
'/api/v1/chats/:chat_id/attachment-uploads/:upload_id/complete'
|
||||
? 'direct'
|
||||
: path === '/api/v1/chats/:chat_id/attachment-uploads'
|
||||
? 'grant'
|
||||
: undefined;
|
||||
if (mode) profileUpload(mode, request.id, reply.raw, done);
|
||||
else done();
|
||||
});
|
||||
if (
|
||||
!Number.isSafeInteger(uploadBodyTimeoutMs) ||
|
||||
uploadBodyTimeoutMs < 1000 ||
|
||||
uploadBodyTimeoutMs > 120000
|
||||
) {
|
||||
throw new Error('UPLOAD_BODY_TIMEOUT_MS must be between 1000 and 120000');
|
||||
}
|
||||
this.getInstance().addHook('onRequest', (request, reply, done) => {
|
||||
if (
|
||||
request.method !== 'POST' ||
|
||||
request.routeOptions.url !== '/api/v1/chats/:chat_id/attachments'
|
||||
) {
|
||||
done();
|
||||
return;
|
||||
}
|
||||
// A total deadline, independent of whether the client keeps sending tiny chunks.
|
||||
// Clear it when reception finishes; decoding and persistence have separate budgets.
|
||||
const raw = request.raw;
|
||||
this.uploadDeadlines.set(raw, Date.now() + uploadBodyTimeoutMs);
|
||||
const cleanup = () => {
|
||||
this.uploadDeadlines.delete(raw);
|
||||
clearTimeout(timer);
|
||||
raw.removeListener('end', cleanup);
|
||||
raw.removeListener('close', cleanup);
|
||||
reply.raw.removeListener('finish', cleanup);
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
cleanup();
|
||||
if (
|
||||
raw.complete ||
|
||||
reply.sent ||
|
||||
raw.destroyed ||
|
||||
reply.statusCode === 413
|
||||
)
|
||||
return;
|
||||
// Let HTTP close after flushing the response. Destroying the request here can
|
||||
// reset the TCP connection before a still-writing client receives the 408.
|
||||
void reply
|
||||
.code(408)
|
||||
.header('connection', 'close')
|
||||
.header(requestIdHeader, request.id)
|
||||
.header(instanceIdHeader, instanceId)
|
||||
.send({
|
||||
error: {
|
||||
code: 'invalid_request',
|
||||
message: 'Истёк срок приёма изображения',
|
||||
request_id: request.id,
|
||||
},
|
||||
});
|
||||
}, uploadBodyTimeoutMs);
|
||||
timer.unref();
|
||||
raw.once('end', cleanup);
|
||||
raw.once('close', cleanup);
|
||||
reply.raw.once('finish', cleanup);
|
||||
done();
|
||||
});
|
||||
this.getInstance().addContentTypeParser(
|
||||
['image/png', 'image/jpeg', 'application/octet-stream'],
|
||||
{ parseAs: 'buffer', bodyLimit: MAX_UPLOAD_BYTES },
|
||||
(_request, body, done) => done(null, body),
|
||||
);
|
||||
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');
|
||||
if (
|
||||
reply.statusCode === 413 &&
|
||||
request.routeOptions.url === '/api/v1/chats/:chat_id/attachments' &&
|
||||
!request.raw.readableEnded &&
|
||||
!request.raw.destroyed
|
||||
) {
|
||||
const deadline =
|
||||
this.uploadDeadlines.get(request.raw) ??
|
||||
Date.now() + uploadBodyTimeoutMs;
|
||||
drainRejectedBody(
|
||||
request.raw,
|
||||
MAX_UPLOAD_BYTES + 1048576,
|
||||
Math.max(1, deadline - Date.now()),
|
||||
(consumed) => {
|
||||
if (!consumed) void reply.header('connection', 'close');
|
||||
done(null, payload);
|
||||
},
|
||||
);
|
||||
return;
|
||||
}
|
||||
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,
|
||||
uploadBodyTimeoutMs?: number,
|
||||
): DrainingFastifyAdapter {
|
||||
return new DrainingFastifyAdapter(drainDelayMs, uploadBodyTimeoutMs);
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
import { hostname } from 'node:os';
|
||||
import { performance } from 'node:perf_hooks';
|
||||
import type { ServerResponse } from 'node:http';
|
||||
import sharp from 'sharp';
|
||||
|
||||
type Memory = ReturnType<typeof process.memoryUsage>;
|
||||
type Stage = {
|
||||
name: string;
|
||||
startedMs: number;
|
||||
durationMs: number;
|
||||
before: Memory;
|
||||
after: Memory;
|
||||
peak: Memory;
|
||||
samples: number;
|
||||
maxSampleGapMs: number;
|
||||
sharpBefore: ReturnType<typeof sharp.cache>;
|
||||
sharpAfter: ReturnType<typeof sharp.cache>;
|
||||
};
|
||||
type Context = {
|
||||
started: number;
|
||||
stages: Stage[];
|
||||
current: Stage;
|
||||
lastSample: number;
|
||||
closed: boolean;
|
||||
};
|
||||
const contexts = new AsyncLocalStorage<Context>();
|
||||
|
||||
function sample(context: Context) {
|
||||
const now = performance.now();
|
||||
const memory = process.memoryUsage();
|
||||
const stage = context.current;
|
||||
for (const key of Object.keys(memory) as (keyof Memory)[])
|
||||
stage.peak[key] = Math.max(stage.peak[key], memory[key]);
|
||||
stage.after = memory;
|
||||
stage.samples++;
|
||||
stage.maxSampleGapMs = Math.max(
|
||||
stage.maxSampleGapMs,
|
||||
now - context.lastSample,
|
||||
);
|
||||
context.lastSample = now;
|
||||
stage.durationMs = now - context.started - stage.startedMs;
|
||||
return memory;
|
||||
}
|
||||
|
||||
function stage(name: string, startedMs: number): Stage {
|
||||
const memory = process.memoryUsage();
|
||||
const cache = sharp.cache();
|
||||
return {
|
||||
name,
|
||||
startedMs,
|
||||
durationMs: 0,
|
||||
before: memory,
|
||||
after: memory,
|
||||
peak: { ...memory },
|
||||
samples: 0,
|
||||
maxSampleGapMs: 0,
|
||||
sharpBefore: cache,
|
||||
sharpAfter: cache,
|
||||
};
|
||||
}
|
||||
|
||||
/** Profiling is opt-in. Contains numeric metrics and a request ID, never URLs or payloads. */
|
||||
export function profileUpload(
|
||||
mode: 'proxy' | 'direct' | 'grant',
|
||||
requestId: string,
|
||||
response: ServerResponse,
|
||||
done: () => void,
|
||||
) {
|
||||
if (process.env.UPLOAD_MEMORY_PROFILE !== '1') return done();
|
||||
const now = performance.now();
|
||||
const context: Context = {
|
||||
started: now,
|
||||
stages: [],
|
||||
current: stage('receive_and_authenticate', 0),
|
||||
lastSample: now,
|
||||
closed: false,
|
||||
};
|
||||
const timer = setInterval(() => sample(context), 20);
|
||||
timer.unref();
|
||||
const finish = () => {
|
||||
if (context.closed) return;
|
||||
context.closed = true;
|
||||
clearInterval(timer);
|
||||
sample(context);
|
||||
context.current.sharpAfter = sharp.cache();
|
||||
context.stages.push(context.current);
|
||||
console.log(
|
||||
'UPLOAD_MEMORY_PROFILE ' +
|
||||
JSON.stringify({
|
||||
mode,
|
||||
requestId,
|
||||
instance: hostname(),
|
||||
pid: process.pid,
|
||||
status: response.statusCode,
|
||||
finished: response.writableFinished,
|
||||
intervalMs: 20,
|
||||
durationMs: performance.now() - context.started,
|
||||
stages: context.stages,
|
||||
}),
|
||||
);
|
||||
};
|
||||
response.once('finish', finish);
|
||||
response.once('close', finish);
|
||||
contexts.run(context, done);
|
||||
}
|
||||
|
||||
export function profileStage(name: string) {
|
||||
const context = contexts.getStore();
|
||||
if (!context || context.closed || context.stages.length >= 64) return;
|
||||
sample(context);
|
||||
context.current.sharpAfter = sharp.cache();
|
||||
context.stages.push(context.current);
|
||||
context.current = stage(name, performance.now() - context.started);
|
||||
context.lastSample = performance.now();
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { ApiException } from './exceptions/api.exception';
|
||||
import { HttpStatus } from '@nestjs/common';
|
||||
|
||||
export const uuidPattern =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
export function invalidRequest(message: string): never {
|
||||
throw new ApiException(HttpStatus.BAD_REQUEST, 'invalid_request', message);
|
||||
}
|
||||
|
||||
export function objectBody(
|
||||
value: unknown,
|
||||
keys: string[],
|
||||
): Record<string, unknown> {
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||
return invalidRequest('Ожидается JSON-объект');
|
||||
}
|
||||
const body = value as Record<string, unknown>;
|
||||
if (Object.keys(body).some((key) => !keys.includes(key))) {
|
||||
return invalidRequest('Неизвестное поле запроса');
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
export function requiredText(
|
||||
value: unknown,
|
||||
field: string,
|
||||
max: number,
|
||||
): string {
|
||||
if (typeof value !== 'string' || value.trim().length === 0) {
|
||||
return invalidRequest(`Некорректное поле ${field}`);
|
||||
}
|
||||
let codePoints = 0;
|
||||
for (const _character of value) codePoints++;
|
||||
if (codePoints > max) return invalidRequest(`Некорректное поле ${field}`);
|
||||
return value;
|
||||
}
|
||||
|
||||
export function uuid(value: unknown, field: string): string {
|
||||
if (typeof value !== 'string' || !uuidPattern.test(value)) {
|
||||
return invalidRequest(`Некорректное поле ${field}`);
|
||||
}
|
||||
return value.toLowerCase();
|
||||
}
|
||||
|
||||
export function pageLimit(value: unknown): number {
|
||||
if (value === undefined) return 50;
|
||||
if (typeof value !== 'string' || !/^[1-9]\d*$/.test(value)) {
|
||||
return invalidRequest('Некорректный limit');
|
||||
}
|
||||
const limit = Number(value);
|
||||
if (limit > 100) return invalidRequest('Некорректный limit');
|
||||
return limit;
|
||||
}
|
||||
Reference in New Issue
Block a user