Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Paid, hosted product at menivor.com, now retired as a company project. Fresh squashed history of the cleaned working tree (secret-scanned, no .env, no customer data, no outreach logs). Built on MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
507 lines
21 KiB
Markdown
507 lines
21 KiB
Markdown
# ReelForge Platform Architecture Specification
|
|
|
|
> **Status:** Implemented platform baseline plus incremental migration contract.
|
|
> **Applies to:** `apps/api`, `apps/web`, `apps/mobile`, `apps/desktop`,
|
|
> `packages`, and `external`.
|
|
> **Current-runtime authority:** `INTEGRATION_CONTRACT.md` and the code.
|
|
> **Directory authority:** `REPOSITORY_LAYOUT_SPEC.md`.
|
|
|
|
## 1. Purpose
|
|
|
|
ReelForge is one product with three first-party clients and one authoritative
|
|
backend. Web, mobile, and desktop may present different user experiences, but
|
|
they must not implement independent business rules, credit accounting, provider
|
|
selection, job orchestration, or media ownership logic.
|
|
|
|
This specification defines:
|
|
|
|
- which deployable owns each responsibility;
|
|
- how clients, workers, storage, and providers communicate;
|
|
- which contracts are public and which are internal;
|
|
- how the embedded editor and GPU generation engine fit into the product;
|
|
- how code under `external/` may be evaluated and adopted safely;
|
|
- the migration sequence from today's tree to the target boundaries.
|
|
|
|
## 2. Architectural decisions
|
|
|
|
### AD-1 — One product API
|
|
|
|
`apps/api` is the only authoritative product backend. Every first-party client
|
|
uses `/api/v1`. There is no web-only, mobile-only, or desktop-only business API.
|
|
|
|
The narrow `apps/web/editor-bff` adapter is permitted only for editor-specific
|
|
transport concerns. It may not own users, jobs, assets, credits, projects,
|
|
subscriptions, provider credentials, or durable product data.
|
|
|
|
### AD-2 — Three thin first-party clients
|
|
|
|
- `apps/web`: Next.js browser application and platform-admin console.
|
|
- `apps/mobile`: Expo/React Native application.
|
|
- `apps/desktop`: Rust/GPUI native desktop application.
|
|
|
|
All three consume the same capability document and API semantics. A feature may
|
|
have platform-specific UX, but a platform must not redefine request models or
|
|
terminal job states.
|
|
|
|
`apps/desktop/electron-legacy` is migration reference material. It is not the
|
|
desktop runtime, is not included in the JavaScript workspace, and receives no
|
|
new product functionality.
|
|
|
|
### AD-3 — FastAPI owns business transactions
|
|
|
|
Only `apps/api` may:
|
|
|
|
- authenticate a product principal;
|
|
- authorize workspace access;
|
|
- debit or refund credits;
|
|
- create or mutate jobs and assets;
|
|
- select an enabled generation provider;
|
|
- enforce idempotency, quotas, pilot access, and policy;
|
|
- create signed media access;
|
|
- publish or schedule social content;
|
|
- write audit and telemetry records.
|
|
|
|
Clients may validate for usability, but server validation is authoritative.
|
|
|
|
### AD-4 — Workers, not HTTP handlers, execute long-running media work
|
|
|
|
FastAPI persists and enqueues. Celery workers execute. HTTP requests must not
|
|
hold open while video, avatar, TTS, caption, compose, or GPU generation work is
|
|
running.
|
|
|
|
The queue boundaries are:
|
|
|
|
| Queue | Owner | Work |
|
|
|---|---|---|
|
|
| `celery` | standard worker | script, TTS, captions, notifications and light tasks |
|
|
| `render` | render worker | avatar and FFmpeg-heavy composition |
|
|
| `generation` | GPU generation worker | Pixelle/Wan/ComfyUI-backed B-roll generation |
|
|
|
|
Database job rows are the status source of truth. Redis is transport and
|
|
coordination infrastructure, not the durable product database.
|
|
|
|
### AD-5 — External projects never become implicit dependencies
|
|
|
|
Nothing in `external/` is imported by a client or by the API application at
|
|
runtime. Adoption requires an explicit adapter in `apps/api`, a pinned version,
|
|
license and model-weight review, a dedicated dependency/image boundary, health
|
|
behavior, failure semantics, and an operational owner.
|
|
|
|
### AD-6 — One machine-readable client contract
|
|
|
|
FastAPI OpenAPI is the machine-readable HTTP source. The target
|
|
`packages/api-contract` normalizes and versions that schema and generates or
|
|
validates client types. Hand-maintained web and mobile copies are transitional.
|
|
|
|
OpenAPI does not replace product-level semantics. The following remain written
|
|
contracts:
|
|
|
|
- idempotency behavior;
|
|
- credit debit/refund rules;
|
|
- polling and terminal-state rules;
|
|
- upload ownership and signed-URL behavior;
|
|
- capability and provider-disabled behavior;
|
|
- error categories and retry eligibility.
|
|
|
|
## 3. System context
|
|
|
|
```text
|
|
┌──────────────────────────────── FIRST-PARTY CLIENTS ────────────────────────────────┐
|
|
│ │
|
|
│ apps/web (Next.js) apps/mobile (Expo) apps/desktop (Rust/GPUI) │
|
|
│ Clerk session SecureStore credential OS credential manager │
|
|
│ browser upload device media picker native file/screen capture │
|
|
│ │
|
|
└──────────────────────────────────────┬─────────────────────────────────────────────┘
|
|
│ HTTPS, /api/v1, correlation id
|
|
▼
|
|
┌──────────────────────────── apps/api: FastAPI request tier ─────────────────────────┐
|
|
│ auth · RBAC · pilot/capabilities · policy · idempotency · credits · jobs · uploads │
|
|
│ provider registry · signed previews · API envelope · audit and telemetry │
|
|
└───────────────┬──────────────────────────┬─────────────────────────┬─────────────────┘
|
|
│ SQL │ broker │ S3 protocol
|
|
▼ ▼ ▼
|
|
Neon/Postgres Redis/Celery Cloudflare R2
|
|
durable product data queue + coordination private media
|
|
│
|
|
┌──────────────────────┼──────────────────────┐
|
|
▼ ▼ ▼
|
|
standard worker render worker generation worker
|
|
script/TTS/etc. avatar/compose AI B-roll/GPU
|
|
│ │ │
|
|
└──────────── provider adapter boundary ─────┘
|
|
│
|
|
Claude · ElevenLabs · HeyGen · ComfyUI Deploy · publishing APIs
|
|
```
|
|
|
|
## 4. Deployable boundaries
|
|
|
|
### 4.1 API request tier
|
|
|
|
Entry points:
|
|
|
|
- `apps/api/app/asgi.py`: FastAPI lifecycle and application assembly.
|
|
- `apps/api/app/router.py`: public router composition.
|
|
- `apps/api/app/domains/reels/router.py`: canonical reel/job HTTP workflows.
|
|
- `apps/api/app/domains/broll/router.py`: canonical B-roll HTTP workflows.
|
|
- `apps/api/app/domains/media/router.py`: upload intents and registration.
|
|
- `apps/api/app/domains/editor/router.py`: non-destructive editor exports.
|
|
- `apps/api/app/controllers/v1/`: compatibility HTTP adapters for domains not
|
|
extracted yet.
|
|
|
|
Domain routers and compatibility controllers translate HTTP requests into service calls. They should not contain
|
|
provider-specific polling loops, FFmpeg graphs, or direct SQL beyond established
|
|
repository transactions.
|
|
|
|
The API is horizontally scalable when all shared state is in Postgres, Redis,
|
|
or R2. Process-local OAuth state, idempotency, quotas, or job state is prohibited
|
|
in production paths.
|
|
|
|
### 4.2 Standard and render workers
|
|
|
|
Entry points:
|
|
|
|
- `apps/api/app/workers/celery_app.py`;
|
|
- `apps/api/app/workers/pipeline.py`;
|
|
- `apps/api/app/workers/tasks.py`.
|
|
|
|
The canonical reel graph remains:
|
|
|
|
```text
|
|
script → tts → { avatar ∥ captions } → compose → optional publish/upload
|
|
```
|
|
|
|
Workers must be idempotent at the stage boundary, record correlation/job ids,
|
|
persist stage progress monotonically, and reconcile reserved credits on terminal
|
|
infrastructure failure.
|
|
|
|
### 4.3 GPU generation worker
|
|
|
|
The `generation` Celery queue is the only product route into backend-owned GPU
|
|
generation. It may use code in `apps/api/engine` and provider adapters in
|
|
`apps/api/app/domains/broll/providers`.
|
|
|
|
It must not expose `apps/api/app/generation` or an upstream project's native API
|
|
directly to product clients. Internal schemas can change independently; the
|
|
stable client surface is `/api/v1/generation/broll/*`.
|
|
|
|
### 4.4 Web deployable
|
|
|
|
`apps/web` owns:
|
|
|
|
- marketing and authenticated browser routes;
|
|
- Clerk browser authentication;
|
|
- platform administration UX;
|
|
- browser media selection/upload orchestration;
|
|
- product polling, signed preview, and editor presentation;
|
|
- accessibility, responsive layout, and browser-specific state.
|
|
|
|
It does not own credits, job truth, provider secrets, media authorization, or
|
|
durable editor/project records outside API-defined resources.
|
|
|
|
The embedded OpenCut migration is split intentionally:
|
|
|
|
- `editor-module`: source being integrated into the Next.js runtime;
|
|
- `editor-bff`: optional narrow adapter for editor transport only.
|
|
|
|
The target is one authenticated web application, not a second editor product.
|
|
|
|
### 4.5 Mobile deployable
|
|
|
|
`apps/mobile` owns device-native routing, media pickers, secure local session
|
|
storage, foreground/background polling lifecycle, video previews, and mobile
|
|
share handoff.
|
|
|
|
Mobile consumes `@reelforge/api-contract` for shared generation DTOs and state
|
|
semantics. Expo-specific native types remain local; API DTOs do not.
|
|
|
|
### 4.6 Desktop deployable
|
|
|
|
`apps/desktop` is Rust/GPUI. It owns:
|
|
|
|
- native windowing and workspace UI;
|
|
- screen/file capture and upload orchestration;
|
|
- platform preferences for non-secret API configuration;
|
|
- macOS Keychain, Windows Credential Manager, or Linux Secret Service storage;
|
|
- typed API execution on background threads/tasks;
|
|
- job polling, library selection, native preview playback, and B-roll attachment.
|
|
|
|
Unavailable secure credential storage must prevent saving credentials. No
|
|
plaintext fallback is allowed.
|
|
|
|
### 4.7 SDK packages
|
|
|
|
SDKs are public consumers of `/api/v1`, not a place to share internal server
|
|
domain logic. Both SDKs should expose the same stable subset and error model.
|
|
|
|
- TypeScript SDK: browser/server JavaScript automation.
|
|
- Python SDK: scripts and backend integrations.
|
|
- API contract package: schema artifact, generated DTOs, compatibility checks.
|
|
|
|
## 5. Data ownership
|
|
|
|
| Data | Authoritative owner | Client cache allowed | Durable location |
|
|
|---|---|---|---|
|
|
| User identity mapping | API auth/core | session presentation only | Postgres + Clerk identity |
|
|
| API credentials | API issues; client secures | yes, secure store only | hash in Postgres; secret at client |
|
|
| Workspace/RBAC | API | read cache | Postgres |
|
|
| Credits/ledger | API | display cache | Postgres |
|
|
| Job state/progress | API/workers | poll cache | Postgres |
|
|
| Media binaries | API storage service | preview/download cache | R2 |
|
|
| Signed preview URL | API | short-lived only | not durable client state |
|
|
| B-roll attachment | API job request | draft cache | durable R2 key in job params |
|
|
| Provider credentials | API/worker environment | never | secret manager/environment |
|
|
| Client preferences | each client | yes | platform-local non-secret storage |
|
|
| Audit/correlation events | API/workers + client emitters | no authoritative cache | Postgres/Sentry/log sink |
|
|
|
|
## 6. Public API and client contract
|
|
|
|
### 6.1 Base and authentication
|
|
|
|
Canonical base: `/api/v1`.
|
|
|
|
The API accepts `X-Correlation-ID` (with legacy `x-task-id` compatibility),
|
|
sanitizes it at the edge, and returns `X-Correlation-ID` on every response. When
|
|
the caller supplies no safe value, the API creates one. Browser CORS exposes the
|
|
header. Job-creating commands persist the same value and carry it through Celery
|
|
context and headers.
|
|
|
|
Web sends a Clerk session token through the shared authentication header behavior.
|
|
Mobile and desktop may use a user-issued API credential. During migration the
|
|
server accepts the existing `x-api-key` convention; the contract package must
|
|
describe exactly which credential types are accepted and must not label a Clerk
|
|
JWT as a public API key internally.
|
|
|
|
### 6.2 Required common response semantics
|
|
|
|
Generation resources expose additive-compatible fields:
|
|
|
|
- stable resource id;
|
|
- `state`;
|
|
- integer `progress`;
|
|
- structured or display-safe `error`;
|
|
- signed `result_url` when previewable;
|
|
- durable media key only where a subsequent API accepts it;
|
|
- `correlation_id`;
|
|
- `retry_eligible`.
|
|
|
|
Clients map HTTP failures consistently:
|
|
|
|
| HTTP | Meaning | UX behavior |
|
|
|---:|---|---|
|
|
| `400/422` | invalid input or content policy | keep draft, mark fields/message |
|
|
| `401` | missing/invalid authentication | reconnect/sign in |
|
|
| `402` | insufficient credits | show required balance/action |
|
|
| `403` | ownership, RBAC, pilot, or provider access denied | explain unavailable action |
|
|
| `404` | missing or non-owned resource | remove stale local reference |
|
|
| `409` | idempotency/conflict | recover original request or refresh |
|
|
| `429` | quota/rate limit | show retry timing; do not duplicate submit |
|
|
| `5xx` | service/provider unavailable | preserve draft; retry only when eligible |
|
|
|
|
### 6.3 Canonical workflow routes
|
|
|
|
- Reel creation and polling: `/jobs`, `/jobs/{id}`.
|
|
- Presigned client upload: `/uploads/presign`, direct R2 upload, then
|
|
`/uploads/register` for a durable caller-owned object key.
|
|
- AI B-roll: `/generation/broll/generate` and
|
|
`/generation/broll/generations/{id}`.
|
|
- Editor export: `/jobs/{id}/exports`, polled through `/jobs/{export_id}`.
|
|
- Capability discovery: `/pilot/capabilities`, later generalized to a versioned
|
|
client-capability document.
|
|
|
|
Legacy `/broll/*` remains an API alias only. Clients must not generate new calls
|
|
to it.
|
|
|
|
## 7. End-to-end workflows
|
|
|
|
### 7.1 Reel generation
|
|
|
|
```text
|
|
client selects recording
|
|
→ API creates a caller-owned presigned upload intent transaction
|
|
→ client uploads directly to R2
|
|
→ client finalizes the intent through /uploads/register
|
|
→ client POST /jobs with durable recording key + idempotency key
|
|
→ API authenticates, authorizes, validates capability and policy
|
|
→ API atomically debits credits and creates job
|
|
→ API enqueues Celery pipeline
|
|
→ client polls GET /jobs/{id}
|
|
→ worker persists stages/progress/result key
|
|
→ API returns short-lived signed result_url
|
|
→ client previews or downloads
|
|
```
|
|
|
|
The client must retain its idempotency key until it knows whether creation was
|
|
accepted. Retrying transport with the same body reuses the same key.
|
|
|
|
### 7.2 Standalone B-roll and attachment
|
|
|
|
```text
|
|
client POST /generation/broll/generate with an idempotency key
|
|
→ API validates pilot access, prompt, optional owned image key, and credits
|
|
→ API creates generation job and enqueues `generation`
|
|
→ provider adapter calls ComfyUI Deploy or another approved backend
|
|
→ worker downloads/verifies output and stores it in R2
|
|
→ client polls canonical generation resource
|
|
→ API returns signed preview URL + durable broll_key
|
|
→ client attaches broll_key to a reel draft
|
|
→ normal POST /jobs persists the attachment
|
|
```
|
|
|
|
Clients must never attach a signed URL or an upstream provider run id.
|
|
They retain the B-roll create idempotency key across ambiguous transport retries
|
|
exactly as they do for reel creation.
|
|
|
|
### 7.3 Polling lifecycle
|
|
|
|
Every client implements the same state machine:
|
|
|
|
```text
|
|
idle → submitting → queued/running → completed
|
|
└─────────→ failed
|
|
```
|
|
|
|
Polling stops on completion, terminal failure, authentication loss, explicit
|
|
navigation cancellation, or app background policy. Resume re-fetches the server
|
|
resource before restarting a timer. Only the create request uses idempotency;
|
|
GET polling does not create work.
|
|
|
|
### 7.4 Preview lifecycle
|
|
|
|
R2 objects are private. A client receives a signed `result_url`, treats expiry as
|
|
normal, and refreshes the job/generation resource to obtain a new URL. The
|
|
durable key is not converted to a public bucket URL client-side.
|
|
|
|
## 8. Dependency rules
|
|
|
|
Allowed dependency direction:
|
|
|
|
```text
|
|
clients ──HTTP──▶ API domain routers/controllers ──▶ services ──▶ repositories/platform adapters
|
|
│
|
|
└──▶ worker command/orchestration
|
|
|
|
workers ──▶ services/provider interfaces ──▶ external services or apps/api/engine
|
|
SDKs ──HTTP──▶ API
|
|
external ──X──▶ product source imports
|
|
```
|
|
|
|
Forbidden:
|
|
|
|
- web/mobile/desktop importing code from another app;
|
|
- clients reading Postgres, Redis, R2 credentials, or provider secrets;
|
|
- API domain routers/controllers importing from `external/`;
|
|
- SDKs depending on app-private code;
|
|
- `editor-bff` owning product persistence;
|
|
- direct client calls to ComfyUI, comfyui-deploy, RunPod, HeyGen, ElevenLabs, or
|
|
social provider APIs;
|
|
- `apps/api/engine` exposing a second first-party product contract.
|
|
|
|
## 9. Observability contract
|
|
|
|
A correlation id is created or accepted at the API edge and propagated to:
|
|
|
|
- API request logs;
|
|
- idempotency and job records;
|
|
- Celery task headers/logs;
|
|
- provider calls and retries;
|
|
- R2 upload/download events;
|
|
- Sentry events;
|
|
- client error telemetry.
|
|
|
|
Secrets, full prompts when policy-sensitive, presigned URLs, OAuth tokens, and
|
|
API credentials must be redacted. Provider cost records attach to the job or
|
|
generation id and use the same correlation id.
|
|
|
|
## 10. Deployment topology
|
|
|
|
The current product compose topology remains valid:
|
|
|
|
- `api`;
|
|
- `worker` consuming `celery,render`;
|
|
- `beat` singleton;
|
|
- `api-generation-worker` consuming `generation` with GPU access;
|
|
- Redis;
|
|
- Postgres for local development, Neon in hosted environments;
|
|
- web.
|
|
|
|
Mobile and desktop are distributed artifacts, not long-running compose services.
|
|
Production R2 and external providers are managed services.
|
|
|
|
Scale independently:
|
|
|
|
- API replicas by request load;
|
|
- standard workers by queue latency;
|
|
- render workers by FFmpeg/avatar capacity;
|
|
- generation workers by GPU memory and provider concurrency;
|
|
- never scale beat beyond one active scheduler without leader election.
|
|
|
|
## 11. Evolution rules
|
|
|
|
1. API changes are additive inside `/api/v1` unless a deprecation plan is approved.
|
|
2. OpenAPI changes regenerate/validate the contract package before client merges.
|
|
3. Clients gate unavailable features from capability data, not hardcoded provider
|
|
assumptions.
|
|
4. A provider adapter returns domain results, never raw upstream response shapes.
|
|
5. External adoption requires the registry gate in `external/REGISTRY.md`.
|
|
6. Runtime documentation distinguishes **current** behavior from **target** behavior.
|
|
7. New desktop work targets Rust/GPUI only.
|
|
|
|
## 12. Migration sequence
|
|
|
|
### Stage A — Contract foundation
|
|
|
|
- **Implemented:** deterministic FastAPI OpenAPI export and
|
|
`packages/api-contract`.
|
|
- **Implemented:** stable error, job, B-roll, upload, editor-export, and
|
|
capability schemas.
|
|
- **Implemented:** additive/breaking compatibility checking.
|
|
|
|
### Stage B — Client convergence
|
|
|
|
- **Implemented for core generation flows:** web and mobile contract DTOs,
|
|
authenticated transports, lifecycle-aware polling, and feature boundaries.
|
|
- **Implemented:** reviewed Rust request/response mapping for upload, reel,
|
|
B-roll, capability, polling, and signed preview behavior.
|
|
- **Remaining incremental work:** migrate non-generation feature DTOs out of
|
|
compatibility `lib/types.ts` files as those domains are touched.
|
|
|
|
### Stage C — Backend boundary cleanup
|
|
|
|
- **Implemented:** `app/generation` is not mounted by public ASGI and is routed
|
|
only as a legacy/internal generation capability.
|
|
- **Implemented:** B-roll provider interface, external-import guard, workflow
|
|
manifest verification, and isolated generation-worker image.
|
|
- **Implemented foundation:** reels, B-roll, media, editor, core auth,
|
|
idempotency, capabilities, and platform storage boundaries.
|
|
- **Remaining incremental work:** extract unrelated compatibility controllers
|
|
only when those product domains are actively changed.
|
|
|
|
### Stage D — Editor convergence
|
|
|
|
- **Implemented:** active Next.js editor feature reads authenticated reel state,
|
|
submits an idempotent export command, polls, previews, and downloads results.
|
|
- Keep the BFF stateless and narrow; retire migration sources after remaining
|
|
editor parity is explicitly accepted.
|
|
|
|
### Stage E — External-provider evaluation
|
|
|
|
- Evaluate ComfyUI + Wan workflow deployment as the primary self-hosted B-roll
|
|
path.
|
|
- Benchmark Pixelle/engine and approved alternatives behind the same provider
|
|
contract.
|
|
- Do not merge training frameworks into the production API environment.
|
|
|
|
## 13. Acceptance criteria
|
|
|
|
The architecture is realized when:
|
|
|
|
- all three clients use the same versioned API contract semantics;
|
|
- web, mobile, and Rust desktop complete upload/create/poll/preview/attach;
|
|
- no first-party client calls an upstream media provider directly;
|
|
- the API and generation workers can deploy and scale independently;
|
|
- `external/` has no undeclared runtime imports;
|
|
- Electron legacy is absent from active build and architecture documentation;
|
|
- generated contract drift fails before release;
|
|
- ownership, credit, idempotency, and correlation behavior is uniform across clients.
|