Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix: stream large knowledge uploads through web (#868)

Bingxi Zhao51d7c9a8b538
diff --git a/web/app/api/v1/knowledge/[kbName]/upload/route.ts b/web/app/api/v1/knowledge/[kbName]/upload/route.ts
new file mode 100644
index 000000000..ad4b8b06b
--- /dev/null
+++ b/web/app/api/v1/knowledge/[kbName]/upload/route.ts
@@ -0,0 +1,8 @@
+import { forwardBackendUpload } from "@/lib/streaming-upload-proxy";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+export function POST(request: Request): Promise<Response> {
+ return forwardBackendUpload(request);
+}
diff --git a/web/app/api/v1/knowledge/create/route.ts b/web/app/api/v1/knowledge/create/route.ts
new file mode 100644
index 000000000..ad4b8b06b
--- /dev/null
+++ b/web/app/api/v1/knowledge/create/route.ts
@@ -0,0 +1,8 @@
+import { forwardBackendUpload } from "@/lib/streaming-upload-proxy";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+export function POST(request: Request): Promise<Response> {
+ return forwardBackendUpload(request);
+}
diff --git a/web/lib/streaming-upload-proxy.ts b/web/lib/streaming-upload-proxy.ts
new file mode 100644
index 000000000..bff37b961
--- /dev/null
+++ b/web/lib/streaming-upload-proxy.ts
@@ -0,0 +1,72 @@
+const DEFAULT_API_BASE_URL = "http://127.0.0.1:8001";
+
+// HTTP/1.1 hop-by-hop headers describe one transport connection and must not
+// be replayed on the independent frontend -> backend connection.
+const HOP_BY_HOP_HEADERS = new Set([
+ "connection",
+ "keep-alive",
+ "proxy-authenticate",
+ "proxy-authorization",
+ "te",
+ "trailer",
+ "transfer-encoding",
+ "upgrade",
+]);
+
+type StreamingRequestInit = RequestInit & { duplex: "half" };
+
+export interface UploadProxyDependencies {
+ apiBaseUrl?: string;
+ fetchImpl?: typeof fetch;
+}
+
+function forwardedHeaders(source: Headers, { request }: { request: boolean }) {
+ const headers = new Headers(source);
+ const connectionTokens = (headers.get("connection") || "")
+ .split(",")
+ .map((value) => value.trim().toLowerCase())
+ .filter(Boolean);
+
+ for (const name of [...HOP_BY_HOP_HEADERS, ...connectionTokens]) {
+ headers.delete(name);
+ }
+ if (request) headers.delete("host");
+ return headers;
+}
+
+/**
+ * Stream a large multipart upload to FastAPI without materializing it in the
+ * Next.js process. The two matching App Router endpoints are excluded from
+ * `proxy.ts`, whose automatic request clone otherwise truncates large batches.
+ */
+export async function forwardBackendUpload(
+ request: Request,
+ dependencies: UploadProxyDependencies = {},
+): Promise<Response> {
+ const apiBaseUrl =
+ dependencies.apiBaseUrl ||
+ process.env.DEEPTUTOR_API_BASE_URL ||
+ DEFAULT_API_BASE_URL;
+ const fetchImpl = dependencies.fetchImpl || globalThis.fetch;
+ const incomingUrl = new URL(request.url);
+ const upstreamUrl = new URL(
+ incomingUrl.pathname + incomingUrl.search,
+ apiBaseUrl,
+ );
+
+ const init: StreamingRequestInit = {
+ method: request.method,
+ headers: forwardedHeaders(request.headers, { request: true }),
+ body: request.body,
+ signal: request.signal,
+ redirect: "manual",
+ duplex: "half",
+ };
+ const upstream = await fetchImpl(upstreamUrl, init);
+
+ return new Response(upstream.body, {
+ status: upstream.status,
+ statusText: upstream.statusText,
+ headers: forwardedHeaders(upstream.headers, { request: false }),
+ });
+}
diff --git a/web/next.config.js b/web/next.config.js
index 44ed21c5e..7fb79d1c9 100644
--- a/web/next.config.js
+++ b/web/next.config.js
@@ -109,12 +109,10 @@ const nextConfig = {
// This eliminates the need to copy the full node_modules into Docker production images
output: "standalone",
- // web/proxy.ts (the Next.js middleware) forwards /api/* and /ws/* to the
- // backend by buffering and re-issuing the request. Next caps the buffered
- // request body at 10MB by default, but the backend accepts uploads up to
- // 200MB (DocumentValidator.MAX_FILE_SIZE). Raise the proxy cap to match (plus
- // multipart overhead headroom) so knowledge-base document uploads aren't
- // silently truncated when they pass through the proxy.
+ // web/proxy.ts clones request bodies before rewriting them. Keep enough room
+ // for individual large-body endpoints that still use Proxy. Knowledge-base
+ // create/upload batches use dedicated streaming route handlers instead, so
+ // their total size is not coupled to this in-memory clone limit.
experimental: {
proxyClientMaxBodySize: 210 * 1024 * 1024,
},
diff --git a/web/proxy.ts b/web/proxy.ts
index fc33daefb..6a625c687 100644
--- a/web/proxy.ts
+++ b/web/proxy.ts
@@ -74,8 +74,13 @@ export function proxy(req: NextRequest): NextResponse {
export const config = {
// Run on every request except Next.js internals and the favicon. The /api/*
// and /ws/* paths are explicitly handled above (rewritten to the backend);
+ // large knowledge create/upload requests are handled by dedicated App Router
+ // endpoints that stream directly to FastAPI. Excluding them here is crucial:
+ // merely entering Proxy makes Next clone and cap the multipart body.
// the browser's /_next/image optimizer requests are excluded here, while the
// optimizer's loopback fetch for the source image (e.g. /logo.png) is let
// through the auth gate by isAuthExempt.
- matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
+ matcher: [
+ "/((?!_next/static|_next/image|favicon.ico|api/v1/knowledge/(?:create|[^/]+/upload)(?:/|$)).*)",
+ ],
};
diff --git a/web/tests/proxy-policy.test.ts b/web/tests/proxy-policy.test.ts
index e0306b510..1e5862220 100644
--- a/web/tests/proxy-policy.test.ts
+++ b/web/tests/proxy-policy.test.ts
@@ -2,6 +2,8 @@ import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import path from "node:path";
+import { unstable_doesMiddlewareMatch } from "next/experimental/testing/server";
+import { config as proxyConfig } from "../proxy";
// Unit tests for the pure middleware routing policy (web/lib/proxy-policy.ts).
// The policy is deliberately decoupled from `next/server`, so it can be
@@ -31,6 +33,19 @@ test("isBackendPath matches /api and /ws paths only", () => {
assert.equal(isBackendPath("/logo.png"), false);
});
+test("large knowledge uploads bypass the buffering proxy", () => {
+ const matches = (url: string) =>
+ unstable_doesMiddlewareMatch({ config: proxyConfig, url });
+
+ assert.equal(matches("http://localhost/api/v1/knowledge/create"), false);
+ assert.equal(
+ matches("http://localhost/api/v1/knowledge/my%20kb/upload"),
+ false,
+ );
+ assert.equal(matches("http://localhost/api/v1/knowledge/list"), true);
+ assert.equal(matches("http://localhost/home"), true);
+});
+
test("isCodexCallbackPath matches only the exact public callback path", () => {
assert.equal(CODEX_CALLBACK_PATH, "/auth/callback");
assert.equal(CODEX_CALLBACK_API_PATH, "/api/v1/auth/openai-codex/callback");
diff --git a/web/tests/streaming-upload-proxy.test.ts b/web/tests/streaming-upload-proxy.test.ts
new file mode 100644
index 000000000..1bfcb3853
--- /dev/null
+++ b/web/tests/streaming-upload-proxy.test.ts
@@ -0,0 +1,60 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { forwardBackendUpload } from "../lib/streaming-upload-proxy";
+
+type StreamingRequestInit = RequestInit & { duplex: "half" };
+
+test("upload proxy streams the original body and preserves the backend response", async () => {
+ const request = new Request(
+ "http://frontend.test/api/v1/knowledge/create?source=web",
+ {
+ method: "POST",
+ headers: {
+ connection: "keep-alive, x-remove-me",
+ "content-type": "multipart/form-data; boundary=example",
+ cookie: "deeptutor_session=token",
+ host: "frontend.test",
+ "x-remove-me": "transport-only",
+ },
+ body: new Blob(["multipart bytes"]).stream(),
+ duplex: "half",
+ } as StreamingRequestInit,
+ );
+
+ const response = await forwardBackendUpload(request, {
+ apiBaseUrl: "http://127.0.0.1:8123",
+ fetchImpl: async (input, init) => {
+ assert.equal(
+ String(input),
+ "http://127.0.0.1:8123/api/v1/knowledge/create?source=web",
+ );
+ assert.equal(init?.method, "POST");
+ const headers = new Headers(init?.headers);
+ assert.equal(
+ headers.get("content-type"),
+ "multipart/form-data; boundary=example",
+ );
+ assert.equal(headers.get("cookie"), "deeptutor_session=token");
+ assert.equal(headers.has("connection"), false);
+ assert.equal(headers.has("host"), false);
+ assert.equal(headers.has("x-remove-me"), false);
+ assert.equal((init as StreamingRequestInit).duplex, "half");
+ assert.equal(await new Response(init?.body).text(), "multipart bytes");
+
+ return new Response('{"task_id":"kb_init_1"}', {
+ status: 202,
+ headers: {
+ connection: "close",
+ "content-type": "application/json",
+ "x-backend": "fastapi",
+ },
+ });
+ },
+ });
+
+ assert.equal(response.status, 202);
+ assert.equal(response.headers.get("content-type"), "application/json");
+ assert.equal(response.headers.get("x-backend"), "fastapi");
+ assert.equal(response.headers.has("connection"), false);
+ assert.equal(await response.text(), '{"task_id":"kb_init_1"}');
+});