feat: two-server AI transport (remote multipart mode)#24
Open
LaNguAx wants to merge 3 commits into
Open
Conversation
Add an AI_TRANSFER_MODE (path | remote) so the NestJS backend can drive the
FastAPI AI service either by shared filesystem paths (path, local/dev default)
or over multipart HTTP for two-server deployments with no shared storage.
Backend:
- env.validation: add AI_TRANSFER_MODE and AI_INTERNAL_TOKEN
- extract all AI HTTP I/O into AiClientService (health, path /process, remote
/process-upload multipart upload via fs.openAsBlob, /result download via
Readable.fromWeb + pipeline, /cancel); typed NDJSON in ai-protocol.types
- slim ProcessingService to orchestration; download+save result in remote mode
- bearer token sent only when configured; never logged
- validate the result download URL (same-origin /result/<id>) to prevent SSRF
AI service:
- pure security helpers (security.py): job-id/extension/constant-time token
- new /process-upload (multipart) and /result/{jobId} (FileResponse, no path
input); extend /cancel; token-guard mutating endpoints when token is set
- WORK_UPLOAD_DIR/WORK_RESULT_DIR; add python-multipart dependency
Tests: backend env + AiClientService specs (mocked fetch); AI security helper
tests. Public API and frontend UX unchanged.
Co-authored-by: Cursor <cursoragent@cursor.com>
Document the new path vs remote transport, the two-server (app + GPU server, no shared storage) architecture, AI_TRANSFER_MODE / AI_INTERNAL_TOKEN and the AI WORK_* dirs, the token-guarded internal endpoints (/process, /process-upload, /result, /cancel), and the 20MB demo cap. - README, root AGENTS.md + CLAUDE.md env table - apps/backend/AGENTS.md, apps/ai/AGENTS.md - backend + ai .env.development.example / .env.production.example (placeholders; no real IPs in source, token placeholder change-me) - note the Context7/Tavily lookup expectation for future framework changes Co-authored-by: Cursor <cursoragent@cursor.com>
Add docs/two-server-ai-transport.md summarizing the refactor (what/why), env vars, endpoints, security, verification results, local manual test, and the remaining infrastructure next steps for the app and GPU servers. Co-authored-by: Cursor <cursoragent@cursor.com>
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Problem
The backend handed work to the AI service by sending absolute filesystem paths (
inputPath,outputPath) toPOST /process. That only works when the backend and AI run on the same machine or share a volume. The real deployment is two machines with no shared storage: an app server (frontend, backend, upload/result storage) and a separate GPU server running the FastAPI/PyTorch service. The path-based protocol cannot bridge that gap.Solution
Introduce a selectable transport via
AI_TRANSFER_MODE:path(default) — unchanged path-based/processfor same-machine / local dev.remote— the backend uploads the video to the AI over multipart HTTP (POST /process-upload), consumes the NDJSON progress stream, then downloads the enhanced result (GET /result/:jobId) and saves it locally. Built for the two-server topology.The browser → frontend → backend flow, storage, SSE, polling, and result streaming are all unchanged; only the internal backend↔AI hop changed.
Public API compatibility
No public endpoints changed. Still:
POST /api/upload,GET /api/upload/status/:jobId,GET /api/upload/result/:jobId,POST /api/upload/cancel/:jobId,SSE /api/upload/events/:jobId,GET /api/upload/stream/:jobId. Shared@repo/consts/@repo/schemas/@repo/contractsare untouched. The frontend was not modified and never talks to the GPU server.New AI internal endpoints
POST /process-upload(multipartjobId+video) → NDJSON stream; thecompletedline carriesresultDownloadUrl.GET /result/{jobId}→ enhanced video viaFileResponsefromWORK_RESULT_DIR; 404 if missing; no caller-supplied path.POST /cancelextended to cover both/processand/process-uploadjobs.GET /healthandPOST /processpreserved.New env vars
AI_TRANSFER_MODEpathpath|remotetransportAI_INTERNAL_TOKENAI_INTERNAL_TOKENWORK_UPLOAD_DIR../../storage/ai/uploadsWORK_RESULT_DIR../../storage/ai/resultsTwo-server example values (placeholders, no real IPs in source) live in the
.env.production.examplefiles withAI_TRANSFER_MODE=remote,AI_INTERNAL_TOKEN=change-me, andMAX_FILE_SIZE_MB=20(demo cap).Security / token behavior
AI_INTERNAL_TOKENis set, the backend sendsAuthorization: Bearer <token>and the AI requires it on/process,/process-upload,/result, and/cancel(constant-timehmac.compare_digest). Empty token = no-op (local dev)./healthis always open. The token is never logged or returned.jobIdis validated (^[A-Za-z0-9_-]{1,128}$) and upload extensions are allow-listed, so request input cannot escape the work dirs./resultresolves and confirms the file is insideWORK_RESULT_DIR./result/<jobId>path before fetching, preventing URL-authority injection / SSRF.Hardened in response to a security review run on this branch (two medium findings: unauthenticated
/processon an exposed GPU host, andresultDownloadUrltrust — both fixed).Tests / checks run
pnpm --filter backend lint✅,check-types✅,build✅,test✅ (14 tests: env validation acceptsremote/ rejects invalid;AiClientServicetoken header, NDJSON parse, result download+save, SSRF-URL rejection, cancel-with-token, 404 tolerance)pnpm --filter frontend check-types✅,build✅pnpm check-types✅,pnpm build✅python -m py_compile apps/ai/server.py apps/ai/security.py✅;python apps/ai/test_security.py✅ (4 tests)pnpm --filter frontend lintfails becauseeslint-plugin-react-hooks@7.0.1can't resolvezod-validation-error/v4under pnpm strict hoisting;pnpm format:checkflags files repo-wide due to CRLF working-tree line endings on Windows (git normalizes to LF on commit). No frontend code,package.json, or lockfile was changed.Research notes (Context7 + Tavily)
FormData+await fs.openAsBlob(path)streams the file; do not setContent-Typemanually (fetch sets the boundary). →streamRemoteProcess.Readable.fromWeb(response.body)+pipeline(..., createWriteStream). →downloadResult./fastapi/fastapi/0.115.13):UploadFile = File()+Form()together (requirespython-multipart); custom Authorization-header dependency;FileResponse(path, media_type, filename). →/process-upload,require_token,/result.Manual verification (local two-server simulation)
Full local e2e was not run here because torch and the model checkpoint are not present on this machine. To verify on a box with the AI deps + checkpoint:
AI_INTERNAL_TOKEN=dev-secret(+WORK_UPLOAD_DIR/WORK_RESULT_DIR), runpnpm --filter ai dev(/healthshowsmodel_loaded: true).AI_TRANSFER_MODE=remote,AI_INTERNAL_TOKEN=dev-secret,AI_SERVICE_URL=http://localhost:8000, runpnpm --filter backend dev.pnpm --filter frontend dev; upload a small (<20MB) video./process-upload, AI streams NDJSON progress, backend downloads/result/:jobIdand saves locally, the frontend streams the result, and Cancel works mid-job. Verify/process-uploadreturns 401 without the bearer header.Remaining limitations
remotemode exists).Out of scope (later infra agents)
No Nginx/PM2/SSH/firewall/SSL/Linux-user/server-folder/production-env work — this PR is a code + docs refactor only. Concrete server addresses, the domain, and the GPU server runtime setup are left to infrastructure tooling.