WebSockets and Real-time Communication
Relevant source files
The following files were used as context for generating this wiki page:
Budibase utilizes WebSockets to enable real-time, bidirectional communication between the client (browser) and the server. This system is crucial for features that require instant updates and collaboration, such as live editing of data in grids. The implementation is split between server-side logic for handling connections and events, and a client-side module for establishing and managing the connection.
The core of the WebSocket architecture involves a central server-side handler that authenticates connections, manages client subscriptions to specific "rooms" (typically based on an application ID), and routes incoming messages to specialized handlers. Shared data structures are defined in @budibase/types to ensure type safety and consistency in communication protocols between the server and client.
System Architecture
The WebSocket system is integrated into the main Koa.js server. It listens for upgrade requests on the same port, establishing a persistent connection with authenticated clients. Clients are organized into rooms to ensure that broadcasts are scoped to the relevant application context.
Sources: packages/server/src/websockets/index.ts, packages/server/src/app.ts
High-Level Flow
The following diagram illustrates the high-level architecture of the WebSocket system, from client connection to event handling.
This diagram shows the client connecting to the Koa server, which upgrades the connection to a WebSocket. The server then authenticates the client, adds them to a room, and routes events to specific handlers like the grid handler.
Sources: packages/server/src/websockets/index.ts, packages/client/src/websocket.js, packages/server/src/websockets/grid.ts
Server-Side Implementation
The server-side WebSocket logic resides primarily in the packages/server/src/websockets/ directory.
Sources: packages/server/src/websockets/index.ts
Initialization
The WebSocket server is initialized by the main application server. The init function, exported from packages/server/src/websockets/index.ts, creates a new ws server instance and attaches it to the main HTTP server. It also sets up the primary connection listener.
// Example from packages/server/src/app.ts
import { websockets } from "./websockets"
// ... server setup ...
const server = http.createServer(app.callback())
websockets.init(server) // Attaches the WebSocket server
Sources: packages/server/src/app.ts, packages/server/src/websockets/index.ts
Connection and Authentication Flow
When a client attempts to connect, the server performs several steps to authenticate and prepare the session.
- Connection: A new WebSocket connection is established.
- Authentication: The server inspects the connection request, likely using the Koa session context, to identify the user and their permissions. Unauthenticated connections are terminated.
- Room Joining: Upon successful authentication, the client is added to a room specific to their current
appId. This isolates communication to within a single Budibase application. - Event Listening: The server begins listening for
messageevents from the client.
The diagram below shows the sequence of events during a client connection.
Event Handling and Routing
Incoming messages are parsed and routed based on an event property in the payload. A central switch statement or a map in index.ts directs the message to the appropriate handler function. For example, events prefixed with grid: are passed to the handler defined in grid.ts.
Sources: packages/server/src/websockets/index.ts, packages/server/src/websockets/grid.ts
Grid Collaboration Events
A specific use case for WebSockets is real-time collaboration on data grids. The packages/server/src/websockets/grid.ts file defines handlers for grid-specific events. These events are then broadcast to all other clients in the same application room, excluding the original sender.
| Event Name | Description |
|---|---|
grid:edit:start | A user has started editing a cell. The server broadcasts this to lock the cell for other users. |
grid:edit:update | A user is actively making changes to a cell. The server broadcasts the partial updates. |
grid:edit:finish | A user has finished editing a cell. The server broadcasts this to unlock the cell and show the final value. |
Sources: packages/server/src/websockets/grid.ts
Client-Side Implementation
The client-side logic is handled by a singleton wrapper found in packages/client/src/websocket.js. This module provides a simple API for the rest of the frontend application to interact with the WebSocket server.
Sources: packages/client/src/websocket.js
API and Usage
The client module exposes several key functions:
connect(appId): Establishes a connection to the WebSocket server for a given application ID.disconnect(): Closes the WebSocket connection.send(event, payload): Sends a message to the server with a specific event name and payload.on(event, callback): Registers a callback function to be executed when a specific event is received from the server.
This abstraction simplifies WebSocket usage throughout the client application, centralizing connection management and event handling.
Client-Side Event Flow
The following diagram shows how the client sends an event and processes a broadcasted event from another user.
Shared Data Structures
To maintain a consistent and reliable communication protocol, the client and server share a set of TypeScript types for WebSocket messages. These are defined in packages/types/src/sdk/websocket.ts.
WebsocketMessage Interface
All messages sent over the WebSocket connection adhere to a common structure.
| Property | Type | Description |
|---|---|---|
event | string | The name of the event, used for routing on the server and handling on the client (e.g., grid:edit:start). |
payload | any | The data associated with the event. |
appId | string | The ID of the application this message pertains to. |
sessionId | string | A unique identifier for the client's session. |
Sources: packages/types/src/sdk/websocket.ts
This standardized format is crucial for the routing and handling logic on both the client and server, preventing mismatches and ensuring that all necessary context is available to process messages.