### Start Store Source: https://y-crdt.github.io/pycrdt-websocket/reference/Store Starts the store, initializing its task group and setting the started event. It can raise a RuntimeError if the store is already running. ```APIDOC ## start(*, task_status=TASK_STATUS_IGNORED, from_context_manager=False) ### Description Start the store. ### Method POST ### Endpoint /start ### Parameters #### Path Parameters None #### Query Parameters - **task_status** (TaskStatus[None]) - Optional - The status to set when the task has started. Defaults to `TASK_STATUS_IGNORED`. - **from_context_manager** (bool) - Optional - Indicates if the start is from a context manager. Defaults to `False`. ### Request Example ```json { "task_status": "", "from_context_manager": false } ``` ### Response #### Success Response (200) - **None** - This method does not return any value upon successful start. #### Response Example ```json null ``` ``` -------------------------------- ### Start YStore Source: https://y-crdt.github.io/pycrdt-websocket/reference/Store Starts the SQLiteYStore, initializing the database and setting up task groups. Use this to begin store operations. ```python async def start( self, *, task_status: TaskStatus[None] = TASK_STATUS_IGNORED, from_context_manager: bool = False, ): """Start the SQLiteYStore. Arguments: task_status: The status to set when the task has started. """ self.db_initialized = Event() if from_context_manager: assert self._task_group is not None self._task_group.start_soon(self._init_db) task_status.started() self.started.set() return async with self._start_lock: if self._task_group is not None: raise RuntimeError("YStore already running") async with create_task_group() as self._task_group: self._task_group.start_soon(self._init_db) task_status.started() self.started.set() await self.stopped.wait() ``` -------------------------------- ### YStore Start Operation Source: https://y-crdt.github.io/pycrdt-websocket/reference/Store Starts the SQLiteYStore, initializing the database and setting up task groups for background operations. ```APIDOC ## start(*, task_status=TASK_STATUS_IGNORED, from_context_manager=False) async ### Description Start the SQLiteYStore. ### Parameters #### Path Parameters - **task_status** (TaskStatus[None]) - Optional - The status to set when the task has started. Default: `TASK_STATUS_IGNORED` - **from_context_manager** (bool) - Optional - Indicates if starting from a context manager. Default: `False` ### Source Code ```python async def start( self, *, task_status: TaskStatus[None] = TASK_STATUS_IGNORED, from_context_manager: bool = False, ): """Start the SQLiteYStore. Arguments: task_status: The status to set when the task has started. """ self.db_initialized = Event() if from_context_manager: assert self._task_group is not None self._task_group.start_soon(self._init_db) task_status.started() self.started.set() return async with self._start_lock: if self._task_group is not None: raise RuntimeError("YStore already running") async with create_task_group() as self._task_group: self._task_group.start_soon(self._init_db) task_status.started() self.started.set() await self.stopped.wait() ``` ``` -------------------------------- ### start Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_server Starts the WebSocket server, making it ready to accept incoming connections. This method can be used independently or as part of a context manager. ```APIDOC ## start ### Description Start the WebSocket server. ### Method POST ### Endpoint /server/start ### Parameters #### Query Parameters - **task_status** (TaskStatus[None]) - Optional - The status to set when the task has started. Defaults to `TASK_STATUS_IGNORED`. - **from_context_manager** (bool) - Optional - Indicates if called from a context manager. Defaults to `False`. ### Request Example ```json { "task_status": "started", "from_context_manager": false } ``` ### Response #### Success Response (200) - **status** (str) - Indicates the server has started. #### Response Example ```json { "status": "Server started successfully" } ``` ``` -------------------------------- ### Start SQLiteYStore Source: https://y-crdt.github.io/pycrdt-websocket/reference/Store Starts the SQLiteYStore, initializing the database and setting up background tasks. Handles context manager usage and ensures the store is not already running. ```python async def start( self, *, task_status: TaskStatus[None] = TASK_STATUS_IGNORED, from_context_manager: bool = False, ): """Start the SQLiteYStore. Arguments: task_status: The status to set when the task has started. """ self.db_initialized = Event() if from_context_manager: assert self._task_group is not None self._task_group.start_soon(self._init_db) task_status.started() self.started.set() return async with self._start_lock: if self._task_group is not None: raise RuntimeError("YStore already running") async with create_task_group() as self._task_group: self._task_group.start_soon(self._init_db) task_status.started() self.started.set() await self.stopped.wait() ``` -------------------------------- ### Start WebsocketProvider Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_provider Starts the WebSocket provider. This method can be called directly or is invoked when using the provider as an async context manager. It sets up the YDoc observer and starts the internal task group. ```python async def start( self, *, task_status: TaskStatus[None] = TASK_STATUS_IGNORED, from_context_manager: bool = False, ): """Start the WebSocket provider. Arguments: task_status: The status to set when the task has started. """ self._subscription = self._ydoc.observe(partial(put_updates, self._update_send_stream)) if from_context_manager: task_status.started() self.started.set() assert self._task_group is not None self._task_group.start_soon(self._run) return async with self._start_lock: if self._task_group is not None: raise RuntimeError("WebsocketProvider already running") async with create_task_group() as self._task_group: task_status.started() self.started.set() self._task_group.start_soon(self._run) ``` -------------------------------- ### Example Django urls.py with YjsConsumer Source: https://y-crdt.github.io/pycrdt-websocket/reference/Django_Channels_consumer A complete example of a urls.py file demonstrating how to include the YjsConsumer alongside other potential consumers. ```python # urls.py from django.urls import path from backend.consumer import DocConsumer, UpdateConsumer urlpatterns = [ path("ws/", YjsConsumer.as_asgi()), ] ``` -------------------------------- ### Build and Serve Documentation Source: https://y-crdt.github.io/pycrdt-websocket/contributing Builds the project documentation and starts a local development server. Access the documentation by navigating to http://127.0.0.1:8000 in your browser. ```bash mkdocs serve ``` -------------------------------- ### Start YRoom with Context Manager Source: https://y-crdt.github.io/pycrdt-websocket/reference/Room Starts the YRoom when used with a context manager. Sets the task status, signals that the room has started, and initializes streams and internal tasks. ```python async def start( self, *, task_status: TaskStatus[None] = TASK_STATUS_IGNORED, from_context_manager: bool = False, ): """Start the room. Arguments: task_status: The status to set when the task has started. """ if from_context_manager: task_status.started() self.started.set() self._update_send_stream, self._update_receive_stream = create_memory_object_stream( max_buffer_size=65536 ) assert self._task_group is not None self._task_group.start_soon(self._stopped.wait) self._task_group.start_soon(self._watch_ready) self._task_group.start_soon(self._broadcast_updates) self._task_group.start_soon(self.awareness.start) return ``` -------------------------------- ### Get or Create a Room Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_server Asynchronously retrieve a room by its name. If the room does not exist, it will be created and started. This ensures a room is ready for synchronization. ```python async def get_room(self, name: str) -> YRoom: """Get or create a room with the given name, and start it. Arguments: name: The room name. Returns: The room with the given name, or a new one if no room with that name was found. """ if name not in self.rooms.keys(): self.rooms[name] = YRoom(ready=self.rooms_ready, log=self.log) room = self.rooms[name] await self.start_room(room) return room ``` -------------------------------- ### Start WebsocketServer Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_server Starts the WebSocket server. Use this method when not using the context manager. It handles the server's lifecycle and ensures it runs until explicitly stopped. ```python async def start( *, task_status: TaskStatus[None] = TASK_STATUS_IGNORED, from_context_manager: bool = False, ): """Start the WebSocket server. Arguments: task_status: The status to set when the task has started. """ if from_context_manager: task_status.started() self.started.set() assert self._task_group is not None # wait until stopped self._task_group.start_soon(self._stopped.wait) return async with self._start_lock: if self._task_group is not None: raise RuntimeError("WebsocketServer already running") while True: try: async with create_task_group() as self._task_group: if not self.started.is_set(): task_status.started() self.started.set() # wait until stopped self._task_group.start_soon(self._stopped.wait) return except Exception as exception: self._handle_exception(exception) ``` -------------------------------- ### Start a Room in WebSocketServer Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_server Asynchronously starts a given YRoom if it has not already been started. This method requires the WebSocket server to be running. ```python async def start_room(self, room: YRoom) -> None: """Start a room, if not already started. Arguments: room: The room to start. """ if self._task_group is None: raise RuntimeError( "The WebsocketServer is not running: use `async with websocket_server:` or " "`await websocket_server.start()`" ) if not room.started.is_set(): await self._task_group.start(room.start) ``` -------------------------------- ### YRoom Initialization and Properties Source: https://y-crdt.github.io/pycrdt-websocket/reference/Room Details the initialization of the YRoom class, its constructor parameters, and its 'ready' and 'started' properties. ```APIDOC ## YRoom Properties ### `ready` property (writable) Returns: Type | Description ---|--- `bool` | True if the internal YDoc is ready to be synchronized. ### `started` property An async event that is set when the YRoom provider has started. ## `__init__` method Initialize the YRoom object. It is recommended to use YRoom as an async context manager. ### Method `__init__` ### Parameters #### Parameters - **ready** (bool) - Optional - Whether the internal YDoc is ready to be synchronized right away. Default: `True` - **ystore** (BaseYStore | None) - Optional - An optional store for persisting document updates. Default: `None` - **exception_handler** (Callable[[Exception, Logger], bool] | None) - Optional - A callback for handling exceptions. Default: `None` - **log** (Logger | None) - Optional - An optional logger. Default: `None` - **ydoc** (Doc | None) - Optional - An optional Yjs document. A new one is created if not provided. Default: `None` ### Request Example ```python async with room: ... ``` ### Alternative Lower-Level API Usage ```python task = asyncio.create_task(room.start()) await room.started.wait() ... await room.stop() ``` ``` -------------------------------- ### Start YRoom Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_server Starts a YRoom if it has not already been started. This method must be called when the WebSocket server is running. ```python async def start_room(self, room: YRoom) -> None: """Start a room, if not already started. Arguments: room: The room to start. """ if self._task_group is None: raise RuntimeError( "The WebsocketServer is not running: use `async with websocket_server:` or " "`await websocket_server.start()`" ) if not room.started.is_set(): await self._task_group.start(room.start) ``` -------------------------------- ### Start YRoom Source: https://y-crdt.github.io/pycrdt-websocket/reference/Room Starts the YRoom instance, initializing necessary streams and task groups. It handles task status and context manager usage. ```APIDOC ## POST /start ### Description Starts the YRoom instance, initializing necessary streams and task groups. It handles task status and context manager usage. ### Method POST ### Endpoint /start ### Parameters #### Query Parameters - **task_status** (TaskStatus[None]) - Optional - The status to set when the task has started. Defaults to TASK_STATUS_IGNORED. - **from_context_manager** (bool) - Optional - Indicates if the start is being called from a context manager. ### Request Example ```json { "task_status": "TASK_STATUS_IGNORED", "from_context_manager": false } ``` ### Response #### Success Response (200) - **None** - Indicates the room has started successfully. #### Response Example ```json null ``` ``` -------------------------------- ### Get or Create Room Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_server Retrieves an existing room by its name or creates a new one if it doesn't exist. The room is then started, ensuring it's ready for synchronization. ```APIDOC ## POST `/room/{name}` (or similar, implied by `get_room`) ### Description Gets a room by its name. If the room does not exist, it is created and started. ### Method `POST` or `GET` (implied by `get_room`) ### Endpoint `/room/{name}` (or similar, actual endpoint not specified, method is `get_room`) ### Parameters #### Path Parameters - **name** (str) - Required - The name of the room. #### Query Parameters None #### Request Body None ### Request Example ```python room = await websocket_server.get_room("my_document_room") ``` ### Response #### Success Response (200) - **YRoom** (YRoom) - The room object, either existing or newly created. #### Response Example ```json { "example": "YRoom object details" } ``` ``` -------------------------------- ### Initialize YRoom with Async Context Manager Source: https://y-crdt.github.io/pycrdt-websocket/reference/Room Use YRoom as an async context manager for preferred usage. This simplifies setup and teardown. ```python async with room: ... ``` -------------------------------- ### Install with pip Source: https://y-crdt.github.io/pycrdt-websocket/install Use this command to install pycrdt-websocket using pip. Ensure pip is up-to-date. ```bash pip install pycrdt-websocket ``` -------------------------------- ### WebsocketProvider Start Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_provider Starts the WebSocket provider. This method can be used independently or as part of the async context manager pattern. It sets up the necessary tasks for YDoc synchronization over the WebSocket. ```APIDOC ## start(*, task_status=TASK_STATUS_IGNORED, from_context_manager=False) ### Description Start the WebSocket provider. ### Method start ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ### Parameters - **task_status** (TaskStatus[None]) - Optional - The status to set when the task has started. Defaults to TASK_STATUS_IGNORED. - **from_context_manager** (bool) - Optional - Indicates if the start method is called from a context manager. Defaults to False. ``` -------------------------------- ### Start YStore with Task Group Source: https://y-crdt.github.io/pycrdt-websocket/reference/Store Starts the YStore, managing its background tasks. It uses a lock to prevent multiple starts and a task group to manage concurrent operations. The store will wait until the `stopped` event is set. ```python async def start( self, *, task_status: TaskStatus[None] = TASK_STATUS_IGNORED, from_context_manager: bool = False, ): """Start the store. Arguments: task_status: The status to set when the task has started. """ if from_context_manager: task_status.started() self.started.set() return async with self._start_lock: if self._task_group is not None: raise RuntimeError("YStore already running") async with create_task_group() as self._task_group: task_status.started() self.started.set() await self.stopped.wait() ``` -------------------------------- ### Start WebSocket Server Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_server Asynchronously starts the WebSocket server. It ensures that the server is not already running and manages the task group for server operations. If started via a context manager, it signals task completion immediately. Otherwise, it enters a loop to manage tasks until the server is stopped. ```python async def start( self, *, task_status: TaskStatus[None] = TASK_STATUS_IGNORED, from_context_manager: bool = False, ): """Start the WebSocket server. Arguments: task_status: The status to set when the task has started. """ if from_context_manager: task_status.started() self.started.set() assert self._task_group is not None # wait until stopped self._task_group.start_soon(self._stopped.wait) return async with self._start_lock: if self._task_group is not None: raise RuntimeError("WebsocketServer already running") while True: try: async with create_task_group() as self._task_group: if not self.started.is_set(): task_status.started() self.started.set() # wait until stopped self._task_group.start_soon(self._stopped.wait) return except Exception as exception: self._handle_exception(exception) ``` -------------------------------- ### start_room Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_server Starts a specific room if it has not already been started. This is typically called internally when a client connects to a room. ```APIDOC ## start_room ### Description Start a room, if not already started. ### Method POST ### Endpoint /rooms/{room_name}/start ### Parameters #### Path Parameters - **room** (YRoom) - Required - The room to start. ### Request Example ```json { "room_name": "my_room" } ``` ### Response #### Success Response (200) - **status** (str) - Indicates the room has started. #### Response Example ```json { "status": "Room started successfully" } ``` ``` -------------------------------- ### Start YRoom in a Loop Source: https://y-crdt.github.io/pycrdt-websocket/reference/Room Starts the YRoom in a loop, creating a task group and initializing streams and internal tasks. Handles exceptions by stopping awareness and re-handling the exception. ```python while True: try: async with create_task_group() as self._task_group: if not self.started.is_set(): task_status.started() self.started.set() self._update_send_stream, self._update_receive_stream = ( create_memory_object_stream(max_buffer_size=65536) ) self._task_group.start_soon(self._stopped.wait) self._task_group.start_soon(self._watch_ready) self._task_group.start_soon(self._broadcast_updates) self._task_group.start_soon(self.awareness.start) return except Exception as exception: await self.awareness.stop() self._handle_exception(exception) ``` -------------------------------- ### YRoom Started Event Source: https://y-crdt.github.io/pycrdt-websocket/reference/Room An async event that is set when the YRoom provider has started. It is lazily initialized. ```python @property def started(self): """An async event that is set when the YRoom provider has started.""" if self._started is None: self._started = Event() return self._started ``` -------------------------------- ### Start YRoom with Task Group Source: https://y-crdt.github.io/pycrdt-websocket/reference/Room Starts the YRoom, creating a task group to manage background tasks. Handles exceptions during startup and ensures the room is not already running. Use when initializing the room from scratch. ```python async def start( self, *, task_status: TaskStatus[None] = TASK_STATUS_IGNORED, from_context_manager: bool = False, ): """Start the room. Arguments: task_status: The status to set when the task has started. """ if from_context_manager: task_status.started() self.started.set() self._update_send_stream, self._update_receive_stream = create_memory_object_stream( max_buffer_size=65536 ) assert self._task_group is not None self._task_group.start_soon(self._stopped.wait) self._task_group.start_soon(self._watch_ready) self._task_group.start_soon(self._broadcast_updates) self._task_group.start_soon(self.awareness.start) return async with self._start_lock: if self._task_group is not None: raise RuntimeError("YRoom already running") while True: try: async with create_task_group() as self._task_group: if not self.started.is_set(): task_status.started() self.started.set() self._update_send_stream, self._update_receive_stream = ( create_memory_object_stream(max_buffer_size=65536) ) self._task_group.start_soon(self._stopped.wait) self._task_group.start_soon(self._watch_ready) self._task_group.start_soon(self._broadcast_updates) self._task_group.start_soon(self.awareness.start) return except Exception as exception: await self.awareness.stop() self._handle_exception(exception) ``` -------------------------------- ### WebsocketProvider Start Method Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_provider Starts the WebSocket provider by setting up the Ypy document observer and potentially signaling task status. This method is called internally when entering the async context. ```python async def start( self, *, task_status: TaskStatus[None] = TASK_STATUS_IGNORED, from_context_manager: bool = False, ): """Start the WebSocket provider. Arguments: task_status: The status to set when the task has started. """ self._subscription = self._ydoc.observe(partial(put_updates, self._update_send_stream)) if from_context_manager: task_status.started() self.started.set() assert self._task_group is not None ``` -------------------------------- ### WebsocketProvider Started Event Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_provider Provides an async event that is set once the WebSocket provider has successfully started its operations. ```python @property def started(self) -> Event: """An async event that is set when the WebSocket provider has started.""" if self._started is None: self._started = Event() return self._started ``` -------------------------------- ### Enter Pixi Shell Source: https://y-crdt.github.io/pycrdt-websocket/contributing Activates the pixi shell, providing access to the installed packages and environment. Commands run within this shell will use the pixi-managed installations. ```bash pixi shell ``` -------------------------------- ### Install with micromamba Source: https://y-crdt.github.io/pycrdt-websocket/install Use this command to install pycrdt-websocket from the conda-forge channel using micromamba. This is an alternative to pip. ```bash micromamba install -c conda-forge pycrdt-websocket ``` -------------------------------- ### Install NPM Test Dependencies Source: https://y-crdt.github.io/pycrdt-websocket/contributing Installs Node Package Manager (NPM) dependencies required for running integration tests. This command should be run from the 'tests/' directory. ```bash cd tests/ npm install cd .. ``` -------------------------------- ### Run Pycrdt-websocket Server with Hypercorn Source: https://y-crdt.github.io/pycrdt-websocket/usage/server This snippet shows how to initialize and run a Pycrdt-websocket server using Hypercorn. Ensure you have Hypercorn installed and configured for ASGI. ```python import asyncio from hypercorn import Config from hypercorn.asyncio import serve from pycrdt_websocket import ASGIServer, WebsocketServer websocket_server = WebsocketServer() app = ASGIServer(websocket_server) async def main(): websocket_server = WebsocketServer() app = ASGIServer(websocket_server) config = Config() config.bind = ["localhost:1234"] async with websocket_server: await serve(app, config, mode="asgi") asyncio.run(main()) ``` -------------------------------- ### Serve Client via WebSocket Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_server This asynchronous method serves a client connection through a given WebSocket. It retrieves the room based on the WebSocket path, starts the room if necessary, and then delegates room serving to the room itself. It also handles potential room cleanup if auto-clean is enabled and the room becomes empty. ```python async def serve(self, websocket: Websocket) -> None: """Serve a client through a WebSocket. Arguments: websocket: The WebSocket through which to serve the client. """ if self._task_group is None: raise RuntimeError( "The WebsocketServer is not running: use `async with websocket_server:` or " "`await websocket_server.start()`" ) try: async with create_task_group(): room = await self.get_room(websocket.path) await self.start_room(room) await room.serve(websocket) if self.auto_clean_rooms and not room.clients: await self.delete_room(room=room) except Exception as exception: self._handle_exception(exception) ``` -------------------------------- ### Install Project in Editable Mode Source: https://y-crdt.github.io/pycrdt-websocket/contributing Installs the pycrdt-websocket project in editable mode, including optional dependencies for testing and documentation. This allows for direct code changes to be reflected without reinstallation. ```bash pip install -e ".[test,docs]" ``` -------------------------------- ### WebsocketProvider Lifecycle Methods Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_provider Methods for starting, stopping, and managing the lifecycle of the WebSocket provider. ```APIDOC ## Lifecycle Methods ### `start(task_status: TaskStatus[None] = TASK_STATUS_IGNORED, *, from_context_manager: bool = False)` Starts the WebSocket provider. - Sets up the YDoc observer to capture updates. - If `from_context_manager` is True, it signals task completion and sets the `started` event. - Otherwise, it initiates the internal `_run` method and the `_send` task. Arguments: - `task_status` (TaskStatus[None]): Status to set when the task has started. - `from_context_manager` (bool): Flag indicating if started from an async context manager. ### `stop()` Stops the WebSocket provider. - Cleans up resources, including the YDoc observer and the task group. ### `__aenter__()` Enters the asynchronous context manager. - Ensures the provider is not already running. - Sets up a task group and starts the `start` method. ### `__aexit__(exc_type, exc_value, exc_tb)` Exits the asynchronous context manager. - Calls the `stop` method to clean up resources. ``` -------------------------------- ### Serve Client via WebSocket Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_server Serves a client connection through a given WebSocket. It handles room retrieval, starting the room, and the client's interaction within the room. If auto-cleaning is enabled and the room becomes empty, it attempts to delete the room. ```python async def serve(self, websocket: Websocket) -> None: """Serve a client through a WebSocket. Arguments: websocket: The WebSocket through which to serve the client. """ if self._task_group is None: raise RuntimeError( "The WebsocketServer is not running: use `async with websocket_server:` or " "`await websocket_server.start()`" ) try: async with create_task_group(): room = await self.get_room(websocket.path) await self.start_room(room) await room.serve(websocket) if self.auto_clean_rooms and not room.clients: await self.delete_room(room=room) except Exception as exception: self._handle_exception(exception) ``` -------------------------------- ### Add Pip and Node.js with Pixi Source: https://y-crdt.github.io/pycrdt-websocket/contributing Installs pip and nodejs into the pixi environment. These are essential for Python package management and JavaScript tooling, respectively. ```bash pixi add pip nodejs ``` -------------------------------- ### YRoom Asynchronous Context Manager Entry Source: https://y-crdt.github.io/pycrdt-websocket/reference/Room Enters the YRoom as an asynchronous context manager. Initializes the task group and starts the room's internal tasks. Raises a RuntimeError if the YRoom is already running. ```python async def __aenter__(self) -> YRoom: async with self._start_lock: if self._task_group is not None: raise RuntimeError("YRoom already running") async with AsyncExitStack() as exit_stack: self._task_group = await exit_stack.enter_async_context(create_task_group()) self._exit_stack = exit_stack.pop_all() await self._task_group.start(partial(self.start, from_context_manager=True)) return self ``` -------------------------------- ### Get or Create YRoom Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_server Retrieves a YRoom by name, creating it if it doesn't exist. Ensures the room is started before returning it. Requires the WebSocket server to be running. ```python async def get_room(self, name: str) -> YRoom: """Get or create a room with the given name, and start it. Arguments: name: The room name. Returns: The room with the given name, or a new one if no room with that name was found. """ if name not in self.rooms.keys(): self.rooms[name] = YRoom(ready=self.rooms_ready, log=self.log) room = self.rooms[name] await self.start_room(room) return room ``` -------------------------------- ### Initialize SQLiteYStore Source: https://y-crdt.github.io/pycrdt-websocket/reference/Store Initializes the SQLiteYStore, setting up the database path, metadata callback, and logger. It also prepares synchronization primitives. ```python def __init__( self, path: str, metadata_callback: Callable[[], Awaitable[bytes] | bytes] | None = None, log: Logger | None = None, ) -> None: """Initialize the object. Arguments: path: The file path used to store the updates. metadata_callback: An optional callback to call to get the metadata. log: An optional logger. """ self.path = path self.metadata_callback = metadata_callback self.log = log or getLogger(__name__) self.lock = Lock() self.db_initialized = None ``` -------------------------------- ### WebsocketServer Initialization and Usage Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_server Explains how to initialize and use the WebsocketServer, including context manager and manual start/stop methods. ```APIDOC ## WebsocketServer Initialization and Usage ### Description Provides methods for initializing and managing a WebSocket server for real-time data synchronization using YCrdt. ### Initialization ```python from pycrdt_websocket import WebsocketServer # Using as an async context manager (recommended) async with WebsocketServer() as server: # Server is running, clients can connect pass # Using manual start/stop websocket_server = WebsocketServer() server_task = asyncio.create_task(websocket_server.start()) await websocket_server.started.wait() # Wait until the server is ready # ... server is running ... await websocket_server.stop() # Stop the server ``` ### Parameters for `__init__` - **rooms_ready** (bool) - Optional - Whether rooms are ready to be synchronized when opened. Defaults to True. - **auto_clean_rooms** (bool) - Optional - Whether rooms should be deleted when no client is there anymore. Defaults to True. - **exception_handler** (Callable[[Exception, Logger], bool] | None) - Optional - A callback to handle exceptions raised during server operation. - **log** (Logger | None) - Optional - An optional logger instance. Defaults to a module-level logger. ``` -------------------------------- ### Initialize Pixi Environment Source: https://y-crdt.github.io/pycrdt-websocket/contributing Use this command to initialize a new project environment with pixi, a package manager. This sets up the necessary tools for development. ```bash pixi init ``` -------------------------------- ### WebsocketProvider Started Event Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_provider An asynchronous event that is set once the WebSocket provider has successfully started and is ready for operation. ```APIDOC ## started `property` ### Description An async event that is set when the WebSocket provider has started. ### Method None ### Endpoint None ### Parameters None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Initialize FileYStore Source: https://y-crdt.github.io/pycrdt-websocket/reference/Store Initializes FileYStore with a file path, optional metadata callback, and logger. Ensures the directory for the store path exists. ```python class FileYStore(BaseYStore): """A YStore which uses one file per document.""" path: str metadata_callback: Callable[[], Awaitable[bytes] | bytes] | None lock: Lock def __init__( self, path: str, metadata_callback: Callable[[], Awaitable[bytes] | bytes] | None = None, log: Logger | None = None, ) -> None: """Initialize the object. Arguments: path: The file path used to store the updates. metadata_callback: An optional callback to call to get the metadata. log: An optional logger. """ self.path = path self.metadata_callback = metadata_callback self.log = log or getLogger(__name__) self.lock = Lock() ``` -------------------------------- ### TempFileYStore __init__ method Source: https://y-crdt.github.io/pycrdt-websocket/reference/Store Initializes the TempFileYStore object, setting up the file path for storing updates and optionally accepting a metadata callback and a logger. ```APIDOC ## __init__(path: str, metadata_callback: Callable[[], Awaitable[bytes] | bytes] | None = None, log: Logger | None = None) ### Description Initialize the object. ### Method POST ### Endpoint /websites/y-crdt_github_io_pycrdt-websocket/ystore.py ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **path** (str) - Required - The file path used to store the updates. - **metadata_callback** (Callable[[], Awaitable[bytes] | bytes] | None) - Optional - An optional callback to call to get the metadata. - **log** (Logger | None) - Optional - An optional logger. ### Request Example ```json { "path": "/path/to/updates", "metadata_callback": "callback_function", "log": "logger_object" } ``` ### Response #### Success Response (200) - **None** - This method does not return any value. #### Response Example ```json null ``` ``` -------------------------------- ### WebsocketProvider Initialization and Usage Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_provider Details on how to initialize and use the WebsocketProvider, including context manager usage and manual start/stop operations. ```APIDOC ## WebsocketProvider ### Description Provides WebSocket connectivity for synchronizing YDoc objects. ### Initialization ```python WebsocketProvider(ydoc: Doc, websocket: Websocket, log: Logger | None = None) ``` Arguments: - `ydoc` (Doc): The YDoc to connect through the WebSocket. - `websocket` (Websocket): The WebSocket through which to connect the YDoc. - `log` (Logger | None): An optional logger. ### Usage as Async Context Manager ```python async with websocket_provider: # Code to run while the provider is active ... ``` ### Manual Lifecycle Management ```python # Start the provider task = asyncio.create_task(websocket_provider.start()) await websocket_provider.started.wait() # Wait until started # ... perform operations ... # Stop the provider await websocket_provider.stop() ``` ### Properties - `started` (Event): An async event that is set when the WebSocket provider has started. - `_start_lock` (Lock): Internal lock for managing the start operation. ``` -------------------------------- ### Initialize ASGIServer Source: https://y-crdt.github.io/pycrdt-websocket/reference/ASGI_server Initializes the ASGI server with a WebsocketServer instance and optional connection/disconnection callbacks. The on_connect callback can prevent a WebSocket from being accepted if it returns True. ```python def __init__( self, websocket_server: WebsocketServer, on_connect: Callable[[dict[str, Any], dict[str, Any]], Awaitable[bool] | bool] | None = None, on_disconnect: Callable[[dict[str, Any]], Awaitable[None] | None] | None = None, ): """Initialize the object. Arguments: websocket_server: An instance of WebsocketServer. on_connect: An optional callback to call when connecting the WebSocket. If the callback returns True, the WebSocket is not accepted. on_disconnect: An optional callback called when disconnecting the WebSocket. """ self._websocket_server = websocket_server self._on_connect = on_connect self._on_disconnect = on_disconnect ``` -------------------------------- ### YRoom Start Lock Source: https://y-crdt.github.io/pycrdt-websocket/reference/Room Provides a lock to ensure that the YRoom start process is not called concurrently. It is lazily initialized. ```python @property def _start_lock(self) -> Lock: if self.__start_lock is None: self.__start_lock = Lock() return self.__start_lock ``` -------------------------------- ### WebsocketProvider Start Lock Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_provider Ensures that the start operation is not called concurrently, preventing race conditions when initializing the provider. ```python @property def _start_lock(self) -> Lock: if self.__start_lock is None: self.__start_lock = Lock() return self.__start_lock ``` -------------------------------- ### YRoom Initialization Source: https://y-crdt.github.io/pycrdt-websocket/reference/Room Initializes a YRoom instance. Supports optional parameters for readiness, persistence, exception handling, logging, and pre-existing YDoc objects. The `ready` parameter controls immediate synchronization readiness. ```python def __init__( self, ready: bool = True, ystore: BaseYStore | None = None, exception_handler: Callable[[Exception, Logger], bool] | None = None, log: Logger | None = None, ydoc: Doc | None = None, ): """Initialize the object. The YRoom instance should preferably be used as an async context manager: ```py async with room: ... ``` However, a lower-level API can also be used: ```py task = asyncio.create_task(room.start()) await room.started.wait() ... await room.stop() ``` Arguments: ready: Whether the internal YDoc is ready to be synchronized right away. ystore: An optional store in which to persist document updates. exception_handler: An optional callback to call when an exception is raised, that returns True if the exception was handled. log: An optional logger. ydoc: An optional document for the room (a new one is created otherwise). """ self.ydoc = Doc() if ydoc is None else ydoc self.ready_event = Event() self.ready = ready self.ystore = ystore self.log = log or getLogger(__name__) self.awareness = Awareness(self.ydoc) self.awareness.observe(self.send_server_awareness) self.clients = set() self._on_message = None self.exception_handler = exception_handler self._stopped = Event() ``` -------------------------------- ### YStore Initialization Source: https://y-crdt.github.io/pycrdt-websocket/reference/Store Initializes the YStore database, creating necessary tables and indexes if they do not exist. ```APIDOC ## YStore Initialization ### Description Initializes the YStore database, creating the `yupdates` table and an index on `path` and `timestamp` if they don't already exist. It also sets the user version for the database. ### Method Internal Initialization (not directly exposed as an API endpoint) ### Endpoint N/A ### Parameters None ### Request Body None ### Response None ``` -------------------------------- ### ASGIServer Initialization Source: https://y-crdt.github.io/pycrdt-websocket/reference/ASGI_server Initializes the ASGIServer with a WebsocketServer instance and optional connection/disconnection callbacks. ```APIDOC ## `__init__(websocket_server, on_connect=None, on_disconnect=None)` ### Description Initialize the object. ### Parameters #### Path Parameters - **websocket_server** (WebsocketServer) - Required - An instance of WebsocketServer. - **on_connect** (Callable[[dict[str, Any], dict[str, Any]], Awaitable[bool] | bool] | None) - Optional - An optional callback to call when connecting the WebSocket. If the callback returns True, the WebSocket is not accepted. - **on_disconnect** (Callable[[dict[str, Any]], Awaitable[None] | None] | None) - Optional - An optional callback called when disconnecting the WebSocket. ### Source Code ```python def __init__( self, websocket_server: WebsocketServer, on_connect: Callable[[dict[str, Any], dict[str, Any]], Awaitable[bool] | bool] | None = None, on_disconnect: Callable[[dict[str, Any]], Awaitable[None] | None] | None = None, ): """Initialize the object. Arguments: websocket_server: An instance of WebsocketServer. on_connect: An optional callback to call when connecting the WebSocket. If the callback returns True, the WebSocket is not accepted. on_disconnect: An optional callback called when disconnecting the WebSocket. """ self._websocket_server = websocket_server self._on_connect = on_connect self._on_disconnect = on_disconnect ``` ``` -------------------------------- ### FileYStore Initialization Source: https://y-crdt.github.io/pycrdt-websocket/reference/Store Initializes the FileYStore with a specified path for storing document updates and an optional metadata callback. ```APIDOC ## FileYStore ### Description A YStore which uses one file per document. ### Method __init__ ### Parameters #### Path Parameters - **path** (str) - Required - The file path used to store the updates. - **metadata_callback** (Callable[[], Awaitable[bytes] | bytes] | None) - Optional - An optional callback to call to get the metadata. - **log** (Logger | None) - Optional - An optional logger. ``` -------------------------------- ### Initialize YStore Source: https://y-crdt.github.io/pycrdt-websocket/reference/Store Initializes the YStore with a file path for storing updates. Optionally accepts a metadata callback and a logger. ```python def __init__( self, path: str, metadata_callback: Callable[[], Awaitable[bytes] | bytes] | None = None, log: Logger | None = None, ) -> None: """Initialize the object. Arguments: path: The file path used to store the updates. metadata_callback: An optional callback to call to get the metadata. log: An optional logger. """ self.path = path self.metadata_callback = metadata_callback self.log = log or getLogger(__name__) self.lock = Lock() ``` -------------------------------- ### Initialize YStore Source: https://y-crdt.github.io/pycrdt-websocket/reference/Store Initializes the YStore with a file path for storing updates. Optionally accepts a metadata callback and a logger. ```python def __init__( self, path: str, metadata_callback: Callable[[], Awaitable[bytes] | bytes] | None = None, log: Logger | None = None, ) -> None: """Initialize the object. Arguments: path: The file path used to store the updates. metadata_callback: An optional callback to call to get the metadata. log: An optional logger. """ self.path = path self.metadata_callback = metadata_callback self.log = log or getLogger(__name__) self.lock = Lock() self.db_initialized = None ``` -------------------------------- ### Initialize WebsocketServer Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_server Initialize the WebsocketServer. It can be used as an async context manager or with lower-level start/stop APIs. Configure room synchronization and automatic room cleanup. ```python async with websocket_server: ... ``` ```python task = asyncio.create_task(websocket_server.start()) await websocket_server.started.wait() ... await websocket_server.stop() ``` ```python def __init__( self, rooms_ready: bool = True, auto_clean_rooms: bool = True, exception_handler: Callable[[Exception, Logger], bool] | None = None, log: Logger | None = None, ) -> None: """Initialize the object. The WebsocketServer instance should preferably be used as an async context manager: ```py async with websocket_server: ... ``` However, a lower-level API can also be used: ```py task = asyncio.create_task(websocket_server.start()) await websocket_server.started.wait() ... await websocket_server.stop() ``` Arguments: rooms_ready: Whether rooms are ready to be synchronized when opened. auto_clean_rooms: Whether rooms should be deleted when no client is there anymore. exception_handler: An optional callback to call when an exception is raised, that returns True if the exception was handled. log: An optional logger. """ self.rooms_ready = rooms_ready self.auto_clean_rooms = auto_clean_rooms self.exception_handler = exception_handler self.log = log or getLogger(__name__) self.rooms = {} self._stopped = Event() ``` -------------------------------- ### WebsocketServer Initialization Source: https://y-crdt.github.io/pycrdt-websocket/reference/WebSocket_server Initializes the WebsocketServer. It can be used as an async context manager or via lower-level start/stop methods. Configuration options include room readiness, automatic room cleanup, and custom exception handling. ```APIDOC ## WebsocketServer `__init__` ### Description Initializes the WebsocketServer object with configurable options for room synchronization, automatic cleanup, and exception handling. ### Method `__init__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **rooms_ready** (bool) - Optional - Whether rooms are ready to be synchronized when opened. Default: `True` - **auto_clean_rooms** (bool) - Optional - Whether rooms should be deleted when no client is there anymore. Default: `True` - **exception_handler** (Callable[[Exception, Logger], bool] | None) - Optional - An optional callback to call when an exception is raised, that returns True if the exception was handled. Default: `None` - **log** (Logger | None) - Optional - An optional logger. Default: `None` ### Request Example ```python # Using as an async context manager async with websocket_server: ... # Using lower-level API task = asyncio.create_task(websocket_server.start()) await websocket_server.started.wait() ... await websocket_server.stop() ``` ### Response None (This is a constructor) ```