187 lines
6.0 KiB
TypeScript
187 lines
6.0 KiB
TypeScript
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 { 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,
|
|
) {}
|
|
|
|
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',
|
|
);
|
|
if ([...input.text].every((character) => /\s/u.test(character)))
|
|
throw new BadRequestException('Message text cannot be blank');
|
|
|
|
const path = messagesPath(chatId);
|
|
const fingerprint = idempotencyFingerprint(input);
|
|
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,
|
|
});
|
|
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();
|
|
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');
|
|
return stored.response_body;
|
|
}
|
|
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>;
|
|
}
|
|
}
|