Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions src/cache/cache_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import constants
from models.config import ConversationCacheConfiguration
from cache.cache import Cache
from cache.noop_cache import NoopCache
from log import get_logger

logger = get_logger("cache.cache_factory")
Expand All @@ -13,20 +14,22 @@ class CacheFactory:
"""Cache factory class."""

@staticmethod
def conversation_cache(config: ConversationCacheConfiguration) -> Cache | None:
def conversation_cache(config: ConversationCacheConfiguration) -> Cache:
"""Create an instance of Cache based on loaded configuration.

Returns:
An instance of `Cache` (either `PostgresCache` or `InMemoryCache`).
An instance of `Cache` (either `SQLiteCache`, `PostgresCache` or `InMemoryCache`).
"""
logger.info("Creating cache instance of type %s", config.type)
match config.type:
case constants.CACHE_TYPE_NOOP:
return NoopCache()
case constants.CACHE_TYPE_MEMORY:
return None
return NoopCache()
case constants.CACHE_TYPE_SQLITE:
return None
return NoopCache()
case constants.CACHE_TYPE_POSTGRES:
return None
return NoopCache()
case _:
raise ValueError(
f"Invalid cache type: {config.type}. "
Expand Down
106 changes: 106 additions & 0 deletions src/cache/noop_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
"""No-operation cache implementation."""

from cache.cache import Cache
from models.cache_entry import CacheEntry
from log import get_logger
from utils.connection_decorator import connection

logger = get_logger("cache.noop_cache")


class NoopCache(Cache):
"""No-operation cache implementation."""

def __init__(self) -> None:
"""Create a new instance of no-op cache."""

def connect(self) -> None:
"""Initialize connection to database."""
logger.info("Connecting to storage")

def connected(self) -> bool:
"""Check if connection to cache is alive."""
return True

def initialize_cache(self) -> None:
"""Initialize cache."""

@connection
def get(
self, user_id: str, conversation_id: str, skip_user_id_check: bool = False
) -> list[CacheEntry]:
"""Get the value associated with the given key.

Args:
user_id: User identification.
conversation_id: Conversation ID unique for given user.
skip_user_id_check: Skip user_id suid check.

Returns:
Empty list.
"""
# just check if user_id and conversation_id are UUIDs
super().construct_key(user_id, conversation_id, skip_user_id_check)
return []

@connection
def insert_or_append(
self,
user_id: str,
conversation_id: str,
cache_entry: CacheEntry,
skip_user_id_check: bool = False,
) -> None:
"""Set the value associated with the given key.

Args:
user_id: User identification.
conversation_id: Conversation ID unique for given user.
cache_entry: The `CacheEntry` object to store.
skip_user_id_check: Skip user_id suid check.

"""
# just check if user_id and conversation_id are UUIDs
super().construct_key(user_id, conversation_id, skip_user_id_check)

@connection
def delete(
self, user_id: str, conversation_id: str, skip_user_id_check: bool = False
) -> bool:
"""Delete conversation history for a given user_id and conversation_id.

Args:
user_id: User identification.
conversation_id: Conversation ID unique for given user.
skip_user_id_check: Skip user_id suid check.

Returns:
bool: True in all cases.

"""
# just check if user_id and conversation_id are UUIDs
super().construct_key(user_id, conversation_id, skip_user_id_check)
return True

@connection
def list(self, user_id: str, skip_user_id_check: bool = False) -> list[str]:
"""List all conversations for a given user_id.

Args:
user_id: User identification.
skip_user_id_check: Skip user_id suid check.

Returns:
An empty list.

"""
super()._check_user_id(user_id, skip_user_id_check)
return []

def ready(self) -> bool:
"""Check if the cache is ready.

Returns:
True in all cases.
"""
return True
1 change: 1 addition & 0 deletions src/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,4 @@
CACHE_TYPE_MEMORY = "memory"
CACHE_TYPE_SQLITE = "sqlite"
CACHE_TYPE_POSTGRES = "postgres"
CACHE_TYPE_NOOP = "noop"
2 changes: 1 addition & 1 deletion src/models/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,7 @@ def check_default_model_and_provider(self) -> Self:
class ConversationCacheConfiguration(ConfigurationBase):
"""Conversation cache configuration."""

type: Literal["memory", "sqlite", "postgres"] | None = None
type: Literal["noop", "memory", "sqlite", "postgres"] | None = None
memory: Optional[InMemoryCacheConfig] = None
sqlite: Optional[SQLiteDatabaseConfiguration] = None
postgres: Optional[PostgreSQLDatabaseConfiguration] = None
Expand Down
22 changes: 22 additions & 0 deletions src/utils/connection_decorator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""Decocator that makes sure the object is 'connected' according to it's connected predicate."""

from typing import Any, Callable


def connection(f: Callable) -> Callable:
"""Decocator that makes sure the object is 'connected' according to it's connected predicate.

Example:
```python
@connection
def list_history(self) -> list[str]:
pass
```
"""

def wrapper(connectable: Any, *args: Any, **kwargs: Any) -> Callable:
if not connectable.connected():
connectable.connect()
return f(connectable, *args, **kwargs)

return wrapper
Comment on lines +1 to +22
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Decorator needs typing, wraps, and typos fixed.

Preserve metadata with wraps, provide precise typing via Protocol/ParamSpec, and fix docstring typos (“Decorator”, “its”).

Apply this diff:

-"""Decocator that makes sure the object is 'connected' according to it's connected predicate."""
-
-from typing import Any, Callable
-
-
-def connection(f: Callable) -> Callable:
-    """Decocator that makes sure the object is 'connected' according to it's connected predicate.
-
-    Example:
-    ```python
-    @connection
-    def list_history(self) -> list[str]:
-       pass
-    ```
-    """
-
-    def wrapper(connectable: Any, *args: Any, **kwargs: Any) -> Callable:
-        if not connectable.connected():
-            connectable.connect()
-        return f(connectable, *args, **kwargs)
-
-    return wrapper
+"""Decorator that ensures the object is connected according to its `connected()` predicate."""
+
+from functools import wraps
+from typing import Callable, Protocol, TypeVar
+from typing_extensions import Concatenate, ParamSpec
+
+P = ParamSpec("P")
+R = TypeVar("R")
+
+
+class Connectable(Protocol):
+    """Protocol for objects supporting connection lifecycle."""
+
+    def connected(self) -> bool: ...
+    def connect(self) -> None: ...
+
+
+def connection(
+    f: Callable[Concatenate[Connectable, P], R]
+) -> Callable[Concatenate[Connectable, P], R]:
+    """Ensure the object is connected before calling the wrapped method.
+
+    Args:
+        f: Bound instance method to wrap.
+
+    Returns:
+        A wrapper that auto-connects on demand, then calls the original method.
+    """
+
+    @wraps(f)
+    def wrapper(connectable: Connectable, *args: P.args, **kwargs: P.kwargs) -> R:
+        if not connectable.connected():
+            connectable.connect()
+        return f(connectable, *args, **kwargs)
+
+    return wrapper

1 change: 1 addition & 0 deletions tests/unit/cache/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Test cases for conversation history cache implementations."""
36 changes: 36 additions & 0 deletions tests/unit/cache/test_cache_factory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"""Unit tests for CacheFactory class."""

import pytest

from constants import CACHE_TYPE_NOOP
from models.config import ConversationCacheConfiguration
from cache.cache_factory import CacheFactory
from cache.noop_cache import NoopCache


@pytest.fixture(scope="module", name="noop_cache_config_fixture")
def noop_cache_config():
"""Fixture containing initialized instance of ConversationCacheConfiguration."""
return ConversationCacheConfiguration(type=CACHE_TYPE_NOOP)


@pytest.fixture(scope="module", name="invalid_cache_type_config_fixture")
def invalid_cache_type_config():
"""Fixture containing instance of ConversationCacheConfiguration with improper settings."""
c = ConversationCacheConfiguration()
c.type = "foo bar baz"
return c


def test_conversation_cache_noop(noop_cache_config_fixture):
"""Check if NoopCache is returned by factory with proper configuration."""
cache = CacheFactory.conversation_cache(noop_cache_config_fixture)
assert cache is not None
# check if the object has the right type
assert isinstance(cache, NoopCache)


def test_conversation_cache_wrong_cache(invalid_cache_type_config_fixture):
"""Check if wrong cache configuration is detected properly."""
with pytest.raises(ValueError, match="Invalid cache type"):
CacheFactory.conversation_cache(invalid_cache_type_config_fixture)
Loading
Loading