fix: 进度文件改为流式恢复,只截断尾部坏行
This commit is contained in:
@@ -10,71 +10,76 @@ import threading
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def _id_key(value) -> int | str:
|
||||||
|
if isinstance(value, bool):
|
||||||
|
return str(value)
|
||||||
|
if isinstance(value, int):
|
||||||
|
return value
|
||||||
|
text = str(value).strip()
|
||||||
|
if text.isdigit():
|
||||||
|
return int(text)
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
class _IdSet(set):
|
||||||
|
"""纯数字编号按 int 保存。成员判断同时接受等价的数字字符串。"""
|
||||||
|
|
||||||
|
def add(self, value) -> None:
|
||||||
|
super().add(_id_key(value))
|
||||||
|
|
||||||
|
def __contains__(self, value: object) -> bool:
|
||||||
|
return super().__contains__(_id_key(value))
|
||||||
|
|
||||||
|
|
||||||
class CsvJournal:
|
class CsvJournal:
|
||||||
def __init__(self, csv_path: Path, progress_path: Path, headers: list[str]):
|
def __init__(self, csv_path: Path, progress_path: Path, headers: list[str]):
|
||||||
self.csv_path = csv_path
|
self.csv_path = csv_path
|
||||||
self.progress_path = progress_path
|
self.progress_path = progress_path
|
||||||
self.headers = headers
|
self.headers = headers
|
||||||
self.completed: set[str] = set()
|
self.completed: _IdSet = _IdSet()
|
||||||
self.written_rows = 0
|
self.written_rows = 0
|
||||||
self._file = None
|
self._file = None
|
||||||
|
self._progress = None
|
||||||
self._lock = threading.Lock()
|
self._lock = threading.Lock()
|
||||||
|
|
||||||
def open(self) -> None:
|
def open(self) -> None:
|
||||||
|
with self._lock:
|
||||||
|
self._close_handles()
|
||||||
|
try:
|
||||||
|
self._open_locked()
|
||||||
|
except Exception:
|
||||||
|
self._close_handles()
|
||||||
|
raise
|
||||||
|
|
||||||
|
def _open_locked(self) -> None:
|
||||||
self.csv_path.parent.mkdir(parents=True, exist_ok=True)
|
self.csv_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
records = self._read_progress()
|
csv_size = self.csv_path.stat().st_size if self.csv_path.exists() else 0
|
||||||
size = self.csv_path.stat().st_size if self.csv_path.exists() else 0
|
completed, written_rows, good_end, tail_dirty, last_offset = self._scan_progress(csv_size)
|
||||||
kept: list[dict] = []
|
if not self.csv_path.exists() or not completed:
|
||||||
previous = 0
|
self.completed = _IdSet()
|
||||||
for record in records:
|
self.written_rows = 0
|
||||||
offset = int(record["offset"])
|
self._file = open(self.csv_path, "w+b")
|
||||||
if offset < previous or offset > size:
|
self._file.write(b"\xef\xbb\xbf" + self._encode(self.headers))
|
||||||
break
|
self._file.flush()
|
||||||
kept.append(
|
os.fsync(self._file.fileno())
|
||||||
{
|
self._bind_progress(0)
|
||||||
"id": str(record["id"]),
|
|
||||||
"offset": offset,
|
|
||||||
"rows": int(record.get("rows") or 0),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
previous = offset
|
|
||||||
self.completed = {item["id"] for item in kept}
|
|
||||||
self.written_rows = sum(int(item.get("rows") or 0) for item in kept)
|
|
||||||
self._file = open(self.csv_path, "a+b")
|
|
||||||
if kept:
|
|
||||||
self._file.truncate(previous)
|
|
||||||
self._file.seek(previous)
|
|
||||||
self._rewrite_progress(kept)
|
|
||||||
return
|
return
|
||||||
self.written_rows = 0
|
self.completed = completed
|
||||||
self._file.truncate(0)
|
self.written_rows = written_rows
|
||||||
self._file.seek(0)
|
self._file = open(self.csv_path, "r+b")
|
||||||
self._file.write(b"\xef\xbb\xbf" + self._encode(self.headers))
|
end = self._file.seek(0, os.SEEK_END)
|
||||||
self._file.flush()
|
if end != last_offset:
|
||||||
os.fsync(self._file.fileno())
|
self._file.truncate(last_offset)
|
||||||
self.progress_path.write_text("", encoding="utf-8")
|
self._file.seek(last_offset)
|
||||||
|
self._file.flush()
|
||||||
|
os.fsync(self._file.fileno())
|
||||||
|
self._bind_progress(good_end if tail_dirty else None)
|
||||||
|
|
||||||
def write_rows(self, grid_id: str, rows: list[list[str]]) -> int:
|
def write_rows(self, grid_id: str, rows: list[list[str]]) -> int:
|
||||||
if not rows:
|
if not rows:
|
||||||
raise ValueError("至少要写出一行")
|
raise ValueError("至少要写出一行")
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if grid_id in self.completed:
|
return self._write_one(grid_id, rows, sync=True)
|
||||||
return 0
|
|
||||||
if self._file is None:
|
|
||||||
raise RuntimeError("下载文件还没有打开")
|
|
||||||
blob = b"".join(self._encode(row) for row in rows)
|
|
||||||
self._file.write(blob)
|
|
||||||
self._file.flush()
|
|
||||||
os.fsync(self._file.fileno())
|
|
||||||
offset = self._file.tell()
|
|
||||||
record = {"id": grid_id, "offset": offset, "rows": len(rows)}
|
|
||||||
self.written_rows += len(rows)
|
|
||||||
with self.progress_path.open("a", encoding="utf-8") as handle:
|
|
||||||
handle.write(json.dumps(record, ensure_ascii=False) + "\n")
|
|
||||||
handle.flush()
|
|
||||||
os.fsync(handle.fileno())
|
|
||||||
self.completed.add(grid_id)
|
|
||||||
return len(rows)
|
|
||||||
|
|
||||||
def commit_many(self, items) -> int:
|
def commit_many(self, items) -> int:
|
||||||
written = 0
|
written = 0
|
||||||
@@ -84,9 +89,69 @@ class CsvJournal:
|
|||||||
|
|
||||||
def close(self) -> None:
|
def close(self) -> None:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
|
self._close_handles()
|
||||||
|
|
||||||
|
def _write_one(self, grid_id: str, rows: list[list[str]], *, sync: bool) -> int:
|
||||||
|
key = _id_key(grid_id)
|
||||||
|
if key in self.completed:
|
||||||
|
return 0
|
||||||
|
if self._file is None or self._progress is None:
|
||||||
|
raise RuntimeError("下载文件还没有打开")
|
||||||
|
blob = b"".join(self._encode(row) for row in rows)
|
||||||
|
start = self._file.tell()
|
||||||
|
progress_at = self._progress.seek(0, os.SEEK_END)
|
||||||
|
try:
|
||||||
|
self._file.write(blob)
|
||||||
|
self._file.flush()
|
||||||
|
if sync:
|
||||||
|
os.fsync(self._file.fileno())
|
||||||
|
offset = self._file.tell()
|
||||||
|
record = {"id": key, "offset": offset, "rows": len(rows)}
|
||||||
|
line = (json.dumps(record, ensure_ascii=False) + "\n").encode("utf-8")
|
||||||
|
self._progress.write(line)
|
||||||
|
self._progress.flush()
|
||||||
|
if sync:
|
||||||
|
os.fsync(self._progress.fileno())
|
||||||
|
except OSError:
|
||||||
|
self._rollback(start, progress_at)
|
||||||
|
raise
|
||||||
|
self.written_rows += len(rows)
|
||||||
|
self.completed.add(key)
|
||||||
|
return len(rows)
|
||||||
|
|
||||||
|
def _rollback(self, csv_at: int, progress_at: int) -> None:
|
||||||
|
try:
|
||||||
if self._file is not None:
|
if self._file is not None:
|
||||||
self._file.close()
|
self._file.truncate(csv_at)
|
||||||
self._file = None
|
self._file.seek(csv_at)
|
||||||
|
self._file.flush()
|
||||||
|
os.fsync(self._file.fileno())
|
||||||
|
if self._progress is not None:
|
||||||
|
self._progress.truncate(progress_at)
|
||||||
|
self._progress.seek(progress_at)
|
||||||
|
self._progress.flush()
|
||||||
|
os.fsync(self._progress.fileno())
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _close_handles(self) -> None:
|
||||||
|
if self._file is not None:
|
||||||
|
self._file.close()
|
||||||
|
self._file = None
|
||||||
|
if self._progress is not None:
|
||||||
|
self._progress.close()
|
||||||
|
self._progress = None
|
||||||
|
|
||||||
|
def _bind_progress(self, truncate_to: int | None) -> None:
|
||||||
|
self.progress_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
if not self.progress_path.exists():
|
||||||
|
self.progress_path.touch()
|
||||||
|
self._progress = open(self.progress_path, "r+b")
|
||||||
|
if truncate_to is not None:
|
||||||
|
self._progress.truncate(truncate_to)
|
||||||
|
self._progress.flush()
|
||||||
|
os.fsync(self._progress.fileno())
|
||||||
|
self._progress.seek(0, os.SEEK_END)
|
||||||
|
|
||||||
def _encode(self, row: list[str]) -> bytes:
|
def _encode(self, row: list[str]) -> bytes:
|
||||||
buffer = io.StringIO(newline="")
|
buffer = io.StringIO(newline="")
|
||||||
@@ -94,28 +159,37 @@ class CsvJournal:
|
|||||||
writer.writerow(row)
|
writer.writerow(row)
|
||||||
return buffer.getvalue().encode("utf-8")
|
return buffer.getvalue().encode("utf-8")
|
||||||
|
|
||||||
def _read_progress(self) -> list[dict]:
|
def _scan_progress(self, csv_size: int):
|
||||||
|
completed = _IdSet()
|
||||||
|
written = 0
|
||||||
|
good_end = 0
|
||||||
|
last_offset = 0
|
||||||
|
tail_dirty = False
|
||||||
if not self.progress_path.exists():
|
if not self.progress_path.exists():
|
||||||
return []
|
return completed, written, good_end, tail_dirty, last_offset
|
||||||
records: list[dict] = []
|
with self.progress_path.open("rb") as handle:
|
||||||
for line in self.progress_path.read_text(encoding="utf-8").splitlines():
|
while True:
|
||||||
text = line.strip()
|
line = handle.readline()
|
||||||
if not text:
|
if not line:
|
||||||
continue
|
break
|
||||||
try:
|
if not line.strip():
|
||||||
record = json.loads(text)
|
good_end = handle.tell()
|
||||||
records.append(
|
continue
|
||||||
{
|
try:
|
||||||
"id": str(record["id"]),
|
record = json.loads(line.decode("utf-8"))
|
||||||
"offset": int(record["offset"]),
|
offset = int(record["offset"])
|
||||||
"rows": int(record.get("rows") or 0),
|
rows = int(record.get("rows") or 0)
|
||||||
}
|
if rows < 0:
|
||||||
)
|
raise ValueError("rows")
|
||||||
except (KeyError, TypeError, ValueError, json.JSONDecodeError):
|
_id_key(record["id"])
|
||||||
break
|
except (UnicodeDecodeError, KeyError, TypeError, ValueError, json.JSONDecodeError):
|
||||||
return records
|
tail_dirty = True
|
||||||
|
break
|
||||||
def _rewrite_progress(self, records: list[dict]) -> None:
|
if offset < last_offset or offset > csv_size:
|
||||||
lines = [json.dumps(item, ensure_ascii=False) for item in records]
|
tail_dirty = True
|
||||||
text = ("\n".join(lines) + "\n") if lines else ""
|
break
|
||||||
self.progress_path.write_text(text, encoding="utf-8")
|
completed.add(record["id"])
|
||||||
|
written += rows
|
||||||
|
last_offset = offset
|
||||||
|
good_end = handle.tell()
|
||||||
|
return completed, written, good_end, tail_dirty, last_offset
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import csv
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from app.features.download.journal import CsvJournal
|
||||||
|
|
||||||
|
|
||||||
|
def test_progress_recovers_by_streaming_and_truncates_only_a_bad_tail(tmp_path: Path, monkeypatch):
|
||||||
|
csv_path = tmp_path / "out.csv"
|
||||||
|
progress = tmp_path / "progress.jsonl"
|
||||||
|
journal = CsvJournal(csv_path, progress, ["栅格", "小区"])
|
||||||
|
journal.open()
|
||||||
|
assert journal.write_rows("1", [["1", "a"], ["1", "b"]]) == 2
|
||||||
|
assert journal.write_rows("2", [["2", ""]]) == 1
|
||||||
|
journal.close()
|
||||||
|
assert all(isinstance(item, int) for item in journal.completed)
|
||||||
|
|
||||||
|
good_progress = progress.read_bytes()
|
||||||
|
with progress.open("ab") as handle:
|
||||||
|
handle.write(b"{bad\n")
|
||||||
|
with csv_path.open("ab") as handle:
|
||||||
|
handle.write("垃圾,数据\r\n".encode("utf-8"))
|
||||||
|
|
||||||
|
def fail_read_text(*_args, **_kwargs):
|
||||||
|
raise AssertionError("恢复进度不应整份读入")
|
||||||
|
|
||||||
|
monkeypatch.setattr(Path, "read_text", fail_read_text)
|
||||||
|
journal.open()
|
||||||
|
monkeypatch.undo()
|
||||||
|
assert progress.read_bytes() == good_progress
|
||||||
|
assert "垃圾" not in csv_path.read_text(encoding="utf-8")
|
||||||
|
assert 1 in journal.completed and "1" in journal.completed
|
||||||
|
assert journal.write_rows("1", [["1", "again"]]) == 0
|
||||||
|
journal.close()
|
||||||
|
body = list(csv.reader(io.StringIO(csv_path.read_text(encoding="utf-8-sig"))))
|
||||||
|
assert body == [["栅格", "小区"], ["1", "a"], ["1", "b"], ["2", ""]]
|
||||||
|
|
||||||
|
|
||||||
|
def test_clean_progress_is_not_rewritten(tmp_path: Path, monkeypatch):
|
||||||
|
csv_path = tmp_path / "out.csv"
|
||||||
|
progress = tmp_path / "progress.jsonl"
|
||||||
|
journal = CsvJournal(csv_path, progress, ["栅格"])
|
||||||
|
journal.open()
|
||||||
|
journal.write_rows("9", [["9"]])
|
||||||
|
journal.close()
|
||||||
|
before = progress.read_bytes()
|
||||||
|
calls = _patch_fsync(monkeypatch)
|
||||||
|
journal.open()
|
||||||
|
journal.close()
|
||||||
|
assert progress.read_bytes() == before
|
||||||
|
assert calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def _patch_fsync(monkeypatch):
|
||||||
|
calls = []
|
||||||
|
original = os.fsync
|
||||||
|
|
||||||
|
def spy(fd):
|
||||||
|
calls.append(fd)
|
||||||
|
return original(fd)
|
||||||
|
|
||||||
|
monkeypatch.setattr("app.features.download.journal.os.fsync", spy)
|
||||||
|
return calls
|
||||||
Reference in New Issue
Block a user