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:
2026-11-09 16:44:21 +03:00
parent 470d9d6f1e
commit 6889e77ab4
203 changed files with 27707 additions and 13 deletions
@@ -0,0 +1,10 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import type { User } from '../../users/user.js';
import { FastifyRequest } from 'fastify';
export const CurrentUser = createParamDecorator(
(_data: unknown, context: ExecutionContext): User => {
const request = context.switchToHttp().getRequest<FastifyRequest>();
return request.currentUser!;
},
);
+85
View File
@@ -0,0 +1,85 @@
import {
CanActivate,
ExecutionContext,
Injectable,
ServiceUnavailableException,
UnauthorizedException,
} from '@nestjs/common';
import type { FastifyRequest } from 'fastify';
import type { User } from '../../users/user.js';
import { RedisClient } from '../../redis/redis.client.js';
import { UsersService } from '../../users/users.service.js';
import { MetricsService } from '../../metrics/metrics.service.js';
@Injectable()
export class CurrentUserGuard implements CanActivate {
constructor(
private readonly redis: RedisClient,
private readonly users: UsersService,
private readonly metrics: MetricsService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<FastifyRequest>();
const authorization = request.headers.authorization;
if (
typeof authorization !== 'string' ||
!/^Bearer\s+[^\s]+$/u.test(authorization)
) {
throw new UnauthorizedException({
message: 'Unauthorized',
challenge: 'Bearer realm="messenger"',
});
}
let session: string | null;
try {
this.metrics.increment('session_get');
session = await this.redis.get(
`session:${authorization.slice(7).trim()}`,
);
} catch {
throw new ServiceUnavailableException('Session store unavailable');
}
if (!session)
throw new UnauthorizedException({
message: 'Unauthorized',
challenge: 'Bearer realm="messenger"',
});
let userId: string;
try {
const parsed: unknown = JSON.parse(session);
if (
typeof parsed !== 'object' ||
parsed === null ||
!('user_id' in parsed) ||
typeof parsed.user_id !== 'string' ||
!('expires_at' in parsed) ||
typeof parsed.expires_at !== 'string' ||
!/^(?:\d{4})-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/u.test(
parsed.expires_at,
)
)
throw new Error('invalid session');
const expiresAt = Date.parse(parsed.expires_at);
if (!Number.isFinite(expiresAt) || Date.now() >= expiresAt)
throw new Error('expired session');
userId = parsed.user_id;
} catch {
throw new UnauthorizedException({
message: 'Unauthorized',
challenge: 'Bearer realm="messenger"',
});
}
let user: User | undefined;
try {
user = await this.users.findById(userId);
} catch {
throw new ServiceUnavailableException(
'Authentication service unavailable',
);
}
if (!user) throw new UnauthorizedException();
request.currentUser = user;
return true;
}
}
+7
View File
@@ -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);
}
}
+85
View File
@@ -0,0 +1,85 @@
import { BadRequestException } from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { describe, expect, it } from 'vitest';
import { decodeCursor, encodeCursor } from './cursor.js';
const scope = 'messages:6f1c2a3e-1111-4222-8333-444455556666';
function encode(createdAt: string, cursorScope = scope): string {
return encodeCursor({
scope: cursorScope,
created_at: createdAt,
id: randomUUID(),
});
}
describe('decodeCursor', () => {
it('accepts valid instants and normalizes them to canonical milliseconds', () => {
const accepted: Array<[string, string]> = [
['2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z'],
['2026-01-01T00:00:00Z', '2026-01-01T00:00:00.000Z'],
['2026-01-01T00:00:00.999999Z', '2026-01-01T00:00:00.999Z'],
['2024-02-29T23:59:59.000Z', '2024-02-29T23:59:59.000Z'],
['2026-12-31T23:59:59.999Z', '2026-12-31T23:59:59.999Z'],
];
for (const [createdAt, expected] of accepted) {
const decoded = decodeCursor(encode(createdAt), scope);
expect(decoded.created_at).toBe(expected);
expect(decoded.scope).toBe(scope);
}
});
it('rejects calendar dates that the platform parser rolls over', () => {
// 2026-02-31 would silently become 2026-03-03 and then fail inside SQL.
for (const createdAt of [
'2026-02-31T00:00:00.000Z',
'2025-02-29T00:00:00.000Z',
'2026-04-31T00:00:00.000Z',
'2026-06-31T12:00:00.000Z',
]) {
expect(() => decodeCursor(encode(createdAt), scope)).toThrow(
BadRequestException,
);
}
});
it('rejects out-of-range and malformed timestamps', () => {
for (const createdAt of [
'2026-01-01T24:00:00.000Z',
'2026-01-01T00:00:60.000Z',
'2026-13-01T00:00:00.000Z',
'2026-00-01T00:00:00.000Z',
'2026-01-01T00:00:00',
'2026-01-01T00:00:00+02:00',
'2026-1-1T00:00:00.000Z',
'2026-01-01',
'not-a-timestamp',
]) {
expect(() => decodeCursor(encode(createdAt), scope)).toThrow(
BadRequestException,
);
}
});
it('rejects a cursor from another scope, a malformed id, and non-cursor input', () => {
expect(() =>
decodeCursor(
encode('2026-01-01T00:00:00.000Z', 'messages:other'),
scope,
),
).toThrow(BadRequestException);
expect(() =>
decodeCursor(
encodeCursor({
scope,
created_at: '2026-01-01T00:00:00.000Z',
id: 'not-a-uuid',
}),
scope,
),
).toThrow(BadRequestException);
expect(() => decodeCursor('not-a-cursor', scope)).toThrow(
BadRequestException,
);
});
});
+54
View File
@@ -0,0 +1,54 @@
import { BadRequestException } from '@nestjs/common';
import { isValid, parseISO } from 'date-fns';
export type Cursor = {
scope: string;
created_at: string;
id: string;
};
// Format check for the canonical API shape: `Date.prototype.toISOString()` with
// optional fractional seconds. Explicit ranges reject values such as 24:00:00.
// Calendar validity (2026-02-31, 2025-02-29, 2026-04-31) is checked by
// date-fns `parseISO`, which refuses impossible dates that the platform parser
// would silently roll over into another day.
const CURSOR_TIMESTAMP =
/^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?Z$/u;
export function encodeCursor(cursor: Cursor): string {
return Buffer.from(JSON.stringify(cursor), 'utf8').toString('base64url');
}
export function decodeCursor(value: string, expectedScope: string): Cursor {
try {
const parsed: unknown = JSON.parse(
Buffer.from(value, 'base64url').toString('utf8'),
);
if (
typeof parsed !== 'object' ||
parsed === null ||
!('scope' in parsed) ||
!('created_at' in parsed) ||
!('id' in parsed) ||
typeof parsed.scope !== 'string' ||
typeof parsed.created_at !== 'string' ||
typeof parsed.id !== 'string' ||
parsed.scope !== expectedScope ||
!/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu.test(
parsed.id,
) ||
!CURSOR_TIMESTAMP.test(parsed.created_at)
)
throw new Error('invalid cursor');
const instant = parseISO(parsed.created_at);
if (!isValid(instant)) throw new Error('invalid cursor');
return {
scope: parsed.scope,
created_at: instant.toISOString(),
id: parsed.id,
};
} catch {
throw new BadRequestException('Invalid cursor');
}
}
+4
View File
@@ -0,0 +1,4 @@
export type Page<T> = {
items: T[];
next_cursor: string | null;
};
@@ -0,0 +1,59 @@
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { HttpAdapterHost } from '@nestjs/core';
import { randomUUID } from 'node:crypto';
import { finalize, Observable } from 'rxjs';
import type { AppConfig } from '../../config/app-config.schema.js';
import { resolveInstanceId } from '../../config/instance-id.js';
import { MetricsService } from '../../metrics/metrics.service.js';
type RequestWithId = { requestId?: string };
@Injectable()
export class RequestIdInterceptor implements NestInterceptor {
// Resolved once: the identity must be stable for the whole process lifetime,
// otherwise a client cannot tell whether it moved to another replica.
private readonly instanceId: string;
constructor(
private readonly adapterHost: HttpAdapterHost,
private readonly metrics: MetricsService,
config: ConfigService<AppConfig>,
) {
this.instanceId = resolveInstanceId(config);
}
intercept(
context: ExecutionContext,
next: CallHandler,
): Observable<unknown> {
const request = context.switchToHttp().getRequest<RequestWithId>();
const response = context.switchToHttp().getResponse<unknown>();
const requestId = randomUUID();
const startedAt = performance.now();
request.requestId = requestId;
this.adapterHost.httpAdapter.setHeader(
response,
'X-Request-Id',
requestId,
);
this.adapterHost.httpAdapter.setHeader(
response,
'X-Instance-Id',
this.instanceId,
);
this.metrics.increment('request_count');
return next
.handle()
.pipe(
finalize(() =>
this.metrics.observeLatency(performance.now() - startedAt),
),
);
}
}
@@ -0,0 +1,43 @@
import { validate } from 'class-validator';
import { describe, expect, it } from 'vitest';
import { CodePointLength } from './code-point-length.js';
class Sample {
@CodePointLength(3, 5)
value!: string;
}
async function fails(value: unknown): Promise<boolean> {
const sample = new Sample();
(sample as { value: unknown }).value = value;
const errors = await validate(sample);
return errors.length > 0;
}
describe('CodePointLength', () => {
it('counts Unicode code points instead of UTF-16 units', async () => {
// '🔐' is one code point but two UTF-16 units.
expect(await fails('🔐🔐')).toBe(true);
expect(await fails('🔐🔐🔐')).toBe(false);
expect(await fails('🔐🔐🔐🔐🔐')).toBe(false);
expect(await fails('🔐🔐🔐🔐🔐🔐')).toBe(true);
// Combining marks are separate code points, not grapheme clusters:
// three 'é' sequences are six code points and exceed the maximum.
expect(await fails('e\u0301e\u0301')).toBe(false);
expect(await fails('e\u0301e\u0301e\u0301')).toBe(true);
});
it('applies to BMP text boundaries', async () => {
expect(await fails('ab')).toBe(true);
expect(await fails('abc')).toBe(false);
expect(await fails('abcde')).toBe(false);
expect(await fails('abcdef')).toBe(true);
});
it('rejects empty and non-string values', async () => {
expect(await fails('')).toBe(true);
expect(await fails(undefined)).toBe(true);
expect(await fails(12345)).toBe(true);
expect(await fails(['a', 'b', 'c'])).toBe(true);
});
});
@@ -0,0 +1,38 @@
import {
registerDecorator,
ValidatorConstraint,
type ValidationArguments,
type ValidatorConstraintInterface,
} from 'class-validator';
// JSON Schema (and the course contract) measure string lengths in Unicode code
// points, while String.prototype.length counts UTF-16 units: one emoji outside
// the BMP is two units. `@Length` therefore accepted an 11-emoji password
// (22 units) and rejected 4000 emoji (8000 units), so these fields use an
// explicit code-point validator instead.
@ValidatorConstraint({ name: 'codePointLength', async: false })
class CodePointLengthConstraint implements ValidatorConstraintInterface {
validate(value: unknown, args: ValidationArguments): boolean {
const [min, max] = args.constraints as [number, number];
if (typeof value !== 'string') return false;
const length = [...value].length;
return length >= min && length <= max;
}
defaultMessage(args: ValidationArguments): string {
const [min, max] = args.constraints as [number, number];
return `${args.property} must be between ${min} and ${max} code points`;
}
}
export function CodePointLength(min: number, max: number): PropertyDecorator {
return (target, propertyKey) => {
registerDecorator({
name: 'codePointLength',
target: target.constructor,
propertyName: String(propertyKey),
constraints: [min, max],
validator: CodePointLengthConstraint,
});
};
}