From 896cb5e4feec8284d15b14f6bb92b1c03e5a8257 Mon Sep 17 00:00:00 2001 From: Fabien Arcellier Date: Wed, 11 Dec 2024 08:30:43 +0100 Subject: [PATCH] feat: implement local storage * feat: propagate local storage into session to keep it into sync --- src/writer/app_runner.py | 1 + src/writer/core.py | 16 ++++++++++++++++ tests/backend/test_core.py | 1 + 3 files changed, 18 insertions(+) diff --git a/src/writer/app_runner.py b/src/writer/app_runner.py index e6496f44f..f90c9c838 100644 --- a/src/writer/app_runner.py +++ b/src/writer/app_runner.py @@ -174,6 +174,7 @@ def _handle_event(self, session: WriterSession, event: WriterEvent) -> EventResp import traceback as tb result = session.event_handler.handle(event) + session.process_local_storage_changes() mutations = {} diff --git a/src/writer/core.py b/src/writer/core.py index 5660ee01f..0eade3f9e 100644 --- a/src/writer/core.py +++ b/src/writer/core.py @@ -139,6 +139,9 @@ class WriterSession: """ def __init__(self, session_id: str, cookies: Optional[Dict[str, str]], headers: Optional[Dict[str, str]], local_storage: Optional[Dict[str, Any]]) -> None: + if local_storage is None: + local_storage = {} + self.session_id = session_id self.cookies = cookies self.headers = headers @@ -154,6 +157,19 @@ def __init__(self, session_id: str, cookies: Optional[Dict[str, str]], headers: def update_last_active_timestamp(self) -> None: self.last_active_timestamp = int(time.time()) + def process_local_storage_changes(self) -> None: + """ + Processes the local storage changes. + + Changes to local storage are propagated by the mail protocol. + It process the mail messages to keep the representation of local storage in a consistent session + """ + for m in self.session_state.mail: + if m["type"] == "localStorageSetItem": + self.local_storage[m['payload']['key']] = m['payload']['value'] + elif m["type"] == "localStorageRemoveItem": + self.local_storage.pop(m['payload']['key'], None) + @dataclasses.dataclass class MutationSubscription: diff --git a/tests/backend/test_core.py b/tests/backend/test_core.py index 810b5d293..b9a68214c 100644 --- a/tests/backend/test_core.py +++ b/tests/backend/test_core.py @@ -1222,6 +1222,7 @@ def test_get_new_session_proposed(self) -> None: self.sm.get_new_session( {"testCookie": "yes"}, {"origin": "example.com"}, + {}, self.proposed_session_id ) self.sm.get_session(self.proposed_session_id)