6bf8bebf51
CI / Test and Build (push) Failing after 1s
CI / Migrate Dev DB (push) Has been skipped
CI / Migrate DB (push) Has been skipped
CodeQL / Analyze actions (push) Has been cancelled
CodeQL / Analyze javascript-typescript (push) Has been cancelled
CI / Detect Version (push) Has been cancelled
CI / Detect Desktop Changes (push) Has been cancelled
CI / Build AMD64 (blacksmith-2vcpu-ubuntu-2404, ./docker/cron.Dockerfile, ubuntu-latest, ghcr.io/simstudioai/cron) (push) Has been cancelled
CI / Build AMD64 (blacksmith-2vcpu-ubuntu-2404, ./docker/db.Dockerfile, ECR_MIGRATIONS, ubuntu-latest, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (blacksmith-4vcpu-ubuntu-2404, ./docker/pii.Dockerfile, ECR_PII, ubuntu-latest, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (blacksmith-4vcpu-ubuntu-2404, ./docker/realtime.Dockerfile, ECR_REALTIME, ubuntu-latest, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build AMD64 (blacksmith-8vcpu-ubuntu-2404, ./docker/app.Dockerfile, ECR_APP, linux-x64-8-core, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/cron.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/cron) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/db.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/pii.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/realtime.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-8vcpu-ubuntu-2404-arm, ./docker/app.Dockerfile, linux-arm64-8-core, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
Helm Chart / Lint, test, and validate chart (push) Has been cancelled
Helm Chart / Chart version bumped (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
CI / Build Dev ECR (blacksmith-8vcpu-ubuntu-2404, ./docker/app.Dockerfile, ECR_APP, linux-x64-8-core) (push) Has been cancelled
CI / Promote Images (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/cron) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build Dev ECR (blacksmith-2vcpu-ubuntu-2404, ./docker/db.Dockerfile, ECR_MIGRATIONS, ubuntu-latest) (push) Has been cancelled
CI / Build Dev ECR (blacksmith-4vcpu-ubuntu-2404, ./docker/pii.Dockerfile, ECR_PII, ubuntu-latest) (push) Has been cancelled
CI / Build Dev ECR (blacksmith-4vcpu-ubuntu-2404, ./docker/realtime.Dockerfile, ECR_REALTIME, ubuntu-latest) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Check Desktop Signing Secrets (push) Has been cancelled
CI / Desktop Release (push) Has been cancelled
CI / Create Desktop Prerelease (push) Has been cancelled
CI / Desktop Prerelease Build (push) Has been cancelled
CI / Publish Desktop Prerelease (push) Has been cancelled
CI / Prune Desktop Prereleases (push) Has been cancelled
Helm Chart / Install on kind and run helm test (push) Has been cancelled
119 lines
4.7 KiB
TypeScript
119 lines
4.7 KiB
TypeScript
import { createLogger, runWithRequestContext } from '@sim/logger'
|
|
import { getErrorMessage } from '@sim/utils/errors'
|
|
import type { NextRequest } from 'next/server'
|
|
import { NextResponse } from 'next/server'
|
|
import { getRateLimitHeaders } from '@/lib/api/server/rate-limit-context'
|
|
import { HttpError } from '@/lib/core/utils/http-error'
|
|
import { generateRequestId } from '@/lib/core/utils/request'
|
|
|
|
const logger = createLogger('RouteHandler')
|
|
|
|
type RouteHandler<T = unknown> = (
|
|
request: NextRequest,
|
|
context: T
|
|
) => Promise<NextResponse | Response> | NextResponse | Response
|
|
|
|
/**
|
|
* Reads a numeric `statusCode` (4xx or 5xx) off an `HttpError` so typed domain
|
|
* errors (e.g. `WorkspaceAccessDeniedError`, `InvalidFieldError`) map to the
|
|
* correct HTTP status when they bubble up unhandled instead of defaulting to
|
|
* 500.
|
|
*
|
|
* Uses an `instanceof HttpError` check (not duck-typing on `statusCode`) so
|
|
* third-party errors that happen to carry a `statusCode`-shaped field cannot
|
|
* trigger this path and leak their internal `message` to the client.
|
|
*
|
|
* When a typed status is returned, the error's `message` is sent to the client
|
|
* verbatim — matching the NestJS `HttpException` / Spring `ResponseStatusException`
|
|
* convention. Subclasses of `HttpError` are responsible for keeping `message`
|
|
* safe to expose to clients (no stack traces, secrets, file paths, ORM
|
|
* internals).
|
|
*/
|
|
function readTypedErrorStatus(error: unknown): number | undefined {
|
|
if (!(error instanceof HttpError)) return undefined
|
|
const status = error.statusCode
|
|
if (status < 400 || status >= 600) return undefined
|
|
return status
|
|
}
|
|
|
|
/**
|
|
* Stamps the request id, plus the rate-limit trio when the route consulted a
|
|
* bucket for this request. Applied on both the success and the unhandled-error
|
|
* path so a caller can read its quota from any response — including the 4xx and
|
|
* 5xx ones, which are exactly the responses worth retrying.
|
|
*/
|
|
function applyResponseHeaders(
|
|
response: NextResponse | Response | undefined,
|
|
request: NextRequest,
|
|
requestId: string
|
|
): void {
|
|
if (!response?.headers) return
|
|
response.headers.set('x-request-id', requestId)
|
|
const rateLimit = getRateLimitHeaders(request)
|
|
if (!rateLimit) return
|
|
for (const [name, value] of Object.entries(rateLimit)) {
|
|
response.headers.set(name, value)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Wraps a Next.js API route handler with centralized error reporting.
|
|
*
|
|
* - Generates a unique request ID and stores it in AsyncLocalStorage so every
|
|
* logger in the request lifecycle automatically includes it
|
|
* - Logs all 4xx and 5xx responses with method, path, status, duration
|
|
* - Catches unhandled errors, logs them, and returns a 500 with the request ID
|
|
* - Attaches `x-request-id`, plus the rate-limit headers when the route
|
|
* recorded a snapshot for the request
|
|
*/
|
|
export function withRouteHandler<T>(handler: RouteHandler<T>): RouteHandler<T> {
|
|
return async (request: NextRequest, context: T) => {
|
|
const requestId = generateRequestId()
|
|
const startTime = Date.now()
|
|
const method = request?.method ?? 'UNKNOWN'
|
|
const path =
|
|
request?.nextUrl?.pathname ?? new URL(request?.url ?? '/', 'http://localhost').pathname
|
|
|
|
return runWithRequestContext({ requestId, method, path }, async () => {
|
|
let response: NextResponse | Response
|
|
try {
|
|
response = await handler(request, context)
|
|
} catch (error) {
|
|
const duration = Date.now() - startTime
|
|
const message = getErrorMessage(error, 'Unknown error')
|
|
const typedStatus = readTypedErrorStatus(error)
|
|
if (typedStatus !== undefined) {
|
|
if (typedStatus >= 500) {
|
|
logger.error('Unhandled route error', { duration, status: typedStatus, error: message })
|
|
} else {
|
|
logger.warn('Typed route error', { duration, status: typedStatus, error: message })
|
|
}
|
|
response = NextResponse.json({ error: message, requestId }, { status: typedStatus })
|
|
} else {
|
|
logger.error('Unhandled route error', { duration, error: message })
|
|
response = NextResponse.json(
|
|
{ error: 'Internal server error', requestId },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
applyResponseHeaders(response, request, requestId)
|
|
return response
|
|
}
|
|
|
|
const status = response?.status ?? 0
|
|
const duration = Date.now() - startTime
|
|
|
|
if (status >= 500) {
|
|
logger.error('Server error response', { status, duration })
|
|
} else if (status >= 400) {
|
|
logger.warn('Client error response', { status, duration })
|
|
} else if (status > 0) {
|
|
logger.info('OK', { status, duration })
|
|
}
|
|
|
|
applyResponseHeaders(response, request, requestId)
|
|
return response
|
|
})
|
|
}
|
|
}
|