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,22 @@
|
||||
import { IsString, Matches } from 'class-validator';
|
||||
import { CodePointLength } from '../../common/validation/code-point-length.js';
|
||||
|
||||
export class CreateUserDTO {
|
||||
@IsString()
|
||||
@Matches(/^[a-z0-9_]{3,32}$/)
|
||||
username!: string;
|
||||
|
||||
@IsString()
|
||||
@CodePointLength(1, 100)
|
||||
@Matches(/\S/u, {
|
||||
message: 'display_name must contain a non-whitespace character',
|
||||
})
|
||||
display_name!: string;
|
||||
|
||||
@IsString()
|
||||
@CodePointLength(12, 128)
|
||||
@Matches(/\S/u, {
|
||||
message: 'password must contain a non-whitespace character',
|
||||
})
|
||||
password!: string;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export type User = {
|
||||
id: string;
|
||||
username: string;
|
||||
display_name: string;
|
||||
created_at: string;
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
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 {
|
||||
constructor(private readonly usersService: UsersService) {}
|
||||
|
||||
@Post()
|
||||
create(@Body() body: CreateUserDTO) {
|
||||
return this.usersService.create(body);
|
||||
}
|
||||
|
||||
@Get('/me')
|
||||
@UseGuards(CurrentUserGuard)
|
||||
getMe(@CurrentUser() currentUser: User) {
|
||||
return currentUser;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
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, RedisModule, MetricsModule],
|
||||
})
|
||||
export class UsersModule {}
|
||||
@@ -0,0 +1,71 @@
|
||||
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 {
|
||||
constructor(private readonly database: DatabaseClient) {}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { 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 { UsersRepository } from './users.repository.js';
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
constructor(private readonly usersRepository: UsersRepository) {}
|
||||
|
||||
async create(input: CreateUserDTO): Promise<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,
|
||||
password_hash: passwordHash,
|
||||
});
|
||||
}
|
||||
|
||||
findById(id: string): Promise<User | undefined> {
|
||||
return this.usersRepository.findById(id);
|
||||
}
|
||||
|
||||
findByUsername(username: string) {
|
||||
return this.usersRepository.findByUsername(username);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user