route.ts 4.76 KB
import { NextRequest } from "next/server";

// 统一的同源 /api 流式代理(catch-all)。
// 取代 next.config 的 rewrites:rewrites 会把请求体与响应整体缓冲,
//   → 大文件上传被卡(约 10MB),SSE 流式接口也变成「跑完一次性下发」。
// 这里对**请求体**与**响应体**都做流式透传,永不缓冲,所有接口(GET/POST/上传/下载/SSE)走同一条通道。

export const runtime = "nodejs";
export const dynamic = "force-dynamic";
// 取消该路由的时长限制,兼容长连接 SSE 与大文件上传
export const maxDuration = 300;

const BACKEND = process.env.BACKEND_INTERNAL_URL || "http://backend:8104";

// 小请求体(JSON/表单提交)的转发阈值:超过此大小才走原始流式透传。
// 原因:用 ReadableStream 作为 fetch 请求体时,一旦上游在读取 body 阶段出现连接层
// 问题,undici 会尝试重放该请求体,但 stream 已被消费一次、无法重放,
// 抛出 "TypeError: fetch failed" / "expected non-null body source"——
// 表现为所有会读取请求体(Body(...))的接口(登录、改密、新建等)必然收到 502,
// 而不读 body 的接口(GET、无 body 的 POST、404 未命中路由)完全正常。
// 只缓冲已知长度且不大的请求体规避该问题;大文件上传/无 Content-Length 的请求
// 仍走原始流式转发,避免回归历史上的大文件上传卡顿问题。
const BUFFER_THRESHOLD = 4 * 1024 * 1024; // 4MB

// 逐跳头(hop-by-hop)与会让上游困惑的头,转发前剔除
const STRIP_REQUEST_HEADERS = new Set([
  "host",
  "connection",
  "content-length",
  "transfer-encoding",
  "keep-alive",
  "upgrade",
  "expect",
]);

async function proxy(req: NextRequest) {
  // 直接用原始 pathname 还原后端路径,避免对已编码的路径段二次编码
  const rest = req.nextUrl.pathname.replace(/^\/api/, "");
  const target = `${BACKEND}${rest}${req.nextUrl.search}`;

  const headers = new Headers();
  req.headers.forEach((value, key) => {
    if (!STRIP_REQUEST_HEADERS.has(key.toLowerCase())) headers.set(key, value);
  });

  const method = req.method.toUpperCase();
  const hasBody = method !== "GET" && method !== "HEAD";
  const contentLength = Number(req.headers.get("content-length") || "0");
  const shouldBuffer = hasBody && contentLength > 0 && contentLength <= BUFFER_THRESHOLD;

  try {
    const upstream = await fetch(target, {
      method,
      headers,
      // 小体积请求(JSON/表单)整体读入后转发,规避 undici 流式请求体的重放限制;
      // 大文件上传等仍走原始流式透传,绝不整体缓冲触发大小上限
      body: shouldBuffer ? await req.arrayBuffer() : (hasBody ? req.body : undefined),
      redirect: "manual",
      // 仅在仍走流式转发时才需要声明 duplex
      ...(hasBody && !shouldBuffer ? { duplex: "half" } : {}),
    } as RequestInit & { duplex?: "half" });

    // 响应头透传(含 content-type、下载用的 content-disposition),剔除逐跳头
    const respHeaders = new Headers();
    upstream.headers.forEach((value, key) => {
      const k = key.toLowerCase();
      if (k === "content-length" || k === "transfer-encoding" || k === "connection") return;
      // Set-Cookie 不能走 forEach:多条 cookie 会被 Headers 合并成一条非法头,
      // 导致浏览器整条丢弃(登录态就是靠它下发的)。下面用 getSetCookie 单独逐条 append。
      if (k === "set-cookie") return;
      respHeaders.set(key, value);
    });

    // 登录/登出的 httpOnly cookie 经此透传
    const setCookies = upstream.headers.getSetCookie?.() ?? [];
    for (const cookie of setCookies) {
      respHeaders.append("set-cookie", cookie);
    }
    // 保障 SSE 等流式响应实时下发
    respHeaders.set("cache-control", "no-cache, no-transform");
    respHeaders.set("x-accel-buffering", "no");

    // 响应体流式透传:直接把上游 ReadableStream 交给浏览器,绝不 await text()
    return new Response(upstream.body, {
      status: upstream.status,
      statusText: upstream.statusText,
      headers: respHeaders,
    });
  } catch (e) {
    // 原始异常仅进服务端日志供排障;返回给浏览器的 detail 用可读文案,
    // 不把 "TypeError: fetch failed" 之类底层错误直接暴露给终端用户。
    console.error(`[api-proxy] ${method} ${target} FAILED ->`, e);
    return new Response(JSON.stringify({ detail: "无法连接后端服务,请稍后重试" }), {
      status: 502,
      headers: { "content-type": "application/json" },
    });
  }
}

export const GET = proxy;
export const POST = proxy;
export const PUT = proxy;
export const PATCH = proxy;
export const DELETE = proxy;
export const HEAD = proxy;
export const OPTIONS = proxy;