selfprivacy-rest-api/selfprivacy_api/utils/redis_pool.py

59 lines
1.6 KiB
Python
Raw Permalink Normal View History

2022-10-28 08:09:36 +00:00
"""
Redis pool module for selfprivacy_api
"""
2024-07-26 19:59:32 +00:00
import redis
2024-04-01 20:12:02 +00:00
import redis.asyncio as redis_async
2024-07-26 19:59:32 +00:00
from redis.asyncio.client import PubSub
2022-10-28 08:09:36 +00:00
REDIS_SOCKET = "/run/redis-sp-api/redis.sock"
2022-10-28 08:09:36 +00:00
2024-04-15 13:37:04 +00:00
class RedisPool:
2022-10-28 08:09:36 +00:00
"""
Redis connection pool singleton.
"""
def __init__(self):
2024-04-15 13:37:04 +00:00
self._dbnumber = 0
url = RedisPool.connection_url(dbnumber=self._dbnumber)
2024-04-01 20:12:02 +00:00
# We need a normal sync pool because otherwise
# our whole API will need to be async
2024-01-19 14:06:07 +00:00
self._pool = redis.ConnectionPool.from_url(
2024-04-01 20:12:02 +00:00
url,
decode_responses=True,
)
# We need an async pool for pubsub
self._async_pool = redis_async.ConnectionPool.from_url(
url,
2024-01-19 14:06:07 +00:00
decode_responses=True,
)
2024-01-19 14:06:07 +00:00
@staticmethod
def connection_url(dbnumber: int) -> str:
"""
redis://[[username]:[password]]@localhost:6379/0
unix://[username@]/path/to/socket.sock?db=0[&password=password]
"""
return f"unix://{REDIS_SOCKET}?db={dbnumber}"
2022-10-28 08:09:36 +00:00
def get_connection(self):
"""
Get a connection from the pool.
"""
return redis.Redis(connection_pool=self._pool)
2024-04-01 20:12:02 +00:00
def get_connection_async(self) -> redis_async.Redis:
2022-10-28 08:09:36 +00:00
"""
2024-04-01 20:12:02 +00:00
Get an async connection from the pool.
Async connections allow pubsub.
2022-10-28 08:09:36 +00:00
"""
2024-04-01 20:12:02 +00:00
return redis_async.Redis(connection_pool=self._async_pool)
2024-04-15 13:37:04 +00:00
2024-07-26 19:59:32 +00:00
async def subscribe_to_keys(self, pattern: str) -> PubSub:
2024-04-15 13:37:04 +00:00
async_redis = self.get_connection_async()
pubsub = async_redis.pubsub()
await pubsub.psubscribe(f"__keyspace@{self._dbnumber}__:" + pattern)
return pubsub