Skip to main content

aimdb_core/outbound/
routes.rs

1//! [`OutboundRoutes`]: every outbound link of one scheme, pulled by the
2//! connector's transport task.
3
4use crate::outbound::events::{report, OutboundEvent};
5
6use alloc::boxed::Box;
7use alloc::sync::Arc;
8use alloc::vec::Vec;
9use core::future::poll_fn;
10use core::task::{Context, Poll};
11
12use super::ready::{Polled, ReadyRoutes};
13use super::RouteId;
14use crate::connector::SerializeError;
15use crate::transport::ConnectorConfig;
16use crate::{AimDb, DbError, DbResult, RuntimeContext};
17
18/// One outbound route, for parsing per-route configuration once at build.
19#[derive(Debug, Clone)]
20pub struct RouteInfo {
21    /// Dense index, `0..routes().len()`.
22    pub id: RouteId,
23    /// `TypeId` of the record the link belongs to.
24    pub type_id: core::any::TypeId,
25    /// The topic from the link URL, used when no topic is written.
26    pub default_topic: Arc<str>,
27    /// Index of the record the link belongs to, in registration order (the
28    /// record's `RecordId`). Set by core, never from the link's query.
29    pub record_index: usize,
30    /// The link's configuration.
31    pub config: ConnectorConfig,
32    /// Longest topic the link's writer produces; 0 without a writer.
33    pub topic_capacity: usize,
34    /// Scratch for `with_serializer_into`; 0 with an owned serializer only.
35    pub payload_capacity: usize,
36}
37
38/// A message pulled from [`OutboundRoutes`].
39#[derive(Debug)]
40pub struct OutboundMessage<'a> {
41    /// The route it came from.
42    pub route: &'a RouteInfo,
43    /// The written topic, or the route's default.
44    pub topic: &'a str,
45    /// The serialized value.
46    pub payload: OutboundPayload<'a>,
47    /// Metadata of the write the route serialized.
48    pub metadata: crate::WriteMetadata,
49}
50
51impl OutboundMessage<'_> {
52    /// When the serialized value was written, on the instance clock.
53    pub fn stamp(&self) -> crate::Stamp {
54        self.metadata.stamp()
55    }
56}
57
58/// Where a pulled message's bytes are.
59#[derive(Debug, PartialEq, Eq)]
60pub enum OutboundPayload<'a> {
61    /// Serialized into `OutboundRoutes`' scratch (`with_serializer_into`).
62    Borrowed(&'a [u8]),
63    /// An owned serializer's bytes (`with_serializer`). Transports that take
64    /// ownership move it in; others borrow it.
65    Owned(Vec<u8>),
66}
67
68impl OutboundPayload<'_> {
69    /// The bytes, whichever variant holds them.
70    pub fn as_slice(&self) -> &[u8] {
71        match self {
72            Self::Borrowed(bytes) => bytes,
73            Self::Owned(bytes) => bytes,
74        }
75    }
76
77    /// The bytes as an owned `Vec`: moved out of `Owned`, copied from
78    /// `Borrowed`.
79    pub fn into_vec(self) -> Vec<u8> {
80        match self {
81            Self::Borrowed(bytes) => bytes.to_vec(),
82            Self::Owned(bytes) => bytes,
83        }
84    }
85}
86
87/// Values taken from one route's buffer, by outcome.
88#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
89pub struct RouteStats {
90    /// Staged and handed to the connector, including any it then rejected.
91    pub sent: u64,
92    /// Handed to the connector, which could not send them (for example,
93    /// larger than its transport accepts). Reported with
94    /// [`OutboundRoutes::reject`].
95    pub rejected: u64,
96    /// Missed because the reader fell behind.
97    pub lagged: u64,
98    /// Skipped: the written topic did not fit.
99    pub topic_overflow: u64,
100    /// Skipped: the serializer failed or reported an invalid length.
101    pub serialize_failed: u64,
102}
103
104/// What polling one route did.
105pub(crate) enum RouteOutcome {
106    /// A value was serialized. `topic_len`: bytes written into the topic
107    /// scratch, `None` for the default topic.
108    Staged {
109        topic_len: Option<usize>,
110        payload: StagedPayload,
111        metadata: crate::WriteMetadata,
112    },
113    /// The reader lagged by this many values.
114    Lagged(u64),
115    /// A value was taken; its topic did not fit.
116    TopicOverflow,
117    /// A value was taken; serializing it failed.
118    SerializeFailed(SerializeFailure),
119    /// The buffer is gone.
120    Closed(DbError),
121}
122
123/// Where a staged payload is.
124pub(crate) enum StagedPayload {
125    /// The first `len` bytes of the payload scratch.
126    Scratch(usize),
127    Owned(Vec<u8>),
128}
129
130/// Why a value that was taken could not be serialized. The caller logs it
131/// with its route.
132#[derive(Debug)]
133pub(crate) enum SerializeFailure {
134    /// The owned serializer (`with_serializer`) failed.
135    Owned(SerializeError),
136    /// `with_serializer_into` failed.
137    Into(SerializeError),
138    /// The value did not fit `with_serializer_into`'s scratch, and the owned
139    /// serializer it fell back to failed.
140    Fallback(SerializeError),
141    /// `with_serializer_into` reported more bytes than its scratch holds.
142    InvalidLength { len: usize, capacity: usize },
143}
144
145// Through `Display`: the variants carry a `SerializeError` and lengths, and
146// one rendering keeps the defmt line identical to the tracing/log one.
147#[cfg(feature = "defmt")]
148impl defmt::Format for SerializeFailure {
149    fn format(&self, f: defmt::Formatter) {
150        defmt::write!(f, "{}", defmt::Display2Format(self))
151    }
152}
153
154impl core::fmt::Display for SerializeFailure {
155    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
156        match self {
157            Self::Owned(e) => write!(f, "serializer failed: {e:?}"),
158            Self::Into(e) => write!(f, "serializer failed into scratch: {e:?}"),
159            Self::Fallback(e) => write!(
160                f,
161                "value did not fit the scratch and the owned fallback failed: {e:?}"
162            ),
163            Self::InvalidLength { len, capacity } => write!(
164                f,
165                "serializer returned invalid length {len} for {capacity}-byte scratch"
166            ),
167        }
168    }
169}
170
171/// A route's typed reader, topic writer and serializers, polled through one
172/// erased call.
173pub(crate) trait PollRoute: Send {
174    /// Poll the reader once with `cx`. On a value, write its topic into
175    /// `topic` and its payload into `payload` (or an owned `Vec`).
176    fn poll_route(
177        &mut self,
178        cx: &mut Context<'_>,
179        ctx: &RuntimeContext,
180        topic: &mut [u8],
181        payload: &mut [u8],
182    ) -> Poll<RouteOutcome>;
183}
184
185/// What a link's route factory builds.
186pub(crate) struct RouteParts {
187    pub(crate) route: Box<dyn PollRoute>,
188    pub(crate) topic_capacity: usize,
189    pub(crate) payload_capacity: usize,
190}
191
192/// Builds a link's [`RouteParts`], subscribing to its record.
193pub(crate) type RouteFactoryFn = Arc<dyn Fn(&AimDb) -> RouteParts + Send + Sync>;
194
195struct Staged {
196    id: RouteId,
197    topic_len: Option<usize>,
198    payload: StagedPayload,
199    metadata: crate::WriteMetadata,
200}
201
202/// Every outbound link of one scheme, read by the connector's transport task.
203///
204/// Built in the connector's `build()`: cursors start then, so an SPMC ring
205/// keeps what is produced before the transport first polls. Only routes
206/// whose readers woke are polled, in round-robin order.
207pub struct OutboundRoutes {
208    routes: Box<[RouteInfo]>,
209    states: Box<[Box<dyn PollRoute>]>,
210    stats: Box<[RouteStats]>,
211    ready: ReadyRoutes,
212    /// Topic region (`topic_region` bytes), then payload region.
213    scratch: Box<[u8]>,
214    topic_region: usize,
215    staged: Option<Staged>,
216    ctx: RuntimeContext,
217}
218
219// Moved into the connector's `Send` transport task.
220const _: fn() = || {
221    fn assert_send<T: Send>() {}
222    assert_send::<OutboundRoutes>();
223};
224
225impl OutboundRoutes {
226    /// Subscribes every outbound link of `scheme` and allocates the scratch
227    /// once: the largest topic capacity plus the largest payload capacity.
228    pub fn new(db: &AimDb, scheme: &str) -> DbResult<Self> {
229        let mut routes = Vec::new();
230        let mut states = Vec::new();
231
232        for (record_index, type_id, link) in db.outbound_links(scheme) {
233            let parts = (link.route_factory)(db);
234            routes.push(RouteInfo {
235                id: routes.len(),
236                type_id,
237                default_topic: Arc::from(link.url.resource_id()),
238                record_index,
239                config: ConnectorConfig::from_query(&link.config),
240                topic_capacity: parts.topic_capacity,
241                payload_capacity: parts.payload_capacity,
242            });
243            states.push(parts.route);
244        }
245
246        let topic_region = routes.iter().map(|r| r.topic_capacity).max().unwrap_or(0);
247        let payload_region = routes.iter().map(|r| r.payload_capacity).max().unwrap_or(0);
248        Ok(Self {
249            stats: alloc::vec![RouteStats::default(); routes.len()].into_boxed_slice(),
250            ready: ReadyRoutes::new(routes.len()),
251            routes: routes.into_boxed_slice(),
252            states: states.into_boxed_slice(),
253            scratch: alloc::vec![0; topic_region + payload_region].into_boxed_slice(),
254            topic_region,
255            staged: None,
256            ctx: db.runtime_ctx(),
257        })
258    }
259
260    /// Routes, for parsing per-route configuration once at build.
261    pub fn routes(&self) -> &[RouteInfo] {
262        &self.routes
263    }
264
265    /// Values taken from route `id`'s buffer so far, by outcome.
266    pub fn stats(&self, id: RouteId) -> Option<RouteStats> {
267        self.stats.get(id).copied()
268    }
269
270    /// Take the next ready value from a route that woke and serialize it into
271    /// the scratch. Lends nothing.
272    ///
273    /// - `Ready(Some(id))`: a message from route `id` is staged; take it with
274    ///   [`take_staged`](Self::take_staged). A staged message that was never
275    ///   taken is returned again, not replaced.
276    /// - `Ready(None)`: every route is closed, or there were none. Final: a
277    ///   `select` arm must be disarmed after it.
278    /// - `Pending`: no woken route had a value. On Tokio this can also mean
279    ///   the task's budget is spent; the task is woken to try again.
280    ///
281    /// A value leaves its buffer only in a call that returns `Ready`, so this
282    /// is safe as a `select` arm. Skipped values (topic overflow, serializer
283    /// error) and lag are logged and counted in [`stats`](Self::stats).
284    pub fn poll_stage(&mut self, cx: &mut Context<'_>) -> Poll<Option<RouteId>> {
285        if let Some(staged) = &self.staged {
286            return Poll::Ready(Some(staged.id));
287        }
288        let Self {
289            routes,
290            states,
291            stats,
292            ready,
293            scratch,
294            topic_region,
295            staged,
296            ctx,
297        } = self;
298        let (topic_buf, payload_buf) = scratch.split_at_mut(*topic_region);
299        ready.poll_ready(cx, |id, route_cx| {
300            let info = &routes[id];
301            let topic = &mut topic_buf[..info.topic_capacity];
302            let payload = &mut payload_buf[..info.payload_capacity];
303            let stats = &mut stats[id];
304            match states[id].poll_route(route_cx, ctx, topic, payload) {
305                Poll::Pending => Polled::Pending,
306                Poll::Ready(RouteOutcome::Staged {
307                    topic_len,
308                    payload,
309                    metadata,
310                }) => {
311                    stats.sent += 1;
312                    *staged = Some(Staged {
313                        id,
314                        topic_len,
315                        payload,
316                        metadata,
317                    });
318                    Polled::Staged
319                }
320                Poll::Ready(RouteOutcome::Lagged(n)) => {
321                    stats.lagged += n;
322                    report(OutboundEvent::Lagged {
323                        topic: &info.default_topic,
324                        skipped: n,
325                    });
326                    Polled::Skipped
327                }
328                Poll::Ready(RouteOutcome::TopicOverflow) => {
329                    stats.topic_overflow += 1;
330                    report(OutboundEvent::TopicOverflow {
331                        topic: &info.default_topic,
332                        capacity: info.topic_capacity,
333                    });
334                    Polled::Skipped
335                }
336                Poll::Ready(RouteOutcome::SerializeFailed(_failure)) => {
337                    stats.serialize_failed += 1;
338                    report(OutboundEvent::SerializeFailed {
339                        topic: &info.default_topic,
340                        error: &_failure,
341                    });
342                    Polled::Skipped
343                }
344                Poll::Ready(RouteOutcome::Closed(_e)) => {
345                    report(OutboundEvent::Closed {
346                        topic: &info.default_topic,
347                        error: &_e,
348                    });
349                    Polled::Closed
350                }
351            }
352        })
353    }
354
355    /// Lend the staged message and clear it. `None` if nothing is staged.
356    pub fn take_staged(&mut self) -> Option<OutboundMessage<'_>> {
357        let staged = self.staged.take()?;
358        let route = &self.routes[staged.id];
359        let (topic_buf, payload_buf) = self.scratch.split_at(self.topic_region);
360        let topic = match staged.topic_len {
361            // Written through `TopicBuf`, which only ever holds whole `&str`s.
362            Some(len) => core::str::from_utf8(&topic_buf[..len]).unwrap_or_default(),
363            None => &route.default_topic,
364        };
365        let payload = match staged.payload {
366            StagedPayload::Scratch(len) => OutboundPayload::Borrowed(&payload_buf[..len]),
367            StagedPayload::Owned(bytes) => OutboundPayload::Owned(bytes),
368        };
369        Some(OutboundMessage {
370            route,
371            topic,
372            payload,
373            metadata: staged.metadata,
374        })
375    }
376
377    /// Count a message from route `id` that the connector took but could not
378    /// send. The connector logs why; this keeps the count beside the route's
379    /// other outcomes.
380    pub fn reject(&mut self, id: RouteId) {
381        if let Some(stats) = self.stats.get_mut(id) {
382            stats.rejected += 1;
383        }
384    }
385
386    /// [`poll_stage`](Self::poll_stage), then [`take_staged`](Self::take_staged),
387    /// for hand-written `poll` code.
388    pub fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<OutboundMessage<'_>>> {
389        match self.poll_stage(cx) {
390            Poll::Ready(Some(_)) => Poll::Ready(self.take_staged()),
391            Poll::Ready(None) => Poll::Ready(None),
392            Poll::Pending => Poll::Pending,
393        }
394    }
395
396    /// The next message, or `None` once every route is closed.
397    ///
398    /// Cancel-safe: dropping the future before it completes takes nothing.
399    pub async fn next(&mut self) -> Option<OutboundMessage<'_>> {
400        poll_fn(|cx| self.poll_stage(cx)).await?;
401        self.take_staged()
402    }
403}
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408
409    #[test]
410    fn payload_helpers_cover_both_variants() {
411        let scratch = [1u8, 2, 3];
412        assert_eq!(OutboundPayload::Borrowed(&scratch).as_slice(), [1, 2, 3]);
413        assert_eq!(OutboundPayload::Borrowed(&scratch).into_vec(), [1, 2, 3]);
414
415        let owned = alloc::vec![4u8, 5];
416        let ptr = owned.as_ptr();
417        let payload = OutboundPayload::Owned(owned);
418        assert_eq!(payload.as_slice(), [4, 5]);
419        let moved = payload.into_vec();
420        assert_eq!(moved.as_ptr(), ptr, "moved, not copied");
421    }
422
423    #[tokio::test]
424    async fn reject_counts_beside_the_routes_other_outcomes() {
425        let (db, _runner) = crate::AimDbBuilder::new()
426            .runtime(Arc::new(crate::executor::test_support::NoopRuntimeOps))
427            .build()
428            .await
429            .expect("empty database");
430        let mut routes = OutboundRoutes::new(&db, "mqtt").unwrap();
431        // No routes: an unknown id is ignored rather than a panic.
432        routes.reject(0);
433        assert_eq!(routes.stats(0), None);
434    }
435}