|
| 1 | +import { json } from "@remix-run/server-runtime"; |
| 2 | +import { |
| 3 | + CreateSessionStreamWaitpointRequestBody, |
| 4 | + type CreateSessionStreamWaitpointResponseBody, |
| 5 | +} from "@trigger.dev/core/v3"; |
| 6 | +import { WaitpointId } from "@trigger.dev/core/v3/isomorphic"; |
| 7 | +import { z } from "zod"; |
| 8 | +import { $replica } from "~/db.server"; |
| 9 | +import { createWaitpointTag, MAX_TAGS_PER_WAITPOINT } from "~/models/waitpointTag.server"; |
| 10 | +import { |
| 11 | + canonicalSessionAddressingKey, |
| 12 | + isSessionFriendlyIdForm, |
| 13 | + resolveSessionByIdOrExternalId, |
| 14 | +} from "~/services/realtime/sessions.server"; |
| 15 | +import { S2RealtimeStreams } from "~/services/realtime/s2realtimeStreams.server"; |
| 16 | +import { getRealtimeStreamInstance } from "~/services/realtime/v1StreamsGlobal.server"; |
| 17 | +import { |
| 18 | + addSessionStreamWaitpoint, |
| 19 | + removeSessionStreamWaitpoint, |
| 20 | +} from "~/services/sessionStreamWaitpointCache.server"; |
| 21 | +import { createActionApiRoute } from "~/services/routeBuilders/apiBuilder.server"; |
| 22 | +import { logger } from "~/services/logger.server"; |
| 23 | +import { parseDelay } from "~/utils/delays"; |
| 24 | +import { resolveIdempotencyKeyTTL } from "~/utils/idempotencyKeys.server"; |
| 25 | +import { engine } from "~/v3/runEngine.server"; |
| 26 | +import { ServiceValidationError } from "~/v3/services/baseService.server"; |
| 27 | + |
| 28 | +const ParamsSchema = z.object({ |
| 29 | + runFriendlyId: z.string(), |
| 30 | +}); |
| 31 | + |
| 32 | +const { action, loader } = createActionApiRoute( |
| 33 | + { |
| 34 | + params: ParamsSchema, |
| 35 | + body: CreateSessionStreamWaitpointRequestBody, |
| 36 | + maxContentLength: 1024 * 10, // 10KB |
| 37 | + method: "POST", |
| 38 | + }, |
| 39 | + async ({ authentication, body, params }) => { |
| 40 | + try { |
| 41 | + const run = await $replica.taskRun.findFirst({ |
| 42 | + where: { |
| 43 | + friendlyId: params.runFriendlyId, |
| 44 | + runtimeEnvironmentId: authentication.environment.id, |
| 45 | + }, |
| 46 | + select: { |
| 47 | + id: true, |
| 48 | + friendlyId: true, |
| 49 | + realtimeStreamsVersion: true, |
| 50 | + }, |
| 51 | + }); |
| 52 | + |
| 53 | + if (!run) { |
| 54 | + return json({ error: "Run not found" }, { status: 404 }); |
| 55 | + } |
| 56 | + |
| 57 | + // Row-optional addressing — see the .out / .in.append handlers. |
| 58 | + // The waitpoint cache + S2 stream key derive from the row's |
| 59 | + // canonical identity (externalId if set, else friendlyId), so |
| 60 | + // the agent's wait registration and the append-side drain |
| 61 | + // converge regardless of which URL form each side used. |
| 62 | + const maybeSession = await resolveSessionByIdOrExternalId( |
| 63 | + $replica, |
| 64 | + authentication.environment.id, |
| 65 | + body.session |
| 66 | + ); |
| 67 | + |
| 68 | + if (!maybeSession && isSessionFriendlyIdForm(body.session)) { |
| 69 | + return json({ error: "Session not found" }, { status: 404 }); |
| 70 | + } |
| 71 | + |
| 72 | + const addressingKey = canonicalSessionAddressingKey(maybeSession, body.session); |
| 73 | + |
| 74 | + const idempotencyKeyExpiresAt = body.idempotencyKeyTTL |
| 75 | + ? resolveIdempotencyKeyTTL(body.idempotencyKeyTTL) |
| 76 | + : undefined; |
| 77 | + |
| 78 | + const timeout = await parseDelay(body.timeout); |
| 79 | + |
| 80 | + const bodyTags = typeof body.tags === "string" ? [body.tags] : body.tags; |
| 81 | + |
| 82 | + if (bodyTags && bodyTags.length > MAX_TAGS_PER_WAITPOINT) { |
| 83 | + throw new ServiceValidationError( |
| 84 | + `Waitpoints can only have ${MAX_TAGS_PER_WAITPOINT} tags, you're trying to set ${bodyTags.length}.` |
| 85 | + ); |
| 86 | + } |
| 87 | + |
| 88 | + if (bodyTags && bodyTags.length > 0) { |
| 89 | + for (const tag of bodyTags) { |
| 90 | + await createWaitpointTag({ |
| 91 | + tag, |
| 92 | + environmentId: authentication.environment.id, |
| 93 | + projectId: authentication.environment.projectId, |
| 94 | + }); |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + // Step 1: Create the waitpoint. |
| 99 | + const result = await engine.createManualWaitpoint({ |
| 100 | + environmentId: authentication.environment.id, |
| 101 | + projectId: authentication.environment.projectId, |
| 102 | + idempotencyKey: body.idempotencyKey, |
| 103 | + idempotencyKeyExpiresAt, |
| 104 | + timeout, |
| 105 | + tags: bodyTags, |
| 106 | + }); |
| 107 | + |
| 108 | + // Step 2: Register the waitpoint on the session channel so the next |
| 109 | + // append fires it. Keyed by (addressingKey, io) — the canonical |
| 110 | + // string for the row. The append handler drains by the same |
| 111 | + // canonical key, so writers and readers converge regardless of |
| 112 | + // which URL form the agent vs. the appending caller used. |
| 113 | + const ttlMs = timeout ? timeout.getTime() - Date.now() : undefined; |
| 114 | + await addSessionStreamWaitpoint( |
| 115 | + addressingKey, |
| 116 | + body.io, |
| 117 | + result.waitpoint.id, |
| 118 | + ttlMs && ttlMs > 0 ? ttlMs : undefined |
| 119 | + ); |
| 120 | + |
| 121 | + // Step 3: Race-check. If a record landed on the channel before this |
| 122 | + // .wait() call, complete the waitpoint synchronously with that data |
| 123 | + // and remove the pending registration. |
| 124 | + if (!result.isCached) { |
| 125 | + try { |
| 126 | + // Session streams are always v2 (S2) — the writer in |
| 127 | + // `appendPartToSessionStream` and the SSE subscribe both |
| 128 | + // hardcode "v2", so the race-check reader has to match. |
| 129 | + // Don't fall through to the run's own `realtimeStreamsVersion`, |
| 130 | + // which only describes the run's run-scoped streams. |
| 131 | + const realtimeStream = getRealtimeStreamInstance(authentication.environment, "v2"); |
| 132 | + |
| 133 | + if (realtimeStream instanceof S2RealtimeStreams) { |
| 134 | + const records = await realtimeStream.readSessionStreamRecords( |
| 135 | + addressingKey, |
| 136 | + body.io, |
| 137 | + body.lastSeqNum |
| 138 | + ); |
| 139 | + |
| 140 | + if (records.length > 0) { |
| 141 | + const record = records[0]!; |
| 142 | + |
| 143 | + await engine.completeWaitpoint({ |
| 144 | + id: result.waitpoint.id, |
| 145 | + output: { |
| 146 | + value: record.data, |
| 147 | + type: "application/json", |
| 148 | + isError: false, |
| 149 | + }, |
| 150 | + }); |
| 151 | + |
| 152 | + await removeSessionStreamWaitpoint( |
| 153 | + addressingKey, |
| 154 | + body.io, |
| 155 | + result.waitpoint.id |
| 156 | + ); |
| 157 | + } |
| 158 | + } |
| 159 | + } catch (error) { |
| 160 | + // Non-fatal: pending registration stays in Redis; the next append |
| 161 | + // will complete the waitpoint via the append handler path. Log so |
| 162 | + // a broken race-check doesn't silently degrade to timeout-only. |
| 163 | + logger.warn("session-stream wait race-check failed", { |
| 164 | + addressingKey, |
| 165 | + io: body.io, |
| 166 | + waitpointId: WaitpointId.toFriendlyId(result.waitpoint.id), |
| 167 | + error, |
| 168 | + }); |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + return json<CreateSessionStreamWaitpointResponseBody>({ |
| 173 | + waitpointId: WaitpointId.toFriendlyId(result.waitpoint.id), |
| 174 | + isCached: result.isCached, |
| 175 | + }); |
| 176 | + } catch (error) { |
| 177 | + if (error instanceof ServiceValidationError) { |
| 178 | + return json({ error: error.message }, { status: 422 }); |
| 179 | + } |
| 180 | + // Don't forward raw internal error messages (could leak Prisma/engine |
| 181 | + // details). Log server-side and return a generic 500. |
| 182 | + logger.error("Failed to create session-stream waitpoint", { error }); |
| 183 | + return json({ error: "Something went wrong" }, { status: 500 }); |
| 184 | + } |
| 185 | + } |
| 186 | +); |
| 187 | + |
| 188 | +export { action, loader }; |
0 commit comments