Skip to content

armgit / burr

Public Imported from GitHub
0

Build applications that make decisions (chatbots, agents, simulations, etc...). Monitor, trace, persist, and execute on your own infrastructure.

Add async support for Redis state persister

jernejfrank1252b93cf5cc
diff --git a/burr/integrations/persisters/b_redis.py b/burr/integrations/persisters/b_redis.py
index 25231bf9..131d3bc3 100644
--- a/burr/integrations/persisters/b_redis.py
+++ b/burr/integrations/persisters/b_redis.py
@@ -2,6 +2,7 @@ from burr.integrations import base
try:
import redis # can't name module redis because this import wouldn't work.
+ import redis.asyncio as aredis
except ImportError as e:
base.require_plugin(e, "redis")
@@ -16,6 +17,14 @@ from burr.core import persistence, state
logger = logging.getLogger(__name__)
+def add_namespace_to_partition_key(partition_key: str, namespace: Optional[str] = None) -> str:
+ """Helper function to add namespace to partition key."""
+
+ if namespace:
+ return f"{namespace}:{partition_key}"
+ return partition_key
+
+
class RedisBasePersister(persistence.BaseStatePersister):
"""Main class for Redis persister.
@@ -28,6 +37,11 @@ class RedisBasePersister(persistence.BaseStatePersister):
so this is an attempt to fix that in a backwards compatible way.
"""
+ @classmethod
+ def from_config(cls, config: dict) -> "RedisBasePersister":
+ """Creates a new instance of the RedisBasePersister from a configuration dictionary."""
+ return cls.from_values(**config)
+
@classmethod
def from_values(
cls,
@@ -63,11 +77,20 @@ class RedisBasePersister(persistence.BaseStatePersister):
self.serde_kwargs = serde_kwargs or {}
self.namespace = namespace if namespace else ""
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self.connection.close()
+ return False
+
+ def set_serde_kwargs(self, serde_kwargs: dict):
+ """Sets the serde_kwargs for the persister."""
+ self.serde_kwargs = serde_kwargs
+
def list_app_ids(self, partition_key: str, **kwargs) -> list[str]:
"""List the app ids for a given partition key."""
- namespaced_partition_key = (
- f"{self.namespace}:{partition_key}" if self.namespace else partition_key
- )
+ namespaced_partition_key = add_namespace_to_partition_key(partition_key, self.namespace)
app_ids = self.connection.zrevrange(namespaced_partition_key, 0, -1)
return [app_id.decode() for app_id in app_ids]
@@ -84,9 +107,7 @@ class RedisBasePersister(persistence.BaseStatePersister):
:param kwargs:
:return: Value or None.
"""
- namespaced_partition_key = (
- f"{self.namespace}:{partition_key}" if self.namespace else partition_key
- )
+ namespaced_partition_key = add_namespace_to_partition_key(partition_key, self.namespace)
if sequence_id is None:
sequence_id = self.connection.zscore(namespaced_partition_key, app_id)
if sequence_id is None:
@@ -109,11 +130,9 @@ class RedisBasePersister(persistence.BaseStatePersister):
def create_key(self, app_id, partition_key, sequence_id):
"""Create a key for the Redis database."""
- if self.namespace:
- key = f"{self.namespace}:{partition_key}:{app_id}:{sequence_id}"
- else:
- key = f"{partition_key}:{app_id}:{sequence_id}"
- return key
+ return add_namespace_to_partition_key(
+ f"{partition_key}:{app_id}:{sequence_id}", self.namespace
+ )
def save(
self,
@@ -152,19 +171,22 @@ class RedisBasePersister(persistence.BaseStatePersister):
"created_at": datetime.now(timezone.utc).isoformat(),
},
)
- namespaced_partition_key = (
- f"{self.namespace}:{partition_key}" if self.namespace else partition_key
- )
+ namespaced_partition_key = add_namespace_to_partition_key(partition_key, self.namespace)
self.connection.zadd(namespaced_partition_key, {app_id: sequence_id})
+ def cleanup(self):
+ """Closes the connection to the database."""
+ self.connection.close()
+
def __del__(self):
+ # This should be deprecated -- using __del__ is unreliable for closing connections to db's;
+ # the preferred way should be for the user to use a context manager or use the `.cleanup()`
+ # method within a REST API framework.
+
self.connection.close()
def __getstate__(self) -> dict:
state = self.__dict__.copy()
- if not hasattr(self.connection, "connection_pool"):
- logger.warning("Redis connection is not serializable.")
- return state
state["connection_params"] = {
"host": self.connection.connection_pool.connection_kwargs["host"],
"port": self.connection.connection_pool.connection_kwargs["port"],
@@ -181,6 +203,163 @@ class RedisBasePersister(persistence.BaseStatePersister):
self.__dict__.update(state)
+class AsyncRedisBasePersister(persistence.AsyncBaseStatePersister):
+ """Main class for async Redis persister.
+
+ .. warning::
+ The synchronous persister closes the connection on deletion of the class using the ``__del__`` method.
+ In an async context that is not reliable (the event loop may already be closed by the time ``__del__``
+ gets invoked). Therefore, you are responsible for closing the connection yourself (i.e. manual cleanup).
+ We suggest to use the persister either as a context manager through the ``async with`` clause or
+ using the method ``.cleanup()``.
+
+
+ This class is responsible for async persisting state data to a Redis database.
+ It inherits from the AsyncBaseStatePersister class.
+ """
+
+ @classmethod
+ def from_config(cls, config: dict) -> "AsyncRedisBasePersister":
+ """Creates a new instance of the RedisBasePersister from a configuration dictionary."""
+ return cls.from_values(**config)
+
+ @classmethod
+ def from_values(
+ cls,
+ host: str,
+ port: int,
+ db: int,
+ password: str = None,
+ serde_kwargs: dict = None,
+ redis_client_kwargs: dict = None,
+ namespace: str = None,
+ ) -> "AsyncRedisBasePersister":
+ """Creates a new instance of the AsyncRedisBasePersister from passed in values."""
+ if redis_client_kwargs is None:
+ redis_client_kwargs = {}
+ connection = aredis.Redis(
+ host=host, port=port, db=db, password=password, **redis_client_kwargs
+ )
+ return cls(connection, serde_kwargs, namespace)
+
+ def __init__(
+ self,
+ connection,
+ serde_kwargs: dict = None,
+ namespace: str = None,
+ ):
+ """Initializes the AsyncRedisPersister class.
+
+ :param connection: the redis connection object.
+ :param serde_kwargs: serialization and deserialization keyword arguments to pass to state SERDE.
+ :param namespace: The name of the project to optionally use in the key prefix.
+ """
+ self.connection = connection
+ self.serde_kwargs = serde_kwargs or {}
+ self.namespace = namespace if namespace else ""
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, exc_type, exc_value, traceback):
+ await self.connection.aclose()
+ return False
+
+ def set_serde_kwargs(self, serde_kwargs: dict):
+ """Sets the serde_kwargs for the persister."""
+ self.serde_kwargs = serde_kwargs
+
+ async def list_app_ids(self, partition_key: str, **kwargs) -> list[str]:
+ """List the app ids for a given partition key."""
+ namespaced_partition_key = add_namespace_to_partition_key(partition_key, self.namespace)
+ app_ids = await self.connection.zrevrange(namespaced_partition_key, 0, -1)
+ return [app_id.decode() for app_id in app_ids]
+
+ async def load(
+ self, partition_key: str, app_id: str, sequence_id: int = None, **kwargs
+ ) -> Optional[persistence.PersistedStateData]:
+ """Load the state data for a given partition key, app id, and sequence id.
+
+ If the sequence id is not given, it will be looked up in the Redis database. If it is not found, None will be returned.
+
+ :param partition_key:
+ :param app_id:
+ :param sequence_id:
+ :param kwargs:
+ :return: Value or None.
+ """
+ namespaced_partition_key = add_namespace_to_partition_key(partition_key, self.namespace)
+ if sequence_id is None:
+ sequence_id = await self.connection.zscore(namespaced_partition_key, app_id)
+ if sequence_id is None:
+ return None
+ sequence_id = int(sequence_id)
+ key = self.create_key(app_id, partition_key, sequence_id)
+ data = await self.connection.hgetall(key)
+ if not data:
+ return None
+ _state = state.State.deserialize(json.loads(data[b"state"].decode()), **self.serde_kwargs)
+ return {
+ "partition_key": partition_key,
+ "app_id": app_id,
+ "sequence_id": sequence_id,
+ "position": data[b"position"].decode(),
+ "state": _state,
+ "created_at": data[b"created_at"].decode(),
+ "status": data[b"status"].decode(),
+ }
+
+ def create_key(self, app_id, partition_key, sequence_id):
+ """Create a key for the Redis database."""
+ return add_namespace_to_partition_key(
+ f"{partition_key}:{app_id}:{sequence_id}", self.namespace
+ )
+
+ async def save(
+ self,
+ partition_key: str,
+ app_id: str,
+ sequence_id: int,
+ position: str,
+ state: state.State,
+ status: Literal["completed", "failed"],
+ **kwargs,
+ ):
+ """Save the state data to the Redis database.
+
+ :param partition_key:
+ :param app_id:
+ :param sequence_id:
+ :param position:
+ :param state:
+ :param status:
+ :param kwargs:
+ :return:
+ """
+ key = self.create_key(app_id, partition_key, sequence_id)
+ if await self.connection.exists(key):
+ raise ValueError(f"partition_key:app_id:sequence_id[{key}] already exists.")
+ json_state = json.dumps(state.serialize(**self.serde_kwargs))
+ await self.connection.hset(
+ key,
+ mapping={
+ "partition_key": partition_key,
+ "app_id": app_id,
+ "sequence_id": sequence_id,
+ "position": position,
+ "state": json_state,
+ "status": status,
+ "created_at": datetime.now(timezone.utc).isoformat(),
+ },
+ )
+ namespaced_partition_key = add_namespace_to_partition_key(partition_key, self.namespace)
+ await self.connection.zadd(namespaced_partition_key, {app_id: sequence_id})
+
+ async def cleanup(self):
+ """Closes the connection to the database."""
+ await self.connection.aclose()
+
+
class RedisPersister(RedisBasePersister):
"""A class used to represent a Redis Persister.
diff --git a/docs/reference/persister.rst b/docs/reference/persister.rst
index ebc92515..76d2bf14 100644
--- a/docs/reference/persister.rst
+++ b/docs/reference/persister.rst
@@ -103,3 +103,8 @@ Currently we support the following, although we highly recommend you contribute
:members:
.. automethod:: __init__
+
+.. autoclass:: burr.integrations.persisters.b_redis.AsyncRedisBasePersister
+ :members:
+
+ .. automethod:: __init__
diff --git a/tests/integrations/persisters/test_b_redis.py b/tests/integrations/persisters/test_b_redis.py
index 80551cec..c75615c3 100644
--- a/tests/integrations/persisters/test_b_redis.py
+++ b/tests/integrations/persisters/test_b_redis.py
@@ -4,7 +4,11 @@ import pickle
import pytest
from burr.core import state
-from burr.integrations.persisters.b_redis import RedisBasePersister, RedisPersister
+from burr.integrations.persisters.b_redis import (
+ AsyncRedisBasePersister,
+ RedisBasePersister,
+ RedisPersister,
+)
if not os.environ.get("BURR_CI_INTEGRATION_TESTS") == "true":
pytest.skip("Skipping integration tests", allow_module_level=True)
@@ -14,14 +18,14 @@ if not os.environ.get("BURR_CI_INTEGRATION_TESTS") == "true":
def redis_persister():
persister = RedisBasePersister.from_values(host="localhost", port=6379, db=0)
yield persister
- persister.connection.close()
+ persister.cleanup()
@pytest.fixture
def redis_persister_with_ns():
persister = RedisBasePersister.from_values(host="localhost", port=6379, db=0, namespace="test")
yield persister
- persister.connection.close()
+ persister.cleanup()
def test_save_and_load_state(redis_persister):
@@ -89,3 +93,65 @@ def test_serialization_with_pickle(redis_persister_with_ns):
data = deserialized_persister.load("pk", "app_id_serde", 1)
assert data["state"].get_all() == {"a": 1, "b": 2}
+
+
+async def async_redis_persister():
+ persister = AsyncRedisBasePersister.from_values(host="localhost", port=6379, db=1)
+ yield persister
+ await persister.cleanup()
+
+
+async def async_redis_persister_with_ns():
+ persister = AsyncRedisBasePersister.from_values(
+ host="localhost", port=6379, db=1, namespace="test_async"
+ )
+ yield persister
+ await persister.cleanup()
+
+
+async def test_async_save_and_load_state(async_redis_persister):
+ await async_redis_persister.save(
+ "pk", "app_id", 1, "pos", state.State({"a": 1, "b": 2}), "completed"
+ )
+ data = await async_redis_persister.load("pk", "app_id", 1)
+ assert data["state"].get_all() == {"a": 1, "b": 2}
+
+
+async def test_async_list_app_ids(async_redis_persister):
+ await async_redis_persister.save("pk", "app_id1", 1, "pos1", state.State({"a": 1}), "completed")
+ await async_redis_persister.save("pk", "app_id2", 2, "pos2", state.State({"b": 2}), "completed")
+ app_ids = await async_redis_persister.list_app_ids("pk")
+ assert "app_id1" in app_ids
+ assert "app_id2" in app_ids
+
+
+async def test_async_load_nonexistent_key(async_redis_persister):
+ state_data = await async_redis_persister.load("pk", "nonexistent_key")
+ assert state_data is None
+
+
+async def test_async_save_and_load_state_ns(async_redis_persister_with_ns):
+ await async_redis_persister_with_ns.save(
+ "pk", "app_id", 1, "pos", state.State({"a": 1, "b": 2}), "completed"
+ )
+ data = await async_redis_persister_with_ns.load("pk", "app_id", 1)
+ assert data["state"].get_all() == {"a": 1, "b": 2}
+
+
+async def test_async_list_app_ids_with_ns(async_redis_persister_with_ns):
+ await async_redis_persister_with_ns.save(
+ "pk", "app_id1", 1, "pos1", state.State({"a": 1}), "completed"
+ )
+ await async_redis_persister_with_ns.save(
+ "pk", "app_id2", 2, "pos2", state.State({"b": 2}), "completed"
+ )
+ app_ids = await async_redis_persister_with_ns.list_app_ids("pk")
+ assert "app_id1" in app_ids
+ assert "app_id2" in app_ids
+
+
+async def test_async_load_nonexistent_key_with_ns(async_redis_persister_with_ns):
+ state_data = await async_redis_persister_with_ns.load("pk", "nonexistent_key")
+ assert state_data is None