Coverage for seqbank/storage.py: 100.00%
141 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-27 04:47 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-27 04:47 +0000
1"""Byte-key/byte-value storage adapters and persistent engine identification."""
3import importlib
4import json
5import hashlib
6from enum import Enum
7from pathlib import Path
8from threading import RLock
9from types import ModuleType
10from typing import Iterable, Iterator, Protocol
12from .exceptions import SeqBankError
15class Engine(str, Enum):
16 """Supported database engines (also accepted as strings in the Python API)."""
18 SPEEDICT = "speedict"
19 ROCKSDICT = "rocksdict"
20 LMDB = "lmdb"
22 def __str__(self) -> str:
23 return self.value
26ENGINES = tuple(engine.value for engine in Engine)
27METADATA = "seqbank.json"
30def _storage_key(key: bytes) -> bytes:
31 """Bound URL tracking keys for LMDB while preserving the internal namespace."""
32 if key.startswith(b"/seqbank/url/") and len(key) > 511:
33 return b"/seqbank/url-sha256/" + hashlib.sha256(key).hexdigest().encode("ascii")
34 return key
37class Storage(Protocol):
38 """Byte-key/byte-value interface implemented by every engine adapter."""
40 def __getitem__(self, key: bytes) -> bytes: ...
42 def __setitem__(self, key: bytes, value: bytes) -> None: ...
44 def __delitem__(self, key: bytes) -> None: ...
46 def __contains__(self, key: bytes) -> bool: ...
48 def items(self) -> Iterator[tuple[bytes, bytes]]: ...
50 def keys(self) -> Iterator[bytes]: ...
52 def put_many(self, records: Iterable[tuple[bytes, bytes]]) -> None: ...
54 def close(self) -> None: ...
57class RocksStorage:
58 def __init__(self, module: ModuleType, path: Path, write: bool) -> None:
59 options = module.Options(raw_mode=True)
60 options.set_compression_type(module.DBCompressionType.none())
61 options.set_optimize_filters_for_hits(True)
62 options.optimize_for_point_lookup(1024)
63 options.set_max_open_files(500)
64 self.module = module
65 self.db = module.Rdict(
66 str(path),
67 options=options,
68 access_type=module.AccessType.read_write() if write else module.AccessType.read_only(),
69 )
71 def __getitem__(self, key: bytes) -> bytes:
72 try:
73 return self.db[key]
74 except KeyError:
75 normalized = _storage_key(key)
76 if normalized == key:
77 raise
78 return self.db[normalized]
80 def __setitem__(self, key: bytes, value: bytes) -> None:
81 self.db[self._write_key(key)] = bytes(value)
83 def __delitem__(self, key: bytes) -> None:
84 del self.db[self._write_key(key)]
86 def __contains__(self, key: bytes) -> bool:
87 if key in self.db:
88 return True
89 normalized = _storage_key(key)
90 return normalized != key and normalized in self.db
92 def items(self) -> Iterator[tuple[bytes, bytes]]:
93 return self.db.items()
95 def keys(self) -> Iterator[bytes]:
96 return self.db.keys()
98 def _write_key(self, key: bytes) -> bytes:
99 normalized = _storage_key(key)
100 # Preserve legacy raw URL records when updating an existing bank.
101 return key if normalized != key and key in self.db else normalized
103 def put_many(self, records: Iterable[tuple[bytes, bytes]]) -> None:
104 batch = self.module.WriteBatch(raw_mode=True)
105 for key, value in records:
106 batch.put(self._write_key(key), bytes(value))
107 self.db.write(batch)
109 def close(self) -> None:
110 self.db.close()
113class LMDBStorage:
114 def __init__(self, module: ModuleType, path: Path, write: bool) -> None:
115 # On 64-bit systems this reserves virtual address space, not RAM.
116 # Read-only banks skip LMDB's lock file: readers then take no file locks, which can hang
117 # on network filesystems when many processes open the same bank.
118 # while it is being read this way.
119 self.db = module.open(str(path), readonly=not write, create=write, map_size=1 << 40, lock=write)
120 self._write_lock = RLock()
122 def __getitem__(self, key: bytes) -> bytes:
123 with self.db.begin() as txn:
124 value = txn.get(_storage_key(key))
125 if value is None:
126 raise KeyError(key)
127 return value
129 def __setitem__(self, key: bytes, value: bytes) -> None:
130 with self._write_lock, self.db.begin(write=True) as txn:
131 txn.put(_storage_key(key), bytes(value))
133 def __delitem__(self, key: bytes) -> None:
134 with self._write_lock, self.db.begin(write=True) as txn:
135 if not txn.delete(_storage_key(key)):
136 raise KeyError(key)
138 def __contains__(self, key: bytes) -> bool:
139 with self.db.begin() as txn:
140 return txn.get(_storage_key(key)) is not None
142 def items(self) -> Iterator[tuple[bytes, bytes]]:
143 with self.db.begin() as txn:
144 with txn.cursor() as cursor:
145 yield from cursor
147 def keys(self) -> Iterator[bytes]:
148 for key, _ in self.items():
149 yield key
151 def put_many(self, records: Iterable[tuple[bytes, bytes]]) -> None:
152 with self._write_lock, self.db.begin(write=True) as txn:
153 for key, value in records:
154 txn.put(_storage_key(key), bytes(value))
156 def close(self) -> None:
157 self.db.close()
160INSTALL_HINTS = {
161 Engine.ROCKSDICT: "pip install 'seqbank[rocksdict]'",
162 Engine.SPEEDICT: "pip install 'seqbank[speedict]' (Speedict wheels require Python <3.13)",
163 Engine.LMDB: "pip install seqbank",
164}
167def default_engine() -> Engine:
168 """Engine for new banks: RocksDict if it can be imported, otherwise LMDB."""
169 try:
170 importlib.import_module(Engine.ROCKSDICT.value)
171 except ImportError:
172 return Engine.LMDB
173 return Engine.ROCKSDICT
176def open_storage(path: Path, write: bool, requested: Engine | str | None = None) -> tuple[Storage, Engine]:
177 """Identify existing banks; never try a different engine on an existing bank."""
178 if requested is not None and requested not in ENGINES:
179 raise SeqBankError(f"Unknown engine {requested!r}; choose from {', '.join(ENGINES)}")
180 if requested is not None:
181 requested = Engine(requested)
182 metadata_path = path / METADATA
183 existing = path.exists() and any(path.iterdir())
184 if metadata_path.exists():
185 try:
186 metadata = json.loads(metadata_path.read_text())
187 engine = Engine(metadata["engine"])
188 if metadata["format_version"] != 1 or engine not in ENGINES:
189 raise ValueError("unsupported format version or engine")
190 except (ValueError, KeyError, TypeError) as err:
191 raise SeqBankError(f"Invalid SeqBank metadata at {metadata_path}: {err}") from err
192 elif existing:
193 if not (path / "CURRENT").exists():
194 raise SeqBankError(f"Cannot identify SeqBank engine at {path}")
195 # All banks created before engine metadata were Speedict banks.
196 engine = Engine.SPEEDICT
197 else:
198 engine = requested or default_engine()
199 if requested is not None and requested != engine:
200 raise SeqBankError(f"Bank uses {engine}, not {requested}; convert it to a new directory instead")
201 try:
202 module = importlib.import_module(engine.value)
203 except ImportError as err:
204 raise SeqBankError(f"Engine {engine.value!r} is unavailable. Install with: {INSTALL_HINTS[engine]}.") from err
205 if write:
206 path.mkdir(parents=True, exist_ok=True)
207 storage = LMDBStorage(module, path, write) if engine == "lmdb" else RocksStorage(module, path, write)
208 if write and not metadata_path.exists():
209 try:
210 # Exclusive creation also permits independent LMDB writer processes.
211 with metadata_path.open("x") as output:
212 json.dump({"format_version": 1, "engine": engine}, output)
213 except FileExistsError:
214 pass
215 except Exception:
216 storage.close()
217 raise
218 return storage, engine