Skip to main content

cortexkit_bus_client/
events.rs

1use std::{
2    sync::{Arc, RwLock},
3    time::Duration,
4};
5
6use async_nats::jetstream::{self, consumer::pull, AckKind};
7use bytes::Bytes;
8use cortexkit_bus_naming::{AccountNames, EventSubject};
9use cortexkit_bus_nats::NatsConnection;
10use cortexkit_bus_trait::Headers;
11use futures_util::StreamExt;
12use tokio::sync::watch;
13
14use crate::{BusClient, Error, Result};
15
16/// One EVENT pull result. Malformed records can only be terminated, not acked.
17#[non_exhaustive]
18pub enum EventItem {
19    Delivery(EventDelivery),
20    Malformed(MalformedDelivery),
21}
22
23/// A stored event. Commit your own transaction before calling [`Self::ack`].
24/// Dropping a delivery does not acknowledge it; the server may redeliver it.
25#[non_exhaustive]
26pub struct EventDelivery {
27    pub subject: EventSubject,
28    pub msg_id: String,
29    pub body: Bytes,
30    pub stream_sequence: u64,
31    pub delivered_count: i64,
32    headers: Headers,
33    message: jetstream::Message,
34}
35
36impl EventDelivery {
37    /// Headers copied once from NATS. A repeated header keeps its first value.
38    pub fn headers(&self) -> &Headers {
39        &self.headers
40    }
41
42    /// Looks up a header by its stored name, keeping the first repeated value.
43    pub fn header(&self, name: &str) -> Option<&str> {
44        self.headers.get(name).map(String::as_str)
45    }
46
47    /// Acknowledges the event after the caller's own commit, waiting for the
48    /// server to confirm receipt. No reader operation acknowledges automatically.
49    pub async fn ack(&self) -> Result<()> {
50        self.message
51            .double_ack()
52            .await
53            .map_err(|error| Error::Nats(error.to_string()))
54    }
55
56    /// Requests redelivery after a delay (zero requests immediate redelivery).
57    pub async fn nak(&self, delay: Duration) -> Result<()> {
58        self.message
59            .double_ack_with(AckKind::Nak(Some(delay)))
60            .await
61            .map_err(|error| Error::Nats(error.to_string()))
62    }
63
64    /// Permanently stops redelivery of this event.
65    pub async fn term(&self) -> Result<()> {
66        terminate(&self.message).await
67    }
68}
69
70/// Why a stored record cannot be exposed as a valid event.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72#[non_exhaustive]
73pub enum MalformedReason {
74    MissingMsgId,
75    BadSubject,
76    BadMetadata,
77}
78
79/// A malformed record. Log the reason and call [`Self::term`] to prevent retries.
80/// Nothing, including malformed records, is acknowledged automatically.
81#[non_exhaustive]
82pub struct MalformedDelivery {
83    pub raw_subject: String,
84    pub reason: MalformedReason,
85    /// Absent only when the server supplied malformed JetStream metadata.
86    pub stream_sequence: Option<u64>,
87    message: jetstream::Message,
88}
89
90impl MalformedDelivery {
91    /// Permanently stops redelivery of a malformed record.
92    pub async fn term(&self) -> Result<()> {
93        terminate(&self.message).await
94    }
95}
96
97async fn terminate(message: &jetstream::Message) -> Result<()> {
98    message
99        .double_ack_with(AckKind::Term)
100        .await
101        .map_err(|error| Error::Nats(error.to_string()))
102}
103
104/// A one-at-a-time reader of an existing module-owned EVENT durable.
105/// The server owns its cursor. Re-issue rebinds the reader to the same durable;
106/// unacknowledged messages may redeliver. Keep the [`BusClient`] alive so its
107/// credential maintenance continues to run.
108pub struct EventReader {
109    connection: Arc<RwLock<NatsConnection>>,
110    changes: watch::Receiver<u64>,
111    names: AccountNames,
112    durable: String,
113    consumer: Option<jetstream::consumer::Consumer<pull::Config>>,
114}
115
116impl EventReader {
117    pub(crate) async fn attach(client: &BusClient, durable: &str) -> Result<Self> {
118        let base = AccountNames::module_consumer_name(&client.module)?;
119        // EventConsumer::durable_name accepts only static declarations; apply
120        // the same owner rule directly to a runtime durable name.
121        if durable != base
122            && !durable
123                .strip_prefix(&format!("{base}_"))
124                .is_some_and(|suffix| {
125                    !suffix.is_empty()
126                        && suffix.bytes().all(|byte| {
127                            byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_'
128                        })
129                })
130        {
131            return Err(Error::DurableNotOwned {
132                durable: durable.into(),
133                module: client.module.clone(),
134            });
135        }
136        let mut reader = Self {
137            connection: client.connection.clone(),
138            changes: client.connection_changes(),
139            names: client.names.clone(),
140            durable: durable.into(),
141            consumer: None,
142        };
143        reader.bind().await?;
144        Ok(reader)
145    }
146
147    async fn bind(&mut self) -> Result<()> {
148        loop {
149            self.changes.borrow_and_update();
150            let connection = self
151                .connection
152                .read()
153                .unwrap_or_else(std::sync::PoisonError::into_inner)
154                .clone();
155            let result = jetstream::new(connection.client())
156                .get_consumer_from_stream(&self.durable, &self.names.streams().event)
157                .await;
158            if self.changes.has_changed().unwrap_or(false) {
159                continue;
160            }
161            self.consumer = Some(result.map_err(|error| Error::Nats(error.to_string()))?);
162            return Ok(());
163        }
164    }
165
166    /// Pulls one event, rebinding after credential re-issue if necessary.
167    /// This never acknowledges a message. Commit before acknowledging a valid
168    /// delivery; log and terminate a malformed record instead of retrying it.
169    /// A closed connection-change stream reports a transport error so the caller
170    /// can reconnect the client or report degraded credential maintenance.
171    pub async fn next(&mut self) -> Result<EventItem> {
172        loop {
173            if self.changes.has_changed().unwrap_or(false) || self.consumer.is_none() {
174                self.bind().await?;
175            }
176            let consumer = self.consumer.as_ref().expect("bound consumer");
177            tokio::select! {
178                biased;
179                changed = self.changes.changed() => {
180                    changed.map_err(|_| Error::Transport("credential maintenance stopped".into()))?;
181                    self.consumer = None;
182                }
183                result = async {
184                    let mut batch = consumer.fetch().max_messages(1)
185                        .expires(Duration::from_secs(30)).messages().await
186                        .map_err(|error| Error::Nats(error.to_string()))?;
187                    batch.next().await.transpose().map_err(|error| Error::Nats(error.to_string()))
188                } => {
189                    if let Some(message) = result? {
190                        return Ok(decode(&self.names, message));
191                    }
192                }
193            }
194        }
195    }
196}
197
198fn decode(names: &AccountNames, message: jetstream::Message) -> EventItem {
199    let metadata = message.info();
200    let stream_sequence = metadata.as_ref().ok().map(|info| info.stream_sequence);
201    let subject = names.parse_event_subject(message.subject.as_str());
202    let headers: Headers = message
203        .headers
204        .as_ref()
205        .into_iter()
206        .flat_map(|headers| headers.iter())
207        .filter_map(|(name, values)| {
208            values
209                .first()
210                .map(|value| (name.to_string(), value.to_string()))
211        })
212        .collect();
213    let msg_id = message.headers.as_ref().and_then(|headers| {
214        headers
215            .get(async_nats::header::NATS_MESSAGE_ID)
216            .map(|value| value.as_str().to_owned())
217    });
218    let reason = if metadata.is_err() {
219        Some(MalformedReason::BadMetadata)
220    } else if subject.is_err() {
221        Some(MalformedReason::BadSubject)
222    } else if msg_id.is_none() {
223        Some(MalformedReason::MissingMsgId)
224    } else {
225        None
226    };
227    if let Some(reason) = reason {
228        return EventItem::Malformed(MalformedDelivery {
229            raw_subject: message.subject.to_string(),
230            reason,
231            stream_sequence,
232            message,
233        });
234    }
235    let delivered_count = metadata.expect("validated metadata").delivered;
236    EventItem::Delivery(EventDelivery {
237        subject: subject.expect("validated subject"),
238        msg_id: msg_id.expect("validated msg id"),
239        body: message.payload.clone(),
240        stream_sequence: stream_sequence.expect("validated sequence"),
241        delivered_count,
242        headers,
243        message,
244    })
245}