Download backend/REFACTORING_GUIDE.md from new-arc/vector: direct link, hf CLI and curl.
- Browser
- Download file 8.15 kB
-
https://huggingface.co/spaces/new-arc/vector/resolve/main/backend/REFACTORING_GUIDE.md
- Command line
-
hf download hf://spaces/new-arc/vector/backend/REFACTORING_GUIDE.md
-
curl -L -o REFACTORING_GUIDE.md https://huggingface.co/spaces/new-arc/vector/resolve/main/backend/REFACTORING_GUIDE.md
Historical migration notes. The migration is complete:
src.main:appis now canonical andsrc.main_refactored:appis a compatibility alias. See architecture for the current layout.
Backend Refactoring Guide
π― What Changed
The backend has been completely refactored from a monolithic structure to a proper layered architecture with:
Architecture Improvements
Before:
- 650+ lines in main.py
- Blocking sync operations (video processing, downloads) in async context
asyncio.create_task()for background jobs (lost on restart)- No progress tracking
- Multiple database sessions per request
- No separation of concerns
After:
- Layered Architecture: routes β services β repositories
- Async Job Queue: arq (Redis-based) with persistent jobs
- Separate Worker Process: Video processing runs independently
- Thread Pool: Blocking operations don't block the event loop
- Real-time Progress: SSE (Server-Sent Events) + Redis pub/sub
- Granular Status: queued β downloading β transcribing β analyzing β generating_clips β completed
New Directory Structure
backend/src/
βββ api/routes/
β βββ tasks.py # Task endpoints + SSE
β βββ media.py # Fonts, transitions, uploads
βββ services/
β βββ video_service.py # Video processing logic
β βββ task_service.py # Task orchestration
βββ repositories/
β βββ task_repository.py # Task DB operations
β βββ clip_repository.py # Clip DB operations
β βββ source_repository.py
βββ workers/
β βββ tasks.py # arq worker functions
β βββ job_queue.py # Queue management
β βββ progress.py # Progress tracking
βββ utils/
β βββ async_helpers.py # Async wrappers
βββ main_refactored.py # New clean entry point
βββ worker_main.py # Worker process entry
π Deployment Steps
Step 1: Apply Database Migration
The refactoring adds progress and progress_message fields to the tasks table.
# Apply migration to existing database
docker exec -i supoclip-postgres psql -U postgres -d supoclip < backend/migrations/001_add_progress_fields.sql
For fresh installs, the updated init.sql already includes these fields.
Step 2: Install New Dependencies
cd backend
# Install arq and redis
uv sync
# Or manually:
uv pip install arq>=0.26.0 redis>=5.0.0
Step 3: Update Docker Configuration
Option A: Update Dockerfile
The Dockerfile will automatically pick up new dependencies from pyproject.toml:
docker-compose build backend
Option B: Add Worker Service (Recommended)
Edit docker-compose.yml to add a separate worker service:
services:
supoclip-worker:
build: ./backend
command: [".venv/bin/arq", "src.workers.tasks.WorkerSettings"]
environment:
- DATABASE_URL=postgresql://postgres:postgres@postgres:5432/supoclip
- REDIS_HOST=redis
- REDIS_PORT=6379
- ASSEMBLY_AI_API_KEY=${ASSEMBLY_AI_API_KEY}
- LLM=${LLM}
- GOOGLE_API_KEY=${GOOGLE_API_KEY}
- TEMP_DIR=/tmp
volumes:
- ./backend:/app
- /tmp:/tmp
depends_on:
- postgres
- redis
restart: unless-stopped
Step 4: Switch to Refactored Main
Update Dockerfile CMD or docker-compose command:
# Change from:
CMD [".venv/bin/uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"]
# To:
CMD [".venv/bin/uvicorn", "src.main_refactored:app", "--host", "0.0.0.0", "--port", "8000"]
Or in docker-compose.yml:
supoclip-backend:
command: [".venv/bin/uvicorn", "src.main_refactored:app", "--host", "0.0.0.0", "--port", "8000"]
Step 5: Restart Services
docker-compose down
docker-compose up -d --build
π§ͺ Testing the Refactored System
1. Check Health Endpoints
# Basic health
curl http://localhost:8000/health
# Database health
curl http://localhost:8000/health/db
# Redis health (new!)
curl http://localhost:8000/health/redis
2. Create a Task
curl -X POST http://localhost:8000/tasks/ \
-H "Content-Type: application/json" \
-H "user_id: YOUR_USER_ID" \
-d '{
"source": {
"url": "https://www.youtube.com/watch?v=VIDEO_ID"
},
"font_options": {
"font_family": "TikTokSans-Regular",
"font_size": 24,
"font_color": "#FFFFFF"
}
}'
Response:
{
"task_id": "uuid-here",
"job_id": "job-uuid",
"message": "Task created and queued for processing"
}
3. Watch Real-time Progress (SSE)
curl -N http://localhost:8000/tasks/{task_id}/progress
You'll see streaming events like:
event: status
data: {"task_id":"...","status":"queued","progress":0,"message":""}
event: progress
data: {"task_id":"...","status":"processing","progress":10,"message":"Downloading video..."}
event: progress
data: {"task_id":"...","status":"processing","progress":30,"message":"Generating transcript..."}
... etc ...
event: close
data: {"status":"completed"}
4. Get Task Details
curl http://localhost:8000/tasks/{task_id}
5. Get Clips
curl http://localhost:8000/tasks/{task_id}/clips
π Monitoring Workers
View Worker Logs
# If using separate worker service:
docker-compose logs -f supoclip-worker
# Or check Redis queue status:
docker exec -it supoclip-redis redis-cli
> KEYS arq:*
> LLEN arq:queue
Check Job Status
The arq queue stores job status in Redis. You can inspect with:
docker exec -it supoclip-redis redis-cli
> KEYS arq:job:*
> GET arq:job:{job_id}
π Rollback Plan
If issues arise, you can rollback:
Option 1: Switch Back to Old Main
# docker-compose.yml
supoclip-backend:
command: [".venv/bin/uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"]
Option 2: Keep Both Running
You can run both versions simultaneously on different ports for gradual migration:
- Old:
src.main:appon port 8000 - New:
src.main_refactored:appon port 8001
π― Performance Improvements
Before Refactoring:
- β Task page took 60+ seconds to show title
- β Blocking operations stalled the entire server
- β No progress visibility
- β Jobs lost on restart
After Refactoring:
- β Instant task creation (< 100ms)
- β Real-time progress updates
- β Non-blocking API (video processing in workers)
- β Persistent jobs survive restarts
- β Horizontal scaling (add more workers)
π Troubleshooting
"Connection refused" to Redis
Check Redis is running:
docker-compose ps redis
docker-compose logs redis
Worker not processing jobs
- Check worker is running:
docker-compose ps supoclip-worker
docker-compose logs supoclip-worker
- Check Redis connection:
docker exec supoclip-backend .venv/bin/python -c "import redis; r=redis.Redis(host='redis'); print(r.ping())"
Database migration errors
If the migration fails, run it manually:
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS progress INTEGER DEFAULT 0;
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS progress_message TEXT;
π Next Steps
- Update Frontend: Consume SSE endpoint instead of polling
- Monitoring: Add Prometheus metrics for job queue
- Scaling: Deploy multiple worker instances for parallel processing
- Caching: Add Redis caching for frequently accessed data
- Rate Limiting: Protect API with rate limits
π API Changes
New Endpoints
POST /tasks/- Create task (replaces/start-with-progress)GET /tasks/{task_id}/progress- SSE endpoint for real-time updates
Deprecated Endpoints
POST /start- Use/tasks/insteadPOST /start-with-progress- Use/tasks/instead
Unchanged Endpoints
GET /tasks/{task_id}- Still worksGET /tasks/{task_id}/clips- Still worksGET /fonts- Still worksGET /transitions- Still worksPOST /upload- Still works