forked from mtusi2026/mtusi2026lab3
lab3: идентичность реплики, LB-проверка и общая идемпотентность отправки
Этот коммит впервые фиксирует порт lab2 (приложение NestJS+Fastify, Dockerfile, одноservice-стенд compose, restart hook) и добавляет уровень 3/4 по lab3: - X-Instance-Id = INSTANCE_ID либо hostname контейнера (стабилен для процесса), добавляется и в ответах об ошибках, которые формируются до интерсептора. - /internal/lb-check: проба LB, намеренно не зависящая от PostgreSQL и Redis (отказ общей БД нельзя лечить выводом реплик из ротации); /health/ready остаётся операторским сигналом. /internal/metrics отдаёт instance_id и build_id. - Общая идемпотентность POST сообщения: таблица idempotency_keys, область (user, method, path, key), канонический отпечаток тела, заявка+результат в одной транзакции, повтор возвращает сохранённый ответ, другое тело — 409, отсутствие/неверный ключ — 400, просрочка по IDEMPOTENCY_TTL_SECONDS. - Транзиентные коды PostgreSQL (57014/40001/40P01) отображаются в 503, чтобы прерывание не фиксировалось идемпотентной записью как окончательный результат. - Миграции 003 (идемпотентность) и 004 (pg_stat_statements для трека 1), операторский прогон GC: npm run idempotency:gc.
This commit is contained in:
@@ -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
@@ -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 {}
|
||||
@@ -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
@@ -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,8 @@
|
||||
import { IsString } from 'class-validator';
|
||||
import { CodePointLength } from '../../common/validation/code-point-length.js';
|
||||
|
||||
export class CreateMessageDto {
|
||||
@IsString()
|
||||
@CodePointLength(1, 4000)
|
||||
text!: string;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { parseAppConfig } 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 = parseAppConfig(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,152 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type 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 in the same transaction, 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;
|
||||
};
|
||||
|
||||
const PURGE_BATCH_LIMIT = 1000;
|
||||
const PURGE_BATCHES = 10;
|
||||
|
||||
@Injectable()
|
||||
export class IdempotencyRepository {
|
||||
constructor(private readonly database: DatabaseClient) {}
|
||||
|
||||
/** True when this request created the claim, i.e. it owns the side effect. */
|
||||
async claim(
|
||||
client: pg.PoolClient,
|
||||
userId: string,
|
||||
path: string,
|
||||
key: string,
|
||||
fingerprint: string,
|
||||
): Promise<boolean> {
|
||||
const result = await client.query({
|
||||
text: `INSERT INTO idempotency_keys (user_id, method, path, key, request_fingerprint)
|
||||
VALUES ($1, 'POST', $2, $3, $4)
|
||||
ON CONFLICT DO NOTHING
|
||||
RETURNING created_at`,
|
||||
values: [userId, path, key, fingerprint],
|
||||
});
|
||||
return result.rowCount === 1;
|
||||
}
|
||||
|
||||
async read(
|
||||
client: pg.PoolClient,
|
||||
userId: string,
|
||||
path: string,
|
||||
key: string,
|
||||
ttlSeconds: number,
|
||||
): Promise<IdempotencyRecord | undefined> {
|
||||
const result = await client.query<IdempotencyRecord>({
|
||||
text: `SELECT request_fingerprint, status_code, response_body, created_at,
|
||||
created_at < now() - make_interval(secs => $4::double precision) AS expired
|
||||
FROM idempotency_keys
|
||||
WHERE user_id = $1 AND method = 'POST' AND path = $2 AND key = $3`,
|
||||
values: [userId, path, key, ttlSeconds],
|
||||
});
|
||||
return result.rows[0];
|
||||
}
|
||||
|
||||
async store(
|
||||
client: pg.PoolClient,
|
||||
userId: string,
|
||||
path: string,
|
||||
key: string,
|
||||
statusCode: number,
|
||||
message: Message,
|
||||
): Promise<void> {
|
||||
await client.query({
|
||||
text: `UPDATE idempotency_keys
|
||||
SET status_code = $4, response_body = $5::jsonb, message_id = $6
|
||||
WHERE user_id = $1 AND method = 'POST' AND path = $2 AND key = $3`,
|
||||
values: [
|
||||
userId,
|
||||
path,
|
||||
key,
|
||||
statusCode,
|
||||
JSON.stringify(message),
|
||||
message.id,
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
async forget(
|
||||
client: pg.PoolClient,
|
||||
userId: string,
|
||||
path: string,
|
||||
key: string,
|
||||
): Promise<void> {
|
||||
await client.query({
|
||||
text: `DELETE FROM idempotency_keys
|
||||
WHERE user_id = $1 AND method = 'POST' AND path = $2 AND key = $3`,
|
||||
values: [userId, path, key],
|
||||
});
|
||||
}
|
||||
|
||||
async isMember(
|
||||
client: pg.PoolClient,
|
||||
chatId: string,
|
||||
userId: string,
|
||||
): Promise<boolean> {
|
||||
const result = await client.query<{ is_member: boolean }>({
|
||||
text: `SELECT EXISTS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2
|
||||
) AS is_member`,
|
||||
values: [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 = 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({
|
||||
text: `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}
|
||||
)`,
|
||||
values: [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,18 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import type { CreateMessageDto } from '../dto/create-message.dto.js';
|
||||
|
||||
// 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.
|
||||
export function idempotencyFingerprint(input: CreateMessageDto): string {
|
||||
return createHash('sha256')
|
||||
.update(JSON.stringify({ text: input.text }))
|
||||
.digest('hex');
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export type Message = {
|
||||
id: string;
|
||||
chat_id: string;
|
||||
sender_id: string;
|
||||
text: string;
|
||||
created_at: string;
|
||||
};
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
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 { MetricsModule } from '../metrics/metrics.module.js';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ChatsModule,
|
||||
MessagesCacheModule,
|
||||
IdempotencyModule,
|
||||
DatabaseModule,
|
||||
UsersModule,
|
||||
RedisModule,
|
||||
MetricsModule,
|
||||
],
|
||||
controllers: [MessagesController],
|
||||
providers: [MessagesRepository, MessagesService],
|
||||
})
|
||||
export class MessagesModule {}
|
||||
@@ -0,0 +1,47 @@
|
||||
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,
|
||||
});
|
||||
|
||||
describe('MessagesRepository', () => {
|
||||
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]),
|
||||
);
|
||||
});
|
||||
|
||||
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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type pg from 'pg';
|
||||
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;
|
||||
};
|
||||
|
||||
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 {
|
||||
constructor(private readonly database: DatabaseClient) {}
|
||||
|
||||
// The caller owns the transaction: the message insert, the chat version bump
|
||||
// and the idempotency claim must commit or roll back as one unit.
|
||||
async create(
|
||||
client: pg.PoolClient,
|
||||
chatId: string,
|
||||
senderId: string,
|
||||
text: string,
|
||||
): Promise<Message> {
|
||||
const id = randomUUID();
|
||||
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]);
|
||||
}
|
||||
|
||||
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 (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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import type pg from 'pg';
|
||||
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 { DatabaseClient } from '../database/database.client.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';
|
||||
|
||||
// A claim row can disappear between our failed insert attempt and the read
|
||||
// (the previous owner rolled back), so a bounded retry is part of the protocol.
|
||||
const MAX_CLAIM_ATTEMPTS = 3;
|
||||
const PURGE_EVERY_REQUESTS = 512;
|
||||
|
||||
type CreateOutcome =
|
||||
| { kind: 'created'; message: Message }
|
||||
| { kind: 'replayed'; message: Message }
|
||||
| { kind: 'retry' };
|
||||
|
||||
@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 database: DatabaseClient,
|
||||
private readonly config: ConfigService<AppConfig>,
|
||||
private readonly metrics: MetricsService,
|
||||
) {}
|
||||
|
||||
async create(
|
||||
chatId: string,
|
||||
input: CreateMessageDto,
|
||||
currentUser: User,
|
||||
rawKey: string | string[] | undefined,
|
||||
): Promise<Message> {
|
||||
// The key is validated before anything else: a missing, malformed or
|
||||
// duplicated header is a client error, never a stored result.
|
||||
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');
|
||||
await this.chatsService.getForUser(chatId, currentUser);
|
||||
|
||||
const path = messagesPath(chatId);
|
||||
const fingerprint = idempotencyFingerprint(input);
|
||||
for (let attempt = 1; attempt <= MAX_CLAIM_ATTEMPTS; attempt += 1) {
|
||||
const outcome = await this.database.withTransaction((client) =>
|
||||
this.attemptCreate(client, {
|
||||
chatId,
|
||||
path,
|
||||
key: rawKey,
|
||||
fingerprint,
|
||||
text: input.text,
|
||||
userId: currentUser.id,
|
||||
}),
|
||||
);
|
||||
if (outcome.kind !== 'retry') {
|
||||
this.scheduleExpiredPurge();
|
||||
return outcome.message;
|
||||
}
|
||||
}
|
||||
throw new ServiceUnavailableException(
|
||||
'Idempotency key could not be claimed',
|
||||
);
|
||||
}
|
||||
|
||||
// One attempt = one transaction: the claim, the side effect and the stored
|
||||
// response commit together, so a retry can never duplicate a message and a
|
||||
// failure never leaves a half-finished claim behind.
|
||||
private async attemptCreate(
|
||||
client: pg.PoolClient,
|
||||
request: {
|
||||
chatId: string;
|
||||
path: string;
|
||||
key: string;
|
||||
fingerprint: string;
|
||||
text: string;
|
||||
userId: string;
|
||||
},
|
||||
): Promise<CreateOutcome> {
|
||||
const { chatId, path, key, fingerprint, text, userId } = request;
|
||||
const claimed = await this.idempotency.claim(
|
||||
client,
|
||||
userId,
|
||||
path,
|
||||
key,
|
||||
fingerprint,
|
||||
);
|
||||
if (claimed) {
|
||||
this.metrics.increment('idempotency.claim');
|
||||
const message = await this.messagesRepository.create(
|
||||
client,
|
||||
chatId,
|
||||
userId,
|
||||
text,
|
||||
);
|
||||
await this.idempotency.store(
|
||||
client,
|
||||
userId,
|
||||
path,
|
||||
key,
|
||||
HttpStatus.CREATED,
|
||||
message,
|
||||
);
|
||||
this.metrics.increment('messages.write');
|
||||
return { kind: 'created', message };
|
||||
}
|
||||
|
||||
const record = await this.idempotency.read(
|
||||
client,
|
||||
userId,
|
||||
path,
|
||||
key,
|
||||
this.config.getOrThrow('IDEMPOTENCY_TTL_SECONDS'),
|
||||
);
|
||||
if (!record) {
|
||||
// The previous owner aborted, so nothing was created and the key is
|
||||
// free again.
|
||||
this.metrics.increment('idempotency.claim_lost');
|
||||
return { kind: 'retry' };
|
||||
}
|
||||
if (record.request_fingerprint !== fingerprint) {
|
||||
this.metrics.increment('idempotency.conflict');
|
||||
throw new ConflictException(
|
||||
'Idempotency key reused with a different body',
|
||||
);
|
||||
}
|
||||
if (record.expired) {
|
||||
this.metrics.increment('idempotency.released');
|
||||
await this.idempotency.forget(client, userId, path, key);
|
||||
return { kind: 'retry' };
|
||||
}
|
||||
// A replay re-checks access, as the contract requires: the stored result
|
||||
// is only returned to a caller that may still read this chat.
|
||||
if (!(await this.idempotency.isMember(client, chatId, userId)))
|
||||
throw new NotFoundException();
|
||||
this.metrics.increment('idempotency.replay');
|
||||
return { kind: 'replayed', message: record.response_body };
|
||||
}
|
||||
|
||||
// Expired claims are storage hygiene, not part of the request: the pass runs
|
||||
// outside the request transaction, 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>;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user