key: extract the key encoding logic into a separate file
- ID
1cc4ab1- date
2026-11-26 12:02:34+00:00- author
Alex Chan <alexc@tailscale.com>- parent
24977df- message
key: extract the key encoding logic into a separate file- changed files
5 files, 218 additions, 196 deletions
Changed files
src/funkycache/key.py (0 → 3999)
diff --git a/src/funkycache/key.py b/src/funkycache/key.py
new file mode 100644
index 0000000..02db05d
--- /dev/null
+++ b/src/funkycache/key.py
@@ -0,0 +1,123 @@
+"""
+Cache keys in a FunkyCache are based on the arguments provided to
+a Python function.
+
+A dict mapping can't be used as a hash key (in a python dict or
+an SQLite database), so we need to convert mappings to a string first.
+"""
+
+import dataclasses
+import functools
+import json
+from typing import Any
+
+from pydantic import BaseModel, TypeAdapter
+import xxhash
+
+
+def encode_key_as_json(key: dict[str, Any]) -> str:
+ """
+ Encode a set of arguments to a Python function as a JSON string.
+
+ This is a lossy transformation that is designed to get a reasonable
+ serialisation as JSON. It is possible for values of different types
+ to collide.
+
+ JSON encoding is a significant bottleneck, so we are trying to reduce
+ the JSON object to be as small as possible before encoding it.
+
+ This function must not mutate its input.
+ """
+ # TODO: How do we handle lazy generators/iterators as the input key?
+
+ reduced_key = {k: _process_value(v) for k, v in key.items()}
+
+ try:
+ return json.dumps(
+ reduced_key, sort_keys=True, default=str, separators=(",", ":")
+ )
+ except TypeError:
+ clean_key = _make_json_compatible(reduced_key)
+ return json.dumps(clean_key, sort_keys=True, default=str, separators=(",", ":"))
+
+
+def _make_json_compatible(value: Any) -> Any:
+ """
+ Recursively walk an arbitrary structure and prepare it for JSON encoding.
+ """
+ if isinstance(value, dict):
+ return {str(k): _make_json_compatible(v) for k, v in value.items()}
+ elif isinstance(value, (list, tuple, set)):
+ return [_make_json_compatible(item) for item in value]
+ else:
+ return value
+
+
+def _process_value(val: Any) -> Any:
+ """
+ Prepare a single value for JSON encoding.
+ """
+ # Primitive types: return directly and skip the isinstance() checks.
+ # Large strings should be hashed.
+ if val is None or type(val) in (str, int, float, bool):
+ if isinstance(val, str) and len(val) > 256:
+ return hash_string(val)
+ return val
+
+ # Dictionaries: walk recursively, and omit keys for empty values.
+ elif isinstance(val, dict):
+ return {k: _process_value(v) for k, v in val.items() if v}
+
+ # Lists and tuples: walk recursively. If a list/tuple contains a list
+ # of dictionaries, extract the keys/values into separate lists to
+ # avoid repeating the keys in the JSON.
+ elif isinstance(val, (list, tuple)):
+ processed_items = [_process_value(v) for v in val]
+
+ if len(processed_items) <= 1:
+ return processed_items
+
+ if all(isinstance(item, dict) for item in processed_items):
+ all_keys = set().union(*(item.keys() for item in processed_items))
+ sorted_keys = sorted(all_keys)
+
+ values_matrix = [
+ [item.get(k) for k in sorted_keys] for item in processed_items
+ ]
+
+ return {"_keys": sorted_keys, "_values": values_matrix}
+
+ return processed_items
+
+ # Pydantic models and dataclasses: convert to dicts.
+ #
+ # This comes after the isinstance(…, dict) check because every Pydantic
+ # value will hit this branch and the dict() branch, but some values can
+ # go directly into the dict() branch. This reduces isinstance and
+ # is_dataclass calls.
+ elif isinstance(val, BaseModel) or dataclasses.is_dataclass(val):
+ adapter = _get_type_adapter(type(val))
+ dumped = adapter.dump_python(val, mode="json")
+ return _process_value(dumped)
+
+ else:
+ return val
+
+
+@functools.cache
+def _get_type_adapter(target_type: Any) -> TypeAdapter:
+ """
+ Return a TypeAdapter for the given Pydantic type.
+
+ The type adapter is cached, so schema generation only runs once
+ per unique type.
+ """
+ return TypeAdapter(target_type)
+
+
+@functools.cache
+def hash_string(s: str) -> str:
+ """
+ Hash a string to reduce it to a fixed size.
+ """
+ return "xxh64:" + xxhash.xxh64_hexdigest(s.encode("utf8"))
src/funkycache/storage.py (14781 → 11150)
diff --git a/src/funkycache/storage.py b/src/funkycache/storage.py
index 88a64a5..993864d 100644
--- a/src/funkycache/storage.py
+++ b/src/funkycache/storage.py
@@ -7,18 +7,16 @@ a collection of arguments to the return value.
from abc import ABC, abstractmethod
from collections.abc import Callable
-import dataclasses
from datetime import datetime, timezone
-import functools
import json
from pathlib import Path
import sqlite3
from types import TracebackType
from typing import Any, cast, Self
-from pydantic import BaseModel, TypeAdapter
-import xxhash
+from pydantic import TypeAdapter
+from .key import encode_key_as_json, hash_string
from .version import __version__
@@ -78,7 +76,7 @@ class MemoryCacheStorage[V](CacheStorage[V]):
"""
Save a key-value pair in the cache.
"""
- enc_key = _encode_key_as_json(key)
+ enc_key = encode_key_as_json(key)
try:
if self._underlying[enc_key] != value:
@@ -90,7 +88,7 @@ class MemoryCacheStorage[V](CacheStorage[V]):
"""
Look up the value of a key in the cache.
"""
- enc_key = _encode_key_as_json(key)
+ enc_key = encode_key_as_json(key)
return self._underlying[enc_key]
@@ -188,7 +186,7 @@ class SQLiteCacheStorage[V](TypedCacheStorage[V]):
}
# Get a fingerprint for the current table definitions
- cur_fingerprint = _hash(json.dumps(table_definitions, sort_keys=True))
+ cur_fingerprint = hash_string(json.dumps(table_definitions, sort_keys=True))
# Check if the fingerprint in the database exists and matches
# the current file.
@@ -257,8 +255,8 @@ class SQLiteCacheStorage[V](TypedCacheStorage[V]):
are serialised as JSON, then hashed to reduce it to a fixed size.
Using fixed-size keys improves SQLite performance.
"""
- json_key = _encode_key_as_json(key)
- return _hash(json_key)
+ json_key = encode_key_as_json(key)
+ return hash_string(json_key)
def _set_str(self, key: dict[str, Any], value: str) -> None:
"""
@@ -356,111 +354,3 @@ class LazyCacheStorage[V](CacheStorage[V]):
if not hasattr(self._underlying, "close"):
return
self._underlying.close() # type: ignore
-
-
-def _encode_key_as_json(key: dict[str, Any]) -> str:
- """
- Encode a set of arguments to a Python function as a JSON string.
-
- This is a lossy transformation that is designed to get a reasonable
- serialisation as JSON. It is possible for values of different types
- to collide.
-
- JSON encoding is a significant bottleneck, so we are trying to reduce
- the JSON object to be as small as possible before encoding it.
-
- This function must not mutate its input.
- """
- # TODO: How do we handle lazy generators/iterators as the input key?
-
- reduced_key = {k: _process_value(v) for k, v in key.items()}
-
- try:
- return json.dumps(
- reduced_key, sort_keys=True, default=str, separators=(",", ":")
- )
- except TypeError:
- clean_key = _make_json_compatible(reduced_key)
- return json.dumps(clean_key, sort_keys=True, default=str, separators=(",", ":"))
-
-
-def _process_value(val: Any) -> Any:
- """
- Prepare a single value for JSON encoding.
- """
- # Primitive types: return directly and skip the isinstance() checks.
- # Large strings should be hashed.
- if val is None or type(val) in (str, int, float, bool):
- if isinstance(val, str) and len(val) > 256:
- return _hash(val)
- return val
-
- # Dictionaries: walk recursively, and omit keys for empty values.
- elif isinstance(val, dict):
- return {k: _process_value(v) for k, v in val.items() if v}
-
- # Lists and tuples: walk recursively. If a list/tuple contains a list
- # of dictionaries, extract the keys/values into separate lists to
- # avoid repeating the keys in the JSON.
- elif isinstance(val, (list, tuple)):
- processed_items = [_process_value(v) for v in val]
-
- if len(processed_items) <= 1:
- return processed_items
-
- if all(isinstance(item, dict) for item in processed_items):
- all_keys = set().union(*(item.keys() for item in processed_items))
- sorted_keys = sorted(all_keys)
-
- values_matrix = [
- [item.get(k) for k in sorted_keys] for item in processed_items
- ]
-
- return {"_keys": sorted_keys, "_values": values_matrix}
-
- return processed_items
-
- # Pydantic models and dataclasses: convert to dicts.
- #
- # This comes after the isinstance(…, dict) check because every Pydantic
- # value will hit this branch and the dict() branch, but some values can
- # go directly into the dict() branch. This reduces isinstance and
- # is_dataclass calls.
- elif isinstance(val, BaseModel) or dataclasses.is_dataclass(val):
- adapter = _get_type_adapter(type(val))
- dumped = adapter.dump_python(val, mode="json")
- return _process_value(dumped)
-
- else:
- return val
-
-
-@functools.cache
-def _get_type_adapter(target_type: Any) -> TypeAdapter:
- """
- Return a TypeAdapter for the given Pydantic type.
-
- The type adapter is cached, so schema generation only runs once
- per unique type.
- """
- return TypeAdapter(target_type)
-
-
-def _make_json_compatible(value: Any) -> Any:
- """
- Recursively walk an arbitrary structure and prepare it for JSON encoding.
- """
- if isinstance(value, dict):
- return {str(k): _make_json_compatible(v) for k, v in value.items()}
- elif isinstance(value, (list, tuple, set)):
- return [_make_json_compatible(item) for item in value]
- else:
- return value
-
-
-@functools.cache
-def _hash(s: str) -> str:
- """
- Hash a string to reduce it to a fixed size.
- """
- return "xxh64:" + xxhash.xxh64_hexdigest(s.encode("utf8"))
tests/bench_key_encode_as_json.py (634 → 624)
diff --git a/tests/bench_key_encode_as_json.py b/tests/bench_key_encode_as_json.py
index eb39668..d9d9ede 100644
--- a/tests/bench_key_encode_as_json.py
+++ b/tests/bench_key_encode_as_json.py
@@ -6,8 +6,8 @@ from collections import defaultdict
import statistics
import time
-from funkycache.storage import _encode_key_as_json
-from test_storage import KEY_ENCODING_TEST_CASES
+from funkycache.key import encode_key_as_json
+from test_key import KEY_ENCODING_TEST_CASES
if __name__ == "__main__":
@@ -16,7 +16,7 @@ if __name__ == "__main__":
for _ in range(5000):
for tc in KEY_ENCODING_TEST_CASES:
t0 = time.perf_counter()
- _encode_key_as_json(tc.values[0]) # type: ignore
+ encode_key_as_json(tc.values[0]) # type: ignore
elapsed = time.perf_counter() - t0
results[tc.id].append(elapsed)
tests/test_key.py (0 → 2250)
diff --git a/tests/test_key.py b/tests/test_key.py
new file mode 100644
index 0000000..c212ec2
--- /dev/null
+++ b/tests/test_key.py
@@ -0,0 +1,85 @@
+"""
+Tests for `funkycache.key`.
+"""
+
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel
+import pytest
+from _pytest.mark.structures import ParameterSet
+
+from funkycache.key import encode_key_as_json
+
+
+class Shape(BaseModel):
+ """A basic model that uses Pydantic."""
+
+ sides: int
+ colour: str
+
+
+@dataclass
+class Greeting:
+ """A basic model that uses dataclasses."""
+
+ name: str
+ message: str
+
+
+KEY_ENCODING_TEST_CASES: list[ParameterSet] = [
+ pytest.param({"n": "one"}, '{"n":"one"}', id="str"),
+ pytest.param({"n": 1}, '{"n":1}', id="int"),
+ pytest.param(
+ {"n": ["one", "uno", "eins"]}, '{"n":["one","uno","eins"]}', id="list"
+ ),
+ pytest.param(
+ {"n": ("one", "uno", "eins")}, '{"n":["one","uno","eins"]}', id="tuple"
+ ),
+ pytest.param({"n": []}, '{"n":[]}', id="empty_list"),
+ pytest.param({"n": [{"en": "one"}]}, '{"n":[{"en":"one"}]}', id="list_1"),
+ pytest.param(
+ {
+ "n": [
+ {"lang": "en", "val": "one"},
+ {"lang": "fr", "val": "un"},
+ {"lang": "de", "val": "eins"},
+ ]
+ },
+ '{"n":{"_keys":["lang","val"],"_values":[["en","one"],["fr","un"],["de","eins"]]}}',
+ id="list_many",
+ ),
+ pytest.param(
+ {"n": Shape(sides=4, colour="red")},
+ '{"n":{"colour":"red","sides":4}}',
+ id="pydantic",
+ ),
+ pytest.param(
+ {"n": Greeting(name="alex", message="hello")},
+ '{"n":{"message":"hello","name":"alex"}}',
+ id="dataclass",
+ ),
+ pytest.param(
+ {"long": "a" * 5000, "short": "a"},
+ '{"long":"xxh64:b2b67943d4803cd6","short":"a"}',
+ id="long_str",
+ ),
+ pytest.param(
+ {"n": {"long": "a" * 5000, "short": "a"}},
+ '{"n":{"long":"xxh64:b2b67943d4803cd6","short":"a"}}',
+ id="long_str",
+ ),
+ pytest.param({"n": {Path("1"): "one"}}, '{"n":{"1":"one"}}', id="nested_path_key"),
+]
+
+
+@pytest.mark.parametrize(
+ "key, json_key",
+ KEY_ENCODING_TEST_CASES,
+)
+def test_encode_key_as_json(key: dict[str, Any], json_key: str) -> None:
+ """
+ Tests for encode_key_as_json.
+ """
+ assert encode_key_as_json(key) == json_key
tests/test_storage.py (13276 → 11146)
diff --git a/tests/test_storage.py b/tests/test_storage.py
index 5dc64ba..31f9aab 100644
--- a/tests/test_storage.py
+++ b/tests/test_storage.py
@@ -6,15 +6,12 @@ from abc import ABC, abstractmethod
from collections.abc import Generator
from contextlib import closing, contextmanager
import copy
-from dataclasses import dataclass
from pathlib import Path
import sqlite3
from typing import Any
from unittest.mock import MagicMock
-from pydantic import BaseModel
import pytest
-from _pytest.mark.structures import ParameterSet
from funkycache.storage import (
CacheStorage,
@@ -22,7 +19,6 @@ from funkycache.storage import (
LazyCacheStorage,
SQLiteCacheStorage,
CannotOverwriteValueException,
- _encode_key_as_json,
)
@@ -343,75 +339,3 @@ class TestLazySQLiteCacheStorage(LazyCacheStorageTestSuite, TestSQLiteCacheStora
assert not db_path.exists()
assert not db_path.parent.exists()
-
-
-class Shape(BaseModel):
- """A basic model that uses Pydantic."""
-
- sides: int
- colour: str
-
-
-@dataclass
-class Greeting:
- """A basic model that uses dataclasses."""
-
- name: str
- message: str
-
-
-KEY_ENCODING_TEST_CASES: list[ParameterSet] = [
- pytest.param({"n": "one"}, '{"n":"one"}', id="str"),
- pytest.param({"n": 1}, '{"n":1}', id="int"),
- pytest.param(
- {"n": ["one", "uno", "eins"]}, '{"n":["one","uno","eins"]}', id="list"
- ),
- pytest.param(
- {"n": ("one", "uno", "eins")}, '{"n":["one","uno","eins"]}', id="tuple"
- ),
- pytest.param({"n": []}, '{"n":[]}', id="empty_list"),
- pytest.param({"n": [{"en": "one"}]}, '{"n":[{"en":"one"}]}', id="list_1"),
- pytest.param(
- {
- "n": [
- {"lang": "en", "val": "one"},
- {"lang": "fr", "val": "un"},
- {"lang": "de", "val": "eins"},
- ]
- },
- '{"n":{"_keys":["lang","val"],"_values":[["en","one"],["fr","un"],["de","eins"]]}}',
- id="list_many",
- ),
- pytest.param(
- {"n": Shape(sides=4, colour="red")},
- '{"n":{"colour":"red","sides":4}}',
- id="pydantic",
- ),
- pytest.param(
- {"n": Greeting(name="alex", message="hello")},
- '{"n":{"message":"hello","name":"alex"}}',
- id="dataclass",
- ),
- pytest.param(
- {"long": "a" * 5000, "short": "a"},
- '{"long":"xxh64:b2b67943d4803cd6","short":"a"}',
- id="long_str",
- ),
- pytest.param(
- {"n": {"long": "a" * 5000, "short": "a"}},
- '{"n":{"long":"xxh64:b2b67943d4803cd6","short":"a"}}',
- id="long_str",
- ),
- pytest.param({"n": {Path("1"): "one"}}, '{"n":{"1":"one"}}', id="nested_path_key"),
-]
-
-
-@pytest.mark.parametrize(
- "key, json_key",
- KEY_ENCODING_TEST_CASES,
-)
-def test_encode_key_as_json(key: dict[str, Any], json_key: str) -> None:
- """
- Tests for _encode_key_as_json.
- """
- assert _encode_key_as_json(key) == json_key