|
| 1 | +import { json } from "@remix-run/server-runtime"; |
| 2 | +import { z } from "zod"; |
| 3 | +import { |
| 4 | + CreateInputStreamWaitpointRequestBody, |
| 5 | + type CreateInputStreamWaitpointResponseBody, |
| 6 | +} from "@trigger.dev/core/v3"; |
| 7 | +import { WaitpointId } from "@trigger.dev/core/v3/isomorphic"; |
| 8 | +import { $replica } from "~/db.server"; |
| 9 | +import { createWaitpointTag, MAX_TAGS_PER_WAITPOINT } from "~/models/waitpointTag.server"; |
| 10 | +import { |
| 11 | + deleteInputStreamWaitpoint, |
| 12 | + setInputStreamWaitpoint, |
| 13 | +} from "~/services/inputStreamWaitpointCache.server"; |
| 14 | +import { getRealtimeStreamInstance } from "~/services/realtime/v1StreamsGlobal.server"; |
| 15 | +import { createActionApiRoute } from "~/services/routeBuilders/apiBuilder.server"; |
| 16 | +import { parseDelay } from "~/utils/delays"; |
| 17 | +import { resolveIdempotencyKeyTTL } from "~/utils/idempotencyKeys.server"; |
| 18 | +import { engine } from "~/v3/runEngine.server"; |
| 19 | +import { ServiceValidationError } from "~/v3/services/baseService.server"; |
| 20 | + |
| 21 | +const ParamsSchema = z.object({ |
| 22 | + runFriendlyId: z.string(), |
| 23 | +}); |
| 24 | + |
| 25 | +const { action, loader } = createActionApiRoute( |
| 26 | + { |
| 27 | + params: ParamsSchema, |
| 28 | + body: CreateInputStreamWaitpointRequestBody, |
| 29 | + maxContentLength: 1024 * 10, // 10KB |
| 30 | + method: "POST", |
| 31 | + allowJWT: true, |
| 32 | + corsStrategy: "all", |
| 33 | + authorization: { |
| 34 | + action: "write", |
| 35 | + resource: (params) => ({ inputStreams: params.runFriendlyId }), |
| 36 | + superScopes: ["write:inputStreams", "write:all", "admin"], |
| 37 | + }, |
| 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 | + const idempotencyKeyExpiresAt = body.idempotencyKeyTTL |
| 58 | + ? resolveIdempotencyKeyTTL(body.idempotencyKeyTTL) |
| 59 | + : undefined; |
| 60 | + |
| 61 | + const timeout = await parseDelay(body.timeout); |
| 62 | + |
| 63 | + // Process tags (same pattern as api.v1.waitpoints.tokens.ts) |
| 64 | + const bodyTags = typeof body.tags === "string" ? [body.tags] : body.tags; |
| 65 | + |
| 66 | + if (bodyTags && bodyTags.length > MAX_TAGS_PER_WAITPOINT) { |
| 67 | + throw new ServiceValidationError( |
| 68 | + `Waitpoints can only have ${MAX_TAGS_PER_WAITPOINT} tags, you're trying to set ${bodyTags.length}.` |
| 69 | + ); |
| 70 | + } |
| 71 | + |
| 72 | + if (bodyTags && bodyTags.length > 0) { |
| 73 | + for (const tag of bodyTags) { |
| 74 | + await createWaitpointTag({ |
| 75 | + tag, |
| 76 | + environmentId: authentication.environment.id, |
| 77 | + projectId: authentication.environment.projectId, |
| 78 | + }); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + // Step 1: Create the waitpoint |
| 83 | + const result = await engine.createManualWaitpoint({ |
| 84 | + environmentId: authentication.environment.id, |
| 85 | + projectId: authentication.environment.projectId, |
| 86 | + idempotencyKey: body.idempotencyKey, |
| 87 | + idempotencyKeyExpiresAt, |
| 88 | + timeout, |
| 89 | + tags: bodyTags, |
| 90 | + inputStreamRunFriendlyId: run.friendlyId, |
| 91 | + inputStreamId: body.streamId, |
| 92 | + }); |
| 93 | + |
| 94 | + // Step 2: Cache the mapping in Redis for fast lookup from .send() |
| 95 | + const ttlMs = timeout ? timeout.getTime() - Date.now() : undefined; |
| 96 | + await setInputStreamWaitpoint( |
| 97 | + run.friendlyId, |
| 98 | + body.streamId, |
| 99 | + result.waitpoint.id, |
| 100 | + ttlMs && ttlMs > 0 ? ttlMs : undefined |
| 101 | + ); |
| 102 | + |
| 103 | + // Step 3: Check if data was already sent to this input stream (race condition handling). |
| 104 | + // If .send() landed before .wait(), the data is in the S2 stream but no waitpoint |
| 105 | + // existed to complete. We check from the client's last known position. |
| 106 | + if (!result.isCached) { |
| 107 | + try { |
| 108 | + const realtimeStream = getRealtimeStreamInstance( |
| 109 | + authentication.environment, |
| 110 | + run.realtimeStreamsVersion |
| 111 | + ); |
| 112 | + |
| 113 | + if (realtimeStream.readRecords) { |
| 114 | + const records = await realtimeStream.readRecords( |
| 115 | + run.friendlyId, |
| 116 | + "__input", |
| 117 | + body.lastSeqNum |
| 118 | + ); |
| 119 | + |
| 120 | + // Find the first record matching this input stream ID |
| 121 | + for (const record of records) { |
| 122 | + try { |
| 123 | + const parsed = JSON.parse(record.data) as { |
| 124 | + stream: string; |
| 125 | + data: unknown; |
| 126 | + }; |
| 127 | + |
| 128 | + if (parsed.stream === body.streamId) { |
| 129 | + // Data exists — complete the waitpoint immediately |
| 130 | + await engine.completeWaitpoint({ |
| 131 | + id: result.waitpoint.id, |
| 132 | + output: { |
| 133 | + value: JSON.stringify(parsed.data), |
| 134 | + type: "application/json", |
| 135 | + isError: false, |
| 136 | + }, |
| 137 | + }); |
| 138 | + |
| 139 | + // Clean up the Redis cache since we completed it ourselves |
| 140 | + await deleteInputStreamWaitpoint(run.friendlyId, body.streamId); |
| 141 | + break; |
| 142 | + } |
| 143 | + } catch { |
| 144 | + // Skip malformed records |
| 145 | + } |
| 146 | + } |
| 147 | + } |
| 148 | + } catch { |
| 149 | + // Non-fatal: if the S2 check fails, the waitpoint is still PENDING. |
| 150 | + // The next .send() will complete it via the Redis cache path. |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + return json<CreateInputStreamWaitpointResponseBody>({ |
| 155 | + waitpointId: WaitpointId.toFriendlyId(result.waitpoint.id), |
| 156 | + isCached: result.isCached, |
| 157 | + }); |
| 158 | + } catch (error) { |
| 159 | + if (error instanceof ServiceValidationError) { |
| 160 | + return json({ error: error.message }, { status: 422 }); |
| 161 | + } else if (error instanceof Error) { |
| 162 | + return json({ error: error.message }, { status: 500 }); |
| 163 | + } |
| 164 | + |
| 165 | + return json({ error: "Something went wrong" }, { status: 500 }); |
| 166 | + } |
| 167 | + } |
| 168 | +); |
| 169 | + |
| 170 | +export { action, loader }; |
0 commit comments