1use 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#[derive(Debug, Clone)]
20pub struct RouteInfo {
21 pub id: RouteId,
23 pub type_id: core::any::TypeId,
25 pub default_topic: Arc<str>,
27 pub record_index: usize,
30 pub config: ConnectorConfig,
32 pub topic_capacity: usize,
34 pub payload_capacity: usize,
36}
37
38#[derive(Debug)]
40pub struct OutboundMessage<'a> {
41 pub route: &'a RouteInfo,
43 pub topic: &'a str,
45 pub payload: OutboundPayload<'a>,
47 pub metadata: crate::WriteMetadata,
49}
50
51impl OutboundMessage<'_> {
52 pub fn stamp(&self) -> crate::Stamp {
54 self.metadata.stamp()
55 }
56}
57
58#[derive(Debug, PartialEq, Eq)]
60pub enum OutboundPayload<'a> {
61 Borrowed(&'a [u8]),
63 Owned(Vec<u8>),
66}
67
68impl OutboundPayload<'_> {
69 pub fn as_slice(&self) -> &[u8] {
71 match self {
72 Self::Borrowed(bytes) => bytes,
73 Self::Owned(bytes) => bytes,
74 }
75 }
76
77 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
89pub struct RouteStats {
90 pub sent: u64,
92 pub rejected: u64,
96 pub lagged: u64,
98 pub topic_overflow: u64,
100 pub serialize_failed: u64,
102}
103
104pub(crate) enum RouteOutcome {
106 Staged {
109 topic_len: Option<usize>,
110 payload: StagedPayload,
111 metadata: crate::WriteMetadata,
112 },
113 Lagged(u64),
115 TopicOverflow,
117 SerializeFailed(SerializeFailure),
119 Closed(DbError),
121}
122
123pub(crate) enum StagedPayload {
125 Scratch(usize),
127 Owned(Vec<u8>),
128}
129
130#[derive(Debug)]
133pub(crate) enum SerializeFailure {
134 Owned(SerializeError),
136 Into(SerializeError),
138 Fallback(SerializeError),
141 InvalidLength { len: usize, capacity: usize },
143}
144
145#[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
171pub(crate) trait PollRoute: Send {
174 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
185pub(crate) struct RouteParts {
187 pub(crate) route: Box<dyn PollRoute>,
188 pub(crate) topic_capacity: usize,
189 pub(crate) payload_capacity: usize,
190}
191
192pub(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
202pub struct OutboundRoutes {
208 routes: Box<[RouteInfo]>,
209 states: Box<[Box<dyn PollRoute>]>,
210 stats: Box<[RouteStats]>,
211 ready: ReadyRoutes,
212 scratch: Box<[u8]>,
214 topic_region: usize,
215 staged: Option<Staged>,
216 ctx: RuntimeContext,
217}
218
219const _: fn() = || {
221 fn assert_send<T: Send>() {}
222 assert_send::<OutboundRoutes>();
223};
224
225impl OutboundRoutes {
226 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 pub fn routes(&self) -> &[RouteInfo] {
262 &self.routes
263 }
264
265 pub fn stats(&self, id: RouteId) -> Option<RouteStats> {
267 self.stats.get(id).copied()
268 }
269
270 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 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 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 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 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 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 routes.reject(0);
433 assert_eq!(routes.stats(0), None);
434 }
435}