|
| 1 | +import { json } from "@remix-run/server-runtime"; |
| 2 | +import { z } from "zod"; |
| 3 | +import { $replica, prisma } from "~/db.server"; |
| 4 | +import { createActionApiRoute } from "~/services/routeBuilders/apiBuilder.server"; |
| 5 | +import { getRealtimeStreamInstance } from "~/services/realtime/v1StreamsGlobal.server"; |
| 6 | + |
| 7 | +const ParamsSchema = z.object({ |
| 8 | + runId: z.string(), |
| 9 | + streamId: z.string(), |
| 10 | +}); |
| 11 | + |
| 12 | +const BodySchema = z.object({ |
| 13 | + data: z.unknown(), |
| 14 | +}); |
| 15 | + |
| 16 | +const { action } = createActionApiRoute( |
| 17 | + { |
| 18 | + params: ParamsSchema, |
| 19 | + maxContentLength: 1024 * 1024, // 1MB max |
| 20 | + }, |
| 21 | + async ({ request, params, authentication }) => { |
| 22 | + const run = await $replica.taskRun.findFirst({ |
| 23 | + where: { |
| 24 | + friendlyId: params.runId, |
| 25 | + runtimeEnvironmentId: authentication.environment.id, |
| 26 | + }, |
| 27 | + select: { |
| 28 | + id: true, |
| 29 | + friendlyId: true, |
| 30 | + completedAt: true, |
| 31 | + hasInputStream: true, |
| 32 | + realtimeStreamsVersion: true, |
| 33 | + }, |
| 34 | + }); |
| 35 | + |
| 36 | + if (!run) { |
| 37 | + return json({ ok: false, error: "Run not found" }, { status: 404 }); |
| 38 | + } |
| 39 | + |
| 40 | + if (run.completedAt) { |
| 41 | + return json( |
| 42 | + { ok: false, error: "Cannot send to input stream on a completed run" }, |
| 43 | + { status: 400 } |
| 44 | + ); |
| 45 | + } |
| 46 | + |
| 47 | + const body = BodySchema.safeParse(await request.json()); |
| 48 | + |
| 49 | + if (!body.success) { |
| 50 | + return json({ ok: false, error: "Invalid request body" }, { status: 400 }); |
| 51 | + } |
| 52 | + |
| 53 | + const realtimeStream = getRealtimeStreamInstance( |
| 54 | + authentication.environment, |
| 55 | + run.realtimeStreamsVersion |
| 56 | + ); |
| 57 | + |
| 58 | + // Lazily create the input stream on first send |
| 59 | + if (!run.hasInputStream) { |
| 60 | + await prisma.taskRun.update({ |
| 61 | + where: { id: run.id }, |
| 62 | + data: { hasInputStream: true }, |
| 63 | + }); |
| 64 | + |
| 65 | + await realtimeStream.initializeStream(run.friendlyId, "__input"); |
| 66 | + } |
| 67 | + |
| 68 | + // Build the input stream record |
| 69 | + const recordId = `inp_${crypto.randomUUID().replace(/-/g, "").slice(0, 12)}`; |
| 70 | + const record = JSON.stringify({ |
| 71 | + stream: params.streamId, |
| 72 | + data: body.data.data, |
| 73 | + ts: Date.now(), |
| 74 | + id: recordId, |
| 75 | + }); |
| 76 | + |
| 77 | + // Append the record to the multiplexed __input stream |
| 78 | + await realtimeStream.appendPart(record, recordId, run.friendlyId, "__input"); |
| 79 | + |
| 80 | + return json({ ok: true }); |
| 81 | + } |
| 82 | +); |
| 83 | + |
| 84 | +export { action }; |
0 commit comments