duck.html.components.core.websocket

Lively Component System WebSocket implementation.

Module Contents

Classes

EventHandler

Event handler for incoming WebSocket messages.

LivelyWebSocketView

WebSocket view for handling communication between server-side HTML components and client-side via virtual DOM patching and JavaScript execution.

Functions

generate_uid

Generate a short unique ID for tracking JS execution results.

API

class duck.html.components.core.websocket.EventHandler(ws_view: duck.html.components.core.websocket.LivelyWebSocketView)[source]

Event handler for incoming WebSocket messages.

Initialization

__slots__

(‘ws_view’, ‘event_map’, ‘browser_state_sync_lock’)

build_navigation_request(root_request, fullpath: str, headers: Dict[str, str]) duck.http.request.HttpRequest[source]

Builds a navigation request object for obtaining the next ASGI response.

Parameters:
  • root_request – The request passed to the component, mostly Page.request for page components.

  • fullpath – The full path the user is navigating to.

  • headers – The current client headers - may include cookies set using JS.

Returns:

The constructed request for retrieving the next response.

Return type:

HttpRequest

async dispatch(opcode: duck.html.components.core.opcodes.EventOpCode, data: List[Any])[source]

Handle incoming WebSocket events.

async dispatch_component_event(data: List[Any])[source]

Dispatch a component event e.g. Button click, then send patches to client on changes the button click event made on the component tree.

async ensure_browser_state_synced(root_request: duck.http.request.HttpRequest)[source]

This ensures that the curent state is synced with the browser. It’s responsible for telling the browser that it needs to do JS fetch() to certain URL so that sensitive data like HTTPONLY cookies are synced to the browser.

… admonition:: Notes

This also syncs the root request state from the middlewares e.g. updating request cookies, X- headers (if applicable)

async handle_js_execution_result(data: List[Any])[source]

Process a JavaScript execution result.

async handle_navigation(data: List[Any])[source]

Handle a navigation request from the client.

class duck.html.components.core.websocket.LivelyWebSocketView(request, **kwargs)[source]

Bases: duck.contrib.websockets.WebSocketView

WebSocket view for handling communication between server-side HTML components and client-side via virtual DOM patching and JavaScript execution.

Initialization

Initialize the WebSocketView with the initial HTTP upgrade request.

Parameters:
  • upgrade_request – The HTTP request that initiated the WebSocket upgrade.

  • **kwargs – Additional keyword arguments passed to subclasses.

Initializes internal state for compression, heartbeat, fragmentation, and communication queues.

RECEIVE_TIMEOUT

240

__slots__

(‘request’, ‘execution_futures’, ‘event_handler’)

async execute_js(code: str, timeout: Union[int, float] = None, wait_for_result: bool = False) Optional[Any][source]

Sends JavaScript code to the client for execution over WebSocket, optionally awaiting the result.

Parameters:
  • code – The JavaScript code to execute on the client.

  • timeout – Maximum time (in seconds) to wait for a result.

  • wait_for_result – Whether to wait for the feedback that the JS code has been executed.

Returns:

The result returned by the client if wait_for_result is True, otherwise None.

Return type:

Optional[Any]

Raises:
  • JavascriptExecutionError – If the future is cancelled, usually due to WebSocket disconnection or the client raised an exception.

  • JavascriptExecutionTimedOut – If the result was not received within the specified timeout.

  • ValueError – If user specified a timeout yet wait_for_result is set to False.

async get_js_result(code: str, variable: str, timeout: Union[int, float, None] = None) Any[source]

Executes JavaScript on the client and retrieves the value of a specific variable.

This is useful when the server needs to fetch a value or result produced by JS code after execution.

Parameters:
  • code – JavaScript code to execute.

  • variable – The name of the variable whose value should be returned after execution.

  • timeout – Maximum time (in seconds) to wait for the variable’s value.

Returns:

The value of the specified variable returned from the client.

Return type:

Any

Raises:
async on_close(frame)[source]

On close event.

async on_open()[source]

On open event.

async on_receive(data: bytes, opcode: int)[source]

Handles incoming WebSocket data.

Parameters:
  • data – Message data.

  • opcode – WebSocket frame opcode.

async send_data(data: Any)[source]

Sends serialized data over the WebSocket.

async send_patches(patches: List)[source]

Sends virtual DOM patch instructions to the client.

Parameters:

patches – A list of patch operations.

static serialize_data(data: Any) bytes[source]

Serializes data using MessagePack.

static unserialize_data(data: bytes) Any[source]

Deserializes MessagePack-encoded binary data.

async update_now(component, updates: List[str])[source]

Sync current updates to the client immediately.

… admonition:: Notes

This uses ForceUpdate logic.

duck.html.components.core.websocket.generate_uid(length: int = 6) str[source]

Generate a short unique ID for tracking JS execution results.