# EasyStream Architecture

This document provides a comprehensive overview of EasyStream's architecture, design patterns, and system components.

## System Overview

EasyStream is a high-performance video streaming platform built with PHP, featuring:
- Multi-format media support (video, audio, images, documents)
- Live streaming with RTMP/HLS
- Containerized deployment with Docker
- Comprehensive security framework
- Background job processing
- Admin dashboard and user management

## Architecture Patterns

### MVC-Like Structure
- **Models**: `f_core/f_classes/` - Core business logic classes
- **Views**: `f_templates/` - Smarty template files
- **Controllers**: `f_modules/` - Feature modules handling requests

### Service Layer Pattern
Core services are implemented as singleton classes:
- `VDatabase` - Database abstraction layer
- `VSecurity` - Security and validation services
- `VLogger` - Centralized logging
- `VAuth` - Authentication and authorization
- `VRBAC` - Role-based access control

## Core Components

### 1. Application Bootstrap (`f_core/config.core.php`)
```php
// Initialization sequence:
1. Environment configuration
2. Database connection
3. Session management
4. Security initialization
5. Logging setup
6. Template engine configuration
```

### 2. Database Layer (`f_core/f_classes/class.database.php`)
- Built on ADOdb for database abstraction
- Prepared statement support
- Connection pooling
- Query validation and sanitization
- Transaction management

### 3. Security Framework (`f_core/f_classes/class.security.php`)
- Input validation and sanitization
- CSRF protection
- Rate limiting
- XSS prevention
- SQL injection protection
- File upload validation

### 4. Authentication System (`f_core/f_classes/class.auth.php`)
- Multi-factor authentication support
- Session management
- Password hashing (bcrypt/Argon2)
- Login attempt tracking
- Account lockout mechanisms

### 5. Authorization (RBAC) (`f_core/f_classes/class.rbac.php`)
- Role-based permissions
- Resource-level access control
- Dynamic permission checking
- Hierarchical role inheritance

## Data Flow Architecture

### Request Processing Flow
```
1. index.php (Entry Point)
   ↓
2. Router (URL parsing)
   ↓
3. Module Selection (f_modules/)
   ↓
4. Authentication Check
   ↓
5. Authorization Validation
   ↓
6. Business Logic Execution
   ↓
7. Template Rendering
   ↓
8. Response Output
```

### Background Job Processing
```
1. Job Creation (f_jobs/)
   ↓
2. Queue Management (class.queuemanager.php)
   ↓
3. Worker Processing (f_core/f_workers/)
   ↓
4. Job Execution
   ↓
5. Result Logging
```

## Live Streaming Architecture

### RTMP/HLS Pipeline
```
1. RTMP Input (SRS Server)
   ↓
2. Stream Processing
   ↓
3. HLS Segmentation
   ↓
4. CDN Distribution (Caddy)
   ↓
5. Client Playback
```

### Components
- **SRS (Simple Realtime Server)**: RTMP ingestion and HLS output
- **Caddy**: HTTP/2 web server with automatic HTTPS
- **FFmpeg**: Video processing and transcoding
- **HLS.js**: Client-side video player

## Database Schema

### Core Tables
- `users` - User accounts and profiles
- `videos` - Video metadata and processing status
- `streams` - Live stream configurations
- `categories` - Content categorization
- `comments` - User interactions
- `notifications` - System notifications

### Security Tables
- `user_sessions` - Active user sessions
- `login_attempts` - Failed login tracking
- `ip_bans` - IP-based access control
- `fingerprints` - Browser fingerprinting data

### System Tables
- `configurations` - Application settings
- `logs` - System and security logs
- `jobs` - Background job queue
- `permissions` - RBAC permissions

## Security Architecture

### Defense in Depth
1. **Input Layer**: Validation and sanitization
2. **Application Layer**: CSRF, rate limiting, authentication
3. **Database Layer**: Prepared statements, access control
4. **Network Layer**: HTTPS, firewall rules
5. **Infrastructure Layer**: Container isolation, secrets management

### Security Components
- **IP Tracking**: Monitor and block suspicious IPs
- **Fingerprinting**: Browser-based user identification
- **Rate Limiting**: Prevent abuse and DoS attacks
- **Audit Logging**: Comprehensive security event logging

## Caching Strategy

### Multi-Level Caching
1. **Application Cache**: In-memory object caching
2. **Database Cache**: Query result caching (ADOdb)
3. **Template Cache**: Compiled template caching (Smarty)
4. **Static Asset Cache**: CDN and browser caching

### Cache Invalidation
- Time-based expiration
- Event-driven invalidation
- Manual cache clearing via admin panel

## Monitoring and Observability

### Logging Framework
- **Structured Logging**: JSON-formatted log entries
- **Log Levels**: Emergency, Alert, Critical, Error, Warning, Notice, Info, Debug
- **Context Enrichment**: Request ID, user ID, IP address
- **Log Rotation**: Automatic cleanup and archival

### Metrics Collection
- Application performance metrics
- Security event tracking
- User behavior analytics
- System resource monitoring

## Scalability Considerations

### Horizontal Scaling
- Stateless application design
- Database connection pooling
- Session storage externalization
- Load balancer compatibility

### Performance Optimization
- Database query optimization
- Template compilation caching
- Static asset optimization
- CDN integration for media delivery

## Development Patterns

### Class Organization
```
f_core/f_classes/
├── class.auth.php          # Authentication
├── class.database.php      # Database abstraction
├── class.security.php      # Security utilities
├── class.logger.php        # Logging framework
├── class.rbac.php          # Role-based access
└── ...
```

### Configuration Management
- Environment-based configuration
- Database-stored settings
- Runtime configuration caching
- Secure credential handling

### Error Handling
- Global exception handling
- User-friendly error pages
- Detailed error logging
- Debug mode for development

## API Architecture

### RESTful Design
- Resource-based URLs
- HTTP method semantics
- Proper status codes
- JSON response format

### Authentication
- Token-based authentication
- API key management
- Rate limiting per client
- Scope-based permissions

## Deployment Architecture

### Container Strategy
- Multi-container deployment (Docker Compose)
- Service isolation
- Volume management for persistent data
- Health checks and restart policies

### Services
- **PHP-FPM**: Application server
- **Caddy**: Web server and reverse proxy
- **MariaDB**: Database server
- **SRS**: Streaming server
- **Cron**: Scheduled task runner

## Future Considerations

### Microservices Migration
- Service decomposition strategy
- API gateway implementation
- Inter-service communication
- Data consistency patterns

### Cloud Native Features
- Kubernetes deployment
- Auto-scaling capabilities
- Service mesh integration
- Observability stack (Prometheus, Grafana)

## Performance Benchmarks

### Target Metrics
- Page load time: < 2 seconds
- API response time: < 500ms
- Concurrent users: 10,000+
- Video processing: Real-time for live streams

### Optimization Techniques
- Database indexing strategy
- Query optimization
- Caching layer implementation
- CDN utilization for static assets