cachebind 1.0.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.
Files changed (81) hide show
  1. cachebind/__init__.py +121 -0
  2. cachebind/indexes/__init__.py +61 -0
  3. cachebind/indexes/_breadcrumb.py +10 -0
  4. cachebind/indexes/_builder.py +171 -0
  5. cachebind/indexes/_serializer.py +17 -0
  6. cachebind/indexes/base.py +51 -0
  7. cachebind/indexes/evict.py +21 -0
  8. cachebind/indexes/key_value/__init__.py +14 -0
  9. cachebind/indexes/key_value/async_index.py +145 -0
  10. cachebind/indexes/key_value/base.py +30 -0
  11. cachebind/indexes/key_value/builder.py +170 -0
  12. cachebind/indexes/key_value/index.py +142 -0
  13. cachebind/indexes/ordered_sets/__init__.py +17 -0
  14. cachebind/indexes/ordered_sets/async_index.py +221 -0
  15. cachebind/indexes/ordered_sets/base.py +38 -0
  16. cachebind/indexes/ordered_sets/builder.py +146 -0
  17. cachebind/indexes/ordered_sets/index.py +218 -0
  18. cachebind/indexes/registry.py +38 -0
  19. cachebind/indexes/sets/__init__.py +14 -0
  20. cachebind/indexes/sets/async_index.py +124 -0
  21. cachebind/indexes/sets/base.py +24 -0
  22. cachebind/indexes/sets/builder.py +146 -0
  23. cachebind/indexes/sets/index.py +121 -0
  24. cachebind/indexes/tries/__init__.py +14 -0
  25. cachebind/indexes/tries/async_index.py +113 -0
  26. cachebind/indexes/tries/base.py +25 -0
  27. cachebind/indexes/tries/builder.py +141 -0
  28. cachebind/indexes/tries/index.py +113 -0
  29. cachebind/serializers/__init__.py +29 -0
  30. cachebind/serializers/bool_serializer.py +21 -0
  31. cachebind/serializers/dataclass_serializer.py +102 -0
  32. cachebind/serializers/datetime_serializer.py +22 -0
  33. cachebind/serializers/dict_serializer.py +29 -0
  34. cachebind/serializers/float_serializer.py +18 -0
  35. cachebind/serializers/int_serializer.py +20 -0
  36. cachebind/serializers/noop_serializer.py +19 -0
  37. cachebind/serializers/pydantic_serializer.py +29 -0
  38. cachebind/serializers/serializer.py +24 -0
  39. cachebind/serializers/str_serializer.py +13 -0
  40. cachebind/serializers/uuid_serializer.py +22 -0
  41. cachebind/storage/__init__.py +67 -0
  42. cachebind/storage/_redis.py +80 -0
  43. cachebind/storage/key_value/__init__.py +37 -0
  44. cachebind/storage/key_value/async_redis_hash_storage.py +73 -0
  45. cachebind/storage/key_value/async_redis_string_storage.py +72 -0
  46. cachebind/storage/key_value/async_storage.py +76 -0
  47. cachebind/storage/key_value/redis_hash_storage.py +73 -0
  48. cachebind/storage/key_value/redis_string_storage.py +72 -0
  49. cachebind/storage/key_value/storage.py +74 -0
  50. cachebind/storage/ordered_sets/__init__.py +29 -0
  51. cachebind/storage/ordered_sets/_values.py +60 -0
  52. cachebind/storage/ordered_sets/async_redis_ordered_set_storage.py +91 -0
  53. cachebind/storage/ordered_sets/async_storage.py +89 -0
  54. cachebind/storage/ordered_sets/redis_ordered_set_storage.py +88 -0
  55. cachebind/storage/ordered_sets/storage.py +85 -0
  56. cachebind/storage/sets/__init__.py +27 -0
  57. cachebind/storage/sets/async_redis_set_storage.py +54 -0
  58. cachebind/storage/sets/async_storage.py +49 -0
  59. cachebind/storage/sets/redis_set_storage.py +52 -0
  60. cachebind/storage/sets/storage.py +49 -0
  61. cachebind/storage/tries/__init__.py +27 -0
  62. cachebind/storage/tries/_reply.py +20 -0
  63. cachebind/storage/tries/_values.py +36 -0
  64. cachebind/storage/tries/async_redis_trie_storage.py +81 -0
  65. cachebind/storage/tries/async_storage.py +78 -0
  66. cachebind/storage/tries/redis_trie_storage.py +79 -0
  67. cachebind/storage/tries/storage.py +78 -0
  68. cachebind/tagging/__init__.py +19 -0
  69. cachebind/tagging/breadcrumbs/__init__.py +11 -0
  70. cachebind/tagging/breadcrumbs/colon_breadcrumbs.py +20 -0
  71. cachebind/tagging/breadcrumbs/noop_breadcrumbs.py +15 -0
  72. cachebind/tagging/breadcrumbs/protocol.py +15 -0
  73. cachebind/tagging/tag_keeper/__init__.py +12 -0
  74. cachebind/tagging/tag_keeper/_keys.py +10 -0
  75. cachebind/tagging/tag_keeper/async_set_tag_keeper.py +47 -0
  76. cachebind/tagging/tag_keeper/protocol.py +37 -0
  77. cachebind/tagging/tag_keeper/set_tag_keeper.py +47 -0
  78. cachebind-1.0.0.dist-info/METADATA +171 -0
  79. cachebind-1.0.0.dist-info/RECORD +81 -0
  80. cachebind-1.0.0.dist-info/WHEEL +4 -0
  81. cachebind-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,29 @@
1
+ """Value serializers. Storage values are strings.
2
+
3
+ ``PydanticSerializer`` stays in ``cachebind.serializers.pydantic_serializer`` so
4
+ importing this package does not require Pydantic.
5
+ """
6
+
7
+ from cachebind.serializers.bool_serializer import BoolSerializer
8
+ from cachebind.serializers.dataclass_serializer import DataclassSerializer
9
+ from cachebind.serializers.datetime_serializer import DatetimeSerializer
10
+ from cachebind.serializers.dict_serializer import DictSerializer
11
+ from cachebind.serializers.float_serializer import FloatSerializer
12
+ from cachebind.serializers.int_serializer import IntSerializer
13
+ from cachebind.serializers.noop_serializer import NoopSerializer
14
+ from cachebind.serializers.serializer import Serializer
15
+ from cachebind.serializers.str_serializer import StrSerializer
16
+ from cachebind.serializers.uuid_serializer import UuidSerializer
17
+
18
+ __all__ = [
19
+ "BoolSerializer",
20
+ "DataclassSerializer",
21
+ "DatetimeSerializer",
22
+ "DictSerializer",
23
+ "FloatSerializer",
24
+ "IntSerializer",
25
+ "NoopSerializer",
26
+ "Serializer",
27
+ "StrSerializer",
28
+ "UuidSerializer",
29
+ ]
@@ -0,0 +1,21 @@
1
+ """Boolean serializer."""
2
+
3
+ from cachebind.serializers.serializer import Serializer
4
+
5
+
6
+ class BoolSerializer(Serializer[bool, str]):
7
+ """``True`` and ``False`` as ``"true"`` and ``"false"``."""
8
+
9
+ def serialize(self, value: bool) -> str:
10
+ if value is True:
11
+ return "true"
12
+ if value is False:
13
+ return "false"
14
+ raise ValueError(f"expected bool, got {type(value).__name__}")
15
+
16
+ def deserialize(self, value: str) -> bool:
17
+ if value == "true":
18
+ return True
19
+ if value == "false":
20
+ return False
21
+ raise ValueError(f"invalid bool: {value!r}")
@@ -0,0 +1,102 @@
1
+ """Dataclass JSON serializer."""
2
+
3
+ import json
4
+ import types
5
+ from dataclasses import MISSING, asdict, fields, is_dataclass
6
+ from typing import Any, Union, get_args, get_origin, get_type_hints
7
+
8
+ from cachebind.serializers.serializer import Serializer
9
+
10
+
11
+ def _dump_json(value: object) -> str:
12
+ try:
13
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
14
+ except TypeError as exc:
15
+ raise ValueError("value is not JSON serializable") from exc
16
+
17
+
18
+ def _load_json(value: str) -> Any:
19
+ if not isinstance(value, str):
20
+ raise ValueError(f"invalid JSON: {value!r}")
21
+ try:
22
+ return json.loads(value)
23
+ except json.JSONDecodeError as exc:
24
+ raise ValueError(f"invalid JSON: {value!r}") from exc
25
+
26
+
27
+ def _is_dataclass_type(cls: object) -> bool:
28
+ return isinstance(cls, type) and is_dataclass(cls)
29
+
30
+
31
+ def _split_optional(hint: Any) -> tuple[Any, bool]:
32
+ origin = get_origin(hint)
33
+ if origin is Union or origin is types.UnionType:
34
+ args = get_args(hint)
35
+ non_none = [arg for arg in args if arg is not type(None)]
36
+ if len(args) == 2 and len(non_none) == 1:
37
+ return non_none[0], True
38
+ return hint, False
39
+
40
+
41
+ def _dataclass_collection(hint: Any) -> tuple[type[list[Any]] | type[tuple[Any, ...]], type] | None:
42
+ origin = get_origin(hint)
43
+ args = get_args(hint)
44
+ if origin is list and len(args) == 1 and _is_dataclass_type(args[0]):
45
+ return list, args[0]
46
+ if (
47
+ origin is tuple
48
+ and len(args) == 2
49
+ and args[1] is Ellipsis
50
+ and _is_dataclass_type(args[0])
51
+ ):
52
+ return tuple, args[0]
53
+ return None
54
+
55
+
56
+ def _from_json_value(hint: Any, value: Any) -> Any:
57
+ inner, optional = _split_optional(hint)
58
+ if optional and value is None:
59
+ return None
60
+ if _is_dataclass_type(inner):
61
+ return _dataclass_from_json(inner, value)
62
+ collection = _dataclass_collection(inner)
63
+ if collection is not None:
64
+ container, item_type = collection
65
+ if not isinstance(value, (list, tuple)):
66
+ raise ValueError(f"expected a list of {item_type.__name__}")
67
+ items = [_dataclass_from_json(item_type, item) for item in value]
68
+ return container(items)
69
+ return value
70
+
71
+
72
+ def _dataclass_from_json(cls: type, data: object) -> Any:
73
+ if not isinstance(data, dict):
74
+ raise ValueError(f"expected JSON object for {cls.__name__}")
75
+ hints = get_type_hints(cls)
76
+ kwargs: dict[str, Any] = {}
77
+ for field in fields(cls):
78
+ if not field.init:
79
+ continue
80
+ if field.name not in data:
81
+ if field.default is MISSING and field.default_factory is MISSING:
82
+ raise ValueError(f"missing field {cls.__name__}.{field.name}")
83
+ continue
84
+ kwargs[field.name] = _from_json_value(hints.get(field.name, Any), data[field.name])
85
+ return cls(**kwargs)
86
+
87
+
88
+ class DataclassSerializer[ModelType](Serializer[ModelType, str]):
89
+ """JSON object text for one dataclass type."""
90
+
91
+ def __init__(self, cls: type[ModelType]) -> None:
92
+ if not _is_dataclass_type(cls):
93
+ raise TypeError(f"expected a dataclass, got {cls!r}")
94
+ self._cls = cls
95
+
96
+ def serialize(self, value: ModelType) -> str:
97
+ if not isinstance(value, self._cls):
98
+ raise ValueError(f"expected {self._cls.__name__} instance")
99
+ return _dump_json(asdict(value))
100
+
101
+ def deserialize(self, value: str) -> ModelType:
102
+ return _dataclass_from_json(self._cls, _load_json(value))
@@ -0,0 +1,22 @@
1
+ """Datetime serializer."""
2
+
3
+ from datetime import datetime
4
+
5
+ from cachebind.serializers.serializer import Serializer
6
+
7
+
8
+ class DatetimeSerializer(Serializer[datetime, str]):
9
+ """ISO 8601 text via ``datetime.isoformat``."""
10
+
11
+ def serialize(self, value: datetime) -> str:
12
+ if not isinstance(value, datetime):
13
+ raise ValueError(f"expected datetime, got {type(value).__name__}")
14
+ return value.isoformat()
15
+
16
+ def deserialize(self, value: str) -> datetime:
17
+ if not isinstance(value, str):
18
+ raise ValueError(f"invalid datetime: {value!r}")
19
+ try:
20
+ return datetime.fromisoformat(value)
21
+ except ValueError as exc:
22
+ raise ValueError(f"invalid datetime: {value!r}") from exc
@@ -0,0 +1,29 @@
1
+ """Dict JSON serializer."""
2
+
3
+ import json
4
+ from typing import Any
5
+
6
+ from cachebind.serializers.serializer import Serializer
7
+
8
+
9
+ class DictSerializer(Serializer[dict[str, Any], str]):
10
+ """JSON object text for a dict."""
11
+
12
+ def serialize(self, value: dict[str, Any]) -> str:
13
+ if not isinstance(value, dict):
14
+ raise ValueError(f"expected dict, got {type(value).__name__}")
15
+ try:
16
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
17
+ except TypeError as exc:
18
+ raise ValueError("value is not JSON serializable") from exc
19
+
20
+ def deserialize(self, value: str) -> dict[str, Any]:
21
+ if not isinstance(value, str):
22
+ raise ValueError(f"invalid JSON: {value!r}")
23
+ try:
24
+ loaded = json.loads(value)
25
+ except json.JSONDecodeError as exc:
26
+ raise ValueError(f"invalid JSON: {value!r}") from exc
27
+ if not isinstance(loaded, dict):
28
+ raise ValueError(f"expected JSON object, got {type(loaded).__name__}")
29
+ return loaded
@@ -0,0 +1,18 @@
1
+ """Float serializer."""
2
+
3
+ from cachebind.serializers.serializer import Serializer
4
+
5
+
6
+ class FloatSerializer(Serializer[float, str]):
7
+ """Float text via ``repr``, which round-trips finite floats."""
8
+
9
+ def serialize(self, value: float) -> str:
10
+ return repr(value)
11
+
12
+ def deserialize(self, value: str) -> float:
13
+ if isinstance(value, bool) or not isinstance(value, str):
14
+ raise ValueError(f"invalid float: {value!r}")
15
+ try:
16
+ return float(value)
17
+ except ValueError as exc:
18
+ raise ValueError(f"invalid float: {value!r}") from exc
@@ -0,0 +1,20 @@
1
+ """Integer serializer."""
2
+
3
+ from cachebind.serializers.serializer import Serializer
4
+
5
+
6
+ class IntSerializer(Serializer[int, str]):
7
+ """Decimal integer text. ``bool`` is rejected because it is an ``int`` subclass."""
8
+
9
+ def serialize(self, value: int) -> str:
10
+ if isinstance(value, bool):
11
+ raise ValueError("expected int, got bool")
12
+ return str(value)
13
+
14
+ def deserialize(self, value: str) -> int:
15
+ if isinstance(value, bool) or not isinstance(value, str):
16
+ raise ValueError(f"invalid int: {value!r}")
17
+ try:
18
+ return int(value)
19
+ except ValueError as exc:
20
+ raise ValueError(f"invalid int: {value!r}") from exc
@@ -0,0 +1,19 @@
1
+ """No-op serializer."""
2
+
3
+ from typing import cast
4
+
5
+ from cachebind.serializers.serializer import Serializer
6
+
7
+
8
+ class NoopSerializer[ValueType, StorageType](Serializer[ValueType, StorageType]):
9
+ """Identity when value and storage types match.
10
+
11
+ When they differ, this instance is only a build-time placeholder. Pass
12
+ ``serializer=`` on index calls that serialize or deserialize.
13
+ """
14
+
15
+ def serialize(self, value: ValueType) -> StorageType:
16
+ return cast(StorageType, value)
17
+
18
+ def deserialize(self, value: StorageType) -> ValueType:
19
+ return cast(ValueType, value)
@@ -0,0 +1,29 @@
1
+ """Pydantic serializer. Importing this module requires the ``pydantic`` extra."""
2
+
3
+ from cachebind.serializers.serializer import Serializer
4
+
5
+ try:
6
+ from pydantic import BaseModel
7
+ except ImportError as exc:
8
+ raise ImportError(
9
+ "Pydantic support is not installed. Install it with: pip install 'cachebind[pydantic]'"
10
+ ) from exc
11
+
12
+
13
+ class PydanticSerializer[ModelType: BaseModel](Serializer[ModelType, str]):
14
+ """JSON text for one Pydantic ``BaseModel`` subclass."""
15
+
16
+ def __init__(self, model: type[ModelType]) -> None:
17
+ if not isinstance(model, type) or not issubclass(model, BaseModel):
18
+ raise TypeError(f"expected a BaseModel subclass, got {model!r}")
19
+ self._model = model
20
+
21
+ def serialize(self, value: ModelType) -> str:
22
+ if not isinstance(value, self._model):
23
+ raise ValueError(f"expected {self._model.__name__} instance")
24
+ return value.model_dump_json()
25
+
26
+ def deserialize(self, value: str) -> ModelType:
27
+ if not isinstance(value, str):
28
+ raise ValueError(f"invalid JSON: {value!r}")
29
+ return self._model.model_validate_json(value)
@@ -0,0 +1,24 @@
1
+ """Serializer protocol."""
2
+
3
+ from collections.abc import Sequence
4
+ from typing import Protocol
5
+
6
+
7
+ class Serializer[ValueType, StorageType](Protocol):
8
+ """Convert a Python value to a storage value and back."""
9
+
10
+ def serialize(self, value: ValueType) -> StorageType:
11
+ """Convert ``value`` into its storage representation."""
12
+ ...
13
+
14
+ def deserialize(self, value: StorageType) -> ValueType:
15
+ """Restore a Python value from its storage representation."""
16
+ ...
17
+
18
+ def mserialize(self, values: Sequence[ValueType]) -> list[StorageType]:
19
+ """Convert each value into its storage representation, in input order."""
20
+ return [self.serialize(value) for value in values]
21
+
22
+ def mdeserialize(self, values: Sequence[StorageType]) -> list[ValueType]:
23
+ """Restore each value from its storage representation, in input order."""
24
+ return [self.deserialize(value) for value in values]
@@ -0,0 +1,13 @@
1
+ """String serializer."""
2
+
3
+ from cachebind.serializers.serializer import Serializer
4
+
5
+
6
+ class StrSerializer(Serializer[str, str]):
7
+ """Identity serializer, including the empty string."""
8
+
9
+ def serialize(self, value: str) -> str:
10
+ return value
11
+
12
+ def deserialize(self, value: str) -> str:
13
+ return value
@@ -0,0 +1,22 @@
1
+ """UUID serializer."""
2
+
3
+ from uuid import UUID
4
+
5
+ from cachebind.serializers.serializer import Serializer
6
+
7
+
8
+ class UuidSerializer(Serializer[UUID, str]):
9
+ """Canonical UUID text via ``str(uuid)``."""
10
+
11
+ def serialize(self, value: UUID) -> str:
12
+ if not isinstance(value, UUID):
13
+ raise ValueError(f"expected UUID, got {type(value).__name__}")
14
+ return str(value)
15
+
16
+ def deserialize(self, value: str) -> UUID:
17
+ if not isinstance(value, str):
18
+ raise ValueError(f"invalid UUID: {value!r}")
19
+ try:
20
+ return UUID(value)
21
+ except ValueError as exc:
22
+ raise ValueError(f"invalid UUID: {value!r}") from exc
@@ -0,0 +1,67 @@
1
+ """Storage.
2
+
3
+ Protocols do not require Redis. Importing a Redis storage class requires the ``redis`` extra.
4
+ """
5
+
6
+ import importlib
7
+
8
+ from cachebind.storage.key_value import AsyncKeyValueStorage, KeyValueStorage
9
+ from cachebind.storage.ordered_sets import AsyncOrderedSetStorage, OrderedSetStorage
10
+ from cachebind.storage.sets import AsyncSetStorage, SetStorage
11
+ from cachebind.storage.tries import AsyncTrieStorage, TrieStorage
12
+
13
+ __all__ = [
14
+ "AsyncKeyValueStorage",
15
+ "AsyncOrderedSetStorage",
16
+ "AsyncRedisHashStorage",
17
+ "AsyncRedisOrderedSetStorage",
18
+ "AsyncRedisSetStorage",
19
+ "AsyncRedisStringStorage",
20
+ "AsyncRedisTrieStorage",
21
+ "AsyncSetStorage",
22
+ "AsyncTrieStorage",
23
+ "KeyValueStorage",
24
+ "OrderedSetStorage",
25
+ "RedisHashStorage",
26
+ "RedisOrderedSetStorage",
27
+ "RedisSetStorage",
28
+ "RedisStringStorage",
29
+ "RedisTrieStorage",
30
+ "SetStorage",
31
+ "TrieStorage",
32
+ ]
33
+
34
+ _KEY_VALUE = {
35
+ "AsyncRedisHashStorage",
36
+ "AsyncRedisStringStorage",
37
+ "RedisHashStorage",
38
+ "RedisStringStorage",
39
+ }
40
+ _SETS = {
41
+ "AsyncRedisSetStorage",
42
+ "RedisSetStorage",
43
+ }
44
+ _ORDERED_SETS = {
45
+ "AsyncRedisOrderedSetStorage",
46
+ "RedisOrderedSetStorage",
47
+ }
48
+ _TRIES = {
49
+ "AsyncRedisTrieStorage",
50
+ "RedisTrieStorage",
51
+ }
52
+
53
+
54
+ def __getattr__(name: str) -> type:
55
+ if name in _KEY_VALUE:
56
+ module = importlib.import_module("cachebind.storage.key_value")
57
+ return getattr(module, name)
58
+ if name in _SETS:
59
+ module = importlib.import_module("cachebind.storage.sets")
60
+ return getattr(module, name)
61
+ if name in _ORDERED_SETS:
62
+ module = importlib.import_module("cachebind.storage.ordered_sets")
63
+ return getattr(module, name)
64
+ if name in _TRIES:
65
+ module = importlib.import_module("cachebind.storage.tries")
66
+ return getattr(module, name)
67
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,80 @@
1
+ """Redis client import and value decoding. Requires the ``redis`` extra."""
2
+
3
+ from uuid import uuid4
4
+
5
+ try:
6
+ from redis import Redis
7
+ from redis.asyncio import Redis as AsyncRedis
8
+ from redis.exceptions import ResponseError
9
+ except ImportError as exc:
10
+ raise ImportError(
11
+ "Redis support is not installed. Install it with: pip install 'cachebind[redis]'"
12
+ ) from exc
13
+
14
+
15
+ SCAN_COUNT = 100
16
+
17
+
18
+ def decode(value: object) -> str | None:
19
+ if value is None:
20
+ return None
21
+ if isinstance(value, str):
22
+ return value
23
+ if isinstance(value, bytes):
24
+ return value.decode("utf-8")
25
+ raise TypeError(f"unexpected Redis value type: {type(value).__name__}")
26
+
27
+
28
+ def required_text(value: object) -> str:
29
+ """Return ``value`` as text. ``None`` is an error."""
30
+ decoded = decode(value)
31
+ if decoded is None:
32
+ raise TypeError(f"unexpected Redis value type: {type(value).__name__}")
33
+ return decoded
34
+
35
+
36
+ def scan_done(cursor: object) -> bool:
37
+ """Return whether a Redis scan cursor marks the end of the walk."""
38
+ if isinstance(cursor, bytes):
39
+ cursor = cursor.decode("utf-8")
40
+ if isinstance(cursor, str):
41
+ return int(cursor) == 0
42
+ if isinstance(cursor, int) and not isinstance(cursor, bool):
43
+ return cursor == 0
44
+ raise TypeError(f"unexpected Redis scan cursor type: {type(cursor).__name__}")
45
+
46
+
47
+ def swap_key(client: Redis, name: str) -> str:
48
+ """Rename ``name`` aside and return the new name. A missing key still returns one."""
49
+ snapshot_name = f"{name}:swap:{uuid4().hex}"
50
+ try:
51
+ client.rename(name, snapshot_name)
52
+ except ResponseError as exc:
53
+ if "no such key" in str(exc).lower():
54
+ return snapshot_name
55
+ raise
56
+ return snapshot_name
57
+
58
+
59
+ async def async_swap_key(client: AsyncRedis, name: str) -> str:
60
+ """Rename ``name`` aside and return the new name. A missing key still returns one."""
61
+ snapshot_name = f"{name}:swap:{uuid4().hex}"
62
+ try:
63
+ await client.rename(name, snapshot_name)
64
+ except ResponseError as exc:
65
+ if "no such key" in str(exc).lower():
66
+ return snapshot_name
67
+ raise
68
+ return snapshot_name
69
+
70
+
71
+ __all__ = [
72
+ "AsyncRedis",
73
+ "Redis",
74
+ "SCAN_COUNT",
75
+ "async_swap_key",
76
+ "decode",
77
+ "required_text",
78
+ "scan_done",
79
+ "swap_key",
80
+ ]
@@ -0,0 +1,37 @@
1
+ """Key-value storage.
2
+
3
+ ``KeyValueStorage`` and ``AsyncKeyValueStorage`` do not require Redis.
4
+ Importing a Redis storage class requires the ``redis`` extra.
5
+ """
6
+
7
+ from cachebind.storage.key_value.async_storage import AsyncKeyValueStorage
8
+ from cachebind.storage.key_value.storage import KeyValueStorage
9
+
10
+ __all__ = [
11
+ "AsyncKeyValueStorage",
12
+ "AsyncRedisHashStorage",
13
+ "AsyncRedisStringStorage",
14
+ "KeyValueStorage",
15
+ "RedisHashStorage",
16
+ "RedisStringStorage",
17
+ ]
18
+
19
+
20
+ def __getattr__(name: str) -> type:
21
+ if name == "AsyncRedisHashStorage":
22
+ from cachebind.storage.key_value.async_redis_hash_storage import AsyncRedisHashStorage
23
+
24
+ return AsyncRedisHashStorage
25
+ if name == "AsyncRedisStringStorage":
26
+ from cachebind.storage.key_value.async_redis_string_storage import AsyncRedisStringStorage
27
+
28
+ return AsyncRedisStringStorage
29
+ if name == "RedisHashStorage":
30
+ from cachebind.storage.key_value.redis_hash_storage import RedisHashStorage
31
+
32
+ return RedisHashStorage
33
+ if name == "RedisStringStorage":
34
+ from cachebind.storage.key_value.redis_string_storage import RedisStringStorage
35
+
36
+ return RedisStringStorage
37
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,73 @@
1
+ """Asynchronous Redis hash storage."""
2
+
3
+ from collections.abc import AsyncIterator, Mapping, Sequence
4
+
5
+ from cachebind.storage._redis import (
6
+ SCAN_COUNT,
7
+ AsyncRedis,
8
+ async_swap_key,
9
+ decode,
10
+ required_text,
11
+ scan_done,
12
+ )
13
+ from cachebind.storage.key_value.async_storage import AsyncKeyValueStorage
14
+
15
+
16
+ class AsyncRedisHashStorage(AsyncKeyValueStorage[AsyncRedis, str, str]):
17
+ """Asynchronous Redis hashes. One instance can serve any hash name."""
18
+
19
+ async def get(self, client: AsyncRedis, name: str, field: str) -> str | None:
20
+ return decode(await client.hget(name, field))
21
+
22
+ async def set(
23
+ self, client: AsyncRedis, name: str, field: str, value: str, *, ttl: int | None = None
24
+ ) -> None:
25
+ await client.hset(name, field, value)
26
+ if ttl is not None:
27
+ await client.hexpire(name, ttl, field)
28
+
29
+ async def delete(self, client: AsyncRedis, name: str, field: str) -> None:
30
+ await client.hdel(name, field)
31
+
32
+ async def mdelete(self, client: AsyncRedis, name: str, fields: Sequence[str]) -> None:
33
+ if not fields:
34
+ return
35
+ await client.hdel(name, *fields)
36
+
37
+ async def exists(self, client: AsyncRedis, name: str, field: str) -> bool:
38
+ return bool(await client.hexists(name, field))
39
+
40
+ async def mget(self, client: AsyncRedis, name: str, fields: Sequence[str]) -> list[str | None]:
41
+ if not fields:
42
+ return []
43
+ raw_values = await client.hmget(name, list(fields))
44
+ return [decode(raw) for raw in raw_values]
45
+
46
+ async def mset(
47
+ self, client: AsyncRedis, name: str, items: Mapping[str, str], *, ttl: int | None = None
48
+ ) -> None:
49
+ if not items:
50
+ return
51
+ mapping = dict(items)
52
+ await client.hset(name, mapping=mapping)
53
+ if ttl is not None:
54
+ await client.hexpire(name, ttl, *mapping)
55
+
56
+ async def swap(self, client: AsyncRedis, name: str) -> str:
57
+ return await async_swap_key(client, name)
58
+
59
+ async def drop(self, client: AsyncRedis, name: str) -> None:
60
+ await client.delete(name)
61
+
62
+ async def iter(
63
+ self, client: AsyncRedis, name: str, *, count: int = SCAN_COUNT
64
+ ) -> AsyncIterator[tuple[str, str]]:
65
+ cursor: object = 0
66
+ while True:
67
+ cursor, raw = await client.hscan(name, cursor=cursor, count=count)
68
+ if not isinstance(raw, dict):
69
+ raise TypeError(f"unexpected Redis hash scan type: {type(raw).__name__}")
70
+ for field, value in raw.items():
71
+ yield required_text(field), required_text(value)
72
+ if scan_done(cursor):
73
+ return