-
Notifications
You must be signed in to change notification settings - Fork 8.8k
fix(frontend): proxy LangGraph SSE without buffering #2797
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
LittleChenLiya
wants to merge
1
commit into
bytedance:main
Choose a base branch
from
LittleChenLiya:fix/langgraph-sse-proxy-buffering
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+259
−22
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| import { type NextRequest } from "next/server"; | ||
|
|
||
| export const runtime = "nodejs"; | ||
| export const dynamic = "force-dynamic"; | ||
|
|
||
| const GATEWAY_BASE_URL = | ||
| process.env.DEER_FLOW_INTERNAL_GATEWAY_BASE_URL ?? "http://127.0.0.1:8001"; | ||
|
|
||
| const HOP_BY_HOP_HEADERS = [ | ||
| "connection", | ||
| "keep-alive", | ||
| "proxy-authenticate", | ||
| "proxy-authorization", | ||
| "te", | ||
| "trailer", | ||
| "transfer-encoding", | ||
| "upgrade", | ||
| ] as const; | ||
|
|
||
| function buildGatewayUrl(path: string[] | undefined, search: string) { | ||
| const pathname = ["api", ...(path ?? []).map(encodeURIComponent)].join("/"); | ||
| return `${GATEWAY_BASE_URL.replace(/\/+$/, "")}/${pathname}${search}`; | ||
| } | ||
|
|
||
| function buildHeaders(request: NextRequest) { | ||
| const headers = new Headers(request.headers); | ||
| for (const name of ["host", "content-length", ...HOP_BY_HOP_HEADERS]) { | ||
| headers.delete(name); | ||
| } | ||
| headers.set("accept-encoding", "identity"); | ||
| return headers; | ||
| } | ||
|
|
||
| async function proxyRequest( | ||
| request: NextRequest, | ||
| context: { params: Promise<{ path?: string[] }> }, | ||
| ) { | ||
| const { path } = await context.params; | ||
| const target = buildGatewayUrl(path, request.nextUrl.search); | ||
| const method = request.method.toUpperCase(); | ||
| const hasBody = method !== "GET" && method !== "HEAD"; | ||
| const init: RequestInit & { duplex?: "half" } = { | ||
| method, | ||
| headers: buildHeaders(request), | ||
| redirect: "manual", | ||
| cache: "no-store", | ||
| signal: request.signal, | ||
| }; | ||
|
|
||
| if (hasBody) { | ||
| init.body = request.body; | ||
| init.duplex = "half"; | ||
| } | ||
|
|
||
| const upstream = await fetch(target, init); | ||
| const headers = new Headers(upstream.headers); | ||
| for (const name of ["content-length", ...HOP_BY_HOP_HEADERS]) { | ||
| headers.delete(name); | ||
| } | ||
| const cacheControl = headers.get("Cache-Control"); | ||
| headers.set( | ||
| "Cache-Control", | ||
| cacheControl ? `${cacheControl}, no-transform` : "no-cache, no-transform", | ||
| ); | ||
| headers.set("X-Accel-Buffering", "no"); | ||
|
|
||
| return new Response(upstream.body, { | ||
| status: upstream.status, | ||
| statusText: upstream.statusText, | ||
| headers, | ||
| }); | ||
| } | ||
|
|
||
| export const GET = proxyRequest; | ||
| export const POST = proxyRequest; | ||
| export const PUT = proxyRequest; | ||
| export const PATCH = proxyRequest; | ||
| export const DELETE = proxyRequest; | ||
| export const OPTIONS = proxyRequest; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| import { NextRequest } from "next/server"; | ||
| import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; | ||
|
|
||
| type RouteContext = { | ||
| params: Promise<{ path?: string[] }>; | ||
| }; | ||
|
|
||
| async function loadRoute() { | ||
| vi.resetModules(); | ||
| return await import("@/app/api/langgraph/[[...path]]/route"); | ||
| } | ||
|
|
||
| function makeContext(path?: string[]): RouteContext { | ||
| return { | ||
| params: Promise.resolve({ path }), | ||
| }; | ||
| } | ||
|
|
||
| describe("/api/langgraph route proxy", () => { | ||
| const originalGatewayBaseUrl = | ||
| process.env.DEER_FLOW_INTERNAL_GATEWAY_BASE_URL; | ||
|
|
||
| beforeEach(() => { | ||
| process.env.DEER_FLOW_INTERNAL_GATEWAY_BASE_URL = | ||
| "http://gateway.example/base/"; | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| vi.unstubAllGlobals(); | ||
| if (originalGatewayBaseUrl === undefined) { | ||
| delete process.env.DEER_FLOW_INTERNAL_GATEWAY_BASE_URL; | ||
| } else { | ||
| process.env.DEER_FLOW_INTERNAL_GATEWAY_BASE_URL = originalGatewayBaseUrl; | ||
| } | ||
| }); | ||
|
|
||
| test("re-encodes path segments and preserves query strings", async () => { | ||
| const fetchMock = vi.fn(async () => new Response("ok")); | ||
| vi.stubGlobal("fetch", fetchMock); | ||
|
|
||
| const { GET } = await loadRoute(); | ||
| const request = new NextRequest( | ||
| "http://localhost:3000/api/langgraph/ignored?after=a%2Fb", | ||
| ); | ||
| await GET(request, makeContext(["threads", "a/b", "x?y", "#z"])); | ||
|
|
||
| expect(fetchMock).toHaveBeenCalledWith( | ||
| "http://gateway.example/base/api/threads/a%2Fb/x%3Fy/%23z?after=a%2Fb", | ||
| expect.objectContaining({ method: "GET", signal: request.signal }), | ||
| ); | ||
| }); | ||
|
|
||
| test("strips proxy headers while forwarding auth headers and streamed body", async () => { | ||
| const fetchMock = vi.fn(async () => new Response("ok")); | ||
| vi.stubGlobal("fetch", fetchMock); | ||
|
|
||
| const { POST } = await loadRoute(); | ||
| const request = new NextRequest( | ||
| "http://localhost:3000/api/langgraph/threads", | ||
| { | ||
| method: "POST", | ||
| headers: { | ||
| host: "localhost:3000", | ||
| connection: "keep-alive", | ||
| "content-length": "123", | ||
| "transfer-encoding": "chunked", | ||
| cookie: "access_token=abc", | ||
| "x-csrf-token": "csrf", | ||
| "accept-encoding": "gzip, br", | ||
| }, | ||
| body: JSON.stringify({ ok: true }), | ||
| }, | ||
| ); | ||
| const body = request.body; | ||
|
|
||
| await POST(request, makeContext(["threads"])); | ||
|
|
||
| const fetchCalls = fetchMock.mock.calls as unknown as [ | ||
| string, | ||
| RequestInit & { duplex?: "half" }, | ||
| ][]; | ||
| const init = fetchCalls[0]?.[1]; | ||
| expect(init).toBeDefined(); | ||
| expect(init?.method).toBe("POST"); | ||
| expect(init?.body).toBe(body); | ||
| expect(init?.duplex).toBe("half"); | ||
| const headers = init?.headers as Headers; | ||
| expect(headers.get("host")).toBeNull(); | ||
| expect(headers.get("connection")).toBeNull(); | ||
| expect(headers.get("content-length")).toBeNull(); | ||
| expect(headers.get("transfer-encoding")).toBeNull(); | ||
| expect(headers.get("cookie")).toBe("access_token=abc"); | ||
| expect(headers.get("x-csrf-token")).toBe("csrf"); | ||
| expect(headers.get("accept-encoding")).toBe("identity"); | ||
| }); | ||
|
|
||
| test("streams upstream bodies and normalizes response headers", async () => { | ||
| const stream = new ReadableStream({ | ||
| start(controller) { | ||
| controller.enqueue(new TextEncoder().encode("event: metadata\n\n")); | ||
| controller.close(); | ||
| }, | ||
| }); | ||
| const fetchMock = vi.fn( | ||
| async () => | ||
| new Response(stream, { | ||
| status: 201, | ||
| statusText: "Created", | ||
| headers: { | ||
| "cache-control": "private, no-store", | ||
| "content-length": "999", | ||
| connection: "close", | ||
| "transfer-encoding": "chunked", | ||
| }, | ||
| }), | ||
| ); | ||
| vi.stubGlobal("fetch", fetchMock); | ||
|
|
||
| const { GET } = await loadRoute(); | ||
| const response = await GET( | ||
| new NextRequest("http://localhost:3000/api/langgraph/threads"), | ||
| makeContext(["threads"]), | ||
| ); | ||
|
|
||
| expect(response.status).toBe(201); | ||
| expect(response.statusText).toBe("Created"); | ||
| expect(response.body).toBe(stream); | ||
| expect(response.headers.get("cache-control")).toBe( | ||
| "private, no-store, no-transform", | ||
| ); | ||
| expect(response.headers.get("x-accel-buffering")).toBe("no"); | ||
| expect(response.headers.get("content-length")).toBeNull(); | ||
| expect(response.headers.get("connection")).toBeNull(); | ||
| expect(response.headers.get("transfer-encoding")).toBeNull(); | ||
| }); | ||
|
|
||
| test("forwards OPTIONS requests", async () => { | ||
| const fetchMock = vi.fn(async () => new Response(null, { status: 204 })); | ||
| vi.stubGlobal("fetch", fetchMock); | ||
|
|
||
| const { OPTIONS } = await loadRoute(); | ||
| const response = await OPTIONS( | ||
| new NextRequest("http://localhost:3000/api/langgraph/threads", { | ||
| method: "OPTIONS", | ||
| }), | ||
| makeContext(["threads"]), | ||
| ); | ||
|
|
||
| expect(response.status).toBe(204); | ||
| expect(fetchMock).toHaveBeenCalledWith( | ||
| "http://gateway.example/base/api/threads", | ||
| expect.objectContaining({ method: "OPTIONS" }), | ||
| ); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.