sockudo-adapter 4.3.0

Connection adapters and horizontal scaling for Sockudo
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
use crate::horizontal_adapter::{BroadcastMessage, RequestBody, ResponseBody};
use crate::horizontal_transport::{HorizontalTransport, TransportConfig, TransportHandlers};
use async_trait::async_trait;
use futures_util::StreamExt;
use lapin::message::Delivery;
use lapin::options::{
    BasicAckOptions, BasicConsumeOptions, BasicPublishOptions, ExchangeDeclareOptions,
    QueueBindOptions, QueueDeclareOptions,
};
use lapin::types::FieldTable;
use lapin::{BasicProperties, Channel, Connection, ConnectionProperties, ExchangeKind};
use sockudo_core::error::{Error, Result};
use sockudo_core::metrics::MetricsInterface;
use sockudo_core::options::RabbitMqAdapterConfig;
use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use tokio::sync::Notify;
use tracing::{debug, error, info, warn};

pub struct RabbitMqTransport {
    connection: Arc<Connection>,
    publish_channel: Channel,
    broadcast_exchange: String,
    request_exchange: String,
    response_exchange: String,
    config: RabbitMqAdapterConfig,
    metrics: Arc<OnceLock<Arc<dyn MetricsInterface + Send + Sync>>>,
    shutdown: Arc<Notify>,
    is_running: Arc<AtomicBool>,
    owner_count: Arc<AtomicUsize>,
}

impl TransportConfig for RabbitMqAdapterConfig {
    fn request_timeout_ms(&self) -> u64 {
        self.request_timeout_ms
    }

    fn prefix(&self) -> &str {
        &self.prefix
    }
}

#[async_trait]
impl HorizontalTransport for RabbitMqTransport {
    type Config = RabbitMqAdapterConfig;

    async fn new(config: Self::Config) -> Result<Self> {
        let connection = Connection::connect(&config.url, ConnectionProperties::default())
            .await
            .map_err(|e| Error::Internal(format!("Failed to connect to RabbitMQ: {e}")))?;
        let connection = Arc::new(connection);

        let publish_channel = connection
            .create_channel()
            .await
            .map_err(|e| Error::Internal(format!("Failed to create RabbitMQ channel: {e}")))?;

        let broadcast_exchange = format!("{}.broadcast", config.prefix);
        let request_exchange = format!("{}.requests", config.prefix);
        let response_exchange = format!("{}.responses", config.prefix);

        for exchange in [&broadcast_exchange, &request_exchange, &response_exchange] {
            publish_channel
                .exchange_declare(
                    exchange.as_str().into(),
                    ExchangeKind::Fanout,
                    ExchangeDeclareOptions::default(),
                    FieldTable::default(),
                )
                .await
                .map_err(|e| {
                    Error::Internal(format!(
                        "Failed to declare RabbitMQ exchange '{exchange}': {e}"
                    ))
                })?;
        }

        info!(
            "RabbitMQ transport initialized with exchanges: {}, {}, {}",
            broadcast_exchange, request_exchange, response_exchange
        );

        Ok(Self {
            connection,
            publish_channel,
            broadcast_exchange,
            request_exchange,
            response_exchange,
            config,
            metrics: Arc::new(OnceLock::new()),
            shutdown: Arc::new(Notify::new()),
            is_running: Arc::new(AtomicBool::new(true)),
            owner_count: Arc::new(AtomicUsize::new(1)),
        })
    }

    async fn publish_broadcast(&self, message: &BroadcastMessage) -> Result<()> {
        self.publish_to_exchange(&self.broadcast_exchange, message)
            .await
    }

    async fn publish_request(&self, request: &RequestBody) -> Result<()> {
        self.publish_to_exchange(&self.request_exchange, request)
            .await
    }

    async fn publish_response(&self, response: &ResponseBody) -> Result<()> {
        self.publish_to_exchange(&self.response_exchange, response)
            .await
    }

    async fn start_listeners(&self, handlers: TransportHandlers) -> Result<()> {
        self.spawn_consumer(
            self.broadcast_exchange.clone(),
            "broadcast",
            handlers.on_broadcast.clone(),
        )
        .await?;

        self.spawn_request_consumer(
            self.request_exchange.clone(),
            self.response_exchange.clone(),
            handlers.on_request.clone(),
        )
        .await?;

        self.spawn_consumer(
            self.response_exchange.clone(),
            "response",
            handlers.on_response.clone(),
        )
        .await?;

        Ok(())
    }

    async fn get_node_count(&self) -> Result<usize> {
        Ok(self.config.nodes_number.unwrap_or(1) as usize)
    }

    async fn check_health(&self) -> Result<()> {
        if self.connection.status().connected() {
            Ok(())
        } else {
            Err(Error::Internal(
                "RabbitMQ connection is not currently connected".to_string(),
            ))
        }
    }

    fn set_metrics(&self, metrics: Arc<dyn MetricsInterface + Send + Sync>) {
        let _ = self.metrics.set(metrics);
    }
}

impl RabbitMqTransport {
    async fn publish_to_exchange<T: serde::Serialize>(
        &self,
        exchange: &str,
        message: &T,
    ) -> Result<()> {
        let payload = sonic_rs::to_vec(message)
            .map_err(|e| Error::Other(format!("Failed to serialize RabbitMQ message: {e}")))?;

        self.publish_channel
            .basic_publish(
                exchange.into(),
                "".into(),
                BasicPublishOptions::default(),
                &payload,
                BasicProperties::default(),
            )
            .await
            .map_err(|e| Error::Internal(format!("Failed to publish to RabbitMQ: {e}")))?
            .await
            .map_err(|e| Error::Internal(format!("RabbitMQ publish confirmation failed: {e}")))?;

        Ok(())
    }

    async fn spawn_consumer<T>(
        &self,
        exchange: String,
        kind: &'static str,
        handler: Arc<
            dyn Fn(T) -> crate::horizontal_transport::BoxFuture<'static, ()> + Send + Sync,
        >,
    ) -> Result<()>
    where
        T: serde::de::DeserializeOwned + Send + 'static,
    {
        let channel = self
            .connection
            .create_channel()
            .await
            .map_err(|e| Error::Internal(format!("Failed to create RabbitMQ channel: {e}")))?;

        let queue = Self::declare_bound_queue(&channel, &exchange, kind).await?;
        let consumer_tag = format!("sockudo-{kind}-{}", uuid::Uuid::new_v4());
        let mut consumer = channel
            .basic_consume(
                queue.as_str().into(),
                consumer_tag.as_str().into(),
                BasicConsumeOptions::default(),
                FieldTable::default(),
            )
            .await
            .map_err(|e| Error::Internal(format!("Failed to start RabbitMQ consumer: {e}")))?;
        let shutdown = self.shutdown.clone();
        let is_running = self.is_running.clone();
        let metrics = self.metrics.clone();

        info!("RabbitMQ transport consuming {kind} from queue {}", queue);

        tokio::spawn(async move {
            loop {
                if !is_running.load(Ordering::Relaxed) {
                    break;
                }
                let delivery = tokio::select! {
                    _ = shutdown.notified() => break,
                    delivery = consumer.next() => delivery,
                };
                let Some(delivery) = delivery else {
                    break;
                };
                match delivery {
                    Ok(delivery) => {
                        Self::handle_delivery(delivery, &handler, &metrics, kind).await;
                    }
                    Err(e) => {
                        error!("RabbitMQ {kind} consumer error: {}", e);
                        break;
                    }
                }
            }

            warn!("RabbitMQ {kind} consumer loop ended");
        });

        Ok(())
    }

    async fn spawn_request_consumer(
        &self,
        exchange: String,
        response_exchange: String,
        handler: Arc<
            dyn Fn(
                    RequestBody,
                )
                    -> crate::horizontal_transport::BoxFuture<'static, Result<ResponseBody>>
                + Send
                + Sync,
        >,
    ) -> Result<()> {
        let channel = self
            .connection
            .create_channel()
            .await
            .map_err(|e| Error::Internal(format!("Failed to create RabbitMQ channel: {e}")))?;

        let queue = Self::declare_bound_queue(&channel, &exchange, "request").await?;
        let consumer_tag = format!("sockudo-request-{}", uuid::Uuid::new_v4());
        let mut consumer = channel
            .basic_consume(
                queue.as_str().into(),
                consumer_tag.as_str().into(),
                BasicConsumeOptions::default(),
                FieldTable::default(),
            )
            .await
            .map_err(|e| Error::Internal(format!("Failed to start RabbitMQ consumer: {e}")))?;
        let shutdown = self.shutdown.clone();
        let is_running = self.is_running.clone();
        let metrics = self.metrics.clone();

        info!("RabbitMQ transport consuming requests from queue {}", queue);

        tokio::spawn(async move {
            loop {
                if !is_running.load(Ordering::Relaxed) {
                    break;
                }
                let delivery = tokio::select! {
                    _ = shutdown.notified() => break,
                    delivery = consumer.next() => delivery,
                };
                let Some(delivery) = delivery else {
                    break;
                };
                match delivery {
                    Ok(delivery) => {
                        let response_channel = channel.clone();
                        let response_exchange = response_exchange.clone();

                        match sonic_rs::from_slice::<RequestBody>(&delivery.data) {
                            Ok(request) => match handler(request).await {
                                Ok(response) => {
                                    if let Ok(payload) = sonic_rs::to_vec(&response) {
                                        if let Err(e) = response_channel
                                            .basic_publish(
                                                response_exchange.as_str().into(),
                                                "".into(),
                                                BasicPublishOptions::default(),
                                                &payload,
                                                BasicProperties::default(),
                                            )
                                            .await
                                        {
                                            warn!("Failed to publish RabbitMQ response: {}", e);
                                        } else {
                                            debug!("Published RabbitMQ response");
                                        }
                                    }
                                }
                                Err(e) => {
                                    warn!("RabbitMQ request handler failed: {}", e);
                                }
                            },
                            Err(e) => {
                                if let Some(metrics) = metrics.get() {
                                    metrics.mark_horizontal_transport_message_dropped("rabbitmq");
                                }
                                warn!("Failed to parse RabbitMQ request payload: {}", e);
                            }
                        }

                        if let Err(e) = delivery.ack(BasicAckOptions::default()).await {
                            warn!("Failed to ack RabbitMQ request delivery: {}", e);
                        }
                    }
                    Err(e) => {
                        error!("RabbitMQ request consumer error: {}", e);
                        break;
                    }
                }
            }

            warn!("RabbitMQ request consumer loop ended");
        });

        Ok(())
    }

    async fn declare_bound_queue(channel: &Channel, exchange: &str, kind: &str) -> Result<String> {
        channel
            .exchange_declare(
                exchange.into(),
                ExchangeKind::Fanout,
                ExchangeDeclareOptions::default(),
                FieldTable::default(),
            )
            .await
            .map_err(|e| Error::Internal(format!("Failed to declare RabbitMQ exchange: {e}")))?;

        let queue = channel
            .queue_declare(
                "".into(),
                QueueDeclareOptions {
                    durable: false,
                    exclusive: true,
                    auto_delete: true,
                    ..Default::default()
                },
                FieldTable::default(),
            )
            .await
            .map_err(|e| Error::Internal(format!("Failed to declare RabbitMQ queue: {e}")))?;

        channel
            .queue_bind(
                queue.name().as_str().into(),
                exchange.into(),
                "".into(),
                QueueBindOptions::default(),
                FieldTable::default(),
            )
            .await
            .map_err(|e| Error::Internal(format!("Failed to bind RabbitMQ queue: {e}")))?;

        debug!(
            "RabbitMQ transport bound {} queue {} to exchange {}",
            kind,
            queue.name().as_str(),
            exchange
        );

        Ok(queue.name().as_str().to_string())
    }

    async fn handle_delivery<T>(
        delivery: Delivery,
        handler: &Arc<
            dyn Fn(T) -> crate::horizontal_transport::BoxFuture<'static, ()> + Send + Sync,
        >,
        metrics: &Arc<OnceLock<Arc<dyn MetricsInterface + Send + Sync>>>,
        driver: &str,
    ) where
        T: serde::de::DeserializeOwned + Send + 'static,
    {
        match sonic_rs::from_slice::<T>(&delivery.data) {
            Ok(message) => handler(message).await,
            Err(e) => {
                if let Some(metrics) = metrics.get() {
                    metrics.mark_horizontal_transport_message_dropped(driver);
                }
                warn!("Failed to parse RabbitMQ payload: {}", e)
            }
        }

        if let Err(e) = delivery.ack(BasicAckOptions::default()).await {
            warn!("Failed to ack RabbitMQ delivery: {}", e);
        }
    }
}

impl Clone for RabbitMqTransport {
    fn clone(&self) -> Self {
        self.owner_count.fetch_add(1, Ordering::Relaxed);
        Self {
            connection: self.connection.clone(),
            publish_channel: self.publish_channel.clone(),
            broadcast_exchange: self.broadcast_exchange.clone(),
            request_exchange: self.request_exchange.clone(),
            response_exchange: self.response_exchange.clone(),
            config: self.config.clone(),
            metrics: self.metrics.clone(),
            shutdown: self.shutdown.clone(),
            is_running: self.is_running.clone(),
            owner_count: self.owner_count.clone(),
        }
    }
}

impl Drop for RabbitMqTransport {
    fn drop(&mut self) {
        if self.owner_count.fetch_sub(1, Ordering::AcqRel) == 1 {
            self.is_running.store(false, Ordering::Relaxed);
            self.shutdown.notify_waiters();
        }
    }
}