Files
quoter/docs/configuration.md
Untone b876564f4a 📚 Complete documentation overhaul
### New Documentation:
- **URL Format Guide**: Complete guide for image resizer URL patterns
- **Hybrid Architecture**: Vercel Edge + Quoter integration strategy
- **Updated How-it-works**: Comprehensive system architecture with diagrams
- **Enhanced Configuration**: Security settings, troubleshooting, Vercel integration

### Documentation Structure:
📋 Architecture & Principles:
- 🚀 How Quoter Works (detailed system architecture)
- 🔀 Hybrid Architecture (Vercel + Quoter best practices)
- 📐 URL Format (complete resizer URL guide)

🛡️ Security & Configuration:
- 🔒 Security & DDoS Protection (comprehensive guide)
- ⚙️ Configuration (updated with new settings)
- 🚀 Deployment & 📊 Monitoring

🎨 Integrations:
- Vercel OG Integration guides
- Edge Function examples

### Key Features Documented:
- Complete URL patterns for image resizing
- Security rate limiting configuration
- Hybrid upload (Quoter) + download (Vercel) strategy
- JWT validation and session management
- Multi-cloud storage (Storj + AWS fallback)
- Performance optimization techniques
- Production deployment strategies

All documentation is now production-ready and includes practical examples! 📖
2025-09-02 12:32:15 +03:00

230 lines
6.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Конфигурация
## Переменные окружения
Quoter использует следующие переменные окружения для настройки:
### Обязательные переменные
| Переменная | Описание | Пример |
|------------|----------|--------|
| `REDIS_URL` | URL для подключения к Redis | `redis://localhost:6379` |
| `STORJ_ACCESS_KEY` | Ключ доступа к Storj S3 | `your-storj-access-key` |
| `STORJ_SECRET_KEY` | Секретный ключ Storj S3 | `your-storj-secret-key` |
| `AWS_ACCESS_KEY` | Ключ доступа к AWS S3 (fallback) | `your-aws-access-key` |
| `AWS_SECRET_KEY` | Секретный ключ AWS S3 (fallback) | `your-aws-secret-key` |
| `JWT_SECRET` | Секрет для валидации JWT токенов | `your-jwt-secret-key` |
### Опциональные переменные
| Переменная | Описание | По умолчанию |
|------------|----------|--------------|
| `PORT` | Порт для запуска сервера | `8080` |
| `STORJ_END_POINT` | Endpoint Storj S3 | `https://gateway.storjshare.io` |
| `STORJ_BUCKET_NAME` | Имя bucket в Storj | `discours-io` |
| `AWS_END_POINT` | Endpoint AWS S3 | `https://s3.amazonaws.com` |
| `RUST_LOG` | Уровень логирования | `info` |
## Пример .env файла
```bash
# Redis (обязательно)
REDIS_URL=redis://localhost:6379
# JWT Authentication (обязательно)
JWT_SECRET=your-super-secret-jwt-key
# Storj S3 - основное хранилище (обязательно)
STORJ_ACCESS_KEY=your-storj-access-key
STORJ_SECRET_KEY=your-storj-secret-key
STORJ_END_POINT=https://gateway.storjshare.io
STORJ_BUCKET_NAME=discours-io
# AWS S3 - fallback хранилище (обязательно)
AWS_ACCESS_KEY=your-aws-access-key
AWS_SECRET_KEY=your-aws-secret-key
AWS_END_POINT=https://s3.amazonaws.com
# Server настройки
PORT=8080
RUST_LOG=info
# Security (опционально)
MAX_PAYLOAD_SIZE=524288000 # 500MB
MAX_PATH_LENGTH=1000
MAX_HEADERS_COUNT=50
```
## Настройка Redis
### Минимальная конфигурация Redis
```redis
# redis.conf
maxmemory 2gb
maxmemory-policy allkeys-lru
save 900 1
save 300 10
save 60 10000
```
### Проверка подключения
```bash
redis-cli ping
```
## Настройка S3
### Storj S3
1. Создайте аккаунт на [Storj](https://storj.io)
2. Создайте API ключи в консоли
3. Создайте bucket для файлов
4. Настройте CORS для bucket:
```json
{
"CORSRules": [
{
"AllowedOrigins": ["*"],
"AllowedMethods": ["GET", "POST", "PUT", "DELETE"],
"AllowedHeaders": ["*"],
"ExposeHeaders": ["ETag"]
}
]
}
```
### AWS S3
1. Создайте IAM пользователя с правами S3
2. Создайте bucket для файлов
3. Настройте CORS аналогично Storj
## Логирование
### Уровни логирования
- `error` - только ошибки
- `warn` - предупреждения и ошибки
- `info` - информационные сообщения, предупреждения и ошибки
- `debug` - отладочная информация
- `trace` - максимальная детализация
### Примеры
```bash
# Только ошибки
RUST_LOG=error cargo run
# Информационные сообщения
RUST_LOG=info cargo run
# Отладка
RUST_LOG=debug cargo run
```
## Дополнительные настройки
### Настройки безопасности
```bash
# Rate limiting (requests per window)
GENERAL_RATE_LIMIT=100 # Общие запросы: 100/мин
UPLOAD_RATE_LIMIT=10 # Загрузка: 10/5мин
AUTH_RATE_LIMIT=20 # Аутентификация: 20/15мин
# Блокировка (секунды)
GENERAL_BLOCK_DURATION=300 # 5 минут
UPLOAD_BLOCK_DURATION=600 # 10 минут
AUTH_BLOCK_DURATION=1800 # 30 минут
```
### Настройки квот
```bash
# Пользовательские квоты
MAX_USER_QUOTA_BYTES=12884901888 # 12 ГБ на пользователя
MAX_SINGLE_FILE_BYTES=524288000 # 500 МБ на файл
```
### Vercel интеграция
```bash
# CORS для Vercel Edge Functions
ALLOWED_ORIGINS=https://discours.io,https://new.discours.io,https://vercel.app
# Health check endpoint
HEALTH_CHECK_ENABLED=true
```
## Проверка конфигурации
Запустите сервер и проверьте логи:
```bash
RUST_LOG=info cargo run
```
Успешный запуск должен показать:
```
[INFO] Started
[INFO] Security config: max_payload=500 MB, upload_rate_limit=10/300s
[WARN] caching AWS filelist...
[WARN] cached 1234 files
```
### Проверка endpoints
```bash
# Health check
curl http://localhost:8080/health
# User info (требует токен)
curl -H "Authorization: Bearer $TOKEN" http://localhost:8080/
# Upload test (требует токен)
curl -X POST -H "Authorization: Bearer $TOKEN" \
-F "file=@test.jpg" http://localhost:8080/
```
### Проверка безопасности
```bash
# Rate limiting test
for i in {1..110}; do curl http://localhost:8080/ & done
# Должно показать 429 после 100 запросов
```
## Troubleshooting
### Частые проблемы
**1. Redis connection failed**
```bash
# Проверьте Redis
redis-cli ping
# Должно вернуть: PONG
```
**2. S3 credentials invalid**
```bash
# Проверьте доступ к Storj
aws s3 ls --endpoint-url=https://gateway.storjshare.io \
--profile storj
# Проверьте доступ к AWS
aws s3 ls --profile aws
```
**3. JWT validation failed**
```bash
# Проверьте JWT_SECRET
echo $JWT_SECRET
# Должен быть установлен и совпадать с core API
```
**4. Rate limiting не работает**
```bash
# Проверьте Redis keys
redis-cli KEYS "rate_limit:*"
# Должны появляться ключи при запросах
```