feat: lab2 done

This commit is contained in:
2026-10-09 15:48:03 +03:00
parent f743ee10a2
commit 575f8ee386
104 changed files with 7038 additions and 1099 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);
});
});
+207
View File
@@ -0,0 +1,207 @@
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 { MetricsService } from '../../metrics/metrics.service.js';
const LOCK_RETRY_COUNT = 4;
const LOCK_RETRY_DELAY_MS = 25;
export type CachePage = {
items: unknown[];
next_cursor: string | null;
};
@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;
}
}
}
+3 -3
View File
@@ -1,7 +1,7 @@
import { IsString, Length } from 'class-validator';
export class CreateMessageDto {
@IsString()
@Length(1, 4000)
text!: string;
@IsString()
@Length(1, 4000)
text!: string;
}
+5 -5
View File
@@ -1,7 +1,7 @@
export type Message = {
id: string;
chat_id: string;
sender_id: string;
text: string;
created_at: string;
id: string;
chat_id: string;
sender_id: string;
text: string;
created_at: string;
};
+34 -43
View File
@@ -1,55 +1,46 @@
import {
BadRequestException,
Body,
Controller,
DefaultValuePipe,
Get,
Param,
ParseIntPipe,
ParseUUIDPipe,
Post,
Query,
Req,
UseGuards,
BadRequestException,
Body,
Controller,
DefaultValuePipe,
Get,
Param,
ParseIntPipe,
ParseUUIDPipe,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import type { FastifyRequest } from 'fastify';
import { CurrentUser } from '../common/auth/current-user.decorator.js';
import { CurrentUserGuard } from '../common/auth/current-user.guard.js';
import type { RequestWithCurrentUser } 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';
type MessageRequest = FastifyRequest & RequestWithCurrentUser;
@Controller('api/v1/chats/:chatId/messages')
@UseGuards(CurrentUserGuard)
export class MessagesController {
constructor(private readonly messagesService: MessagesService) {}
constructor(private readonly messagesService: MessagesService) {}
@Post()
create(
@Param('chatId', new ParseUUIDPipe()) chatId: string,
@Body() body: CreateMessageDto,
@Req() request: MessageRequest,
) {
return this.messagesService.create(chatId, body, request.currentUser!);
}
@Post()
create(
@Param('chatId', new ParseUUIDPipe()) chatId: string,
@Body() body: CreateMessageDto,
@CurrentUser() currentUser: User,
) {
return this.messagesService.create(chatId, body, currentUser);
}
@Get()
list(
@Param('chatId', new ParseUUIDPipe()) chatId: string,
@Req() request: MessageRequest,
@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,
request.currentUser!,
limit,
cursor,
);
}
@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);
}
}
+15 -4
View File
@@ -1,13 +1,24 @@
import { Module } from '@nestjs/common';
import { DatabaseModule } from '../database/database.module.js';
import { ChatsModule } from '../chats/chats.module.js';
import { UsersModule } from '../users/users.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 { UsersModule } from '../users/users.module.js';
import { RedisModule } from '../redis/redis.module.js';
import { MetricsModule } from '../metrics/metrics.module.js';
@Module({
imports: [UsersModule, ChatsModule],
controllers: [MessagesController],
providers: [MessagesRepository, MessagesService],
imports: [
ChatsModule,
MessagesCacheModule,
DatabaseModule,
UsersModule,
RedisModule,
MetricsModule,
],
controllers: [MessagesController],
providers: [MessagesRepository, MessagesService],
})
export class MessagesModule {}
+37 -32
View File
@@ -1,42 +1,47 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
import type { Cursor } from '../common/http/cursor.js';
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,
id,
chat_id: 'chat',
sender_id: 'sender',
text: id,
created_at,
});
describe('MessagesRepository', () => {
it('appends messages whose key is after the current tail', () => {
const repository = new MessagesRepository();
repository.save(message('1', '2026-01-01T00:00:00.000Z'));
repository.save(message('2', '2026-01-01T00:00:01.000Z'));
it('uses named SQL history and a keyset cursor', async () => {
const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 });
const repository = new MessagesRepository({
query,
withTransaction: vi.fn(),
} as never);
const cursor: Cursor = {
scope: 'messages:chat',
created_at: '2026-01-01T00:00:01.000Z',
id: '1',
};
await repository.findPage('chat', 10, cursor);
expect(query).toHaveBeenCalledWith(
'messages.history',
expect.stringContaining('(created_at, id) >'),
expect.arrayContaining(['chat', cursor.created_at, cursor.id, 11]),
);
});
expect(repository.findByChatId('chat').map((item) => item.id)).toEqual([
'1',
'2',
]);
});
it('keeps key order for delayed out-of-order messages', () => {
const repository = new MessagesRepository();
repository.save(message('2', '2026-01-01T00:00:02.000Z'));
repository.save(message('1', '2026-01-01T00:00:01.000Z'));
repository.save(message('3', '2026-01-01T00:00:03.000Z'));
const messages = repository.findByChatId('chat');
expect(messages.map((item) => item.id)).toEqual(['1', '2', '3']);
const cursor: Cursor = {
scope: 'messages:chat',
created_at: '2026-01-01T00:00:01.000Z',
id: '1',
};
expect(repository.findFirstAfter('chat', cursor)).toBe(1);
});
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,
});
});
});
+84 -59
View File
@@ -1,68 +1,93 @@
import { Injectable } from '@nestjs/common';
import {
BadRequestException,
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 { isAfter } from '../common/http/cursor.js';
import type { User } from '../users/user.js';
import type { Message } from './message.js';
type MessageRow = {
id: string;
chat_id: string;
sender_id: string;
text: string;
created_at: Date | 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(),
};
}
@Injectable()
export class MessagesRepository {
private readonly messagesByChatId = new Map<string, Message[]>();
constructor(private readonly database: DatabaseClient) {}
save(message: Message): void {
const messages = this.messagesByChatId.get(message.chat_id) ?? [];
const last = messages.at(-1);
async create(
chatId: string,
senderId: string,
text: string,
): Promise<Message> {
const id = randomUUID();
return this.database.withTransaction(async (client) => {
const membership = await client.query({
name: 'messages.checkMembership',
text: 'SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2',
values: [chatId, senderId],
});
if (!membership.rowCount) throw new NotFoundException();
const result = await client.query<MessageRow>({
name: 'messages.insert',
text: 'INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1, $2, $3, $4) RETURNING id, chat_id, sender_id, text, created_at',
values: [id, chatId, senderId, text],
});
await client.query({
name: 'messages.incrementVersion',
text: 'UPDATE chats SET message_version = message_version + 1 WHERE id = $1',
values: [chatId],
});
return toMessage(result.rows[0]);
});
}
if (
!last ||
last.created_at < message.created_at ||
(last.created_at === message.created_at && last.id < message.id)
) {
messages.push(message);
this.messagesByChatId.set(message.chat_id, messages);
return;
}
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);
}
// Preserve keyset order if a delayed request carries an older key.
let low = 0;
let high = messages.length;
while (low < high) {
const middle = Math.floor((low + high) / 2);
const current = messages[middle];
const comesAfter =
current.created_at > message.created_at ||
(current.created_at === message.created_at && current.id > message.id);
if (comesAfter) high = middle;
else low = middle + 1;
}
messages.splice(low, 0, message);
this.messagesByChatId.set(message.chat_id, messages);
}
findByChatId(chatId: string): Message[] {
return this.messagesByChatId.get(chatId) ?? [];
}
findFirstAfter(chatId: string, cursor: Cursor): number {
const messages = this.messagesByChatId.get(chatId) ?? [];
if (process.env.BENCHMARK_CURSOR_SEARCH === 'linear') {
return messages.findIndex((message) =>
isAfter(message.created_at, message.id, cursor),
);
}
let low = 0;
let high = messages.length;
while (low < high) {
const middle = Math.floor((low + high) / 2);
if (isAfter(messages[middle].created_at, messages[middle].id, cursor)) {
high = middle;
} else {
low = middle + 1;
}
}
return low;
}
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 (created_at, id) > ($2::timestamptz, $3::uuid)';
}
values.push(limit + 1);
const result = await this.database.query<MessageRow>(
'messages.history',
`SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1 ${predicate} ORDER BY created_at, id LIMIT $${values.length}`,
values,
);
return {
items: result.rows.slice(0, limit).map(toMessage),
hasMore: result.rows.length > limit,
};
}
}
+63 -63
View File
@@ -1,75 +1,75 @@
import {
BadRequestException,
Injectable,
} from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { BadRequestException, Injectable } from '@nestjs/common';
import { decodeCursor, encodeCursor } from '../common/http/cursor.js';
import type { User } from '../users/user.js';
import { ChatsService } from '../chats/chats.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';
@Injectable()
export class MessagesService {
constructor(
private readonly messagesRepository: MessagesRepository,
private readonly chatsService: ChatsService,
) {}
constructor(
private readonly messagesRepository: MessagesRepository,
private readonly chatsService: ChatsService,
private readonly cache: MessagesCacheService,
) {}
create(
chatId: string,
input: CreateMessageDto,
currentUser: User,
): Message {
const chat = this.chatsService.getForUser(chatId, currentUser);
async create(
chatId: string,
input: CreateMessageDto,
currentUser: User,
): Promise<Message> {
await this.chatsService.getForUser(chatId, currentUser);
if ([...input.text].every((character) => /\s/u.test(character)))
throw new BadRequestException('Message text cannot be blank');
return this.messagesRepository.create(
chatId,
currentUser.id,
input.text,
);
}
if ([...input.text].every((character) => /\s/u.test(character))) {
throw new BadRequestException('Message text cannot be blank');
}
const message: Message = {
id: randomUUID(),
chat_id: chat.id,
sender_id: currentUser.id,
text: input.text,
created_at: new Date().toISOString(),
};
this.messagesRepository.save(message);
return message;
}
list(
chatId: string,
currentUser: User,
limit: number,
cursorValue?: string,
): { items: Message[]; next_cursor: string | null } {
this.chatsService.getForUser(chatId, currentUser);
const scope = `messages:${chatId}`;
const cursor = cursorValue
? decodeCursor(cursorValue, scope)
: undefined;
const messages = this.messagesRepository.findByChatId(chatId);
const start = cursor
? this.messagesRepository.findFirstAfter(chatId, cursor)
: 0;
const items = messages.slice(start, start + limit);
const hasMore = messages.length > start + limit;
const last = items.at(-1);
return {
items,
next_cursor:
hasMore && last
? encodeCursor({
scope,
created_at: last.created_at,
id: last.id,
})
: null,
};
}
async list(
chatId: string,
currentUser: User,
limit: number,
cursorValue?: string,
): Promise<{ items: Message[]; next_cursor: string | null }> {
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 { items: Message[]; next_cursor: string | null };
}
}