feat: 把去重后的全市栅格编号写入 ids.spool
This commit is contained in:
@@ -0,0 +1,218 @@
|
||||
"""全市编号暂存。去重后按行追加,批量 fsync,并记下已提交行数。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class IdSpool:
|
||||
"""ids.spool 每行一个编号。meta 记录已 fsync 的行数、是否读完和失败块。"""
|
||||
|
||||
batch_size = 200
|
||||
flush_seconds = 0.5
|
||||
|
||||
def __init__(self, directory: Path) -> None:
|
||||
self.directory = Path(directory)
|
||||
self.path = self.directory / "ids.spool"
|
||||
self.meta_path = self.directory / "ids.spool.meta"
|
||||
self.seen: set[int] = set()
|
||||
self.committed = 0
|
||||
self.complete = False
|
||||
self.failed_tiles: list[list[float]] = []
|
||||
self._pending: list[str] = []
|
||||
self._pending_at = 0.0
|
||||
self._file = None
|
||||
self._read = None
|
||||
self._read_offset = 0
|
||||
self._committed_size = 0
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def open(self) -> None:
|
||||
self.directory.mkdir(parents=True, exist_ok=True)
|
||||
meta = self._read_meta()
|
||||
raw = self.path.read_bytes() if self.path.exists() else b""
|
||||
lines = raw.splitlines()
|
||||
if meta is None:
|
||||
if raw and not raw.endswith(b"\n"):
|
||||
lines = lines[:-1]
|
||||
committed = len(lines)
|
||||
complete = False
|
||||
failed: list[list[float]] = []
|
||||
else:
|
||||
committed = int(meta.get("committed") or 0)
|
||||
complete = bool(meta.get("complete"))
|
||||
failed = [list(item) for item in meta.get("failedTiles") or []]
|
||||
if len(lines) > committed:
|
||||
lines = lines[:committed]
|
||||
elif len(lines) < committed:
|
||||
committed = len(lines)
|
||||
complete = False
|
||||
data = b"".join(line + b"\n" for line in lines)
|
||||
with open(self.path, "wb") as handle:
|
||||
handle.write(data)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
self.committed = len(lines)
|
||||
self.complete = complete
|
||||
self.failed_tiles = failed
|
||||
self.seen = set()
|
||||
for line in lines:
|
||||
text = line.decode("utf-8").strip()
|
||||
if text.isdigit():
|
||||
self.seen.add(int(text))
|
||||
self._committed_size = len(data)
|
||||
self._pending = []
|
||||
self._pending_at = 0.0
|
||||
self._read_offset = 0
|
||||
self._file = open(self.path, "a+b")
|
||||
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:
|
||||
self._write_meta()
|
||||
|
||||
def add(self, grid_id: str) -> bool:
|
||||
"""去重后放入待写缓冲。编号按整数比较,010 与 10 视为同一个。"""
|
||||
if not str(grid_id).isdigit():
|
||||
return False
|
||||
number = int(grid_id)
|
||||
with self._lock:
|
||||
if number in self.seen:
|
||||
return False
|
||||
self.seen.add(number)
|
||||
self._remember(str(number))
|
||||
return True
|
||||
|
||||
def append(self, grid_id: str) -> None:
|
||||
"""调用方已经放进 seen 时,只追加到待写缓冲。"""
|
||||
with self._lock:
|
||||
self._remember(str(grid_id))
|
||||
|
||||
def due(self) -> bool:
|
||||
with self._lock:
|
||||
if not self._pending:
|
||||
return False
|
||||
if len(self._pending) >= self.batch_size:
|
||||
return True
|
||||
return time.monotonic() - self._pending_at >= self.flush_seconds
|
||||
|
||||
def flush(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 mark_complete(self) -> None:
|
||||
# 先把缓冲写稳,再标记读完,避免下载侧提前认为没有新编号。
|
||||
self.flush()
|
||||
with self._lock:
|
||||
self.complete = True
|
||||
self._write_meta()
|
||||
|
||||
def caught_up(self) -> bool:
|
||||
"""编号已经读完,并且下载侧已经取走全部已提交行。"""
|
||||
with self._lock:
|
||||
return self.complete and not self._pending and self._read_offset >= self._committed_size
|
||||
|
||||
def pull(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 close(self) -> None:
|
||||
if self._file is not None or self._pending:
|
||||
self.flush()
|
||||
if self._file is not None:
|
||||
self._file.close()
|
||||
self._file = None
|
||||
if self._read is not None:
|
||||
self._read.close()
|
||||
self._read = None
|
||||
|
||||
@classmethod
|
||||
def listing_finished(cls, directory: Path) -> bool:
|
||||
data = cls._peek(directory)
|
||||
if data is None:
|
||||
return False
|
||||
return bool(data.get("complete")) and not data.get("failedTiles")
|
||||
|
||||
@classmethod
|
||||
def committed_count(cls, directory: Path) -> int:
|
||||
data = cls._peek(directory)
|
||||
if data is None:
|
||||
return 0
|
||||
try:
|
||||
return int(data.get("committed") or 0)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
def _remember(self, grid_id: str) -> None:
|
||||
if not self._pending:
|
||||
self._pending_at = time.monotonic()
|
||||
self._pending.append(grid_id)
|
||||
|
||||
def _read_at(self, offset: int, size: int) -> bytes:
|
||||
self._read.seek(offset)
|
||||
blob = self._read.read(size)
|
||||
if len(blob) == size:
|
||||
return blob
|
||||
self._read.close()
|
||||
self._read = open(self.path, "rb")
|
||||
self._read.seek(offset)
|
||||
return self._read.read(size)
|
||||
|
||||
def _read_meta(self) -> dict | None:
|
||||
if not self.meta_path.exists():
|
||||
return None
|
||||
try:
|
||||
data = json.loads(self.meta_path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return None
|
||||
if not isinstance(data, dict):
|
||||
return None
|
||||
return data
|
||||
|
||||
def _write_meta(self) -> None:
|
||||
with self._lock:
|
||||
payload = {
|
||||
"committed": self.committed,
|
||||
"complete": self.complete,
|
||||
"failedTiles": self.failed_tiles,
|
||||
}
|
||||
text = json.dumps(payload, ensure_ascii=False)
|
||||
temporary = self.meta_path.with_suffix(".tmp")
|
||||
with open(temporary, "w", encoding="utf-8") as handle:
|
||||
handle.write(text)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temporary, self.meta_path)
|
||||
|
||||
@staticmethod
|
||||
def _peek(directory: Path) -> dict | None:
|
||||
path = Path(directory) / "ids.spool.meta"
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return None
|
||||
if not isinstance(data, dict):
|
||||
return None
|
||||
return data
|
||||
Reference in New Issue
Block a user