1# SPDX-FileCopyrightText: 2015 Eric Larson
2#
3# SPDX-License-Identifier: Apache-2.0
4
5"""
6The cache object API for implementing caches. The default is a thread
7safe in-memory dictionary.
8"""
9
10from __future__ import annotations
11
12from threading import Lock
13from typing import IO, TYPE_CHECKING, MutableMapping
14
15if TYPE_CHECKING:
16 from datetime import datetime
17
18
19class BaseCache:
20 def get(self, key: str) -> bytes | None:
21 raise NotImplementedError()
22
23 def set(
24 self, key: str, value: bytes, expires: int | datetime | None = None
25 ) -> None:
26 raise NotImplementedError()
27
28 def delete(self, key: str) -> None:
29 raise NotImplementedError()
30
31 def close(self) -> None:
32 pass
33
34
35class DictCache(BaseCache):
36 def __init__(self, init_dict: MutableMapping[str, bytes] | None = None) -> None:
37 self.lock = Lock()
38 self.data = init_dict or {}
39
40 def get(self, key: str) -> bytes | None:
41 return self.data.get(key, None)
42
43 def set(
44 self, key: str, value: bytes, expires: int | datetime | None = None
45 ) -> None:
46 with self.lock:
47 self.data.update({key: value})
48
49 def delete(self, key: str) -> None:
50 with self.lock:
51 if key in self.data:
52 self.data.pop(key)
53
54
55class SeparateBodyBaseCache(BaseCache):
56 """
57 In this variant, the body is not stored mixed in with the metadata, but is
58 passed in (as a bytes-like object) in a separate call to ``set_body()``.
59
60 That is, the expected interaction pattern is::
61
62 cache.set(key, serialized_metadata)
63 cache.set_body(key)
64
65 Similarly, the body should be loaded separately via ``get_body()``.
66 """
67
68 def set_body(self, key: str, body: bytes) -> None:
69 raise NotImplementedError()
70
71 def get_body(self, key: str) -> IO[bytes] | None:
72 """
73 Return the body as file-like object.
74 """
75 raise NotImplementedError()