Monteeq CI commited on
Commit
abb5911
·
1 Parent(s): b7698ad

🚀 Deploy from GitHub @ e4b7162079f432dfcd38ff17b3c6b5388851de53

Browse files

Triggered by: Smasduq
Message: Fix background task cleanup on video stream proxy

BackgroundTasks([resp.aclose, client.aclose]) passed bare callables,
bypassing add_task() and leaving no .func attribute on the tasks. Newer
FastAPI versions read task.func for telemetry, raising AttributeError at
the end of every /stream and /stream-res response.

Files changed (1) hide show
  1. app/api/v1/endpoints/videos.py +16 -2
app/api/v1/endpoints/videos.py CHANGED
@@ -35,6 +35,20 @@ class VideoStatus(str, Enum):
35
  READY = "ready"
36
  FAILED = "failed"
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  def get_video_db(db: Session, video_id: str) -> Optional[Video]:
39
  if isinstance(video_id, str) and not video_id.isdigit():
40
  return db.query(Video).filter(Video.public_id == video_id).first()
@@ -294,7 +308,7 @@ async def stream_video(video_id: str, request: Request, db: Session = Depends(ge
294
  resp.aiter_bytes(chunk_size=65536),
295
  status_code=resp.status_code,
296
  headers=response_headers,
297
- background=BackgroundTasks([resp.aclose, client.aclose])
298
  )
299
 
300
  return await get_stream()
@@ -376,7 +390,7 @@ async def stream_video_resolution(
376
  resp.aiter_bytes(chunk_size=65536),
377
  status_code=resp.status_code,
378
  headers=response_headers,
379
- background=BackgroundTasks([resp.aclose, client.aclose])
380
  )
381
 
382
  return await get_res_stream()
 
35
  READY = "ready"
36
  FAILED = "failed"
37
 
38
+ def _stream_cleanup(*resources) -> BackgroundTasks:
39
+ """Release upstream stream/response resources once the response is fully sent.
40
+
41
+ Tasks must be registered via ``add_task`` (which wraps each callable in a
42
+ ``BackgroundTask``). Passing bare callables to ``BackgroundTasks([...])``
43
+ bypasses that wrapping and breaks newer FastAPI versions, which read
44
+ ``task.func`` when instrumenting background tasks.
45
+ """
46
+ tasks = BackgroundTasks()
47
+ for resource in resources:
48
+ tasks.add_task(resource.aclose)
49
+ return tasks
50
+
51
+
52
  def get_video_db(db: Session, video_id: str) -> Optional[Video]:
53
  if isinstance(video_id, str) and not video_id.isdigit():
54
  return db.query(Video).filter(Video.public_id == video_id).first()
 
308
  resp.aiter_bytes(chunk_size=65536),
309
  status_code=resp.status_code,
310
  headers=response_headers,
311
+ background=_stream_cleanup(resp, client)
312
  )
313
 
314
  return await get_stream()
 
390
  resp.aiter_bytes(chunk_size=65536),
391
  status_code=resp.status_code,
392
  headers=response_headers,
393
+ background=_stream_cleanup(resp, client)
394
  )
395
 
396
  return await get_res_stream()