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 { private readonly items: T[] = []; private readonly indexById = new Map(); 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(); private readonly userIdByUsername = new Map(); private readonly chatsById = new Map(); private readonly chatsByMember = new Map>(); private readonly messagesByChatId = new Map< string, OrderedList >(); 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()); 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 { let list = this.chatsByMember.get(memberId); if (!list) { list = new OrderedList(); 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 | null { try { const parsed = JSON.parse( Buffer.from(raw, 'base64url').toString('utf8'), ); return typeof parsed === 'object' && parsed !== null ? parsed : null; } catch { return null; } }