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