Elffuss BraidHub

kikocis/llama-stack public

3fc339af16ee · 2.0 KiBRawPermalink
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2# All rights reserved.
3#
4# This source code is licensed under the terms described in the LICENSE file in
5# the root directory of this source tree.
6
7from datetime import datetime, timedelta
8from typing import Any, List, Optional
9
10from redis.asyncio import Redis
11
12from llama_stack.apis.control_plane import * # noqa: F403
13
14
15from .config import RedisImplConfig
16
17
18class RedisControlPlaneAdapter(ControlPlane):
19 def __init__(self, config: RedisImplConfig):
20 self.config = config
21
22 async def initialize(self) -> None:
23 self.redis = Redis.from_url(self.config.url)
24
25 def _namespaced_key(self, key: str) -> str:
26 if not self.config.namespace:
27 return key
28 return f"{self.config.namespace}:{key}"
29
30 async def set(
31 self, key: str, value: Any, expiration: Optional[datetime] = None
32 ) -> None:
33 key = self._namespaced_key(key)
34 await self.redis.set(key, value)
35 if expiration:
36 await self.redis.expireat(key, expiration)
37
38 async def get(self, key: str) -> Optional[ControlPlaneValue]:
39 key = self._namespaced_key(key)
40 value = await self.redis.get(key)
41 if value is None:
42 return None
43 ttl = await self.redis.ttl(key)
44 expiration = datetime.now() + timedelta(seconds=ttl) if ttl > 0 else None
45 return ControlPlaneValue(key=key, value=value, expiration=expiration)
46
47 async def delete(self, key: str) -> None:
48 key = self._namespaced_key(key)
49 await self.redis.delete(key)
50
51 async def range(self, start_key: str, end_key: str) -> List[ControlPlaneValue]:
52 start_key = self._namespaced_key(start_key)
53 end_key = self._namespaced_key(end_key)
54
55 keys = await self.redis.keys(f"{start_key}*")
56 result = []
57 for key in keys:
58 if key <= end_key:
59 value = await self.get(key)
60 if value:
61 result.append(value)
62 return result