|
| 1 | +//! NATS sink for publishing events to a NATS subject. |
| 2 | +//! |
| 3 | +//! Publishes each event as a JSON message to the configured subject. |
| 4 | +//! The sink maintains a persistent connection with automatic reconnection. |
| 5 | +
|
| 6 | +use async_nats::Client; |
| 7 | +use etl::error::EtlResult; |
| 8 | +use serde::Deserialize; |
| 9 | +use std::sync::Arc; |
| 10 | +use tracing::info; |
| 11 | + |
| 12 | +use crate::sink::Sink; |
| 13 | +use crate::types::TriggeredEvent; |
| 14 | + |
| 15 | +/// Configuration for the NATS sink. |
| 16 | +#[derive(Clone, Debug, Deserialize)] |
| 17 | +pub struct NatsSinkConfig { |
| 18 | + /// NATS server URL (e.g., "nats://localhost:4222"). |
| 19 | + pub url: String, |
| 20 | + |
| 21 | + /// Subject to publish messages to. |
| 22 | + pub subject: String, |
| 23 | +} |
| 24 | + |
| 25 | +/// Sink that publishes events to a NATS subject. |
| 26 | +/// |
| 27 | +/// Each event is serialized as JSON and published to the configured subject. |
| 28 | +/// The NATS client handles connection pooling and automatic reconnection. |
| 29 | +#[derive(Clone)] |
| 30 | +pub struct NatsSink { |
| 31 | + /// Shared NATS client connection. |
| 32 | + client: Arc<Client>, |
| 33 | + |
| 34 | + /// Subject to publish messages to. |
| 35 | + subject: String, |
| 36 | +} |
| 37 | + |
| 38 | +impl NatsSink { |
| 39 | + /// Creates a new NATS sink from configuration. |
| 40 | + /// |
| 41 | + /// # Errors |
| 42 | + /// |
| 43 | + /// Returns an error if the NATS connection cannot be established. |
| 44 | + pub async fn new( |
| 45 | + config: NatsSinkConfig, |
| 46 | + ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> { |
| 47 | + let client = async_nats::connect(&config.url).await?; |
| 48 | + |
| 49 | + Ok(Self { |
| 50 | + client: Arc::new(client), |
| 51 | + subject: config.subject, |
| 52 | + }) |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +impl Sink for NatsSink { |
| 57 | + fn name() -> &'static str { |
| 58 | + "nats" |
| 59 | + } |
| 60 | + |
| 61 | + async fn publish_events(&self, events: Vec<TriggeredEvent>) -> EtlResult<()> { |
| 62 | + if events.is_empty() { |
| 63 | + return Ok(()); |
| 64 | + } |
| 65 | + |
| 66 | + info!( |
| 67 | + "publishing {} events to NATS subject '{}'", |
| 68 | + events.len(), |
| 69 | + self.subject |
| 70 | + ); |
| 71 | + |
| 72 | + for event in &events { |
| 73 | + // Build JSON object manually since TriggeredEvent doesn't implement Serialize. |
| 74 | + let mut json_obj = serde_json::json!({ |
| 75 | + "id": event.id.id, |
| 76 | + "created_at": event.id.created_at.to_rfc3339_opts(chrono::SecondsFormat::Millis, true), |
| 77 | + "payload": event.payload, |
| 78 | + "stream_id": format!("{:?}", event.stream_id), |
| 79 | + }); |
| 80 | + |
| 81 | + // Add optional fields. |
| 82 | + if let Some(ref metadata) = event.metadata { |
| 83 | + json_obj["metadata"] = metadata.clone(); |
| 84 | + } |
| 85 | + if let Some(lsn) = event.lsn { |
| 86 | + json_obj["lsn"] = serde_json::json!(lsn.to_string()); |
| 87 | + } |
| 88 | + |
| 89 | + let payload = serde_json::to_vec(&json_obj).map_err(|e| { |
| 90 | + etl::etl_error!( |
| 91 | + etl::error::ErrorKind::InvalidData, |
| 92 | + "Failed to serialize event to JSON", |
| 93 | + e.to_string() |
| 94 | + ) |
| 95 | + })?; |
| 96 | + |
| 97 | + // Publish to the configured subject. |
| 98 | + self.client |
| 99 | + .publish(self.subject.clone(), payload.into()) |
| 100 | + .await |
| 101 | + .map_err(|e| { |
| 102 | + etl::etl_error!( |
| 103 | + etl::error::ErrorKind::InvalidData, |
| 104 | + "Failed to publish event to NATS", |
| 105 | + e.to_string() |
| 106 | + ) |
| 107 | + })?; |
| 108 | + } |
| 109 | + |
| 110 | + Ok(()) |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +#[cfg(test)] |
| 115 | +mod tests { |
| 116 | + use super::*; |
| 117 | + |
| 118 | + #[test] |
| 119 | + fn test_sink_name() { |
| 120 | + assert_eq!(NatsSink::name(), "nats"); |
| 121 | + } |
| 122 | +} |
0 commit comments