fix(history): make write() thread-safe

Guard DownloadHistory.write() with a threading.Lock so concurrent
worker threads do not corrupt or lose history entries during parallel
downloads. Lock wraps both _data mutation and disk flush; read-only
methods (is_downloaded, find) stay lock-free per CPython dict atomicity.

Closes #13
This commit is contained in:
AlexKucera committed 2026-06-03 17:15:57 +02:00
1 parent 2547bd1f22
commit a18232c063
5 files changed
+214 -3

No files matched your search

+6 -3
View File
@@ -2,6 +2,7 @@
import json
import logging
import threading
from dataclasses import dataclass, asdict
from pathlib import Path
@@ -25,6 +26,7 @@ class DownloadHistory:
def __init__(self, path: Path | str):
self._path = Path(path)
self._data: dict[str, dict] = {}
self._lock = threading.Lock()
self._load()
def _load(self) -> None:
@@ -51,9 +53,10 @@ class DownloadHistory:
return str(isbn) in self._data
def write(self, entry: HistoryEntry) -> None:
"""Persist a history entry to disk."""
self._data[entry.isbn] = asdict(entry)
self._flush()
"""Persist a history entry to disk. Thread-safe."""
with self._lock:
self._data[entry.isbn] = asdict(entry)
self._flush()
def _flush(self) -> None:
"""Write current in-memory state to disk."""