All files / src/server/platform request.server.ts

100% Statements 13/13
100% Branches 4/4
100% Functions 2/2
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44                        4x 4x 4x 4x   4x 4x   1x         1x   4x 1x           4x 4x 4x              
// Starts each request's trace: the trace id from the browser's traceparent
// header (src/lib/trace.ts), or a new one, goes into the log context for
// every line of the request and back to the browser as x-trace-id.
import { newTraceId, traceIdFrom } from '#/lib/trace'
import { runWithLogContext } from './log-context.server'
import { createRequestLogger } from './version.server'
 
export function handleTraced(
  request: Request,
  handle: () => Promise<Response>,
): Promise<Response> {
  const traceId =
    traceIdFrom(request.headers.get('traceparent')) ?? newTraceId()
  return runWithLogContext({ traceId }, async () => {
    const log = createRequestLogger()
    const { pathname } = new URL(request.url)
    let response: Response
    try {
      response = await handle()
    } catch (error) {
      log.error(
        'http.unhandled_error',
        { method: request.method, path: pathname },
        error,
      )
      response = new Response('Internal Server Error', { status: 500 })
    }
    if (response.status >= 500) {
      log.error('http.server_error', {
        method: request.method,
        path: pathname,
        status: response.status,
      })
    }
    const headers = new Headers(response.headers)
    headers.set('x-trace-id', traceId)
    return new Response(response.body, {
      status: response.status,
      statusText: response.statusText,
      headers,
    })
  })
}