Skip to main content

tauri_plugin_centrifugo/
models.rs

1//! # Data Models
2//!
3//! This module contains all the data structures used for communication between
4//! the frontend and the Centrifugo plugin, as well as internal data handling.
5//!
6//! ## Overview
7//!
8//! The models are designed to work with Tauri's serialization system and provide
9//! type-safe communication between Rust backend and JavaScript frontend.
10//!
11//! ## Serialization
12//!
13//! All models use `serde` with `camelCase` naming convention to match JavaScript
14//! conventions while maintaining Rust naming standards.
15
16use serde::{Deserialize, Serialize};
17
18#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, Default)]
19#[serde(rename_all = "camelCase")]
20pub enum DataEncoding {
21    #[default]
22    Base64,
23    RawJson,
24}
25
26/// Configuration for establishing a connection to Centrifugo server
27///
28/// This struct contains all the necessary parameters to establish and configure
29/// a WebSocket connection to a Centrifugo server.
30///
31/// # Example
32///
33/// ```rust
34/// use tauri_plugin_centrifugo::models::StartConfig;
35///
36/// let config = StartConfig {
37///     url: "ws://localhost:8000/connection/websocket".to_string(),
38///     token: Some("jwt-token".to_string()),
39///     name: Some("my-client".to_string()),
40///     version: Some("1.0.0".to_string()),
41///     channels: vec!["news".to_string(), "updates".to_string()],
42///     use_protobuf: false,
43///     read_timeout: Some(5000),
44///     http_stream_url: None,
45///     headers: None,
46///     request_token: None,
47/// };
48/// ```
49#[derive(Debug, Deserialize, Serialize, Clone)]
50#[serde(rename_all = "camelCase")]
51pub struct StartConfig {
52    /// WebSocket URL for the Centrifugo server
53    pub url: String,
54    /// Optional JWT authentication token
55    pub token: Option<String>,
56    /// Optional client name identifier
57    pub name: Option<String>,
58    /// Optional client version string
59    pub version: Option<String>,
60    /// List of channels to subscribe to upon connection
61    pub channels: Vec<String>,
62    /// Whether to use Protobuf protocol instead of JSON
63    pub use_protobuf: bool,
64    /// Read timeout in milliseconds (optional)
65    pub read_timeout: Option<u64>,
66    /// HTTP-streaming fallback endpoint (`.../connection/http_stream`), tried
67    /// together with `url` on the first connect
68    #[serde(default)]
69    pub http_stream_url: Option<String>,
70    /// Extra HTTP headers for the WebSocket upgrade / HTTP-stream requests
71    #[serde(default)]
72    pub headers: Option<std::collections::HashMap<String, String>>,
73    /// Ask the frontend for the connection token (`centrifugo:need_token`,
74    /// answered with `provide_token`) when `token` is not set. With `token`
75    /// set, `need_token` is sent anyway before the token expires.
76    #[serde(default)]
77    pub request_token: Option<bool>,
78}
79
80/// Configuration for individual channel subscription
81///
82/// Used when adding or configuring individual channels with specific settings.
83#[derive(Debug, Deserialize, Serialize, Clone)]
84#[serde(rename_all = "camelCase")]
85pub struct ChannelConfig {
86    /// Channel name
87    pub name: String,
88    /// Optional channel-specific token for authentication
89    pub token: Option<String>,
90}
91
92/// Extended subscription options for dynamic subscriptions.
93#[derive(Debug, Deserialize, Serialize, Clone)]
94#[serde(rename_all = "camelCase")]
95pub struct SubscribeOptions {
96    pub channel: String,
97    pub token: Option<String>,
98    pub recoverable: Option<bool>,
99    pub join_leave: Option<bool>,
100    pub positioned: Option<bool>,
101    /// Fossil delta compression (the server must allow it for the channel)
102    #[serde(default)]
103    pub delta: Option<bool>,
104    /// Resume from a saved position (from the `subscribed` event's `streamPosition`)
105    #[serde(default)]
106    pub since: Option<StreamPositionData>,
107}
108
109impl SubscribeOptions {
110    /// Options with defaults for the channel.
111    pub fn channel(channel: impl Into<String>) -> Self {
112        Self {
113            channel: channel.into(),
114            token: None,
115            recoverable: None,
116            join_leave: None,
117            positioned: None,
118            delta: None,
119            since: None,
120        }
121    }
122}
123
124/// Position in a channel stream.
125#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
126#[serde(rename_all = "camelCase")]
127pub struct StreamPositionData {
128    pub offset: u64,
129    pub epoch: String,
130}
131
132/// Request structure for publishing messages to channels
133///
134/// The `data` field should contain base64-encoded content that will be
135/// sent to the specified channel.
136#[derive(Debug, Deserialize, Serialize, Clone)]
137#[serde(rename_all = "camelCase")]
138pub struct PublishRequest {
139    /// Target channel name
140    pub channel: String,
141    /// Base64-encoded message data
142    pub data: String,
143    /// Optional encoding mode for `data` (default: base64)
144    pub data_encoding: Option<DataEncoding>,
145    /// Optional publish type: 0 = regular (default), 1 = map
146    pub r#type: Option<i32>,
147    /// Optional map key for map-style publish
148    pub key: Option<String>,
149    /// Optional remove flag for map-style publish
150    pub removed: Option<bool>,
151}
152
153/// Request structure for RPC method calls
154///
155/// Used to execute remote procedure calls on the Centrifugo server.
156#[derive(Debug, Deserialize, Serialize, Clone)]
157#[serde(rename_all = "camelCase")]
158pub struct RpcRequest {
159    /// RPC method name to execute
160    pub method: String,
161    /// Base64-encoded method parameters
162    pub data: String,
163    /// Optional encoding mode for `data` (default: base64)
164    pub data_encoding: Option<DataEncoding>,
165}
166
167/// Request structure for presence information
168///
169/// Used to get information about clients currently subscribed to a channel.
170#[derive(Debug, Deserialize, Serialize, Clone)]
171#[serde(rename_all = "camelCase")]
172pub struct PresenceRequest {
173    /// Channel name to get presence information for
174    pub channel: String,
175}
176
177/// Request structure for presence statistics
178///
179/// Used to get aggregated statistics about channel presence.
180#[derive(Debug, Deserialize, Serialize, Clone)]
181#[serde(rename_all = "camelCase")]
182pub struct PresenceStatsRequest {
183    /// Channel name to get statistics for
184    pub channel: String,
185}
186
187/// Request structure for message history
188///
189/// Used to retrieve historical messages from a channel with optional filtering.
190#[derive(Debug, Deserialize, Serialize, Clone)]
191#[serde(rename_all = "camelCase")]
192pub struct HistoryRequest {
193    /// Channel name to get history for
194    pub channel: String,
195    /// Maximum number of messages to retrieve
196    pub limit: Option<u32>,
197    /// Message ID to start from (for pagination)
198    pub since: Option<String>,
199    /// Whether to retrieve messages in reverse chronological order
200    pub reverse: Option<bool>,
201}
202
203/// Request structure for sending messages to server
204///
205/// Used to send messages directly to the server (not to specific channels).
206#[derive(Debug, Deserialize, Serialize, Clone)]
207#[serde(rename_all = "camelCase")]
208pub struct SendRequest {
209    /// Base64-encoded message data to send to server
210    pub data: String,
211    /// Optional encoding mode for `data` (default: base64)
212    pub data_encoding: Option<DataEncoding>,
213}
214
215/// Request structure for refreshing authentication tokens
216///
217/// Used to update the client's authentication token during an active session.
218#[derive(Debug, Deserialize, Serialize, Clone)]
219#[serde(rename_all = "camelCase")]
220pub struct RefreshRequest {
221    /// New JWT authentication token
222    pub token: String,
223}
224
225/// Request structure for refreshing subscription tokens
226///
227/// Used to update channel-specific subscription tokens.
228#[derive(Debug, Deserialize, Serialize, Clone)]
229#[serde(rename_all = "camelCase")]
230pub struct SubRefreshRequest {
231    /// Channel name for the subscription
232    pub channel: String,
233    /// New subscription token
234    pub token: String,
235    /// Optional tracked items with versions
236    pub items: Option<Vec<KeyedItem>>,
237    /// Optional list of keys to stop tracking
238    pub untrack_keys: Option<Vec<String>>,
239    /// Optional sub refresh type: 0=sub_refresh, 1=track, 2=untrack
240    pub r#type: Option<i32>,
241    /// Optional HMAC signature for track auth
242    pub signature: Option<String>,
243}
244
245/// Keyed item metadata for advanced sub refresh operations
246#[derive(Debug, Deserialize, Serialize, Clone)]
247#[serde(rename_all = "camelCase")]
248pub struct KeyedItem {
249    pub key: String,
250    pub version: u64,
251}
252
253/// Connection status information
254///
255/// Contains timestamp information about connection state changes.
256#[derive(Debug, Deserialize, Serialize, Clone)]
257#[serde(rename_all = "camelCase")]
258pub struct ConnectionStatus {
259    /// Unix timestamp of the status change
260    pub ts: i64,
261}
262
263/// Channel subscription status
264///
265/// Contains information about a specific channel subscription.
266#[derive(Debug, Deserialize, Serialize, Clone)]
267#[serde(rename_all = "camelCase")]
268pub struct ChannelStatus {
269    /// Channel name
270    pub channel: String,
271}
272
273/// Error information structure
274///
275/// Used to convey error details from the backend to the frontend.
276#[derive(Debug, Deserialize, Serialize, Clone)]
277#[serde(rename_all = "camelCase")]
278pub struct ErrorData {
279    /// Error message or description
280    pub error: String,
281}
282
283/// Publication data received from channels
284///
285/// Contains message data received from subscribed channels.
286#[derive(Debug, Deserialize, Serialize, Clone)]
287#[serde(rename_all = "camelCase")]
288pub struct PublicationData {
289    /// Source channel name
290    pub channel: String,
291    /// Base64-encoded message data
292    pub data: String,
293    /// Transport encoding for `data` field (always base64 for backward compatibility)
294    pub data_encoding: Option<DataEncoding>,
295    /// Optional decoded JSON representation when payload is valid JSON
296    pub raw_json: Option<serde_json::Value>,
297    /// Optional stream offset from Centrifugo publication
298    pub offset: Option<u64>,
299    /// Optional publisher info
300    pub info: Option<ClientInfoData>,
301    /// Optional publication tags
302    pub tags: Option<std::collections::HashMap<String, String>>,
303    /// Unix timestamp of the publication
304    pub timestamp: i64,
305}
306
307/// Publisher/client information attached to publications.
308#[derive(Debug, Deserialize, Serialize, Clone)]
309#[serde(rename_all = "camelCase")]
310pub struct ClientInfoData {
311    pub client: String,
312    pub user: String,
313    pub conn_info: String,
314    pub chan_info: String,
315}
316
317/// RPC response structure
318///
319/// Contains the result of an RPC method execution.
320#[derive(Debug, Deserialize, Serialize, Clone)]
321#[serde(rename_all = "camelCase")]
322pub struct RpcResponse {
323    /// RPC method name that was executed
324    pub method: String,
325    /// Base64-encoded response data
326    pub data: String,
327    /// Unix timestamp of the response
328    pub timestamp: i64,
329}
330
331/// Presence response structure
332///
333/// Contains information about clients present in a channel.
334#[derive(Debug, Deserialize, Serialize, Clone)]
335#[serde(rename_all = "camelCase")]
336pub struct PresenceResponse {
337    /// Channel name
338    pub channel: String,
339    /// List of client identifiers present in the channel
340    pub clients: Vec<String>,
341    /// Unix timestamp of the presence information
342    pub timestamp: i64,
343}
344
345/// Presence statistics response structure
346///
347/// Contains aggregated statistics about channel presence.
348#[derive(Debug, Deserialize, Serialize, Clone)]
349#[serde(rename_all = "camelCase")]
350pub struct PresenceStatsResponse {
351    /// Channel name
352    pub channel: String,
353    /// Number of clients in the channel
354    pub num_clients: u32,
355    /// Number of unique users in the channel
356    pub num_users: u32,
357    /// Unix timestamp of the statistics
358    pub timestamp: i64,
359}
360
361/// History response structure
362///
363/// Contains historical messages from a channel.
364#[derive(Debug, Deserialize, Serialize, Clone)]
365#[serde(rename_all = "camelCase")]
366pub struct HistoryResponse {
367    /// Channel name
368    pub channel: String,
369    /// List of historical publications
370    pub publications: Vec<PublicationData>,
371    /// Unix timestamp of the history retrieval
372    pub timestamp: i64,
373}
374
375/// Ping response structure
376///
377/// Contains server ping response information.
378#[derive(Debug, Deserialize, Serialize, Clone)]
379#[serde(rename_all = "camelCase")]
380pub struct PingResponse {
381    /// Unix timestamp of the ping response
382    pub timestamp: i64,
383}