|
| 1 | +import { json } from "@remix-run/server-runtime"; |
| 2 | +import { pageTranscriptEntries, parseTranscriptSnapshot } from "@trigger.dev/core/v3"; |
| 3 | +import { z } from "zod/v4"; |
| 4 | +import { $replica } from "~/db.server"; |
| 5 | +import { chatSnapshotStorageKey } from "~/services/realtime/chatSnapshot.server"; |
| 6 | +import { resolveSessionByIdOrExternalId } from "~/services/realtime/sessions.server"; |
| 7 | +import { anyResource, createLoaderApiRoute } from "~/services/routeBuilders/apiBuilder.server"; |
| 8 | +import { downloadPacketFromObjectStore } from "~/v3/objectStore.server"; |
| 9 | +import { logger } from "~/services/logger.server"; |
| 10 | + |
| 11 | +const ParamsSchema = z.object({ |
| 12 | + sessionId: z.string(), |
| 13 | +}); |
| 14 | + |
| 15 | +const SearchParamsSchema = z.object({ |
| 16 | + limit: z.coerce.number().int().min(1).max(1000).optional(), |
| 17 | + before: z.string().optional(), |
| 18 | +}); |
| 19 | + |
| 20 | +function sessionResource( |
| 21 | + paramId: string, |
| 22 | + session: { friendlyId: string; externalId: string | null } | null | undefined |
| 23 | +) { |
| 24 | + const ids = new Set<string>([paramId]); |
| 25 | + if (session) { |
| 26 | + ids.add(session.friendlyId); |
| 27 | + if (session.externalId) ids.add(session.externalId); |
| 28 | + } |
| 29 | + return anyResource([...ids].map((id) => ({ type: "sessions" as const, id }))); |
| 30 | +} |
| 31 | + |
| 32 | +function isObjectNotFound(error: unknown): boolean { |
| 33 | + if (!error) return false; |
| 34 | + const name = (error as { name?: unknown }).name; |
| 35 | + if (name === "NoSuchKey" || name === "NotFound") return true; |
| 36 | + const status = (error as { $metadata?: { httpStatusCode?: number } }).$metadata?.httpStatusCode; |
| 37 | + if (status === 404) return true; |
| 38 | + const message = error instanceof Error ? error.message : String(error); |
| 39 | + return /not found|nosuchkey|404|does not exist/i.test(message); |
| 40 | +} |
| 41 | + |
| 42 | +export const loader = createLoaderApiRoute( |
| 43 | + { |
| 44 | + params: ParamsSchema, |
| 45 | + searchParams: SearchParamsSchema, |
| 46 | + corsStrategy: "none", |
| 47 | + findResource: async (params, auth) => |
| 48 | + resolveSessionByIdOrExternalId($replica, auth.environment.id, params.sessionId), |
| 49 | + authorization: { |
| 50 | + action: "read", |
| 51 | + resource: (session, params) => sessionResource(params.sessionId, session), |
| 52 | + }, |
| 53 | + }, |
| 54 | + async ({ authentication, resource: session, searchParams }) => { |
| 55 | + if (!session) { |
| 56 | + return json({ error: "Session not found" }, { status: 404 }); |
| 57 | + } |
| 58 | + |
| 59 | + let body: unknown; |
| 60 | + try { |
| 61 | + const packet = await downloadPacketFromObjectStore( |
| 62 | + { dataType: "application/store", data: chatSnapshotStorageKey(session) }, |
| 63 | + authentication.environment |
| 64 | + ); |
| 65 | + body = typeof packet.data === "string" ? JSON.parse(packet.data) : undefined; |
| 66 | + } catch (error) { |
| 67 | + // A missing blob is a valid empty transcript (a session that has not |
| 68 | + // saved yet). Any other read failure must NOT look like an empty chat: |
| 69 | + // return an error so the client falls back to the whole-blob read |
| 70 | + // instead of rendering a saved conversation as empty. |
| 71 | + if (isObjectNotFound(error)) { |
| 72 | + return json({ messages: [], state: null }); |
| 73 | + } |
| 74 | + logger.error("transcript endpoint: snapshot read failed", { |
| 75 | + sessionId: session.friendlyId, |
| 76 | + error: error instanceof Error ? error.message : String(error), |
| 77 | + }); |
| 78 | + return json({ error: "Failed to read transcript" }, { status: 502 }); |
| 79 | + } |
| 80 | + |
| 81 | + const snapshot = parseTranscriptSnapshot(body); |
| 82 | + if (!snapshot) { |
| 83 | + return json({ messages: [], state: null }); |
| 84 | + } |
| 85 | + |
| 86 | + const page = pageTranscriptEntries(snapshot.messages, searchParams); |
| 87 | + return json({ |
| 88 | + messages: page.entries.map((entry) => entry.message), |
| 89 | + state: snapshot.state, |
| 90 | + cursors: { |
| 91 | + lastOutEventId: snapshot.lastOutEventId, |
| 92 | + lastInEventId: snapshot.lastInEventId, |
| 93 | + }, |
| 94 | + nextCursor: page.nextCursor, |
| 95 | + }); |
| 96 | + } |
| 97 | +); |
0 commit comments