# Server Foundation Library

Server-side foundation library for Rustelo web applications built with Axum and Leptos SSR.

## Quick Start

### Basic Server Usage
```rust
use server::run_server;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Use foundation server directly - simplest approach
    run_server().await?;
    Ok(())
}
```

### Configured Server
```rust
use server::{run_server_with_config, ServerConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = ServerConfig::builder()
        .host("0.0.0.0")
        .port(8080)
        .enable_features(["auth", "content-db", "metrics"])
        .database_url("postgresql://localhost/myapp")
        .build();
    
    run_server_with_config(config).await?;
    Ok(())
}
```

### Custom Server with Foundation Components
```rust
use server::{create_base_app, serve_custom_app, ServerConfig, setup_tracing};
use axum::{Router, routing::get};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = ServerConfig::default();
    setup_tracing(&config)?;
    
    // Start with foundation base app
    let app = create_base_app(&config).await?
        .route("/custom", get(custom_handler))
        .layer(custom_middleware());
    
    serve_custom_app(app, config).await?;
    Ok(())
}

async fn custom_handler() -> &'static str {
    "Custom endpoint built on foundation"
}
```

## Usage Patterns

### 1. Direct Import (Simplest)
Perfect for getting started quickly:
```rust
use server::run_server;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    run_server().await?;
    Ok(())
}
```

**What you get:**
- Server on 0.0.0.0:3030 (configurable via env)
- Basic route configuration from content/routes/
- Static file serving
- Logging setup
- CORS and security headers

### 2. Configuration-Based
Customize server behavior through configuration:
```rust
use server::{run_server_with_config, ServerConfig, DatabaseConfig};

let config = ServerConfig::builder()
    .host("127.0.0.1")
    .port(9000)
    .enable_features(["auth", "content-db", "email"])
    .database(DatabaseConfig {
        url: "postgresql://localhost/myapp".to_string(),
        max_connections: Some(20),
        timeout_seconds: Some(30),
    })
    .content_path("custom-content")
    .build();

run_server_with_config(config).await?;
```

### 3. Extended Server
Add custom functionality to foundation server:
```rust
use server::{create_base_app, serve_custom_app, ServerConfig};
use axum::{Router, middleware, routing::get};

let config = ServerConfig::default();
let base_app = create_base_app(&config).await?;

// Add custom routes and middleware
let app = base_app
    .route("/api/custom", get(custom_api))
    .route("/health", get(health_check))
    .layer(middleware::from_fn(custom_auth_middleware));

serve_custom_app(app, config).await?;
```

### 4. Modular Composition  
Build server from individual foundation components:
```rust
use server::{
    setup_tracing, ServerConfig,
    middleware::{cors_middleware, security_headers_middleware},
    routing::{create_api_routes, create_static_routes},
    database::create_pool,
};

// Setup individual components
let config = ServerConfig::from_env()?;
setup_tracing(&config)?;

// Compose application
let app = Router::new()
    .merge(create_api_routes(&config).await?)
    .merge(create_static_routes(&config))
    .layer(cors_middleware(&config))
    .layer(security_headers_middleware());

// Start with custom server logic
let listener = tokio::net::TcpListener::bind(&format!("{}:{}", config.host, config.port)).await?;
axum::serve(listener, app).await?;
```

## Available Features

### Core Features (Always Available)
- HTTP server with Axum
- Static file serving
- Route configuration from content/
- CORS and security headers
- Health check endpoints
- Logging and tracing setup

### Optional Features (Feature-Gated)

#### Authentication (`auth` feature)
- JWT token authentication
- OAuth2 integration (Google, GitHub, etc.)
- Two-factor authentication (TOTP)
- Role-based access control (RBAC)
- Session management
- Password hashing (Argon2)

#### Content Management (`content-static`, `content-db`)
- Markdown content processing
- Database-driven content (PostgreSQL/SQLite)
- File-based content (markdown + frontmatter)
- Content caching and optimization
- Image processing and optimization

#### Email System (`email` feature)
- SMTP email sending
- Email templates (Handlebars)
- Multi-provider support (SendGrid, Mailgun, etc.)
- Email queuing and retry logic

#### Database Support (`auth`, `content-db`)
- PostgreSQL and SQLite support
- Connection pooling (SQLx)
- Automatic migrations
- Health checks

#### Security (`tls`, `crypto`)
- HTTPS/TLS support (rustls)
- Data encryption (AES-GCM)
- Security headers middleware
- CSRF protection
- Rate limiting

#### Monitoring (`metrics` feature)
- Prometheus metrics
- Health check endpoints
- Performance monitoring
- Error tracking and alerting

## Server Configuration

### Environment Variables
```bash
# Basic configuration
HOST=0.0.0.0
PORT=3030
RUST_LOG=info

# Content paths
SITE_CONTENT_PATH=content
SITE_SERVER_CONTENT_URL=/content

# Database (if auth or content-db features enabled)
DATABASE_URL=postgresql://localhost/myapp
DATABASE_MAX_CONNECTIONS=10

# Authentication (if auth feature enabled)
JWT_SECRET=your-secret-key
SESSION_TIMEOUT_HOURS=24
OAUTH_GOOGLE_CLIENT_ID=your-client-id
OAUTH_GOOGLE_CLIENT_SECRET=your-client-secret

# Email (if email feature enabled)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USERNAME=your-email@gmail.com
SMTP_PASSWORD=your-app-password
EMAIL_FROM=noreply@yoursite.com

# Security
ENABLE_HTTPS=false
TLS_CERT_PATH=/path/to/cert.pem
TLS_KEY_PATH=/path/to/key.pem

# Metrics (if metrics feature enabled)
METRICS_ENABLED=true
METRICS_PATH=/metrics
```

### Configuration File (config.toml)
```toml
[server]
host = "0.0.0.0"
port = 3030
workers = 4

[content]
path = "content"
server_url = "/content"
cache_enabled = true
cache_ttl_seconds = 3600

[database]
url = "postgresql://localhost/myapp"
max_connections = 20
timeout_seconds = 30

[auth]
jwt_secret = "your-jwt-secret"
session_timeout_hours = 24
enable_oauth = true
enable_2fa = true

[email]
provider = "smtp"
smtp_host = "smtp.gmail.com"
smtp_port = 587
from_address = "noreply@yoursite.com"

[security]
enable_cors = true
cors_origins = ["http://localhost:3000", "https://yoursite.com"]
enable_rate_limiting = true
rate_limit_requests = 100
rate_limit_window_seconds = 60

[metrics]
enabled = true
path = "/metrics"
include_route_metrics = true
```

## Build System Integration

### Using Foundation Build Utilities
```rust
// build.rs
use server::build::{generate_routes, setup_i18n, build_foundation};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Use foundation build utilities
    build_foundation()?;
    
    // Or call individual functions
    let content_path = std::env::var("SITE_CONTENT_PATH")
        .unwrap_or_else(|_| "content".to_string());
    
    generate_routes(&content_path)?;
    setup_i18n(&format!("{}/i18n", content_path))?;
    
    Ok(())
}
```

### Custom Build Integration
```rust
// build.rs with custom logic
use server::build;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Foundation build steps
    build::generate_routes("content/routes")?;
    build::setup_i18n("content/i18n")?;
    
    // Your custom build steps
    custom_asset_processing()?;
    custom_config_validation()?;
    
    Ok(())
}

fn custom_asset_processing() -> Result<(), Box<dyn std::error::Error>> {
    // Your custom build logic
    Ok(())
}
```

## API Reference

### Main Functions
```rust
// Simple server startup
pub async fn run_server() -> Result<(), ServerError>

// Configurable server startup  
pub async fn run_server_with_config(config: ServerConfig) -> Result<(), ServerError>

// Custom app serving
pub async fn serve_custom_app(app: Router, config: ServerConfig) -> Result<(), ServerError>
```

### App Building Functions
```rust
// Create base app with foundation routes and middleware
pub async fn create_base_app(config: &ServerConfig) -> Result<Router, ServerError>

// Create configured app with all features
pub async fn create_configured_app(config: &ServerConfig) -> Result<Router, ServerError>
```

### Utility Functions
```rust
// Setup logging and tracing
pub fn setup_tracing(config: &ServerConfig) -> Result<(), ServerError>

// Create database connection pool
pub async fn create_database_pool(config: &DatabaseConfig) -> Result<Pool, DatabaseError>

// Setup authentication system
pub fn setup_auth(config: &AuthConfig) -> Result<AuthService, AuthError>
```

### Build Functions
```rust
// Generate routes from content configuration
pub fn generate_routes<P: AsRef<Path>>(content_path: P) -> Result<(), BuildError>

// Setup internationalization files  
pub fn setup_i18n<P: AsRef<Path>>(i18n_path: P) -> Result<(), BuildError>

// Complete foundation build process
pub fn build_foundation() -> Result<(), BuildError>
```

## Documentation

- [📚 Usage Patterns](docs/USAGE_PATTERNS.md) - Detailed usage examples
- [⚙️ Configuration Guide](docs/CONFIGURATION.md) - Complete configuration reference
- [🔧 Extension Guide](docs/EXTENSION_GUIDE.md) - How to extend the foundation
- [🔐 Authentication Guide](docs/AUTHENTICATION.md) - Auth system integration
- [📊 Monitoring Guide](docs/MONITORING.md) - Metrics and health checks
- [🚀 Deployment Guide](docs/DEPLOYMENT.md) - Production deployment

## Examples

- [📁 examples/](examples/) - Complete usage examples
- [🏗️ Basic Server](examples/basic_server.rs) - Simple server setup
- [⚙️ Custom Config Server](examples/custom_config_server.rs) - Advanced configuration
- [🔌 Extended Server](examples/extended_server.rs) - Adding custom functionality
- [🧩 Modular Server](examples/modular_server.rs) - Component composition
- [🔐 Auth Server](examples/auth_server.rs) - Authentication integration
- [📊 Monitored Server](examples/monitored_server.rs) - Metrics integration

## Feature Flags

```toml
[dependencies.server]
path = "path/to/server"
features = [
    "auth",           # Authentication and authorization
    "content-static", # File-based content management  
    "content-db",     # Database content management
    "email",          # Email system
    "tls",            # HTTPS/TLS support
    "crypto",         # Data encryption
    "metrics",        # Prometheus metrics
    "rbac",           # Role-based access control
]
```

## Production Deployment

### Docker Example
```dockerfile
FROM rust:1.75 as builder
WORKDIR /app
COPY . .
RUN cargo build --release --features "auth,content-db,email,tls,metrics"

FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y ca-certificates
COPY --from=builder /app/target/release/my-server /usr/local/bin/server
COPY content/ /app/content/
COPY config/ /app/config/
WORKDIR /app
CMD ["server"]
```

### Systemd Service
```ini
[Unit]
Description=Rustelo Server
After=network.target

[Service]
Type=simple
User=rustelo
WorkingDirectory=/opt/rustelo
Environment=RUST_LOG=info
Environment=HOST=0.0.0.0
Environment=PORT=3030
ExecStart=/opt/rustelo/bin/server
Restart=always

[Install]
WantedBy=multi-user.target
```

## Performance & Security

### Performance Tips
- Enable release mode for production builds
- Use connection pooling for database connections
- Enable gzip compression middleware
- Configure appropriate logging levels
- Use static file serving for assets

### Security Checklist
- [ ] Enable HTTPS/TLS in production
- [ ] Configure CORS properly for your domain
- [ ] Use strong JWT secrets (32+ characters)
- [ ] Enable rate limiting
- [ ] Keep dependencies updated
- [ ] Use environment variables for secrets
- [ ] Enable security headers middleware

## Troubleshooting

### Common Issues
1. **Port already in use** - Check if another process is using the port
2. **Database connection failed** - Verify DATABASE_URL and database is running
3. **Static files not found** - Check SITE_CONTENT_PATH configuration
4. **Authentication not working** - Verify JWT_SECRET is set
5. **CORS errors** - Configure cors_origins properly

### Debug Mode
Enable debug logging:
```bash
RUST_LOG=debug cargo run
```

### Health Checks
The server provides health check endpoints:
- `GET /health` - Basic health check
- `GET /health/detailed` - Detailed system status (if metrics enabled)

## Contributing

The server foundation is designed to be extended:

1. **Add middleware** - Create custom middleware functions
2. **Add routes** - Extend routing capabilities  
3. **Add features** - Implement new optional features
4. **Improve docs** - Help others understand usage patterns
5. **Add examples** - Show real-world integration scenarios

## License

MIT License - See LICENSE file for details.
