|
| 1 | +import { json } from "@remix-run/server-runtime"; |
| 2 | +import { |
| 3 | + CreateSessionRequestBody, |
| 4 | + type CreatedSessionResponseBody, |
| 5 | + ListSessionsQueryParams, |
| 6 | + type ListSessionsResponseBody, |
| 7 | + type SessionStatus, |
| 8 | +} from "@trigger.dev/core/v3"; |
| 9 | +import { SessionId } from "@trigger.dev/core/v3/isomorphic"; |
| 10 | +import type { Prisma, Session } from "@trigger.dev/database"; |
| 11 | +import { $replica, prisma, type PrismaClient } from "~/db.server"; |
| 12 | +import { clickhouseClient } from "~/services/clickhouseInstance.server"; |
| 13 | +import { serializeSession } from "~/services/realtime/sessions.server"; |
| 14 | +import { SessionsRepository } from "~/services/sessionsRepository/sessionsRepository.server"; |
| 15 | +import { |
| 16 | + createActionApiRoute, |
| 17 | + createLoaderApiRoute, |
| 18 | +} from "~/services/routeBuilders/apiBuilder.server"; |
| 19 | +import { ServiceValidationError } from "~/v3/services/common.server"; |
| 20 | + |
| 21 | +function asArray<T>(value: T | T[] | undefined): T[] | undefined { |
| 22 | + if (value === undefined) return undefined; |
| 23 | + return Array.isArray(value) ? value : [value]; |
| 24 | +} |
| 25 | + |
| 26 | +export const loader = createLoaderApiRoute( |
| 27 | + { |
| 28 | + searchParams: ListSessionsQueryParams, |
| 29 | + findResource: async () => 1, |
| 30 | + }, |
| 31 | + async ({ searchParams, authentication }) => { |
| 32 | + const repository = new SessionsRepository({ |
| 33 | + clickhouse: clickhouseClient, |
| 34 | + prisma: $replica as PrismaClient, |
| 35 | + }); |
| 36 | + |
| 37 | + // `page[after]` is the forward cursor, `page[before]` is the backward |
| 38 | + // cursor. The repository internally keys off `{cursor, direction}`. |
| 39 | + const cursor = searchParams["page[after]"] ?? searchParams["page[before]"]; |
| 40 | + const direction = searchParams["page[before]"] ? "backward" : "forward"; |
| 41 | + |
| 42 | + const { sessions: rows, pagination } = await repository.listSessions({ |
| 43 | + organizationId: authentication.environment.organizationId, |
| 44 | + projectId: authentication.environment.projectId, |
| 45 | + environmentId: authentication.environment.id, |
| 46 | + types: asArray(searchParams["filter[type]"]), |
| 47 | + tags: asArray(searchParams["filter[tags]"]), |
| 48 | + taskIdentifiers: asArray(searchParams["filter[taskIdentifier]"]), |
| 49 | + externalId: searchParams["filter[externalId]"], |
| 50 | + statuses: asArray(searchParams["filter[status]"]) as SessionStatus[] | undefined, |
| 51 | + period: searchParams["filter[createdAt][period]"], |
| 52 | + from: searchParams["filter[createdAt][from]"], |
| 53 | + to: searchParams["filter[createdAt][to]"], |
| 54 | + page: { |
| 55 | + size: searchParams["page[size]"], |
| 56 | + cursor, |
| 57 | + direction, |
| 58 | + }, |
| 59 | + }); |
| 60 | + |
| 61 | + return json<ListSessionsResponseBody>({ |
| 62 | + data: rows.map((session) => |
| 63 | + serializeSession({ |
| 64 | + ...session, |
| 65 | + // Columns the list query doesn't select — filled so `serializeSession` |
| 66 | + // can operate on a narrowed payload without type errors. |
| 67 | + projectId: authentication.environment.projectId, |
| 68 | + environmentType: authentication.environment.type, |
| 69 | + organizationId: authentication.environment.organizationId, |
| 70 | + } as Session) |
| 71 | + ), |
| 72 | + pagination: { |
| 73 | + ...(pagination.nextCursor ? { next: pagination.nextCursor } : {}), |
| 74 | + ...(pagination.previousCursor ? { previous: pagination.previousCursor } : {}), |
| 75 | + }, |
| 76 | + }); |
| 77 | + } |
| 78 | +); |
| 79 | + |
| 80 | +const { action } = createActionApiRoute( |
| 81 | + { |
| 82 | + body: CreateSessionRequestBody, |
| 83 | + method: "POST", |
| 84 | + maxContentLength: 1024 * 32, // 32KB — metadata is the only thing that grows |
| 85 | + }, |
| 86 | + async ({ authentication, body }) => { |
| 87 | + try { |
| 88 | + let session: Session; |
| 89 | + let isCached = false; |
| 90 | + |
| 91 | + if (body.externalId) { |
| 92 | + // Idempotent: (env, externalId) uniquely identifies the Session. |
| 93 | + const existing = await prisma.session.findUnique({ |
| 94 | + where: { |
| 95 | + runtimeEnvironmentId_externalId: { |
| 96 | + runtimeEnvironmentId: authentication.environment.id, |
| 97 | + externalId: body.externalId, |
| 98 | + }, |
| 99 | + }, |
| 100 | + }); |
| 101 | + |
| 102 | + if (existing) { |
| 103 | + session = existing; |
| 104 | + isCached = true; |
| 105 | + } else { |
| 106 | + const { id, friendlyId } = SessionId.generate(); |
| 107 | + session = await prisma.session.create({ |
| 108 | + data: { |
| 109 | + id, |
| 110 | + friendlyId, |
| 111 | + externalId: body.externalId, |
| 112 | + type: body.type, |
| 113 | + taskIdentifier: body.taskIdentifier ?? null, |
| 114 | + tags: body.tags ?? [], |
| 115 | + metadata: body.metadata as Prisma.InputJsonValue | undefined, |
| 116 | + expiresAt: body.expiresAt ?? null, |
| 117 | + projectId: authentication.environment.projectId, |
| 118 | + runtimeEnvironmentId: authentication.environment.id, |
| 119 | + environmentType: authentication.environment.type, |
| 120 | + organizationId: authentication.environment.organizationId, |
| 121 | + }, |
| 122 | + }); |
| 123 | + } |
| 124 | + } else { |
| 125 | + const { id, friendlyId } = SessionId.generate(); |
| 126 | + session = await prisma.session.create({ |
| 127 | + data: { |
| 128 | + id, |
| 129 | + friendlyId, |
| 130 | + type: body.type, |
| 131 | + taskIdentifier: body.taskIdentifier ?? null, |
| 132 | + tags: body.tags ?? [], |
| 133 | + metadata: body.metadata as Prisma.InputJsonValue | undefined, |
| 134 | + expiresAt: body.expiresAt ?? null, |
| 135 | + projectId: authentication.environment.projectId, |
| 136 | + runtimeEnvironmentId: authentication.environment.id, |
| 137 | + environmentType: authentication.environment.type, |
| 138 | + organizationId: authentication.environment.organizationId, |
| 139 | + }, |
| 140 | + }); |
| 141 | + } |
| 142 | + |
| 143 | + return json<CreatedSessionResponseBody>( |
| 144 | + { ...serializeSession(session), isCached }, |
| 145 | + { status: isCached ? 200 : 201 } |
| 146 | + ); |
| 147 | + } catch (error) { |
| 148 | + if (error instanceof ServiceValidationError) { |
| 149 | + return json({ error: error.message }, { status: 422 }); |
| 150 | + } |
| 151 | + if (error instanceof Error) { |
| 152 | + return json({ error: error.message }, { status: 500 }); |
| 153 | + } |
| 154 | + return json({ error: "Something went wrong" }, { status: 500 }); |
| 155 | + } |
| 156 | + } |
| 157 | +); |
| 158 | + |
| 159 | +export { action }; |
0 commit comments