# Video Sharing App - Architecture Plan **Note:** See `DECISION_LOG.md` for detailed rationale behind architectural decisions. ## Overview A self-hosted, small-group video sharing application built with Rust for correctness and type safety. **Target Users:** Small groups of friends (5-20 people) **Deployment:** Self-hosted on VPS/home server **Client:** Progressive Web App (PWA) **Video Type:** Short clips primarily, with adaptive streaming support **Product Vision:** Video-only communication - no text messaging in MVP. Pure, focused visual sharing. ## Core Design Principles 1. **Type Safety First**: Leverage Rust's type system to catch errors at compile time 2. **Minimal Runtime Failures**: Use compile-time SQL checking, strict validation 3. **Simple Deployment**: Single binary + database, easy to self-host 4. **Adaptive Quality**: Support high-quality on WiFi, optimized streaming on mobile data 5. **Real-Time by Default**: Users see new videos immediately via Server-Sent Events ## Technology Stack ### Backend - **Framework**: `axum` with `tower` middleware - **Database**: SQLite with `sqlx` for compile-time query verification - **Runtime**: `tokio` for async operations - **Video Processing**: `ffmpeg` for transcoding - **Real-Time**: Server-Sent Events (SSE) for push notifications ### Frontend - **Language**: TypeScript with modern ES modules - **Component Model**: Web Components (native browser standard) - **Dev Server & Bundler**: rsbuild (Rspack-based, fast builds with HMR) - **Tooling**: Deno (task runner, formatting, TypeScript) + Biome (linting) - **PWA Features**: Service Worker, MediaRecorder API, EventSource (SSE) ### Storage - **Database**: SQLite file (configurable path) - **Videos**: Filesystem with configurable storage directory - **Paths**: FHS-compliant defaults with XDG fallback ## System Architecture **Clients:** - Mobile PWA (TypeScript) - Desktop Web (TypeScript) **Rust Backend (axum):** - REST API handlers - SSE event broadcasting - Auth middleware - Video upload/chunking handler - HLS streaming handler - Background video processing **Data Layer:** - SQLite database (via sqlx) - Filesystem for video storage - ffmpeg for transcoding ## Key Components ### 1. Backend Server (Rust) **Framework**: `axum` with `tower` middleware **Port**: Configurable (default 8080) **REST API Endpoints:** ``` POST /api/auth/register POST /api/auth/login POST /api/auth/refresh GET /api/groups POST /api/groups GET /api/groups/:id POST /api/groups/:id/invite GET /api/groups/:id/videos POST /api/videos/upload (chunked multipart) GET /api/videos/:id DELETE /api/videos/:id GET /api/videos/:id/stream/* (HLS manifest and segments) GET /api/events (SSE endpoint) GET /admin (admin dashboard) ``` **Key Libraries:** - `axum` - Web framework - `tower` - Middleware - `sqlx` - Database with compile-time query checking - `tokio` - Async runtime - `serde` - Type-safe serialization - `jsonwebtoken` - JWT authentication - `validator` - Input validation (pragmatic use) - `tracing` - Structured logging ### 2. Database (SQLite) **Default Paths:** - System service: `/var/lib/parco-molo/data.db` - User mode: `~/.local/share/parco-molo/data.db` - Override via: `DATABASE_PATH` environment variable **Schema:** - Users and authentication - Groups and memberships - Video metadata - Invite tokens - Metrics and observability data **Benefits:** - Single file, zero config - Perfect for small scale (5-20 users) - Simple backups (copy file) - Can migrate to PostgreSQL if needed (sqlx supports both) ### 3. Video Storage **Default Paths:** - System service: `/var/lib/parco-molo/storage/` - User mode: `~/.local/share/parco-molo/storage/` - Override via: `STORAGE_PATH` environment variable **Directory Structure:** - `$STORAGE_PATH/originals/{video_id}/original.mp4` - Original uploaded videos - `$STORAGE_PATH/variants/{video_id}/high/` - High quality HLS segments - `$STORAGE_PATH/variants/{video_id}/medium/` - Medium quality HLS segments - `$STORAGE_PATH/variants/{video_id}/low/` - Low quality HLS segments - `$STORAGE_PATH/thumbs/{video_id}.jpg` - Video thumbnails ### 4. Video Processing Pipeline ``` Upload → Chunked Reception → Validation → Transcode → Store → SSE Notify ``` **Chunked Upload:** - 5MB chunks (industry standard, AWS S3-compatible) - Resumable on failure - Progress tracking **Transcoding (ffmpeg):** - Generate 3 quality variants with HLS manifests - Preserve arbitrary aspect ratios (vertical, horizontal, square) - Dimension-based quality tiers: - High: 5 Mbps, max 1920px dimension - Medium: 2.5 Mbps, max 1280px dimension - Low: 1 Mbps, max 854px dimension - Generate thumbnail at 3-second mark ### 5. Real-Time Updates (SSE) **Endpoint:** `GET /api/events` **Event Types:** ```rust enum Event { NewVideo { group_id: Uuid, video_id: Uuid, uploader: String }, VideoProcessingComplete { video_id: Uuid }, VideoProcessingFailed { video_id: Uuid, error: String }, } ``` **Client Usage:** ```typescript const eventSource = new EventSource('/api/events'); eventSource.onmessage = (event) => { const data = JSON.parse(event.data); handleRealtimeEvent(data); }; ``` ### 6. PWA Client (TypeScript + Web Components) **Project Structure:** - `client/src/main.ts` - Entry point - `client/src/api.ts` - Type-safe API client - `client/src/events.ts` - SSE event handling - `client/src/types.ts` - Shared TypeScript interfaces - `client/src/components/video-upload.ts` - Web Component for upload - `client/src/components/video-player.ts` - Web Component for HLS player - `client/src/components/video-grid.ts` - Web Component for video list - `client/src/components/video-card.ts` - Web Component for video thumbnail - `client/public/sw.js` - Service Worker - `client/index.html` - Main HTML entry - `rsbuild.config.ts` - rsbuild configuration (root level) - `deno.json` - Deno tasks and configuration (root level) - `biome.json` - Biome linting/formatting config (root level) **Web Component Example:** ```typescript class VideoPlayer extends HTMLElement { connectedCallback() { const videoId = this.getAttribute('video-id'); this.innerHTML = ``; this.initHLS(videoId); } private initHLS(videoId: string) { // HLS.js initialization } } customElements.define('video-player', VideoPlayer); ``` **Modern APIs Used:** - ES modules for imports - Web Components (Custom Elements API) for component abstraction - Fetch API for HTTP - EventSource for SSE - MediaRecorder for video capture - Service Worker for PWA features - IntersectionObserver for lazy loading - Web Crypto API for secure tokens **Tooling:** - **rsbuild**: Rspack-based bundler for fast builds and modern defaults - **Deno**: Task runner, TypeScript execution, and formatting - **Biome**: Unified linting and formatting (replaces ESLint + Prettier) **Features:** - Offline capability via Service Worker - Camera recording interface (MediaRecorder) - Chunked upload with progress and retry - HLS video playback with quality switching - Real-time notifications via SSE - Component-based architecture using native Web Components ## Data Models ### User ```rust struct User { id: Uuid, email: String, password_hash: String, display_name: String, created_at: DateTime, } ``` ### Group ```rust struct Group { id: Uuid, name: String, created_by: Uuid, created_at: DateTime, } ``` ### GroupInvite ```rust struct GroupInvite { id: Uuid, group_id: Uuid, token: String, // Cryptographically random created_by: Uuid, created_at: DateTime, expires_at: Option>, // None = never expires max_uses: Option, // None = unlimited, Some(1) = single-use use_count: u32, } ``` **Invite Flow:** 1. Admin creates invite with chosen expiry/uses 2. Share link: `https://your-domain.com/join/{token}` 3. Recipient clicks → register/login → join group 4. No email infrastructure required ### Video ```rust struct Video { id: Uuid, uploader_id: Uuid, group_id: Uuid, title: Option, description: Option, duration_secs: f32, upload_date: DateTime, original_path: String, thumbnail_path: String, } struct VideoVariant { video_id: Uuid, quality: Quality, // High, Medium, Low max_dimension: u32, // 1920, 1280, 854 path: String, bitrate_kbps: u32, } ``` ### GroupMembership ```rust struct GroupMembership { user_id: Uuid, group_id: Uuid, role: MemberRole, // Admin, Member joined_at: DateTime, } ``` ## Security Model ### Authentication - JWT tokens (access + refresh) - Access token: 15 min expiry - Refresh token: 7 day expiry - Secure, HTTP-only cookies for web client ### Authorization - Videos accessible only to group members - Upload requires group membership - Group admins can remove videos - Invite links with configurable expiry and usage limits ### Video Access ```rust fn can_view_video(user: &User, video: &Video) -> Result { // Compile-time verified SQL query check_group_membership(user.id, video.group_id) } ``` ## Video Streaming Strategy ### Adaptive Bitrate Streaming (HLS) **Arbitrary Aspect Ratios Supported:** - Vertical videos (1080x1920) from phones - Horizontal videos (1920x1080) from cameras - Square videos (1080x1080) - Any aspect ratio preserved naturally **ffmpeg Scaling:** ```bash # Preserves aspect ratio, fits within max dimension ffmpeg -i input.mp4 \ -vf "scale='min(1920,iw)':'min(1080,ih)':force_original_aspect_ratio=decrease" \ ... ``` **On Upload:** 1. Validate video format 2. Generate 3 quality variants (High/Medium/Low) 3. Create HLS manifest (.m3u8) for each variant 4. Generate thumbnail at 3-second mark 5. Broadcast SSE event to group members **On Playback:** - Client requests manifest - HLS.js handles quality switching based on bandwidth - Progressive download (not full buffering) - Works on all devices ### Chunked Upload - Client splits video into 5MB chunks - Each chunk uploaded separately with retry logic - Server assembles chunks before processing - Allows resumable uploads on connection failure - Progress tracking for user feedback ## Deployment Architecture ### Environment Configuration ```bash # Database (defaults to FHS-compliant paths) DATABASE_PATH=/var/lib/parco-molo/data.db # or ~/.local/share/parco-molo/data.db # Storage (defaults to FHS-compliant paths) STORAGE_PATH=/var/lib/parco-molo/storage # or ~/.local/share/parco-molo/storage # Security JWT_SECRET= # Network BIND_ADDRESS=127.0.0.1:8080 PUBLIC_URL=https://videos.yourdomain.com ``` **Path Behavior:** - Running as system service → `/var/lib/parco-molo/` - Running as user → `~/.local/share/parco-molo/` - Always respect environment variable overrides **Deployment Notes:** - Single binary, no external dependencies except ffmpeg - TLS termination handled by reverse proxy (nginx, caddy, etc.) - Good error messages guide configuration - Works out-of-box for both systemd service and user mode ## Type Safety Benefits ### Compile-Time SQL Checking (sqlx) ```rust // sqlx verifies this query against actual database at compile time let videos = sqlx::query_as!( Video, "SELECT * FROM videos WHERE group_id = $1 ORDER BY upload_date DESC", group_id ) .fetch_all(&pool) .await?; ``` **Benefits:** - SQL errors caught at compile time - Type mismatches impossible - Refactoring changes caught immediately ### Type-Safe Validation **Pragmatic approach:** Use newtype pattern for critical domain types, validation macros for simple constraints. ```rust // Critical domain types struct VideoId(Uuid); struct GroupId(Uuid); struct Email(String); // Validated on construction // Simple constraints #[derive(Deserialize, Validate)] struct UploadRequest { group_id: Uuid, #[validate(length(max = 200))] title: Option, } ``` ### Impossible States Prevention ```rust enum UploadStatus { Uploading { chunks_received: usize, total_chunks: usize }, Processing, Complete { video: Video }, Failed { error: String }, } // Type system ensures only one state at a time ``` ## Performance Characteristics ### Expected Load (20 users, 10 videos/day) - API requests: ~100/hour (low) - Video uploads: ~10/day = 1-5 GB/day storage - Concurrent streams: 1-5 typical - Database size: <1GB/year - SSE connections: 1-20 concurrent ### Resource Requirements - **CPU**: 2 cores (for transcoding) - **RAM**: 2-4 GB - **Storage**: 100GB initially (grows with videos) - **Bandwidth**: 10Mbps upload (for streaming) ## Monitoring and Observability ### Built-In Admin Dashboard **Self-contained metrics stored in SQLite:** - Total videos / uploads today / uploads this week - Storage usage (GB used) - Upload success vs failure counts - Recent failed uploads with errors - User count / active users (last 30 days) - Failed authentication attempts **Access:** Protected admin route at `/admin` **Metrics Collection:** ```rust use tracing::{info, warn, error, instrument}; #[instrument] async fn handle_upload(upload: Upload) -> Result