cli-watch-kit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,48 @@
1
+ """A small in-memory cache bounded by bytes, for what the daemon fetched on behalf of its clients.
2
+
3
+ The key always carries the version of what it holds (a job id of a finished job, a discussion id with the signature
4
+ of its notes), so a hit is never stale and nothing needs invalidating. The least recently used entries go first.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections import OrderedDict
10
+ from collections.abc import Hashable
11
+
12
+ DEFAULT_MAX_BYTES = 64 * 1024 * 1024
13
+
14
+
15
+ class ByteBoundedCache[V]:
16
+ def __init__(self, max_bytes: int = DEFAULT_MAX_BYTES) -> None:
17
+ self.max_bytes = max_bytes
18
+ self.bytes = 0
19
+ self.hits = 0
20
+ self.misses = 0
21
+ self._entries: OrderedDict[Hashable, tuple[V, int]] = OrderedDict()
22
+
23
+ def get(self, key: Hashable) -> V | None:
24
+ entry = self._entries.get(key)
25
+ if entry is None:
26
+ self.misses += 1
27
+ return None
28
+ self._entries.move_to_end(key)
29
+ self.hits += 1
30
+ return entry[0]
31
+
32
+ def put(self, key: Hashable, value: V, size: int) -> None:
33
+ if size > self.max_bytes:
34
+ return
35
+ old = self._entries.pop(key, None)
36
+ if old is not None:
37
+ self.bytes -= old[1]
38
+ self._entries[key] = (value, size)
39
+ self.bytes += size
40
+ while self.bytes > self.max_bytes:
41
+ _, (_, dropped) = self._entries.popitem(last=False)
42
+ self.bytes -= dropped
43
+
44
+ def __len__(self) -> int:
45
+ return len(self._entries)
46
+
47
+ def describe(self) -> dict[str, int]:
48
+ return {"entries": len(self), "bytes": self.bytes, "hits": self.hits, "misses": self.misses}