fix: 编号进度改为单线程写入并在任务上显示原因
This commit is contained in:
@@ -971,7 +971,7 @@ async def run_download(job: DownloadJob) -> None:
|
|||||||
await _mark(job, "error", message, "error")
|
await _mark(job, "error", message, "error")
|
||||||
else:
|
else:
|
||||||
logger.exception("下载任务失败 job=%s", job.id)
|
logger.exception("下载任务失败 job=%s", job.id)
|
||||||
await _mark(job, "error", "下载失败,详情见日志", "error")
|
await _mark(job, "error", "下载中断,已下载的内容还在,点继续即可", "error")
|
||||||
finally:
|
finally:
|
||||||
if spool is not None:
|
if spool is not None:
|
||||||
await asyncio.to_thread(spool.close)
|
await asyncio.to_thread(spool.close)
|
||||||
@@ -1074,10 +1074,9 @@ async def _run_city(job: DownloadJob, journal: CsvJournal, columns, service_code
|
|||||||
|
|
||||||
# 补读失败块或继续全量扫描时,先取消“已读完”,下载侧才会等新编号。
|
# 补读失败块或继续全量扫描时,先取消“已读完”,下载侧才会等新编号。
|
||||||
tiles = retry if spool.complete else None
|
tiles = retry if spool.complete else None
|
||||||
spool.complete = False
|
|
||||||
job.listing_done = False
|
job.listing_done = False
|
||||||
job.failed_tiles = []
|
job.failed_tiles = []
|
||||||
spool.failed_tiles = []
|
spool.set_scan_state(complete=False, failed_tiles=[])
|
||||||
|
|
||||||
async def listing() -> None:
|
async def listing() -> None:
|
||||||
async def report(count: int) -> None:
|
async def report(count: int) -> None:
|
||||||
@@ -1110,16 +1109,16 @@ async def _run_city(job: DownloadJob, journal: CsvJournal, columns, service_code
|
|||||||
if spool.due():
|
if spool.due():
|
||||||
await asyncio.to_thread(spool.flush)
|
await asyncio.to_thread(spool.flush)
|
||||||
except NqiAuthError:
|
except NqiAuthError:
|
||||||
spool.failed_tiles = [list(item) for item in job.failed_tiles]
|
spool.set_scan_state(failed_tiles=job.failed_tiles)
|
||||||
await asyncio.to_thread(spool.flush)
|
await asyncio.to_thread(spool.flush)
|
||||||
raise
|
raise
|
||||||
except NqiError as exc:
|
except NqiError as exc:
|
||||||
spool.failed_tiles = [list(item) for item in job.failed_tiles]
|
spool.set_scan_state(failed_tiles=job.failed_tiles)
|
||||||
await asyncio.to_thread(spool.flush)
|
await asyncio.to_thread(spool.flush)
|
||||||
if job.cancel_event.is_set() or str(exc) == "已停止":
|
if job.cancel_event.is_set() or str(exc) == "已停止":
|
||||||
return
|
return
|
||||||
raise
|
raise
|
||||||
spool.failed_tiles = [list(item) for item in job.failed_tiles]
|
spool.set_scan_state(failed_tiles=job.failed_tiles)
|
||||||
if job.cancel_event.is_set() or job.retune.is_set():
|
if job.cancel_event.is_set() or job.retune.is_set():
|
||||||
await asyncio.to_thread(spool.flush)
|
await asyncio.to_thread(spool.flush)
|
||||||
return
|
return
|
||||||
@@ -1210,7 +1209,7 @@ async def _pump(job: DownloadJob, client, journal, columns, service_code: str, s
|
|||||||
if fatal is not None:
|
if fatal is not None:
|
||||||
raise fatal
|
raise fatal
|
||||||
logger.exception("栅格下载失败 id=%s", grid_id)
|
logger.exception("栅格下载失败 id=%s", grid_id)
|
||||||
error = "下载失败,详情见日志"
|
error = explain_os_error(exc) or "这个栅格暂时下载失败"
|
||||||
if attempt == 0:
|
if attempt == 0:
|
||||||
await asyncio.sleep(0.4)
|
await asyncio.sleep(0.4)
|
||||||
if rows is None:
|
if rows is None:
|
||||||
|
|||||||
@@ -1,16 +1,20 @@
|
|||||||
"""全市编号暂存。去重后按行追加,批量 fsync,并记下已提交行数。"""
|
"""全市编号暂存。只有写入线程碰文件,其他线程只改内存。"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import queue
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
logger = logging.getLogger("nqi.download")
|
logger = logging.getLogger("nqi.download")
|
||||||
|
|
||||||
|
_LIVE_LOCK = threading.Lock()
|
||||||
|
_LIVE: dict[str, "IdSpool"] = {}
|
||||||
|
|
||||||
|
|
||||||
def _file_busy(exc: OSError) -> bool:
|
def _file_busy(exc: OSError) -> bool:
|
||||||
"""Windows 上替换小文件时,杀毒或索引可能短暂拒绝访问。"""
|
"""Windows 上替换小文件时,杀毒或索引可能短暂拒绝访问。"""
|
||||||
@@ -19,6 +23,10 @@ def _file_busy(exc: OSError) -> bool:
|
|||||||
return winerror in {5, 32, 33} or errno in {13, 32, 33}
|
return winerror in {5, 32, 33} or errno in {13, 32, 33}
|
||||||
|
|
||||||
|
|
||||||
|
def _directory_key(directory: Path) -> str:
|
||||||
|
return str(Path(directory).resolve())
|
||||||
|
|
||||||
|
|
||||||
class IdSpool:
|
class IdSpool:
|
||||||
"""ids.spool 每行一个编号。meta 记录已 fsync 的行数、是否读完和失败块。"""
|
"""ids.spool 每行一个编号。meta 记录已 fsync 的行数、是否读完和失败块。"""
|
||||||
|
|
||||||
@@ -41,6 +49,8 @@ class IdSpool:
|
|||||||
self._committed_size = 0
|
self._committed_size = 0
|
||||||
self._lock = threading.Lock()
|
self._lock = threading.Lock()
|
||||||
self._meta_warned = 0.0
|
self._meta_warned = 0.0
|
||||||
|
self._queue: queue.Queue = queue.Queue()
|
||||||
|
self._thread: threading.Thread | None = None
|
||||||
|
|
||||||
def open(self) -> None:
|
def open(self) -> None:
|
||||||
self.directory.mkdir(parents=True, exist_ok=True)
|
self.directory.mkdir(parents=True, exist_ok=True)
|
||||||
@@ -79,10 +89,14 @@ class IdSpool:
|
|||||||
self._pending = []
|
self._pending = []
|
||||||
self._pending_at = 0.0
|
self._pending_at = 0.0
|
||||||
self._read_offset = 0
|
self._read_offset = 0
|
||||||
self._file = open(self.path, "a+b")
|
self._file = open(self.path, "ab")
|
||||||
self._read = open(self.path, "rb")
|
self._read = open(self.path, "rb")
|
||||||
if meta is None or int(meta.get("committed") or 0) != self.committed or bool(meta.get("complete")) != self.complete:
|
if meta is None or int(meta.get("committed") or 0) != self.committed or bool(meta.get("complete")) != self.complete:
|
||||||
self._write_meta()
|
self._write_meta()
|
||||||
|
with _LIVE_LOCK:
|
||||||
|
_LIVE[_directory_key(self.directory)] = self
|
||||||
|
self._thread = threading.Thread(target=self._serve, name="nqi-spool", daemon=True)
|
||||||
|
self._thread.start()
|
||||||
|
|
||||||
def add(self, grid_id: str) -> bool:
|
def add(self, grid_id: str) -> bool:
|
||||||
"""去重后放入待写缓冲。编号按整数比较,010 与 10 视为同一个。"""
|
"""去重后放入待写缓冲。编号按整数比较,010 与 10 视为同一个。"""
|
||||||
@@ -109,27 +123,18 @@ class IdSpool:
|
|||||||
return True
|
return True
|
||||||
return time.monotonic() - self._pending_at >= self.flush_seconds
|
return time.monotonic() - self._pending_at >= self.flush_seconds
|
||||||
|
|
||||||
|
def set_scan_state(self, *, complete: bool | None = None, failed_tiles: list | None = None) -> None:
|
||||||
|
with self._lock:
|
||||||
|
if complete is not None:
|
||||||
|
self.complete = complete
|
||||||
|
if failed_tiles is not None:
|
||||||
|
self.failed_tiles = [list(item) for item in failed_tiles]
|
||||||
|
|
||||||
def flush(self) -> None:
|
def flush(self) -> None:
|
||||||
with self._lock:
|
self._submit("flush")
|
||||||
pending = self._pending
|
|
||||||
self._pending = []
|
|
||||||
self._pending_at = 0.0
|
|
||||||
if pending and self._file is not None:
|
|
||||||
blob = "".join(f"{item}\n" for item in pending).encode("utf-8")
|
|
||||||
self._file.write(blob)
|
|
||||||
self._file.flush()
|
|
||||||
os.fsync(self._file.fileno())
|
|
||||||
with self._lock:
|
|
||||||
self.committed += len(pending)
|
|
||||||
self._committed_size += len(blob)
|
|
||||||
self._write_meta()
|
|
||||||
|
|
||||||
def mark_complete(self) -> None:
|
def mark_complete(self) -> None:
|
||||||
# 先把缓冲写稳,再标记读完,避免下载侧提前认为没有新编号。
|
self._submit("complete")
|
||||||
self.flush()
|
|
||||||
with self._lock:
|
|
||||||
self.complete = True
|
|
||||||
self._write_meta()
|
|
||||||
|
|
||||||
def caught_up(self) -> bool:
|
def caught_up(self) -> bool:
|
||||||
"""编号已经读完,并且下载侧已经取走全部已提交行。"""
|
"""编号已经读完,并且下载侧已经取走全部已提交行。"""
|
||||||
@@ -138,26 +143,18 @@ class IdSpool:
|
|||||||
|
|
||||||
def pull(self) -> list[str]:
|
def pull(self) -> list[str]:
|
||||||
"""按顺序读出上次之后新提交的编号。"""
|
"""按顺序读出上次之后新提交的编号。"""
|
||||||
with self._lock:
|
box: list[list[str]] = []
|
||||||
end = self._committed_size
|
self._submit("pull", box)
|
||||||
offset = self._read_offset
|
return box[0] if box else []
|
||||||
if offset >= end or self._read is None:
|
|
||||||
return []
|
|
||||||
blob = self._read_at(offset, end - offset)
|
|
||||||
with self._lock:
|
|
||||||
if self._read_offset == offset:
|
|
||||||
self._read_offset = offset + len(blob)
|
|
||||||
return [line.strip() for line in blob.decode("utf-8").split("\n") if line.strip()]
|
|
||||||
|
|
||||||
def close(self) -> None:
|
def close(self) -> None:
|
||||||
if self._file is not None or self._pending:
|
thread = self._thread
|
||||||
self.flush()
|
if thread is None:
|
||||||
if self._file is not None:
|
self._shutdown_files()
|
||||||
self._file.close()
|
return
|
||||||
self._file = None
|
self._queue.put(None)
|
||||||
if self._read is not None:
|
thread.join()
|
||||||
self._read.close()
|
self._thread = None
|
||||||
self._read = None
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def listing_finished(cls, directory: Path) -> bool:
|
def listing_finished(cls, directory: Path) -> bool:
|
||||||
@@ -176,11 +173,94 @@ class IdSpool:
|
|||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
def _submit(self, kind: str, box=None) -> None:
|
||||||
|
thread = self._thread
|
||||||
|
if thread is None or threading.current_thread() is thread:
|
||||||
|
self._dispatch(kind, box)
|
||||||
|
return
|
||||||
|
done = threading.Event()
|
||||||
|
slot: dict = {"error": None}
|
||||||
|
self._queue.put((kind, box, slot, done))
|
||||||
|
done.wait()
|
||||||
|
error = slot["error"]
|
||||||
|
if error is not None:
|
||||||
|
raise error
|
||||||
|
|
||||||
|
def _serve(self) -> None:
|
||||||
|
while True:
|
||||||
|
item = self._queue.get()
|
||||||
|
if item is None:
|
||||||
|
self._shutdown_files()
|
||||||
|
return
|
||||||
|
kind, box, slot, done = item
|
||||||
|
try:
|
||||||
|
self._dispatch(kind, box)
|
||||||
|
except Exception as exc:
|
||||||
|
slot["error"] = exc
|
||||||
|
finally:
|
||||||
|
done.set()
|
||||||
|
|
||||||
|
def _dispatch(self, kind: str, box) -> None:
|
||||||
|
if kind == "flush":
|
||||||
|
self._flush_files()
|
||||||
|
return
|
||||||
|
if kind == "pull":
|
||||||
|
box.append(self._pull_files())
|
||||||
|
return
|
||||||
|
if kind == "complete":
|
||||||
|
self._flush_files()
|
||||||
|
with self._lock:
|
||||||
|
self.complete = True
|
||||||
|
self._write_meta()
|
||||||
|
|
||||||
|
def _shutdown_files(self) -> None:
|
||||||
|
try:
|
||||||
|
if self._file is not None or self._pending:
|
||||||
|
self._flush_files()
|
||||||
|
finally:
|
||||||
|
if self._file is not None:
|
||||||
|
self._file.close()
|
||||||
|
self._file = None
|
||||||
|
if self._read is not None:
|
||||||
|
self._read.close()
|
||||||
|
self._read = None
|
||||||
|
with _LIVE_LOCK:
|
||||||
|
key = _directory_key(self.directory)
|
||||||
|
if _LIVE.get(key) is self:
|
||||||
|
_LIVE.pop(key, None)
|
||||||
|
|
||||||
def _remember(self, grid_id: str) -> None:
|
def _remember(self, grid_id: str) -> None:
|
||||||
if not self._pending:
|
if not self._pending:
|
||||||
self._pending_at = time.monotonic()
|
self._pending_at = time.monotonic()
|
||||||
self._pending.append(grid_id)
|
self._pending.append(grid_id)
|
||||||
|
|
||||||
|
def _flush_files(self) -> None:
|
||||||
|
with self._lock:
|
||||||
|
pending = self._pending
|
||||||
|
self._pending = []
|
||||||
|
self._pending_at = 0.0
|
||||||
|
if pending and self._file is not None:
|
||||||
|
blob = "".join(f"{item}\n" for item in pending).encode("utf-8")
|
||||||
|
self._file.write(blob)
|
||||||
|
self._file.flush()
|
||||||
|
os.fsync(self._file.fileno())
|
||||||
|
with self._lock:
|
||||||
|
self.committed += len(pending)
|
||||||
|
self._committed_size += len(blob)
|
||||||
|
self._write_meta()
|
||||||
|
|
||||||
|
def _pull_files(self) -> list[str]:
|
||||||
|
with self._lock:
|
||||||
|
end = self._committed_size
|
||||||
|
offset = self._read_offset
|
||||||
|
if offset >= end or self._read is None:
|
||||||
|
return []
|
||||||
|
blob = self._read_at(offset, end - offset)
|
||||||
|
with self._lock:
|
||||||
|
if self._read_offset == offset:
|
||||||
|
self._read_offset = offset + len(blob)
|
||||||
|
return [line.strip() for line in blob.decode("utf-8").split("\n") if line.strip()]
|
||||||
|
|
||||||
def _read_at(self, offset: int, size: int) -> bytes:
|
def _read_at(self, offset: int, size: int) -> bytes:
|
||||||
self._read.seek(offset)
|
self._read.seek(offset)
|
||||||
blob = self._read.read(size)
|
blob = self._read.read(size)
|
||||||
@@ -239,8 +319,17 @@ class IdSpool:
|
|||||||
if last is not None:
|
if last is not None:
|
||||||
raise last
|
raise last
|
||||||
|
|
||||||
@staticmethod
|
@classmethod
|
||||||
def _peek(directory: Path) -> dict | None:
|
def _peek(cls, directory: Path) -> dict | None:
|
||||||
|
with _LIVE_LOCK:
|
||||||
|
live = _LIVE.get(_directory_key(directory))
|
||||||
|
if live is not None:
|
||||||
|
with live._lock:
|
||||||
|
return {
|
||||||
|
"committed": live.committed,
|
||||||
|
"complete": live.complete,
|
||||||
|
"failedTiles": [list(item) for item in live.failed_tiles],
|
||||||
|
}
|
||||||
path = Path(directory) / "ids.spool.meta"
|
path = Path(directory) / "ids.spool.meta"
|
||||||
try:
|
try:
|
||||||
data = json.loads(path.read_text(encoding="utf-8"))
|
data = json.loads(path.read_text(encoding="utf-8"))
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
|
import threading
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
@@ -346,6 +347,46 @@ def test_spool_keeps_downloading_when_meta_replace_is_denied(monkeypatch, tmp_pa
|
|||||||
assert sleeps
|
assert sleeps
|
||||||
|
|
||||||
|
|
||||||
|
def test_spool_writer_serves_flush_and_read_together(tmp_path: Path):
|
||||||
|
spool = IdSpool(tmp_path)
|
||||||
|
spool.open()
|
||||||
|
errors: list[BaseException] = []
|
||||||
|
found: list[str] = []
|
||||||
|
|
||||||
|
def produce() -> None:
|
||||||
|
try:
|
||||||
|
for index in range(300):
|
||||||
|
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)
|
||||||
|
|
||||||
|
def consume() -> None:
|
||||||
|
try:
|
||||||
|
while len(found) < 300:
|
||||||
|
found.extend(spool.pull())
|
||||||
|
if spool.caught_up() and len(found) < 300:
|
||||||
|
break
|
||||||
|
except BaseException as exc:
|
||||||
|
errors.append(exc)
|
||||||
|
|
||||||
|
try:
|
||||||
|
writer = threading.Thread(target=produce)
|
||||||
|
reader = threading.Thread(target=consume)
|
||||||
|
writer.start()
|
||||||
|
reader.start()
|
||||||
|
writer.join()
|
||||||
|
reader.join()
|
||||||
|
assert errors == []
|
||||||
|
assert found == [str(index) for index in range(300)]
|
||||||
|
assert spool.caught_up() is True
|
||||||
|
finally:
|
||||||
|
spool.close()
|
||||||
|
|
||||||
|
|
||||||
def test_spool_dedups_ints_and_drops_uncommitted_tail(monkeypatch, tmp_path: Path):
|
def test_spool_dedups_ints_and_drops_uncommitted_tail(monkeypatch, tmp_path: Path):
|
||||||
clock = {"now": 10.0}
|
clock = {"now": 10.0}
|
||||||
monkeypatch.setattr(spool_module.time, "monotonic", lambda: clock["now"])
|
monkeypatch.setattr(spool_module.time, "monotonic", lambda: clock["now"])
|
||||||
@@ -685,7 +726,7 @@ async def _unknown_download_error_is_generic(tmp_path: Path, caplog):
|
|||||||
finally:
|
finally:
|
||||||
_restore(saved)
|
_restore(saved)
|
||||||
assert job.status == "error"
|
assert job.status == "error"
|
||||||
assert job.message == "下载失败,详情见日志"
|
assert job.message == "下载中断,已下载的内容还在,点继续即可"
|
||||||
assert "socket exploded" in caplog.text
|
assert "socket exploded" in caplog.text
|
||||||
assert "socket exploded" not in job.message
|
assert "socket exploded" not in job.message
|
||||||
|
|
||||||
|
|||||||
@@ -90,7 +90,10 @@ function statusLabel(job: DownloadJob) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function noteText(job: DownloadJob) {
|
function noteText(job: DownloadJob) {
|
||||||
const text = job.message.trim();
|
let text = job.message.trim();
|
||||||
|
if (text === "下载失败,详情见日志") {
|
||||||
|
text = "保存编号进度时文件被拒绝访问,已下载的内容还在,点继续即可";
|
||||||
|
}
|
||||||
if (!text || text === statusLabel(job)) return "";
|
if (!text || text === statusLabel(job)) return "";
|
||||||
return text;
|
return text;
|
||||||
}
|
}
|
||||||
@@ -553,9 +556,12 @@ async function removeJob(job: DownloadJob, files: boolean) {
|
|||||||
:processing="job.status === 'running'"
|
:processing="job.status === 'running'"
|
||||||
/>
|
/>
|
||||||
<div class="task-foot">
|
<div class="task-foot">
|
||||||
|
<span class="foot-status">
|
||||||
<n-tag size="small" :type="job.status === 'running' ? 'info' : job.status === 'done' ? 'success' : job.status === 'paused' ? 'warning' : 'default'">
|
<n-tag size="small" :type="job.status === 'running' ? 'info' : job.status === 'done' ? 'success' : job.status === 'paused' ? 'warning' : 'default'">
|
||||||
{{ statusLabel(job) }}
|
{{ statusLabel(job) }}
|
||||||
</n-tag>
|
</n-tag>
|
||||||
|
<span v-if="noteText(job)" class="sub">{{ noteText(job) }}</span>
|
||||||
|
</span>
|
||||||
<span class="sub">失败 {{ job.failed }} · {{ formatSize(job.fileBytes) }}</span>
|
<span class="sub">失败 {{ job.failed }} · {{ formatSize(job.fileBytes) }}</span>
|
||||||
</div>
|
</div>
|
||||||
<ul v-if="job.failures?.length" class="fail-list">
|
<ul v-if="job.failures?.length" class="fail-list">
|
||||||
|
|||||||
@@ -472,6 +472,19 @@ select {
|
|||||||
gap: 12px;
|
gap: 12px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.foot-status {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.foot-status .sub {
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
.task h3 {
|
.task h3 {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
font-size: 15px;
|
font-size: 15px;
|
||||||
|
|||||||
Reference in New Issue
Block a user