forked from mtusi2026/mtusi2026lab2
feat: init after lab 1
This commit is contained in:
@@ -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,
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user