diff libervia/server/server.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 6643855770a5
children a169cbc315f0
line wrap: on
line diff
--- a/libervia/server/server.py	Wed Mar 01 17:55:25 2023 +0100
+++ b/libervia/server/server.py	Wed Mar 01 18:02:44 2023 +0100
@@ -844,6 +844,7 @@
 
     def __init__(self, options):
         self.options = options
+        websockets.host = self
 
     def _init(self):
         # we do init here and not in __init__ to avoid doule initialisation with twistd
@@ -1199,10 +1200,10 @@
 
         # websocket
         if self.options["connection_type"] in ("https", "both"):
-            wss = websockets.LiberviaPageWSProtocol.getResource(self, secure=True)
+            wss = websockets.LiberviaPageWSProtocol.getResource(secure=True)
             self.putChildAll(b'wss', wss)
         if self.options["connection_type"] in ("http", "both"):
-            ws = websockets.LiberviaPageWSProtocol.getResource(self, secure=False)
+            ws = websockets.LiberviaPageWSProtocol.getResource(secure=False)
             self.putChildAll(b'ws', ws)
 
         ## following signal is needed for cache handling in Libervia pages
@@ -1210,7 +1211,7 @@
             "psEventRaw", partial(LiberviaPage.onNodeEvent, self), "plugin"
         )
         self.bridge.register_signal(
-            "messageNew", partial(LiberviaPage.onSignal, self, "messageNew")
+            "messageNew", partial(self.on_signal, "messageNew")
         )
 
         #  Progress handling
@@ -1325,6 +1326,19 @@
         getattr(self.bridge, method_name)(*args, **kwargs)
         return d
 
+    def on_signal(self, signal_name, *args):
+        profile = args[-1]
+        if not profile:
+            log.error(f"got signal without profile: {signal_name}, {args}")
+            return
+        try:
+            sockets = websockets.LiberviaPageWSProtocol.profile_map[profile]
+        except KeyError:
+            log.debug(f"no socket opened for profile {profile}")
+            return
+        for socket in sockets:
+            socket.send("bridge", {"signal": signal_name, "args": args})
+
     async def _logged(self, profile, request):
         """Set everything when a user just logged in
 
@@ -1360,16 +1374,19 @@
             )
         )
 
-        def onExpire():
+        def on_expire():
             log.info("Session expired (profile={profile})".format(profile=profile))
             self.cache_resource.delEntity(sat_session.uuid.encode('utf-8'))
             log.debug(
                 _("profile cache resource {uuid} deleted").format(uuid=sat_session.uuid)
             )
+            sat_session.on_expire()
+            if sat_session.ws_socket is not None:
+                sat_session.ws_socket.close()
             # and now we disconnect the profile
             self.bridgeCall("disconnect", profile)
 
-        session.notifyOnExpire(onExpire)
+        session.notifyOnExpire(on_expire)
 
         # FIXME: those session infos should be returned by connect or isConnected
         infos = await self.bridgeCall("sessionInfosGet", profile)
@@ -1768,6 +1785,11 @@
         session = request.session
         if session is not None:
             log.debug(_("session purge"))
+            sat_session = self.getSessionData(request, session_iface.ISATSession)
+            socket = sat_session.ws_socket
+            if socket is not None:
+                socket.close()
+                session.ws_socket = None
             session.expire()
             # FIXME: not clean but it seems that it's the best way to reset
             #        session during request handling
@@ -1824,7 +1846,7 @@
 
     ## Websocket (dynamic pages) ##
 
-    def getWebsocketURL(self, request):
+    def get_websocket_url(self, request):
         base_url_split = self.getExtBaseURLData(request)
         if base_url_split.scheme.endswith("s"):
             scheme = "wss"
@@ -1833,12 +1855,6 @@
 
         return self.getExtBaseURL(request, path=scheme, scheme=scheme)
 
-    def registerWSToken(self, token, page, request):
-        # we make a shallow copy of request to avoid losing request.channel when
-        # connection is lost (which would result as request.isSecure() being always
-        # False). See #327
-        request._signal_id = id(request)
-        websockets.LiberviaPageWSProtocol.registerToken(token, page, copy.copy(request))
 
     ## Various utils ##