Rust Core Implementation
Relevant source files
The following files were used as context for generating this wiki page:
The Rust core of the tauri-plugin-centrifugo provides a high-performance, asynchronous bridge between a Tauri application and a Centrifugo server. Built upon the tokio-centrifuge crate, it manages WebSocket connections, authentication, and channel-based pub/sub logic within a dedicated Tokio runtime to ensure non-blocking operation on the main UI thread.
Sources: src/lib.rs:1-30, src/core.rs:1-30
Plugin Architecture and Initialization
The plugin follows the standard Tauri 2.0 pattern by exposing an init function that registers command handlers and initializes the global state. The core state is managed by the Centrifugo struct, which is injected into the Tauri application state using app.manage().
Initialization Flow
- Plugin Builder: The plugin is named
centrifugo. - Command Registration: Commands from
src/commands.rsare registered to handle frontend requests. - State Setup: A new instance of
core::Centrifugois created and managed by the TauriManager.
Sources: src/lib.rs:60-95
Sources: src/lib.rs:88-93, src/core.rs:77-85
Core State Management
The Centrifugo struct is the central coordinator for all real-time operations. It manages thread-safe access to the underlying tokio-centrifuge client and tracks active subscriptions.
Component Structure
| Component | Type | Description |
|---|---|---|
runtime | Arc<TokioRuntime> | Dedicated asynchronous runtime for network operations. |
client | Arc<Mutex<Option<Client>>> | Thread-safe storage for the active Centrifugo WebSocket client. |
client_task | Arc<Mutex<Option<JoinHandle<()>>>> | Handle to the background task managing the connection lifecycle. |
subscriptions | Arc<Mutex<HashMap<String, bool>>> | Local cache of active channel subscriptions. |
Sources: src/core.rs:61-66
Thread Safety and Concurrency
To allow concurrent access from multiple Tauri commands, the client and subscription map are wrapped in Arc<Mutex<...>>. This ensures that even if multiple frontend components attempt to publish or subscribe simultaneously, the internal state remains consistent.
Sources: src/core.rs:44-55
Connection Lifecycle
Establishing a connection involves spawning a background task within the plugin's dedicated runtime. This task handles the protocol negotiation (JSON or Protobuf) and sets up event listeners for state changes.
Connection Process
The connect command triggers Centrifugo::connect, which performs the following:
- Abort Previous: Any existing connection task is aborted to prevent leaks.
- Protocol Selection: Appends
?format=protobufto the URL if Protobuf is enabled inStartConfig. - Callback Binding: Attaches Rust closures to the client’s lifecycle events (Connecting, Connected, Disconnected, Error).
- Event Emission: Uses Tauri's
Emitterto broadcast these states to the frontend.
Sources: src/core.rs:104-142
Sources: src/commands.rs:36-41, src/core.rs:143-160
Data Models and Serialization
The plugin uses highly structured data models defined in src/models.rs. All structures implement serde::Serialize and serde::Deserialize with camelCase renaming to match JavaScript conventions.
Key Data Structures
| Model | Purpose | Fields |
|---|---|---|
StartConfig | Connection params | url, token, channels, useProtobuf, readTimeout |
PublishRequest | Sending data | channel, data (Base64) |
PublicationData | Receiving data | channel, data (Base64), timestamp |
RpcRequest | Server RPC | method, data (Base64) |
Sources: src/models.rs:33-55, src/models.rs:75-84, src/models.rs:172-181
Messaging and RPC Operations
The core implementation handles data as binary buffers, requiring the frontend to send data as Base64 strings. The Rust backend decodes these before transmission to the Centrifugo server.
Message Publication
When a message is published, the core validates the connection state. If the client is in the Connected state, the Base64 data is decoded using the base64 crate and sent via client.publish.
Sources: src/core.rs:307-331
Event Emission Flow
The core maps tokio-centrifuge events to Tauri events with a centrifugo: prefix:
centrifugo:publication: Triggered when a message is received on a subscribed channel.centrifugo:subscribed/centrifugo:unsubscribed: Triggered on channel status changes.
Sources: src/core.rs:195-218
Sources: src/core.rs:219-227
Command Implementation Matrix
The src/commands.rs file acts as the interface layer. While many methods are fully implemented, some advanced Centrifugo features are currently placeholders in the core implementation.
| Command | Status | Description |
|---|---|---|
connect | ✅ Full | Establishes WebSocket connection and initial subscriptions. |
publish | ✅ Full | Broadcasts Base64 data to a specific channel. |
rpc | ✅ Full | Executes a Remote Procedure Call. |
add_subscription | ✅ Full | Subscribes to a new channel at runtime. |
presence | ❌ N/I | Not implemented in tokio-centrifuge layer. |
history | ❌ N/I | Not implemented in tokio-centrifuge layer. |
ping | ❌ N/I | Not implemented in tokio-centrifuge layer. |
Sources: src/commands.rs:11-255, src/core.rs:434-480
Summary
The Rust core implementation of the Centrifugo plugin provides a robust foundation for real-time features by leveraging Rust's safety and asynchronous capabilities. By encapsulating the tokio-centrifuge client within a managed state and exposing it through Tauri commands, the plugin enables seamless integration of Centrifugo's pub/sub and RPC features into cross-platform desktop and mobile applications.
Sources: src/lib.rs:1-40, src/core.rs:1-50