122 lines
4.3 KiB
Python
122 lines
4.3 KiB
Python
"""单写者 CSV。未记入进度的尾部会在下次打开时丢掉并重新下载。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import csv
|
|
import io
|
|
import json
|
|
import os
|
|
import threading
|
|
from pathlib import Path
|
|
|
|
|
|
class CsvJournal:
|
|
def __init__(self, csv_path: Path, progress_path: Path, headers: list[str]):
|
|
self.csv_path = csv_path
|
|
self.progress_path = progress_path
|
|
self.headers = headers
|
|
self.completed: set[str] = set()
|
|
self.written_rows = 0
|
|
self._file = None
|
|
self._lock = threading.Lock()
|
|
|
|
def open(self) -> None:
|
|
self.csv_path.parent.mkdir(parents=True, exist_ok=True)
|
|
records = self._read_progress()
|
|
size = self.csv_path.stat().st_size if self.csv_path.exists() else 0
|
|
kept: list[dict] = []
|
|
previous = 0
|
|
for record in records:
|
|
offset = int(record["offset"])
|
|
if offset < previous or offset > size:
|
|
break
|
|
kept.append(
|
|
{
|
|
"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
|
|
self.written_rows = 0
|
|
self._file.truncate(0)
|
|
self._file.seek(0)
|
|
self._file.write(b"\xef\xbb\xbf" + self._encode(self.headers))
|
|
self._file.flush()
|
|
os.fsync(self._file.fileno())
|
|
self.progress_path.write_text("", encoding="utf-8")
|
|
|
|
def write_rows(self, grid_id: str, rows: list[list[str]]) -> int:
|
|
if not rows:
|
|
raise ValueError("至少要写出一行")
|
|
with self._lock:
|
|
if grid_id in self.completed:
|
|
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:
|
|
written = 0
|
|
for grid_id, rows in items:
|
|
written += self.write_rows(grid_id, rows)
|
|
return written
|
|
|
|
def close(self) -> None:
|
|
with self._lock:
|
|
if self._file is not None:
|
|
self._file.close()
|
|
self._file = None
|
|
|
|
def _encode(self, row: list[str]) -> bytes:
|
|
buffer = io.StringIO(newline="")
|
|
writer = csv.writer(buffer, lineterminator="\r\n")
|
|
writer.writerow(row)
|
|
return buffer.getvalue().encode("utf-8")
|
|
|
|
def _read_progress(self) -> list[dict]:
|
|
if not self.progress_path.exists():
|
|
return []
|
|
records: list[dict] = []
|
|
for line in self.progress_path.read_text(encoding="utf-8").splitlines():
|
|
text = line.strip()
|
|
if not text:
|
|
continue
|
|
try:
|
|
record = json.loads(text)
|
|
records.append(
|
|
{
|
|
"id": str(record["id"]),
|
|
"offset": int(record["offset"]),
|
|
"rows": int(record.get("rows") or 0),
|
|
}
|
|
)
|
|
except (KeyError, TypeError, ValueError, json.JSONDecodeError):
|
|
break
|
|
return records
|
|
|
|
def _rewrite_progress(self, records: list[dict]) -> None:
|
|
lines = [json.dumps(item, ensure_ascii=False) for item in records]
|
|
text = ("\n".join(lines) + "\n") if lines else ""
|
|
self.progress_path.write_text(text, encoding="utf-8")
|