fix: 按当前登录调度下载,失效则暂停、批量落盘并改为轮询任务数

This commit is contained in:
2026-10-25 07:34:26 +08:00
parent c8ce1275f1
commit c2f362053c
3 changed files with 514 additions and 216 deletions
+10 -37
View File
@@ -11,7 +11,6 @@ from pathlib import Path
from typing import Any
from fastapi import APIRouter, Body, File, Form, HTTPException, UploadFile
from fastapi.responses import StreamingResponse
from app.features.download.fields import IDENTITY, NETWORKS, cell_columns, columns_for, grid_spec, meta_groups
from app.features.download.ids import parse_upload
@@ -31,13 +30,9 @@ def _bad(message: str, status: int = 400) -> HTTPException:
return HTTPException(status_code=status, detail=message)
def _sse(payload: dict) -> str:
return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
def _spawn(job, client) -> None:
def _spawn(job) -> None:
async def runner() -> None:
await run_download(job, client)
await run_download(job)
task = asyncio.create_task(runner())
job.task = task
@@ -53,8 +48,7 @@ def _spawn(job, client) -> None:
def fill_slots() -> None:
client = state.client
if client is None:
if state.expired or state.client is None or state.user is None:
return
while state.jobs.running_count() < state.jobs.max_concurrent:
waiting = state.jobs.queued_jobs()
@@ -64,7 +58,7 @@ def fill_slots() -> None:
if kind == "wait":
return
if kind == "run":
_spawn(waiting[0], client)
_spawn(waiting[0])
@router.get("/meta")
@@ -107,6 +101,12 @@ async def update_download_settings(body: Any = Body(default=None)) -> dict:
return {"maxConcurrentJobs": limit}
@router.get("/active")
async def active_downloads() -> dict:
state.require_client()
return {"count": state.jobs.running_count()}
@router.get("/jobs")
async def list_jobs() -> dict:
state.require_client()
@@ -290,30 +290,3 @@ async def pause_job(job_id: str) -> dict:
raise _bad(str(exc), 404 if str(exc) == "任务不存在" else 400) from exc
fill_slots()
return job.snapshot()
@router.get("/jobs/{job_id}/events")
async def job_events(job_id: str) -> StreamingResponse:
state.require_client()
try:
job = state.jobs.get(job_id)
except NqiError as exc:
raise _bad(str(exc), 404) from exc
queue: asyncio.Queue = asyncio.Queue()
job.subscribers.append(queue)
async def stream():
try:
yield _sse({"type": "snapshot", **job.snapshot()})
if job.status in {"done", "done_with_errors", "cancelled", "error"} and not job.is_active():
return
while True:
event = await queue.get()
yield _sse(event)
if event.get("type") in {"done", "error", "cancelled"}:
return
finally:
if queue in job.subscribers:
job.subscribers.remove(queue)
return StreamingResponse(stream(), media_type="text/event-stream")