|
| 1 | +import { json, type ActionFunctionArgs, type LoaderFunctionArgs } from "@remix-run/server-runtime"; |
| 2 | +import { z } from "zod"; |
| 3 | +import { env } from "~/env.server"; |
| 4 | +import { |
| 5 | + StreamBatchItemsService, |
| 6 | + createNdjsonParserStream, |
| 7 | + streamToAsyncIterable, |
| 8 | +} from "~/runEngine/services/streamBatchItems.server"; |
| 9 | +import { authenticateApiRequestWithFailure } from "~/services/apiAuth.server"; |
| 10 | +import { logger } from "~/services/logger.server"; |
| 11 | +import { ServiceValidationError } from "~/v3/services/baseService.server"; |
| 12 | +import { engine } from "~/v3/runEngine.server"; |
| 13 | + |
| 14 | +const ParamsSchema = z.object({ |
| 15 | + batchId: z.string(), |
| 16 | +}); |
| 17 | + |
| 18 | +/** |
| 19 | + * Phase 2 of 2-phase batch API: Stream batch items. |
| 20 | + * |
| 21 | + * POST /api/v3/batches/:batchId/items |
| 22 | + * |
| 23 | + * Accepts an NDJSON stream of batch items and enqueues them to the BatchQueue. |
| 24 | + * Each line in the body should be a valid BatchItemNDJSON object. |
| 25 | + * |
| 26 | + * The stream is processed with backpressure - items are enqueued as they arrive. |
| 27 | + * The batch is sealed when the stream completes successfully. |
| 28 | + */ |
| 29 | +export async function action({ request, params }: ActionFunctionArgs) { |
| 30 | + // Validate params |
| 31 | + const paramsResult = ParamsSchema.safeParse(params); |
| 32 | + if (!paramsResult.success) { |
| 33 | + return json({ error: "Invalid batch ID" }, { status: 400 }); |
| 34 | + } |
| 35 | + |
| 36 | + const { batchId } = paramsResult.data; |
| 37 | + |
| 38 | + // Validate content type |
| 39 | + const contentType = request.headers.get("content-type") || ""; |
| 40 | + if ( |
| 41 | + !contentType.includes("application/x-ndjson") && |
| 42 | + !contentType.includes("application/ndjson") |
| 43 | + ) { |
| 44 | + return json( |
| 45 | + { |
| 46 | + error: "Content-Type must be application/x-ndjson or application/ndjson", |
| 47 | + }, |
| 48 | + { status: 415 } |
| 49 | + ); |
| 50 | + } |
| 51 | + |
| 52 | + // Authenticate the request |
| 53 | + const authResult = await authenticateApiRequestWithFailure(request, { |
| 54 | + allowPublicKey: true, |
| 55 | + }); |
| 56 | + |
| 57 | + if (!authResult.ok) { |
| 58 | + return json({ error: authResult.error }, { status: 401 }); |
| 59 | + } |
| 60 | + |
| 61 | + // Verify BatchQueue is enabled |
| 62 | + if (!engine.isBatchQueueEnabled()) { |
| 63 | + return json( |
| 64 | + { |
| 65 | + error: "Streaming batch API is not available. BatchQueue is not enabled.", |
| 66 | + }, |
| 67 | + { status: 503 } |
| 68 | + ); |
| 69 | + } |
| 70 | + |
| 71 | + // Get the request body stream |
| 72 | + const body = request.body; |
| 73 | + if (!body) { |
| 74 | + return json({ error: "Request body is required" }, { status: 400 }); |
| 75 | + } |
| 76 | + |
| 77 | + logger.debug("Stream batch items request", { |
| 78 | + batchId, |
| 79 | + contentType, |
| 80 | + envId: authResult.environment.id, |
| 81 | + }); |
| 82 | + |
| 83 | + try { |
| 84 | + // Create NDJSON parser transform stream |
| 85 | + const parser = createNdjsonParserStream(env.STREAMING_BATCH_ITEM_MAXIMUM_SIZE); |
| 86 | + |
| 87 | + // Pipe the request body through the parser |
| 88 | + const parsedStream = body.pipeThrough(parser); |
| 89 | + |
| 90 | + // Convert to async iterable for the service |
| 91 | + const itemsIterator = streamToAsyncIterable(parsedStream); |
| 92 | + |
| 93 | + // Process the stream |
| 94 | + const service = new StreamBatchItemsService(); |
| 95 | + const result = await service.call(authResult.environment, batchId, itemsIterator, { |
| 96 | + maxItemBytes: env.STREAMING_BATCH_ITEM_MAXIMUM_SIZE, |
| 97 | + }); |
| 98 | + |
| 99 | + return json(result, { status: 200 }); |
| 100 | + } catch (error) { |
| 101 | + logger.error("Stream batch items error", { |
| 102 | + batchId, |
| 103 | + error: { |
| 104 | + message: (error as Error).message, |
| 105 | + stack: (error as Error).stack, |
| 106 | + }, |
| 107 | + }); |
| 108 | + |
| 109 | + if (error instanceof ServiceValidationError) { |
| 110 | + return json({ error: error.message }, { status: 422 }); |
| 111 | + } else if (error instanceof Error) { |
| 112 | + // Check for stream parsing errors |
| 113 | + if ( |
| 114 | + error.message.includes("Invalid JSON") || |
| 115 | + error.message.includes("exceeds maximum size") |
| 116 | + ) { |
| 117 | + return json({ error: error.message }, { status: 400 }); |
| 118 | + } |
| 119 | + |
| 120 | + return json( |
| 121 | + { error: error.message }, |
| 122 | + { status: 500, headers: { "x-should-retry": "false" } } |
| 123 | + ); |
| 124 | + } |
| 125 | + |
| 126 | + return json({ error: "Something went wrong" }, { status: 500 }); |
| 127 | + } |
| 128 | +} |
| 129 | + |
| 130 | +export async function loader({ request }: LoaderFunctionArgs) { |
| 131 | + // Return 405 for GET requests - only POST is allowed |
| 132 | + return json( |
| 133 | + { |
| 134 | + error: "Method not allowed. Use POST to stream batch items.", |
| 135 | + }, |
| 136 | + { status: 405 } |
| 137 | + ); |
| 138 | +} |
0 commit comments