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,79 @@
1
+ """Synchronous Redis trie storage. ``name`` is one suggestion dictionary."""
2
+
3
+ from collections.abc import Sequence
4
+
5
+ from cachebind.storage._redis import Redis, swap_key
6
+ from cachebind.storage.tries._reply import payloads_from_suggestions
7
+ from cachebind.storage.tries._values import length_value, sugadd_command, sugget_command
8
+ from cachebind.storage.tries.storage import TrieStorage
9
+
10
+
11
+ class RedisTrieStorage(TrieStorage[Redis, str]):
12
+ """Synchronous Redis Search trie. ``name`` is the suggestion-dictionary key.
13
+
14
+ Rank uses the stored score. A shorter remainder after the prefix ranks higher
15
+ than a longer suggestion with the same score. ``search`` returns payloads in that order.
16
+ """
17
+
18
+ def add(
19
+ self,
20
+ client: Redis,
21
+ name: str,
22
+ string: str,
23
+ score: float,
24
+ payload: str,
25
+ *,
26
+ increment: bool = False,
27
+ ) -> None:
28
+ client.execute_command(
29
+ *sugadd_command(name, string, score, payload, increment=increment)
30
+ )
31
+
32
+ def madd(
33
+ self,
34
+ client: Redis,
35
+ name: str,
36
+ entries: Sequence[tuple[str, float, str]],
37
+ *,
38
+ increment: bool = False,
39
+ ) -> None:
40
+ if not entries:
41
+ return
42
+ pipe = client.pipeline(transaction=False)
43
+ for string, score, payload in entries:
44
+ pipe.execute_command(
45
+ *sugadd_command(name, string, score, payload, increment=increment)
46
+ )
47
+ pipe.execute()
48
+
49
+ def remove(self, client: Redis, name: str, string: str) -> None:
50
+ client.execute_command("FT.SUGDEL", name, string)
51
+
52
+ def mremove(self, client: Redis, name: str, strings: Sequence[str]) -> None:
53
+ if not strings:
54
+ return
55
+ pipe = client.pipeline(transaction=False)
56
+ for string in strings:
57
+ pipe.execute_command("FT.SUGDEL", name, string)
58
+ pipe.execute()
59
+
60
+ def search(
61
+ self,
62
+ client: Redis,
63
+ name: str,
64
+ prefix: str,
65
+ *,
66
+ fuzzy: bool = False,
67
+ limit: int = 10,
68
+ ) -> list[str]:
69
+ raw = client.execute_command(*sugget_command(name, prefix, fuzzy=fuzzy, limit=limit))
70
+ return payloads_from_suggestions(raw)
71
+
72
+ def length(self, client: Redis, name: str) -> int:
73
+ return length_value(client.execute_command("FT.SUGLEN", name))
74
+
75
+ def swap(self, client: Redis, name: str) -> str:
76
+ return swap_key(client, name)
77
+
78
+ def drop(self, client: Redis, name: str) -> None:
79
+ client.delete(name)
@@ -0,0 +1,78 @@
1
+ """Synchronous trie storage."""
2
+
3
+ from collections.abc import Hashable, Sequence
4
+ from typing import Protocol, runtime_checkable
5
+
6
+
7
+ @runtime_checkable
8
+ class TrieStorage[ClientType, PayloadType: Hashable](Protocol):
9
+ """Synchronous trie storage.
10
+
11
+ ``client`` is the storage client for that call.
12
+ ``name`` is the trie name. ``string`` is one suggestion in that trie.
13
+ Each suggestion has one score and one payload. Adding a string that is already
14
+ present replaces its score and payload, unless ``increment`` is true.
15
+ ``increment`` adds the score to the stored score. Removing a missing string is not an error.
16
+ ``search`` returns payloads in rank order. ``limit`` is the maximum number of payloads.
17
+ ``fuzzy`` requests matches within one edit of ``prefix``.
18
+ """
19
+
20
+ def add(
21
+ self,
22
+ client: ClientType,
23
+ name: str,
24
+ string: str,
25
+ score: float,
26
+ payload: PayloadType,
27
+ *,
28
+ increment: bool = False,
29
+ ) -> None:
30
+ """Add ``string`` with ``score`` and ``payload``.
31
+
32
+ A string that is already present gets the new score and payload.
33
+ ``increment=True`` adds ``score`` to the stored score instead of replacing it.
34
+ """
35
+ ...
36
+
37
+ def madd(
38
+ self,
39
+ client: ClientType,
40
+ name: str,
41
+ entries: Sequence[tuple[str, float, PayloadType]],
42
+ *,
43
+ increment: bool = False,
44
+ ) -> None:
45
+ """Add every suggestion. A repeated string keeps the last score and payload."""
46
+ ...
47
+
48
+ def remove(self, client: ClientType, name: str, string: str) -> None:
49
+ """Remove ``string``. A missing string is not an error."""
50
+ ...
51
+
52
+ def mremove(self, client: ClientType, name: str, strings: Sequence[str]) -> None:
53
+ """Remove every string. Missing strings are not an error."""
54
+ ...
55
+
56
+ def search(
57
+ self,
58
+ client: ClientType,
59
+ name: str,
60
+ prefix: str,
61
+ *,
62
+ fuzzy: bool = False,
63
+ limit: int = 10,
64
+ ) -> list[PayloadType]:
65
+ """Return payloads for suggestions that match ``prefix``, in rank order."""
66
+ ...
67
+
68
+ def length(self, client: ClientType, name: str) -> int:
69
+ """Return the number of suggestion strings in the trie."""
70
+ ...
71
+
72
+ def swap(self, client: ClientType, name: str) -> str:
73
+ """Rename ``name`` aside and return the new name. A missing name still returns one."""
74
+ ...
75
+
76
+ def drop(self, client: ClientType, name: str) -> None:
77
+ """Delete ``name``. A missing name is not an error."""
78
+ ...
@@ -0,0 +1,19 @@
1
+ """Tags, breadcrumbs, and tag keepers."""
2
+
3
+ from cachebind.tagging.breadcrumbs import Breadcrumbs, ColonBreadcrumbs, NoopBreadcrumbs
4
+ from cachebind.tagging.tag_keeper import (
5
+ AsyncSetTagKeeper,
6
+ AsyncTagKeeper,
7
+ SetTagKeeper,
8
+ TagKeeper,
9
+ )
10
+
11
+ __all__ = [
12
+ "AsyncSetTagKeeper",
13
+ "AsyncTagKeeper",
14
+ "Breadcrumbs",
15
+ "ColonBreadcrumbs",
16
+ "NoopBreadcrumbs",
17
+ "SetTagKeeper",
18
+ "TagKeeper",
19
+ ]
@@ -0,0 +1,11 @@
1
+ """Breadcrumbs encode an index and an identifier into one string."""
2
+
3
+ from cachebind.tagging.breadcrumbs.colon_breadcrumbs import ColonBreadcrumbs
4
+ from cachebind.tagging.breadcrumbs.noop_breadcrumbs import NoopBreadcrumbs
5
+ from cachebind.tagging.breadcrumbs.protocol import Breadcrumbs
6
+
7
+ __all__ = [
8
+ "Breadcrumbs",
9
+ "ColonBreadcrumbs",
10
+ "NoopBreadcrumbs",
11
+ ]
@@ -0,0 +1,20 @@
1
+ """Colon-separated breadcrumbs."""
2
+
3
+ from cachebind.tagging.breadcrumbs.protocol import Breadcrumbs
4
+
5
+
6
+ class ColonBreadcrumbs(Breadcrumbs):
7
+ """Join and split an index and an identifier with a colon.
8
+
9
+ ``decode`` splits on the first colon, so an identifier may contain colons.
10
+ """
11
+
12
+ def encode(self, index: str, identifier: str) -> str:
13
+ return f"{index}:{identifier}"
14
+
15
+ def decode(self, value: str) -> tuple[str, str]:
16
+ parts = value.split(":", 1)
17
+ if len(parts) != 2:
18
+ raise ValueError(f"invalid breadcrumb: {value!r}")
19
+ index, identifier = parts
20
+ return index, identifier
@@ -0,0 +1,15 @@
1
+ """No-op breadcrumbs."""
2
+
3
+ from cachebind.tagging.breadcrumbs.protocol import Breadcrumbs
4
+
5
+
6
+ class NoopBreadcrumbs(Breadcrumbs):
7
+ """Always encode to an empty breadcrumb string."""
8
+
9
+ def encode(self, index: str, identifier: str) -> str:
10
+ return ""
11
+
12
+ def decode(self, value: str) -> tuple[str, str]:
13
+ if value != "":
14
+ raise ValueError(f"invalid breadcrumb: {value!r}")
15
+ return "", ""
@@ -0,0 +1,15 @@
1
+ """Breadcrumbs protocol."""
2
+
3
+ from typing import Protocol
4
+
5
+
6
+ class Breadcrumbs(Protocol):
7
+ """Encode an index and an identifier into one string, and split that string back."""
8
+
9
+ def encode(self, index: str, identifier: str) -> str:
10
+ """Join ``index`` and ``identifier`` into one string."""
11
+ ...
12
+
13
+ def decode(self, value: str) -> tuple[str, str]:
14
+ """Split ``value`` into the index and the identifier."""
15
+ ...
@@ -0,0 +1,12 @@
1
+ """Tag keepers group cache breadcrumbs in sets keyed by tag."""
2
+
3
+ from cachebind.tagging.tag_keeper.async_set_tag_keeper import AsyncSetTagKeeper
4
+ from cachebind.tagging.tag_keeper.protocol import AsyncTagKeeper, TagKeeper
5
+ from cachebind.tagging.tag_keeper.set_tag_keeper import SetTagKeeper
6
+
7
+ __all__ = [
8
+ "AsyncSetTagKeeper",
9
+ "AsyncTagKeeper",
10
+ "SetTagKeeper",
11
+ "TagKeeper",
12
+ ]
@@ -0,0 +1,10 @@
1
+ """Tag keeper storage key helpers."""
2
+
3
+ TAG_KEEPER_PREFIX = "tag_keeper"
4
+
5
+ DEFAULT_TAG_KEEPER_NAME = "default"
6
+
7
+
8
+ def tag_set_key(name: str, tag: str) -> str:
9
+ """Set storage key for one tag under a keeper name."""
10
+ return f"{TAG_KEEPER_PREFIX}:{name}:{tag}"
@@ -0,0 +1,47 @@
1
+ """Asynchronous set-backed tag keeper."""
2
+
3
+ from cachebind.indexes._builder import storage_client_type
4
+ from cachebind.indexes.base import get_registry
5
+ from cachebind.indexes.evict import AsyncEvictableIndex
6
+ from cachebind.storage.sets.async_storage import AsyncSetStorage
7
+ from cachebind.tagging.breadcrumbs.colon_breadcrumbs import ColonBreadcrumbs
8
+ from cachebind.tagging.breadcrumbs.protocol import Breadcrumbs
9
+ from cachebind.tagging.tag_keeper._keys import DEFAULT_TAG_KEEPER_NAME, tag_set_key
10
+
11
+
12
+ class AsyncSetTagKeeper[ClientType]:
13
+ """Collect breadcrumbs in sets ``tag_keeper:{name}:{tag}``; flush via registry eviction."""
14
+
15
+ def __init__(
16
+ self,
17
+ *,
18
+ storage: AsyncSetStorage[ClientType, str],
19
+ name: str = DEFAULT_TAG_KEEPER_NAME,
20
+ breadcrumbs: Breadcrumbs | None = None,
21
+ ) -> None:
22
+ self.name = name
23
+ self._storage = storage
24
+ self._client_type = storage_client_type("tag_keeper", type(storage), AsyncSetStorage)
25
+ self._breadcrumbs = ColonBreadcrumbs() if breadcrumbs is None else breadcrumbs
26
+
27
+ async def add(self, client: ClientType, tag: str, breadcrumb: str) -> None:
28
+ if breadcrumb == "":
29
+ return
30
+ await self._storage.add(client, tag_set_key(self.name, tag), breadcrumb)
31
+
32
+ async def madd(self, client: ClientType, tag: str, breadcrumbs: list[str]) -> None:
33
+ members = [item for item in breadcrumbs if item != ""]
34
+ if not members:
35
+ return
36
+ await self._storage.madd(client, tag_set_key(self.name, tag), members)
37
+
38
+ async def evict(self, client: ClientType, tag: str) -> None:
39
+ key = tag_set_key(self.name, tag)
40
+ registry = get_registry(self._client_type)
41
+ async for breadcrumb in self._storage.iter(client, key):
42
+ index_name, identifier = self._breadcrumbs.decode(breadcrumb)
43
+ index = registry.get(index_name)
44
+ if not isinstance(index, AsyncEvictableIndex):
45
+ raise TypeError(f"index {index_name!r} does not support eviction")
46
+ await index.evict(client, identifier)
47
+ await self._storage.drop(client, key)
@@ -0,0 +1,37 @@
1
+ """Tag keeper protocol."""
2
+
3
+ from typing import Protocol, runtime_checkable
4
+
5
+
6
+ @runtime_checkable
7
+ class TagKeeper[ClientType](Protocol):
8
+ """Group cache breadcrumbs in sets keyed by tag."""
9
+
10
+ def add(self, client: ClientType, tag: str, breadcrumb: str) -> None:
11
+ """Add ``breadcrumb`` to the set for ``tag``."""
12
+ ...
13
+
14
+ def madd(self, client: ClientType, tag: str, breadcrumbs: list[str]) -> None:
15
+ """Add every breadcrumb to the set for ``tag``."""
16
+ ...
17
+
18
+ def evict(self, client: ClientType, tag: str) -> None:
19
+ """Evict every entry referenced by breadcrumbs in the set for ``tag``, then drop that set."""
20
+ ...
21
+
22
+
23
+ @runtime_checkable
24
+ class AsyncTagKeeper[ClientType](Protocol):
25
+ """Asynchronous tag keeper."""
26
+
27
+ async def add(self, client: ClientType, tag: str, breadcrumb: str) -> None:
28
+ """Add ``breadcrumb`` to the set for ``tag``."""
29
+ ...
30
+
31
+ async def madd(self, client: ClientType, tag: str, breadcrumbs: list[str]) -> None:
32
+ """Add every breadcrumb to the set for ``tag``."""
33
+ ...
34
+
35
+ async def evict(self, client: ClientType, tag: str) -> None:
36
+ """Evict every entry referenced by breadcrumbs in the set for ``tag``, then drop that set."""
37
+ ...
@@ -0,0 +1,47 @@
1
+ """Synchronous set-backed tag keeper."""
2
+
3
+ from cachebind.indexes._builder import storage_client_type
4
+ from cachebind.indexes.base import get_registry
5
+ from cachebind.indexes.evict import EvictableIndex
6
+ from cachebind.storage.sets.storage import SetStorage
7
+ from cachebind.tagging.breadcrumbs.colon_breadcrumbs import ColonBreadcrumbs
8
+ from cachebind.tagging.breadcrumbs.protocol import Breadcrumbs
9
+ from cachebind.tagging.tag_keeper._keys import DEFAULT_TAG_KEEPER_NAME, tag_set_key
10
+
11
+
12
+ class SetTagKeeper[ClientType]:
13
+ """Collect breadcrumbs in sets ``tag_keeper:{name}:{tag}``; flush via registry eviction."""
14
+
15
+ def __init__(
16
+ self,
17
+ *,
18
+ storage: SetStorage[ClientType, str],
19
+ name: str = DEFAULT_TAG_KEEPER_NAME,
20
+ breadcrumbs: Breadcrumbs | None = None,
21
+ ) -> None:
22
+ self.name = name
23
+ self._storage = storage
24
+ self._client_type = storage_client_type("tag_keeper", type(storage), SetStorage)
25
+ self._breadcrumbs = ColonBreadcrumbs() if breadcrumbs is None else breadcrumbs
26
+
27
+ def add(self, client: ClientType, tag: str, breadcrumb: str) -> None:
28
+ if breadcrumb == "":
29
+ return
30
+ self._storage.add(client, tag_set_key(self.name, tag), breadcrumb)
31
+
32
+ def madd(self, client: ClientType, tag: str, breadcrumbs: list[str]) -> None:
33
+ members = [item for item in breadcrumbs if item != ""]
34
+ if not members:
35
+ return
36
+ self._storage.madd(client, tag_set_key(self.name, tag), members)
37
+
38
+ def evict(self, client: ClientType, tag: str) -> None:
39
+ key = tag_set_key(self.name, tag)
40
+ registry = get_registry(self._client_type)
41
+ for breadcrumb in self._storage.iter(client, key):
42
+ index_name, identifier = self._breadcrumbs.decode(breadcrumb)
43
+ index = registry.get(index_name)
44
+ if not isinstance(index, EvictableIndex):
45
+ raise TypeError(f"index {index_name!r} does not support eviction")
46
+ index.evict(client, identifier)
47
+ self._storage.drop(client, key)
@@ -0,0 +1,171 @@
1
+ Metadata-Version: 2.5
2
+ Name: cachebind
3
+ Version: 1.0.0
4
+ Summary: A Python library.
5
+ Author: goroba
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.12
9
+ Provides-Extra: dev
10
+ Requires-Dist: fakeredis>=2; extra == 'dev'
11
+ Requires-Dist: pydantic>=2; extra == 'dev'
12
+ Requires-Dist: pytest>=8; extra == 'dev'
13
+ Provides-Extra: pydantic
14
+ Requires-Dist: pydantic>=2; extra == 'pydantic'
15
+ Provides-Extra: redis
16
+ Requires-Dist: redis>=5; extra == 'redis'
17
+ Description-Content-Type: text/markdown
18
+
19
+ # cachebind
20
+
21
+ A Python library that names a cache binding — one storage key, a serializer, and a storage — and reads or writes Python values through it.
22
+
23
+ **What is it for?** Cachebind is a way to name a cache binding and use it from application code. An index holds one storage key, a serializer, and a storage. You build it once. Each call takes your storage client and reads or writes a Python value through that binding. Redis storages are included. Any storage that matches the protocol works the same way.
24
+
25
+ **What can an index store?** A key-value index stores one model per id. A set index stores members in one set. An ordered set index stores members with scores, lowest score first. A trie index stores suggestion strings with scores and keeps each member as the payload. `search` returns those members in rank order. Each has a sync builder and an async builder.
26
+
27
+ ## Indexes
28
+
29
+ Build an index once with `build_async_key_value_index`, `build_async_set_index`, `build_async_ordered_set_index`, or `build_async_trie_index`. Pass a key, the value type, a serializer instance, and a storage instance. Optionally pass `breadcrumbs` (default `ColonBreadcrumbs`) on key-value, set, and ordered-set builders. Trie indexes always use `NoopBreadcrumbs` and do not accept `breadcrumbs`. Then pass a storage client into every call.
30
+
31
+ `set` and `add` return one breadcrumb. `mset` and `madd` return one breadcrumb per item. By default, breadcrumbs encode the index key and eviction identifier. With `NoopBreadcrumbs`, writes return an empty breadcrumb. Decode a breadcrumb to get the index name and identifier, then call `evict(client, identifier)` on that index (not supported on trie indexes).
32
+
33
+ A **tag keeper** groups those breadcrumbs in Redis sets. Create `SetTagKeeper(storage=RedisSetStorage())` or `AsyncSetTagKeeper` with async set storage; optional `name` defaults to `"default"`, optional `breadcrumbs` defaults to `ColonBreadcrumbs()` for decoding on `evict`. Each logical `tag` is one set at `tag_keeper:{name}:{tag}`. After writes, call `add(client, tag, breadcrumb)` or `madd(client, tag, breadcrumbs)`; call `evict(client, tag)` to decode every breadcrumb in that set, evict through the index registry, and delete the set.
34
+
35
+ ```python
36
+ from uuid import UUID
37
+
38
+ from pydantic import BaseModel
39
+ from redis.asyncio import Redis as AsyncRedis
40
+
41
+ from cachebind import build_async_key_value_index
42
+ from cachebind.serializers.pydantic_serializer import PydanticSerializer
43
+ from cachebind.storage import AsyncRedisHashStorage
44
+
45
+ class User(BaseModel):
46
+ id: UUID
47
+ name: str
48
+
49
+ ada = User(id=UUID("12345678-1234-5678-1234-567812345678"), name="Ada")
50
+
51
+ users = build_async_key_value_index(
52
+ "users",
53
+ id_type=UUID,
54
+ model_type=User,
55
+ serializer=PydanticSerializer(User),
56
+ storage=AsyncRedisHashStorage(),
57
+ )
58
+
59
+ async def main() -> None:
60
+ client = AsyncRedis(decode_responses=True)
61
+ await users.set(client, ada.id, ada, ttl=60)
62
+ value = await users.get(client, ada.id)
63
+ await users.delete(client, ada.id)
64
+ ```
65
+
66
+ `ttl` is a whole number of seconds on `set` and `mset`. Omit it, or pass `None`, and the write does not expire. `mset` applies that one TTL to every id. `delete` removes one id. `mdelete` removes every given id. A missing id is not an error.
67
+
68
+ Inside `main`, the same client works for a set index.
69
+
70
+ ```python
71
+ from cachebind import IntSerializer, build_async_set_index
72
+ from cachebind.storage import AsyncRedisSetStorage
73
+
74
+ active = build_async_set_index(
75
+ "active_users",
76
+ member_type=int,
77
+ serializer=IntSerializer(),
78
+ storage=AsyncRedisSetStorage(),
79
+ )
80
+
81
+ await active.add(client, 1)
82
+ present = await active.contains(client, 1)
83
+ await active.remove(client, 1)
84
+ ```
85
+
86
+ `remove` drops one member. A missing member is not an error. Sets have no TTL.
87
+
88
+ An ordered set uses the same client. Each member has one score. Adding a member that is already present updates its score. `rank` is 0-based, from the lowest score. `range` includes both ends. Ordered sets have no TTL.
89
+
90
+ ```python
91
+ from cachebind import IntSerializer, build_async_ordered_set_index
92
+ from cachebind.storage import AsyncRedisOrderedSetStorage
93
+
94
+ ranking = build_async_ordered_set_index(
95
+ "user_scores",
96
+ member_type=int,
97
+ serializer=IntSerializer(),
98
+ storage=AsyncRedisOrderedSetStorage(),
99
+ )
100
+
101
+ await ranking.add(client, 1, 10.0)
102
+ place = await ranking.rank(client, 1)
103
+ top = await ranking.range(client, 0, 0)
104
+ await ranking.remove(client, 1)
105
+ ```
106
+
107
+ A trie uses the same client. The suggestion string is the text you complete. The member is stored as the payload. `search` deserializes those payloads in rank order. `limit` defaults to 10. A trie has no TTL.
108
+
109
+ ```python
110
+ from cachebind import IntSerializer, build_async_trie_index
111
+ from cachebind.storage import AsyncRedisTrieStorage
112
+
113
+ cities = build_async_trie_index(
114
+ "cities",
115
+ member_type=int,
116
+ serializer=IntSerializer(),
117
+ storage=AsyncRedisTrieStorage(),
118
+ )
119
+
120
+ await cities.add(client, "Paris", 1, 900.0)
121
+ matches = await cities.search(client, "P")
122
+ await cities.remove(client, "Paris")
123
+ ```
124
+
125
+ `matches` is `[1]`. Redis 8 includes the suggestion commands this storage sends.
126
+
127
+ Sync indexes use `build_key_value_index`, `build_set_index`, `build_ordered_set_index`, and `build_trie_index` with the matching sync storage. Those calls are not awaited.
128
+
129
+ `get_registry` from `cachebind` returns that index: `get_registry(AsyncRedis).get("users")`.
130
+
131
+ ## Install
132
+
133
+ ```bash
134
+ pip install cachebind
135
+ pip install "cachebind[redis]"
136
+ pip install "cachebind[pydantic]"
137
+ pip install "cachebind[redis,pydantic]"
138
+ ```
139
+
140
+ From a checkout, the same extras are:
141
+
142
+ ```bash
143
+ pip install -e ".[dev]"
144
+ pip install -e ".[redis]"
145
+ pip install -e ".[redis,pydantic]"
146
+ ```
147
+
148
+ Runtime dependencies live in `pyproject.toml` under `[project] dependencies`. Optional Redis and Pydantic support, and the test tools, live in extras. A plain install does not pull Redis or Pydantic. There is no `requirements.txt`.
149
+
150
+ ## Test
151
+
152
+ ```bash
153
+ pytest
154
+ ```
155
+
156
+ ## Publish
157
+
158
+ When the package is ready for PyPI, build and upload it. Confirm the project name is free on PyPI first, and fill in the author details in `pyproject.toml`.
159
+
160
+ ```bash
161
+ pip install build twine
162
+ python -m build
163
+ twine upload dist/*
164
+ ```
165
+
166
+ ## Documentation
167
+
168
+ - [Leaderboard](docs/leaderboard.md) — ordered set of user ids, with users loaded from Postgres
169
+ - [Tag-Based Caching](docs/tag-based-caching.md) — bind key-value user cache and leaderboard entry under `user:{id}`, evict together on delete
170
+ - [Trie (Prefix Tree)](docs/trie.md) — city names in a Redis Search trie, with cities loaded from Postgres on search
171
+ - [Write-Back Caching example](docs/write-back-caching.md) — collect last-visit times, then save them to the database
@@ -0,0 +1,81 @@
1
+ cachebind/__init__.py,sha256=EaPBLYKNpAwrndIszSqv-j959el2G7Kv9xo4UA7rAJk,2558
2
+ cachebind/indexes/__init__.py,sha256=XxiS4doCtyuaSThh_aLTvoIc9bxRjjZ8g_VDVcu4bjc,1471
3
+ cachebind/indexes/_breadcrumb.py,sha256=zDCd2ojxcb8tOwXnGs8H-TvTZpWm7d8ioDFipgRDbew,324
4
+ cachebind/indexes/_builder.py,sha256=AT_voGniaK3BPjYuGut24mod8cIHHjEGXOw4RWKnk4c,5501
5
+ cachebind/indexes/_serializer.py,sha256=maqiL829cDAYHJivPYQ-8MoVp-uCsIWgvTaFkBu3QDs,593
6
+ cachebind/indexes/base.py,sha256=vUFYMYlBiOj7gRmSCmaswSTyK9oDi4VJSGhMaBPJBN4,1738
7
+ cachebind/indexes/evict.py,sha256=zYRTMRX4nyZfPUeg683u3utReHhu2F7Av2hnNUWGxUE,703
8
+ cachebind/indexes/registry.py,sha256=XfjaAJAVnk1sG2qDAVBPNapvxHQvQfmvkkHH2xc3INQ,1157
9
+ cachebind/indexes/key_value/__init__.py,sha256=5nBvmA8rLm8cj0MmdyG-CysWbgl3o-MvgfjbuxWSiDs,527
10
+ cachebind/indexes/key_value/async_index.py,sha256=YHACtY7rfcRvjaQXsW_1pwHy4F8AXgCXTku1WiIjKHw,5676
11
+ cachebind/indexes/key_value/base.py,sha256=tpFPiReOmaRI_l4Jed4KMQOFibyr7OiDJl2Pt8fwDlc,1163
12
+ cachebind/indexes/key_value/builder.py,sha256=rMSYNj1nfKWizuc6o0K9kb1tfB4vfZJcyCZ71Db0Gi8,5737
13
+ cachebind/indexes/key_value/index.py,sha256=HNWnaq0gytKGka1ZrX1HJLPO6j_Kbld-KEd-r4bquX0,5367
14
+ cachebind/indexes/ordered_sets/__init__.py,sha256=zNA98CIACinrmuitOaKXpStNJcSlLsf-LGuEgwX5I4Y,577
15
+ cachebind/indexes/ordered_sets/async_index.py,sha256=d-bTMFLxDC_5rIrWEJBCxaIf3wJoseddCYmaNBrJ9TQ,8602
16
+ cachebind/indexes/ordered_sets/base.py,sha256=lH3NrqlnSF_QA0j_azv4NpLI10I2iyOjpgYGXIHK5EA,1333
17
+ cachebind/indexes/ordered_sets/builder.py,sha256=FsgBktWG031LeTX276ITvmAxPuvJ2NTxFgIAW5Surt4,5048
18
+ cachebind/indexes/ordered_sets/index.py,sha256=ZDaq5EssMVJ1dK7r2PSAhtZTyYRuFwhZAHhRrJHB1n0,8233
19
+ cachebind/indexes/sets/__init__.py,sha256=jc1ScTSTKjouQr_iAdQNgSp_T37qNU1Qro2NYl3DzI4,442
20
+ cachebind/indexes/sets/async_index.py,sha256=-03go0lR7tnExw4UUPcDrBPi9C_4YxOTsq-nlI7z1Tc,4492
21
+ cachebind/indexes/sets/base.py,sha256=StPMPVX181nIVd1mNieleryb-IIpfVHIQOzLzF9-TDg,868
22
+ cachebind/indexes/sets/builder.py,sha256=fMkQH2AuPK85elJJS5ICf7oE1faRqVh6n_wYDSBRsGc,4785
23
+ cachebind/indexes/sets/index.py,sha256=84MtYMV9EsWh5HSRRkKKlaVANDl-FaNf1zmJDYvCGrI,4213
24
+ cachebind/indexes/tries/__init__.py,sha256=42N1nD1AgLNi93L64Lty6Q2g2MOQKFH756-NtGLSMTE,458
25
+ cachebind/indexes/tries/async_index.py,sha256=oH-rJL1dI3Fk1CAmkyvlNzvPDSFfOsm1egPFOlWLBmY,4322
26
+ cachebind/indexes/tries/base.py,sha256=HtNgjDrboixac0CX5A1FcdOQCGFBtrrluYGzyigRw3U,963
27
+ cachebind/indexes/tries/builder.py,sha256=-fWelDRDyQNaguU7fexehukrw8wjgs-V2DbALeCIWGI,4504
28
+ cachebind/indexes/tries/index.py,sha256=9z5loL5omDYmCA0Yeq91xF51WetnlNb4ymudD_WmOdk,4197
29
+ cachebind/serializers/__init__.py,sha256=vcwUOfSn6k-jUj_Vcv40s9QBdoA236_eTPXvtYJmjGQ,1083
30
+ cachebind/serializers/bool_serializer.py,sha256=DjPgj8jTbIPqfykSOog3KkTG6ZjsJ_r0J2TYzWRrdos,624
31
+ cachebind/serializers/dataclass_serializer.py,sha256=Wwht4xXNqBsHLpVaNdi7nPwYRAFAto3ihyDos8Zf6Hs,3498
32
+ cachebind/serializers/datetime_serializer.py,sha256=boXGU4R5MJE6_kvdyb-yr_12adH18ByYlnHQf5NCtS8,746
33
+ cachebind/serializers/dict_serializer.py,sha256=zPfwg_VxNBYmL9pJy5b1SaKanoVoT0LkHm3KiIB2skk,1048
34
+ cachebind/serializers/float_serializer.py,sha256=h75TcEx-0u515-2alde5ssGn98csoDbBS-X8iAYdsk8,591
35
+ cachebind/serializers/int_serializer.py,sha256=T-Tsj6eV697OgJeTU_jBHFHjPNQ1RZEKsopHDpUbYaU,689
36
+ cachebind/serializers/noop_serializer.py,sha256=UIRMOpr0zr5IBP9sRFxVlJgPYFP1dBrOrNtjgrr1GaI,589
37
+ cachebind/serializers/pydantic_serializer.py,sha256=RWYZqJjT8G_bFpvIugFWGGae35sT9I-WSusfyl2sPIM,1132
38
+ cachebind/serializers/serializer.py,sha256=JW1q9turH7Yhj2vpbRthzWyHD46iX715FU1yN4nVpUw,928
39
+ cachebind/serializers/str_serializer.py,sha256=zlG-w_jQd8TWDNSbYuJXV29fTEvnniMCLig5UpYo1N0,320
40
+ cachebind/serializers/uuid_serializer.py,sha256=3mMLhUXtXfL9iYZ-za-jaZHKgvdYJ26bys_KrwRYu1g,673
41
+ cachebind/storage/__init__.py,sha256=bLH70qe2x1_QYYp9b9WLCLqAH3_yzktKA4ZfYufLj7Q,1893
42
+ cachebind/storage/_redis.py,sha256=eMMnd6uyFerZUN1L-TXfIa70f8YgIFih5tLjp3_n3Uk,2326
43
+ cachebind/storage/key_value/__init__.py,sha256=yuwodfvvu5Ll2BBBlZbfzgE5paMvCX0KLkV1fnuou1k,1255
44
+ cachebind/storage/key_value/async_redis_hash_storage.py,sha256=71Z7NrmVgDsVhWa5x0BfwVq6uc0LzencEX3jCya_Bd4,2653
45
+ cachebind/storage/key_value/async_redis_string_storage.py,sha256=K1WlFrSm6ovvm1hovvit4BYWdMQTitPlP6xHkRhEFRQ,2768
46
+ cachebind/storage/key_value/async_storage.py,sha256=DVIdhjFi6aWtn_D8YlS7mQWnvuopxH-XSWnNVKwtOIs,2603
47
+ cachebind/storage/key_value/redis_hash_storage.py,sha256=Yrm0eTjssgfRmu6a6dJ077lvJoGtBwLF0RcQJCtNmbc,2416
48
+ cachebind/storage/key_value/redis_string_storage.py,sha256=clb9kgFXzVof37A-QnCcN9xV6mDA1MvlnzfXbBrg6Rs,2567
49
+ cachebind/storage/key_value/storage.py,sha256=RLElF6Nfa4fTkZJi8ZeDQAdUTpbo7iMqsawwRVc0vRM,2518
50
+ cachebind/storage/ordered_sets/__init__.py,sha256=J8RAWHtkhbvL3oj0B-Cnu7MOQO3WHpnAKeftz5z_RSI,970
51
+ cachebind/storage/ordered_sets/_values.py,sha256=xey3S5OfMqC7RBwuljQH8aE6KqoHmTlKFLUq3UvTTs4,2060
52
+ cachebind/storage/ordered_sets/async_redis_ordered_set_storage.py,sha256=4s0ZRrkv21pn1QWHqzgR8koG35MXWzd39EIE7SAnjRM,3555
53
+ cachebind/storage/ordered_sets/async_storage.py,sha256=dSHaFbYWEITooJXP_5KSi9X4Eq6ypsYx3yxQ2B4ImWk,3783
54
+ cachebind/storage/ordered_sets/redis_ordered_set_storage.py,sha256=Z3trSXjve1s02XtjurK7-rtetuYvWKIimyYBL4TAZMU,3182
55
+ cachebind/storage/ordered_sets/storage.py,sha256=A35S2L9DhFstMAk5hJcIerCb38Vd61Rjx7Qe56RCyx4,3654
56
+ cachebind/storage/sets/__init__.py,sha256=c494YhqbAsrMtHF7dBwFsbPiVoxfkGeQ2OagNRLJXKc,791
57
+ cachebind/storage/sets/async_redis_set_storage.py,sha256=SOQXa6fuo6YGjXT3TvFgJJXOZPlB-Qz_0AJq2oQ_03I,1869
58
+ cachebind/storage/sets/async_storage.py,sha256=jC7B2RDvSTLkfb2Le9Gp_eCZ_w9qCwWl3VsaaFiiXEg,1873
59
+ cachebind/storage/sets/redis_set_storage.py,sha256=6QJ5pDH3SbMsfGyfuV9TiFPmuuPvO7Rqdo5xCdbzfvU,1664
60
+ cachebind/storage/sets/storage.py,sha256=lX0RtVKipMJ-1IElVOQv5T5KZ9Kgn6lq9iEMkIqNA9w,1814
61
+ cachebind/storage/tries/__init__.py,sha256=oeGkKjlAFifUKGvsLxhZPJGQRMkuCZhMz14lw8lADfw,812
62
+ cachebind/storage/tries/_reply.py,sha256=BzTcMsAbeARzVH0G7i_tko9R2xI34jOd_30uq3qgOog,800
63
+ cachebind/storage/tries/_values.py,sha256=YYA7Hz5p0vlYRfhCSpeZyU3vq3wrsynjPIYUptv6Lc8,1370
64
+ cachebind/storage/tries/async_redis_trie_storage.py,sha256=iV_UMImhNm43XpseLX7ynePAbC4D_OdmHfpT3v2Jjpk,2730
65
+ cachebind/storage/tries/async_storage.py,sha256=Xa-ts6HyUmRfFyf9aA0szxMQA_cpkKEOYyRfgLVOJVs,2638
66
+ cachebind/storage/tries/redis_trie_storage.py,sha256=puA_VuJMAWACs1xnu-ynUKuDYkT7igYpLtPAXd7kFa4,2527
67
+ cachebind/storage/tries/storage.py,sha256=Cattl-IY4HRW_Vm5_rrIE3otVqad00UWuTHYiDiOR4M,2583
68
+ cachebind/tagging/__init__.py,sha256=KhMWb_z55DSz7Rmq90T8WpNBJCQA0dSRxAMFZi4UnYk,417
69
+ cachebind/tagging/breadcrumbs/__init__.py,sha256=vfTqlsdfdo6JoYOgZivULSVPWqq2MgZROMzbK1wfdfo,365
70
+ cachebind/tagging/breadcrumbs/colon_breadcrumbs.py,sha256=ApxKXOBy-xRvDFFnHIs7JVosQziAdPPWSv2jYU2AD8w,634
71
+ cachebind/tagging/breadcrumbs/noop_breadcrumbs.py,sha256=PFANgNl7RwcMoq4GBIf5W_hqaVFGuwXWIpwxTki7_N8,421
72
+ cachebind/tagging/breadcrumbs/protocol.py,sha256=apgpkzfnT3jX652qkUqwjJ7dpGEJ4v22Zt5MKn7Gnv4,443
73
+ cachebind/tagging/tag_keeper/__init__.py,sha256=JaTw9DE0HdBQu-pYeuGzCJgblAKzRpP-u9kH9EWKcj4,388
74
+ cachebind/tagging/tag_keeper/_keys.py,sha256=xsGMoSlsFVP2_Y_5YdWHeYZrnn5_9RfUkmcLSkseveo,261
75
+ cachebind/tagging/tag_keeper/async_set_tag_keeper.py,sha256=nChCGgAsyPpTh3xPg4RVYI2WVQVcwMX0m9qmqndVPWY,2135
76
+ cachebind/tagging/tag_keeper/protocol.py,sha256=BTHxInwFnYC3rbk4dj9Y071s5CYutkxPd_9xDgQ_3GE,1252
77
+ cachebind/tagging/tag_keeper/set_tag_keeper.py,sha256=1WtAukqIQD8As6tgBPPXc5IVSS_tUSS8FCYukeqJI5c,2050
78
+ cachebind-1.0.0.dist-info/METADATA,sha256=xba2X_bhOY_42z1Av4Y8hwgS8wHXSMil47s-84M6Ud4,7218
79
+ cachebind-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
80
+ cachebind-1.0.0.dist-info/licenses/LICENSE,sha256=Ne6JLo140O8v_ebf7i86V9QMaLZZKiyWw29HWamyUKk,1063
81
+ cachebind-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any