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
#![allow(dead_code)]
// src/adapter/handler/connection_management.rs
use super::ConnectionHandler;
use crate::app::config::App;
use crate::error::{Error, Result};
use crate::protocol::messages::PusherMessage;
use crate::websocket::SocketId;
use sockudo_ws::Message;
use sockudo_ws::axum_integration::WebSocketWriter;
use std::sync::Arc;
use tracing::warn;
impl ConnectionHandler {
pub async fn send_message_to_socket(
&self,
app_id: &str,
socket_id: &SocketId,
message: PusherMessage,
) -> Result<()> {
// Calculate message size for metrics
let message_size = sonic_rs::to_string(&message).unwrap_or_default().len();
// Send the message (lock-free - all ConnectionManager methods are &self)
let result = self
.connection_manager
.send_message(app_id, socket_id, message)
.await;
// Track metrics if message was sent successfully
if result.is_ok()
&& let Some(ref metrics) = self.metrics
{
let metrics_locked = metrics.lock().await;
metrics_locked.mark_ws_message_sent(app_id, message_size);
}
result
}
/// Broadcast to channel (backward compatible version)
pub async fn broadcast_to_channel(
&self,
app_config: &App,
channel: &str,
message: PusherMessage,
exclude_socket: Option<&SocketId>,
) -> Result<()> {
self.broadcast_to_channel_with_timing(app_config, channel, message, exclude_socket, None)
.await
}
/// Broadcast to channel with optional timing for latency tracking
pub async fn broadcast_to_channel_with_timing(
&self,
app_config: &App,
channel: &str,
message: PusherMessage,
exclude_socket: Option<&SocketId>,
start_time_ms: Option<f64>,
) -> Result<()> {
self.broadcast_to_channel_internal(
app_config,
channel,
message,
exclude_socket,
start_time_ms,
false, // allow delta compression
)
.await
}
/// Broadcast to channel forcing full messages (skip delta compression)
///
/// This is used when the publisher explicitly requests `delta: false` in the
/// publish API. All recipients will receive the full message regardless of
/// their delta compression subscription settings.
pub async fn broadcast_to_channel_force_full(
&self,
app_config: &App,
channel: &str,
message: PusherMessage,
exclude_socket: Option<&SocketId>,
start_time_ms: Option<f64>,
) -> Result<()> {
self.broadcast_to_channel_internal(
app_config,
channel,
message,
exclude_socket,
start_time_ms,
true, // force full messages, skip delta compression
)
.await
}
/// Internal broadcast implementation with delta compression control
async fn broadcast_to_channel_internal(
&self,
app_config: &App,
channel: &str,
message: PusherMessage,
exclude_socket: Option<&SocketId>,
start_time_ms: Option<f64>,
force_full_message: bool,
) -> Result<()> {
// Calculate message size for metrics
let message_size = sonic_rs::to_string(&message).unwrap_or_default().len();
// Extract channel-specific delta compression settings
// If force_full_message is true, we pass None to disable delta compression
let channel_settings = if force_full_message {
None
} else {
Self::get_channel_delta_settings(app_config, channel)
};
// Get the number of sockets in the channel before sending and send the message
let (result, target_socket_count) = {
let socket_count = self
.connection_manager
.get_channel_socket_count(&app_config.id, channel)
.await;
// Adjust for excluded socket
let target_socket_count = if exclude_socket.is_some() && socket_count > 0 {
socket_count - 1
} else {
socket_count
};
let result = if force_full_message {
// Send without compression - bypass delta compression entirely
self.connection_manager
.send(
channel,
message,
exclude_socket,
&app_config.id,
start_time_ms,
)
.await
} else {
// Normal path with delta compression
self.connection_manager
.send_with_compression(
channel,
message,
exclude_socket,
&app_config.id,
start_time_ms,
crate::adapter::connection_manager::CompressionParams {
delta_compression: Arc::clone(&self.delta_compression),
channel_settings: channel_settings.as_ref(),
},
)
.await
};
(result, target_socket_count)
};
// Track metrics if message was sent successfully
if result.is_ok()
&& target_socket_count > 0
&& let Some(ref metrics) = self.metrics
{
let metrics_locked = metrics.lock().await;
// Batch metrics update instead of loop for performance
metrics_locked.mark_ws_messages_sent_batch(
&app_config.id,
message_size,
target_socket_count,
);
// Track broadcast latency if we have a start time
if let Some(start_ms) = start_time_ms {
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos() as f64
/ 1_000_000.0; // Convert to milliseconds
let latency_ms = (now_ms - start_ms).max(0.0); // Already in milliseconds with microsecond precision
metrics_locked.track_broadcast_latency(
&app_config.id,
channel,
target_socket_count,
latency_ms,
);
}
}
result
}
pub async fn close_connection(
&self,
socket_id: &SocketId,
app_config: &App,
code: u16,
reason: &str,
) -> Result<()> {
if let Some(conn) = self
.connection_manager
.get_connection(socket_id, &app_config.id)
.await
{
let mut conn_locked = conn.inner.lock().await;
conn_locked
.close(code, reason.to_string())
.await
.map_err(|e| Error::Internal(format!("Failed to close connection: {e}")))
} else {
warn!("Connection not found for close: {}", socket_id);
Ok(())
}
}
pub async fn get_channel_member_count(&self, app_config: &App, channel: &str) -> Result<usize> {
self.connection_manager
.get_channel_members(&app_config.id, channel)
.await
.map(|members| members.len())
}
pub async fn verify_channel_subscription(
&self,
socket_id: &SocketId,
app_config: &App,
channel: &str,
) -> Result<()> {
let is_subscribed = self
.connection_manager
.is_in_channel(&app_config.id, channel, socket_id)
.await?;
if !is_subscribed {
return Err(Error::ClientEvent(format!(
"Socket {socket_id} is not subscribed to channel {channel}"
)));
}
Ok(())
}
async fn send_error_frame(ws_tx: &mut WebSocketWriter, error: &Error) {
let error_message = PusherMessage::error(error.close_code(), error.to_string(), None);
if let Ok(payload) = sonic_rs::to_string(&error_message)
&& let Err(e) = ws_tx.send(Message::text(payload)).await
{
warn!("Failed to send error frame: {e}");
}
if let Err(e) = ws_tx.close(error.close_code(), &error.to_string()).await {
warn!("Failed to send close frame: {}", e);
}
}
/// Get channel-specific delta compression settings with pattern matching support
///
/// Supports:
/// - Exact channel name match (e.g., "market-data")
/// - Wildcard patterns (e.g., "market-*" matches "market-btc", "market-eth")
/// - Prefix patterns (e.g., "private-*")
fn get_channel_delta_settings(
app_config: &App,
channel: &str,
) -> Option<crate::delta_compression::ChannelDeltaSettings> {
let channel_delta_map = app_config.channel_delta_compression.as_ref()?;
// First try exact match
if let Some(config) = channel_delta_map.get(channel) {
return Self::convert_channel_config_to_settings(config);
}
// Try pattern matching for wildcard patterns
for (pattern, config) in channel_delta_map.iter() {
if Self::matches_pattern(channel, pattern) {
return Self::convert_channel_config_to_settings(config);
}
}
None
}
/// Convert ChannelDeltaConfig enum to ChannelDeltaSettings struct
fn convert_channel_config_to_settings(
config: &crate::delta_compression::ChannelDeltaConfig,
) -> Option<crate::delta_compression::ChannelDeltaSettings> {
use crate::delta_compression::{ChannelDeltaConfig, ChannelDeltaSettings, DeltaAlgorithm};
match config {
ChannelDeltaConfig::Full(settings) => Some(settings.clone()),
ChannelDeltaConfig::Simple(simple) => {
use crate::delta_compression::ChannelDeltaSimple;
match simple {
ChannelDeltaSimple::Disabled => None,
ChannelDeltaSimple::Inherit => None, // Inherit from global settings
ChannelDeltaSimple::Fossil => Some(ChannelDeltaSettings {
enabled: true,
algorithm: DeltaAlgorithm::Fossil,
conflation_key: None,
max_messages_per_key: 10,
max_conflation_keys: 100,
enable_tags: true,
}),
ChannelDeltaSimple::Xdelta3 => Some(ChannelDeltaSettings {
enabled: true,
algorithm: DeltaAlgorithm::Xdelta3,
conflation_key: None,
max_messages_per_key: 10,
max_conflation_keys: 100,
enable_tags: true,
}),
}
}
}
}
/// Check if a channel name matches a pattern
/// Supports:
/// - Exact match: "market-data" matches "market-data"
/// - Wildcard suffix: "market-*" matches "market-btc", "market-eth", etc.
/// - Wildcard prefix: "*-data" matches "market-data", "price-data", etc.
fn matches_pattern(channel: &str, pattern: &str) -> bool {
// Exact match
if channel == pattern {
return true;
}
// Wildcard pattern matching
if pattern.contains('*') {
if let Some(prefix) = pattern.strip_suffix('*') {
// Prefix match: "market-*" matches "market-btc"
return channel.starts_with(prefix);
} else if let Some(suffix) = pattern.strip_prefix('*') {
// Suffix match: "*-data" matches "market-data"
return channel.ends_with(suffix);
} else {
// Middle wildcard: "market-*-data" matches "market-btc-data"
let parts: Vec<&str> = pattern.split('*').collect();
if parts.len() == 2 {
return channel.starts_with(parts[0]) && channel.ends_with(parts[1]);
}
}
}
false
}
}