Total Complexity | 9 |
Total Lines | 55 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | """ |
||
2 | Temporary caching of search results as they progress. |
||
3 | """ |
||
4 | from pathlib import Path |
||
5 | from typing import Iterator, Sequence |
||
6 | |||
7 | import orjson |
||
|
|||
8 | from suretime import Suretime |
||
9 | |||
10 | from mandos import logger |
||
11 | |||
12 | |||
13 | class SearchCache: |
||
14 | def __init__(self, path: Path, compounds: Sequence[str]): |
||
15 | self._path = path |
||
16 | if self._meta_path.exists(): |
||
17 | self._data = orjson.loads(self._meta_path.read_text(encoding="utf8")) |
||
18 | logger.caution(f"Resuming {path} with {self.at} completed compounds") |
||
19 | else: |
||
20 | self._data = dict( |
||
21 | start=Suretime.tagged.now_utc_sys().iso, last=None, path=self.path, done=set() |
||
22 | ) |
||
23 | logger.debug(f"Starting fresh cache for {path}") |
||
24 | self._queue: Iterator[str] = iter([c for c in compounds if c not in self._data["done"]]) |
||
25 | |||
26 | def next(self) -> str: |
||
27 | return next(self._queue) |
||
28 | |||
29 | def save(self, *compounds: str) -> None: |
||
30 | for c in compounds: |
||
31 | self._data["done"].add(c) |
||
32 | data = orjson.dumps(self._data).decode(encoding="utf8") |
||
33 | self._meta_path.write_text(data) |
||
34 | logger.debug(f"Saved to {self._meta_path}") |
||
35 | |||
36 | @property |
||
37 | def path(self) -> Path: |
||
38 | return self._path |
||
39 | |||
40 | @property |
||
41 | def at(self) -> int: |
||
42 | return len(self._data["done"]) |
||
43 | |||
44 | @property |
||
45 | def _meta_path(self) -> Path: |
||
46 | return self._path.parent / (self._path.name + ".meta.json.tmp") |
||
47 | |||
48 | def kill(self) -> None: |
||
49 | self._data = None |
||
50 | self._meta_path.unlink() |
||
51 | logger.debug(f"Destroyed search cache {self._meta_path}") |
||
52 | |||
53 | |||
54 | __all__ = ["SearchCache"] |
||
55 |