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,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,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user