|
| 1 | +import { db } from '@sim/db' |
| 2 | +import { copilotChatMessages } from '@sim/db/schema' |
| 3 | +import { createLogger } from '@sim/logger' |
| 4 | +import { getErrorMessage } from '@sim/utils/errors' |
| 5 | +import { generateShortId } from '@sim/utils/id' |
| 6 | +import { eq, sql } from 'drizzle-orm' |
| 7 | + |
| 8 | +const logger = createLogger('CopilotChatMessagesDualWrite') |
| 9 | + |
| 10 | +/** |
| 11 | + * Build a row payload for `copilot_chat_messages` from a JSONB message blob. |
| 12 | + * The blob format mirrors what's stored in the legacy `copilot_chats.messages` |
| 13 | + * array — `id`, `role`, and optionally `model`/`createdAt` at the top level — |
| 14 | + * with the entire blob preserved as the row's `content` for forward compat. |
| 15 | + */ |
| 16 | +function toMessageRow( |
| 17 | + chatId: string, |
| 18 | + rawMessage: unknown, |
| 19 | + options?: { chatModel?: string | null; streamId?: string | null } |
| 20 | +): typeof copilotChatMessages.$inferInsert | null { |
| 21 | + if (!rawMessage || typeof rawMessage !== 'object') return null |
| 22 | + const msg = rawMessage as Record<string, unknown> |
| 23 | + const id = typeof msg.id === 'string' && msg.id.length > 0 ? msg.id : generateShortId() |
| 24 | + const role = typeof msg.role === 'string' ? msg.role : 'user' |
| 25 | + const model = |
| 26 | + typeof msg.model === 'string' && msg.model.length > 0 ? msg.model : (options?.chatModel ?? null) |
| 27 | + return { |
| 28 | + chatId, |
| 29 | + messageId: id, |
| 30 | + role, |
| 31 | + content: msg, |
| 32 | + model, |
| 33 | + streamId: options?.streamId ?? null, |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +/** |
| 38 | + * Append messages to the new `copilot_chat_messages` table. Best-effort — |
| 39 | + * errors are logged but never thrown, since the legacy `copilot_chats.messages` |
| 40 | + * JSONB column remains the source of truth during the dual-write rollout. |
| 41 | + */ |
| 42 | +export async function appendCopilotChatMessages( |
| 43 | + chatId: string, |
| 44 | + messages: unknown[], |
| 45 | + options?: { chatModel?: string | null; streamId?: string | null } |
| 46 | +): Promise<void> { |
| 47 | + if (!Array.isArray(messages) || messages.length === 0) return |
| 48 | + |
| 49 | + const rows = messages |
| 50 | + .map((msg) => toMessageRow(chatId, msg, options)) |
| 51 | + .filter((row): row is typeof copilotChatMessages.$inferInsert => row !== null) |
| 52 | + |
| 53 | + if (rows.length === 0) return |
| 54 | + |
| 55 | + try { |
| 56 | + await db |
| 57 | + .insert(copilotChatMessages) |
| 58 | + .values(rows) |
| 59 | + .onConflictDoUpdate({ |
| 60 | + target: [copilotChatMessages.chatId, copilotChatMessages.messageId], |
| 61 | + set: { |
| 62 | + content: sql`excluded.content`, |
| 63 | + role: sql`excluded.role`, |
| 64 | + model: sql`excluded.model`, |
| 65 | + updatedAt: sql`now()`, |
| 66 | + }, |
| 67 | + }) |
| 68 | + } catch (err) { |
| 69 | + logger.warn('Failed to append copilot chat messages', { |
| 70 | + chatId, |
| 71 | + messageCount: rows.length, |
| 72 | + error: getErrorMessage(err), |
| 73 | + }) |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +/** |
| 78 | + * Replace all messages for a chat. Used by the update-messages endpoint that |
| 79 | + * receives a full snapshot of the conversation state. Best-effort. |
| 80 | + */ |
| 81 | +export async function replaceCopilotChatMessages( |
| 82 | + chatId: string, |
| 83 | + messages: unknown[], |
| 84 | + options?: { chatModel?: string | null } |
| 85 | +): Promise<void> { |
| 86 | + if (!Array.isArray(messages)) return |
| 87 | + |
| 88 | + const rows = messages |
| 89 | + .map((msg) => toMessageRow(chatId, msg, options)) |
| 90 | + .filter((row): row is typeof copilotChatMessages.$inferInsert => row !== null) |
| 91 | + |
| 92 | + try { |
| 93 | + await db.transaction(async (tx) => { |
| 94 | + await tx.delete(copilotChatMessages).where(eq(copilotChatMessages.chatId, chatId)) |
| 95 | + if (rows.length > 0) { |
| 96 | + await tx.insert(copilotChatMessages).values(rows) |
| 97 | + } |
| 98 | + }) |
| 99 | + } catch (err) { |
| 100 | + logger.warn('Failed to replace copilot chat messages', { |
| 101 | + chatId, |
| 102 | + messageCount: rows.length, |
| 103 | + error: getErrorMessage(err), |
| 104 | + }) |
| 105 | + } |
| 106 | +} |
0 commit comments