Files
stack/packages/brain/src/conversations.ts
Jason Woltje 3b81bc9f3d perf: gateway + DB + frontend optimizations (P8-003)
- DB client: configure connection pool (max=20, idle_timeout=30s, connect_timeout=5s)
- DB schema: add missing indexes for auth sessions, accounts, conversations, agent_logs
- DB schema: promote preferences(user_id,key) to UNIQUE index for ON CONFLICT upsert
- Drizzle migration: 0003_p8003_perf_indexes.sql
- preferences.service: replace 2-query SELECT+INSERT/UPDATE with single-round-trip upsert
- conversations repo: add ORDER BY + LIMIT to findAll (200) and findMessages (500)
- session-gc.service: make onModuleInit fire-and-forget (removes cold-start TTFB block)
- next.config.ts: enable compress, productionBrowserSourceMaps:false, image avif/webp
- docs/PERFORMANCE.md: full profiling report and change impact notes
2026-03-18 21:26:45 -05:00

65 lines
2.1 KiB
TypeScript

import { eq, asc, desc, type Db, conversations, messages } from '@mosaic/db';
/** Maximum number of conversations returned per list query. */
const MAX_CONVERSATIONS = 200;
/** Maximum number of messages returned per conversation history query. */
const MAX_MESSAGES = 500;
export type Conversation = typeof conversations.$inferSelect;
export type NewConversation = typeof conversations.$inferInsert;
export type Message = typeof messages.$inferSelect;
export type NewMessage = typeof messages.$inferInsert;
export function createConversationsRepo(db: Db) {
return {
async findAll(userId: string): Promise<Conversation[]> {
return db
.select()
.from(conversations)
.where(eq(conversations.userId, userId))
.orderBy(desc(conversations.updatedAt))
.limit(MAX_CONVERSATIONS);
},
async findById(id: string): Promise<Conversation | undefined> {
const rows = await db.select().from(conversations).where(eq(conversations.id, id));
return rows[0];
},
async create(data: NewConversation): Promise<Conversation> {
const rows = await db.insert(conversations).values(data).returning();
return rows[0]!;
},
async update(id: string, data: Partial<NewConversation>): Promise<Conversation | undefined> {
const rows = await db
.update(conversations)
.set({ ...data, updatedAt: new Date() })
.where(eq(conversations.id, id))
.returning();
return rows[0];
},
async remove(id: string): Promise<boolean> {
const rows = await db.delete(conversations).where(eq(conversations.id, id)).returning();
return rows.length > 0;
},
async findMessages(conversationId: string): Promise<Message[]> {
return db
.select()
.from(messages)
.where(eq(messages.conversationId, conversationId))
.orderBy(asc(messages.createdAt))
.limit(MAX_MESSAGES);
},
async addMessage(data: NewMessage): Promise<Message> {
const rows = await db.insert(messages).values(data).returning();
return rows[0]!;
},
};
}
export type ConversationsRepo = ReturnType<typeof createConversationsRepo>;