ws_sync.session

  1from __future__ import annotations
  2
  3import logging
  4from asyncio import Lock
  5from collections.abc import Callable
  6from contextlib import suppress
  7from contextvars import ContextVar, Token
  8from logging import Logger
  9from typing import Any, Self
 10
 11from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState
 12
 13from .utils import nonblock_call
 14
 15logger = logging.getLogger(__name__)
 16
 17# session context
 18session_context: ContextVar[Session] = ContextVar("session_context")
 19"""Per-task session context. Within concurrent async tasks, this context variable can be used to access the current Session object."""
 20
 21
 22class Session:
 23    """
 24    A session is a persistent connection with the other.
 25
 26    This is a counter-part to the SessionManager in the frontend.
 27    There should be one instance of this class per user session, even across reconnects of the websocket. This means the states that belong to the user session should be subscribed to the events of this class.
 28    It defines a simple state-syncing protocol between the frontend and the backend, every event being of type {type: str, data: any}.
 29    """
 30
 31    def __init__(self, logger: Logger | None = logger):
 32        self.ws = None
 33        self.ws_lock = Lock()  # when multiple clients try to connect at the same time, we need to ensure that only one connection is established
 34        self.event_handlers: dict[str, Callable[..., Any]] = {}  # triggered on event
 35        self.init_handlers: list[
 36            Callable[..., Any]
 37        ] = []  # triggered on connection init
 38        self.logger = logger
 39        self.state: SessionState | None = None
 40        """user-assigned state associated with the session"""
 41        self._tokens: list[Token[Session]] = []
 42
 43    @property
 44    def is_connected(self) -> bool:
 45        return self.ws is not None
 46
 47    # ===== Low-Level: Register Event Callbacks =====#
 48    def register_event(self, event: str, callback: Callable[..., Any]):
 49        if event in self.event_handlers and self.logger:
 50            self.logger.warning("Event %s already has a subscriber.", event)
 51        self.event_handlers[event] = callback
 52
 53    def deregister_event(self, event: str):
 54        if event not in self.event_handlers:
 55            if self.logger:
 56                self.logger.warning("Event %s has no subscriber.", event)
 57            return
 58        del self.event_handlers[event]
 59
 60    def register_init(self, callback: Callable[..., Any]):
 61        self.init_handlers.append(callback)
 62
 63    # ===== Low-Level: Networking =====#
 64    async def new_connection(self, ws: WebSocket):
 65        """
 66        Set the new ws connection while possibly gracefully disconnecting the old one.
 67        """
 68        async with self.ws_lock:
 69            if self.ws is not None:
 70                if self.logger:
 71                    self.logger.warning(
 72                        "Overwriting existing websocket %s with %s",
 73                        self.ws.client,
 74                        ws.client,
 75                    )
 76                await self.disconnect()
 77            self.ws = ws
 78
 79        if self.ws.application_state == WebSocketState.CONNECTING:
 80            await self.ws.accept()
 81
 82        await self.init()
 83
 84    async def disconnect(
 85        self,
 86        message: str = "Seems like you're logged in somewhere else. If this is a mistake, please refresh the page.",
 87        ws: WebSocket | None = None,
 88    ):
 89        """
 90        Disconnect the websocket connection after sending a message.
 91        """
 92        # TODO: not sure why I made the ws argument, but I will keep it for now.
 93        if ws:
 94            self.ws = ws
 95        if self.ws is None:
 96            return
 97        await self.send("_DISCONNECT", message)
 98        assert self.ws is not None
 99        with suppress(Exception):
100            await self.ws.close()
101        self.ws = None
102
103    async def init(self):
104        for handler in self.init_handlers:
105            await nonblock_call(handler)
106
107    async def send(self, event: str, data: Any):
108        if self.ws is None:
109            return
110        try:
111            await self.ws.send_json({"type": event, "data": data})
112        except Exception:
113            if self.logger:
114                self.logger.exception("Error sending event %s", event)
115
116    async def send_binary(self, event: str, metadata: dict[str, Any], data: bytes):
117        if self.ws is None:
118            return
119        try:
120            await self.ws.send_json(
121                {"type": "_BIN_META", "data": {"type": event, "metadata": metadata}}
122            )
123            await self.ws.send_bytes(data)
124        except Exception:
125            if self.logger:
126                self.logger.exception("Error sending binary event %s", event)
127
128    async def handle_connection(self, ws: WebSocket | None = None):
129        """
130        Handler that blocks until the websocket is disconnected. It takes care of accepting the websocket connection, and dispatching events to the appropriate handlers. If the ws argument is provided, it will be used as the websocket connection, otherwise it will use the existing connection.
131
132        Args:
133            ws: The websocket connection to use. If None, it will use the existing connection.
134        """
135        if ws:
136            await self.new_connection(ws)
137
138        assert self.ws is not None
139
140        with self:  # provide the session context
141            try:
142                if self.state:
143                    await self.state.on_connect()
144            except Exception:
145                if self.logger:
146                    self.logger.exception("Error while calling state.on_connect")
147
148            try:
149                while self.ws.application_state == WebSocketState.CONNECTED:
150                    full_data = await self.ws.receive_json()
151                    event = full_data.get("type")
152                    data = full_data.get("data")
153
154                    if event == "_BIN_META":
155                        # unwrap and construct the original event
156                        event = data.get("type")
157                        metadata = data.get("metadata")
158                        bindata = await self.ws.receive_bytes()
159                        data = {"data": bindata, **metadata}
160
161                    if handler := self.event_handlers.get(event):
162                        await nonblock_call(handler, data)
163                    elif self.logger:
164                        self.logger.warning(
165                            "Received event %s but no subscriber was found.", event
166                        )
167            except WebSocketDisconnect:
168                if self.logger:
169                    self.logger.info("Websocket disconnected")
170            except Exception:
171                if self.logger:
172                    self.logger.exception("Error while handling connection")
173            finally:
174                try:
175                    if self.state:
176                        await self.state.on_disconnect()
177                except Exception:
178                    if self.logger:
179                        self.logger.exception("Error while calling state.on_disconnect")
180                with suppress(Exception):
181                    ws = self.ws
182                    self.ws = None
183                    if ws is not None:
184                        await ws.close()
185
186    # ===== High-Level: Context Manager =====#
187    def __enter__(self) -> Self:
188        token = session_context.set(self)
189        self._tokens.append(token)
190        return self
191
192    def __exit__(
193        self,
194        exc_type: type[BaseException] | None,
195        exc_value: BaseException | None,
196        traceback: object,
197    ):
198        if self._tokens:
199            token = self._tokens.pop()
200            session_context.reset(token)
201
202
203class SessionState:
204    """
205    Abstract base class for user-defined session state objects that can be associated with a Session object.
206    """
207
208    async def on_connect(self):
209        """Called after the websocket connection is established."""
210
211    async def on_disconnect(self):
212        """Called after the websocket connection is closed."""
213
214    async def on_terminate(self):
215        """Called when the session is forcefully terminated by the server."""
logger = <Logger ws_sync.session (WARNING)>
session_context: _contextvars.ContextVar[Session] = <ContextVar name='session_context'>

Per-task session context. Within concurrent async tasks, this context variable can be used to access the current Session object.

class Session:
 23class Session:
 24    """
 25    A session is a persistent connection with the other.
 26
 27    This is a counter-part to the SessionManager in the frontend.
 28    There should be one instance of this class per user session, even across reconnects of the websocket. This means the states that belong to the user session should be subscribed to the events of this class.
 29    It defines a simple state-syncing protocol between the frontend and the backend, every event being of type {type: str, data: any}.
 30    """
 31
 32    def __init__(self, logger: Logger | None = logger):
 33        self.ws = None
 34        self.ws_lock = Lock()  # when multiple clients try to connect at the same time, we need to ensure that only one connection is established
 35        self.event_handlers: dict[str, Callable[..., Any]] = {}  # triggered on event
 36        self.init_handlers: list[
 37            Callable[..., Any]
 38        ] = []  # triggered on connection init
 39        self.logger = logger
 40        self.state: SessionState | None = None
 41        """user-assigned state associated with the session"""
 42        self._tokens: list[Token[Session]] = []
 43
 44    @property
 45    def is_connected(self) -> bool:
 46        return self.ws is not None
 47
 48    # ===== Low-Level: Register Event Callbacks =====#
 49    def register_event(self, event: str, callback: Callable[..., Any]):
 50        if event in self.event_handlers and self.logger:
 51            self.logger.warning("Event %s already has a subscriber.", event)
 52        self.event_handlers[event] = callback
 53
 54    def deregister_event(self, event: str):
 55        if event not in self.event_handlers:
 56            if self.logger:
 57                self.logger.warning("Event %s has no subscriber.", event)
 58            return
 59        del self.event_handlers[event]
 60
 61    def register_init(self, callback: Callable[..., Any]):
 62        self.init_handlers.append(callback)
 63
 64    # ===== Low-Level: Networking =====#
 65    async def new_connection(self, ws: WebSocket):
 66        """
 67        Set the new ws connection while possibly gracefully disconnecting the old one.
 68        """
 69        async with self.ws_lock:
 70            if self.ws is not None:
 71                if self.logger:
 72                    self.logger.warning(
 73                        "Overwriting existing websocket %s with %s",
 74                        self.ws.client,
 75                        ws.client,
 76                    )
 77                await self.disconnect()
 78            self.ws = ws
 79
 80        if self.ws.application_state == WebSocketState.CONNECTING:
 81            await self.ws.accept()
 82
 83        await self.init()
 84
 85    async def disconnect(
 86        self,
 87        message: str = "Seems like you're logged in somewhere else. If this is a mistake, please refresh the page.",
 88        ws: WebSocket | None = None,
 89    ):
 90        """
 91        Disconnect the websocket connection after sending a message.
 92        """
 93        # TODO: not sure why I made the ws argument, but I will keep it for now.
 94        if ws:
 95            self.ws = ws
 96        if self.ws is None:
 97            return
 98        await self.send("_DISCONNECT", message)
 99        assert self.ws is not None
100        with suppress(Exception):
101            await self.ws.close()
102        self.ws = None
103
104    async def init(self):
105        for handler in self.init_handlers:
106            await nonblock_call(handler)
107
108    async def send(self, event: str, data: Any):
109        if self.ws is None:
110            return
111        try:
112            await self.ws.send_json({"type": event, "data": data})
113        except Exception:
114            if self.logger:
115                self.logger.exception("Error sending event %s", event)
116
117    async def send_binary(self, event: str, metadata: dict[str, Any], data: bytes):
118        if self.ws is None:
119            return
120        try:
121            await self.ws.send_json(
122                {"type": "_BIN_META", "data": {"type": event, "metadata": metadata}}
123            )
124            await self.ws.send_bytes(data)
125        except Exception:
126            if self.logger:
127                self.logger.exception("Error sending binary event %s", event)
128
129    async def handle_connection(self, ws: WebSocket | None = None):
130        """
131        Handler that blocks until the websocket is disconnected. It takes care of accepting the websocket connection, and dispatching events to the appropriate handlers. If the ws argument is provided, it will be used as the websocket connection, otherwise it will use the existing connection.
132
133        Args:
134            ws: The websocket connection to use. If None, it will use the existing connection.
135        """
136        if ws:
137            await self.new_connection(ws)
138
139        assert self.ws is not None
140
141        with self:  # provide the session context
142            try:
143                if self.state:
144                    await self.state.on_connect()
145            except Exception:
146                if self.logger:
147                    self.logger.exception("Error while calling state.on_connect")
148
149            try:
150                while self.ws.application_state == WebSocketState.CONNECTED:
151                    full_data = await self.ws.receive_json()
152                    event = full_data.get("type")
153                    data = full_data.get("data")
154
155                    if event == "_BIN_META":
156                        # unwrap and construct the original event
157                        event = data.get("type")
158                        metadata = data.get("metadata")
159                        bindata = await self.ws.receive_bytes()
160                        data = {"data": bindata, **metadata}
161
162                    if handler := self.event_handlers.get(event):
163                        await nonblock_call(handler, data)
164                    elif self.logger:
165                        self.logger.warning(
166                            "Received event %s but no subscriber was found.", event
167                        )
168            except WebSocketDisconnect:
169                if self.logger:
170                    self.logger.info("Websocket disconnected")
171            except Exception:
172                if self.logger:
173                    self.logger.exception("Error while handling connection")
174            finally:
175                try:
176                    if self.state:
177                        await self.state.on_disconnect()
178                except Exception:
179                    if self.logger:
180                        self.logger.exception("Error while calling state.on_disconnect")
181                with suppress(Exception):
182                    ws = self.ws
183                    self.ws = None
184                    if ws is not None:
185                        await ws.close()
186
187    # ===== High-Level: Context Manager =====#
188    def __enter__(self) -> Self:
189        token = session_context.set(self)
190        self._tokens.append(token)
191        return self
192
193    def __exit__(
194        self,
195        exc_type: type[BaseException] | None,
196        exc_value: BaseException | None,
197        traceback: object,
198    ):
199        if self._tokens:
200            token = self._tokens.pop()
201            session_context.reset(token)

A session is a persistent connection with the other.

This is a counter-part to the SessionManager in the frontend. There should be one instance of this class per user session, even across reconnects of the websocket. This means the states that belong to the user session should be subscribed to the events of this class. It defines a simple state-syncing protocol between the frontend and the backend, every event being of type {type: str, data: any}.

Session(logger: logging.Logger | None = <Logger ws_sync.session (WARNING)>)
32    def __init__(self, logger: Logger | None = logger):
33        self.ws = None
34        self.ws_lock = Lock()  # when multiple clients try to connect at the same time, we need to ensure that only one connection is established
35        self.event_handlers: dict[str, Callable[..., Any]] = {}  # triggered on event
36        self.init_handlers: list[
37            Callable[..., Any]
38        ] = []  # triggered on connection init
39        self.logger = logger
40        self.state: SessionState | None = None
41        """user-assigned state associated with the session"""
42        self._tokens: list[Token[Session]] = []
ws
ws_lock
event_handlers: dict[str, Callable[..., typing.Any]]
init_handlers: list[Callable[..., typing.Any]]
logger
state: SessionState | None

user-assigned state associated with the session

is_connected: bool
44    @property
45    def is_connected(self) -> bool:
46        return self.ws is not None
def register_event(self, event: str, callback: Callable[..., typing.Any]):
49    def register_event(self, event: str, callback: Callable[..., Any]):
50        if event in self.event_handlers and self.logger:
51            self.logger.warning("Event %s already has a subscriber.", event)
52        self.event_handlers[event] = callback
def deregister_event(self, event: str):
54    def deregister_event(self, event: str):
55        if event not in self.event_handlers:
56            if self.logger:
57                self.logger.warning("Event %s has no subscriber.", event)
58            return
59        del self.event_handlers[event]
def register_init(self, callback: Callable[..., typing.Any]):
61    def register_init(self, callback: Callable[..., Any]):
62        self.init_handlers.append(callback)
async def new_connection(self, ws: starlette.websockets.WebSocket):
65    async def new_connection(self, ws: WebSocket):
66        """
67        Set the new ws connection while possibly gracefully disconnecting the old one.
68        """
69        async with self.ws_lock:
70            if self.ws is not None:
71                if self.logger:
72                    self.logger.warning(
73                        "Overwriting existing websocket %s with %s",
74                        self.ws.client,
75                        ws.client,
76                    )
77                await self.disconnect()
78            self.ws = ws
79
80        if self.ws.application_state == WebSocketState.CONNECTING:
81            await self.ws.accept()
82
83        await self.init()

Set the new ws connection while possibly gracefully disconnecting the old one.

async def disconnect( self, message: str = "Seems like you're logged in somewhere else. If this is a mistake, please refresh the page.", ws: starlette.websockets.WebSocket | None = None):
 85    async def disconnect(
 86        self,
 87        message: str = "Seems like you're logged in somewhere else. If this is a mistake, please refresh the page.",
 88        ws: WebSocket | None = None,
 89    ):
 90        """
 91        Disconnect the websocket connection after sending a message.
 92        """
 93        # TODO: not sure why I made the ws argument, but I will keep it for now.
 94        if ws:
 95            self.ws = ws
 96        if self.ws is None:
 97            return
 98        await self.send("_DISCONNECT", message)
 99        assert self.ws is not None
100        with suppress(Exception):
101            await self.ws.close()
102        self.ws = None

Disconnect the websocket connection after sending a message.

async def init(self):
104    async def init(self):
105        for handler in self.init_handlers:
106            await nonblock_call(handler)
async def send(self, event: str, data: Any):
108    async def send(self, event: str, data: Any):
109        if self.ws is None:
110            return
111        try:
112            await self.ws.send_json({"type": event, "data": data})
113        except Exception:
114            if self.logger:
115                self.logger.exception("Error sending event %s", event)
async def send_binary(self, event: str, metadata: dict[str, typing.Any], data: bytes):
117    async def send_binary(self, event: str, metadata: dict[str, Any], data: bytes):
118        if self.ws is None:
119            return
120        try:
121            await self.ws.send_json(
122                {"type": "_BIN_META", "data": {"type": event, "metadata": metadata}}
123            )
124            await self.ws.send_bytes(data)
125        except Exception:
126            if self.logger:
127                self.logger.exception("Error sending binary event %s", event)
async def handle_connection(self, ws: starlette.websockets.WebSocket | None = None):
129    async def handle_connection(self, ws: WebSocket | None = None):
130        """
131        Handler that blocks until the websocket is disconnected. It takes care of accepting the websocket connection, and dispatching events to the appropriate handlers. If the ws argument is provided, it will be used as the websocket connection, otherwise it will use the existing connection.
132
133        Args:
134            ws: The websocket connection to use. If None, it will use the existing connection.
135        """
136        if ws:
137            await self.new_connection(ws)
138
139        assert self.ws is not None
140
141        with self:  # provide the session context
142            try:
143                if self.state:
144                    await self.state.on_connect()
145            except Exception:
146                if self.logger:
147                    self.logger.exception("Error while calling state.on_connect")
148
149            try:
150                while self.ws.application_state == WebSocketState.CONNECTED:
151                    full_data = await self.ws.receive_json()
152                    event = full_data.get("type")
153                    data = full_data.get("data")
154
155                    if event == "_BIN_META":
156                        # unwrap and construct the original event
157                        event = data.get("type")
158                        metadata = data.get("metadata")
159                        bindata = await self.ws.receive_bytes()
160                        data = {"data": bindata, **metadata}
161
162                    if handler := self.event_handlers.get(event):
163                        await nonblock_call(handler, data)
164                    elif self.logger:
165                        self.logger.warning(
166                            "Received event %s but no subscriber was found.", event
167                        )
168            except WebSocketDisconnect:
169                if self.logger:
170                    self.logger.info("Websocket disconnected")
171            except Exception:
172                if self.logger:
173                    self.logger.exception("Error while handling connection")
174            finally:
175                try:
176                    if self.state:
177                        await self.state.on_disconnect()
178                except Exception:
179                    if self.logger:
180                        self.logger.exception("Error while calling state.on_disconnect")
181                with suppress(Exception):
182                    ws = self.ws
183                    self.ws = None
184                    if ws is not None:
185                        await ws.close()

Handler that blocks until the websocket is disconnected. It takes care of accepting the websocket connection, and dispatching events to the appropriate handlers. If the ws argument is provided, it will be used as the websocket connection, otherwise it will use the existing connection.

Arguments:
  • ws: The websocket connection to use. If None, it will use the existing connection.
class SessionState:
204class SessionState:
205    """
206    Abstract base class for user-defined session state objects that can be associated with a Session object.
207    """
208
209    async def on_connect(self):
210        """Called after the websocket connection is established."""
211
212    async def on_disconnect(self):
213        """Called after the websocket connection is closed."""
214
215    async def on_terminate(self):
216        """Called when the session is forcefully terminated by the server."""

Abstract base class for user-defined session state objects that can be associated with a Session object.

async def on_connect(self):
209    async def on_connect(self):
210        """Called after the websocket connection is established."""

Called after the websocket connection is established.

async def on_disconnect(self):
212    async def on_disconnect(self):
213        """Called after the websocket connection is closed."""

Called after the websocket connection is closed.

async def on_terminate(self):
215    async def on_terminate(self):
216        """Called when the session is forcefully terminated by the server."""

Called when the session is forcefully terminated by the server.