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
+24 -1
View File
@@ -1,10 +1,33 @@
import { Module } from '@nestjs/common';
import { AppConfigModule } from './config/app-config.module.js';
import { DatabaseModule } from './database/database.module.js';
import { RedisModule } from './redis/redis.module.js';
import { AuthModule } from './auth/auth.module.js';
import { ChatsModule } from './chats/chats.module.js';
import { HealthModule } from './health/health.module.js';
import { MessagesModule } from './messages/messages.module.js';
import { MetricsModule } from './metrics/metrics.module.js';
import { UsersModule } from './users/users.module.js';
import { APP_FILTER } from '@nestjs/core';
import { ApiExceptionFilter } from './common/errors/api-exception.filter.js';
@Module({
imports: [HealthModule, UsersModule, ChatsModule, MessagesModule],
imports: [
AppConfigModule,
DatabaseModule,
RedisModule,
UsersModule,
AuthModule,
HealthModule,
ChatsModule,
MessagesModule,
MetricsModule,
],
providers: [
{
provide: APP_FILTER,
useClass: ApiExceptionFilter,
},
],
})
export class AppModule {}
+79
View File
@@ -0,0 +1,79 @@
import {
BadRequestException,
Body,
Controller,
Delete,
Headers,
HttpCode,
HttpStatus,
Post,
UnauthorizedException,
UseGuards,
} from '@nestjs/common';
import { TextDecoder } from 'node:util';
import { AuthService } from './auth.service.js';
import { CurrentUserGuard } from '../common/auth/current-user.guard.js';
const BASE64 =
/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;
const BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"';
function basicUnauthorized(): UnauthorizedException {
return new UnauthorizedException({
message: 'Unauthorized',
challenge: BASIC_CHALLENGE,
});
}
function bearerUnauthorized(): UnauthorizedException {
return new UnauthorizedException({
message: 'Unauthorized',
challenge: 'Bearer realm="messenger"',
});
}
function parseBasic(value: string | undefined): [string, string] {
if (typeof value !== 'string') throw basicUnauthorized();
const match = /^Basic[ \t]+([^ \t]+)$/iu.exec(value);
if (!match || !BASE64.test(match[1])) throw basicUnauthorized();
const bytes = Buffer.from(match[1], 'base64');
if (bytes.toString('base64') !== match[1]) throw basicUnauthorized();
let decoded: string;
try {
decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
} catch {
throw basicUnauthorized();
}
const separator = decoded.indexOf(':');
if (separator < 1) throw basicUnauthorized();
return [decoded.slice(0, separator), decoded.slice(separator + 1)];
}
@Controller('api/v1/auth/sessions')
export class AuthController {
constructor(private readonly auth: AuthService) {}
@Post()
create(
@Headers('authorization') authorization: string | undefined,
@Body() body: unknown,
) {
const [username, password] = parseBasic(authorization);
if (body !== undefined)
throw new BadRequestException(
'Session creation does not accept a body',
);
return this.auth.createSession(username, password);
}
@Delete('current')
@UseGuards(CurrentUserGuard)
@HttpCode(HttpStatus.NO_CONTENT)
async delete(
@Headers('authorization') authorization: string | undefined,
): Promise<void> {
if (!authorization || !/^Bearer\s+[^\s]+$/iu.test(authorization))
throw bearerUnauthorized();
await this.auth.deleteSession(authorization.slice(7).trim());
}
}
+16
View File
@@ -0,0 +1,16 @@
import { Module } from '@nestjs/common';
import { DatabaseModule } from '../database/database.module.js';
import { RedisModule } from '../redis/redis.module.js';
import { UsersModule } from '../users/users.module.js';
import { AuthController } from './auth.controller.js';
import { AuthService } from './auth.service.js';
import { SessionRepository } from './session.repository.js';
import { MetricsModule } from '../metrics/metrics.module.js';
@Module({
imports: [UsersModule, DatabaseModule, RedisModule, MetricsModule],
controllers: [AuthController],
providers: [AuthService, SessionRepository],
exports: [AuthService, SessionRepository],
})
export class AuthModule {}
+63
View File
@@ -0,0 +1,63 @@
import {
Injectable,
ServiceUnavailableException,
UnauthorizedException,
} from '@nestjs/common';
import argon2 from 'argon2';
import type { User } from '../users/user.js';
import { UsersService } from '../users/users.service.js';
import { SessionRepository } from './session.repository.js';
export type SessionResponse = {
token: string;
token_type: 'Bearer';
expires_at: string;
user: User;
};
@Injectable()
export class AuthService {
constructor(
private readonly users: UsersService,
private readonly sessions: SessionRepository,
) {}
async createSession(
username: string,
password: string,
): Promise<SessionResponse> {
const storedUser = await this.users.findByUsername(username);
if (
!storedUser ||
!(await argon2.verify(storedUser.password_hash, password))
) {
throw new UnauthorizedException();
}
const user: User = {
id: storedUser.id,
username: storedUser.username,
display_name: storedUser.display_name,
created_at: storedUser.created_at,
};
let session: { token: string; expiresAt: string };
try {
session = await this.sessions.create(user.id);
} catch {
throw new ServiceUnavailableException('Session store unavailable');
}
return {
token: session.token,
token_type: 'Bearer',
expires_at: session.expiresAt,
user,
};
}
async deleteSession(token: string): Promise<void> {
try {
await this.sessions.delete(token);
} catch {
throw new ServiceUnavailableException('Session store unavailable');
}
}
}
+35
View File
@@ -0,0 +1,35 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { randomBytes } from 'node:crypto';
import type { AppConfig } from '../config/app-config.schema.js';
import { RedisClient } from '../redis/redis.client.js';
import { MetricsService } from '../metrics/metrics.service.js';
@Injectable()
export class SessionRepository {
constructor(
private readonly redis: RedisClient,
private readonly config: ConfigService<AppConfig>,
private readonly metrics: MetricsService,
) {}
async create(
userId: string,
): Promise<{ token: string; expiresAt: string }> {
const token = randomBytes(32).toString('base64url');
const ttl = this.config.getOrThrow('SESSION_TTL_SECONDS');
const expiresAt = new Date(Date.now() + ttl * 1000).toISOString();
this.metrics.increment('session_set');
await this.redis.set(
`session:${token}`,
JSON.stringify({ user_id: userId, expires_at: expiresAt }),
{ EX: ttl },
);
return { token, expiresAt };
}
delete(token: string): Promise<number> {
this.metrics.increment('session_del');
return this.redis.del(`session:${token}`);
}
}
+36 -41
View File
@@ -1,54 +1,49 @@
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 { CurrentUser } from '../common/auth/current-user.decorator.js';
import { CurrentUserGuard } from '../common/auth/current-user.guard.js';
import type { FastifyRequest } from 'fastify';
import { ChatsService } from './chats.service.js';
import { CreateChatDto } from './dto/create-chat.dto.js';
import type { User } from '../users/user.js';
@Controller('api/v1/chats')
@UseGuards(CurrentUserGuard)
export class ChatsController {
constructor(private readonly chatsService: ChatsService) {}
constructor(private readonly chatsService: ChatsService) {}
@Post()
create(@Body() body: CreateChatDto, @Req() request: FastifyRequest) {
return this.chatsService.create(body, request.currentUser!);
}
@Post()
create(@Body() body: CreateChatDto, @CurrentUser() currentUser: User) {
return this.chatsService.create(body, currentUser);
}
@Get()
list(
@Req() request: FastifyRequest,
@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');
}
@Get()
list(
@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.chatsService.listForUser(currentUser, limit, cursor);
}
return this.chatsService.listForUser(
request.currentUser!,
limit,
cursor,
);
}
@Get(':chatId')
get(
@Param('chatId', new ParseUUIDPipe()) chatId: string,
@Req() request: FastifyRequest,
) {
return this.chatsService.getForUser(chatId, request.currentUser!);
}
@Get(':chatId')
get(
@Param('chatId', new ParseUUIDPipe()) chatId: string,
@CurrentUser() currentUser: User,
) {
return this.chatsService.getForUser(chatId, currentUser);
}
}
+8 -5
View File
@@ -1,13 +1,16 @@
import { Module } from '@nestjs/common';
import { ChatsController } from './chats.controller.js';
import { DatabaseModule } from '../database/database.module.js';
import { RedisModule } from '../redis/redis.module.js';
import { MetricsModule } from '../metrics/metrics.module.js';
import { UsersModule } from '../users/users.module.js';
import { ChatsController } from './chats.controller.js';
import { ChatsRepository } from './chats.repository.js';
import { ChatsService } from './chats.service.js';
@Module({
imports: [UsersModule],
controllers: [ChatsController],
providers: [ChatsRepository, ChatsService],
exports: [ChatsService],
imports: [UsersModule, DatabaseModule, RedisModule, MetricsModule],
controllers: [ChatsController],
providers: [ChatsRepository, ChatsService],
exports: [ChatsService],
})
export class ChatsModule {}
+103 -9
View File
@@ -1,19 +1,113 @@
import { Injectable } from '@nestjs/common';
import { Chat } from './chat.js';
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 type { User } from '../users/user.js';
import type { Chat } from './chat.js';
type ChatRow = {
id: string;
title: string;
created_at: Date | string;
member_ids: string[];
};
function toChat(row: ChatRow): Chat {
return {
id: row.id,
title: row.title,
created_at: new Date(row.created_at).toISOString(),
member_ids: row.member_ids,
};
}
@Injectable()
export class ChatsRepository {
private readonly chatsById = new Map<string, Chat>();
constructor(private readonly database: DatabaseClient) {}
save(chat: Chat): void {
this.chatsById.set(chat.id, chat);
async create(title: string, memberIds: string[]): Promise<Chat> {
const id = randomUUID();
return this.database.withTransaction(async (client) => {
const users = await client.query<{ id: string }>({
name: 'chats.validateMembers',
text: 'SELECT id FROM users WHERE id = ANY($1::uuid[])',
values: [memberIds],
});
if (users.rowCount !== memberIds.length)
throw new BadRequestException('Chat member does not exist');
const inserted = await client.query<ChatRow>({
name: 'chats.insert',
text: 'INSERT INTO chats (id, title) VALUES ($1, $2) RETURNING id, title, created_at',
values: [id, title],
});
for (const memberId of memberIds) {
await client.query({
name: 'chats.insertMember',
text: 'INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)',
values: [id, memberId],
});
}
return {
...toChat({ ...inserted.rows[0], member_ids: memberIds }),
member_ids: memberIds,
};
});
}
findById(id: string): Chat | undefined {
return this.chatsById.get(id);
async findForUser(id: string, user: User): Promise<Chat | undefined> {
const result = await this.database.query<ChatRow>(
'chats.findForUser',
`SELECT c.id, c.title, c.created_at,
COALESCE(array_agg(cm.user_id ORDER BY cm.user_id)
FILTER (WHERE cm.user_id IS NOT NULL), '{}') AS member_ids
FROM chats c
LEFT JOIN chat_members cm ON cm.chat_id = c.id
WHERE c.id = $1
AND EXISTS (
SELECT 1 FROM chat_members own
WHERE own.chat_id = c.id AND own.user_id = $2
)
GROUP BY c.id`,
[id, user.id],
);
return result.rows[0] ? toChat(result.rows[0]) : undefined;
}
findAll(): Chat[] {
return Array.from(this.chatsById.values());
async findPageForUser(
user: User,
limit: number,
cursor?: Cursor,
): Promise<{ items: Chat[]; hasMore: boolean }> {
const values: unknown[] = [user.id];
let predicate = '';
if (cursor) {
values.push(cursor.created_at, cursor.id);
predicate =
'AND (c.created_at, c.id) > ($2::timestamptz, $3::uuid)';
}
values.push(limit + 1);
const result = await this.database.query<ChatRow>(
'chats.listForUser',
`SELECT c.id, c.title, c.created_at,
COALESCE(array_agg(cm.user_id ORDER BY cm.user_id)
FILTER (WHERE cm.user_id IS NOT NULL), '{}') AS member_ids
FROM chats c
LEFT JOIN chat_members cm ON cm.chat_id = c.id
WHERE EXISTS (
SELECT 1 FROM chat_members own
WHERE own.chat_id = c.id AND own.user_id = $1
)
${predicate}
GROUP BY c.id ORDER BY c.created_at, c.id LIMIT $${values.length}`,
values,
);
return {
items: result.rows.slice(0, limit).map(toChat),
hasMore: result.rows.length > limit,
};
}
}
+48 -83
View File
@@ -1,95 +1,60 @@
import {
BadRequestException,
Injectable,
NotFoundException,
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import {
decodeCursor,
encodeCursor,
isAfter,
} from '../common/http/cursor.js';
import { encodeCursor, decodeCursor } from '../common/http/cursor.js';
import type { User } from '../users/user.js';
import { UsersService } from '../users/users.service.js';
import type { Chat } from './chat.js';
import type { CreateChatDto } from './dto/create-chat.dto.js';
import type { Chat } from './chat.js';
import { ChatsRepository } from './chats.repository.js';
@Injectable()
export class ChatsService {
constructor(
private readonly chatsRepository: ChatsRepository,
private readonly usersService: UsersService,
) {}
constructor(private readonly chatsRepository: ChatsRepository) {}
create(input: CreateChatDto, currentUser: User): Chat {
if (!input.member_ids.includes(currentUser.id)) {
throw new BadRequestException('Current user must be a chat member');
}
create(input: CreateChatDto, currentUser: User): Promise<Chat> {
if (!input.member_ids.includes(currentUser.id))
throw new BadRequestException('Current user must be a chat member');
if (new Set(input.member_ids).size !== input.member_ids.length)
throw new BadRequestException('Duplicate chat member');
return this.chatsRepository.create(input.title, input.member_ids);
}
for (const memberId of input.member_ids) {
if (!this.usersService.findById(memberId)) {
throw new BadRequestException('Chat member does not exist');
}
}
async getForUser(chatId: string, currentUser: User): Promise<Chat> {
const chat = await this.chatsRepository.findForUser(
chatId,
currentUser,
);
if (!chat) throw new NotFoundException();
return chat;
}
const chat: Chat = {
id: randomUUID(),
title: input.title,
member_ids: [...input.member_ids],
created_at: new Date().toISOString(),
};
this.chatsRepository.save(chat);
return chat;
}
getForUser(chatId: string, currentUser: User): Chat {
const chat = this.chatsRepository.findById(chatId);
if (!chat || !chat.member_ids.includes(currentUser.id)) {
throw new NotFoundException();
}
return chat;
}
listForUser(
currentUser: User,
limit: number,
cursorValue?: string,
): { items: Chat[]; next_cursor: string | null } {
const scope = `chats:${currentUser.id}`;
const cursor = cursorValue
? decodeCursor(cursorValue, scope)
: undefined;
const chats = this.chatsRepository
.findAll()
.filter((chat) => chat.member_ids.includes(currentUser.id))
.sort((left, right) => {
const byDate = left.created_at.localeCompare(right.created_at);
return byDate !== 0 ? byDate : left.id.localeCompare(right.id);
});
const start = cursor
? chats.findIndex((chat) => isAfter(chat.created_at, chat.id, cursor))
: 0;
const visible = chats.slice(start < 0 ? chats.length : start);
const items = visible.slice(0, limit);
const hasMore = visible.length > limit;
const last = items.at(-1);
return {
items,
next_cursor:
hasMore && last
? encodeCursor({
scope,
created_at: last.created_at,
id: last.id,
})
: null,
};
}
async listForUser(
currentUser: User,
limit: number,
cursorValue?: string,
): Promise<{ items: Chat[]; next_cursor: string | null }> {
const scope = `chats:${currentUser.id}`;
const cursor = cursorValue
? decodeCursor(cursorValue, scope)
: undefined;
const page = await this.chatsRepository.findPageForUser(
currentUser,
limit,
cursor,
);
const last = page.items.at(-1);
return {
items: page.items,
next_cursor:
page.hasMore && last
? encodeCursor({
scope,
created_at: last.created_at,
id: last.id,
})
: null,
};
}
}
@@ -0,0 +1,10 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import type { User } from '../../users/user.js';
import { FastifyRequest } from 'fastify';
export const CurrentUser = createParamDecorator(
(_data: unknown, context: ExecutionContext): User => {
const request = context.switchToHttp().getRequest<FastifyRequest>();
return request.currentUser!;
},
);
+67 -25
View File
@@ -2,42 +2,84 @@ import {
CanActivate,
ExecutionContext,
Injectable,
ServiceUnavailableException,
UnauthorizedException,
} from '@nestjs/common';
import { isUUID } from 'class-validator';
import type { FastifyRequest } from 'fastify';
import type { User } from '../../users/user.js';
import { RedisClient } from '../../redis/redis.client.js';
import { UsersService } from '../../users/users.service.js';
export type RequestWithCurrentUser = {
headers: {
'x-user-id'?: string | string[];
};
currentUser?: User;
};
import { MetricsService } from '../../metrics/metrics.service.js';
@Injectable()
export class CurrentUserGuard implements CanActivate {
constructor(private readonly usersService: UsersService) {}
constructor(
private readonly redis: RedisClient,
private readonly users: UsersService,
private readonly metrics: MetricsService,
) {}
canActivate(context: ExecutionContext): boolean {
const request = context
.switchToHttp()
.getRequest<RequestWithCurrentUser>();
const header = request.headers['x-user-id'];
if (typeof header !== 'string' || !isUUID(header)) {
throw new UnauthorizedException();
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<FastifyRequest>();
const authorization = request.headers.authorization;
if (
typeof authorization !== 'string' ||
!/^Bearer\s+[^\s]+$/u.test(authorization)
) {
throw new UnauthorizedException({
message: 'Unauthorized',
challenge: 'Bearer realm="messenger"',
});
}
const user = this.usersService.findById(header);
if (!user) {
throw new UnauthorizedException();
let session: string | null;
try {
this.metrics.increment('session_get');
session = await this.redis.get(
`session:${authorization.slice(7).trim()}`,
);
} catch {
throw new ServiceUnavailableException('Session store unavailable');
}
if (!session)
throw new UnauthorizedException({
message: 'Unauthorized',
challenge: 'Bearer realm="messenger"',
});
let userId: string;
try {
const parsed: unknown = JSON.parse(session);
if (
typeof parsed !== 'object' ||
parsed === null ||
!('user_id' in parsed) ||
typeof parsed.user_id !== 'string' ||
!('expires_at' in parsed) ||
typeof parsed.expires_at !== 'string' ||
!/^(?:\d{4})-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/u.test(
parsed.expires_at,
)
)
throw new Error('invalid session');
const expiresAt = Date.parse(parsed.expires_at);
if (!Number.isFinite(expiresAt) || Date.now() >= expiresAt)
throw new Error('expired session');
userId = parsed.user_id;
} catch {
throw new UnauthorizedException({
message: 'Unauthorized',
challenge: 'Bearer realm="messenger"',
});
}
let user: User | undefined;
try {
user = await this.users.findById(userId);
} catch {
throw new ServiceUnavailableException(
'Authentication service unavailable',
);
}
if (!user) throw new UnauthorizedException();
request.currentUser = user;
return true;
}
}
+83 -54
View File
@@ -5,85 +5,114 @@ import {
HttpException,
HttpStatus,
} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import { randomUUID } from 'node:crypto';
type RequestWithId = {
requestId?: string;
};
type RequestWithId = { requestId?: string; method?: string; url?: string };
type ExceptionBody = { message?: unknown; challenge?: unknown };
type HttpResponse = {
header(name: string, value: string): void;
status(code: number): HttpResponse;
send(body: unknown): void;
};
// Connection/session loss codes reported by node-postgres and the network layer.
const UNAVAILABLE_ERROR_CODES = new Set([
'ECONNREFUSED',
'ECONNRESET',
'ENOTFOUND',
'ETIMEDOUT',
'EPIPE',
'08000',
'08001',
'08003',
'08004',
'08006',
'57P01',
'57P02',
'57P03',
'53300',
]);
function isDependencyOutage(exception: unknown): boolean {
if (typeof exception !== 'object' || exception === null) return false;
const code = (exception as { code?: unknown }).code;
return typeof code === 'string' && UNAVAILABLE_ERROR_CODES.has(code);
}
function errorCodeForStatus(status: number): string {
switch (status) {
case HttpStatus.BAD_REQUEST:
return 'invalid_request';
case HttpStatus.UNAUTHORIZED:
return 'unauthorized';
case HttpStatus.NOT_FOUND:
return 'not_found';
case HttpStatus.CONFLICT:
return 'conflict';
case HttpStatus.PAYLOAD_TOO_LARGE:
return 'payload_too_large';
case HttpStatus.UNSUPPORTED_MEDIA_TYPE:
return 'unsupported_media_type';
case HttpStatus.TOO_MANY_REQUESTS:
return 'rate_limited';
case HttpStatus.SERVICE_UNAVAILABLE:
return 'unavailable';
default:
return 'internal_error';
}
const codes: Record<number, string> = {
[HttpStatus.BAD_REQUEST]: 'invalid_request',
[HttpStatus.UNAUTHORIZED]: 'unauthorized',
[HttpStatus.NOT_FOUND]: 'not_found',
[HttpStatus.CONFLICT]: 'conflict',
[HttpStatus.PAYLOAD_TOO_LARGE]: 'payload_too_large',
[HttpStatus.UNSUPPORTED_MEDIA_TYPE]: 'unsupported_media_type',
[HttpStatus.TOO_MANY_REQUESTS]: 'rate_limited',
[HttpStatus.SERVICE_UNAVAILABLE]: 'unavailable',
};
return codes[status] ?? 'internal_error';
}
@Catch()
export class ApiExceptionFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
const context = host.switchToHttp();
const request = context.getRequest<RequestWithId>();
const response = context.getResponse<HttpResponse>();
constructor(private readonly adapterHost: HttpAdapterHost) {}
catch(exception: unknown, host: ArgumentsHost): void {
const http = host.switchToHttp();
const request = http.getRequest<RequestWithId>();
const response = http.getResponse<unknown>();
const adapter = this.adapterHost.httpAdapter;
const requestId = request.requestId ?? randomUUID();
request.requestId = requestId;
response.header('X-Request-Id', requestId);
let status = HttpStatus.INTERNAL_SERVER_ERROR;
let message = 'Internal server error';
let challenge: string | undefined;
if (exception instanceof HttpException) {
status = exception.getStatus();
const exceptionResponse = exception.getResponse();
const body = exception.getResponse();
const details: ExceptionBody =
typeof body === 'object' && body !== null
? (body as ExceptionBody)
: {};
const rawMessage =
typeof exceptionResponse === 'object' &&
exceptionResponse !== null &&
'message' in exceptionResponse
? exceptionResponse.message
'message' in details ? details.message : undefined;
challenge =
typeof details.challenge === 'string'
? details.challenge
: undefined;
message = Array.isArray(rawMessage)
? rawMessage.join('; ')
: typeof rawMessage === 'string'
? rawMessage
: 'Request failed';
if (status === HttpStatus.NOT_FOUND) {
message = 'Resource not found';
}
if (status === HttpStatus.NOT_FOUND) message = 'Resource not found';
if (status >= HttpStatus.INTERNAL_SERVER_ERROR)
message =
status === HttpStatus.SERVICE_UNAVAILABLE
? 'Service unavailable'
: 'Internal server error';
} else if (isDependencyOutage(exception)) {
// A dropped dependency is a bounded outage, not an internal fault.
status = HttpStatus.SERVICE_UNAVAILABLE;
message = 'Service unavailable';
}
response.status(status).send({
error: {
code: errorCodeForStatus(status),
message: message,
request_id: requestId,
if (status === HttpStatus.UNAUTHORIZED) {
const authChallenge =
challenge ??
(request.method === 'POST' &&
request.url?.startsWith('/api/v1/auth/sessions')
? 'Basic realm="messenger", charset="UTF-8"'
: 'Bearer realm="messenger"');
adapter.setHeader(response, 'WWW-Authenticate', authChallenge);
}
adapter.setHeader(response, 'X-Request-Id', requestId);
adapter.reply(
response,
{
error: {
code: errorCodeForStatus(status),
message,
request_id: requestId,
},
},
});
status,
);
}
}
+43 -40
View File
@@ -1,54 +1,57 @@
import { BadRequestException } from '@nestjs/common';
export type Cursor = {
scope: string;
created_at: string;
id: string;
scope: string;
created_at: string;
id: string;
};
export function encodeCursor(cursor: Cursor): string {
return Buffer.from(JSON.stringify(cursor), 'utf8').toString('base64url');
return Buffer.from(JSON.stringify(cursor), 'utf8').toString('base64url');
}
export function decodeCursor(value: string, expectedScope: string): Cursor {
try {
const parsed: unknown = JSON.parse(
Buffer.from(value, 'base64url').toString('utf8'),
);
if (
typeof parsed !== 'object' ||
parsed === null ||
!('scope' in parsed) ||
!('created_at' in parsed) ||
!('id' in parsed) ||
typeof parsed.scope !== 'string' ||
typeof parsed.created_at !== 'string' ||
typeof parsed.id !== 'string' ||
parsed.scope !== expectedScope ||
parsed.created_at.length === 0 ||
parsed.id.length === 0
) {
throw new Error('invalid cursor');
}
return {
scope: parsed.scope,
created_at: parsed.created_at,
id: parsed.id,
};
} catch {
throw new BadRequestException('Invalid cursor');
}
try {
const parsed: unknown = JSON.parse(
Buffer.from(value, 'base64url').toString('utf8'),
);
if (
typeof parsed !== 'object' ||
parsed === null ||
!('scope' in parsed) ||
!('created_at' in parsed) ||
!('id' in parsed) ||
typeof parsed.scope !== 'string' ||
typeof parsed.created_at !== 'string' ||
typeof parsed.id !== 'string' ||
parsed.scope !== expectedScope ||
!/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu.test(
parsed.id,
) ||
!/^(?:\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)$/u.test(
parsed.created_at,
)
)
throw new Error('invalid cursor');
const timestamp = Date.parse(parsed.created_at);
if (!Number.isFinite(timestamp)) throw new Error('invalid cursor');
return {
scope: parsed.scope,
created_at: parsed.created_at,
id: parsed.id,
};
} catch {
throw new BadRequestException('Invalid cursor');
}
}
export function isAfter(
createdAt: string,
id: string,
cursor: Cursor,
createdAt: string,
id: string,
cursor: Cursor,
): boolean {
return (
createdAt > cursor.created_at ||
(createdAt === cursor.created_at && id > cursor.id)
);
return (
createdAt > cursor.created_at ||
(createdAt === cursor.created_at && id > cursor.id)
);
}
+32 -17
View File
@@ -4,32 +4,47 @@ import {
Injectable,
NestInterceptor,
} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import { randomUUID } from 'node:crypto';
import { Observable } from 'rxjs';
import { finalize, Observable } from 'rxjs';
import { MetricsService } from '../../metrics/metrics.service.js';
const INSTANCE_ID = randomUUID();
type RequestWithId = {
requestId?: string;
};
type ResponseWithHeader = {
header(name: string, value: string): void;
};
type RequestWithId = { requestId?: string };
@Injectable()
export class RequestIdInterceptor implements NestInterceptor {
constructor(
private readonly adapterHost: HttpAdapterHost,
private readonly metrics: MetricsService,
) {}
intercept(
context: ExecutionContext,
next: CallHandler<any>,
): Observable<any> | Promise<Observable<any>> {
next: CallHandler,
): Observable<unknown> {
const request = context.switchToHttp().getRequest<RequestWithId>();
const response = context.switchToHttp().getResponse<ResponseWithHeader>();
const response = context.switchToHttp().getResponse<unknown>();
const requestId = randomUUID();
const startedAt = performance.now();
request.requestId = requestId;
response.header('X-Request-Id', requestId);
return next.handle();
this.adapterHost.httpAdapter.setHeader(
response,
'X-Request-Id',
requestId,
);
this.adapterHost.httpAdapter.setHeader(
response,
'X-Instance-Id',
INSTANCE_ID,
);
this.metrics.increment('request_count');
return next
.handle()
.pipe(
finalize(() =>
this.metrics.observeLatency(performance.now() - startedAt),
),
);
}
}
+16
View File
@@ -0,0 +1,16 @@
import { Global, Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { parseAppConfig } from './app-config.schema.js';
@Global()
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
cache: true,
validate: parseAppConfig,
}),
],
exports: [ConfigModule],
})
export class AppConfigModule {}
+91
View File
@@ -0,0 +1,91 @@
import { readFileSync } from 'node:fs';
import { z } from 'zod';
function numeric(
name: string,
minimum: number,
maximum: number | undefined,
fallback: number,
) {
let schema = z
.number({ message: `${name} must be a number` })
.int()
.min(minimum);
if (maximum !== undefined) schema = schema.max(maximum);
return z.preprocess(
(value) =>
typeof value === 'string' && value.trim() !== ''
? Number(value)
: value,
schema.default(fallback),
);
}
function requiredString(name: string) {
return z
.string({ message: `${name} is required` })
.min(1, `${name} is required`);
}
export const appConfigSchema = z
.object({
APP_HOST: z.string().min(1).default('0.0.0.0'),
APP_PORT: numeric('APP_PORT', 1, 65535, 8080),
APP_ENV: z.string().min(1).default('lab'),
SESSION_TTL_SECONDS: numeric('SESSION_TTL_SECONDS', 2, undefined, 3600),
DATABASE_URL: requiredString('DATABASE_URL'),
REDIS_URL: requiredString('REDIS_URL'),
DATABASE_POOL_MAX: numeric('DATABASE_POOL_MAX', 1, 100, 10),
DATABASE_CONNECTION_TIMEOUT_MS: numeric(
'DATABASE_CONNECTION_TIMEOUT_MS',
1,
undefined,
5000,
),
DATABASE_STATEMENT_TIMEOUT_MS: numeric(
'DATABASE_STATEMENT_TIMEOUT_MS',
1,
undefined,
5000,
),
CACHE_TTL_SECONDS: numeric('CACHE_TTL_SECONDS', 1, undefined, 30),
CACHE_MODE: z.enum(['protected', 'naive']).default('protected'),
CACHE_LOCK_TTL_MS: numeric('CACHE_LOCK_TTL_MS', 1, undefined, 1000),
CACHE_MISS_DELAY_MS: numeric('CACHE_MISS_DELAY_MS', 0, undefined, 0),
METRICS_TOKEN: z.string().min(1).optional(),
DRAIN_DELAY_MS: numeric('DRAIN_DELAY_MS', 0, undefined, 5000),
})
.strip();
export type AppConfig = z.infer<typeof appConfigSchema>;
export type AppConfigKey = keyof AppConfig;
function resolveSecret(
raw: Record<string, unknown>,
key: 'DATABASE_URL' | 'REDIS_URL',
): unknown {
const fileKey = `${key}_FILE`;
const path = raw[fileKey];
if (typeof path !== 'string' || path.length === 0) return raw[key];
try {
const value = readFileSync(path, 'utf8').trim();
if (value.length === 0)
throw new Error(`${fileKey} contains an empty value`);
return value;
} catch (error) {
if (
error instanceof Error &&
error.message.includes('contains an empty value')
)
throw error;
throw new Error(`${fileKey} could not be read`);
}
}
export function parseAppConfig(raw: Record<string, unknown>): AppConfig {
return appConfigSchema.parse({
...raw,
DATABASE_URL: resolveSecret(raw, 'DATABASE_URL'),
REDIS_URL: resolveSecret(raw, 'REDIS_URL'),
});
}
+75
View File
@@ -0,0 +1,75 @@
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import pg from 'pg';
import { MetricsService } from '../metrics/metrics.service.js';
import type { AppConfig } from '../config/app-config.schema.js';
@Injectable()
export class DatabaseClient implements OnModuleDestroy {
readonly pool: pg.Pool;
private readonly logger = new Logger(DatabaseClient.name);
constructor(
private readonly config: ConfigService<AppConfig>,
private readonly metrics: MetricsService,
) {
this.pool = new pg.Pool({
connectionString: this.config.getOrThrow('DATABASE_URL'),
max: this.config.getOrThrow('DATABASE_POOL_MAX'),
connectionTimeoutMillis: this.config.getOrThrow(
'DATABASE_CONNECTION_TIMEOUT_MS',
),
statement_timeout: this.config.getOrThrow(
'DATABASE_STATEMENT_TIMEOUT_MS',
),
});
// Idle clients emit 'error' on the pool when the database drops; without a
// listener Node treats it as uncaught and terminates the process.
this.pool.on('error', (error: Error) => {
this.metrics.increment('database.pool_error');
this.logger.warn(`PostgreSQL pool error: ${error.message}`);
});
}
query<T extends pg.QueryResultRow = pg.QueryResultRow>(
label: string,
text: string,
values: readonly unknown[] = [],
): Promise<pg.QueryResult<T>> {
this.metrics.increment(label);
return this.pool.query<T>({ text, values: [...values] });
}
async health(): Promise<void> {
await this.query('health.database', 'SELECT 1');
}
async withTransaction<T>(
work: (client: pg.PoolClient) => Promise<T>,
): Promise<T> {
const client = await this.pool.connect();
try {
await client.query('BEGIN');
const result = await work(client);
await client.query('COMMIT');
return result;
} catch (error) {
try {
await client.query('ROLLBACK');
} catch (rollbackError) {
this.metrics.increment('database.rollback_error');
this.logger.warn(
`Rollback failed: ${rollbackError instanceof Error ? rollbackError.message : 'unknown error'}`,
);
}
// Callers must see the operation error, not the rollback error.
throw error;
} finally {
client.release();
}
}
async onModuleDestroy(): Promise<void> {
await this.pool.end();
}
}
+10
View File
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { MetricsModule } from '../metrics/metrics.module.js';
import { DatabaseClient } from './database.client.js';
@Module({
imports: [MetricsModule],
providers: [DatabaseClient],
exports: [DatabaseClient],
})
export class DatabaseModule {}
+63
View File
@@ -0,0 +1,63 @@
import { readdir, readFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { DatabaseClient } from './database.client.js';
import { MetricsService } from '../metrics/metrics.service.js';
import { parseAppConfig } from '../config/app-config.schema.js';
const migrationsDirectory = join(
dirname(fileURLToPath(import.meta.url)),
'migrations',
);
async function migrationFiles(): Promise<string[]> {
const files = await readdir(migrationsDirectory);
return files.filter((file) => /^\d+_.+\.sql$/u.test(file)).sort();
}
export async function runMigrations(database: DatabaseClient): Promise<void> {
await database.query(
'migrations.ensure_table',
`CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT now()
)`,
);
for (const version of await migrationFiles()) {
await database.withTransaction(async (client) => {
const applied = await client.query({
text: 'SELECT version FROM schema_migrations WHERE version = $1',
values: [version],
});
if (applied.rowCount) return;
const sql = await readFile(
join(migrationsDirectory, version),
'utf8',
);
await client.query(sql);
await client.query({
text: 'INSERT INTO schema_migrations (version) VALUES ($1)',
values: [version],
});
});
}
}
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 {
await runMigrations(database);
} finally {
await database.onModuleDestroy();
}
}
if (process.argv[1] === fileURLToPath(import.meta.url)) await main();
@@ -0,0 +1,41 @@
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS users (
id uuid PRIMARY KEY,
username text NOT NULL UNIQUE,
display_name text NOT NULL,
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS chats (
id uuid PRIMARY KEY,
title text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
message_version bigint NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS chat_members (
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
PRIMARY KEY (chat_id, user_id)
);
CREATE TABLE IF NOT EXISTS messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
text text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT messages_sender_member_fk
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id)
ON DELETE RESTRICT
);
CREATE INDEX IF NOT EXISTS messages_chat_created_id_idx
ON messages (chat_id, created_at, id);
CREATE INDEX IF NOT EXISTS chat_members_user_chat_idx
ON chat_members (user_id, chat_id);
@@ -0,0 +1,5 @@
-- HTTP timestamps and keyset cursors use JavaScript millisecond precision.
-- Store the same precision so a returned cursor cannot point before its own row.
ALTER TABLE users ALTER COLUMN created_at TYPE timestamptz(3);
ALTER TABLE chats ALTER COLUMN created_at TYPE timestamptz(3);
ALTER TABLE messages ALTER COLUMN created_at TYPE timestamptz(3);
+9 -9
View File
@@ -3,15 +3,15 @@ import { HealthService } from './health.service.js';
@Controller('health')
export class HealthController {
constructor(private readonly healthService: HealthService) {}
constructor(private readonly healthService: HealthService) {}
@Get('live')
getLive() {
return this.healthService.getLiveness();
}
@Get('live')
getLive() {
return this.healthService.getLiveness();
}
@Get('ready')
getReady() {
return this.healthService.getReadiness();
}
@Get('ready')
async getReady() {
return this.healthService.getReadiness();
}
}
+5 -3
View File
@@ -1,10 +1,12 @@
import { Module } from '@nestjs/common';
import { HealthController } from './health.controller.js';
import { HealthService } from './health.service.js';
import { DatabaseModule } from '../database/database.module.js';
import { RedisModule } from '../redis/redis.module.js';
@Module({
imports: [],
controllers: [HealthController],
providers: [HealthService],
imports: [DatabaseModule, RedisModule],
controllers: [HealthController],
providers: [HealthService],
})
export class HealthModule {}
+39 -50
View File
@@ -1,57 +1,46 @@
import { describe, expect, it, vi } from 'vitest';
import { ServiceUnavailableException } from '@nestjs/common';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { HealthService } from './health.service.js';
describe('HealthService', () => {
const originalDrainDelay = process.env.DRAIN_DELAY_MS;
it('reports liveness and readiness when dependencies are healthy', async () => {
const database = { health: vi.fn().mockResolvedValue(undefined) };
const redis = { health: vi.fn().mockResolvedValue(undefined) };
const config = { get: vi.fn().mockReturnValue(0) };
const service = new HealthService(
database as never,
redis as never,
config as never,
);
expect(service.getLiveness()).toEqual({ status: 'ok' });
await expect(service.getReadiness()).resolves.toEqual({ status: 'ok' });
});
beforeEach(() => {
vi.useFakeTimers();
});
it('rejects readiness when a dependency is unavailable', async () => {
const database = {
health: vi.fn().mockRejectedValue(new Error('down')),
};
const redis = { health: vi.fn().mockResolvedValue(undefined) };
const service = new HealthService(
database as never,
redis as never,
{ get: vi.fn() } as never,
);
await expect(service.getReadiness()).rejects.toBeInstanceOf(
ServiceUnavailableException,
);
});
afterEach(() => {
vi.useRealTimers();
if (originalDrainDelay === undefined) {
delete process.env.DRAIN_DELAY_MS;
} else {
process.env.DRAIN_DELAY_MS = originalDrainDelay;
}
});
it('reports live and ready before shutdown starts', () => {
const service = new HealthService();
expect(service.getLiveness()).toEqual({ status: 'ok' });
expect(service.getReadiness()).toEqual({ status: 'ok' });
});
it('keeps liveness healthy but rejects readiness while draining', () => {
const service = new HealthService();
service.setDraining();
expect(service.getLiveness()).toEqual({ status: 'ok' });
expect(() => service.getReadiness()).toThrow(ServiceUnavailableException);
expect(() => service.getReadiness()).toThrow('Service is shutting down');
});
it('waits for the configured drain window after a termination signal', async () => {
process.env.DRAIN_DELAY_MS = '5000';
const service = new HealthService();
const shutdown = service.beforeApplicationShutdown('SIGTERM');
await vi.advanceTimersByTimeAsync(4999);
expect(() => service.getReadiness()).toThrow('Service is shutting down');
await vi.advanceTimersByTimeAsync(1);
await expect(shutdown).resolves.toBeUndefined();
});
it('does not delay explicit application close without a signal', async () => {
process.env.DRAIN_DELAY_MS = '5000';
const service = new HealthService();
await expect(service.beforeApplicationShutdown()).resolves.toBeUndefined();
expect(() => service.getReadiness()).toThrow('Service is shutting down');
expect(vi.getTimerCount()).toBe(0);
});
it('keeps liveness healthy while draining', async () => {
const service = new HealthService(
{ health: vi.fn() } as never,
{ health: vi.fn() } as never,
{ get: vi.fn() } as never,
);
service.setDraining();
expect(service.getLiveness()).toEqual({ status: 'ok' });
await expect(service.getReadiness()).rejects.toThrow(
'Service is shutting down',
);
});
});
+42 -40
View File
@@ -1,45 +1,47 @@
import {
Injectable,
ServiceUnavailableException,
Global,
Injectable,
Module,
ServiceUnavailableException,
} from '@nestjs/common';
import type { BeforeApplicationShutdown } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { DatabaseClient } from '../database/database.client.js';
import { RedisClient } from '../redis/redis.client.js';
import type { AppConfig } from '../config/app-config.schema.js';
@Injectable()
export class HealthService implements BeforeApplicationShutdown {
private ready = true;
private readonly drainDelayMs = this.readDrainDelay();
getLiveness() {
return { status: 'ok' as const };
}
getReadiness() {
if (!this.ready) {
throw new ServiceUnavailableException('Service is shutting down');
}
return { status: 'ok' as const };
}
setDraining(): void {
this.ready = false;
}
async beforeApplicationShutdown(signal?: string): Promise<void> {
this.setDraining();
// Explicit app.close() in tests should remain immediate. Signals get a
// drain window so orchestrators can observe readiness=503 before Nest
// closes the HTTP server.
if (signal && this.drainDelayMs > 0) {
await new Promise<void>((resolve) => {
setTimeout(resolve, this.drainDelayMs);
});
}
}
private readDrainDelay(): number {
const value = Number.parseInt(process.env.DRAIN_DELAY_MS ?? '5000', 10);
return Number.isFinite(value) && value >= 0 ? value : 5000;
}
export class HealthService {
private ready = true;
constructor(
private readonly database: DatabaseClient,
private readonly redis: RedisClient,
private readonly config: ConfigService<AppConfig>,
) {}
getLiveness() {
return { status: 'ok' as const };
}
async getReadiness() {
if (!this.ready)
throw new ServiceUnavailableException('Service is shutting down');
try {
await Promise.all([this.database.health(), this.redis.health()]);
} catch {
throw new ServiceUnavailableException('Dependencies unavailable');
}
return { status: 'ok' as const };
}
setDraining() {
this.ready = false;
}
async beforeApplicationShutdown(signal?: string): Promise<void> {
this.setDraining();
const delay = this.config.get<number>('DRAIN_DELAY_MS') ?? 5000;
if (signal && delay > 0) {
await new Promise<void>((resolve) => setTimeout(resolve, delay));
}
}
}
@Global()
@Module({ providers: [HealthService], exports: [HealthService] })
export class HealthServiceModule {}
+15 -14
View File
@@ -1,23 +1,26 @@
import { NestFactory } from '@nestjs/core';
import { HttpAdapterHost } from '@nestjs/core';
import { ConfigService } from '@nestjs/config';
import { ValidationPipe } from '@nestjs/common';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { AppModule } from './app.module.js';
import { ApiExceptionFilter } from './common/errors/api-exception.filter.js';
import { MetricsService } from './metrics/metrics.service.js';
import { RequestIdInterceptor } from './common/http/request-id.interceptor.js';
async function bootstrap() {
async function bootstrap(): Promise<void> {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({
logger: true,
}),
new FastifyAdapter({ logger: true }),
);
app.useGlobalInterceptors(
new RequestIdInterceptor(
app.get(HttpAdapterHost),
app.get(MetricsService),
),
);
app.useGlobalInterceptors(new RequestIdInterceptor());
app.useGlobalFilters(new ApiExceptionFilter());
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
@@ -27,12 +30,10 @@ async function bootstrap() {
);
app.enableShutdownHooks();
const port = Number(process.env.APP_PORT ?? '8080');
const host = process.env.APP_HOST ?? '0.0.0.0';
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error('APP_PORT must be an integer between 1 and 65535');
}
const config = app.get(ConfigService);
const port = config.getOrThrow<number>('APP_PORT');
const host = config.getOrThrow<string>('APP_HOST');
await app.listen(port, host);
}
await bootstrap();
+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 };
}
}
+43
View File
@@ -0,0 +1,43 @@
import {
Controller,
Get,
Headers,
HttpCode,
HttpStatus,
Post,
UnauthorizedException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import type { AppConfig } from '../config/app-config.schema.js';
import { MetricsService } from './metrics.service.js';
@Controller('internal')
export class MetricsController {
constructor(
private readonly config: ConfigService<AppConfig>,
private readonly metrics: MetricsService,
) {}
@Get('metrics')
get(@Headers('authorization') authorization?: string) {
this.requireToken(authorization);
return this.metrics.snapshot();
}
@Post('metrics/reset')
@HttpCode(HttpStatus.OK)
reset(@Headers('authorization') authorization?: string): { status: 'ok' } {
this.requireToken(authorization);
this.metrics.reset();
return { status: 'ok' };
}
private requireToken(authorization?: string): void {
const token = this.config.get<string>('METRICS_TOKEN');
if (!token || authorization !== `Bearer ${token}`)
throw new UnauthorizedException({
message: 'Unauthorized',
challenge: 'Bearer realm="metrics"',
});
}
}
+10
View File
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { MetricsController } from './metrics.controller.js';
import { MetricsService } from './metrics.service.js';
@Module({
controllers: [MetricsController],
providers: [MetricsService],
exports: [MetricsService],
})
export class MetricsModule {}
+62
View File
@@ -0,0 +1,62 @@
import { describe, expect, it } from 'vitest';
import { MetricsService } from './metrics.service.js';
describe('MetricsService', () => {
it('computes nearest-rank percentiles from observed latencies', () => {
const metrics = new MetricsService();
metrics.increment('cache_hit');
metrics.increment('cache_hit');
metrics.observeLatency(30);
metrics.observeLatency(10);
metrics.observeLatency(20);
expect(metrics.snapshot()).toEqual({
counters: { cache_hit: 2 },
latency_ms: {
count: 3,
sample_count: 3,
p50: 20,
p95: 30,
p99: 30,
max: 30,
},
});
});
it('keeps snapshots isolated from callers and later observations', () => {
const metrics = new MetricsService();
metrics.increment('cache_hit');
const snapshot = metrics.snapshot();
snapshot.counters.cache_hit = 99;
metrics.increment('cache_hit');
expect(metrics.snapshot().counters.cache_hit).toBe(2);
expect(snapshot.latency_ms.count).toBe(0);
});
it('bounds retained samples but keeps cumulative count and maximum', () => {
const metrics = new MetricsService();
metrics.observeLatency(9000);
for (let index = 0; index < 4096; index += 1)
metrics.observeLatency(10);
expect(metrics.snapshot().latency_ms).toEqual({
count: 4097,
sample_count: 4096,
p50: 10,
p95: 10,
p99: 10,
max: 9000,
});
});
it('ignores invalid latency observations', () => {
const metrics = new MetricsService();
for (const value of [-1, NaN, Infinity]) metrics.observeLatency(value);
expect(metrics.snapshot().latency_ms).toEqual({
count: 0,
sample_count: 0,
p50: 0,
p95: 0,
p99: 0,
max: 0,
});
});
});
+69
View File
@@ -0,0 +1,69 @@
import { Injectable } from '@nestjs/common';
const LATENCY_SAMPLE_CAPACITY = 4096;
type LatencySnapshot = {
count: number;
sample_count: number;
p50: number;
p95: number;
p99: number;
max: number;
};
@Injectable()
export class MetricsService {
private readonly counters: Record<string, number> = {};
private readonly latencies: number[] = [];
private latencyCount = 0;
private maximumLatency = 0;
private nextSample = 0;
increment(name: string): void {
this.counters[name] = (this.counters[name] ?? 0) + 1;
}
observeLatency(milliseconds: number): void {
if (!Number.isFinite(milliseconds) || milliseconds < 0) return;
this.latencyCount += 1;
this.maximumLatency = Math.max(this.maximumLatency, milliseconds);
this.latencies[this.nextSample] = milliseconds;
this.nextSample = (this.nextSample + 1) % LATENCY_SAMPLE_CAPACITY;
}
snapshot(): {
counters: Record<string, number>;
latency_ms: LatencySnapshot;
} {
const sorted = [...this.latencies].sort((left, right) => left - right);
return {
counters: { ...this.counters },
latency_ms: {
count: this.latencyCount,
sample_count: sorted.length,
p50: this.percentile(sorted, 0.5),
p95: this.percentile(sorted, 0.95),
p99: this.percentile(sorted, 0.99),
max: this.maximumLatency,
},
};
}
reset(): void {
for (const name of Object.keys(this.counters))
delete this.counters[name];
this.latencies.length = 0;
this.latencyCount = 0;
this.maximumLatency = 0;
this.nextSample = 0;
}
private percentile(sorted: number[], percentile: number): number {
if (sorted.length === 0) return 0;
const index = Math.min(
sorted.length - 1,
Math.ceil(sorted.length * percentile) - 1,
);
return sorted[index];
}
}
+134
View File
@@ -0,0 +1,134 @@
import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { createClient, type RedisClientType } from 'redis';
import type { AppConfig } from '../config/app-config.schema.js';
import { MetricsService } from '../metrics/metrics.service.js';
const UNLOCK_SCRIPT =
'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end';
type Client = RedisClientType;
@Injectable()
export class RedisClient implements OnModuleInit, OnModuleDestroy {
readonly client: Client;
private readonly logger = new Logger(RedisClient.name);
constructor(
private readonly config: ConfigService<AppConfig>,
private readonly metrics: MetricsService,
) {
this.client = createClient({
url: this.config.getOrThrow('REDIS_URL'),
disableOfflineQueue: true,
socket: {
reconnectStrategy: (attempt) =>
Math.min(1000 + attempt * 250, 5000),
connectTimeout: 5000,
},
}) as Client;
// Reconnect failures must be visible; the readiness probe pings Redis.
this.client.on('error', (error: Error) => {
this.metrics.increment('redis.error');
this.logger.warn(`Redis error: ${error.message}`);
});
}
async onModuleInit(): Promise<void> {
await this.client.connect();
}
async onModuleDestroy(): Promise<void> {
if (this.client.isOpen) await this.client.quit();
}
async health(): Promise<void> {
this.metrics.increment('redis.ping');
await this.client.ping();
}
async get(key: string): Promise<string | null> {
this.metrics.increment('redis.get');
return this.client.get(key);
}
async set(
key: string,
value: string,
options?: { EX?: number; PX?: number; NX?: boolean },
): Promise<string | null> {
this.metrics.increment('redis.set');
return this.client.set(key, value, options);
}
async setNxEx(
key: string,
value: string,
seconds: number,
): Promise<boolean> {
this.metrics.increment('redis.set');
return (
(await this.client.set(key, value, { NX: true, EX: seconds })) ===
'OK'
);
}
async setNxPx(
key: string,
value: string,
milliseconds: number,
): Promise<boolean> {
this.metrics.increment('redis.set');
return (
(await this.client.set(key, value, {
NX: true,
PX: milliseconds,
})) === 'OK'
);
}
async del(key: string): Promise<number> {
this.metrics.increment('redis.del');
return this.client.del(key);
}
async incr(key: string): Promise<number> {
this.metrics.increment('redis.incr');
return this.client.incr(key);
}
async expire(key: string, seconds: number): Promise<boolean> {
this.metrics.increment('redis.expire');
return (await this.client.expire(key, seconds)) === 1;
}
async scan(
cursor: number,
pattern?: string,
count = 100,
): Promise<{ cursor: number; keys: string[] }> {
this.metrics.increment('redis.scan');
const result = await this.client.scan(String(cursor), {
MATCH: pattern,
COUNT: count,
});
return { cursor: Number(result.cursor), keys: result.keys };
}
async unlock(key: string, owner: string): Promise<number> {
this.metrics.increment('redis.unlock');
return Number(
await this.client.eval(UNLOCK_SCRIPT, {
keys: [key],
arguments: [owner],
}),
);
}
pipeline(commands: Array<[string, ...string[]]>): Promise<unknown[]> {
this.metrics.increment('redis.pipeline');
const multi = this.client.multi();
for (const [command, ...args] of commands)
multi.addCommand([command, ...args]);
return multi.exec();
}
}
+10
View File
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { MetricsModule } from '../metrics/metrics.module.js';
import { RedisClient } from './redis.client.js';
@Module({
imports: [MetricsModule],
providers: [RedisClient],
exports: [RedisClient],
})
export class RedisModule {}
+11 -4
View File
@@ -1,11 +1,18 @@
import { IsNotEmpty, IsString, Matches } from 'class-validator';
import { IsString, Length, Matches } from 'class-validator';
export class CreateUserDTO {
@IsString()
@Matches(/^[a-z0-9_]{3,32}$/)
username: string;
username!: string;
@IsString()
@IsNotEmpty()
display_name: string;
@Length(1, 100)
@Matches(/\S/u, {
message: 'display_name must contain a non-whitespace character',
})
display_name!: string;
@IsString()
@Length(12, 128)
password!: string;
}
+7 -6
View File
@@ -1,8 +1,9 @@
import { Body, Controller, Get, Post, Req, UseGuards } from '@nestjs/common';
import { UsersService } from './users.service.js';
import { CreateUserDTO } from './dto/create-user.dto.js';
import type { FastifyRequest } from 'fastify';
import { Body, Controller, Get, Post, 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 './user.js';
import { CreateUserDTO } from './dto/create-user.dto.js';
import { UsersService } from './users.service.js';
@Controller('api/v1/users')
export class UsersController {
@@ -15,7 +16,7 @@ export class UsersController {
@Get('/me')
@UseGuards(CurrentUserGuard)
getMe(@Req() request: FastifyRequest) {
return request.currentUser;
getMe(@CurrentUser() currentUser: User) {
return currentUser;
}
}
+5 -1
View File
@@ -3,10 +3,14 @@ import { UsersController } from './users.controller.js';
import { UsersRepository } from './users.repository.js';
import { UsersService } from './users.service.js';
import { CurrentUserGuard } from '../common/auth/current-user.guard.js';
import { RedisModule } from '../redis/redis.module.js';
import { MetricsModule } from '../metrics/metrics.module.js';
import { DatabaseModule } from '../database/database.module.js';
@Module({
imports: [DatabaseModule, RedisModule, MetricsModule],
controllers: [UsersController],
providers: [UsersRepository, UsersService, CurrentUserGuard],
exports: [UsersService, CurrentUserGuard],
exports: [UsersService, CurrentUserGuard, RedisModule, MetricsModule],
})
export class UsersModule {}
+64 -18
View File
@@ -1,25 +1,71 @@
import { Injectable } from '@nestjs/common';
import { User } from './user.js';
import { ConflictException, Injectable } from '@nestjs/common';
import { DatabaseClient } from '../database/database.client.js';
import type { User } from './user.js';
type UserRow = {
id: string;
username: string;
display_name: string;
password_hash: string;
created_at: Date | string;
};
function toUser(row: UserRow): User {
return {
id: row.id,
username: row.username,
display_name: row.display_name,
created_at: new Date(row.created_at).toISOString(),
};
}
@Injectable()
export class UsersRepository {
private readonly usersById = new Map<string, User>();
private readonly userIdByUsername = new Map<string, string>();
constructor(private readonly database: DatabaseClient) {}
findById(id: string): User | undefined {
return this.usersById.get(id);
}
async findById(id: string): Promise<User | undefined> {
const result = await this.database.query<UserRow>(
'users.findById',
'SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = $1',
[id],
);
const row = result.rows[0];
return row ? toUser(row) : undefined;
}
findByUsername(username: string): User | undefined {
const userId = this.userIdByUsername.get(username);
if (!userId) {
return undefined;
}
return this.usersById.get(userId);
}
async findByUsername(
username: string,
): Promise<(User & { password_hash: string }) | undefined> {
const result = await this.database.query<UserRow>(
'users.findByUsername',
'SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1',
[username],
);
const row = result.rows[0];
return row
? { ...toUser(row), password_hash: row.password_hash }
: undefined;
}
save(user: User): void {
this.usersById.set(user.id, user);
this.userIdByUsername.set(user.username, user.id);
}
async create(user: {
id: string;
username: string;
display_name: string;
password_hash: string;
}): Promise<User> {
try {
const result = await this.database.query<UserRow>(
'users.insert',
`INSERT INTO users (id, username, display_name, password_hash)
VALUES ($1, $2, $3, $4)
RETURNING id, username, display_name, password_hash, created_at`,
[user.id, user.username, user.display_name, user.password_hash],
);
return toUser(result.rows[0]);
} catch (error) {
if ((error as { code?: string }).code === '23505')
throw new ConflictException('Username already exists');
throw error;
}
}
}
+18 -25
View File
@@ -1,45 +1,38 @@
import {
BadRequestException,
ConflictException,
Injectable,
} from '@nestjs/common';
import { UsersRepository } from './users.repository.js';
import { BadRequestException, Injectable } from '@nestjs/common';
import argon2 from 'argon2';
import { randomUUID } from 'node:crypto';
import { CreateUserDTO } from './dto/create-user.dto.js';
import { User } from './user.js';
import { randomUUID } from 'node:crypto';
import { UsersRepository } from './users.repository.js';
@Injectable()
export class UsersService {
constructor(private readonly usersRepository: UsersRepository) {}
create(input: CreateUserDTO): User {
const displayNameLength = [...input.display_name].length;
async create(input: CreateUserDTO): Promise<User> {
if (
displayNameLength < 1 ||
displayNameLength > 100 ||
[...input.display_name].length < 1 ||
[...input.display_name].length > 100 ||
input.display_name.trim().length === 0
) {
throw new BadRequestException('Invalid display name');
}
if (this.usersRepository.findByUsername(input.username)) {
throw new ConflictException('Username already exists');
}
const user: User = {
const passwordHash = await argon2.hash(input.password, {
type: argon2.argon2id,
});
return this.usersRepository.create({
id: randomUUID(),
username: input.username,
display_name: input.display_name,
created_at: new Date().toISOString(),
};
this.usersRepository.save(user);
return user;
password_hash: passwordHash,
});
}
findById(id: string): User | undefined {
findById(id: string): Promise<User | undefined> {
return this.usersRepository.findById(id);
}
findByUsername(username: string) {
return this.usersRepository.findByUsername(username);
}
}