refactor: 预留并行修复所需的共享接口
This commit is contained in:
@@ -6,6 +6,8 @@ import csv
|
||||
import io
|
||||
from pathlib import Path
|
||||
|
||||
from app.shared.ids import normalize_id
|
||||
|
||||
_HEADER_KEYS = {
|
||||
"栅格id",
|
||||
"20米栅格id",
|
||||
@@ -19,19 +21,6 @@ _HEADER_KEYS = {
|
||||
}
|
||||
|
||||
|
||||
def normalize_id(value) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
text = str(value).strip().strip("\ufeff")
|
||||
text = text.translate(str.maketrans("0123456789", "0123456789"))
|
||||
text = "".join(text.split())
|
||||
if text.endswith(".0") and text[:-2].isdigit():
|
||||
text = text[:-2]
|
||||
if not text or not text.isdigit():
|
||||
return ""
|
||||
return text
|
||||
|
||||
|
||||
def _header_index(header: list[str]) -> int | None:
|
||||
for index, name in enumerate(header):
|
||||
key = name.strip().lower().replace(" ", "").replace("_", "")
|
||||
|
||||
@@ -48,6 +48,9 @@ class DownloadJob:
|
||||
listing_done: bool = True
|
||||
last_flush: float = 0.0
|
||||
failures: list[dict[str, str]] = field(default_factory=list)
|
||||
paused_by: str = ""
|
||||
stopping: bool = False
|
||||
failed_tiles: list = field(default_factory=list)
|
||||
subscribers: list[asyncio.Queue] = field(default_factory=list)
|
||||
task: asyncio.Task | None = None
|
||||
cancel_event: asyncio.Event = field(default_factory=asyncio.Event)
|
||||
@@ -62,6 +65,9 @@ class DownloadJob:
|
||||
def is_active(self) -> bool:
|
||||
return self.task is not None and not self.task.done()
|
||||
|
||||
def load_ids(self) -> list[str]:
|
||||
return self.grid_ids
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
@@ -84,6 +90,9 @@ class DownloadJob:
|
||||
"fileBytes": _file_bytes(self.csv_path),
|
||||
"csvPath": str(self.csv_path),
|
||||
"failures": self.failures[-20:],
|
||||
"pausedBy": self.paused_by,
|
||||
"stopping": self.stopping,
|
||||
"failedTiles": list(self.failed_tiles),
|
||||
"createdAt": self.created_at,
|
||||
"name": f"{'5G' if self.network == 'NR' else '4G'} · {self.city_name} · {self.month}",
|
||||
}
|
||||
@@ -185,28 +194,26 @@ class JobManager:
|
||||
total += 1
|
||||
return total
|
||||
|
||||
def hydrate(self) -> None:
|
||||
"""进程重启后,把仍在等待的任务装回内存,空位出现时可以继续排。"""
|
||||
if not DATA_DIR.exists():
|
||||
return
|
||||
for directory in DATA_DIR.iterdir():
|
||||
if not directory.is_dir() or _JOB_ID.fullmatch(directory.name) is None:
|
||||
def suspend_all(self, reason: str, mark: str) -> None:
|
||||
for job in self.jobs.values():
|
||||
if job.status not in {"running", "queued"}:
|
||||
continue
|
||||
if directory.name in self.jobs:
|
||||
continue
|
||||
path = directory / "job.json"
|
||||
if not path.exists():
|
||||
continue
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
continue
|
||||
if data.get("status") != "queued" or data.get("id") != directory.name:
|
||||
continue
|
||||
try:
|
||||
self.jobs[directory.name] = self._load(directory.name)
|
||||
except NqiError:
|
||||
if job.status == "running":
|
||||
job.run_event.clear()
|
||||
job.status = "paused"
|
||||
job.paused_by = mark
|
||||
job.message = reason
|
||||
job.save()
|
||||
|
||||
def resume_marked(self, mark: str) -> None:
|
||||
for job in self.jobs.values():
|
||||
if job.paused_by != mark:
|
||||
continue
|
||||
job.paused_by = ""
|
||||
if job.status == "paused":
|
||||
job.status = "queued"
|
||||
job.message = "等待中"
|
||||
job.save()
|
||||
|
||||
def queued_jobs(self) -> list[DownloadJob]:
|
||||
waiting = [job for job in self.jobs.values() if job.status == "queued"]
|
||||
|
||||
@@ -76,6 +76,12 @@ class CsvJournal:
|
||||
self.completed.add(grid_id)
|
||||
return len(rows)
|
||||
|
||||
def commit_many(self, items) -> int:
|
||||
written = 0
|
||||
for grid_id, rows in items:
|
||||
written += self.write_rows(grid_id, rows)
|
||||
return written
|
||||
|
||||
def close(self) -> None:
|
||||
with self._lock:
|
||||
if self._file is not None:
|
||||
|
||||
@@ -53,7 +53,6 @@ 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:
|
||||
|
||||
Reference in New Issue
Block a user