forked from mtusi2026/mtusi2026lab2
feat: init after lab 1
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ChatsModule } from './chats/chats.module.js';
|
||||
import { HealthModule } from './health/health.module.js';
|
||||
import { MessagesModule } from './messages/messages.module.js';
|
||||
import { UsersModule } from './users/users.module.js';
|
||||
|
||||
@Module({
|
||||
imports: [HealthModule, UsersModule, ChatsModule, MessagesModule],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -0,0 +1,6 @@
|
||||
export type Chat = {
|
||||
id: string;
|
||||
title: string;
|
||||
member_ids: string[];
|
||||
created_at: string;
|
||||
};
|
||||
@@ -0,0 +1,54 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
DefaultValuePipe,
|
||||
Get,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
ParseUUIDPipe,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
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';
|
||||
|
||||
@Controller('api/v1/chats')
|
||||
@UseGuards(CurrentUserGuard)
|
||||
export class ChatsController {
|
||||
constructor(private readonly chatsService: ChatsService) {}
|
||||
|
||||
@Post()
|
||||
create(@Body() body: CreateChatDto, @Req() request: FastifyRequest) {
|
||||
return this.chatsService.create(body, request.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');
|
||||
}
|
||||
|
||||
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!);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ChatsController } from './chats.controller.js';
|
||||
import { UsersModule } from '../users/users.module.js';
|
||||
import { ChatsRepository } from './chats.repository.js';
|
||||
import { ChatsService } from './chats.service.js';
|
||||
|
||||
@Module({
|
||||
imports: [UsersModule],
|
||||
controllers: [ChatsController],
|
||||
providers: [ChatsRepository, ChatsService],
|
||||
exports: [ChatsService],
|
||||
})
|
||||
export class ChatsModule {}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Chat } from './chat.js';
|
||||
|
||||
@Injectable()
|
||||
export class ChatsRepository {
|
||||
private readonly chatsById = new Map<string, Chat>();
|
||||
|
||||
save(chat: Chat): void {
|
||||
this.chatsById.set(chat.id, chat);
|
||||
}
|
||||
|
||||
findById(id: string): Chat | undefined {
|
||||
return this.chatsById.get(id);
|
||||
}
|
||||
|
||||
findAll(): Chat[] {
|
||||
return Array.from(this.chatsById.values());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import {
|
||||
decodeCursor,
|
||||
encodeCursor,
|
||||
isAfter,
|
||||
} 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 { ChatsRepository } from './chats.repository.js';
|
||||
|
||||
@Injectable()
|
||||
export class ChatsService {
|
||||
constructor(
|
||||
private readonly chatsRepository: ChatsRepository,
|
||||
private readonly usersService: UsersService,
|
||||
) {}
|
||||
|
||||
create(input: CreateChatDto, currentUser: User): Chat {
|
||||
if (!input.member_ids.includes(currentUser.id)) {
|
||||
throw new BadRequestException('Current user must be a chat member');
|
||||
}
|
||||
|
||||
for (const memberId of input.member_ids) {
|
||||
if (!this.usersService.findById(memberId)) {
|
||||
throw new BadRequestException('Chat member does not exist');
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import {
|
||||
ArrayMaxSize,
|
||||
ArrayMinSize,
|
||||
ArrayUnique,
|
||||
IsArray,
|
||||
IsString,
|
||||
IsUUID,
|
||||
Length,
|
||||
Matches,
|
||||
} from 'class-validator';
|
||||
|
||||
export class CreateChatDto {
|
||||
@IsString()
|
||||
@Length(1, 100)
|
||||
@Matches(/\S/, {
|
||||
message: 'title must contain a non-whitespace character',
|
||||
})
|
||||
title: string;
|
||||
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@ArrayMaxSize(100)
|
||||
@ArrayUnique()
|
||||
@IsUUID('4', { each: true })
|
||||
member_ids: string[];
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { isUUID } from 'class-validator';
|
||||
import type { User } from '../../users/user.js';
|
||||
import { UsersService } from '../../users/users.service.js';
|
||||
|
||||
export type RequestWithCurrentUser = {
|
||||
headers: {
|
||||
'x-user-id'?: string | string[];
|
||||
};
|
||||
currentUser?: User;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class CurrentUserGuard implements CanActivate {
|
||||
constructor(private readonly usersService: UsersService) {}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
const user = this.usersService.findById(header);
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
|
||||
request.currentUser = user;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
type RequestWithId = {
|
||||
requestId?: string;
|
||||
};
|
||||
|
||||
type HttpResponse = {
|
||||
header(name: string, value: string): void;
|
||||
status(code: number): HttpResponse;
|
||||
send(body: unknown): void;
|
||||
};
|
||||
|
||||
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';
|
||||
}
|
||||
}
|
||||
|
||||
@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>();
|
||||
|
||||
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';
|
||||
|
||||
if (exception instanceof HttpException) {
|
||||
status = exception.getStatus();
|
||||
const exceptionResponse = exception.getResponse();
|
||||
const rawMessage =
|
||||
typeof exceptionResponse === 'object' &&
|
||||
exceptionResponse !== null &&
|
||||
'message' in exceptionResponse
|
||||
? exceptionResponse.message
|
||||
: undefined;
|
||||
|
||||
message = Array.isArray(rawMessage)
|
||||
? rawMessage.join('; ')
|
||||
: typeof rawMessage === 'string'
|
||||
? rawMessage
|
||||
: 'Request failed';
|
||||
|
||||
if (status === HttpStatus.NOT_FOUND) {
|
||||
message = 'Resource not found';
|
||||
}
|
||||
}
|
||||
|
||||
response.status(status).send({
|
||||
error: {
|
||||
code: errorCodeForStatus(status),
|
||||
message: message,
|
||||
request_id: requestId,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
|
||||
export type Cursor = {
|
||||
scope: string;
|
||||
created_at: string;
|
||||
id: string;
|
||||
};
|
||||
|
||||
export function encodeCursor(cursor: Cursor): string {
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
export function isAfter(
|
||||
createdAt: string,
|
||||
id: string,
|
||||
cursor: Cursor,
|
||||
): boolean {
|
||||
return (
|
||||
createdAt > cursor.created_at ||
|
||||
(createdAt === cursor.created_at && id > cursor.id)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import {
|
||||
CallHandler,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
NestInterceptor,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
type RequestWithId = {
|
||||
requestId?: string;
|
||||
};
|
||||
|
||||
type ResponseWithHeader = {
|
||||
header(name: string, value: string): void;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class RequestIdInterceptor implements NestInterceptor {
|
||||
intercept(
|
||||
context: ExecutionContext,
|
||||
next: CallHandler<any>,
|
||||
): Observable<any> | Promise<Observable<any>> {
|
||||
const request = context.switchToHttp().getRequest<RequestWithId>();
|
||||
|
||||
const response = context.switchToHttp().getResponse<ResponseWithHeader>();
|
||||
|
||||
const requestId = randomUUID();
|
||||
|
||||
request.requestId = requestId;
|
||||
response.header('X-Request-Id', requestId);
|
||||
|
||||
return next.handle();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { HealthService } from './health.service.js';
|
||||
|
||||
@Controller('health')
|
||||
export class HealthController {
|
||||
constructor(private readonly healthService: HealthService) {}
|
||||
|
||||
@Get('live')
|
||||
getLive() {
|
||||
return this.healthService.getLiveness();
|
||||
}
|
||||
|
||||
@Get('ready')
|
||||
getReady() {
|
||||
return this.healthService.getReadiness();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HealthController } from './health.controller.js';
|
||||
import { HealthService } from './health.service.js';
|
||||
|
||||
@Module({
|
||||
imports: [],
|
||||
controllers: [HealthController],
|
||||
providers: [HealthService],
|
||||
})
|
||||
export class HealthModule {}
|
||||
@@ -0,0 +1,57 @@
|
||||
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;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import {
|
||||
Injectable,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
import type { BeforeApplicationShutdown } from '@nestjs/common';
|
||||
|
||||
@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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
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 { RequestIdInterceptor } from './common/http/request-id.interceptor.js';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create<NestFastifyApplication>(
|
||||
AppModule,
|
||||
new FastifyAdapter({
|
||||
logger: true,
|
||||
}),
|
||||
);
|
||||
|
||||
app.useGlobalInterceptors(new RequestIdInterceptor());
|
||||
app.useGlobalFilters(new ApiExceptionFilter());
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
transform: true,
|
||||
}),
|
||||
);
|
||||
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');
|
||||
}
|
||||
|
||||
await app.listen(port, host);
|
||||
}
|
||||
await bootstrap();
|
||||
@@ -0,0 +1,7 @@
|
||||
import { IsString, Length } from 'class-validator';
|
||||
|
||||
export class CreateMessageDto {
|
||||
@IsString()
|
||||
@Length(1, 4000)
|
||||
text!: string;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export type Message = {
|
||||
id: string;
|
||||
chat_id: string;
|
||||
sender_id: string;
|
||||
text: string;
|
||||
created_at: string;
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
DefaultValuePipe,
|
||||
Get,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
ParseUUIDPipe,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import type { FastifyRequest } from 'fastify';
|
||||
import { CurrentUserGuard } from '../common/auth/current-user.guard.js';
|
||||
import type { RequestWithCurrentUser } from '../common/auth/current-user.guard.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) {}
|
||||
|
||||
@Post()
|
||||
create(
|
||||
@Param('chatId', new ParseUUIDPipe()) chatId: string,
|
||||
@Body() body: CreateMessageDto,
|
||||
@Req() request: MessageRequest,
|
||||
) {
|
||||
return this.messagesService.create(chatId, body, request.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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
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';
|
||||
|
||||
@Module({
|
||||
imports: [UsersModule, ChatsModule],
|
||||
controllers: [MessagesController],
|
||||
providers: [MessagesRepository, MessagesService],
|
||||
})
|
||||
export class MessagesModule {}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { Cursor } from '../common/http/cursor.js';
|
||||
import type { Message } from './message.js';
|
||||
import { MessagesRepository } from './messages.repository.js';
|
||||
|
||||
const message = (id: string, created_at: string): Message => ({
|
||||
id,
|
||||
chat_id: 'chat',
|
||||
sender_id: 'sender',
|
||||
text: id,
|
||||
created_at,
|
||||
});
|
||||
|
||||
describe('MessagesRepository', () => {
|
||||
it('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'));
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { Cursor } from '../common/http/cursor.js';
|
||||
import { isAfter } from '../common/http/cursor.js';
|
||||
import type { Message } from './message.js';
|
||||
|
||||
@Injectable()
|
||||
export class MessagesRepository {
|
||||
private readonly messagesByChatId = new Map<string, Message[]>();
|
||||
|
||||
save(message: Message): void {
|
||||
const messages = this.messagesByChatId.get(message.chat_id) ?? [];
|
||||
const last = messages.at(-1);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
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';
|
||||
|
||||
@Injectable()
|
||||
export class MessagesService {
|
||||
constructor(
|
||||
private readonly messagesRepository: MessagesRepository,
|
||||
private readonly chatsService: ChatsService,
|
||||
) {}
|
||||
|
||||
create(
|
||||
chatId: string,
|
||||
input: CreateMessageDto,
|
||||
currentUser: User,
|
||||
): Message {
|
||||
const chat = this.chatsService.getForUser(chatId, currentUser);
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
import { User } from './users/user.ts';
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyRequest {
|
||||
currentUser?: User;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { IsNotEmpty, IsString, Matches } from 'class-validator';
|
||||
|
||||
export class CreateUserDTO {
|
||||
@IsString()
|
||||
@Matches(/^[a-z0-9_]{3,32}$/)
|
||||
username: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
display_name: string;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export type User = {
|
||||
id: string;
|
||||
username: string;
|
||||
display_name: string;
|
||||
created_at: string;
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
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 { CurrentUserGuard } from '../common/auth/current-user.guard.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(@Req() request: FastifyRequest) {
|
||||
return request.currentUser;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
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';
|
||||
|
||||
@Module({
|
||||
controllers: [UsersController],
|
||||
providers: [UsersRepository, UsersService, CurrentUserGuard],
|
||||
exports: [UsersService, CurrentUserGuard],
|
||||
})
|
||||
export class UsersModule {}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { User } from './user.js';
|
||||
|
||||
@Injectable()
|
||||
export class UsersRepository {
|
||||
private readonly usersById = new Map<string, User>();
|
||||
private readonly userIdByUsername = new Map<string, string>();
|
||||
|
||||
findById(id: string): User | undefined {
|
||||
return this.usersById.get(id);
|
||||
}
|
||||
|
||||
findByUsername(username: string): User | undefined {
|
||||
const userId = this.userIdByUsername.get(username);
|
||||
if (!userId) {
|
||||
return undefined;
|
||||
}
|
||||
return this.usersById.get(userId);
|
||||
}
|
||||
|
||||
save(user: User): void {
|
||||
this.usersById.set(user.id, user);
|
||||
this.userIdByUsername.set(user.username, user.id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { UsersRepository } from './users.repository.js';
|
||||
import { CreateUserDTO } from './dto/create-user.dto.js';
|
||||
import { User } from './user.js';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
constructor(private readonly usersRepository: UsersRepository) {}
|
||||
|
||||
create(input: CreateUserDTO): User {
|
||||
const displayNameLength = [...input.display_name].length;
|
||||
|
||||
if (
|
||||
displayNameLength < 1 ||
|
||||
displayNameLength > 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 = {
|
||||
id: randomUUID(),
|
||||
username: input.username,
|
||||
display_name: input.display_name,
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
|
||||
this.usersRepository.save(user);
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
findById(id: string): User | undefined {
|
||||
return this.usersRepository.findById(id);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user