chore: migrate minimum from lab1

This commit is contained in:
2026-10-21 09:41:45 +03:00
parent 65003b6119
commit d8fb486709
44 changed files with 11664 additions and 0 deletions
+25
View File
@@ -0,0 +1,25 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { validate as isUuid } from '../uuid';
import { FastifyRequest } from 'fastify';
import { ApiError } from '../filters/api-error';
import { StoreService } from '../store/store.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private readonly store: StoreService) {}
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest<FastifyRequest>();
const header = request.headers['x-user-id'];
const userId = Array.isArray(header) ? header[0] : header;
if (!userId || !isUuid(userId)) {
throw new ApiError('unauthorized', 'Missing or invalid X-User-Id');
}
const user = this.store.getUserById(userId);
if (!user) {
throw new ApiError('unauthorized', 'Missing or invalid X-User-Id');
}
request.currentUser = user;
return true;
}
}
+19
View File
@@ -0,0 +1,19 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { FastifyRequest } from 'fastify';
import { User } from '../store/domain';
declare module 'fastify' {
interface FastifyRequest {
currentUser?: User;
}
}
export const CurrentUser = createParamDecorator(
(_data: unknown, ctx: ExecutionContext): User => {
const request = ctx.switchToHttp().getRequest<FastifyRequest>();
if (!request.currentUser) {
throw new Error('CurrentUser used without AuthGuard');
}
return request.currentUser;
},
);
+10
View File
@@ -0,0 +1,10 @@
import { Global, Module } from '@nestjs/common';
import { AuthGuard } from './auth/auth.guard';
import { StoreService } from './store/store.service';
@Global()
@Module({
providers: [StoreService, AuthGuard],
exports: [StoreService, AuthGuard],
})
export class CommonModule {}
@@ -0,0 +1,33 @@
import { registerDecorator, ValidationOptions } from 'class-validator';
export function codePointLength(value: string): number {
return [...value].length;
}
export function CodePointLength(
min: number,
max: number,
options?: ValidationOptions,
) {
return function (object: object, propertyName: string) {
registerDecorator({
name: 'codePointLength',
target: object.constructor,
propertyName,
constraints: [min, max],
options,
validator: {
validate(value: unknown): boolean {
if (typeof value !== 'string') {
return false;
}
const length = codePointLength(value);
return length >= min && length <= max;
},
defaultMessage(): string {
return `${propertyName} must be between ${min} and ${max} Unicode code points`;
},
},
});
};
}
+20
View File
@@ -0,0 +1,20 @@
import { registerDecorator, ValidationOptions } from 'class-validator';
export function NotBlank(options?: ValidationOptions) {
return function (object: object, propertyName: string) {
registerDecorator({
name: 'notBlank',
target: object.constructor,
propertyName,
options,
validator: {
validate(value: unknown): boolean {
return typeof value === 'string' && value.trim().length > 0;
},
defaultMessage(): string {
return `${propertyName} must not be empty or whitespace-only`;
},
},
});
};
}
+37
View File
@@ -0,0 +1,37 @@
import { ApiError } from '../filters/api-error';
const DEFAULT_LIMIT = 50;
const MIN_LIMIT = 1;
const MAX_LIMIT = 100;
export function parseLimit(raw: unknown): number {
if (raw === undefined) {
return DEFAULT_LIMIT;
}
const value = Array.isArray(raw) ? raw[0] : raw;
if (typeof value !== 'string' || !/^\d+$/.test(value)) {
throw new ApiError('invalid_request', 'limit must be an integer');
}
const limit = Number(value);
if (limit < MIN_LIMIT || limit > MAX_LIMIT) {
throw new ApiError(
'invalid_request',
`limit must be between ${MIN_LIMIT} and ${MAX_LIMIT}`,
);
}
return limit;
}
export function rawCursorParam(raw: unknown): string | null {
if (raw === undefined) {
return null;
}
const value = Array.isArray(raw) ? raw[0] : raw;
if (typeof value !== 'string' || value.length === 0) {
throw new ApiError(
'invalid_request',
'cursor must be a non-empty string',
);
}
return value;
}
+33
View File
@@ -0,0 +1,33 @@
import { HttpException, HttpStatus } from '@nestjs/common';
export type ErrorCode =
| 'invalid_request'
| 'unauthorized'
| 'not_found'
| 'conflict'
| 'payload_too_large'
| 'unsupported_media_type'
| 'rate_limited'
| 'unavailable'
| 'internal_error';
const STATUS_BY_CODE: Record<ErrorCode, number> = {
invalid_request: HttpStatus.BAD_REQUEST,
unauthorized: HttpStatus.UNAUTHORIZED,
not_found: HttpStatus.NOT_FOUND,
conflict: HttpStatus.CONFLICT,
payload_too_large: HttpStatus.PAYLOAD_TOO_LARGE,
unsupported_media_type: HttpStatus.UNSUPPORTED_MEDIA_TYPE,
rate_limited: HttpStatus.TOO_MANY_REQUESTS,
unavailable: HttpStatus.SERVICE_UNAVAILABLE,
internal_error: HttpStatus.INTERNAL_SERVER_ERROR,
};
export class ApiError extends HttpException {
constructor(
public readonly code: ErrorCode,
message: string,
) {
super(message, STATUS_BY_CODE[code]);
}
}
+104
View File
@@ -0,0 +1,104 @@
import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
HttpStatus,
Logger,
} from '@nestjs/common';
import { FastifyReply, FastifyRequest } from 'fastify';
import { ApiError, ErrorCode } from './api-error';
const CODE_BY_STATUS: Partial<Record<number, ErrorCode>> = {
[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',
};
interface Resolved {
status: number;
code: ErrorCode;
message: string;
}
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
private readonly logger = new Logger('HttpExceptionFilter');
catch(exception: unknown, host: ArgumentsHost): void {
const ctx = host.switchToHttp();
const reply = ctx.getResponse<FastifyReply>();
const request = ctx.getRequest<FastifyRequest>();
const requestId = request.requestId;
const { status, code, message } = this.resolve(exception);
if (status >= 500) {
this.logger.error(
`${request.method} ${request.url} -> ${status}: ${message}`,
);
}
reply
.code(status)
.header('x-request-id', requestId)
.send({ error: { code, message, request_id: requestId } });
}
private resolve(exception: unknown): Resolved {
if (exception instanceof ApiError) {
return {
status: exception.getStatus(),
code: exception.code,
message: exception.message,
};
}
if (exception instanceof HttpException) {
const status = exception.getStatus();
const code = CODE_BY_STATUS[status] ?? 'internal_error';
const message =
extractMessage(exception.getResponse()) ?? exception.message;
return { status, code, message };
}
const fastifyStatus = (exception as { statusCode?: unknown })
?.statusCode;
if (typeof fastifyStatus === 'number' && CODE_BY_STATUS[fastifyStatus]) {
const message =
exception instanceof Error ? exception.message : 'Invalid request';
return {
status: fastifyStatus,
code: CODE_BY_STATUS[fastifyStatus]!,
message,
};
}
return {
status: 500,
code: 'internal_error',
message: 'Internal server error',
};
}
}
function extractMessage(response: unknown): string | null {
if (typeof response === 'string') {
return response;
}
if (
typeof response === 'object' &&
response !== null &&
'message' in response
) {
const value = (response as { message: unknown }).message;
if (typeof value === 'string') {
return value;
}
if (Array.isArray(value) && value.every((v) => typeof v === 'string')) {
return value.join('; ');
}
}
return null;
}
+18
View File
@@ -0,0 +1,18 @@
import { randomUUID } from 'crypto';
import { FastifyInstance, FastifyRequest } from 'fastify';
const REQUEST_ID_HEADER = 'x-request-id';
declare module 'fastify' {
interface FastifyRequest {
requestId: string;
}
}
export function registerRequestId(instance: FastifyInstance): void {
instance.addHook('onRequest', (request: FastifyRequest, reply, done) => {
request.requestId = randomUUID();
reply.header(REQUEST_ID_HEADER, request.requestId);
done();
});
}
+21
View File
@@ -0,0 +1,21 @@
export interface User {
id: string;
username: string;
displayName: string;
createdAt: string;
}
export interface Chat {
id: string;
title: string;
memberIds: string[];
createdAt: string;
}
export interface Message {
id: string;
chatId: string;
senderId: string;
text: string;
createdAt: string;
}
+240
View File
@@ -0,0 +1,240 @@
import { Injectable } from '@nestjs/common';
import { randomUUID } from 'crypto';
import { Chat, Message, User } from './domain';
export interface ChatCursor {
id: string;
}
export interface MessageCursor {
chatId: string;
id: string;
}
interface Ordered {
id: string;
seq: number;
createdAt: string;
}
type StoredChat = Chat & Ordered;
type StoredMessage = Message & Ordered;
class OrderedList<T extends Ordered> {
private readonly items: T[] = [];
private readonly indexById = new Map<string, number>();
push(item: T): void {
this.items.push(item);
let index = this.items.length - 1;
while (
index > 0 &&
this.items[index - 1].createdAt === item.createdAt &&
this.items[index - 1].id > item.id
) {
this.items[index] = this.items[index - 1];
this.indexById.set(this.items[index].id, index);
index--;
}
this.items[index] = item;
this.indexById.set(item.id, index);
}
get length(): number {
return this.items.length;
}
toArray(): T[] {
return this.items;
}
page(afterId: string | null, limit: number): T[] {
if (afterId === null) {
return this.items.slice(0, limit);
}
const cursorIndex = this.indexById.get(afterId);
const startIndex =
cursorIndex === undefined ? this.items.length : cursorIndex + 1;
return this.items.slice(startIndex, startIndex + limit);
}
hasMoreAfter(lastId: string): boolean {
const cursorIndex = this.indexById.get(lastId);
return cursorIndex !== undefined && cursorIndex < this.items.length - 1;
}
hasId(id: string): boolean {
return this.indexById.has(id);
}
}
@Injectable()
export class StoreService {
private readonly usersById = new Map<string, User>();
private readonly userIdByUsername = new Map<string, string>();
private readonly chatsById = new Map<string, StoredChat>();
private readonly chatsByMember = new Map<string, OrderedList<StoredChat>>();
private readonly messagesByChatId = new Map<
string,
OrderedList<StoredMessage>
>();
private nextChatSeq = 0;
private nextMessageSeq = 0;
createUser(username: string, displayName: string): User | null {
if (this.userIdByUsername.has(username)) {
return null;
}
const user: User = {
id: randomUUID(),
username,
displayName,
createdAt: new Date().toISOString(),
};
this.usersById.set(user.id, user);
this.userIdByUsername.set(username, user.id);
return user;
}
getUserById(id: string): User | undefined {
return this.usersById.get(id);
}
createChat(title: string, memberIds: string[]): Chat {
const stored: StoredChat = {
id: randomUUID(),
title,
memberIds: [...memberIds],
createdAt: new Date().toISOString(),
seq: this.nextChatSeq++,
};
this.chatsById.set(stored.id, stored);
for (const memberId of memberIds) {
this.chatListFor(memberId).push(stored);
}
this.messagesByChatId.set(stored.id, new OrderedList<StoredMessage>());
return toPublicChat(stored);
}
getChatById(id: string): Chat | undefined {
const stored = this.chatsById.get(id);
return stored ? toPublicChat(stored) : undefined;
}
isMember(chatId: string, userId: string): boolean {
return !!this.chatsById.get(chatId)?.memberIds.includes(userId);
}
listChatsForMember(
userId: string,
afterCursor: ChatCursor | null,
limit: number,
): Chat[] {
return this.chatListFor(userId)
.page(afterCursor?.id ?? null, limit)
.map(toPublicChat);
}
hasMoreChatsAfter(userId: string, lastId: string): boolean {
return this.chatListFor(userId).hasMoreAfter(lastId);
}
chatCursorExists(userId: string, cursorId: string): boolean {
return this.chatListFor(userId).hasId(cursorId);
}
createMessage(chatId: string, senderId: string, text: string): Message {
const list = this.messagesByChatId.get(chatId);
if (!list) {
throw new Error('chat must exist before appending a message');
}
const stored: StoredMessage = {
id: randomUUID(),
chatId,
senderId,
text,
createdAt: new Date().toISOString(),
seq: this.nextMessageSeq++,
};
list.push(stored);
return toPublicMessage(stored);
}
listMessages(
chatId: string,
afterCursor: MessageCursor | null,
limit: number,
): Message[] {
const list = this.messagesByChatId.get(chatId);
if (!list) {
return [];
}
return list.page(afterCursor?.id ?? null, limit).map(toPublicMessage);
}
hasMoreMessagesAfter(chatId: string, lastId: string): boolean {
return this.messagesByChatId.get(chatId)?.hasMoreAfter(lastId) ?? false;
}
messageCursorExists(chatId: string, cursorId: string): boolean {
return this.messagesByChatId.get(chatId)?.hasId(cursorId) ?? false;
}
private chatListFor(memberId: string): OrderedList<StoredChat> {
let list = this.chatsByMember.get(memberId);
if (!list) {
list = new OrderedList<StoredChat>();
this.chatsByMember.set(memberId, list);
}
return list;
}
}
function toPublicChat(stored: StoredChat): Chat {
const { seq: _seq, ...chat } = stored;
return chat;
}
function toPublicMessage(stored: StoredMessage): Message {
const { seq: _seq, ...message } = stored;
return message;
}
export function encodeChatCursor(cursor: ChatCursor): string {
return encode(cursor);
}
export function decodeChatCursor(raw: string): ChatCursor | null {
const decoded = decode(raw);
return decoded && typeof decoded.id === 'string'
? { id: decoded.id }
: null;
}
export function encodeMessageCursor(cursor: MessageCursor): string {
return encode(cursor);
}
export function decodeMessageCursor(raw: string): MessageCursor | null {
const decoded = decode(raw);
return decoded &&
typeof decoded.chatId === 'string' &&
typeof decoded.id === 'string'
? { chatId: decoded.chatId, id: decoded.id }
: null;
}
function encode(value: object): string {
return Buffer.from(JSON.stringify(value), 'utf8').toString('base64url');
}
function decode(raw: string): Record<string, unknown> | null {
try {
const parsed = JSON.parse(
Buffer.from(raw, 'base64url').toString('utf8'),
);
return typeof parsed === 'object' && parsed !== null ? parsed : null;
} catch {
return null;
}
}
+6
View File
@@ -0,0 +1,6 @@
const UUID_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
export function validate(value: string): boolean {
return UUID_PATTERN.test(value);
}