# Architecture Decision Log This document records key architectural decisions made during the development of this project. ## Format Each decision includes: - **Date**: When the decision was made - **Decision**: What was decided - **Context**: Why we needed to make this decision - **Options Considered**: Alternatives we evaluated - **Rationale**: Why we chose this option - **Consequences**: Trade-offs and implications --- ## 2025-10-21: Database Choice - SQLite **Decision**: Use SQLite as the primary database for MVP **Context**: Need to choose a database solution that balances simplicity, type safety, and operational overhead for a small-scale self-hosted video sharing app (5-20 users). **Options Considered**: 1. **SQLite** - Embedded, single-file database 2. **PostgreSQL** - Full-featured client-server database 3. **RocksDB** - Embedded key-value store **Rationale**: - **Relational model is essential**: We need to model complex relationships (users, groups, memberships, videos, permissions). RocksDB's key-value nature would require building a query layer from scratch, defeating the purpose of type safety. - **Load is minimal**: Expected load is ~100 requests/hour, <5 concurrent streams, 10 video uploads/day. SQLite's write concurrency limitations are not a concern. - **Deployment simplicity**: Single-file database with no separate server process. Perfect for self-hosting scenario. - **Migration path exists**: Using `sqlx` provides compatibility with both SQLite and PostgreSQL, allowing easy migration if scale increases. - **Type safety maintained**: `sqlx` provides compile-time query verification for both databases. **Consequences**: - ✅ Simplest possible deployment (single binary + single DB file) - ✅ Zero database configuration required - ✅ Excellent for self-hosting use case - ⚠️ If concurrent writes become an issue (unlikely), migration to PostgreSQL is straightforward - ⚠️ Database backups = copy single file (actually a benefit) **Status**: Decided - will implement with SQLite --- ## 2025-10-21: Backend Framework - axum + Separate PWA **Decision**: Use axum for the backend API with a separate PWA frontend (not Leptos full-stack) **Context**: Need to choose between Leptos (full-stack Rust framework) or axum (backend-only) + separate PWA frontend for building the video sharing application. **Options Considered**: 1. **Leptos** - Full-stack framework with shared frontend/backend code in Rust 2. **axum + separate PWA** - Traditional backend API with JavaScript PWA client **Rationale**: - **Video-specific requirements**: This app has non-traditional web app needs (chunked video uploads with retry, HLS streaming, large file handling) that require fine-grained HTTP control - **PWA features require JavaScript anyway**: Service Workers, MediaRecorder API, and chunked upload with retry logic need custom JavaScript regardless of framework choice - **Leptos optimized for different use case**: Leptos excels at reactive UIs and forms (CRUD apps), not video streaming/upload operations - **Battle-tested streaming**: axum's streaming primitives (built on tower/hyper) are mature and widely used for exactly this use case - **Simpler mental model**: Clear separation - Rust handles all business logic, JavaScript handles browser APIs - **Type safety where it matters**: Backend business logic in Rust catches errors at compile time **Consequences**: - ✅ Explicit control over all HTTP endpoints and streaming behavior - ✅ Easy to implement chunked uploads and HLS streaming - ✅ Mature ecosystem with extensive documentation - ✅ Can optimize frontend bundle separately from backend - ❌ Need to manually define API contracts (will document these clearly) - ❌ Type safety doesn't extend to frontend (acceptable trade-off for this use case) - 📋 **Action Required**: Need to make decisions about JavaScript approach (vanilla JS vs framework, bundler, etc.) **Status**: Decided - will implement with axum + separate PWA --- ## 2025-10-21: Data Layer - sqlx **Decision**: Use sqlx for database interactions with SQLite **Context**: Need to choose how to interact with the SQLite database - either raw SQL with compile-time checking (sqlx) or a full ORM (diesel_async). **Options Considered**: 1. **sqlx** - Type-checked SQL queries with compile-time verification 2. **diesel_async** - Full-featured ORM with query builder **Rationale**: - **Compile-time safety**: sqlx verifies SQL queries against the actual database schema at compile time - **Explicit over implicit**: See exactly what SQL is running, easier to debug and optimize - **SQLite first-class**: sqlx treats SQLite as a primary target, not an afterthought - **Simple mental model**: No ORM abstractions to learn, just SQL and Rust types - **Aligns with philosophy**: Fits "parse don't validate" - queries are validated at compile time - **Good enough for use case**: Simple queries (get videos, check memberships) don't benefit much from query builder - **Migration path maintained**: sqlx supports PostgreSQL if we need to migrate later **Consequences**: - ✅ Compile-time SQL verification catches errors early - ✅ Explicit SQL is easier to understand and optimize - ✅ Simpler to learn and debug - ✅ Faster compile times than diesel - ⚠️ Requires database connection at compile time for query checking - ⚠️ Write SQL manually (but provides clarity) - 🔄 **Swap-out option**: If this doesn't feel right during implementation, can switch to diesel_async **Status**: Decided - will implement with sqlx, open to revisiting based on implementation experience --- ## 2025-10-21: Video Aspect Ratio Support **Decision**: Support arbitrary aspect ratios (vertical, horizontal, square, etc.) from the start **Context**: Need to determine if the video transcoding and streaming system should support only specific aspect ratios (e.g., 16:9) or arbitrary aspect ratios from user uploads. **Options Considered**: 1. **Fixed aspect ratios** - Force all videos to 16:9 or specific ratios 2. **Arbitrary aspect ratios** - Support any aspect ratio users upload **Rationale**: - **Modern usage patterns**: Users expect vertical video support (phones record in portrait mode) - **HLS handles this naturally**: HTTP Live Streaming preserves original aspect ratio automatically - **Actually simpler**: Using aspect-ratio-aware ffmpeg scaling is easier than forcing specific dimensions - **Better user experience**: No black bars or cropping needed - **Client rendering is easy**: CSS `object-fit: contain` handles display naturally **Implementation approach**: - Use dimension-based quality tiers instead of resolution names: - High: 5 Mbps, max dimension 1920px (either width or height) - Medium: 2.5 Mbps, max dimension 1280px - Low: 1 Mbps, max dimension 854px - ffmpeg scaling preserves aspect ratio: `scale='min(1920,iw)':'min(1080,ih)':force_original_aspect_ratio=decrease` - Thumbnails generated at original aspect ratio with max dimension constraint - Examples: - Vertical 1080x1920 → stays 1080x1920 - Horizontal 1920x1080 → stays 1920x1080 - Square 1080x1080 → stays 1080x1080 **Consequences**: - ✅ Natural support for phone-recorded videos (vertical) - ✅ No cropping or letterboxing needed - ✅ Simpler implementation than forcing aspect ratios - ✅ Better user experience - ✅ Standard CSS handles display across all aspect ratios **Status**: Decided - will implement with arbitrary aspect ratio support --- ## 2025-10-21: Upload Chunk Size **Decision**: Use 5MB chunks for chunked video uploads **Context**: Need to determine the optimal chunk size for resumable video uploads. Chunks must balance reliability (smaller = more resilient), efficiency (larger = less HTTP overhead), and user experience (reasonable retry times on failure). **Options Considered**: 1. **Small chunks (< 1MB)** - Maximum resilience to connection issues 2. **Medium chunks (2-8MB)** - Balance between resilience and efficiency 3. **Large chunks (> 20MB)** - Minimize HTTP overhead **Rationale**: - **Industry alignment**: AWS S3 uses 5MB minimum for multipart uploads, well-tested in production - **Reasonable retry time**: 5MB @ 1 MB/s (typical 4G) = ~5 seconds, not frustrating to retry - **Manageable request count**: 50MB video = 10 chunks, 200MB video = 40 chunks (both reasonable) - **Low memory footprint**: ~5MB client-side buffer is acceptable for mobile devices - **Avoids extremes**: Not so small that HTTP overhead dominates, not so large that retries are painful **Upload time examples**: - 4G (1 MB/s): 5 seconds per chunk - 5G (5 MB/s): 1 second per chunk - Poor connection (500 KB/s): 10 seconds per chunk **Consequences**: - ✅ Proven size used by major platforms (S3, Dropbox uses 4MB) - ✅ Good balance for mobile connections - ✅ Reasonable memory usage - ✅ Acceptable retry cost on connection failure - 🔧 **Future enhancement**: Could make configurable or adaptive based on connection quality detection **Status**: Decided - will implement with 5MB chunks, keep as configurable constant for future tuning --- ## 2025-10-21: Linux Filesystem Paths **Decision**: Use FHS-compliant defaults with XDG fallback and environment variable overrides **Context**: Need to determine appropriate default paths for DATABASE_PATH (SQLite file) and STORAGE_PATH (video files) that work well with systemd services and user-mode installations. **Options Considered**: 1. **Hard-coded paths** - Fixed locations like /var/lib/parco-molo 2. **Only environment variables** - Require user to always specify paths 3. **Smart defaults with overrides** - Follow standards, allow customization **Rationale**: - **FHS compliance**: `/var/lib//` is the standard location for service state data in Linux - **Systemd compatibility**: Systemd services expect data in `/var/lib/` - **User-mode support**: XDG Base Directory spec supports running as regular user - **Flexibility**: Environment variables allow custom paths (e.g., separate storage volume) - **Good UX**: Works out-of-box for both system service and user deployments **Implementation approach**: System service mode (running as root/system user): - DATABASE_PATH: `/var/lib/parco-molo/data.db` - STORAGE_PATH: `/var/lib/parco-molo/storage/` User mode (running as regular user): - DATABASE_PATH: `$XDG_DATA_HOME/parco-molo/data.db` (defaults to `~/.local/share/parco-molo/data.db`) - STORAGE_PATH: `$XDG_DATA_HOME/parco-molo/storage/` Environment variable overrides (always respected): ```bash DATABASE_PATH=/custom/path/db.sqlite STORAGE_PATH=/mnt/big-disk/videos ``` Clear error messages with hints when paths don't exist. **Consequences**: - ✅ Follows Linux Filesystem Hierarchy Standard - ✅ Works with systemd out of the box - ✅ Supports user-mode development/testing - ✅ Allows custom paths for advanced deployments - ✅ Provides helpful error messages - 📝 Documentation should explain both modes **Status**: Decided - will implement smart defaults with environment variable overrides --- ## 2025-10-21: Validation Strategy - Pragmatic Parse-Don't-Validate **Decision**: Use validation macros for MVP, apply parse-don't-validate pattern selectively for critical domain types **Context**: Need to determine validation approach for user inputs. The "parse, don't validate" philosophy suggests creating types that are impossible to construct in invalid states, rather than validating and keeping data as primitive types. **Options Considered**: 1. **Full parse-don't-validate** - Newtype wrappers for all validated fields 2. **Validation macros** - Use `#[validate]` attributes for all validation 3. **Hybrid approach** - Parse-don't-validate for critical types, validation macros for simple cases **Rationale**: - **"Parse, don't validate" philosophy**: After parsing into a domain type, the type system guarantees validity - Example: `VideoTitle(String)` that can only be constructed with valid length - Impossible to accidentally use invalid data - **Pragmatism for MVP**: Not every String field needs a newtype wrapper - **Balance**: Use newtype pattern for critical domain concepts, validation macros for simple constraints - **Upgrade path**: Can refactor to stronger types as patterns emerge **Implementation approach**: Critical domain types (use newtype pattern): ```rust struct Email(String); // Must be valid email format struct VideoId(Uuid); // Semantic meaning struct GroupId(Uuid); ``` Simple validation (use macros for MVP): ```rust #[derive(Deserialize, Validate)] struct UploadRequest { #[validate(length(max = 200))] title: Option, // Simple length check } ``` **Consequences**: - ✅ Pragmatic balance between type safety and development speed - ✅ Strong types for critical domain concepts - ✅ Simple validation for basic constraints - ✅ Can refactor toward more parse-don't-validate as we learn domain better - 🔄 **Future enhancement**: Add more newtype wrappers as validation complexity increases **Status**: Decided - will use hybrid approach, can strengthen types over time --- ## 2025-10-21: Metrics and Observability Strategy **Decision**: Build self-contained admin dashboard with metrics stored in SQLite, Prometheus/Grafana support as future enhancement **Context**: Need to provide visibility into system health and usage for self-hosted deployments. Options include exposing Prometheus metrics for Grafana or building an integrated admin dashboard. **Options Considered**: 1. **Prometheus/Grafana endpoint** - Expose `/metrics` endpoint for external monitoring 2. **Self-contained admin dashboard** - Build simple web UI with metrics in database 3. **Both** - Admin dashboard for MVP, Prometheus endpoint later **Rationale**: - **Self-hosted target audience**: Users deploying for 5-20 friends shouldn't need Grafana/Prometheus infrastructure - **Simplicity**: Single binary with built-in monitoring is much easier to deploy - **Database storage**: Metrics stored in SQLite persist with the application - **Good enough**: Basic dashboard showing upload success/failure, storage usage, active users is sufficient for small deployments - **Future enhancement**: Advanced users with existing Grafana can add Prometheus endpoint later **Implementation approach**: Admin dashboard (MVP): - Simple read-only web UI (protected by admin auth) - Basic metrics: - Total videos / uploads today / uploads this week - Storage usage (total GB used) - Upload success vs failure counts - Recent failed uploads with errors - User count / active users (uploaded in last 30 days) - Failed authentication attempts - Store metrics in SQLite tables - Background task periodically calculates aggregates Future enhancement (Post-MVP): - `/metrics` endpoint in Prometheus format - Allows advanced users to integrate with existing Grafana - Optional feature, not required for basic operation **Consequences**: - ✅ Self-contained deployment (no external dependencies) - ✅ Perfect for target audience (small groups, self-hosted) - ✅ Metrics persist in database - ✅ Simple built-in observability - ⚠️ Need to build basic admin UI - 🔧 **Future enhancement**: Prometheus endpoint for advanced users with Grafana **Status**: Decided - will implement self-contained admin dashboard, defer Grafana integration to post-MVP --- ## 2025-10-21: Group Invite Mechanism **Decision**: Use shareable invite links with configurable expiry and usage limits for MVP, defer email invites to post-MVP **Context**: Need to determine how group admins invite friends to join their groups. Options include shareable links, email invites, or in-app-only invites. **Options Considered**: 1. **Shareable invite links** - Generate token-based URL that can be shared via any channel 2. **Email invites** - System sends invitation emails to specified addresses 3. **In-app only** - Users must be registered before they can be invited **Rationale**: - **Zero infrastructure**: No email server (SMTP) configuration required for self-hosted users - **Flexibility**: Users share links via their preferred channels (text, Signal, WhatsApp, email, etc.) - **Simple UX**: Copy link, paste to friend - no email deliverability issues - **Self-hosted friendly**: One less service to configure and maintain - **Configurable security**: Single-use vs reusable, with optional expiry **Implementation approach**: Data model: ```rust struct GroupInvite { id: Uuid, group_id: Uuid, token: String, // Cryptographically random token 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 creation flow: 1. Group admin clicks "Create Invite Link" 2. Configure: Single-use / Multi-use / Unlimited 3. Optional expiry: 7 days / 30 days / Never 4. System generates: `https://your-domain.com/join/abc123xyz` 5. Copy to clipboard, share via any channel Invite redemption: 1. Recipient clicks link 2. If not logged in: Redirect to register/login, preserve invite token 3. After auth: Join group automatically 4. Increment use_count, check against max_uses **Consequences**: - ✅ No email infrastructure needed - ✅ Users share via their preferred channels - ✅ Simple for self-hosted deployments - ✅ Flexible security options (single-use, expiry) - ✅ Works for new users (register then join) - 🔧 **Future enhancement**: Email invites for users who want tighter control **Status**: Decided - will implement shareable links, defer email functionality to post-MVP --- ## 2025-10-21: Real-Time Updates Architecture **Decision**: Use REST API + Server-Sent Events (SSE) for real-time notifications and updates **Context**: Users expect real-time updates when new videos are posted or events occur in their groups. Need to determine the best approach for real-time communication that integrates well with video upload/streaming operations. **Options Considered**: 1. **REST + Server-Sent Events (SSE)** - Traditional REST API with SSE for server-to-client push 2. **GraphQL + Subscriptions** - GraphQL for all operations with WebSocket-based subscriptions 3. **REST + WebSockets** - Traditional REST API with bidirectional WebSocket connections **Rationale**: - **Video operations don't fit GraphQL**: Chunked multipart uploads and HLS streaming require specialized HTTP endpoints regardless of API paradigm - **SSE is simpler**: One-way server-to-client push is sufficient for notifications (new video, new comment, etc.) - **Built on HTTP**: SSE works over regular HTTP, automatic reconnection, simpler to debug - **axum has excellent SSE support**: Native `Sse` extractor, battle-tested - **PWA compatible**: EventSource API is standard in all browsers - **No learning curve**: REST is familiar, SSE is straightforward **Implementation approach**: REST API endpoints (unchanged from original plan): ``` POST /api/auth/login POST /api/auth/register POST /api/videos/upload (chunked multipart) GET /api/videos/:id/stream (HLS manifest and segments) GET /api/groups/:id/videos POST /api/comments ``` New SSE endpoint: ``` GET /api/events (Server-Sent Events stream) ``` Event types pushed to clients: ```rust enum Event { NewVideo { group_id: Uuid, video_id: Uuid, uploader: String }, NewComment { video_id: Uuid, comment_id: Uuid, author: String }, VideoProcessingComplete { video_id: Uuid }, VideoProcessingFailed { video_id: Uuid, error: String }, } ``` Client implementation (JavaScript): ```javascript const eventSource = new EventSource('/api/events'); eventSource.onmessage = (event) => { const data = JSON.parse(event.data); handleRealtimeEvent(data); }; ``` **Consequences**: - ✅ Real-time updates for all users with minimal complexity - ✅ Works perfectly with existing REST + axum architecture - ✅ Simple to implement and debug - ✅ Automatic reconnection handled by browser - ✅ Low overhead (keeps connection open, pushes when needed) - ✅ No impact on video upload/streaming implementation - 🔄 **Future enhancement**: Add WebSockets if bidirectional chat is needed (can coexist with SSE) **Impact on previous decisions**: None - all previous architectural decisions remain valid. This is an additive feature. **Status**: Decided - will implement REST + SSE, open to adding WebSockets later if needed for chat --- ## 2025-10-21: Messaging/Comments Feature Scope **Decision**: Defer all messaging features (video comments and group chat) to post-MVP, prioritize video comments as first post-MVP feature **Context**: Need to determine if messaging features (video comments, group chat) should be included in MVP or deferred. With SSE infrastructure decided, real-time comments would be straightforward to implement. **Options Considered**: 1. **MVP: Video comments + group chat** - Full messaging features 2. **MVP: Video comments only** - Comments on videos with real-time updates 3. **Post-MVP: All messaging** - Focus MVP purely on video sharing **Rationale**: - **Tight MVP scope**: Core value is video sharing with real-time notifications of new uploads - **SSE infrastructure is ready**: When we add comments later, real-time updates will work immediately - **Clear priority**: Video comments are natural first post-MVP feature (more valuable than general chat) - **Avoid competing with messaging apps**: Users already have WhatsApp/Signal for general chat - **Natural progression**: Get video sharing solid first, then add discussion layer **MVP scope (messaging features)**: - ❌ Video comments - ❌ Group chat - ❌ Reactions/emoji - ✅ Real-time notifications of new video uploads (via SSE) **Post-MVP priority order**: 1. **Video comments** (first post-MVP feature) - Comments on specific videos - Real-time via SSE (infrastructure already in place) - Simple data model and REST endpoints 2. **Emoji reactions** on videos (optional, simpler than comments) 3. **General group chat** (if users request it, would use WebSockets) 4. **@mentions** in comments 5. **Comment threads/replies** **Consequences**: - ✅ Cleaner MVP scope focused on core video sharing - ✅ SSE infrastructure ready for when comments are added - ✅ Clear roadmap for post-MVP enhancements - ✅ Can validate core video sharing works well before adding discussion layer - 📋 Video comments will be straightforward to add once MVP is stable **Status**: Decided - defer to post-MVP, make video comments first priority after MVP --- ## 2025-10-21: Frontend JavaScript/PWA Approach **Decision**: Use TypeScript + modern vanilla JavaScript with ES modules, Web Components for component abstraction, rsbuild for bundling, Deno for task running, and Biome for linting/formatting **Context**: With axum backend decided, need to determine frontend approach for the PWA. Options range from vanilla JavaScript to full frameworks like React/Vue. **Options Considered**: 1. **TypeScript + vanilla JS + Web Components** - Modern vanilla approach with native component abstraction 2. **Lightweight framework** (Preact, Alpine.js) - Minimal framework abstraction 3. **Modern framework** (React, Vue, Svelte) - Full framework with ecosystem **Rationale**: - **Type safety throughout**: TypeScript on frontend matches Rust's type safety philosophy on backend - **Simple UI needs**: Video grid, player, upload, forms - no complex state management needed - **Modern browser APIs**: ES modules, MediaRecorder, EventSource (SSE), Service Workers all built-in - **Web Components for structure**: Native browser component abstraction without framework overhead - **Fast and lightweight**: Tiny bundle size, fast initial load critical for mobile - **rsbuild for modern DX**: Rspack-based build tool, faster than Webpack, simpler config than Vite - **Deno for task running**: Run rsbuild via Deno tasks, handle formatting with Deno's built-in formatter - **Biome for tooling**: All-in-one linter and formatter (faster than ESLint + Prettier) - **Straightforward debugging**: No framework magic to understand, just TypeScript → JavaScript **Implementation approach**: 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 types - `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); ``` TypeScript types mirror Rust types: ```typescript interface Video { id: string; // Uuid uploader_id: string; group_id: string; title?: string; duration_secs: number; upload_date: string; thumbnail_path: string; } ``` Modern APIs used: - ES modules for imports - Web Components for component abstraction - Fetch API for HTTP requests - 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, faster builds, better defaults than Webpack - **Deno**: Task runner (`deno task dev`, `deno task build`), TypeScript execution, and formatting - **Biome**: Single tool for linting (replaces ESLint + Prettier for linting) **Consequences**: - ✅ Type safety from backend to frontend (Rust → TypeScript) - ✅ Minimal bundle size and fast loading - ✅ Web Components provide native component abstraction - ✅ Modern browser APIs work great - ✅ rsbuild provides fast builds with great DX - ✅ Deno provides unified task running and formatting - ✅ Biome provides unified, fast tooling - ✅ Easy to understand and debug (no framework magic) - ✅ No framework dependencies or runtime overhead **Status**: Decided - will use TypeScript + Web Components + rsbuild + Deno + Biome