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
+5
View File
@@ -1,6 +1,7 @@
"""在导入 app 之前把数据和下载目录指到临时目录。"""
import os
import shutil
import sys
import tempfile
from pathlib import Path
@@ -24,3 +25,7 @@ def pytest_configure() -> None:
raise RuntimeError("DOWNLOAD_ROOT 没有使用 NQI_DOWNLOAD_DIR")
if DOWNLOAD_ROOT.exists():
raise RuntimeError("导入时不应创建下载目录")
def pytest_unconfigure() -> None:
shutil.rmtree(_ROOT, ignore_errors=True)
+37 -6
View File
@@ -16,7 +16,9 @@ from app.features.download.journal import CsvJournal
from app.features.download.router import active_downloads, router
from app.features.download.rows import build_rows
from app.features.download.spool import IdSpool
from app.features.download import jobs as job_module
from app.features.download import spool as spool_module
from app.shared import files as files_module
from app.platform.client import (
MIN_TILE_WIDTH,
NqiAuthError,
@@ -326,10 +328,10 @@ async def _server_error_is_retried(monkeypatch):
def test_spool_keeps_downloading_when_meta_replace_is_denied(monkeypatch, tmp_path: Path):
sleeps: list[float] = []
monkeypatch.setattr(spool_module.time, "sleep", lambda seconds: sleeps.append(seconds))
monkeypatch.setattr(files_module.time, "sleep", lambda seconds: sleeps.append(seconds))
spool = IdSpool(tmp_path)
spool.open()
real = spool_module.os.replace
real = files_module.os.replace
calls = {"n": 0}
def flaky(src, dst):
@@ -338,13 +340,39 @@ def test_spool_keeps_downloading_when_meta_replace_is_denied(monkeypatch, tmp_pa
raise PermissionError(13, "Access is denied", str(src), 5)
real(src, dst)
monkeypatch.setattr(spool_module.os, "replace", flaky)
monkeypatch.setattr(files_module.os, "replace", flaky)
assert spool.add("10") is True
spool.flush()
assert spool.committed == 1
assert IdSpool._peek(tmp_path)["committed"] == 1
assert IdSpool.read_meta(tmp_path)["committed"] == 1
assert calls["n"] == 2
assert sleeps
spool.close()
def test_spool_flush_failure_keeps_ids_and_trims_tail(monkeypatch, tmp_path: Path):
spool = IdSpool(tmp_path)
spool.open()
real = spool_module.os.fsync
failed = {"n": 0}
def fail_once(fd):
if fd == spool._file.fileno() and failed["n"] == 0:
failed["n"] += 1
raise OSError(28, "No space left on device")
return real(fd)
monkeypatch.setattr(spool_module.os, "fsync", fail_once)
assert spool.add("7") and spool.add("8")
with pytest.raises(OSError):
spool.flush()
assert spool.committed == 0
assert (tmp_path / "ids.spool").stat().st_size == 0
spool.flush()
assert spool.committed == 2
spool.mark_complete()
assert spool.pull() == ["7", "8"]
spool.close()
def test_spool_writer_serves_flush_and_read_together(tmp_path: Path):
@@ -359,7 +387,6 @@ def test_spool_writer_serves_flush_and_read_together(tmp_path: Path):
spool.add(str(index))
if index % 40 == 0:
spool.flush()
IdSpool.listing_finished(tmp_path)
spool.mark_complete()
except BaseException as exc:
errors.append(exc)
@@ -704,15 +731,18 @@ async def _auth_failure_pauses_without_counting(tmp_path: Path):
assert "good-layer" in used and "good-grid" in used
def test_unknown_download_error_is_generic(tmp_path: Path, caplog):
def test_unknown_download_error_is_generic(tmp_path: Path, caplog, monkeypatch):
monkeypatch.setattr(job_module, "PASS_RETRY_WAITS", (0, 0, 0))
asyncio.run(_unknown_download_error_is_generic(tmp_path, caplog))
async def _unknown_download_error_is_generic(tmp_path: Path, caplog):
job = _job(tmp_path, grid_ids=["5"])
calls = {"n": 0}
class Boom:
async def layer_code(self, **_kwargs):
calls["n"] += 1
raise RuntimeError("socket exploded")
async def aclose(self):
@@ -725,6 +755,7 @@ async def _unknown_download_error_is_generic(tmp_path: Path, caplog):
await run_download(job)
finally:
_restore(saved)
assert calls["n"] == 4
assert job.status == "error"
assert job.message == "下载中断,已下载的内容还在,点继续即可"
assert "socket exploded" in caplog.text
+417
View File
@@ -0,0 +1,417 @@
"""并发、重入和文件竞争。每个用例对应一种会让任务出错或漏数据的时序。"""
from __future__ import annotations
import asyncio
import csv
import io
import json
import os
import shutil
import threading
import time
from pathlib import Path
import pytest
from app.features.download import jobs as job_module
from app.features.download.jobs import JobManager, run_download
from app.features.download.journal import CsvJournal
from app.platform.client import NqiError, NqiNetworkError
from app.shared import files as files_module
from app.shared.state import state
@pytest.fixture
def places(tmp_path: Path, monkeypatch) -> Path:
monkeypatch.setattr(job_module, "DATA_DIR", tmp_path / "jobs")
monkeypatch.setattr(job_module, "DOWNLOAD_ROOT", tmp_path / "downloads")
monkeypatch.setattr(job_module, "SETTINGS_PATH", tmp_path / "settings.json")
return tmp_path
@pytest.fixture
def manager(places: Path, monkeypatch) -> JobManager:
current = JobManager()
monkeypatch.setattr(state, "jobs", current)
monkeypatch.setattr(state, "user", {"loginId": "tester"})
monkeypatch.setattr(state, "expired", False)
return current
class FakeClient:
"""按网络返回各自的编号;每个栅格写出一行空数据。"""
def __init__(self, ids: dict[str, list[str]] | None = None, *, delay: float = 0.0) -> None:
self.ids = ids or {}
self.delay = delay
self.fetched: list[str] = []
self.on_fetch = None
async def layer_code(self, *, network, **_kwargs):
return {"serviceCode": network, "originRelatedField": "grid20_id"}
async def iter_grid_ids(
self,
service_code,
_id_field,
cancel_event,
progress,
_skip=None,
run_event=None,
halt_event=None,
*,
seen=None,
**_kwargs,
):
seen = set() if seen is None else seen
ids = self.ids[service_code]
def halted() -> bool:
return cancel_event.is_set() or (halt_event is not None and halt_event.is_set())
for start in range(0, len(ids), 40):
fresh = [item for item in ids[start : start + 40] if int(item) not in seen]
await progress(len(seen) + len(fresh))
for grid_id in fresh:
while run_event is not None and not run_event.is_set():
if halted():
return
await asyncio.sleep(0.005)
if halted():
return
seen.add(int(grid_id))
yield grid_id
await asyncio.sleep(0)
async def grid_feature(self, _service, grid_id, _field):
if self.delay:
await asyncio.sleep(self.delay)
self.fetched.append(grid_id)
if self.on_fetch is not None:
await self.on_fetch(grid_id)
return {"grid20_id": grid_id}
async def cell_rows(self, *_args):
return []
async def aclose(self):
return None
def _create(manager: JobManager, network: str = "NR", *, whole_city: bool = True, grid_ids=None, concurrency: int = 4):
return manager.create(
network=network,
city_code="JM",
city_name="江门",
month="2026-09",
groups=["rsrp"],
concurrency=concurrency,
grid_ids=list(grid_ids or []),
csv_path=None,
grid_size="GRID20",
whole_city=whole_city,
)
def _start(job) -> asyncio.Task:
job.task = asyncio.create_task(run_download(job))
return job.task
def _rows(job) -> list[str]:
"""CSV 里每行的栅格编号。"""
body = list(csv.reader(io.StringIO(job.csv_path.read_text(encoding="utf-8-sig"))))
column = body[0].index("20米栅格ID")
return [row[column] for row in body[1:]]
async def _until(check, seconds: float = 10.0) -> None:
deadline = time.monotonic() + seconds
while not check():
if time.monotonic() > deadline:
raise AssertionError("等待超时")
await asyncio.sleep(0.01)
def _scan(jobs, stop: threading.Event) -> None:
"""模拟杀毒软件和索引:不停打开任务目录里的文件读一下再放手。"""
while not stop.is_set():
for job in jobs:
paths = (
job.directory / "job.json",
job.directory / "ids.spool.meta",
job.directory / "ids.spool",
job.directory / "progress.jsonl",
job.csv_path,
)
for path in paths:
try:
with open(path, "rb") as handle:
handle.read(4096)
time.sleep(0.001)
except OSError:
pass
def test_two_city_jobs_survive_list_polling_and_file_scanners(manager, monkeypatch):
asyncio.run(_two_city_jobs(manager, monkeypatch))
async def _two_city_jobs(manager: JobManager, monkeypatch) -> None:
ids = {
"NR": [str(100000 + number) for number in range(700)],
"LTE": [str(500000 + number) for number in range(700)],
}
monkeypatch.setattr(state, "client", FakeClient(ids, delay=0.001))
first = _create(manager, "NR", concurrency=8)
second = _create(manager, "LTE", concurrency=8)
stop = threading.Event()
scanner = threading.Thread(target=_scan, args=([first, second], stop), daemon=True)
scanner.start()
polls = {"n": 0}
async def poll() -> None:
while not (first.task.done() and second.task.done()):
manager.list_jobs()
polls["n"] += 1
await asyncio.sleep(0.002)
try:
tasks = [_start(first), _start(second)]
await asyncio.wait_for(asyncio.gather(poll(), *tasks), timeout=60)
finally:
stop.set()
scanner.join(timeout=5)
for job, network in ((first, "NR"), (second, "LTE")):
assert job.status == "done", (job.status, job.message)
assert job.completed == 700
assert sorted(_rows(job)) == sorted(ids[network])
assert job.io is None
assert polls["n"] > 10
def test_list_reads_memory_after_first_load(manager, places, monkeypatch):
job = _create(manager, "NR")
job.status = "queued"
job.save()
other = places / "jobs" / "20260101010101"
other.mkdir(parents=True)
record = {
"id": other.name,
"network": "LTE",
"cityCode": "JM",
"cityName": "江门",
"month": "2026-08",
"groups": [],
"concurrency": 2,
"gridCount": 0,
"wholeCity": True,
"csvPath": str(other / "out.csv"),
"createdAt": "2026-01-01T01:01:01",
"status": "done",
"message": "已完成",
}
(other / "job.json").write_text(json.dumps(record, ensure_ascii=False), encoding="utf-8")
assert {item["id"] for item in manager.list_jobs()} == {job.id, other.name}
jobs_root = places / "jobs"
real_read_text = Path.read_text
real_open = Path.open
def guard(path: Path) -> None:
if jobs_root in path.parents:
raise AssertionError(f"不应再读 {path}")
def read_text(self, *args, **kwargs):
guard(self)
return real_read_text(self, *args, **kwargs)
def open_path(self, *args, **kwargs):
guard(self)
return real_open(self, *args, **kwargs)
monkeypatch.setattr(Path, "read_text", read_text)
monkeypatch.setattr(Path, "open", open_path)
assert {item["id"] for item in manager.list_jobs()} == {job.id, other.name}
def test_record_write_failure_never_raises_and_deleted_dirs_stay_deleted(manager, monkeypatch):
job = _create(manager, "NR")
monkeypatch.setattr(files_module.time, "sleep", lambda _seconds: None)
real_replace = files_module.os.replace
def deny(src, dst):
raise PermissionError(13, "Access is denied", str(dst), 5)
monkeypatch.setattr(files_module.os, "replace", deny)
job.message = "写不进去"
job.save()
monkeypatch.setattr(files_module.os, "replace", real_replace)
job.message = "写进去了"
job.save()
stored = json.loads((job.directory / "job.json").read_text(encoding="utf-8"))
assert stored["message"] == "写进去了"
assert list(job.directory.glob("*.tmp")) == []
shutil.rmtree(job.directory)
job.save()
assert not job.directory.exists()
def test_delete_paused_job_stops_its_task_before_removing_files(manager, monkeypatch):
asyncio.run(_delete_paused(manager, monkeypatch))
async def _delete_paused(manager: JobManager, monkeypatch) -> None:
gate = asyncio.Event()
client = FakeClient()
async def hold(_grid_id) -> None:
if len(client.fetched) >= 3:
await gate.wait()
client.on_fetch = hold
monkeypatch.setattr(state, "client", client)
job = _create(manager, "NR", whole_city=False, grid_ids=[str(number) for number in range(1, 30)], concurrency=2)
task = _start(job)
await _until(lambda: len(client.fetched) >= 3)
manager.pause(job)
assert job.is_active()
await manager.delete(job.id, files=True)
assert task.done()
assert job.io is None
assert job.id not in manager.jobs
assert not job.directory.exists()
assert not job.csv_path.parent.exists()
await asyncio.sleep(0.2)
assert not job.directory.exists()
def test_changing_concurrency_mid_city_download_keeps_every_grid(manager, monkeypatch):
asyncio.run(_retune_keeps_every_grid(manager, monkeypatch))
async def _retune_keeps_every_grid(manager: JobManager, monkeypatch) -> None:
ids = {"NR": [str(200000 + number) for number in range(500)]}
client = FakeClient(ids, delay=0.002)
holder: dict = {}
async def pause_once(_grid_id) -> None:
if len(client.fetched) == 60 and "paused" not in holder:
holder["paused"] = True
manager.pause(holder["job"])
client.on_fetch = pause_once
monkeypatch.setattr(state, "client", client)
job = _create(manager, "NR", concurrency=4)
holder["job"] = job
task = _start(job)
await _until(lambda: job.status == "paused")
await asyncio.sleep(0.1)
manager.set_concurrency(job, 7)
assert manager.place(job) == "resume"
await asyncio.wait_for(task, timeout=30)
assert job.status == "done", (job.status, job.message)
assert job.applied_concurrency == 7
assert sorted(_rows(job)) == sorted(ids["NR"])
def test_network_error_retries_the_pass_automatically(manager, monkeypatch):
monkeypatch.setattr(job_module, "PASS_RETRY_WAITS", (0, 0, 0))
asyncio.run(_network_retry(manager, monkeypatch))
async def _network_retry(manager: JobManager, monkeypatch) -> None:
client = FakeClient()
calls = {"n": 0}
real_layer = client.layer_code
async def flaky_layer(**kwargs):
calls["n"] += 1
if calls["n"] <= 2:
raise NqiNetworkError("连接失败,请稍后重试")
return await real_layer(**kwargs)
client.layer_code = flaky_layer
monkeypatch.setattr(state, "client", client)
job = _create(manager, "NR", whole_city=False, grid_ids=["1", "2", "3"])
await asyncio.wait_for(_start(job), timeout=10)
assert job.status == "done", (job.status, job.message)
assert calls["n"] == 3
assert sorted(_rows(job)) == ["1", "2", "3"]
def test_busy_csv_pauses_until_continue(manager, monkeypatch):
asyncio.run(_busy_csv(manager, monkeypatch))
async def _busy_csv(manager: JobManager, monkeypatch) -> None:
real_commit = CsvJournal.commit_many
failures = {"n": 0}
def flaky(self, items):
if failures["n"] == 0:
failures["n"] += 1
raise NqiError("文件被占用,请先关闭 Excel 等程序")
return real_commit(self, items)
monkeypatch.setattr(CsvJournal, "commit_many", flaky)
monkeypatch.setattr(state, "client", FakeClient())
grid_ids = [str(number) for number in range(1, 11)]
job = _create(manager, "NR", whole_city=False, grid_ids=grid_ids)
task = _start(job)
await _until(lambda: job.status == "paused" and job.paused_by == "file")
assert job.message == "文件被占用,请先关闭 Excel 等程序,处理好后点继续"
assert job.is_active()
assert manager.place(job) == "resume"
await asyncio.wait_for(task, timeout=10)
assert job.status == "done", (job.status, job.message)
assert sorted(_rows(job), key=int) == grid_ids
def test_resume_while_previous_run_is_closing_waits_for_it(manager):
job = _create(manager, "NR")
class Alive:
def done(self):
return False
job.task = Alive()
job.closing = True
job.status = "cancelled"
assert manager.place(job) == "wait"
assert job.status == "queued"
assert manager.queued_jobs() == []
job.task = None
assert manager.queued_jobs() == [job]
def test_commit_failure_leaves_no_partial_rows(tmp_path: Path, monkeypatch):
journal = CsvJournal(tmp_path / "out.csv", tmp_path / "progress.jsonl", ["栅格"])
journal.open()
journal.commit_many([("1", [["1"]])])
before_csv = (tmp_path / "out.csv").read_bytes()
before_progress = (tmp_path / "progress.jsonl").read_bytes()
real_fsync = os.fsync
failed = {"n": 0}
def fail_once(fd):
if fd == journal._file.fileno() and failed["n"] == 0:
failed["n"] += 1
error = OSError(33, "locked")
error.winerror = 33
raise error
return real_fsync(fd)
monkeypatch.setattr("app.features.download.journal.os.fsync", fail_once)
with pytest.raises(NqiError):
journal.commit_many([("2", [["2"]]), ("3", [["3"]])])
assert (tmp_path / "out.csv").read_bytes() == before_csv
assert (tmp_path / "progress.jsonl").read_bytes() == before_progress
assert journal.commit_many([("2", [["2"]]), ("3", [["3"]])]) == 2
journal.close()
body = list(csv.reader(io.StringIO((tmp_path / "out.csv").read_text(encoding="utf-8-sig"))))
assert body == [["栅格"], ["1"], ["2"], ["3"]]
reopened = CsvJournal(tmp_path / "out.csv", tmp_path / "progress.jsonl", ["栅格"])
reopened.open()
assert reopened.completed == {1, 2, 3}
reopened.close()
+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",