sockudo-core 4.6.0

Core traits, types, error handling, and configuration for Sockudo
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use super::*;
use serde::{Deserialize, Serialize};
use std::str::FromStr;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct IdempotencyConfig {
    /// Whether idempotency key support is enabled
    pub enabled: bool,
    /// TTL in seconds for idempotency keys (default: 120s, like Ably's 2-minute window)
    pub ttl_seconds: u64,
    /// Maximum length of an idempotency key
    pub max_key_length: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct EphemeralConfig {
    /// Whether ephemeral message handling is enabled.
    pub enabled: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct EchoControlConfig {
    /// Whether connection-level and per-message echo control is enabled.
    pub enabled: bool,
    /// Default echo behavior for new V2 connections when the query param is omitted.
    pub default_echo_messages: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct EventNameFilteringConfig {
    /// Whether per-subscription event name filtering is enabled.
    pub enabled: bool,
    /// Maximum event names allowed in a single filter.
    pub max_events_per_filter: usize,
    /// Maximum length for each event name in a filter.
    pub max_event_name_length: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ConnectionRecoveryConfig {
    /// Whether connection recovery (resume) is enabled.
    /// When enabled, the server keeps a bounded replay buffer per channel so that
    /// reconnecting clients can receive missed messages. Disabled by default for
    /// Pusher protocol compatibility.
    pub enabled: bool,
    /// How long messages stay in the replay buffer (seconds). Default: 120 (2 min).
    pub buffer_ttl_seconds: u64,
    /// Maximum number of messages kept per channel. Default: 100.
    pub max_buffer_size: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum VersionStoreDriver {
    #[default]
    Memory,
    Postgres,
    Mysql,
    DynamoDb,
    ScyllaDb,
    SurrealDb,
}

impl FromStr for VersionStoreDriver {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "postgres" | "postgresql" | "pgsql" => Ok(Self::Postgres),
            "mysql" => Ok(Self::Mysql),
            "dynamodb" => Ok(Self::DynamoDb),
            "scylladb" | "scylla" => Ok(Self::ScyllaDb),
            "surrealdb" | "surreal" => Ok(Self::SurrealDb),
            "memory" => Ok(Self::Memory),
            _ => Err(format!("Unknown version store driver: {s}")),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct VersionedMessagesConfig {
    /// Whether V2 mutable message HTTP/retrieval surfaces are enabled.
    pub enabled: bool,
    /// Storage driver for versioned messages. Defaults to memory.
    pub driver: VersionStoreDriver,
    /// Maximum page size for version-history retrieval.
    pub max_page_size: usize,
    /// Retention window for version entries, in seconds. `0` disables expiry
    /// (entries are kept forever).
    ///
    /// Backends with native row TTL (ScyllaDB `USING TTL`, DynamoDB TTL
    /// attribute) apply this at the storage layer. Other backends (MySQL,
    /// PostgreSQL, SurrealDB, Memory) enforce it via a periodic background
    /// purge worker controlled by `purge_interval_seconds`.
    pub retention_window_seconds: u64,
    /// Interval between purge worker runs, in seconds. Only consulted for
    /// backends without native TTL. Clamped to a minimum of 10 seconds.
    pub purge_interval_seconds: u64,
    /// Maximum rows deleted per purge query. Bounds lock/transaction sizes
    /// for SQL backends. The worker loops until no more expired rows remain
    /// or `max_purge_per_tick` is reached.
    pub purge_batch_size: usize,
    /// Hard cap on rows deleted per purge tick across all loop iterations.
    /// Prevents a backlog of expired rows from monopolising a worker run.
    pub max_purge_per_tick: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct AnnotationsConfig {
    /// Whether Sockudo-native annotation APIs and realtime annotation protocol
    /// surfaces are enabled. Disabled by default while the feature is opt-in.
    pub enabled: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum HistoryBackend {
    #[default]
    Postgres,
    Mysql,
    DynamoDb,
    SurrealDb,
    ScyllaDb,
    Memory,
}

impl FromStr for HistoryBackend {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "postgres" | "postgresql" | "pgsql" => Ok(Self::Postgres),
            "mysql" => Ok(Self::Mysql),
            "dynamodb" => Ok(Self::DynamoDb),
            "surrealdb" | "surreal" => Ok(Self::SurrealDb),
            "scylladb" | "scylla" => Ok(Self::ScyllaDb),
            "memory" => Ok(Self::Memory),
            _ => Err(format!("Unknown history backend: {s}")),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct PostgresHistoryConfig {
    pub table_prefix: String,
    pub write_timeout_ms: u64,
}

impl Default for PostgresHistoryConfig {
    fn default() -> Self {
        Self {
            table_prefix: "sockudo_history".to_string(),
            write_timeout_ms: 5000,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct MySqlHistoryConfig {
    pub table_prefix: String,
    pub write_timeout_ms: u64,
}

impl Default for MySqlHistoryConfig {
    fn default() -> Self {
        Self {
            table_prefix: "sockudo_history".to_string(),
            write_timeout_ms: 5000,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct DynamoDbHistoryConfig {
    pub table_prefix: String,
    pub write_timeout_ms: u64,
}

impl Default for DynamoDbHistoryConfig {
    fn default() -> Self {
        Self {
            table_prefix: "sockudo_history".to_string(),
            write_timeout_ms: 5000,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SurrealDbHistoryConfig {
    pub table_prefix: String,
    pub write_timeout_ms: u64,
}

impl Default for SurrealDbHistoryConfig {
    fn default() -> Self {
        Self {
            table_prefix: "sockudo_history".to_string(),
            write_timeout_ms: 5000,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ScyllaDbHistoryConfig {
    pub table_prefix: String,
    pub write_timeout_ms: u64,
}

impl Default for ScyllaDbHistoryConfig {
    fn default() -> Self {
        Self {
            table_prefix: "sockudo_history".to_string(),
            write_timeout_ms: 5000,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct HistoryConfig {
    pub enabled: bool,
    pub rewind_enabled: bool,
    pub backend: HistoryBackend,
    pub retention_window_seconds: u64,
    pub max_page_size: usize,
    pub max_messages_per_channel: Option<usize>,
    pub max_bytes_per_channel: Option<u64>,
    pub writer_shards: usize,
    pub writer_queue_capacity: usize,
    pub purge_interval_seconds: u64,
    pub purge_batch_size: usize,
    pub max_purge_per_tick: usize,
    pub postgres: PostgresHistoryConfig,
    pub mysql: MySqlHistoryConfig,
    pub dynamodb: DynamoDbHistoryConfig,
    pub surrealdb: SurrealDbHistoryConfig,
    pub scylladb: ScyllaDbHistoryConfig,
}

impl Default for HistoryConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            rewind_enabled: true,
            backend: HistoryBackend::Postgres,
            retention_window_seconds: 86400,
            max_page_size: 100,
            max_messages_per_channel: None,
            max_bytes_per_channel: None,
            writer_shards: 16,
            writer_queue_capacity: 4096,
            purge_interval_seconds: 300,
            purge_batch_size: 1000,
            max_purge_per_tick: 100_000,
            postgres: PostgresHistoryConfig::default(),
            mysql: MySqlHistoryConfig::default(),
            dynamodb: DynamoDbHistoryConfig::default(),
            surrealdb: SurrealDbHistoryConfig::default(),
            scylladb: ScyllaDbHistoryConfig::default(),
        }
    }
}

impl Default for VersionedMessagesConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            driver: VersionStoreDriver::Memory,
            max_page_size: 100,
            retention_window_seconds: 0,
            purge_interval_seconds: 300,
            purge_batch_size: 1000,
            max_purge_per_tick: 100_000,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct PresenceHistoryConfig {
    pub enabled: bool,
    pub retention_window_seconds: u64,
    pub max_page_size: usize,
    pub max_events_per_channel: Option<usize>,
    pub max_bytes_per_channel: Option<u64>,
}

impl Default for PresenceHistoryConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            retention_window_seconds: 86400,
            max_page_size: 100,
            max_events_per_channel: None,
            max_bytes_per_channel: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct DeltaCompressionOptionsConfig {
    pub enabled: bool,
    pub algorithm: String,
    pub full_message_interval: u32,
    pub min_message_size: usize,
    pub max_state_age_secs: u64,
    pub max_channel_states_per_socket: usize,
    pub max_conflation_states_per_channel: Option<usize>,
    pub conflation_key_path: Option<String>,
    pub cluster_coordination: bool,
    pub coordination_backend: DeltaCoordinationBackend,
    pub omit_delta_algorithm: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct TagFilteringConfig {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default = "default_true")]
    pub enable_tags: bool,
}

fn default_true() -> bool {
    true
}

impl Default for IdempotencyConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            ttl_seconds: 120,
            max_key_length: 128,
        }
    }
}

impl Default for EphemeralConfig {
    fn default() -> Self {
        Self { enabled: true }
    }
}

impl Default for EchoControlConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            default_echo_messages: true,
        }
    }
}

impl Default for EventNameFilteringConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_events_per_filter: 50,
            max_event_name_length: 200,
        }
    }
}

impl Default for ConnectionRecoveryConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            buffer_ttl_seconds: 120,
            max_buffer_size: 100,
        }
    }
}

impl Default for DeltaCompressionOptionsConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            algorithm: "fossil".to_string(),
            full_message_interval: 10,
            min_message_size: 100,
            max_state_age_secs: 300,
            max_channel_states_per_socket: 100,
            max_conflation_states_per_channel: Some(100),
            conflation_key_path: None,
            cluster_coordination: false,
            coordination_backend: DeltaCoordinationBackend::Auto,
            omit_delta_algorithm: false,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{ServerOptions, VersionStoreDriver};

    #[tokio::test]
    async fn versioned_messages_driver_overrides_from_env() {
        let previous = std::env::var("VERSIONED_MESSAGES_DRIVER").ok();
        // SAFETY: This test controls the environment variable lifecycle for a
        // single key and restores the prior value before it returns.
        unsafe { std::env::set_var("VERSIONED_MESSAGES_DRIVER", "postgres") };

        let mut options = ServerOptions::default();
        options.override_from_env().await.unwrap();

        if let Some(previous) = previous {
            // SAFETY: Restoring the pre-test value for the same key.
            unsafe { std::env::set_var("VERSIONED_MESSAGES_DRIVER", previous) };
        } else {
            // SAFETY: Removing the test-only environment variable before exit.
            unsafe { std::env::remove_var("VERSIONED_MESSAGES_DRIVER") };
        }

        assert_eq!(
            options.versioned_messages.driver,
            VersionStoreDriver::Postgres
        );
    }
}