Quantum/docs/api.md
RTSDA 85a4115a71 🚀 Initial release: Quantum Web Server v0.2.0
 Features:
• HTTP/1.1, HTTP/2, and HTTP/3 support with proper architecture
• Reverse proxy with advanced load balancing (round-robin, least-conn, etc.)
• Static file serving with content-type detection and security
• Revolutionary file sync system with WebSocket real-time updates
• Enterprise-grade health monitoring (active/passive checks)
• TLS/HTTPS with ACME/Let's Encrypt integration
• Dead simple JSON configuration + full Caddy v2 compatibility
• Comprehensive test suite (72 tests passing)

🏗️ Architecture:
• Rust-powered async performance with zero-cost abstractions
• HTTP/3 as first-class citizen with shared routing core
• Memory-safe design with input validation throughout
• Modular structure for easy extension and maintenance

📊 Status: 95% production-ready
🧪 Test Coverage: 72/72 tests passing (100% success rate)
🔒 Security: Memory safety + input validation + secure defaults

Built with ❤️ in Rust - Start simple, scale to enterprise!
2025-08-17 17:08:49 -04:00

617 lines
13 KiB
Markdown

# Quantum Configuration API Reference
Quantum supports two configuration formats:
1. **Simple Configuration** - Dead simple JSON for common use cases (90% of users)
2. **Full Configuration** - Complete Caddy v2 compatibility for advanced features
**Start with simple, upgrade when needed.**
## 🚀 Simple Configuration Format
The simple format handles most common use cases with minimal JSON. Perfect for:
- Reverse proxies
- Static file serving
- File upload/download APIs
- Basic TLS setup
### Quick Reference
```json
{
"proxy": {
"upstream:port": "listen_port"
},
"static_files": {
"directory": "listen_port"
},
"file_sync": {
"directory": "listen_port"
},
"tls": "auto|off|/path/to/certs",
"admin_port": ":2019"
}
```
### Simple Configuration Fields
| Field | Type | Description | Example |
|-------|------|-------------|---------|
| `proxy` | object | Map upstream services to listen ports | `{"localhost:3000": ":8080"}` |
| `static_files` | object | Map directories to serve on ports | `{"./public": ":8080"}` |
| `file_sync` | object | Map directories with upload API to ports | `{"./uploads": ":9000"}` |
| `tls` | string | TLS mode: "auto", "off", or certificate path | `"auto"` |
| `admin_port` | string | Admin API port (optional) | `":2019"` |
### Simple Configuration Examples
#### Basic Proxy
```json
{
"proxy": {
"localhost:3000": ":8080"
}
}
```
**Result:** Proxy all requests from `:8080` to your app on `localhost:3000`
#### Multiple Services
```json
{
"proxy": {
"localhost:3000": ":80",
"localhost:4000": ":443"
}
}
```
**Result:** Proxy `:80``localhost:3000` and `:443``localhost:4000`
#### Static Files
```json
{
"static_files": {
"./public": ":8080",
"./assets": ":8081"
}
}
```
**Result:** Serve `./public` on `:8080` and `./assets` on `:8081`
#### File Upload/Download
```json
{
"file_sync": {
"./uploads": ":9000"
}
}
```
**Result:** Enable file upload/download API on `:9000` for `./uploads` directory
#### Full Stack Setup
```json
{
"proxy": {"localhost:3000": ":80"},
"static_files": {"./public": ":8080"},
"file_sync": {"./uploads": ":9000"},
"tls": "auto",
"admin_port": ":2019"
}
```
**Result:** Complete setup with proxy, static files, uploads, automatic TLS, and admin API
### Port Formats
All port formats are supported:
```json
{
"proxy": {
"localhost:3000": ":8080", // Listen on all interfaces, port 8080
"localhost:4000": "8081", // Same as ":8081" (colon added automatically)
"localhost:5000": "127.0.0.1:8082", // Listen only on localhost
"localhost:6000": "[::1]:8083" // IPv6 localhost
}
}
```
### TLS Configuration
```json
{
"tls": "auto" // Automatic certificate management (Let's Encrypt)
}
```
```json
{
"tls": "off" // Disable TLS
}
```
```json
{
"tls": "/path/to/certs" // Use certificates from directory
}
```
### Validation and Error Messages
The simple format includes comprehensive validation with helpful error messages:
**Valid Configuration:**
```
✅ Detected simple configuration format
HTTP server listening on 0.0.0.0:8080
```
**Invalid Configurations:**
```
❌ Proxy upstream 'localhost' must include port (e.g., 'localhost:3000')
⚠️ Port 80 for proxy upstream 'localhost:3000' requires root privileges
❌ Invalid port 'abc' for static files './public'
❌ Static file directory cannot be empty
❌ TLS must be 'auto', 'off', or a path to certificate files
```
### Migration from Simple to Full
The simple format automatically converts to full Caddy format. You can start simple and migrate to full format when you need:
- Custom matchers (host, path, method)
- Advanced load balancing algorithms
- Health checks
- Custom middleware
- Complex TLS automation
---
## 🔧 Full Configuration Format (Caddy v2 Compatible)
For advanced use cases, Quantum supports the complete Caddy v2 JSON configuration format.
### Root Configuration Structure
```json
{
"admin": { ... },
"apps": { ... }
}
```
### Admin Configuration
```json
{
"admin": {
"listen": ":2019"
}
}
```
| Field | Type | Description | Default |
|-------|------|-------------|---------|
| `listen` | string | Address and port for admin API | `:2019` |
### Apps Configuration
```json
{
"apps": {
"http": {
"servers": {
"server_name": { ... }
}
}
}
}
```
### Server Configuration
```json
{
"listen": [":80", ":443"],
"routes": [ ... ],
"automatic_https": { ... },
"tls": { ... }
}
```
| Field | Type | Description | Required |
|-------|------|-------------|----------|
| `listen` | array[string] | List of addresses to listen on | Yes |
| `routes` | array[Route] | List of route configurations | Yes |
| `automatic_https` | AutomaticHttps | HTTPS automation settings | No |
| `tls` | TlsConfig | TLS/SSL configuration | No |
### Route Configuration
Routes define how to handle requests based on matching criteria.
```json
{
"match": [ ... ],
"handle": [ ... ]
}
```
| Field | Type | Description | Required |
|-------|------|-------------|----------|
| `match` | array[Matcher] | List of matching conditions | No |
| `handle` | array[Handler] | List of handlers to execute | Yes |
### Matchers
#### Host Matcher
```json
{
"matcher": "host",
"hosts": ["example.com", "*.example.com", "api.example.com"]
}
```
#### Path Matcher
```json
{
"matcher": "path",
"paths": ["/api/*", "/v1/users", "/static/*"]
}
```
#### Path Regexp Matcher
```json
{
"matcher": "path_regexp",
"pattern": "^/api/v[0-9]+/users/[0-9]+$"
}
```
#### Method Matcher
```json
{
"matcher": "method",
"methods": ["GET", "POST", "PUT", "DELETE"]
}
```
### Handlers
#### Reverse Proxy Handler
```json
{
"handler": "reverse_proxy",
"upstreams": [
{
"dial": "backend1.example.com:8080",
"max_requests": 1000,
"unhealthy_request_count": 5
}
],
"load_balancing": {
"selection_policy": {
"policy": "round_robin"
}
},
"health_checks": {
"active": {
"path": "/health",
"interval": "30s",
"timeout": "5s"
},
"passive": {
"unhealthy_status": [500, 502, 503, 504],
"unhealthy_latency": "3s"
}
}
}
```
##### Load Balancing Policies
| Policy | Description |
|--------|-------------|
| `round_robin` | Distribute requests evenly across upstreams |
| `random` | Randomly select an upstream |
| `least_conn` | Select upstream with fewest active connections |
| `ip_hash` | Select upstream based on client IP hash |
#### Static Response Handler
```json
{
"handler": "static_response",
"status_code": 200,
"headers": {
"Content-Type": ["application/json"],
"Cache-Control": ["no-cache", "no-store"]
},
"body": "{\"status\": \"ok\", \"message\": \"Service is running\"}"
}
```
#### File Server Handler
```json
{
"handler": "file_server",
"root": "/var/www/html",
"browse": true
}
```
#### File Sync Handler
```json
{
"handler": "file_sync",
"root": "./sync-data",
"enable_upload": true
}
```
### TLS Configuration
```json
{
"tls": {
"certificates": [
{
"certificate": "/path/to/cert.pem",
"key": "/path/to/key.pem",
"subjects": ["example.com", "www.example.com"]
}
],
"automation": {
"policies": [
{
"subjects": ["*.example.com"],
"issuer": {
"module": "acme",
"ca": "https://acme-v02.api.letsencrypt.org/directory",
"email": "admin@example.com",
"agreed": true
}
}
]
}
}
}
```
---
## 📋 Complete Configuration Examples
### Simple Format Examples
#### Development Proxy
```json
{
"proxy": {"localhost:3000": ":8080"},
"admin_port": ":2019"
}
```
#### Production Multi-Service
```json
{
"proxy": {
"localhost:3000": ":80",
"localhost:4000": ":443"
},
"static_files": {
"./public": ":8080"
},
"tls": "auto"
}
```
#### File Server with Uploads
```json
{
"static_files": {"./public": ":80"},
"file_sync": {"./uploads": ":8080"}
}
```
### Full Format Examples
#### Simple Static Site
```json
{
"admin": {"listen": ":2019"},
"apps": {
"http": {
"servers": {
"static_site": {
"listen": [":80"],
"routes": [
{
"handle": [
{
"handler": "file_server",
"root": "./public"
}
]
}
]
}
}
}
}
}
```
#### Advanced API Gateway
```json
{
"admin": {"listen": ":2019"},
"apps": {
"http": {
"servers": {
"api_gateway": {
"listen": [":80", ":443"],
"routes": [
{
"match": [
{"matcher": "host", "hosts": ["api.example.com"]},
{"matcher": "path", "paths": ["/v1/*"]}
],
"handle": [
{
"handler": "reverse_proxy",
"upstreams": [
{"dial": "backend1:8080"},
{"dial": "backend2:8080"},
{"dial": "backend3:8080"}
],
"load_balancing": {
"selection_policy": {"policy": "least_conn"}
},
"health_checks": {
"active": {
"path": "/health",
"interval": "30s",
"timeout": "5s"
}
}
}
]
}
],
"tls": {
"automation": {
"policies": [
{
"subjects": ["api.example.com"],
"issuer": {
"module": "acme",
"email": "admin@example.com",
"agreed": true
}
}
]
}
}
}
}
}
}
}
```
---
## 🖥️ CLI API
### Command Line Options
```bash
quantum [OPTIONS]
OPTIONS:
-c, --config <FILE> Configuration file path [default: quantum.json]
-p, --port <PORT> HTTP port to listen on [default: 8080]
--https-port <PORT> HTTPS port to listen on [default: 8443]
-h, --help Print help information
-V, --version Print version information
```
### Environment Variables
| Variable | Description | Default |
|----------|-------------|---------|
| `RUST_LOG` | Log level (error, warn, info, debug, trace) | `info` |
| `QUANTUM_CONFIG` | Default configuration file path | `quantum.json` |
### Exit Codes
| Code | Description |
|------|-------------|
| 0 | Success |
| 1 | Configuration error |
| 2 | Network binding error |
| 3 | Runtime error |
---
## 📊 Configuration Detection and Validation
Quantum automatically detects which configuration format you're using:
```bash
quantum --config simple.json
# ✅ Detected simple configuration format
# HTTP server listening on 0.0.0.0:8080
quantum --config full.json
# ✅ Detected full Caddy configuration format
# HTTP server listening on 0.0.0.0:8080
```
If configuration parsing fails, you get helpful error messages for both formats:
```
❌ Failed to parse config file 'config.json':
Simple format error: missing field `proxy`
Full format error: missing field `apps`
💡 Try using the simple format:
{
"proxy": { "localhost:3000": ":8080" }
}
```
---
## 🔍 Logging and Monitoring
### Structured Logging
```
2024-01-01T12:00:00.000Z INFO quantum::server: HTTP server listening on 0.0.0.0:8080
2024-01-01T12:00:01.123Z INFO quantum::middleware: GET / HTTP/1.1 from 192.168.1.100:12345
2024-01-01T12:00:01.145Z INFO quantum::proxy: Proxying request to localhost:3000
```
### Log Levels
- **ERROR**: Critical errors that may cause the server to stop
- **WARN**: Non-critical issues that should be addressed
- **INFO**: General operational information
- **DEBUG**: Detailed debugging information
- **TRACE**: Very detailed debugging information
### Future Metrics API
Future versions will expose Prometheus metrics at `/metrics`:
```
# HELP quantum_requests_total Total number of HTTP requests
# TYPE quantum_requests_total counter
quantum_requests_total{method="GET",status="200"} 1234
# HELP quantum_request_duration_seconds Request duration in seconds
# TYPE quantum_request_duration_seconds histogram
quantum_request_duration_seconds_bucket{le="0.1"} 100
```
---
## 🚀 Migration Path
**Start Simple → Scale to Full**
1. **Begin with simple format** for immediate productivity
2. **Add features incrementally** as needs grow
3. **Migrate to full format** when advanced features needed
4. **Use both formats** - simple for basic services, full for complex ones
The simple format handles 90% of use cases. Use full format for:
- Custom request matching logic
- Advanced load balancing strategies
- Complex TLS automation policies
- Custom middleware chains
- Health check configurations
---
**For more examples and guides, see [SIMPLE-CONFIG.md](../SIMPLE-CONFIG.md)**