Files
NqiTools/backend/app/features/download/router.py
T

290 lines
8.8 KiB
Python

"""栅格下载接口。工单、回单等功能各自放在 features 下,不写进这里。"""
from __future__ import annotations
import asyncio
import json
import logging
import re
import shutil
from pathlib import Path
from fastapi import APIRouter, File, Form, HTTPException, UploadFile
from fastapi.responses import FileResponse, 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
from app.features.download.jobs import run_download
from app.platform.client import NqiError
from app.platform.constants import CITIES
from app.shared.state import state
logger = logging.getLogger("nqi.download")
router = APIRouter(prefix="/api/download", tags=["download"])
MONTH_RE = re.compile(r"^\d{4}-(0[1-9]|1[0-2])$")
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:
async def runner() -> None:
await run_download(job, client)
task = asyncio.create_task(runner())
job.task = task
def _done(finished: asyncio.Task) -> None:
if not finished.cancelled():
error = finished.exception()
if error:
logger.exception("下载任务异常", exc_info=error)
fill_slots()
task.add_done_callback(_done)
def fill_slots() -> None:
client = state.client
if client is None:
return
state.jobs.hydrate()
while state.jobs.running_count() < state.jobs.max_concurrent:
waiting = state.jobs.queued_jobs()
if not waiting:
return
kind = state.jobs.place(waiting[0])
if kind == "wait":
return
if kind == "run":
_spawn(waiting[0], client)
@router.get("/meta")
async def meta() -> dict:
return {
"networks": list(NETWORKS),
"cities": CITIES,
"groups": {"NR": meta_groups("NR"), "LTE": meta_groups("LTE")},
"fixed": {
"grid": [label for label, _field in IDENTITY],
"cell": {
"NR": [column.label for column in cell_columns("NR")],
"LTE": [column.label for column in cell_columns("LTE")],
},
},
}
@router.get("/settings")
async def download_settings() -> dict:
state.require_client()
return {"maxConcurrentJobs": state.jobs.max_concurrent}
@router.put("/settings")
async def update_download_settings(body: dict) -> dict:
state.require_client()
try:
value = int(body.get("maxConcurrentJobs"))
except (TypeError, ValueError) as exc:
raise _bad("同时任务数不正确") from exc
limit = state.jobs.set_limit(value)
fill_slots()
return {"maxConcurrentJobs": limit}
@router.get("/jobs")
async def list_jobs() -> dict:
state.require_client()
fill_slots()
return {"jobs": state.jobs.list_jobs()}
@router.get("/jobs/{job_id}")
async def get_job(job_id: str) -> dict:
state.require_client()
try:
job = state.jobs.get(job_id)
except NqiError as exc:
raise _bad(str(exc), 404) from exc
return job.snapshot()
@router.post("/jobs")
async def create_job(
file: UploadFile | None = File(None),
network: str = Form(...),
city_code: str = Form(...),
month: str = Form(...),
groups: str = Form("[]"),
concurrency: int = Form(8),
output_dir: str = Form(""),
grid_size: str = Form("GRID20"),
) -> dict:
state.require_client()
if network not in {"NR", "LTE"}:
raise _bad("网络只支持 4G 或 5G")
city = next((item for item in CITIES if item["code"] == city_code), None)
if city is None:
raise _bad("请选择地市")
if not MONTH_RE.fullmatch(month):
raise _bad("月份格式应为 YYYY-MM")
try:
selected = json.loads(groups)
except json.JSONDecodeError as exc:
raise _bad("下载项目格式不正确") from exc
if not isinstance(selected, list) or any(not isinstance(item, str) for item in selected):
raise _bad("下载项目格式不正确")
try:
columns_for(network, selected, grid_size)
size_name, _id_label, _id_field = grid_spec(grid_size)
except ValueError as exc:
raise _bad(str(exc)) from exc
workers = min(32, max(1, int(concurrency)))
label = "5G" if network == "NR" else "4G"
target: Path | None = None
if output_dir.strip():
folder = Path(output_dir.strip())
folder.mkdir(parents=True, exist_ok=True)
target = folder / f"栅格_{label}_{size_name}_{city['name']}_{month}.csv"
whole_city = file is None or not file.filename
grid_ids: list[str] = []
duplicates = 0
if not whole_city:
suffix = Path(file.filename or "").suffix.lower()
if suffix != ".csv":
raise _bad("区域表只支持 CSV")
raw = await file.read()
if not raw:
raise _bad("区域表是空的")
if len(raw) > 20 * 1024 * 1024:
raise _bad("区域表不能超过 20MB")
job = state.jobs.create(
network=network,
city_code=city["code"],
city_name=city["name"],
month=month,
groups=selected,
concurrency=workers,
grid_ids=[],
csv_path=target,
grid_size=grid_size,
whole_city=whole_city,
)
if not whole_city:
source = job.directory / "source.csv"
source.write_bytes(raw)
try:
grid_ids, duplicates = parse_upload(source)
except Exception as exc:
shutil.rmtree(job.directory, ignore_errors=True)
state.jobs.jobs.pop(job.id, None)
raise _bad(f"读取区域表失败:{exc}") from exc
if not grid_ids:
shutil.rmtree(job.directory, ignore_errors=True)
state.jobs.jobs.pop(job.id, None)
raise _bad("区域表里没有栅格 ID")
job.grid_ids = grid_ids
job.duplicate_count = duplicates
if duplicates:
job.message = f"已去掉 {duplicates} 个重复栅格"
elif whole_city:
job.message = "准备下载整个地市"
job.status = "queued"
job.save()
fill_slots()
if job.status == "queued":
job.message = "等待中"
job.save()
return job.snapshot()
@router.post("/jobs/{job_id}/cancel")
async def cancel_job(job_id: str) -> dict:
state.require_client()
try:
job = state.jobs.get(job_id)
except NqiError as exc:
raise _bad(str(exc), 404) from exc
try:
state.jobs.request_stop(job)
except NqiError as exc:
raise _bad(str(exc)) from exc
return job.snapshot()
@router.post("/jobs/{job_id}/resume")
async def resume_job(job_id: str) -> dict:
state.require_client()
try:
job = state.jobs.get(job_id)
except NqiError as exc:
raise _bad(str(exc), 404) from exc
if job.status == "done":
raise _bad("这个任务已经完成")
if job.status == "running" and job.is_active():
raise _bad("这个任务正在下载")
if job.status != "queued":
job.status = "queued"
job.message = "等待中"
job.save()
fill_slots()
return job.snapshot()
@router.post("/jobs/{job_id}/pause")
async def pause_job(job_id: str) -> dict:
state.require_client()
try:
job = state.jobs.get(job_id)
state.jobs.pause(job)
except NqiError as exc:
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")
@router.get("/jobs/{job_id}/file")
async def job_file(job_id: str) -> FileResponse:
state.require_client()
try:
job = state.jobs.get(job_id)
except NqiError as exc:
raise _bad(str(exc), 404) from exc
if not job.csv_path.exists():
raise _bad("文件还没有生成", 404)
return FileResponse(job.csv_path, filename=job.csv_path.name)