use crate::outbound::events::{report, OutboundEvent};
use alloc::boxed::Box;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::future::poll_fn;
use core::task::{Context, Poll};
use super::ready::{Polled, ReadyRoutes};
use super::RouteId;
use crate::connector::SerializeError;
use crate::transport::ConnectorConfig;
use crate::{AimDb, DbError, DbResult, RuntimeContext};
#[derive(Debug, Clone)]
pub struct RouteInfo {
pub id: RouteId,
pub type_id: core::any::TypeId,
pub default_topic: Arc<str>,
pub record_index: usize,
pub config: ConnectorConfig,
pub topic_capacity: usize,
pub payload_capacity: usize,
}
#[derive(Debug)]
pub struct OutboundMessage<'a> {
pub route: &'a RouteInfo,
pub topic: &'a str,
pub payload: OutboundPayload<'a>,
pub metadata: crate::WriteMetadata,
}
impl OutboundMessage<'_> {
pub fn stamp(&self) -> crate::Stamp {
self.metadata.stamp()
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum OutboundPayload<'a> {
Borrowed(&'a [u8]),
Owned(Vec<u8>),
}
impl OutboundPayload<'_> {
pub fn as_slice(&self) -> &[u8] {
match self {
Self::Borrowed(bytes) => bytes,
Self::Owned(bytes) => bytes,
}
}
pub fn into_vec(self) -> Vec<u8> {
match self {
Self::Borrowed(bytes) => bytes.to_vec(),
Self::Owned(bytes) => bytes,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RouteStats {
pub sent: u64,
pub rejected: u64,
pub lagged: u64,
pub topic_overflow: u64,
pub serialize_failed: u64,
}
pub(crate) enum RouteOutcome {
Staged {
topic_len: Option<usize>,
payload: StagedPayload,
metadata: crate::WriteMetadata,
},
Lagged(u64),
TopicOverflow,
SerializeFailed(SerializeFailure),
Closed(DbError),
}
pub(crate) enum StagedPayload {
Scratch(usize),
Owned(Vec<u8>),
}
#[derive(Debug)]
pub(crate) enum SerializeFailure {
Owned(SerializeError),
Into(SerializeError),
Fallback(SerializeError),
InvalidLength { len: usize, capacity: usize },
}
#[cfg(feature = "defmt")]
impl defmt::Format for SerializeFailure {
fn format(&self, f: defmt::Formatter) {
defmt::write!(f, "{}", defmt::Display2Format(self))
}
}
impl core::fmt::Display for SerializeFailure {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Owned(e) => write!(f, "serializer failed: {e:?}"),
Self::Into(e) => write!(f, "serializer failed into scratch: {e:?}"),
Self::Fallback(e) => write!(
f,
"value did not fit the scratch and the owned fallback failed: {e:?}"
),
Self::InvalidLength { len, capacity } => write!(
f,
"serializer returned invalid length {len} for {capacity}-byte scratch"
),
}
}
}
pub(crate) trait PollRoute: Send {
fn poll_route(
&mut self,
cx: &mut Context<'_>,
ctx: &RuntimeContext,
topic: &mut [u8],
payload: &mut [u8],
) -> Poll<RouteOutcome>;
}
pub(crate) struct RouteParts {
pub(crate) route: Box<dyn PollRoute>,
pub(crate) topic_capacity: usize,
pub(crate) payload_capacity: usize,
}
pub(crate) type RouteFactoryFn = Arc<dyn Fn(&AimDb) -> RouteParts + Send + Sync>;
struct Staged {
id: RouteId,
topic_len: Option<usize>,
payload: StagedPayload,
metadata: crate::WriteMetadata,
}
pub struct OutboundRoutes {
routes: Box<[RouteInfo]>,
states: Box<[Box<dyn PollRoute>]>,
stats: Box<[RouteStats]>,
ready: ReadyRoutes,
scratch: Box<[u8]>,
topic_region: usize,
staged: Option<Staged>,
ctx: RuntimeContext,
}
const _: fn() = || {
fn assert_send<T: Send>() {}
assert_send::<OutboundRoutes>();
};
impl OutboundRoutes {
pub fn new(db: &AimDb, scheme: &str) -> DbResult<Self> {
let mut routes = Vec::new();
let mut states = Vec::new();
for (record_index, type_id, link) in db.outbound_links(scheme) {
let parts = (link.route_factory)(db);
routes.push(RouteInfo {
id: routes.len(),
type_id,
default_topic: Arc::from(link.url.resource_id()),
record_index,
config: ConnectorConfig::from_query(&link.config),
topic_capacity: parts.topic_capacity,
payload_capacity: parts.payload_capacity,
});
states.push(parts.route);
}
let topic_region = routes.iter().map(|r| r.topic_capacity).max().unwrap_or(0);
let payload_region = routes.iter().map(|r| r.payload_capacity).max().unwrap_or(0);
Ok(Self {
stats: alloc::vec![RouteStats::default(); routes.len()].into_boxed_slice(),
ready: ReadyRoutes::new(routes.len()),
routes: routes.into_boxed_slice(),
states: states.into_boxed_slice(),
scratch: alloc::vec![0; topic_region + payload_region].into_boxed_slice(),
topic_region,
staged: None,
ctx: db.runtime_ctx(),
})
}
pub fn routes(&self) -> &[RouteInfo] {
&self.routes
}
pub fn stats(&self, id: RouteId) -> Option<RouteStats> {
self.stats.get(id).copied()
}
pub fn poll_stage(&mut self, cx: &mut Context<'_>) -> Poll<Option<RouteId>> {
if let Some(staged) = &self.staged {
return Poll::Ready(Some(staged.id));
}
let Self {
routes,
states,
stats,
ready,
scratch,
topic_region,
staged,
ctx,
} = self;
let (topic_buf, payload_buf) = scratch.split_at_mut(*topic_region);
ready.poll_ready(cx, |id, route_cx| {
let info = &routes[id];
let topic = &mut topic_buf[..info.topic_capacity];
let payload = &mut payload_buf[..info.payload_capacity];
let stats = &mut stats[id];
match states[id].poll_route(route_cx, ctx, topic, payload) {
Poll::Pending => Polled::Pending,
Poll::Ready(RouteOutcome::Staged {
topic_len,
payload,
metadata,
}) => {
stats.sent += 1;
*staged = Some(Staged {
id,
topic_len,
payload,
metadata,
});
Polled::Staged
}
Poll::Ready(RouteOutcome::Lagged(n)) => {
stats.lagged += n;
report(OutboundEvent::Lagged {
topic: &info.default_topic,
skipped: n,
});
Polled::Skipped
}
Poll::Ready(RouteOutcome::TopicOverflow) => {
stats.topic_overflow += 1;
report(OutboundEvent::TopicOverflow {
topic: &info.default_topic,
capacity: info.topic_capacity,
});
Polled::Skipped
}
Poll::Ready(RouteOutcome::SerializeFailed(_failure)) => {
stats.serialize_failed += 1;
report(OutboundEvent::SerializeFailed {
topic: &info.default_topic,
error: &_failure,
});
Polled::Skipped
}
Poll::Ready(RouteOutcome::Closed(_e)) => {
report(OutboundEvent::Closed {
topic: &info.default_topic,
error: &_e,
});
Polled::Closed
}
}
})
}
pub fn take_staged(&mut self) -> Option<OutboundMessage<'_>> {
let staged = self.staged.take()?;
let route = &self.routes[staged.id];
let (topic_buf, payload_buf) = self.scratch.split_at(self.topic_region);
let topic = match staged.topic_len {
Some(len) => core::str::from_utf8(&topic_buf[..len]).unwrap_or_default(),
None => &route.default_topic,
};
let payload = match staged.payload {
StagedPayload::Scratch(len) => OutboundPayload::Borrowed(&payload_buf[..len]),
StagedPayload::Owned(bytes) => OutboundPayload::Owned(bytes),
};
Some(OutboundMessage {
route,
topic,
payload,
metadata: staged.metadata,
})
}
pub fn reject(&mut self, id: RouteId) {
if let Some(stats) = self.stats.get_mut(id) {
stats.rejected += 1;
}
}
pub fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<OutboundMessage<'_>>> {
match self.poll_stage(cx) {
Poll::Ready(Some(_)) => Poll::Ready(self.take_staged()),
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
}
pub async fn next(&mut self) -> Option<OutboundMessage<'_>> {
poll_fn(|cx| self.poll_stage(cx)).await?;
self.take_staged()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn payload_helpers_cover_both_variants() {
let scratch = [1u8, 2, 3];
assert_eq!(OutboundPayload::Borrowed(&scratch).as_slice(), [1, 2, 3]);
assert_eq!(OutboundPayload::Borrowed(&scratch).into_vec(), [1, 2, 3]);
let owned = alloc::vec![4u8, 5];
let ptr = owned.as_ptr();
let payload = OutboundPayload::Owned(owned);
assert_eq!(payload.as_slice(), [4, 5]);
let moved = payload.into_vec();
assert_eq!(moved.as_ptr(), ptr, "moved, not copied");
}
#[tokio::test]
async fn reject_counts_beside_the_routes_other_outcomes() {
let (db, _runner) = crate::AimDbBuilder::new()
.runtime(Arc::new(crate::executor::test_support::NoopRuntimeOps))
.build()
.await
.expect("empty database");
let mut routes = OutboundRoutes::new(&db, "mqtt").unwrap();
routes.reject(0);
assert_eq!(routes.stats(0), None);
}
}