forked from mtusi2026/mtusi2026lab6
lab6: базовый коммит из lab5 (0790599)
Перенесено дерево lab5 целиком: NestJS-приложение (API + worker,
RabbitMQ, outbox, S3), Dockerfile, compose.yaml, infra/{haproxy,minio,
rabbitmq}, стендовые скрипты, scripts/lab4, scripts/lab5,
evidence/lab4, evidence/lab5 и contracts/extensions.openapi.json.
Задание lab6 оставлено своим: README, REPORT, COURSE, lab.json,
contracts/{openapi,infrastructure,jobs.schema,attachment-states,
examples,observability}, tests, compose.example.yaml, infra/otel,
.github/pull_request_template.md.
Адаптации при переносе:
- docker-проект mtusi-lab5 -> mtusi-lab6 и тег образа
mtusi-messenger:lab6 (compose.yaml, scripts/stop-one.sh, .env.example,
infra/README.md), чтобы тома и контейнеры не пересекались с lab5;
- Makefile: цели lab5 сохранены целиком (skeleton lab6 не отличается
от skeleton lab5);
- .env.example: переменные приложения и стенда lab5 + блок lab6
(OTEL_*) из skeleton.
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
export type ApiErrorBody = {
|
||||
error: {
|
||||
code: string;
|
||||
message: string;
|
||||
request_id: string;
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,181 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { HttpAdapterHost } from '@nestjs/core';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type { AppConfig } from '../../config/app-config.schema.js';
|
||||
import { resolveInstanceId } from '../../config/instance-id.js';
|
||||
import type { ApiErrorBody } from './api-error.js';
|
||||
|
||||
type RequestWithId = { requestId?: string; method?: string; url?: string };
|
||||
type ExceptionBody = {
|
||||
message?: unknown;
|
||||
challenge?: unknown;
|
||||
retryAfter?: unknown;
|
||||
};
|
||||
|
||||
// Connection/session loss codes reported by node-postgres and the network layer.
|
||||
const UNAVAILABLE_ERROR_CODES: Record<string, true> = {
|
||||
ECONNREFUSED: true,
|
||||
ECONNRESET: true,
|
||||
ENOTFOUND: true,
|
||||
ETIMEDOUT: true,
|
||||
EPIPE: true,
|
||||
'08000': true,
|
||||
'08001': true,
|
||||
'08003': true,
|
||||
'08004': true,
|
||||
'08006': true,
|
||||
'57P01': true,
|
||||
'57P02': true,
|
||||
'57P03': true,
|
||||
'53300': true,
|
||||
// Transient aborts: the statement was cancelled by statement_timeout, the
|
||||
// transaction was rolled back by a serialization failure or a deadlock. The
|
||||
// work was never confirmed, so callers see a retryable 503 instead of an
|
||||
// internal error. Without this, such an abort would be recorded as the final
|
||||
// result of an idempotent operation.
|
||||
'57014': true,
|
||||
'40001': true,
|
||||
'40P01': true,
|
||||
};
|
||||
|
||||
// Some driver failures carry no `code` at all: node-postgres raises plain errors
|
||||
// when a connection dies or its pool attempt times out, and node-redis reports a
|
||||
// closed socket the same way. Without these patterns a stopped database would
|
||||
// surface as an internal fault instead of a bounded outage.
|
||||
const UNAVAILABLE_ERROR_MESSAGES = [
|
||||
'Connection terminated unexpectedly',
|
||||
'Connection terminated due to connection timeout',
|
||||
'timeout exceeded when trying to connect',
|
||||
'Client has encountered a connection error and is not queryable',
|
||||
'Socket closed unexpectedly',
|
||||
'Connection is closed',
|
||||
];
|
||||
|
||||
function isDependencyOutage(exception: unknown): boolean {
|
||||
if (typeof exception !== 'object' || exception === null) return false;
|
||||
const code = (exception as { code?: unknown }).code;
|
||||
if (typeof code === 'string' && UNAVAILABLE_ERROR_CODES[code] === true)
|
||||
return true;
|
||||
const message = (exception as { message?: unknown }).message;
|
||||
return (
|
||||
typeof message === 'string' &&
|
||||
UNAVAILABLE_ERROR_MESSAGES.some((pattern) => message.includes(pattern))
|
||||
);
|
||||
}
|
||||
|
||||
function errorCodeForStatus(status: number): string {
|
||||
const codes: Record<number, string> = {
|
||||
[HttpStatus.BAD_REQUEST]: 'invalid_request',
|
||||
[HttpStatus.UNAUTHORIZED]: 'unauthorized',
|
||||
[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',
|
||||
};
|
||||
return codes[status] ?? 'internal_error';
|
||||
}
|
||||
|
||||
@Catch()
|
||||
export class ApiExceptionFilter implements ExceptionFilter {
|
||||
private readonly logger = new Logger(ApiExceptionFilter.name);
|
||||
// Guards and pipes run before interceptors, so an error response may be the
|
||||
// first thing the filter writes: it must carry the replica identity too.
|
||||
private readonly instanceId: string;
|
||||
|
||||
constructor(
|
||||
private readonly adapterHost: HttpAdapterHost,
|
||||
config: ConfigService<AppConfig>,
|
||||
) {
|
||||
this.instanceId = resolveInstanceId(config);
|
||||
}
|
||||
|
||||
catch(exception: unknown, host: ArgumentsHost): void {
|
||||
const http = host.switchToHttp();
|
||||
const request = http.getRequest<RequestWithId>();
|
||||
const response = http.getResponse<unknown>();
|
||||
const adapter = this.adapterHost.httpAdapter;
|
||||
const requestId = request.requestId ?? randomUUID();
|
||||
request.requestId = requestId;
|
||||
|
||||
let status = HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
let message = 'Internal server error';
|
||||
let challenge: string | undefined;
|
||||
let retryAfter = 1;
|
||||
if (exception instanceof HttpException) {
|
||||
status = exception.getStatus();
|
||||
const body = exception.getResponse();
|
||||
const details: ExceptionBody =
|
||||
typeof body === 'object' && body !== null
|
||||
? (body as ExceptionBody)
|
||||
: {};
|
||||
const rawMessage =
|
||||
'message' in details ? details.message : undefined;
|
||||
challenge =
|
||||
typeof details.challenge === 'string'
|
||||
? details.challenge
|
||||
: undefined;
|
||||
if (
|
||||
typeof details.retryAfter === 'number' &&
|
||||
Number.isFinite(details.retryAfter) &&
|
||||
details.retryAfter >= 1
|
||||
)
|
||||
retryAfter = Math.ceil(details.retryAfter);
|
||||
message = Array.isArray(rawMessage)
|
||||
? rawMessage.join('; ')
|
||||
: typeof rawMessage === 'string'
|
||||
? rawMessage
|
||||
: 'Request failed';
|
||||
if (status === HttpStatus.NOT_FOUND) message = 'Resource not found';
|
||||
if (status >= HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
message =
|
||||
status === HttpStatus.SERVICE_UNAVAILABLE
|
||||
? 'Service unavailable'
|
||||
: 'Internal server error';
|
||||
} else if (isDependencyOutage(exception)) {
|
||||
// A dropped dependency is a bounded outage, not an internal fault.
|
||||
status = HttpStatus.SERVICE_UNAVAILABLE;
|
||||
message = 'Service unavailable';
|
||||
this.logger.warn(
|
||||
`Dependency outage on ${request.method ?? ''} ${request.url ?? ''}: ${exception instanceof Error ? exception.message : 'unknown error'}`,
|
||||
);
|
||||
} else {
|
||||
this.logger.error(
|
||||
`Unhandled exception on ${request.method ?? ''} ${request.url ?? ''}`,
|
||||
exception instanceof Error
|
||||
? exception.stack
|
||||
: String(exception),
|
||||
);
|
||||
}
|
||||
if (status === HttpStatus.UNAUTHORIZED) {
|
||||
const authChallenge =
|
||||
challenge ??
|
||||
(request.method === 'POST' &&
|
||||
request.url?.startsWith('/api/v1/auth/sessions')
|
||||
? 'Basic realm="messenger", charset="UTF-8"'
|
||||
: 'Bearer realm="messenger"');
|
||||
adapter.setHeader(response, 'WWW-Authenticate', authChallenge);
|
||||
}
|
||||
if (status === HttpStatus.TOO_MANY_REQUESTS)
|
||||
adapter.setHeader(response, 'Retry-After', String(retryAfter));
|
||||
adapter.setHeader(response, 'X-Request-Id', requestId);
|
||||
adapter.setHeader(response, 'X-Instance-Id', this.instanceId);
|
||||
const payload: ApiErrorBody = {
|
||||
error: {
|
||||
code: errorCodeForStatus(status),
|
||||
message,
|
||||
request_id: requestId,
|
||||
},
|
||||
};
|
||||
adapter.reply(response, payload, status);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user