lab5: базовый коммит из lab4 (abba248)

Перенесено дерево lab4 целиком: NestJS-приложение с вложениями и S3,
Dockerfile, compose.yaml, infra/{haproxy,minio}, стендовые скрипты,
scripts/lab4, evidence/lab4 и contracts/extensions.openapi.json.

Задание lab5 оставлено своим: README, REPORT, COURSE, lab.json,
contracts/{openapi,infrastructure,jobs.schema,attachment-states,examples},
tests, compose.example.yaml, .github/pull_request_template.md.

Адаптации при переносе:
- docker-проект mtusi-lab4 -> mtusi-lab5 и тег образа mtusi-messenger:lab5,
  чтобы тома и контейнеры не пересекались с lab4 (scripts/stop-one.sh:
  LAB_PROJECT вместо LAB4_PROJECT);
- Makefile: цели lab5 сохранены, добавлены стендовые (stand-up/down,
  wait-ready, init-env, test-e2e, test-dependencies, s3-security,
  consistency, bench);
- .env.example: реальные переменные приложения и стенда lab4 (без них
  compose.yaml не поднимается) + блок lab5 (BROKER_URL_FILE, WORKER_*).
This commit is contained in:
2026-11-04 23:44:11 +03:00
parent 276dbdad8a
commit 1982bdb690
153 changed files with 21742 additions and 11 deletions
+203
View File
@@ -0,0 +1,203 @@
import {
BadRequestException,
ConflictException,
Injectable,
Logger,
NotFoundException,
ServiceUnavailableException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { decodeCursor, encodeCursor } from '../common/http/cursor.js';
import type { Page } from '../common/http/page.js';
import type { AppConfig } from '../config/app-config.schema.js';
import type { User } from '../users/user.js';
import { ChatsService } from '../chats/chats.service.js';
import { AttachmentsRepository } from '../attachments/attachments.repository.js';
import { MetricsService } from '../metrics/metrics.service.js';
import type { CreateMessageDto } from './dto/create-message.dto.js';
import type { Message } from './message.js';
import { MessagesRepository } from './messages.repository.js';
import { MessagesCacheService } from './cache/messages-cache.service.js';
import {
IDEMPOTENCY_KEY_PATTERN,
idempotencyFingerprint,
messagesPath,
} from './idempotency/idempotency.js';
import { IdempotencyRepository } from './idempotency/idempotency.repository.js';
// Один повтор нужен только для просроченного ключа: запись удаляется, и тот же
// оператор занимает ключ заново. Больше трёх кругов означает, что ключ
// перехватывают параллельные запросы, и честнее вернуть 503, чем крутиться.
const MAX_CLAIM_ATTEMPTS = 3;
const PURGE_EVERY_REQUESTS = 512;
@Injectable()
export class MessagesService {
private readonly logger = new Logger(MessagesService.name);
private requestsSincePurge = 0;
constructor(
private readonly messagesRepository: MessagesRepository,
private readonly chatsService: ChatsService,
private readonly cache: MessagesCacheService,
private readonly idempotency: IdempotencyRepository,
private readonly config: ConfigService<AppConfig>,
private readonly metrics: MetricsService,
private readonly attachments: AttachmentsRepository,
) {}
async create(
chatId: string,
input: CreateMessageDto,
currentUser: User,
rawKey: string | string[] | undefined,
): Promise<Message> {
// Ключ и тело проверяются до обращения к БД: клиентская ошибка не должна
// создавать заявку и не должна зависеть от состояния хранилища.
if (typeof rawKey !== 'string' || !IDEMPOTENCY_KEY_PATTERN.test(rawKey))
throw new BadRequestException('Idempotency-Key header is required');
const ids = input.attachment_ids.map((id) => id.toLowerCase());
if (new Set(ids).size !== ids.length)
throw new BadRequestException('attachment_ids must be unique');
if (
ids.length === 0 &&
[...input.text].every((character) => /\s/u.test(character))
)
throw new BadRequestException('Message text cannot be blank');
const path = messagesPath(chatId);
const fingerprint = idempotencyFingerprint(input.text, ids);
const ttl = this.config.getOrThrow('IDEMPOTENCY_TTL_SECONDS');
for (let attempt = 1; attempt <= MAX_CLAIM_ATTEMPTS; attempt += 1) {
const created = await this.messagesRepository.createOnce({
userId: currentUser.id,
chatId,
path,
key: rawKey,
fingerprint,
text: input.text,
attachmentIds: ids,
});
if (created) {
this.metrics.increment('idempotency.claim');
this.metrics.increment('messages.write');
this.scheduleExpiredPurge();
return created;
}
const stored = await this.idempotency.read(
currentUser.id,
path,
rawKey,
chatId,
ttl,
);
if (!stored) {
// Заявки нет: либо запрос не имеет доступа к чату (404), либо
// чужую заявку сняли между нашими двумя запросами (503).
if (!(await this.idempotency.isMember(chatId, currentUser.id)))
throw new NotFoundException();
// Unknown, foreign-chat or unfinished attachment: not found.
if (
ids.length > 0 &&
!(await this.attachments.allLinkable(chatId, ids))
)
throw new NotFoundException();
this.metrics.increment('idempotency.claim_lost');
throw new ServiceUnavailableException(
'Idempotency key could not be claimed',
);
}
if (stored.expired) {
this.metrics.increment('idempotency.released');
await this.idempotency.forget(
currentUser.id,
path,
rawKey,
ttl,
);
continue;
}
if (stored.request_fingerprint !== fingerprint) {
this.metrics.increment('idempotency.conflict');
throw new ConflictException(
'Idempotency key reused with a different body',
);
}
if (!stored.is_member) throw new NotFoundException();
this.metrics.increment('idempotency.replay');
// Bodies stored before attachments existed carry no attachment_ids.
return {
...stored.response_body,
attachment_ids: stored.response_body.attachment_ids ?? [],
};
}
throw new ServiceUnavailableException(
'Idempotency key could not be claimed',
);
}
// Expired claims are storage hygiene, not part of the request: the pass runs
// outside the request path, at most once per PURGE_EVERY_REQUESTS successful
// writes, and its failure never changes the client's result.
private scheduleExpiredPurge(): void {
this.requestsSincePurge += 1;
if (this.requestsSincePurge < PURGE_EVERY_REQUESTS) return;
this.requestsSincePurge = 0;
const ttl = this.config.getOrThrow('IDEMPOTENCY_TTL_SECONDS');
void this.idempotency
.purgeExpired(ttl)
.then((purged) => {
if (purged > 0) this.metrics.increment('idempotency.purged');
})
.catch((error: unknown) => {
this.metrics.increment('idempotency.purge_error');
this.logger.warn(
`Idempotency purge failed: ${error instanceof Error ? error.message : 'unknown error'}`,
);
});
}
async list(
chatId: string,
currentUser: User,
limit: number,
cursorValue?: string,
): Promise<Page<Message>> {
await this.chatsService.getForUser(chatId, currentUser);
const scope = `messages:${chatId}`;
const cursor = cursorValue
? decodeCursor(cursorValue, scope)
: undefined;
const version = await this.messagesRepository.getVersion(
chatId,
currentUser.id,
);
const page = await this.cache.getOrLoad(
chatId,
version,
cursorValue,
limit,
async () => {
const loaded = await this.messagesRepository.findPage(
chatId,
limit,
cursor,
);
const lastLoaded = loaded.items.at(-1);
return {
items: loaded.items,
next_cursor:
loaded.hasMore && lastLoaded
? encodeCursor({
scope,
created_at: lastLoaded.created_at,
id: lastLoaded.id,
})
: null,
};
},
);
return page as Page<Message>;
}
}