lily/transport/websocket

WebSocket transport for real-time client-server communication. Provides automatic reconnection with exponential backoff and localStorage-backed offline message queueing.

The transport automatically reconnects using exponential backoff with configurable timing, persists messages in localStorage while disconnected, and flushes queued messages automatically when the connection restores

import lily/client
import lily/transport
import lily/transport/websocket

pub fn main() {
  let runtime = client.start(app_store)

  runtime
  |> client.connect(
    with: websocket.config(url: "ws://localhost:8080/ws")
      |> websocket.reconnect_base_milliseconds(1000)
      |> websocket.reconnect_max_milliseconds(30_000)
      |> websocket.connect,
    serialiser: transport.automatic(),
  )
}

WebSocket transport is JavaScript-only (@target(javascript)).

Types

Configuration for WebSocket connection. Use the builder functions to customise reconnection behaviour.

pub opaque type Config

Values

pub fn config(url url: String) -> Config

Create a new WebSocket configuration with the given URL. Default reconnect settings are 1000ms base delay and 30000ms maximum delay (exponential backoff).

pub fn connect(
  config: Config,
) -> fn(transport.Handler) -> transport.Transport

Returns a connector function that establishes a WebSocket connection. This connector can be passed to client.connect.

Example

client.connect(
  with: websocket.config(url: "ws://localhost:8080/ws")
    |> websocket.reconnect_base_milliseconds(2000)
    |> websocket.connect,
  serialiser: my_serialiser,
)
pub fn reconnect_base_milliseconds(
  config: Config,
  milliseconds: Int,
) -> Config

Set the base delay in milliseconds for reconnection attempts. The actual delay doubles on each failed attempt until reaching the maximum.

pub fn reconnect_max_milliseconds(
  config: Config,
  milliseconds: Int,
) -> Config

Set the maximum delay in milliseconds between reconnection attempts.

pub fn url_from_current_location(path path: String) -> String

Derive a WebSocket URL from the browser’s current location. Automatically uses wss: for HTTPS pages and ws: for HTTP. The path argument specifies the WebSocket endpoint path.

Example

// On https://example.com:3000/app
websocket.url_from_current_location("/ws")
// Returns "wss://example.com:3000/ws"
Search Document