File size: 8,149 Bytes
851e5ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
> Historical migration notes. The migration is complete: `src.main:app` is now canonical and `src.main_refactored:app` is a compatibility alias. See [architecture](../docs/architecture.md) 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.

```bash
# 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

```bash
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`:

```bash
docker-compose build backend
```

#### Option B: Add Worker Service (Recommended)

Edit `docker-compose.yml` to add a separate worker service:

```yaml
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:

```dockerfile
# 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`:

```yaml
supoclip-backend:
  command: [".venv/bin/uvicorn", "src.main_refactored:app", "--host", "0.0.0.0", "--port", "8000"]
```

### Step 5: Restart Services

```bash
docker-compose down
docker-compose up -d --build
```

## πŸ§ͺ Testing the Refactored System

### 1. Check Health Endpoints

```bash
# 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

```bash
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:
```json
{
  "task_id": "uuid-here",
  "job_id": "job-uuid",
  "message": "Task created and queued for processing"
}
```

### 3. Watch Real-time Progress (SSE)

```bash
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

```bash
curl http://localhost:8000/tasks/{task_id}
```

### 5. Get Clips

```bash
curl http://localhost:8000/tasks/{task_id}/clips
```

## πŸ“Š Monitoring Workers

### View Worker Logs

```bash
# 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:

```bash
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

```yaml
# 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:app` on port 8000
- New: `src.main_refactored:app` on 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:
```bash
docker-compose ps redis
docker-compose logs redis
```

### Worker not processing jobs

1. Check worker is running:
```bash
docker-compose ps supoclip-worker
docker-compose logs supoclip-worker
```

2. Check Redis connection:
```bash
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:
```sql
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

1. **Update Frontend**: Consume SSE endpoint instead of polling
2. **Monitoring**: Add Prometheus metrics for job queue
3. **Scaling**: Deploy multiple worker instances for parallel processing
4. **Caching**: Add Redis caching for frequently accessed data
5. **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/` instead
- `POST /start-with-progress` - Use `/tasks/` instead

### Unchanged Endpoints

- `GET /tasks/{task_id}` - Still works
- `GET /tasks/{task_id}/clips` - Still works
- `GET /fonts` - Still works
- `GET /transitions` - Still works
- `POST /upload` - Still works