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
+37
View File
@@ -0,0 +1,37 @@
import { ConfigService } from '@nestjs/config';
import { describe, expect, it, vi } from 'vitest';
import { MetricsService } from '../../metrics/metrics.service.js';
import { MessagesCacheService } from './messages-cache.service.js';
describe('MessagesCacheService metrics', () => {
it('records a miss and a hit for a protected page fill', async () => {
const metrics = new MetricsService();
const page = { items: [], next_cursor: null };
const redis = {
get: vi
.fn()
.mockResolvedValueOnce(null)
.mockResolvedValueOnce(null)
.mockResolvedValue(JSON.stringify(page)),
setNxPx: vi.fn().mockResolvedValue(true),
set: vi.fn().mockResolvedValue('OK'),
unlock: vi.fn().mockResolvedValue(1),
};
const config = new ConfigService({
CACHE_MODE: 'protected',
CACHE_LOCK_TTL_MS: 1000,
CACHE_TTL_SECONDS: 30,
});
const service = new MessagesCacheService(
redis as never,
config,
metrics,
);
await service.getOrLoad('chat', 1n, undefined, 50, async () => page);
await service.getOrLoad('chat', 1n, undefined, 50, async () => page);
expect(metrics.snapshot().counters).toMatchObject({
cache_miss: 1,
cache_hit: 1,
});
});
});
+11
View File
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { MessagesCacheService } from './messages-cache.service.js';
import { MetricsModule } from '../../metrics/metrics.module.js';
import { RedisModule } from '../../redis/redis.module.js';
@Module({
imports: [RedisModule, MetricsModule],
providers: [MessagesCacheService],
exports: [MessagesCacheService],
})
export class MessagesCacheModule {}
+72
View File
@@ -0,0 +1,72 @@
import { ConfigService } from '@nestjs/config';
import { describe, expect, it, vi } from 'vitest';
import type { AppConfig } from '../../config/app-config.schema.js';
import type { RedisClient } from '../../redis/redis.client.js';
import { MessagesCacheService } from './messages-cache.service.js';
import { MetricsService } from '../../metrics/metrics.service.js';
function serviceWithRedis(redis: Partial<RedisClient>): MessagesCacheService {
const config = new ConfigService<AppConfig>({
CACHE_MODE: 'protected',
CACHE_LOCK_TTL_MS: 1000,
CACHE_TTL_SECONDS: 30,
CACHE_MISS_DELAY_MS: 0,
});
return new MessagesCacheService(
redis as RedisClient,
config,
new MetricsService(),
);
}
describe('MessagesCacheService fallback', () => {
it('loads from the authoritative source when Redis read fails', async () => {
const load = vi
.fn()
.mockResolvedValue({ items: [{ id: 'db' }], next_cursor: null });
const service = serviceWithRedis({
get: vi.fn().mockRejectedValue(new Error('redis down')),
});
await expect(
service.getOrLoad('chat', 1n, undefined, 50, load),
).resolves.toEqual({
items: [{ id: 'db' }],
next_cursor: null,
});
expect(load).toHaveBeenCalledOnce();
});
it('falls back after bounded lock contention', async () => {
const load = vi
.fn()
.mockResolvedValue({ items: [{ id: 'db' }], next_cursor: null });
const service = serviceWithRedis({
get: vi.fn().mockResolvedValue(null),
setNxPx: vi.fn().mockResolvedValue(false),
});
await expect(
service.getOrLoad('chat', 1n, undefined, 50, load),
).resolves.toEqual({
items: [{ id: 'db' }],
next_cursor: null,
});
expect(load).toHaveBeenCalledOnce();
});
it('returns the authoritative page when cache write fails', async () => {
const page = { items: [{ id: 'db' }], next_cursor: null };
const load = vi.fn().mockResolvedValue(page);
const service = serviceWithRedis({
get: vi.fn().mockResolvedValue(null),
setNxPx: vi.fn().mockResolvedValue(true),
set: vi.fn().mockRejectedValue(new Error('redis down')),
unlock: vi.fn().mockResolvedValue(1),
});
await expect(
service.getOrLoad('chat', 1n, undefined, 50, load),
).resolves.toEqual(page);
});
});
+205
View File
@@ -0,0 +1,205 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { setTimeout as delay } from 'node:timers/promises';
import type { AppConfig } from '../../config/app-config.schema.js';
import { RedisClient } from '../../redis/redis.client.js';
import type { Page } from '../../common/http/page.js';
import { MetricsService } from '../../metrics/metrics.service.js';
const LOCK_RETRY_COUNT = 4;
const LOCK_RETRY_DELAY_MS = 25;
export type CachePage = Page<unknown>;
@Injectable()
export class MessagesCacheService {
private readonly logger = new Logger(MessagesCacheService.name);
constructor(
private readonly redis: RedisClient,
private readonly config: ConfigService<AppConfig>,
private readonly metrics: MetricsService,
) {}
async getOrLoad(
chatId: string,
version: bigint,
cursor: string | undefined,
limit: number,
loader: () => Promise<CachePage>,
): Promise<CachePage> {
const key = this.cacheKey(chatId, version, cursor, limit);
if (this.config.getOrThrow('CACHE_MODE') === 'naive') {
return this.loadNaively(key, loader);
}
let cached: string | null;
try {
cached = await this.redis.get(key);
} catch (error) {
return this.fallbackToDatabase('read', error, loader);
}
const cachedPage = this.parsePage(cached);
if (cachedPage) {
this.metrics.increment('cache_hit');
return cachedPage;
}
this.metrics.increment('cache_miss');
const lockKey = `lock:${key}`;
const owner = `${process.pid}:${Math.random().toString(36).slice(2)}`;
for (let attempt = 0; attempt < LOCK_RETRY_COUNT; attempt += 1) {
let locked: boolean;
try {
locked = await this.redis.setNxPx(
lockKey,
owner,
this.config.getOrThrow('CACHE_LOCK_TTL_MS'),
);
} catch (error) {
return this.fallbackToDatabase('lock', error, loader);
}
if (locked) return this.fillLocked(key, lockKey, owner, loader);
if (attempt === 0) this.metrics.increment('cache_lock_wait');
try {
const waitedPage = this.parsePage(await this.redis.get(key));
if (waitedPage) {
this.metrics.increment('cache_hit');
return waitedPage;
}
} catch (error) {
return this.fallbackToDatabase('waiting read', error, loader);
}
await delay(LOCK_RETRY_DELAY_MS);
}
// The owner did not publish the page within the bounded wait: serve the
// authoritative result instead of blocking the request further.
this.metrics.increment('cache_lock_timeout');
return loader();
}
private async fillLocked(
key: string,
lockKey: string,
owner: string,
loader: () => Promise<CachePage>,
): Promise<CachePage> {
try {
let secondCheck: string | null;
try {
secondCheck = await this.redis.get(key);
} catch (error) {
return this.fallbackToDatabase('double-check', error, loader);
}
const secondPage = this.parsePage(secondCheck);
if (secondPage) {
this.metrics.increment('cache_hit');
return secondPage;
}
const page = await loader();
try {
await this.redis.set(key, JSON.stringify(page), {
EX: this.config.getOrThrow('CACHE_TTL_SECONDS'),
});
} catch (error) {
// Redis is derived state: the page is still valid for this response,
// but the failure must stay visible in metrics and logs.
this.metrics.increment('cache_write_error');
this.logger.warn(
`Cache fill failed: ${error instanceof Error ? error.message : 'unknown error'}`,
);
}
return page;
} finally {
try {
await this.redis.unlock(lockKey, owner);
} catch (error) {
// The lock has a TTL, so a stale lock expires on its own; a successful
// response must not be replaced by an unlock failure.
this.metrics.increment('cache_unlock_error');
this.logger.warn(
`Cache unlock failed: ${error instanceof Error ? error.message : 'unknown error'}`,
);
}
}
}
private cacheKey(
chatId: string,
version: bigint,
cursor: string | undefined,
limit: number,
): string {
return `messages:${chatId}:v${version.toString()}:c${cursor ?? 'start'}:l${limit}`;
}
private async loadNaively(
key: string,
loader: () => Promise<CachePage>,
): Promise<CachePage> {
let cached: string | null;
try {
cached = await this.redis.get(key);
} catch (error) {
return this.fallbackToDatabase('naive read', error, loader);
}
const cachedPage = this.parsePage(cached);
if (cachedPage) {
this.metrics.increment('cache_hit');
return cachedPage;
}
this.metrics.increment('cache_miss');
const cacheMissDelay = this.config.getOrThrow('CACHE_MISS_DELAY_MS');
if (cacheMissDelay > 0) await delay(cacheMissDelay);
const page = await loader();
try {
await this.redis.set(key, JSON.stringify(page), {
EX: this.config.getOrThrow('CACHE_TTL_SECONDS'),
});
} catch (error) {
this.metrics.increment('cache_write_error');
this.logger.warn(
`Cache fill failed: ${error instanceof Error ? error.message : 'unknown error'}`,
);
}
return page;
}
private async fallbackToDatabase(
stage: string,
error: unknown,
loader: () => Promise<CachePage>,
): Promise<CachePage> {
this.metrics.increment('cache_fallback');
this.logger.warn(
`Cache ${stage} failed, serving PostgreSQL: ${error instanceof Error ? error.message : 'unknown error'}`,
);
return loader();
}
private parsePage(value: string | null): CachePage | undefined {
if (!value) return undefined;
try {
const parsed: unknown = JSON.parse(value);
if (
typeof parsed !== 'object' ||
parsed === null ||
!('items' in parsed) ||
!('next_cursor' in parsed) ||
!Array.isArray(parsed.items) ||
(parsed.next_cursor !== null &&
typeof parsed.next_cursor !== 'string')
)
return undefined;
return { items: parsed.items, next_cursor: parsed.next_cursor };
} catch {
// A malformed entry is treated as a miss and overwritten by the owner fill.
this.metrics.increment('cache_corrupt_entry');
return undefined;
}
}
}
@@ -0,0 +1,23 @@
import {
ArrayMaxSize,
ArrayUnique,
IsArray,
IsString,
IsUUID,
ValidateIf,
} from 'class-validator';
import { CodePointLength } from '../../common/validation/code-point-length.js';
export class CreateMessageDto {
@IsString()
@CodePointLength(0, 4000)
text!: string;
// Absent means []; null is a client error.
@ValidateIf((_, value) => value !== undefined)
@IsArray()
@ArrayMaxSize(10)
@ArrayUnique()
@IsUUID('all', { each: true })
attachment_ids: string[] = [];
}
@@ -0,0 +1,33 @@
import { fileURLToPath } from 'node:url';
import { parseDatabaseConfig } from '../../config/app-config.schema.js';
import { DatabaseClient } from '../../database/database.client.js';
import { MetricsService } from '../../metrics/metrics.service.js';
import { IdempotencyRepository } from './idempotency.repository.js';
// Manual operator pass over the idempotency ledger: the API also purges expired
// claims in the background, but an operator must be able to reclaim space
// without waiting for traffic. It never touches unexpired claims.
// in the stand: docker compose exec api node dist/messages/idempotency/idempotency-gc.cli.js
// on the host: npm run idempotency:gc (needs a reachable DATABASE_URL)
async function main(): Promise<void> {
const config = parseDatabaseConfig(process.env as Record<string, unknown>);
const database = new DatabaseClient(
{
getOrThrow: (key: keyof typeof config) => config[key],
} as never,
new MetricsService(),
);
try {
const repository = new IdempotencyRepository(database);
const purged = await repository.purgeExpired(
config.IDEMPOTENCY_TTL_SECONDS,
);
process.stdout.write(
`Purged ${purged} idempotency key(s) older than ${config.IDEMPOTENCY_TTL_SECONDS} seconds\n`,
);
} finally {
await database.onModuleDestroy();
}
}
if (process.argv[1] === fileURLToPath(import.meta.url)) await main();
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { DatabaseModule } from '../../database/database.module.js';
import { IdempotencyRepository } from './idempotency.repository.js';
@Module({
imports: [DatabaseModule],
providers: [IdempotencyRepository],
exports: [IdempotencyRepository],
})
export class IdempotencyModule {}
@@ -0,0 +1,24 @@
import { describe, expect, it, vi } from 'vitest';
import { IdempotencyRepository } from './idempotency.repository.js';
describe('IdempotencyRepository expired-key cleanup', () => {
it('deletes only rows older than the configured TTL', async () => {
const query = vi.fn().mockResolvedValue({ rowCount: 0, rows: [] });
const repository = new IdempotencyRepository({ query } as never);
await repository.forget(
'user',
'/api/v1/chats/chat/messages',
'key',
86400,
);
expect(query).toHaveBeenCalledWith(
'idempotency.forget',
expect.stringContaining(
'created_at < now() - make_interval(secs => $4::double precision)',
),
['user', '/api/v1/chats/chat/messages', 'key', 86400],
);
});
});
@@ -0,0 +1,119 @@
import { Injectable } from '@nestjs/common';
import pg from 'pg';
import { DatabaseClient } from '../../database/database.client.js';
import type { Message } from '../message.js';
// A committed row always carries the response: the claim and the stored response
// are written by one statement, so there is no poisoned intermediate state to
// re-check at replay time.
export type IdempotencyRecord = {
request_fingerprint: string;
status_code: number;
response_body: Message;
created_at: Date | string;
expired: boolean;
is_member: boolean;
};
const PURGE_BATCH_LIMIT = 1000;
const PURGE_BATCHES = 10;
@Injectable()
export class IdempotencyRepository {
constructor(private readonly database: DatabaseClient) {}
/**
* Reads the stored result and re-checks access in the same round trip: a
* replay must still prove that the caller may read this chat.
*/
async read(
userId: string,
path: string,
key: string,
chatId: string,
ttlSeconds: number,
): Promise<IdempotencyRecord | undefined> {
const result = await this.database.query<IdempotencyRecord>(
'idempotency.read',
`SELECT k.request_fingerprint, k.status_code, k.response_body, k.created_at,
k.created_at < now() - make_interval(secs => $4::double precision) AS expired,
EXISTS (
SELECT 1 FROM chat_members WHERE chat_id = $5 AND user_id = $1
) AS is_member
FROM idempotency_keys k
WHERE k.user_id = $1 AND k.method = 'POST' AND k.path = $2 AND k.key = $3`,
[userId, path, key, ttlSeconds, chatId],
);
return result.rows[0];
}
async forget(
userId: string,
path: string,
key: string,
ttlSeconds: number,
): Promise<void> {
await this.database.query(
'idempotency.forget',
`DELETE FROM idempotency_keys
WHERE user_id = $1 AND method = 'POST' AND path = $2 AND key = $3
AND created_at < now() - make_interval(secs => $4::double precision)`,
[userId, path, key, ttlSeconds],
);
}
async isMember(chatId: string, userId: string): Promise<boolean> {
const result = await this.database.query<{ is_member: boolean }>(
'messages.checkMembership',
`SELECT EXISTS (
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2
) AS is_member`,
[chatId, userId],
);
return result.rows[0]?.is_member === true;
}
/**
* Deletes expired claims in bounded batches. The transaction-scoped advisory
* lock makes the pass single-flight across replicas without risking a lock
* leaking back into the pool with a released connection. Returns the number
* of deleted rows (0 when another replica is purging).
*/
async purgeExpired(ttlSeconds: number): Promise<number> {
const client: pg.PoolClient = await this.database.pool.connect();
try {
await client.query('BEGIN');
try {
const lock = await client.query<{ locked: boolean }>(
"SELECT pg_try_advisory_xact_lock(hashtext('idempotency_gc')) AS locked",
);
if (lock.rows[0]?.locked !== true) {
await client.query('ROLLBACK');
return 0;
}
let purged = 0;
for (let batch = 0; batch < PURGE_BATCHES; batch += 1) {
const result = await client.query(
`DELETE FROM idempotency_keys
WHERE ctid IN (
SELECT ctid FROM idempotency_keys
WHERE created_at < now() - make_interval(secs => $1::double precision)
LIMIT ${PURGE_BATCH_LIMIT}
)`,
[ttlSeconds],
);
const deleted = result.rowCount ?? 0;
purged += deleted;
if (deleted < PURGE_BATCH_LIMIT) break;
}
await client.query('COMMIT');
return purged;
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
}
} finally {
client.release();
}
}
}
@@ -0,0 +1,26 @@
import { createHash } from 'node:crypto';
// Contract: ASCII [A-Za-z0-9._:-]{1,128}. Anything else (including a duplicated
// header, which Fastify joins with ", ") is rejected as a client error.
export const IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
export function messagesPath(chatId: string): string {
return `/api/v1/chats/${chatId}/messages`;
}
// The fingerprint is derived from the validated payload with a fixed field
// order, so neither JSON key order nor an absent optional field can change it.
// Text-only messages keep the lab3 fingerprint; the order of attachment ids
// is significant because it is the order of attachments in the message.
export function idempotencyFingerprint(
text: string,
attachmentIds: string[],
): string {
return createHash('sha256')
.update(
attachmentIds.length === 0
? JSON.stringify({ text })
: JSON.stringify({ text, attachment_ids: attachmentIds }),
)
.digest('hex');
}
+8
View File
@@ -0,0 +1,8 @@
export type Message = {
id: string;
chat_id: string;
sender_id: string;
text: string;
created_at: string;
attachment_ids: string[];
};
+53
View File
@@ -0,0 +1,53 @@
import {
BadRequestException,
Body,
Controller,
DefaultValuePipe,
Get,
Headers,
Param,
ParseIntPipe,
ParseUUIDPipe,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import { CurrentUser } from '../common/auth/current-user.decorator.js';
import { CurrentUserGuard } from '../common/auth/current-user.guard.js';
import type { User } from '../users/user.js';
import { CreateMessageDto } from './dto/create-message.dto.js';
import { MessagesService } from './messages.service.js';
@Controller('api/v1/chats/:chatId/messages')
@UseGuards(CurrentUserGuard)
export class MessagesController {
constructor(private readonly messagesService: MessagesService) {}
@Post()
create(
@Param('chatId', new ParseUUIDPipe()) chatId: string,
@Body() body: CreateMessageDto,
@CurrentUser() currentUser: User,
@Headers('idempotency-key') idempotencyKey?: string | string[],
) {
return this.messagesService.create(
chatId,
body,
currentUser,
idempotencyKey,
);
}
@Get()
list(
@Param('chatId', new ParseUUIDPipe()) chatId: string,
@CurrentUser() currentUser: User,
@Query('limit', new DefaultValuePipe(50), new ParseIntPipe())
limit: number,
@Query('cursor') cursor?: string,
) {
if (limit < 1 || limit > 100)
throw new BadRequestException('limit must be between 1 and 100');
return this.messagesService.list(chatId, currentUser, limit, cursor);
}
}
+28
View File
@@ -0,0 +1,28 @@
import { Module } from '@nestjs/common';
import { DatabaseModule } from '../database/database.module.js';
import { ChatsModule } from '../chats/chats.module.js';
import { MessagesController } from './messages.controller.js';
import { MessagesRepository } from './messages.repository.js';
import { MessagesService } from './messages.service.js';
import { MessagesCacheModule } from './cache/messages-cache.module.js';
import { IdempotencyModule } from './idempotency/idempotency.module.js';
import { UsersModule } from '../users/users.module.js';
import { RedisModule } from '../redis/redis.module.js';
import { AttachmentsModule } from '../attachments/attachments.module.js';
import { MetricsModule } from '../metrics/metrics.module.js';
@Module({
imports: [
ChatsModule,
MessagesCacheModule,
IdempotencyModule,
DatabaseModule,
UsersModule,
RedisModule,
MetricsModule,
AttachmentsModule,
],
controllers: [MessagesController],
providers: [MessagesRepository, MessagesService],
})
export class MessagesModule {}
@@ -0,0 +1,26 @@
import { describe, expect, it, vi } from 'vitest';
import type { Message } from './message.js';
import { MessagesRepository } from './messages.repository.js';
const message = (id: string, created_at: string): Message => ({
id,
chat_id: 'chat',
sender_id: 'sender',
text: id,
created_at,
attachment_ids: [],
});
describe('MessagesRepository', () => {
it('returns rows in response shape', async () => {
const query = vi.fn().mockResolvedValue({
rows: [message('1', '2026-01-01T00:00:00.000Z')],
rowCount: 1,
});
const repository = new MessagesRepository({ query } as never);
await expect(repository.findPage('chat', 1)).resolves.toEqual({
items: [message('1', '2026-01-01T00:00:00.000Z')],
hasMore: false,
});
});
});
+144
View File
@@ -0,0 +1,144 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { DatabaseClient } from '../database/database.client.js';
import type { Cursor } from '../common/http/cursor.js';
import type { Message } from './message.js';
type MessageRow = {
id: string;
chat_id: string;
sender_id: string;
text: string;
created_at: Date | string;
attachment_ids?: string[] | null;
};
export type CreateOnceRequest = {
userId: string;
chatId: string;
path: string;
key: string;
fingerprint: string;
text: string;
attachmentIds: string[];
};
function toMessage(row: MessageRow): Message {
return {
id: row.id,
chat_id: row.chat_id,
sender_id: row.sender_id,
text: row.text,
created_at: new Date(row.created_at).toISOString(),
attachment_ids: row.attachment_ids ?? [],
};
}
// Один оператор делает всё, что нужно пути записи: проверяет членство, занимает
// ключ идемпотентности, вставляет сообщение, увеличивает версию чата (якорь
// инвалидации кэша истории) и сохраняет тело ответа. Атомарность даёт сам
// оператор, поэтому явная транзакция и отдельные round trip'ы не нужны; тело
// ответа строится в SQL и служит единственным источником истины и для первого
// ответа, и для повторов.
//
// Зависимости CTE задают порядок выполнения: claim -> inserted -> bumped.
const CREATE_ONCE_SQL = `
WITH claim AS (
INSERT INTO idempotency_keys (user_id, method, path, key, request_fingerprint,
status_code, response_body, message_id)
SELECT $1, 'POST', $2, $3, $4, 201,
jsonb_build_object(
'id', $5::uuid,
'chat_id', $7::uuid,
'sender_id', $1::uuid,
'text', $6::text,
'created_at', to_char(date_trunc('milliseconds', now()) AT TIME ZONE 'UTC',
'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'),
'attachment_ids', to_jsonb($8::uuid[])),
$5::uuid
WHERE EXISTS (
SELECT 1 FROM chat_members WHERE chat_id = $7::uuid AND user_id = $1
)
AND (SELECT count(*) FROM attachments a
WHERE a.chat_id = $7::uuid AND a.status = 'ready'
AND a.id = ANY($8::uuid[])) = cardinality($8::uuid[])
ON CONFLICT DO NOTHING
RETURNING response_body
), inserted AS (
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT $5::uuid, $7::uuid, $1::uuid, $6::text, date_trunc('milliseconds', now())
FROM claim
RETURNING id
), linked AS (
INSERT INTO message_attachments (message_id, chat_id, attachment_id, ordinal)
SELECT $5::uuid, $7::uuid, t.id, t.ord
FROM inserted, unnest($8::uuid[]) WITH ORDINALITY AS t(id, ord)
), bumped AS (
UPDATE chats SET message_version = message_version + 1
WHERE id = $7::uuid AND EXISTS (SELECT 1 FROM inserted)
)
SELECT response_body FROM claim`;
@Injectable()
export class MessagesRepository {
constructor(private readonly database: DatabaseClient) {}
/**
* Returns the created message, or undefined when the key is already taken or
* the caller is not a member of the chat (both leave no side effect).
*/
async createOnce(request: CreateOnceRequest): Promise<Message | undefined> {
const result = await this.database.query<{ response_body: Message }>(
'messages.createIdempotent',
CREATE_ONCE_SQL,
[
request.userId,
request.path,
request.key,
request.fingerprint,
randomUUID(),
request.text,
request.chatId,
request.attachmentIds,
],
);
return result.rows[0]?.response_body;
}
async getVersion(chatId: string, userId: string): Promise<bigint> {
const result = await this.database.query<{ message_version: string }>(
'messages.version',
'SELECT c.message_version FROM chats c WHERE c.id = $1 AND EXISTS (SELECT 1 FROM chat_members WHERE chat_id = c.id AND user_id = $2)',
[chatId, userId],
);
if (!result.rows[0]) throw new NotFoundException();
return BigInt(result.rows[0].message_version);
}
async findPage(
chatId: string,
limit: number,
cursor?: Cursor,
): Promise<{ items: Message[]; hasMore: boolean }> {
const values: unknown[] = [chatId];
let predicate = '';
if (cursor) {
values.push(cursor.created_at, cursor.id);
predicate =
'AND (m.created_at, m.id) > ($2::timestamptz, $3::uuid)';
}
values.push(limit + 1);
const result = await this.database.query<MessageRow>(
'messages.history',
`SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
COALESCE((SELECT json_agg(ma.attachment_id ORDER BY ma.ordinal)
FROM message_attachments ma WHERE ma.message_id = m.id), '[]'::json) AS attachment_ids
FROM messages m WHERE m.chat_id = $1 ${predicate} ORDER BY m.created_at, m.id LIMIT $${values.length}`,
values,
);
return {
items: result.rows.slice(0, limit).map(toMessage),
hasMore: result.rows.length > limit,
};
}
}
+121
View File
@@ -0,0 +1,121 @@
import { describe, expect, it, vi } from 'vitest';
import { MessagesService } from './messages.service.js';
import { idempotencyFingerprint } from './idempotency/idempotency.js';
import type { Message } from './message.js';
type StoredRow = {
request_fingerprint: string;
response_body: Message;
created_at: Date;
expired: boolean;
is_member: boolean;
};
function deferred(): { promise: Promise<void>; resolve: () => void } {
let resolve!: () => void;
const promise = new Promise<void>((done) => {
resolve = done;
});
return { promise, resolve };
}
describe('MessagesService idempotency expiry race', () => {
it('does not let a stale expiry decision delete a replacement claim', async () => {
const oldCreatedAt = new Date('2020-01-01T00:00:00.000Z');
const newMessage: Message = {
id: 'message-new',
chat_id: 'chat',
sender_id: 'user',
text: 'hello',
created_at: '2026-01-01T00:00:00.000Z',
attachment_ids: [],
};
let row: StoredRow | undefined = {
request_fingerprint: idempotencyFingerprint('hello', []),
response_body: {
...newMessage,
id: 'message-old',
text: 'old',
},
created_at: oldCreatedAt,
expired: true,
is_member: true,
};
let createCalls = 0;
let readCalls = 0;
let forgetCalls = 0;
let messageWrites = 0;
const bothInitialClaims = deferred();
const bothInitialReads = deferred();
const replacementCreated = deferred();
const messagesRepository = {
createOnce: vi.fn(async () => {
createCalls += 1;
if (createCalls === 2) bothInitialClaims.resolve();
if (createCalls <= 2) {
await bothInitialClaims.promise;
return undefined;
}
if (row) return undefined;
messageWrites += 1;
row = {
request_fingerprint: idempotencyFingerprint('hello', []),
response_body: newMessage,
created_at: new Date('2026-01-01T00:00:00.000Z'),
expired: false,
is_member: true,
};
replacementCreated.resolve();
return newMessage;
}),
};
const idempotency = {
read: vi.fn(async () => {
readCalls += 1;
if (readCalls === 2) bothInitialReads.resolve();
if (readCalls <= 2) await bothInitialReads.promise;
return row;
}),
forget: vi.fn(async (...args: unknown[]) => {
forgetCalls += 1;
if (args.length !== 4) {
row = undefined;
return;
}
if (forgetCalls === 2) await replacementCreated.promise;
if (
!row ||
row.created_at >= new Date('2026-01-01T00:00:00.000Z')
)
return;
row = undefined;
}),
isMember: vi.fn().mockResolvedValue(true),
};
const makeService = () =>
new MessagesService(
messagesRepository as never,
{} as never,
{} as never,
idempotency as never,
{ getOrThrow: vi.fn().mockReturnValue(60) } as never,
{ increment: vi.fn() } as never,
{} as never,
);
const input = { text: 'hello', attachment_ids: [] } as never;
const user = { id: 'user' } as never;
const results = await Promise.all([
makeService().create('chat', input, user, 'same-key'),
makeService().create('chat', input, user, 'same-key'),
]);
expect(results).toEqual([newMessage, newMessage]);
expect(new Set(results.map((message) => message.id))).toEqual(
new Set(['message-new']),
);
expect(messageWrites).toBe(1);
expect(forgetCalls).toBe(2);
});
});
+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>;
}
}