|
| 1 | +from __future__ import annotations |
| 2 | +from typing import Tuple, TypeVar, Generic, Any, Callable |
| 3 | +from . import utils, io_unsafe, locking |
| 4 | + |
| 5 | +from contextlib import contextmanager |
| 6 | + |
| 7 | + |
| 8 | +T = TypeVar("T") |
| 9 | +JSONSerializable = TypeVar("JSONSerializable", str, int, float, bool, None, list, dict) |
| 10 | + |
| 11 | + |
| 12 | + |
| 13 | +def type_cast(obj, as_type): |
| 14 | + return obj if as_type is None else as_type(obj) |
| 15 | + |
| 16 | + |
| 17 | + |
| 18 | +class SessionBase: |
| 19 | + in_session: bool |
| 20 | + db_name: str |
| 21 | + as_type: T |
| 22 | + |
| 23 | + def __init__(self, db_name: str, as_type): |
| 24 | + self.in_session = False |
| 25 | + self.db_name = db_name |
| 26 | + self.as_type = as_type |
| 27 | + |
| 28 | + def __enter__(self): |
| 29 | + self.in_session = True |
| 30 | + self.data_handle = {} |
| 31 | + |
| 32 | + def __exit__(self, type, value, tb): |
| 33 | + write_lock = getattr(self, "write_lock", None) |
| 34 | + if write_lock is not None: |
| 35 | + if isinstance(write_lock, list): |
| 36 | + for lock in write_lock: |
| 37 | + lock._unlock() |
| 38 | + else: |
| 39 | + write_lock._unlock() |
| 40 | + self.write_lock, self.in_session = None, False |
| 41 | + |
| 42 | + def write(self): |
| 43 | + if not self.in_session: |
| 44 | + raise PermissionError("Only call write() inside a with statement.") |
| 45 | + |
| 46 | + |
| 47 | + |
| 48 | +@contextmanager |
| 49 | +def safe_context(super, self, *, db_names_to_lock=None): |
| 50 | + """ |
| 51 | + If an exception happens in the context, the __exit__ method of the passed super |
| 52 | + class will be called. |
| 53 | + """ |
| 54 | + super.__enter__() |
| 55 | + try: |
| 56 | + if isinstance(db_names_to_lock, str): |
| 57 | + self.write_lock = locking.WriteLock(self.db_name) |
| 58 | + self.write_lock._lock() |
| 59 | + elif isinstance(db_names_to_lock, list): |
| 60 | + self.write_lock = [locking.WriteLock(x) for x in self.db_name] |
| 61 | + for lock in self.write_lock: |
| 62 | + lock._lock() |
| 63 | + yield |
| 64 | + except BaseException as e: |
| 65 | + super.__exit__(type(e), e, e.__traceback__) |
| 66 | + raise e |
| 67 | + |
| 68 | + |
| 69 | + |
| 70 | +######################################################################################## |
| 71 | +#### File sessions |
| 72 | +######################################################################################## |
| 73 | + |
| 74 | + |
| 75 | + |
| 76 | +class SessionFileFull(SessionBase, Generic[T]): |
| 77 | + """ |
| 78 | + Context manager for read-write access to a full file. |
| 79 | +
|
| 80 | + Efficiency: |
| 81 | + Reads and writes the entire file. |
| 82 | + """ |
| 83 | + |
| 84 | + def __enter__(self) -> Tuple[SessionFileFull, JSONSerializable | T]: |
| 85 | + with safe_context(super(), self, db_names_to_lock=self.db_name): |
| 86 | + self.data_handle = io_unsafe.read(self.db_name) |
| 87 | + return self, type_cast(self.data_handle, self.as_type) |
| 88 | + |
| 89 | + def write(self): |
| 90 | + super().write() |
| 91 | + io_unsafe.write(self.db_name, self.data_handle) |
| 92 | + |
| 93 | + |
| 94 | + |
| 95 | +class SessionFileKey(SessionBase, Generic[T]): |
| 96 | + """ |
| 97 | + Context manager for read-write access to a single key-value item in a file. |
| 98 | +
|
| 99 | + Efficiency: |
| 100 | + Uses partial reading, which allows only reading the bytes of the key-value item. |
| 101 | + When writing, only the bytes of the key-value and the bytes of the file after |
| 102 | + the key-value are written. |
| 103 | + """ |
| 104 | + |
| 105 | + def __init__(self, db_name: str, key: str, as_type: T): |
| 106 | + super().__init__(db_name, as_type) |
| 107 | + self.key = key |
| 108 | + |
| 109 | + def __enter__(self) -> Tuple[SessionFileKey, JSONSerializable | T]: |
| 110 | + with safe_context(super(), self, db_names_to_lock=self.db_name): |
| 111 | + self.partial_handle = io_unsafe.get_partial_file_handle(self.db_name, self.key) |
| 112 | + self.data_handle = self.partial_handle.partial_dict.value |
| 113 | + return self, type_cast(self.data_handle, self.as_type) |
| 114 | + |
| 115 | + def write(self): |
| 116 | + super().write() |
| 117 | + io_unsafe.partial_write(self.partial_handle) |
| 118 | + |
| 119 | + |
| 120 | + |
| 121 | +class SessionFileWhere(SessionBase, Generic[T]): |
| 122 | + """ |
| 123 | + Context manager for read-write access to selection of key-value items in a file. |
| 124 | + The where callable is called with the key and value of each item in the file. |
| 125 | +
|
| 126 | + Efficiency: |
| 127 | + Reads and writes the entire file, so it is not more efficient than |
| 128 | + SessionFileFull. |
| 129 | + """ |
| 130 | + def __init__(self, db_name: str, where: Callable[[Any, Any], bool], as_type: T): |
| 131 | + super().__init__(db_name, as_type) |
| 132 | + self.where = where |
| 133 | + |
| 134 | + def __enter__(self) -> Tuple[SessionFileWhere, JSONSerializable | T]: |
| 135 | + with safe_context(super(), self, db_names_to_lock=self.db_name): |
| 136 | + self.original_data = io_unsafe.read(self.db_name) |
| 137 | + for k, v in self.original_data.items(): |
| 138 | + if self.where(k, v): |
| 139 | + self.data_handle[k] = v |
| 140 | + return self, type_cast(self.data_handle, self.as_type) |
| 141 | + |
| 142 | + def write(self): |
| 143 | + super().write() |
| 144 | + self.original_data.update(self.data_handle) |
| 145 | + io_unsafe.write(self.db_name, self.original_data) |
| 146 | + |
| 147 | + |
| 148 | + |
| 149 | +######################################################################################## |
| 150 | +#### File sessions |
| 151 | +######################################################################################## |
| 152 | + |
| 153 | + |
| 154 | + |
| 155 | +class SessionDirFull(SessionBase, Generic[T]): |
| 156 | + """ |
| 157 | + Context manager for read-write access to all files in a directory. |
| 158 | + They are provided as a dict of {str(file_name): dict(file_content)}, where the |
| 159 | + file name does not contain the directory name nor the file extension. |
| 160 | +
|
| 161 | + Efficiency: |
| 162 | + Fully reads and writes all files. |
| 163 | + """ |
| 164 | + def __init__(self, db_name: str, as_type: T): |
| 165 | + super().__init__(utils.find_all(db_name), as_type) |
| 166 | + |
| 167 | + def __enter__(self) -> Tuple[SessionDirFull, JSONSerializable | T]: |
| 168 | + with safe_context(super(), self, db_names_to_lock=self.db_name): |
| 169 | + self.data_handle = {n.split("/")[-1]: io_unsafe.read(n) for n in self.db_name} |
| 170 | + return self, type_cast(self.data_handle, self.as_type) |
| 171 | + |
| 172 | + def write(self): |
| 173 | + super().write() |
| 174 | + for name in self.db_name: |
| 175 | + io_unsafe.write(name, self.data_handle[name.split("/")[-1]]) |
| 176 | + |
| 177 | + |
| 178 | + |
| 179 | +class SessionDirWhere(SessionBase, Generic[T]): |
| 180 | + """ |
| 181 | + Context manager for read-write access to selection of files in a directory. |
| 182 | + The where callable is called with the file name and parsed content of each file. |
| 183 | +
|
| 184 | + Efficiency: |
| 185 | + Fully reads all files, but only writes the selected files. |
| 186 | + """ |
| 187 | + def __init__(self, db_name: str, where: Callable[[Any, Any], bool], as_type: T): |
| 188 | + super().__init__(utils.find_all(db_name), as_type) |
| 189 | + self.where = where |
| 190 | + |
| 191 | + def __enter__(self) -> Tuple[SessionDirWhere, JSONSerializable | T]: |
| 192 | + with safe_context(super(), self): |
| 193 | + selected_db_names, write_lock = [], [] |
| 194 | + for db_name in self.db_name: |
| 195 | + lock = locking.WriteLock(db_name) |
| 196 | + lock._lock() |
| 197 | + k, v = db_name.split("/")[-1], io_unsafe.read(db_name) |
| 198 | + if self.where(k, v): |
| 199 | + self.data_handle[k] = v |
| 200 | + write_lock.append(lock) |
| 201 | + selected_db_names.append(db_name) |
| 202 | + else: |
| 203 | + lock._unlock() |
| 204 | + self.write_lock = write_lock |
| 205 | + self.db_name = selected_db_names |
| 206 | + return self, type_cast(self.data_handle, self.as_type) |
| 207 | + |
| 208 | + def write(self): |
| 209 | + super().write() |
| 210 | + for name in self.db_name: |
| 211 | + io_unsafe.write(name, self.data_handle[name.split("/")[-1]]) |
0 commit comments