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: