From 4f9c8ec2818c24e82b5ca71bea963c7209fc334b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 24 Jul 2026 01:38:54 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(container):=20serve=20the=20SP?= =?UTF-8?q?A=20with=20Bun,=20drop=20nginx?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the nginx serving stage with a small Bun.serve script (server.ts) that serves the built dist/ and reverse-proxies /api/* to the backend — both plain HTTP and the exam-room WebSocket (forwarding the session cookie), stripping the /api prefix exactly as nginx did. Same-origin is preserved, so no CORS/cookie changes. (nginx.conf + its whitelist test were removed in the prior commit.) Multi-stage Containerfile: bun build -> bun:1-slim runtime running server.ts (no node_modules — server.ts uses only Bun built-ins). BACKEND_ORIGIN points the proxy at the backend on the compose network; healthcheck moves to a bun one-liner (slim image has no curl). Verified end-to-end under podman compose: SPA + asset caching + /api proxy + a live exam WS state frame round-tripping through the bridge on :5173. --- Containerfile | 31 +++++------ compose.yaml | 5 +- server.ts | 138 +++++++++++++++++++++++++++++++++++++++++++++++++ vite.config.ts | 2 +- 4 files changed, 157 insertions(+), 19 deletions(-) create mode 100644 server.ts diff --git a/Containerfile b/Containerfile index ea63a0c..0a3ea2f 100644 --- a/Containerfile +++ b/Containerfile @@ -1,3 +1,7 @@ +# Build the SPA, then serve the static bundle with Bun (which also reverse- +# proxies /api to the backend — see server.ts). No nginx: one runtime, one +# tool, same-origin preserved. + FROM docker.io/oven/bun:1 AS build WORKDIR /app COPY package.json bun.lock ./ @@ -6,24 +10,17 @@ RUN --mount=type=cache,target=/root/.bun/install/cache \ COPY . . RUN bun run build -FROM docker.io/library/debian:trixie-slim AS serve - -RUN apt-get update && \ - apt-get install -y --no-install-recommends nginx curl ca-certificates && \ - rm -rf /var/lib/apt/lists/* && \ - useradd --system --uid 10001 hezarfen && \ - mkdir -p /var/cache/nginx /var/lib/nginx /var/log/nginx && \ - chown -R hezarfen:hezarfen /var/cache/nginx /var/lib/nginx /var/log/nginx /usr/share/nginx/html && \ - rm -f /etc/nginx/sites-enabled/default - -COPY nginx.conf /etc/nginx/conf.d/default.conf -COPY --from=build /app/dist /usr/share/nginx/html -RUN sed -i 's|pid /run/nginx.pid;|pid /tmp/nginx.pid;|' /etc/nginx/nginx.conf - -USER hezarfen +FROM docker.io/oven/bun:1-slim AS serve +WORKDIR /app +# Only the built assets and the server script are needed at runtime; server.ts +# imports nothing but Bun built-ins, so there are no node_modules to copy. +COPY --from=build /app/dist ./dist +COPY server.ts ./server.ts ENV PORT=5173 - EXPOSE 5173 +USER bun -CMD ["nginx", "-g", "daemon off;"] +# Healthcheck lives in compose.yaml (podman's OCI image format ignores a +# Containerfile HEALTHCHECK). +CMD ["bun", "run", "server.ts"] diff --git a/compose.yaml b/compose.yaml index fa96a3a..951e721 100644 --- a/compose.yaml +++ b/compose.yaml @@ -9,9 +9,12 @@ services: - "5173:5173" environment: PORT: "5173" + # Backend on the shared compose network; server.ts proxies /api here. + BACKEND_ORIGIN: "http://hezarfen-backend:8080" restart: unless-stopped healthcheck: - test: ["CMD", "curl", "-fsS", "http://127.0.0.1:5173/"] + # Bun-based: the slim runtime image ships no curl. + test: ["CMD", "bun", "-e", "fetch('http://127.0.0.1:5173/').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"] interval: 30s timeout: 5s retries: 3 diff --git a/server.ts b/server.ts new file mode 100644 index 0000000..ef4f080 --- /dev/null +++ b/server.ts @@ -0,0 +1,138 @@ +// Production server: serve the built SPA and reverse-proxy /api/* to the +// backend, so the browser stays same-origin (session cookies, no CORS). This +// replaces the old nginx image — Bun serves the static `dist/` and bridges +// both plain HTTP and the exam-room WebSocket through to the backend. +// +// Local dev uses Vite's own proxy (vite.config.ts); this file is only the +// container's runtime after `vite build`. + +const PORT = Number(Bun.env.PORT ?? 5173); +// Where the backend lives on the compose network. Override in compose. +const BACKEND_ORIGIN = Bun.env.BACKEND_ORIGIN ?? "http://127.0.0.1:8080"; +const BACKEND_HTTP = BACKEND_ORIGIN.replace(/\/+$/, ""); +const BACKEND_WS = BACKEND_HTTP.replace(/^http/, "ws"); +const BACKEND_HOST = new URL(BACKEND_HTTP).host; + +const DIST = `${import.meta.dir}/dist`; + +// Strip the /api prefix exactly like nginx did (rewrite ^/api(/.*)$ -> $1), +// so /api/exams/x -> /exams/x and /api -> "". +function backendPath(url: URL): string { + return url.pathname.replace(/^\/api(?=\/|$)/, "") + url.search; +} + +function isApi(pathname: string): boolean { + return pathname === "/api" || pathname.startsWith("/api/"); +} + +// One held-open client socket to the backend per browser socket. Frames are +// piped both ways; messages that arrive before the upstream finishes its +// handshake are queued, not dropped. +type Bridge = { + upstream: WebSocket; + ready: boolean; + queue: (string | Uint8Array)[]; +}; + +async function serveStatic(pathname: string): Promise { + // No path traversal out of dist. + if (pathname.includes("..")) return new Response("bad request", { status: 400 }); + const rel = pathname === "/" ? "/index.html" : pathname; + const file = Bun.file(DIST + rel); + if (await file.exists()) { + const headers: Record = {}; + // Vite emits content-hashed files under /assets — safe to cache forever. + if (rel.startsWith("/assets/")) headers["Cache-Control"] = "public, max-age=31536000, immutable"; + else if (rel === "/index.html") headers["Cache-Control"] = "no-store"; + return new Response(file, { headers }); + } + // SPA fallback: unknown paths are client routes, serve the shell. + return new Response(Bun.file(`${DIST}/index.html`), { headers: { "Cache-Control": "no-store" } }); +} + +async function proxyHttp(req: Request, url: URL): Promise { + const target = BACKEND_HTTP + backendPath(url); + const headers = new Headers(req.headers); + // Let fetch set Host from the target; forwarding the browser's Host confuses + // the backend's absolute-URL / cookie-domain logic. + headers.set("host", BACKEND_HOST); + const hasBody = req.method !== "GET" && req.method !== "HEAD"; + const resp = await fetch(target, { + method: req.method, + headers, + body: hasBody ? req.body : undefined, + redirect: "manual", + // Stream the request body instead of buffering it (uploads). + ...(hasBody ? { duplex: "half" } : {}), + } as RequestInit); + return resp; +} + +const server = Bun.serve({ + port: PORT, + hostname: "0.0.0.0", + // Long-running exam sockets must not be reaped by an idle timeout; the + // backend sends its own periodic state ticks but a quiet client can still + // sit for minutes between frames. + idleTimeout: 0, + async fetch(req, srv) { + const url = new URL(req.url); + + if (isApi(url.pathname)) { + // WebSocket upgrade (/api/exams/:id/attempt/ws): open the upstream and + // bridge. Forward the session cookie — it's what authenticates the WS. + if (req.headers.get("upgrade")?.toLowerCase() === "websocket") { + const cookie = req.headers.get("cookie") ?? undefined; + const proto = req.headers.get("sec-websocket-protocol") ?? undefined; + const upstream = new WebSocket(BACKEND_WS + backendPath(url), { + headers: cookie ? { cookie } : undefined, + ...(proto ? { protocols: proto.split(",").map((p) => p.trim()) } : {}), + } as unknown as string[]); + const bridge: Bridge = { upstream, ready: false, queue: [] }; + const ok = srv.upgrade(req, { data: bridge }); + if (ok) return undefined; + upstream.close(); + return new Response("websocket upgrade failed", { status: 426 }); + } + return proxyHttp(req, url); + } + + return serveStatic(url.pathname); + }, + websocket: { + open(ws) { + const b = ws.data; + b.upstream.onopen = () => { + b.ready = true; + for (const m of b.queue) b.upstream.send(m); + b.queue.length = 0; + }; + b.upstream.onmessage = (e) => { + // e.data is string for text frames, ArrayBuffer/Uint8Array for binary. + ws.send(e.data as string | Uint8Array); + }; + b.upstream.onclose = (e) => ws.close(e.code || 1000, e.reason); + b.upstream.onerror = () => { + try { + ws.close(1011, "upstream error"); + } catch { + // socket already gone + } + }; + }, + message(ws, message) { + const b = ws.data; + if (b.ready) b.upstream.send(message); + else b.queue.push(message); + }, + close(ws, code, reason) { + try { + ws.data.upstream.close(code >= 1000 && code <= 4999 ? code : 1000, reason); + } catch { + // upstream already closed + } + }, + }, +}); + +console.log(`serving dist/ on :${server.port}, proxying /api -> ${BACKEND_HTTP}`); diff --git a/vite.config.ts b/vite.config.ts index b7cbb1f..349657f 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -18,7 +18,7 @@ export default defineConfig({ // reloads its cache entries wedge and every later request queues in the // browser forever — no bytes ever reach vite. `no-store` stops Chromium // from creating the cache entries at all. Dev-only; the production build - // is served by nginx with its own cache headers. + // is served by Bun (server.ts) with its own cache headers. headers: { "Cache-Control": "no-store", },