Files
mtusi2026lab2/src/common/store/store.service.ts
T

241 lines
5.9 KiB
TypeScript

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;
}
}