Repository navigation
Expand file tree
/
Copy pathqueue.py
More file actions
580 lines (539 loc) · 21.2 KB
/
Copy pathqueue.py
File metadata and controls
580 lines (539 loc) · 21.2 KB
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
"""SQLite-backed job queue with progress/ETA, restart recovery, and cancellation."""
from __future__ import annotations
import json
import os
import sqlite3
import subprocess
import threading
import uuid
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from .config import Config, apply_overrides
from .pipeline import PipelineCancelledError, run_pipeline, validate_source
TERMINAL_STATUSES = {"completed", "failed", "cancelled", "partial", "interrupted"}
DEFAULT_POLL_AFTER_SEC = 3
def _utc_now() -> str:
return datetime.now(UTC).isoformat()
def _is_pid_alive(pid: int | None) -> bool:
if pid is None or pid <= 0:
return False
try:
os.kill(pid, 0)
return True
except ProcessLookupError:
return False
except PermissionError:
return True
except OSError:
return False
def _artifact_stem(name: str) -> str:
lower = name.lower()
for suffix in (
".meta.json",
".cover.jpg",
".post.txt",
".kit.zip",
".fcpxml",
".edl",
".mp4",
".json",
".jpg",
".zip",
".txt",
):
if lower.endswith(suffix):
return name[: -len(suffix)]
return Path(name).stem
class JobQueue:
"""SQLite job queue with bounded worker pool."""
def __init__(
self,
config: Config,
processor: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
*,
recover_orphans: bool = True,
) -> None:
self.config = config
self.db_path: Path = config.resolve_path(config.queue.db_path)
self._max_workers = max(1, min(2, int(config.queue.max_workers)))
self._processor = processor or self._default_processor
self._recover_orphans = bool(recover_orphans)
self._executor = ThreadPoolExecutor(max_workers=self._max_workers, thread_name_prefix="dz-worker")
self._lock = threading.Lock()
self._cancel_events: dict[str, threading.Event] = {}
self._active_procs: dict[str, set[subprocess.Popen[Any]]] = {}
self._partial_clips: dict[str, list[dict[str, Any]]] = {}
self._has_legacy_tier_col = False
self._init_db()
def _connect(self) -> sqlite3.Connection:
self.db_path.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(str(self.db_path), timeout=30.0)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA busy_timeout=30000;")
return conn
def _init_db(self) -> None:
conn = self._connect()
try:
conn.execute("PRAGMA journal_mode=WAL;")
conn.execute("PRAGMA synchronous=NORMAL;")
conn.execute(
"""
CREATE TABLE IF NOT EXISTS jobs (
job_id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
source TEXT NOT NULL,
status TEXT NOT NULL,
stage TEXT NOT NULL DEFAULT 'queued',
progress REAL NOT NULL DEFAULT 0.0,
eta_sec REAL,
params_json TEXT,
owner_pid INTEGER,
result_json TEXT,
error TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)
"""
)
# Safe schema migration for existing DBs created before newer columns existed.
cols = {row["name"] for row in conn.execute("PRAGMA table_info(jobs)").fetchall()}
self._has_legacy_tier_col = "tier" in cols
if "stage" not in cols:
conn.execute("ALTER TABLE jobs ADD COLUMN stage TEXT NOT NULL DEFAULT 'queued'")
if "eta_sec" not in cols:
conn.execute("ALTER TABLE jobs ADD COLUMN eta_sec REAL")
if "params_json" not in cols:
conn.execute("ALTER TABLE jobs ADD COLUMN params_json TEXT")
if "owner_pid" not in cols:
conn.execute("ALTER TABLE jobs ADD COLUMN owner_pid INTEGER")
# Recover orphaned in-flight rows from dead/crashed server processes when enabled.
if self._recover_orphans:
rows = conn.execute(
"SELECT job_id, owner_pid FROM jobs WHERE status IN ('queued', 'running')"
).fetchall()
stale_ids = [
r["job_id"]
for r in rows
if r["owner_pid"] is None or not _is_pid_alive(int(r["owner_pid"]))
]
if stale_ids:
now = _utc_now()
placeholders = ",".join("?" for _ in stale_ids)
conn.execute(
f"""
UPDATE jobs
SET status = 'interrupted',
stage = 'interrupted',
error = COALESCE(error, 'Interrupted by server restart'),
eta_sec = NULL,
updated_at = ?
WHERE job_id IN ({placeholders})
AND status IN ('queued', 'running')
""",
(now, *stale_ids),
)
conn.commit()
finally:
conn.close()
def is_cancelled(self, job_id: str) -> bool:
with self._lock:
ev = self._cancel_events.get(job_id)
return bool(ev and ev.is_set())
def register_process(self, job_id: str, proc: subprocess.Popen[Any]) -> None:
should_kill = False
with self._lock:
ev = self._cancel_events.get(job_id)
if ev is not None and ev.is_set():
should_kill = True
else:
self._active_procs.setdefault(job_id, set()).add(proc)
if should_kill:
self._terminate_proc(proc)
def unregister_process(self, job_id: str, proc: subprocess.Popen[Any]) -> None:
with self._lock:
procs = self._active_procs.get(job_id)
if procs is not None:
procs.discard(proc)
@staticmethod
def _terminate_proc(proc: subprocess.Popen[Any]) -> None:
try:
if proc.poll() is not None:
return
proc.terminate()
try:
proc.wait(timeout=2.0)
except subprocess.TimeoutExpired:
proc.kill()
try:
proc.wait(timeout=3.0)
except subprocess.TimeoutExpired:
pass
except OSError:
pass
def report_progress(
self,
job_id: str,
stage: str,
progress: float,
eta_sec: float | None = None,
) -> None:
if self.is_cancelled(job_id):
return
pct = max(0.0, min(1.0, float(progress)))
conn = self._connect()
try:
conn.execute(
"""
UPDATE jobs
SET stage = ?, progress = ?, eta_sec = ?, updated_at = ?
WHERE job_id = ? AND status IN ('queued', 'running')
""",
(stage, pct, eta_sec, _utc_now(), job_id),
)
conn.commit()
finally:
conn.close()
def _record_partial_clip(self, job_id: str, clip_item: dict[str, Any]) -> None:
with self._lock:
clips = self._partial_clips.setdefault(job_id, [])
clips.append(clip_item)
snapshot = list(clips)
conn = self._connect()
try:
conn.execute(
"""
UPDATE jobs
SET result_json = ?, updated_at = ?
WHERE job_id = ? AND status IN ('queued', 'running')
""",
(json.dumps({"ok": True, "clips": snapshot}), _utc_now(), job_id),
)
conn.commit()
finally:
conn.close()
def _default_processor(self, payload: dict[str, Any]) -> dict[str, Any]:
job_id = str(payload["job_id"])
cfg = apply_overrides(self.config, payload.get("overrides"))
return run_pipeline(
source=payload["source"],
config=cfg,
mode=payload.get("mode", "greenscreen"),
max_clips=payload.get("max_clips"),
require_absolute_local=True,
export_kits=bool(payload.get("export_kits", False)),
fresh=bool(payload.get("fresh", False)),
progress_cb=lambda st, pct, eta: self.report_progress(job_id, st, pct, eta),
cancel_check=lambda: self.is_cancelled(job_id),
on_process_start=lambda proc: self.register_process(job_id, proc),
on_process_end=lambda proc: self.unregister_process(job_id, proc),
on_clip_done=lambda item: self._record_partial_clip(job_id, item),
)
def enqueue(
self,
source: str,
user_id: str = "default",
mode: str = "greenscreen",
max_clips: int | None = None,
overrides: dict[str, Any] | None = None,
require_absolute_local: bool = True,
export_kits: bool = False,
fresh: bool = False,
) -> dict[str, Any]:
ok, err = validate_source(source, require_absolute_local=require_absolute_local)
if not ok:
return {"error": err}
job_id = uuid.uuid4().hex[:12]
now = _utc_now()
owner_pid = os.getpid()
params_json = json.dumps(
{
"mode": mode,
"max_clips": max_clips,
"overrides": overrides,
"export_kits": export_kits,
"fresh": fresh,
}
)
conn = self._connect()
try:
if self._has_legacy_tier_col:
conn.execute(
"""
INSERT INTO jobs (job_id, user_id, tier, source, status, stage, progress, eta_sec, params_json, owner_pid, result_json, error, created_at, updated_at)
VALUES (?, ?, '', ?, 'queued', 'queued', 0.0, NULL, ?, ?, NULL, NULL, ?, ?)
""",
(job_id, user_id, source, params_json, owner_pid, now, now),
)
else:
conn.execute(
"""
INSERT INTO jobs (job_id, user_id, source, status, stage, progress, eta_sec, params_json, owner_pid, result_json, error, created_at, updated_at)
VALUES (?, ?, ?, 'queued', 'queued', 0.0, NULL, ?, ?, NULL, NULL, ?, ?)
""",
(job_id, user_id, source, params_json, owner_pid, now, now),
)
conn.commit()
finally:
conn.close()
with self._lock:
self._cancel_events[job_id] = threading.Event()
self._active_procs[job_id] = set()
self._partial_clips[job_id] = []
payload = {
"job_id": job_id,
"user_id": user_id,
"source": source,
"mode": mode,
"max_clips": max_clips,
"overrides": overrides,
"export_kits": export_kits,
"fresh": fresh,
}
self._executor.submit(self._run_job, job_id, payload)
return {
"ok": True,
"job_id": job_id,
"status": "queued",
"stage": "queued",
"poll_after_sec": DEFAULT_POLL_AFTER_SEC,
"user_id": user_id,
}
def _update_job(
self,
job_id: str,
status: str,
progress: float,
result_json: str | None = None,
error: str | None = None,
stage: str | None = None,
eta_sec: float | None = None,
) -> None:
with self._lock:
conn = self._connect()
try:
conn.execute(
"""
UPDATE jobs
SET status = ?, stage = ?, progress = ?, eta_sec = ?, result_json = ?, error = ?, updated_at = ?
WHERE job_id = ?
AND status NOT IN ('cancelled', 'completed', 'failed', 'partial', 'interrupted')
""",
(status, stage or status, progress, eta_sec, result_json, error, _utc_now(), job_id),
)
conn.commit()
finally:
conn.close()
def update_result_json(self, job_id: str, result: dict[str, Any]) -> None:
"""Persist enriched result_json (e.g. on-demand Publish Kits) without altering job status."""
with self._lock:
conn = self._connect()
try:
conn.execute(
"UPDATE jobs SET result_json = ?, updated_at = ? WHERE job_id = ?",
(json.dumps(result), _utc_now(), job_id),
)
conn.commit()
finally:
conn.close()
def find_artifact_owners(self, filename: str) -> set[str]:
"""Return user_ids whose jobs produced filename or a sibling artifact with the same clip stem."""
target_name = Path(filename).name
target_stem = _artifact_stem(target_name)
owners: set[str] = set()
conn = self._connect()
try:
rows = conn.execute(
"SELECT user_id, result_json FROM jobs WHERE result_json IS NOT NULL"
).fetchall()
finally:
conn.close()
artifact_keys = ("clip", "mp4", "meta", "cover", "kit_path", "edl", "edl_path", "fcpxml", "fcpxml_path", "post_file")
for row in rows:
try:
res = json.loads(row["result_json"])
except (TypeError, ValueError):
continue
if not isinstance(res, dict):
continue
clips = res.get("clips")
items: list[dict[str, Any]] = [res]
if isinstance(clips, list):
items.extend(c for c in clips if isinstance(c, dict))
for item in items:
for key in artifact_keys:
val = item.get(key)
if not isinstance(val, str) or not val:
continue
art_name = Path(val).name
if art_name == target_name or _artifact_stem(art_name) == target_stem:
owners.add(str(row["user_id"]))
break
return owners
def _run_job(self, job_id: str, payload: dict[str, Any]) -> None:
if self.is_cancelled(job_id):
self._finalize_cancelled(job_id)
return
self._update_job(job_id, "running", 0.05, stage="starting")
try:
result = self._processor(payload)
if self.is_cancelled(job_id) or (isinstance(result, dict) and result.get("status") == "cancelled"):
self._finalize_cancelled(job_id, result if isinstance(result, dict) else None)
elif isinstance(result, dict) and "error" in result and not result.get("ok"):
self._update_job(
job_id,
"failed",
1.0,
result_json=json.dumps(result) if result.get("clips") else None,
error=str(result["error"]),
stage="failed",
eta_sec=0.0,
)
elif isinstance(result, dict) and result.get("status") == "partial":
errs = result.get("errors") or []
err_summary = f"{len(errs)} clip(s) failed" if errs else "Partial completion"
self._update_job(
job_id,
"partial",
1.0,
result_json=json.dumps(result),
error=err_summary,
stage="partial",
eta_sec=0.0,
)
else:
self._update_job(
job_id,
"completed",
1.0,
result_json=json.dumps(result),
stage="completed",
eta_sec=0.0,
)
except PipelineCancelledError:
self._finalize_cancelled(job_id)
except Exception as exc: # noqa: BLE001
if self.is_cancelled(job_id):
self._finalize_cancelled(job_id)
else:
self._update_job(job_id, "failed", 1.0, error=str(exc), stage="failed", eta_sec=0.0)
finally:
with self._lock:
self._cancel_events.pop(job_id, None)
self._active_procs.pop(job_id, None)
self._partial_clips.pop(job_id, None)
def _finalize_cancelled(self, job_id: str, result: dict[str, Any] | None = None) -> None:
with self._lock:
saved_clips = list(self._partial_clips.get(job_id, []))
payload = result or {}
if saved_clips and not payload.get("clips"):
payload = {**payload, "clips": saved_clips}
res_json = json.dumps(payload) if payload.get("clips") else None
self._update_job(
job_id,
"cancelled",
1.0,
result_json=res_json,
error="Cancelled by user",
stage="cancelled",
eta_sec=0.0,
)
def cancel_job(self, job_id: str, user_id: str | None = None) -> dict[str, Any]:
"""Cancel an active job, terminate child FFmpeg/yt-dlp procs, and keep any finished clips."""
cur = self.get_status(job_id)
if not cur.get("ok"):
return cur
if user_id is not None and cur.get("user_id") != user_id:
return {"error": f"Job not found: {job_id}"}
if cur["status"] in TERMINAL_STATUSES:
return {
"ok": True,
"job_id": job_id,
"status": cur["status"],
"already_terminal": True,
"result": cur.get("result"),
}
procs_to_kill: list[subprocess.Popen[Any]] = []
with self._lock:
ev = self._cancel_events.get(job_id)
if ev is None:
ev = threading.Event()
self._cancel_events[job_id] = ev
ev.set()
procs_to_kill = list(self._active_procs.get(job_id, set()))
for proc in procs_to_kill:
self._terminate_proc(proc)
self._finalize_cancelled(job_id, cur.get("result"))
updated = self.get_status(job_id)
return {
"ok": True,
"job_id": job_id,
"status": updated.get("status", "cancelled"),
"terminated_processes": len(procs_to_kill),
"result": updated.get("result"),
}
def get_status(self, job_id: str) -> dict[str, Any]:
conn = self._connect()
try:
row = conn.execute("SELECT * FROM jobs WHERE job_id = ?", (job_id,)).fetchone()
finally:
conn.close()
if row is None:
return {"error": f"Job not found: {job_id}"}
result = json.loads(row["result_json"]) if row["result_json"] else None
status = row["status"]
poll_after = 0 if status in TERMINAL_STATUSES else DEFAULT_POLL_AFTER_SEC
return {
"ok": True,
"job_id": row["job_id"],
"user_id": row["user_id"],
"source": row["source"],
"status": status,
"stage": row["stage"] or status,
"progress": row["progress"],
"eta_sec": row["eta_sec"],
"poll_after_sec": poll_after,
"result": result,
"error": row["error"],
"created_at": row["created_at"],
"updated_at": row["updated_at"],
}
def list_jobs(self, user_id: str | None = None, limit: int = 20) -> dict[str, Any]:
lim = max(1, min(100, int(limit)))
conn = self._connect()
try:
if user_id:
rows = conn.execute(
"SELECT job_id, user_id, source, status, stage, progress, eta_sec, error, created_at, updated_at "
"FROM jobs WHERE user_id = ? ORDER BY created_at DESC LIMIT ?",
(user_id, lim),
).fetchall()
else:
rows = conn.execute(
"SELECT job_id, user_id, source, status, stage, progress, eta_sec, error, created_at, updated_at "
"FROM jobs ORDER BY created_at DESC LIMIT ?",
(lim,),
).fetchall()
finally:
conn.close()
return {
"ok": True,
"jobs": [dict(r) for r in rows],
}
def shutdown(self, wait: bool = True) -> None:
if not wait:
with self._lock:
for ev in self._cancel_events.values():
ev.set()
procs = [p for ps in self._active_procs.values() for p in ps]
for proc in procs:
self._terminate_proc(proc)
self._executor.shutdown(wait=False)
return
self._executor.shutdown(wait=True)
with self._lock:
procs = [p for ps in self._active_procs.values() for p in ps]
for proc in procs:
self._terminate_proc(proc)