|
| 1 | +use crate::api::error::LdkServerError; |
| 2 | +use crate::api::error::LdkServerErrorCode::InternalServerError; |
| 3 | +use crate::io::events::event_publisher::EventPublisher; |
| 4 | +use ::prost::Message; |
| 5 | +use async_trait::async_trait; |
| 6 | +use lapin::options::{BasicPublishOptions, ConfirmSelectOptions, ExchangeDeclareOptions}; |
| 7 | +use lapin::types::FieldTable; |
| 8 | +use lapin::{ |
| 9 | + BasicProperties, Channel, Connection, ConnectionProperties, ConnectionState, ExchangeKind, |
| 10 | +}; |
| 11 | +use ldk_server_protos::events::EventEnvelope; |
| 12 | +use std::sync::Arc; |
| 13 | +use tokio::sync::Mutex; |
| 14 | + |
| 15 | +/// A RabbitMQ-based implementation of the EventPublisher trait. |
| 16 | +pub struct RabbitMqEventPublisher { |
| 17 | + /// The RabbitMQ connection, used for reconnection logic. |
| 18 | + connection: Arc<Mutex<Option<Connection>>>, |
| 19 | + /// The RabbitMQ channel used for publishing events. |
| 20 | + channel: Arc<Mutex<Option<Channel>>>, |
| 21 | + /// Configuration details, including connection string and exchange name. |
| 22 | + config: RabbitMqConfig, |
| 23 | +} |
| 24 | + |
| 25 | +/// Configuration for the RabbitMQ event publisher. |
| 26 | +#[derive(Debug, Clone)] |
| 27 | +pub struct RabbitMqConfig { |
| 28 | + pub connection_string: String, |
| 29 | + pub exchange_name: String, |
| 30 | +} |
| 31 | + |
| 32 | +/// Delivery mode for persistent messages (written to disk). |
| 33 | +const DELIVERY_MODE_PERSISTENT: u8 = 2; |
| 34 | + |
| 35 | +impl RabbitMqEventPublisher { |
| 36 | + /// Creates a new RabbitMqEventPublisher instance. |
| 37 | + pub fn new(config: RabbitMqConfig) -> Self { |
| 38 | + Self { connection: Arc::new(Mutex::new(None)), channel: Arc::new(Mutex::new(None)), config } |
| 39 | + } |
| 40 | + |
| 41 | + async fn connect(config: &RabbitMqConfig) -> Result<(Connection, Channel), LdkServerError> { |
| 42 | + let conn = Connection::connect(&config.connection_string, ConnectionProperties::default()) |
| 43 | + .await |
| 44 | + .map_err(|e| { |
| 45 | + LdkServerError::new( |
| 46 | + InternalServerError, |
| 47 | + format!("Failed to connect to RabbitMQ: {}", e), |
| 48 | + ) |
| 49 | + })?; |
| 50 | + |
| 51 | + let channel = conn.create_channel().await.map_err(|e| { |
| 52 | + LdkServerError::new(InternalServerError, format!("Failed to create channel: {}", e)) |
| 53 | + })?; |
| 54 | + |
| 55 | + channel.confirm_select(ConfirmSelectOptions::default()).await.map_err(|e| { |
| 56 | + LdkServerError::new(InternalServerError, format!("Failed to enable confirms: {}", e)) |
| 57 | + })?; |
| 58 | + |
| 59 | + channel |
| 60 | + .exchange_declare( |
| 61 | + &config.exchange_name, |
| 62 | + ExchangeKind::Fanout, |
| 63 | + ExchangeDeclareOptions { durable: true, ..Default::default() }, |
| 64 | + FieldTable::default(), |
| 65 | + ) |
| 66 | + .await |
| 67 | + .map_err(|e| { |
| 68 | + LdkServerError::new( |
| 69 | + InternalServerError, |
| 70 | + format!("Failed to declare exchange: {}", e), |
| 71 | + ) |
| 72 | + })?; |
| 73 | + |
| 74 | + Ok((conn, channel)) |
| 75 | + } |
| 76 | + |
| 77 | + async fn ensure_connected(&self) -> Result<(), LdkServerError> { |
| 78 | + { |
| 79 | + let connection = self.connection.lock().await; |
| 80 | + if let Some(connection) = &*connection { |
| 81 | + if connection.status().state() == ConnectionState::Connected { |
| 82 | + return Ok(()); |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + // Connection is not alive, attempt reconnecting. |
| 88 | + let (connection, channel) = Self::connect(&self.config) |
| 89 | + .await |
| 90 | + .map_err(|e| LdkServerError::new(InternalServerError, e.to_string()))?; |
| 91 | + *self.connection.lock().await = Some(connection); |
| 92 | + *self.channel.lock().await = Some(channel); |
| 93 | + Ok(()) |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +#[async_trait] |
| 98 | +impl EventPublisher for RabbitMqEventPublisher { |
| 99 | + /// Publishes an event to RabbitMQ. |
| 100 | + /// |
| 101 | + /// The event is published to a fanout exchange with persistent delivery mode, |
| 102 | + /// and the method waits for confirmation from RabbitMQ to ensure durability. |
| 103 | + async fn publish(&self, event: EventEnvelope) -> Result<(), LdkServerError> { |
| 104 | + // Ensure connection is alive before proceeding |
| 105 | + self.ensure_connected().await?; |
| 106 | + |
| 107 | + let channel_guard = self.channel.lock().await; |
| 108 | + let channel = channel_guard.as_ref().ok_or_else(|| { |
| 109 | + LdkServerError::new(InternalServerError, "Channel not initialized".to_string()) |
| 110 | + })?; |
| 111 | + |
| 112 | + // Publish the event with persistent delivery mode |
| 113 | + let confirm = channel |
| 114 | + .basic_publish( |
| 115 | + &self.config.exchange_name, |
| 116 | + "", // Empty routing key should be used for fanout exchange, since it is ignored. |
| 117 | + BasicPublishOptions::default(), |
| 118 | + &event.encode_to_vec(), |
| 119 | + BasicProperties::default().with_delivery_mode(DELIVERY_MODE_PERSISTENT), |
| 120 | + ) |
| 121 | + .await |
| 122 | + .map_err(|e| { |
| 123 | + LdkServerError::new( |
| 124 | + InternalServerError, |
| 125 | + format!("Failed to publish event, error: {}", e), |
| 126 | + ) |
| 127 | + })?; |
| 128 | + |
| 129 | + let confirmation = confirm.await.map_err(|e| { |
| 130 | + LdkServerError::new(InternalServerError, format!("Failed to get confirmation: {}", e)) |
| 131 | + })?; |
| 132 | + |
| 133 | + match confirmation { |
| 134 | + lapin::publisher_confirm::Confirmation::Ack(_) => Ok(()), |
| 135 | + lapin::publisher_confirm::Confirmation::Nack(_) => Err(LdkServerError::new( |
| 136 | + InternalServerError, |
| 137 | + "Message not acknowledged".to_string(), |
| 138 | + )), |
| 139 | + _ => { |
| 140 | + Err(LdkServerError::new(InternalServerError, "Unexpected confirmation".to_string())) |
| 141 | + }, |
| 142 | + } |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +#[cfg(test)] |
| 147 | +#[cfg(feature = "integration-tests-events-rabbitmq")] |
| 148 | +mod integration_tests_events_rabbitmq { |
| 149 | + use super::*; |
| 150 | + use lapin::{ |
| 151 | + options::{BasicAckOptions, BasicConsumeOptions, QueueBindOptions, QueueDeclareOptions}, |
| 152 | + types::FieldTable, |
| 153 | + Channel, Connection, |
| 154 | + }; |
| 155 | + use ldk_server_protos::events::event_envelope::Event; |
| 156 | + use ldk_server_protos::events::PaymentForwarded; |
| 157 | + use std::io; |
| 158 | + use std::time::Duration; |
| 159 | + use tokio; |
| 160 | + |
| 161 | + use futures_util::stream::StreamExt; |
| 162 | + #[tokio::test] |
| 163 | + async fn test_publish_and_consume_event() { |
| 164 | + let config = RabbitMqConfig { |
| 165 | + connection_string: "amqp://guest:guest@localhost:5672/%2f".to_string(), |
| 166 | + exchange_name: "test_exchange".to_string(), |
| 167 | + }; |
| 168 | + |
| 169 | + let publisher = RabbitMqEventPublisher::new(config.clone()); |
| 170 | + |
| 171 | + let conn = Connection::connect(&config.connection_string, ConnectionProperties::default()) |
| 172 | + .await |
| 173 | + .expect("Failed make rabbitmq connection"); |
| 174 | + let channel = conn.create_channel().await.expect("Failed to create rabbitmq channel"); |
| 175 | + |
| 176 | + let queue_name = "test_queue"; |
| 177 | + setup_queue(&queue_name, &channel, &config).await; |
| 178 | + |
| 179 | + let event = |
| 180 | + EventEnvelope { event: Some(Event::PaymentForwarded(PaymentForwarded::default())) }; |
| 181 | + publisher.publish(event.clone()).await.expect("Failed to publish event"); |
| 182 | + |
| 183 | + consume_event(&queue_name, &channel, &event).await.expect("Failed to consume event"); |
| 184 | + } |
| 185 | + |
| 186 | + async fn setup_queue(queue_name: &str, channel: &Channel, config: &RabbitMqConfig) { |
| 187 | + channel |
| 188 | + .queue_declare(queue_name, QueueDeclareOptions::default(), FieldTable::default()) |
| 189 | + .await |
| 190 | + .unwrap(); |
| 191 | + channel |
| 192 | + .exchange_declare( |
| 193 | + &config.exchange_name, |
| 194 | + ExchangeKind::Fanout, |
| 195 | + ExchangeDeclareOptions { durable: true, ..Default::default() }, |
| 196 | + FieldTable::default(), |
| 197 | + ) |
| 198 | + .await |
| 199 | + .unwrap(); |
| 200 | + |
| 201 | + channel |
| 202 | + .queue_bind( |
| 203 | + queue_name, |
| 204 | + &config.exchange_name, |
| 205 | + "", |
| 206 | + QueueBindOptions::default(), |
| 207 | + FieldTable::default(), |
| 208 | + ) |
| 209 | + .await |
| 210 | + .unwrap(); |
| 211 | + } |
| 212 | + |
| 213 | + async fn consume_event( |
| 214 | + queue_name: &str, channel: &Channel, expected_event: &EventEnvelope, |
| 215 | + ) -> io::Result<()> { |
| 216 | + let mut consumer = channel |
| 217 | + .basic_consume( |
| 218 | + queue_name, |
| 219 | + "test_consumer", |
| 220 | + BasicConsumeOptions::default(), |
| 221 | + FieldTable::default(), |
| 222 | + ) |
| 223 | + .await |
| 224 | + .unwrap(); |
| 225 | + let delivery = |
| 226 | + tokio::time::timeout(Duration::from_secs(10), consumer.next()).await?.unwrap().unwrap(); |
| 227 | + let received_event = EventEnvelope::decode(&*delivery.data)?; |
| 228 | + assert_eq!(received_event, *expected_event, "Event mismatch"); |
| 229 | + channel.basic_ack(delivery.delivery_tag, BasicAckOptions::default()).await.unwrap(); |
| 230 | + Ok(()) |
| 231 | + } |
| 232 | +} |
0 commit comments