Mercurial > libervia-web
diff libervia/server/session_iface.py @ 1504:409d10211b20
server, browser: dynamic pages refactoring:
dynamic pages has been reworked, to change the initial basic implementation.
Pages are now dynamic by default, and a websocket is established by the first connected
page of a session. The socket is used to transmit bridge signals, and then the signal is
broadcasted to other tabs using broadcast channel.
If the connecting tab is closed, an other one is chosen.
Some tests are made to retry connecting in case of problem, and sometimes reload the pages
(e.g. if profile is connected).
Signals (or other data) are cached during reconnection phase, to avoid lost of data.
All previous partial rendering mechanism have been removed, chat page is temporarily not
working anymore, but will be eventually redone (one of the goal of this work is to have
proper chat).
author | Goffi <goffi@goffi.org> |
---|---|
date | Wed, 01 Mar 2023 18:02:44 +0100 |
parents | 822bd0139769 |
children | ce879da7fcf7 |
line wrap: on
line diff
--- a/libervia/server/session_iface.py Wed Mar 01 17:55:25 2023 +0100 +++ b/libervia/server/session_iface.py Wed Mar 01 18:02:44 2023 +0100 @@ -15,14 +15,22 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. -from zope.interface import Interface, Attribute +from collections import OrderedDict, deque +import os.path +import time +from typing import List, Dict, Optional + +import shortuuid +from zope.interface import Attribute, Interface from zope.interface import implementer -from libervia.server.constants import Const as C + +from sat.core.log import getLogger + from libervia.server.classes import Notification -from collections import OrderedDict -import os.path -import shortuuid -import time +from libervia.server.constants import Const as C + + +log = getLogger(__name__) FLAGS_KEY = "_flags" NOTIFICATIONS_KEY = "_notifications" @@ -37,10 +45,11 @@ @implementer(ISATSession) -class SATSession(object): +class SATSession: + profiles_map: Dict[Optional[str], List["SATSession"]] = {} def __init__(self, session): - self.profile = None + self._profile = None self.jid = None self.started = time.time() # time when the backend session was started @@ -48,10 +57,39 @@ self.uuid = str(shortuuid.uuid()) self.identities = {} self.csrf_token = str(shortuuid.uuid()) + self.ws_token = str(shortuuid.uuid()) + self.ws_socket = None + self.ws_buffer = deque(maxlen=200) self.locale = None # i18n of the pages self.theme = None self.pages_data = {} # used to keep data accross reloads (key is page instance) self.affiliations = OrderedDict() # cache for node affiliations + self.profiles_map.setdefault(C.SERVICE_PROFILE, []).append(self) + log.debug( + f"session started for {C.SERVICE_PROFILE} " + f"({len(self.get_profile_sessions(C.SERVICE_PROFILE))} session(s) active)" + ) + + @property + def profile(self) -> Optional[str]: + return self._profile + + @profile.setter + def profile(self, profile: Optional[str]) -> None: + old_profile = self._profile or C.SERVICE_PROFILE + new_profile = profile or C.SERVICE_PROFILE + try: + self.profiles_map[old_profile].remove(self) + except (ValueError, KeyError): + log.warning(f"session was not registered for profile {old_profile}") + else: + nb_session_old = len(self.get_profile_sessions(old_profile)) + log.debug(f"{old_profile} has now {nb_session_old} session(s) active") + + self._profile = profile + self.profiles_map.setdefault(new_profile, []).append(self) + nb_session_new = len(self.get_profile_sessions(new_profile)) + log.debug(f"{new_profile} has now {nb_session_new} session(s) active") @property def cache_dir(self): @@ -71,6 +109,36 @@ else: return self.profile.startswith("guest@@") + @classmethod + def send(cls, profile: str, data_type: str, data: dict) -> None: + """Send a message to all session + + If the session doesn't have an active websocket, the message is buffered until a + socket is available + """ + for session in cls.profiles_map.get(profile, []): + if session.ws_socket is None or not session.ws_socket.init_ok: + session.ws_buffer.append({"data_type": data_type, "data": data}) + else: + session.ws_socket.send(data_type, data) + + def on_expire(self) -> None: + profile = self._profile or C.SERVICE_PROFILE + try: + self.profiles_map[profile].remove(self) + except (ValueError, KeyError): + log.warning(f"session was not registered for profile {profile}") + else: + nb_session = len(self.get_profile_sessions(profile)) + log.debug( + f"Session for profile {profile} expired. {profile} has now {nb_session} " + f"session(s) active." + ) + + @classmethod + def get_profile_sessions(cls, profile: str) -> List["SATSession"]: + return cls.profiles_map.get(profile, []) + def getPageData(self, page, key): """get session data for a page