fix: 批量提交每批只同步一次磁盘

This commit is contained in:
2026-10-25 07:20:39 +08:00
parent ea3d1a5be0
commit 72b7c05fb8
2 changed files with 91 additions and 4 deletions
+40 -4
View File
@@ -82,10 +82,46 @@ class CsvJournal:
return self._write_one(grid_id, rows, sync=True)
def commit_many(self, items) -> int:
written = 0
for grid_id, rows in items:
written += self.write_rows(grid_id, rows)
return written
"""一批先写 CSV 并 fsync 一次,再写进度并 fsync 一次。"""
pending = list(items)
with self._lock:
if self._file is None or self._progress is None:
raise RuntimeError("下载文件还没有打开")
prepared: list[tuple[int | str, int, bytes]] = []
seen: set[int | str] = set()
for grid_id, rows in pending:
if not rows:
raise ValueError("至少要写出一行")
key = _id_key(grid_id)
if key in self.completed or key in seen:
continue
seen.add(key)
blob = b"".join(self._encode(row) for row in rows)
prepared.append((key, len(rows), blob))
if not prepared:
return 0
start = self._file.tell()
progress_at = self._progress.seek(0, os.SEEK_END)
written = 0
lines: list[bytes] = []
try:
for key, row_count, blob in prepared:
self._file.write(blob)
record = {"id": key, "offset": self._file.tell(), "rows": row_count}
lines.append((json.dumps(record, ensure_ascii=False) + "\n").encode("utf-8"))
written += row_count
self._file.flush()
os.fsync(self._file.fileno())
self._progress.write(b"".join(lines))
self._progress.flush()
os.fsync(self._progress.fileno())
except OSError:
self._rollback(start, progress_at)
raise
for key, row_count, _blob in prepared:
self.completed.add(key)
self.written_rows += row_count
return written
def close(self) -> None:
with self._lock:
+51
View File
@@ -1,6 +1,7 @@
import csv
import io
import os
import threading
from pathlib import Path
from app.features.download.journal import CsvJournal
@@ -52,6 +53,56 @@ def test_clean_progress_is_not_rewritten(tmp_path: Path, monkeypatch):
assert calls == []
def test_commit_many_fsyncs_once_per_batch_and_keeps_progress_open(tmp_path: Path, monkeypatch):
journal = CsvJournal(tmp_path / "out.csv", tmp_path / "progress.jsonl", ["栅格"])
journal.open()
handle = journal._progress
calls = _patch_fsync(monkeypatch)
written = journal.commit_many(
[
("1", [["1"], ["1"]]),
("1", [["1"]]),
("2", [["2"]]),
]
)
assert written == 3
assert calls == [journal._file.fileno(), handle.fileno()]
assert journal._progress is handle
assert handle.closed is False
calls.clear()
assert journal.commit_many([("1", [["1"]])]) == 0
assert calls == []
try:
journal.commit_many([("3", [])])
except ValueError as exc:
assert "至少要写出一行" in str(exc)
else:
raise AssertionError("空行应该拒绝")
journal.close()
rows = list(csv.reader(io.StringIO((tmp_path / "out.csv").read_text(encoding="utf-8-sig"))))
assert rows == [["栅格"], ["1"], ["1"], ["2"]]
def test_commit_many_is_thread_safe(tmp_path: Path):
journal = CsvJournal(tmp_path / "out.csv", tmp_path / "progress.jsonl", ["组", "序号", "内容"])
journal.open()
def write_group(name: str) -> None:
items = [(f"{name}-{index}", [[name, str(index), "甲" * 20]]) for index in range(20)]
journal.commit_many(items)
threads = [threading.Thread(target=write_group, args=(name,)) for name in ("甲", "乙")]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
journal.close()
rows = list(csv.reader(io.StringIO((tmp_path / "out.csv").read_text(encoding="utf-8-sig"))))
assert len(rows) == 41
assert all(len(row) == 3 for row in rows)
assert {row[0] for row in rows[1:]} == {"甲", "乙"}
def _patch_fsync(monkeypatch):
calls = []
original = os.fsync