Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

server-functions-handler.ts

535 lines15.5 KB

1import { invariant, isNotFound, isRedirect } from '@tanstack/router-core'
2import {
3 createRawStreamRPCPlugin,
4 defaultSerovalDeserializerPlugins as routerDefaultSerovalPlugins,
5} from '@tanstack/router-core/ssr/server'
6import {
7 TSS_CONTENT_TYPE_FRAMED_VERSIONED,
8 TSS_FORMDATA_CONTEXT,
9 X_TSS_RAW_RESPONSE,
10 X_TSS_SERIALIZED,
11 getSerovalPlugins,
12 safeObjectMerge,
13} from '@tanstack/start-client-core'
14import {
15 MAX_FRAMED_STREAMS,
16 MAX_FRAME_PAYLOAD_SIZE,
17} from '@tanstack/start-client-core/client-rpc'
18import { fromJSON, toCrossJSONAsync, toCrossJSONStream } from 'seroval'
19import { getResponse } from './request-response'
20import { getServerFnById } from './getServerFnById'
21import { createMultiplexedStream } from './frame-protocol'
22import type {
23 LateStreamRegistration,
24 MultiplexedStreamOptions,
25 MultiplexedStreamRecord,
26} from './frame-protocol'
27import type { Plugin as SerovalPlugin } from 'seroval'
28​
29// Cache serovalPlugins at module level to avoid repeated calls
30let serovalPlugins: Array<SerovalPlugin<any, any>> | undefined = undefined
31​
32// Known FormData 'Content-Type' header values - module-level constant
33const FORM_DATA_CONTENT_TYPES = [
34 'multipart/form-data',
35 'application/x-www-form-urlencoded',
37​
38// Maximum payload size for GET requests (1MB)
39const MAX_PAYLOAD_SIZE = 1_000_000
40const MAX_PENDING_SERIALIZATION_RECORDS = 1024
41const MAX_PENDING_SERIALIZATION_BYTES = 32 * 1024 * 1024
42const textEncoder = new TextEncoder()
43​
44function encodeSerializationRecord(value: unknown) {
45 return textEncoder.encode(JSON.stringify(value))
47​
48function exceedsPendingSerializationLimit(
49 record: Uint8Array,
50 recordCount: number,
51 pendingBytes: number,
52) {
53 return (
54 recordCount >= MAX_PENDING_SERIALIZATION_RECORDS ||
55 pendingBytes + record.byteLength > MAX_PENDING_SERIALIZATION_BYTES
56 )
58​
59function runSerializationCleanup(dispose: () => void) {
60 try {
61 dispose()
62 } catch {}
64​
65function cancelRawStream(stream: ReadableStream<Uint8Array>, reason?: unknown) {
66 void stream.cancel(reason).catch(() => {})
68​
69export const handleServerAction = async ({
70 request,
71 context,
72 serverFnId,
73}: {
74 request: Request
75 context: any
76 serverFnId: string
77}) => {
78 const methodUpper = request.method.toUpperCase()
79 const url = new URL(request.url)
80​
81 const action = await getServerFnById(serverFnId, { origin: 'client' })
82​
83 // Early method check: reject mismatched HTTP methods before parsing
84 // the request payload (FormData, JSON, query string, etc.)
85 if (action.method && methodUpper !== action.method) {
86 return new Response(
87 `expected ${action.method} method. Got ${methodUpper}`,
88 {
89 status: 405,
90 headers: {
91 Allow: action.method,
92 },
93 },
94 )
95 }
96​
97 const isServerFn = request.headers.get('x-tsr-serverFn') === 'true'
98 // Initialize serovalPlugins lazily (cached at module level)
99 serovalPlugins ??= getSerovalPlugins(routerDefaultSerovalPlugins)
100 const contentType = request.headers.get('Content-Type')
101​
102 try {
103 let res: any
104 if (
105 FORM_DATA_CONTENT_TYPES.some(
106 (type) => contentType && contentType.includes(type),
107 )
108 ) {
109 // We don't support GET requests with FormData payloads... that seems impossible
110 if (methodUpper === 'GET') {
111 if (process.env.NODE_ENV !== 'production') {
112 throw new Error(
113 'Invariant failed: GET requests with FormData payloads are not supported',
114 )
115 }
116​
117 invariant()
118 }
119 const formData = await request.formData()
120 const serializedContext = formData.get(TSS_FORMDATA_CONTEXT)
121 formData.delete(TSS_FORMDATA_CONTEXT)
122​
123 const params = {
124 context,
125 data: formData,
126 method: methodUpper,
127 }
128 if (typeof serializedContext === 'string') {
129 try {
130 const parsedContext = JSON.parse(serializedContext)
131 const deserializedContext = fromJSON(parsedContext, {
132 plugins: serovalPlugins,
133 })
134 if (typeof deserializedContext === 'object' && deserializedContext) {
135 params.context = safeObjectMerge(
136 deserializedContext as Record<string, unknown>,
137 context,
138 )
139 }
140 } catch (e) {
141 // Log warning for debugging but don't expose to client
142 if (process.env.NODE_ENV === 'development') {
143 console.warn('Failed to parse FormData context:', e)
144 }
145 }
146 }
147​
148 res = await action(params)
149 } else if (methodUpper === 'GET') {
150 // Get payload directly from searchParams
151 const payloadParam = url.searchParams.get('payload')
152 // Reject oversized payloads to prevent DoS
153 if (payloadParam && payloadParam.length > MAX_PAYLOAD_SIZE) {
154 throw new Error('Payload too large')
155 }
156 const payload: any = payloadParam
157 ? fromJSON(JSON.parse(payloadParam), { plugins: serovalPlugins })
158 : undefined
159 res = await action({
160 data: payload?.data,
161 context: safeObjectMerge(payload?.context, context),
162 method: methodUpper,
163 })
164 } else {
165 const payload: any = contentType?.includes('application/json')
166 ? fromJSON(await request.json(), { plugins: serovalPlugins })
167 : undefined
168 res = await action({
169 data: payload?.data,
170 context: safeObjectMerge(payload?.context, context),
171 method: methodUpper,
172 })
173 }
174​
175 const unwrapped = res.error !== undefined ? res.error : res.result
176​
177 if (isNotFound(res)) {
178 res = isNotFoundResponse(res)
179 }
180​
181 if (
182 !isServerFn &&
183 (unwrapped instanceof Response ||
184 unwrapped === null ||
185 typeof unwrapped !== 'object')
186 ) {
187 return unwrapped
188 }
189​
190 if (unwrapped instanceof Response) {
191 if (isRedirect(unwrapped)) {
192 return unwrapped
193 }
194 unwrapped.headers.set(X_TSS_RAW_RESPONSE, 'true')
195 return unwrapped
196 }
197​
198 return serializeResult(res, request.signal, serovalPlugins)
199 } catch (error: any) {
200 if (error instanceof Response) {
201 return error
202 }
203​
204 // Currently this server-side context has no idea how to
205 // build final URLs, so we need to defer that to the client.
206 // The client will check for __redirect and __notFound keys,
207 // and if they exist, it will handle them appropriately.
208​
209 if (isNotFound(error)) {
210 return isNotFoundResponse(error)
211 }
212​
213 console.error('Server Fn Error!', error)
214​
215 const serializedError = JSON.stringify(
216 await toCrossJSONAsync(error, {
217 refs: new Map(),
218 plugins: serovalPlugins,
219 }),
220 )
221 const response = getResponse()
222 const headers = {
223 'Content-Type': 'application/json',
224 [X_TSS_SERIALIZED]: 'true',
225 }
226 try {
227 return new Response(serializedError, {
228 status: response.status ?? 500,
229 statusText: response.statusText,
230 headers,
231 })
232 } catch {
233 return new Response(serializedError, {
234 status: 500,
235 statusText: '',
236 headers,
237 })
238 }
239 }
241​
242/**
243 * Serializes a server-function result. A result that Seroval completes
244 * synchronously without RawStreams becomes plain JSON; everything else is a
245 * framed response whose records and raw streams are multiplexed in order.
246 */
247function serializeResult(
248 res: unknown,
249 signal: AbortSignal,
250 plugins: Array<SerovalPlugin<any, any>>,
251): Response {
252 const alsResponse = getResponse()
253 const initialRecords: Array<Uint8Array> = []
254 let initialBytes = 0
255 const pendingRawStreams: Array<LateStreamRegistration> = []
256​
257 // Seroval replays synchronously discovered work before returning. Collect
258 // that first pass so a complete result can skip framing entirely.
259 let done = false as boolean
260 let initialParsed = false
261 let serializationFailure: [unknown] | undefined
262 let disposeSerialization: (() => void) | undefined
263 let onParse = (value: any, initial: boolean) => {
264 if (serializationFailure) {
265 return
266 }
267 initialParsed ||= initial
268 const record = encodeSerializationRecord(value)
269 if (
270 exceedsPendingSerializationLimit(
271 record,
272 initialRecords.length,
273 initialBytes,
274 )
275 ) {
276 serializationFailure = [
277 new Error(
278 'Server function serialization exceeded its pending output limit',
279 ),
280 ]
281 return
282 }
283 initialRecords.push(record)
284 initialBytes += record.byteLength
285 }
286 let onDone = () => {
287 if (initialParsed) {
288 done = true
289 }
290 }
291 let onError = (error: any) => {
292 serializationFailure ??= [error]
293 }
294 const rawStreamPlugin = createRawStreamRPCPlugin(
295 (id: number, stream: ReadableStream<Uint8Array>) => {
296 if (serializationFailure) {
297 cancelRawStream(stream, serializationFailure[0])
298 return
299 }
300 if (id > MAX_FRAMED_STREAMS) {
301 const error = new Error(
302 `Too many raw streams in framed response (max ${MAX_FRAMED_STREAMS})`,
303 )
304 cancelRawStream(stream, error)
305 onError(error)
306 return
307 }
308 pendingRawStreams.push({ id, stream })
309 },
310 )
311​
312 const dispose = toCrossJSONStream(res, {
313 refs: new Map(),
314 plugins: [rawStreamPlugin, ...plugins],
315 onParse(value, initial) {
316 onParse(value, initial)
317 },
318 onDone() {
319 onDone()
320 },
321 onError: (error) => {
322 onError(error)
323 },
324 })
325 if (serializationFailure) {
326 runSerializationCleanup(dispose)
327 for (const registration of pendingRawStreams) {
328 cancelRawStream(registration.stream, serializationFailure[0])
329 }
330 throw serializationFailure[0]
331 }
332 if (!done) {
333 disposeSerialization = dispose
334 }
335​
336 if (done && pendingRawStreams.length === 0 && initialRecords.length === 1) {
337 // TextEncoder always creates an ArrayBuffer-backed Uint8Array.
338 return new Response(initialRecords[0]! as BodyInit, {
339 status: alsResponse.status,
340 statusText: alsResponse.statusText,
341 headers: {
342 'Content-Type': 'application/json',
343 [X_TSS_SERIALIZED]: 'true',
344 },
345 })
346 }
347​
348 if (done && initialRecords.length === 1) {
349 const json = initialRecords[0]!
350 if (json.byteLength > MAX_FRAME_PAYLOAD_SIZE) {
351 const error = new Error(
352 'Server function serialization exceeded its pending output limit',
353 )
354 for (const registration of pendingRawStreams) {
355 cancelRawStream(registration.stream, error)
356 }
357 throw error
358 }
359​
360 // Serialization is complete, so this one bounded record needs no writer
361 // or pending-serialization lifecycle. The mux still controls raw demand.
362 const rawStreams = pendingRawStreams.splice(0)
363 initialRecords.length = 0
364 return createFramedResponse(
365 new ReadableStream<MultiplexedStreamRecord>({
366 start(controller) {
367 controller.enqueue({ json, rawStreams })
368 controller.close()
369 },
370 cancel(reason) {
371 for (const registration of rawStreams) {
372 cancelRawStream(registration.stream, reason)
373 }
374 },
375 }),
376 { signal },
377 )
378 }
379​
380 // Couple every JSON patch to the RawStreams it introduces. The mux admits
381 // each JSON reference before it starts that stream's chunks.
382 const { readable, writable } = new TransformStream<MultiplexedStreamRecord>()
383 const writer = writable.getWriter()
384 const recordAbortController = new AbortController()
385 let pendingBytes = 0
386 const pendingRecords = new Set<MultiplexedStreamRecord>()
387​
388 const abortRecordStream = (error: unknown) => {
389 if (serializationFailure) {
390 return
391 }
392 serializationFailure = [error]
393 const disposeCurrentSerialization = disposeSerialization
394 disposeSerialization = undefined
395 for (const registration of pendingRawStreams.splice(0)) {
396 cancelRawStream(registration.stream, error)
397 }
398 for (const record of pendingRecords) {
399 for (const registration of record.rawStreams) {
400 cancelRawStream(registration.stream, error)
401 }
402 }
403 pendingRecords.clear()
404 recordAbortController.abort(error)
405 void writer.abort(error).catch(() => {})
406 if (disposeCurrentSerialization) {
407 runSerializationCleanup(disposeCurrentSerialization)
408 }
409 }
410​
411 const writeRecord = (
412 json: Uint8Array,
413 rawStreams: Array<LateStreamRegistration>,
414 ) => {
415 if (serializationFailure) {
416 for (const registration of rawStreams) {
417 cancelRawStream(registration.stream, serializationFailure[0])
418 }
419 return false
420 }
421​
422 if (
423 json.byteLength > MAX_FRAME_PAYLOAD_SIZE ||
424 exceedsPendingSerializationLimit(json, pendingRecords.size, pendingBytes)
425 ) {
426 const error = new Error(
427 'Server function serialization exceeded its pending output limit',
428 )
429 for (const registration of rawStreams) {
430 cancelRawStream(registration.stream, error)
431 }
432 onError(error)
433 return false
434 }
435​
436 pendingBytes += json.byteLength
437 const record = { json, rawStreams }
438 pendingRecords.add(record)
439 void writer.write(record).then(
440 () => {
441 pendingRecords.delete(record)
442 pendingBytes -= json.byteLength
443 },
444 (error) => {
445 const stillOwned = pendingRecords.delete(record)
446 pendingBytes -= json.byteLength
447 if (stillOwned) {
448 for (const registration of rawStreams) {
449 cancelRawStream(registration.stream, error)
450 }
451 }
452 },
453 )
454 return true
455 }
456​
457 onParse = (value) => {
458 if (serializationFailure) {
459 return
460 }
461 writeRecord(encodeSerializationRecord(value), pendingRawStreams.splice(0))
462 }
463 onDone = () => {
464 if (serializationFailure) {
465 return
466 }
467 disposeSerialization = undefined
468 void writer.close().catch(() => {})
469 }
470 onError = (error) => {
471 abortRecordStream(error)
472 }
473​
474 // Seroval buffers nested patches during its initial traversal. Their
475 // RawStream callbacks may precede the root callback, so start every
476 // synchronously discovered stream only after all initial records.
477 const initialRawStreams = pendingRawStreams.splice(0)
478 for (let index = 0; index < initialRecords.length; index++) {
479 const isLast = index === initialRecords.length - 1
480 if (!writeRecord(initialRecords[index]!, isLast ? initialRawStreams : [])) {
481 // `writeRecord` recorded the failure. Nothing was handed to the client
482 // yet, so fail the whole call.
483 if (!isLast) {
484 for (const registration of initialRawStreams) {
485 cancelRawStream(registration.stream, serializationFailure![0])
486 }
487 }
488 initialRecords.length = 0
489 throw serializationFailure![0]
490 }
491 }
492 initialRecords.length = 0
493 if (done) {
494 onDone()
495 }
496​
497 void writer.closed.catch((error) => {
498 abortRecordStream(error)
499 })
500​
501 return createFramedResponse(readable, {
502 signal: AbortSignal.any([recordAbortController.signal, signal]),
503 onCancel: abortRecordStream,
504 })
505​
506 function createFramedResponse(
507 records: ReadableStream<MultiplexedStreamRecord>,
508 options: MultiplexedStreamOptions,
509 ) {
510 const multiplexedStream = createMultiplexedStream(records, options)
511 try {
512 return new Response(multiplexedStream, {
513 status: alsResponse.status,
514 statusText: alsResponse.statusText,
515 headers: {
516 'Content-Type': TSS_CONTENT_TYPE_FRAMED_VERSIONED,
517 [X_TSS_SERIALIZED]: 'true',
518 },
519 })
520 } catch (error) {
521 cancelRawStream(multiplexedStream, error)
522 throw error
523 }
524 }
526​
527function isNotFoundResponse(error: any) {
528 const { headers, ...rest } = error
529 const response = new Response(JSON.stringify(rest), {
530 status: 404,
531 headers,
532 })
533 response.headers.set('Content-Type', 'application/json')
534 return response