fix: 下载文件改由任务自己的线程读写,消除并发竞争和漏下载

This commit is contained in:
2026-10-25 09:27:26 +08:00
parent 2aa8990b63
commit d3e553155d
13 changed files with 1151 additions and 509 deletions
+12 -18
View File
@@ -1,3 +1,4 @@
import asyncio
import csv
import io
import json
@@ -8,6 +9,7 @@ from pathlib import Path
from fastapi.testclient import TestClient
from app.features.download import jobs as job_module
from app.shared import files as files_module
from app.features.download.ids import parse_table
from app.features.download.jobs import JobManager, ensure_output_dir
from app.features.download.journal import CsvJournal, explain_os_error
@@ -206,7 +208,7 @@ def test_ids_file_replaces_grid_ids_and_release_reloads(tmp_path: Path, monkeypa
def test_save_retries_permission_error_and_corrupt_record(tmp_path: Path, monkeypatch):
monkeypatch.setattr(job_module, "DATA_DIR", tmp_path / "jobs")
monkeypatch.setattr(job_module, "DOWNLOAD_ROOT", tmp_path / "downloads")
monkeypatch.setattr(job_module.time, "sleep", lambda _seconds: None)
monkeypatch.setattr(files_module.time, "sleep", lambda _seconds: None)
job = JobManager().create(
network="NR",
city_code="JM",
@@ -229,7 +231,7 @@ def test_save_retries_permission_error_and_corrupt_record(tmp_path: Path, monkey
raise error
return real(src, dst)
monkeypatch.setattr(job_module.os, "replace", flaky)
monkeypatch.setattr(files_module.os, "replace", flaky)
job.message = "仍在"
job.save()
assert calls["n"] == 3
@@ -248,7 +250,11 @@ def test_save_retries_permission_error_and_corrupt_record(tmp_path: Path, monkey
def test_startup_marks_leftover_jobs_interrupted_and_list_skips_progress(tmp_path: Path, monkeypatch):
jobs = tmp_path / "jobs"
monkeypatch.setattr(job_module, "DATA_DIR", jobs)
monkeypatch.setattr(job_module, "_progress_stats", lambda _directory: (_ for _ in ()).throw(AssertionError("不应读取进度")))
monkeypatch.setattr(
CsvJournal,
"_scan_progress",
lambda *_args: (_ for _ in ()).throw(AssertionError("不应读取进度")),
)
for index, status in enumerate(("running", "paused", "queued"), start=1):
_write_record(
jobs / f"2026010101010{index}",
@@ -306,7 +312,7 @@ def test_delete_rejects_active_jobs_and_optional_files(tmp_path: Path, monkeypat
)
download_dir = kept.csv_path.parent
assert download_dir == tmp_path / "downloads" / kept.id
manager.delete(kept.id, files=False)
asyncio.run(manager.delete(kept.id, files=False))
assert not kept.directory.exists()
assert download_dir.exists()
@@ -322,7 +328,7 @@ def test_delete_rejects_active_jobs_and_optional_files(tmp_path: Path, monkeypat
whole_city=True,
)
removed_dir = removed.csv_path.parent
manager.delete(removed.id, files=True)
asyncio.run(manager.delete(removed.id, files=True))
assert not removed.directory.exists()
assert not removed_dir.exists()
@@ -345,7 +351,7 @@ def test_delete_rejects_active_jobs_and_optional_files(tmp_path: Path, monkeypat
active.task = Alive()
active.status = "running"
try:
manager.delete(active.id, files=True)
asyncio.run(manager.delete(active.id, files=True))
except NqiError as exc:
assert "不能删除" in str(exc)
else:
@@ -503,18 +509,6 @@ def test_legacy_grid_ids_can_still_be_loaded(tmp_path: Path, monkeypatch):
assert (directory / "ids.txt").read_text(encoding="utf-8").splitlines() == ["3", "4"]
def test_progress_stats_uses_mtime_cache(tmp_path: Path, monkeypatch):
progress = tmp_path / "progress.jsonl"
progress.write_bytes(b'{"id": 1, "offset": 3, "rows": 2}\n{"id": 2, "offset": 5, "rows": 1}\n')
assert job_module._progress_stats(tmp_path) == (2, 3)
def fail_open(*_args, **_kwargs):
raise AssertionError("缓存命中后不应再读进度")
monkeypatch.setattr(Path, "open", fail_open)
assert job_module._progress_stats(tmp_path) == (2, 3)
def _post_job(client: TestClient, *, output_dir: str, filename: str | None = None, content: bytes | None = None, grid_size: str = "GRID20"):
data = {
"network": "NR",