Skip to content
Python

Gateway: los enlaces absolutos del proxy salen con la dirección externa del gateway

neuregexd2b66a6b56f7
diff --git a/infra/gateway.py b/infra/gateway.py
index 6514b40..af23e3c 100644
--- a/infra/gateway.py
+++ b/infra/gateway.py
@@ -9,6 +9,10 @@
unload everything (POST /free) so nothing from the previous app stays in VRAM.
- GET /freefield/status shows the current app and ComfyUI's device stats.
- GET /health is open, for Modal's startup probe.
+- The proxy writes absolute links (a job's `urls.self`, `.events`, `.cancel`, an output's
+ `url`) from the host *it* sees, http://127.0.0.1:8189; the SDK follows those links
+ verbatim, so from outside they went nowhere ("fetch failed", 23 oct). JSON answers are
+ rewritten to the address the client reached the gateway on.
Run: python gateway.py (env: FREEFIELD_TOKEN, COMFYUI_URL, PROXY_URL, GATEWAY_PORT)
"""
@@ -92,6 +96,17 @@ async def status(request: web.Request) -> web.Response:
return web.json_response({"app": pantry.app, "models": pantry.models, "frees": pantry.frees, "comfyui": stats})
+def external_base(request: web.Request) -> str:
+ """Where the client reached us: Modal terminates TLS and says so in X-Forwarded-Proto."""
+ scheme = request.headers.get("X-Forwarded-Proto", request.scheme).split(",")[0].strip()
+ return f"{scheme}://{request.host}"
+
+
+def relink(body: bytes, request: web.Request) -> bytes:
+ """The proxy's own address in a JSON answer becomes the gateway's external one."""
+ return body.replace(PROXY_URL.encode(), external_base(request).encode())
+
+
async def forward(request: web.Request) -> web.StreamResponse:
session: ClientSession = request.app["session"]
headers = {k: v for k, v in request.headers.items() if k.lower() not in HOP_HEADERS}
@@ -103,10 +118,14 @@ async def forward(request: web.Request) -> web.StreamResponse:
data = body() if request.can_read_body else None
async with session.request(request.method, f"{PROXY_URL}{request.rel_url}", headers=headers, data=data,
allow_redirects=False) as upstream:
+ passthrough = {k: v for k, v in upstream.headers.items() if k.lower() not in HOP_HEADERS | {"content-encoding"}}
+ if upstream.content_type == "application/json": # job and asset answers carry links: fix them up whole
+ raw = relink(await upstream.read(), request)
+ passthrough.pop("Content-Length", None)
+ return web.Response(status=upstream.status, body=raw, headers=passthrough)
resp = web.StreamResponse(status=upstream.status)
- for k, v in upstream.headers.items():
- if k.lower() not in HOP_HEADERS | {"content-encoding"}:
- resp.headers[k] = v
+ for k, v in passthrough.items():
+ resp.headers[k] = v
await resp.prepare(request)
async for chunk in upstream.content.iter_any(): # streams SSE events and big files as they come
await resp.write(chunk)
diff --git a/test/gateway_test.py b/test/gateway_test.py
new file mode 100644
index 0000000..1cc9e7e
--- /dev/null
+++ b/test/gateway_test.py
@@ -0,0 +1,47 @@
+"""The gateway against a fake proxy: JSON links come back on the gateway's own address, streams pass through.
+
+ pip install aiohttp && python test/gateway_test.py
+"""
+import asyncio, os, sys
+from pathlib import Path
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "infra"))
+os.environ["FREEFIELD_TOKEN"] = "t0k"
+os.environ["PROXY_URL"] = "http://127.0.0.1:18189"
+from aiohttp import web, ClientSession
+import gateway # infra/gateway.py
+
+async def fake_proxy_app():
+ async def job(request):
+ base = f"{request.scheme}://{request.host}"
+ return web.json_response({"id": "j1", "status": "succeeded",
+ "urls": {"self": f"{base}/api/v2/jobs/j1", "events": f"{base}/api/v2/jobs/j1/events"},
+ "outputs": [{"id": "o1", "url": f"{base}/api/v2/jobs/j1/outputs/o1"}]})
+ async def events(request):
+ resp = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
+ await resp.prepare(request)
+ await resp.write(b"data: {\"url\": \"http://127.0.0.1:18189/x\"}\n\n")
+ await resp.write_eof(); return resp
+ app = web.Application(); app.router.add_get("/api/v2/jobs/j1", job); app.router.add_get("/api/v2/jobs/j1/events", events)
+ return app
+
+async def main():
+ proxy = web.AppRunner(await fake_proxy_app()); await proxy.setup(); await web.TCPSite(proxy, "127.0.0.1", 18189).start()
+ gw = web.AppRunner(gateway.make_app()); await gw.setup(); await web.TCPSite(gw, "127.0.0.1", 18000).start()
+ async with ClientSession() as s:
+ h = {"Authorization": "Bearer t0k"}
+ async with s.get("http://127.0.0.1:18000/api/v2/jobs/j1", headers=h) as r:
+ body = await r.json(); assert r.status == 200, r.status
+ assert body["urls"]["self"] == "http://127.0.0.1:18000/api/v2/jobs/j1", body["urls"]
+ assert body["outputs"][0]["url"] == "http://127.0.0.1:18000/api/v2/jobs/j1/outputs/o1"
+ async with s.get("http://127.0.0.1:18000/api/v2/jobs/j1", headers={**h, "X-Forwarded-Proto": "https", "Host": "gw.example.test"}) as r:
+ body = await r.json()
+ assert body["urls"]["self"] == "https://gw.example.test/api/v2/jobs/j1", body["urls"]
+ async with s.get("http://127.0.0.1:18000/api/v2/jobs/j1/events", headers=h) as r:
+ text = await r.text(); assert r.headers["Content-Type"].startswith("text/event-stream")
+ assert "http://127.0.0.1:18189/x" in text, "streams are passed through untouched"
+ async with s.get("http://127.0.0.1:18000/api/v2/jobs/j1") as r:
+ assert r.status == 401, r.status
+ print("gateway relink ok")
+ await gw.cleanup(); await proxy.cleanup()
+
+asyncio.run(main())