Read-only Store variant with a size-aware LRU for repeated lookups.
| 91 | |
| 92 | |
| 93 | class CachingStore(Store): |
| 94 | """Read-only Store variant with a size-aware LRU for repeated lookups.""" |
| 95 | |
| 96 | def __init__( |
| 97 | self, |
| 98 | db_path: str, |
| 99 | *, |
| 100 | max_cache_bytes: int = _MANPAGE_CACHE_MAX_BYTES, |
| 101 | max_entry_bytes: int = _MANPAGE_CACHE_MAX_ENTRY_BYTES, |
| 102 | max_entries: int = _MANPAGE_CACHE_MAX_ENTRIES, |
| 103 | ) -> None: |
| 104 | self._db_path = db_path |
| 105 | self._local = local() |
| 106 | self._stores: list[Store] = [] |
| 107 | self._stores_lock = RLock() |
| 108 | self._closed = False |
| 109 | self._lock = RLock() |
| 110 | self._manpage_cache: LRUCache[_CacheKey, _CacheValue] = LRUCache( |
| 111 | maxsize=max_cache_bytes, |
| 112 | getsizeof=_estimate_cache_value_size, |
| 113 | ) |
| 114 | self._manpage_cache_hits = 0 |
| 115 | self._manpage_cache_misses = 0 |
| 116 | self._manpage_cache_max_entry_bytes = max_entry_bytes |
| 117 | self._manpage_cache_max_entries = max_entries |
| 118 | |
| 119 | @property |
| 120 | def _conn(self) -> sqlite3.Connection: |
| 121 | # Inherited read-only Store methods use ``self._conn``. Route them |
| 122 | # through the current thread's underlying Store connection. |
| 123 | return self._store()._conn |
| 124 | |
| 125 | def _store(self) -> Store: |
| 126 | if self._closed: |
| 127 | raise RuntimeError("CachingStore is closed") |
| 128 | |
| 129 | thread_store = getattr(self._local, "store", None) |
| 130 | if thread_store is not None: |
| 131 | return thread_store |
| 132 | |
| 133 | with self._stores_lock: |
| 134 | if self._closed: |
| 135 | raise RuntimeError("CachingStore is closed") |
| 136 | |
| 137 | thread_store = Store(self._db_path, read_only=True) |
| 138 | self._local.store = thread_store |
| 139 | self._stores.append(thread_store) |
| 140 | return thread_store |
| 141 | |
| 142 | @classmethod |
| 143 | def create(cls, db_path: str) -> NoReturn: |
| 144 | raise TypeError("CachingStore is read-only; use Store.create() to build a DB") |
| 145 | |
| 146 | def close(self) -> None: |
| 147 | with self._stores_lock: |
| 148 | self._closed = True |
| 149 | stores = self._stores |
| 150 | self._stores = [] |