Skip to content

Commit 68a19f2

Browse files
committed
use yield for strays; fix tests
1 parent eb7cb8d commit 68a19f2

File tree

10 files changed

+39
-18
lines changed

10 files changed

+39
-18
lines changed

compose.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ services:
1818
- TZ=${CCAT_TIMEZONE:-UTC}
1919
volumes:
2020
- ./core:/app
21+
- ./tmp:/tmp
2122
command:
2223
- python
2324
- "-m"

core/cat/auth/connection.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,13 @@ async def __call__(
5454
protocol, credential, self.resource, self.permission, user_id=user_id
5555
)
5656
if user:
57-
return await self.get_user_stray(user, connection)
57+
stray = await self.get_user_stray(user, connection)
58+
yield stray
59+
60+
log.critical("STRAY FINITO")
61+
stray.update_working_memory_cache()
62+
del stray
63+
return
5864

5965
# if no stray was obtained, raise exception
6066
self.not_allowed(connection)
@@ -135,7 +141,7 @@ def extract_credentials(self, connection: WebSocket) -> Tuple[str, str] | None:
135141

136142

137143
async def get_user_stray(self, user: AuthUserInfo, connection: WebSocket) -> StrayCat:
138-
return StrayCat(
144+
return StrayCat(
139145
ws=connection,
140146
user_id=user.name, # TODOV2: user_id should be the user.id
141147
user_data=user,

core/cat/looking_glass/stray_cat.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ def __init__(
4242
self.__user_data = user_data
4343

4444
# get working memory from cache or create a new one
45+
log.warning(f"GET working memory for {user_id}")
4546
self.working_memory = self.cache.get_value(f"{user_id}_working_memory") or WorkingMemory()
4647

4748
# attribute to store ws connection
@@ -52,11 +53,15 @@ def __init__(
5253
def __repr__(self):
5354
return f"StrayCat(user_id={self.user_id})"
5455

55-
def __del__(self):
56+
#def __del__(self):
57+
# log.critical(f"StrayCat __del__ called for {self.user_id}")
58+
#self.__main_loop = None
59+
#self.__ws = None
5660
# when the garbage collector deletes the stray, we update working memory in cache
57-
updated_cache_item = CacheItem(f"{self.user_id}_working_memory", self.working_memory, -1)
58-
self.cache.insert(updated_cache_item)
59-
log.critical(f"StrayCat {self.user_id} deleted")
61+
# self.update_working_memory_cache()
62+
#self.__user_id = None
63+
#self.__user_data = None
64+
# del self
6065

6166

6267
def __send_ws_json(self, data: Any):
@@ -95,6 +100,12 @@ def __build_why(self) -> MessageWhy:
95100
)
96101

97102
return why
103+
104+
def update_working_memory_cache(self):
105+
"""Update the working memory in the cache."""
106+
log.warning(f"SAVE working memory for {self.user_id}")
107+
updated_cache_item = CacheItem(f"{self.user_id}_working_memory", self.working_memory, -1)
108+
self.cache.insert(updated_cache_item)
98109

99110
def send_ws_message(self, content: str, msg_type: MSG_TYPES = "notification"):
100111
"""Send a message via websocket.
@@ -478,6 +489,7 @@ def __call__(self, message_dict):
478489
def run(self, user_message_json, return_message=False):
479490
try:
480491
cat_message = self.__call__(user_message_json)
492+
self.update_working_memory_cache()
481493
if return_message:
482494
# return the message for HTTP usage
483495
return cat_message

core/cat/memory/working_memory.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def update_conversation_history(self, message: str, who: str, why = {}):
6363
-----
6464
This method is deprecated and will be removed in future versions. Use `update_history` instead.
6565
"""
66-
66+
6767
deprecation_warning(
6868
"update_conversation_history is deprecated and will be removed in a future release. Use update_history instead."
6969
)

core/cat/routes/base.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,5 @@ async def message_with_cat(
2929
"""Get a response from the Cat"""
3030
user_message_json = {"user_id": stray.user_id, **payload}
3131
answer = await run_in_threadpool(stray.run, user_message_json, True)
32+
del stray
3233
return answer

core/cat/routes/static/static.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ async def __call__(self, scope, receive, send) -> None:
1414
stray_http_auth = HTTPAuth(
1515
resource=AuthResource.STATIC, permission=AuthPermission.READ
1616
)
17-
allowed = await stray_http_auth(request)
17+
allowed = stray_http_auth(request)
1818
if allowed:
1919
await super().__call__(scope, receive, send)
2020
else:

core/cat/startup.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -78,14 +78,6 @@ def custom_generate_unique_id(route: APIRoute):
7878
allow_headers=["*"],
7979
)
8080

81-
# Auto update sessions cache witha middleware
82-
#@cheshire_cat_api.middleware("http")
83-
#async def update_stray_cache(request: Request, call_next):
84-
# log.critical("MIDDLEWARE")
85-
# print(request)
86-
# response = await call_next(request)
87-
# return response
88-
8981
# Add routers to the middleware stack.
9082
cheshire_cat_api.include_router(base.router, tags=["Home"])
9183
cheshire_cat_api.include_router(auth.router, tags=["User Auth"], prefix="/auth")

core/tests/conftest.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ def clean_up_mocks():
6666
"tests/mocks/mock_plugin/settings.json",
6767
"tests/mocks/mock_plugin_folder/mock_plugin",
6868
"tests/mocks/empty_folder",
69+
"/tmp_test",
6970
]
7071
for tbr in to_be_removed:
7172
if os.path.exists(tbr):
@@ -86,6 +87,7 @@ def client(monkeypatch) -> Generator[TestClient, Any, None]:
8687
clean_up_mocks()
8788
# env variables
8889
os.environ["CCAT_DEBUG"] = "false" # do not autoreload
90+
os.environ["CCAT_CACHE_DIR"] = "/tmp_test" # use a different file system cache dir
8991
# monkeypatch classes
9092
mock_classes(monkeypatch)
9193
# delete all singletons!!!

core/tests/routes/test_session.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@
55
from tests.utils import send_websocket_message
66

77

8+
def test_no_sessions_at_startup(client):
9+
assert False # TODO
10+
11+
812
def test_session_creation_from_websocket(client):
913
# send websocket message
1014
mex = {"text": "Where do I go?"}
@@ -14,7 +18,7 @@ def test_session_creation_from_websocket(client):
1418
assert "You did not configure" in res["content"]
1519

1620
# verify session
17-
strays = client.app.state.ccat.cache
21+
strays = client.app.state.ccat.cache.get_value()
1822
assert "Alice" in strays
1923
assert isinstance(strays["Alice"], StrayCat)
2024
assert strays["Alice"].user_id == "Alice"

core/tests/test_env_variables.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,10 @@ def test_get_env(client):
2222

2323
if k == "CCAT_DEBUG":
2424
assert get_env(k) == "false" # we test installation with autoreload off
25-
else:
25+
elif k == "CCAT_CACHE_DIR":
26+
assert get_env(k) == "/tmp_test" # we test installation with a different cache dir
27+
else:
28+
# default values
2629
assert get_env(k) == v
2730

2831
# TODO: take away in v2

0 commit comments

Comments
 (0)