pub mod claim;
pub mod client;
pub mod coordinator;
pub mod net;
pub mod network;
pub mod ship;
pub use net::{Durability, Qos, Reliability};
pub const HEARTBEAT_INTERVAL_MS: u64 = 400;
pub const HEARTBEAT_SUPPRESS_MS: u64 = HEARTBEAT_INTERVAL_MS / 2;
pub const DISCONNECT_TIMEOUT_MS: u64 = HEARTBEAT_INTERVAL_MS * 2;
pub const REGISTRATION_TIMEOUT_MS: u64 = 2000;
pub const PEER_DEAD_THRESHOLD: u32 = 3;
#[derive(Debug, Clone, Copy, Default)]
pub struct NodeOptions {
pub timing: Timing,
pub reconnect: Option<ReconnectPolicy>,
pub bypass_route_cache: bool,
}
impl NodeOptions {
pub fn wan() -> Self {
Self {
timing: Timing::wan(),
reconnect: Some(ReconnectPolicy::always()),
bypass_route_cache: false,
}
}
pub fn with_route_cache_bypassed(mut self) -> Self {
self.bypass_route_cache = true;
self
}
pub fn with_timing(mut self, timing: Timing) -> Self {
self.timing = timing;
self
}
pub fn with_reconnect(mut self, reconnect: ReconnectPolicy) -> Self {
self.reconnect = Some(reconnect);
self
}
pub fn reconnect_policy(&self, qos: Qos) -> ReconnectPolicy {
self.reconnect
.unwrap_or_else(|| ReconnectPolicy::for_qos(qos))
}
}
#[derive(Debug)]
pub struct ConnectionState {
generation: std::sync::atomic::AtomicU64,
connected: std::sync::atomic::AtomicBool,
link_proven: std::sync::atomic::AtomicBool,
heartbeating: std::sync::atomic::AtomicBool,
announce: tokio::sync::broadcast::Sender<u64>,
}
impl Default for ConnectionState {
fn default() -> Self {
Self::new()
}
}
impl ConnectionState {
pub fn new() -> Self {
let (announce, _) = tokio::sync::broadcast::channel(16);
Self {
generation: std::sync::atomic::AtomicU64::new(0),
connected: std::sync::atomic::AtomicBool::new(true),
link_proven: std::sync::atomic::AtomicBool::new(false),
heartbeating: std::sync::atomic::AtomicBool::new(false),
announce,
}
}
pub fn for_session(shutdown: tokio_util::sync::CancellationToken) -> std::sync::Arc<Self> {
let state = std::sync::Arc::new(Self::new());
state.mark_link_proven();
let watcher = std::sync::Arc::clone(&state);
tokio::spawn(async move {
shutdown.cancelled().await;
watcher.mark_disconnected();
});
state
}
pub fn generation(&self) -> u64 {
self.generation.load(std::sync::atomic::Ordering::Acquire)
}
pub fn is_connected(&self) -> bool {
self.connected.load(std::sync::atomic::Ordering::Acquire)
}
pub fn subscribe(&self) -> tokio::sync::broadcast::Receiver<u64> {
self.announce.subscribe()
}
pub fn is_link_proven(&self) -> bool {
self.link_proven.load(std::sync::atomic::Ordering::Acquire)
}
pub fn is_heartbeating(&self) -> bool {
self.heartbeating.load(std::sync::atomic::Ordering::Acquire)
}
pub(crate) fn mark_heartbeating(&self) {
self.heartbeating
.store(true, std::sync::atomic::Ordering::Release);
}
pub(crate) fn mark_link_proven(&self) {
self.link_proven
.store(true, std::sync::atomic::Ordering::Release);
}
pub(crate) fn mark_link_unproven(&self) {
self.link_proven
.store(false, std::sync::atomic::Ordering::Release);
}
pub(crate) fn mark_disconnected(&self) {
self.mark_link_unproven();
self.connected
.store(false, std::sync::atomic::Ordering::Release);
}
pub(crate) fn mark_reconnected(&self) -> u64 {
let generation = self
.generation
.fetch_add(1, std::sync::atomic::Ordering::AcqRel)
+ 1;
self.connected
.store(true, std::sync::atomic::Ordering::Release);
let _ = self.announce.send(generation);
generation
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ReconnectPolicy {
#[default]
Never,
Always {
initial_backoff_ms: u64,
max_backoff_ms: u64,
},
}
impl ReconnectPolicy {
pub fn always() -> Self {
Self::Always {
initial_backoff_ms: 250,
max_backoff_ms: 10_000,
}
}
pub fn is_enabled(self) -> bool {
matches!(self, Self::Always { .. })
}
pub fn for_qos(qos: Qos) -> Self {
if qos.fires_torpedo() {
Self::Never
} else {
Self::always()
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Timing {
pub heartbeat_interval_ms: u64,
pub heartbeat_suppress_ms: u64,
pub disconnect_timeout_ms: u64,
pub registration_timeout_ms: u64,
pub peer_dead_threshold: u32,
}
impl Default for Timing {
fn default() -> Self {
Self {
heartbeat_interval_ms: HEARTBEAT_INTERVAL_MS,
heartbeat_suppress_ms: HEARTBEAT_SUPPRESS_MS,
disconnect_timeout_ms: DISCONNECT_TIMEOUT_MS,
registration_timeout_ms: REGISTRATION_TIMEOUT_MS,
peer_dead_threshold: PEER_DEAD_THRESHOLD,
}
}
}
impl Timing {
pub fn wan() -> Self {
Self {
heartbeat_interval_ms: 2_000,
heartbeat_suppress_ms: 1_000,
disconnect_timeout_ms: 10_000,
registration_timeout_ms: 15_000,
peer_dead_threshold: 3,
}
}
pub fn validate(&self) -> anyhow::Result<()> {
if self.heartbeat_interval_ms == 0 {
anyhow::bail!("Timing::heartbeat_interval_ms must be greater than zero");
}
if self.heartbeat_suppress_ms > self.heartbeat_interval_ms {
anyhow::bail!(
"Timing::heartbeat_suppress_ms ({}) must be <= heartbeat_interval_ms ({}), \
otherwise a heartbeat can be suppressed past the disconnect timeout",
self.heartbeat_suppress_ms,
self.heartbeat_interval_ms
);
}
if self.disconnect_timeout_ms <= self.heartbeat_interval_ms + self.heartbeat_suppress_ms {
anyhow::bail!(
"Timing::disconnect_timeout_ms ({}) must be > heartbeat_interval_ms + \
heartbeat_suppress_ms ({}), otherwise healthy nodes are declared dead",
self.disconnect_timeout_ms,
self.heartbeat_interval_ms + self.heartbeat_suppress_ms
);
}
if self.peer_dead_threshold == 0 {
anyhow::bail!("Timing::peer_dead_threshold must be greater than zero");
}
Ok(())
}
pub fn heartbeat_interval(&self) -> std::time::Duration {
std::time::Duration::from_millis(self.heartbeat_interval_ms)
}
pub fn heartbeat_suppress(&self) -> std::time::Duration {
std::time::Duration::from_millis(self.heartbeat_suppress_ms)
}
pub fn disconnect_timeout(&self) -> std::time::Duration {
std::time::Duration::from_millis(self.disconnect_timeout_ms)
}
pub fn registration_timeout(&self) -> std::time::Duration {
std::time::Duration::from_millis(self.registration_timeout_ms)
}
}
pub const TRY_RELIABLE_SEND_BUDGET_MS: u64 = 3000;
pub const COORD_CLIENT_IDLE_TIMEOUT_MS: u64 = 30_000;
use mt_net::{ActionPlan, BagMsg, Rules, VariableHuman};
pub struct ArchivedMessage<T: Archive> {
bytes: AlignedVec,
_type: std::marker::PhantomData<fn() -> T>,
}
impl<T> std::fmt::Debug for ArchivedMessage<T>
where
T: Archive,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ArchivedMessage")
.field("len", &self.bytes.len())
.finish_non_exhaustive()
}
}
impl<T> ArchivedMessage<T>
where
T: Archive,
T::Archived: for<'a> CheckBytes<HighValidator<'a, rkyv::rancor::Error>>,
{
pub fn from_aligned_bytes(bytes: AlignedVec) -> anyhow::Result<Self> {
rkyv::access::<T::Archived, rkyv::rancor::Error>(&bytes)
.map_err(|error| anyhow::anyhow!("Could not validate archived message: {error}"))?;
Ok(Self {
bytes,
_type: std::marker::PhantomData,
})
}
pub fn archived(&self) -> &T::Archived {
unsafe { rkyv::access_unchecked::<T::Archived>(&self.bytes) }
}
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
pub fn len(&self) -> usize {
self.bytes.len()
}
pub fn is_empty(&self) -> bool {
self.bytes.is_empty()
}
}
impl<T> ArchivedMessage<T>
where
T: Archive,
T::Archived: for<'a> CheckBytes<HighValidator<'a, rkyv::rancor::Error>>
+ Deserialize<T, Strategy<Pool, rkyv::rancor::Error>>,
{
pub fn deserialize(&self) -> anyhow::Result<T> {
let mut pool = Pool::new();
self.archived()
.deserialize(Strategy::wrap(&mut pool))
.map_err(|error| anyhow::anyhow!("Could not deserialize archived message: {error}"))
}
}
pub fn init_logging() {
mt_log::init_filtered("Minot", "RUST_LOG", "info", mt_log::QUIET_ZENOH);
}
use rkyv::{
Archive, Deserialize, Serialize,
api::high::{HighSerializer, HighValidator},
bytecheck::CheckBytes,
de::Pool,
rancor::Strategy,
ser::allocator::ArenaHandle,
util::AlignedVec,
};
#[derive(Debug, Clone, PartialEq, Archive, Serialize, Deserialize, Hash, Eq, PartialOrd, Ord)]
pub enum ShipKind {
Rat(String),
Wind(String),
}
pub type ShipName = i128;
#[derive(Debug, Clone, Serialize, Deserialize, Archive, PartialEq, Eq)]
pub struct NetworkShipAddress {
ip: [u8; 4],
pub port: u16,
ship: ShipName,
pub kind: ShipKind,
pub node_mode: net::Qos,
}
#[derive(Debug, Archive, Clone, Default, Serialize, Deserialize)]
pub enum Action {
#[default]
Sail,
Shoot {
target: Vec<NetworkShipAddress>,
id: u32,
},
Catch {
source: NetworkShipAddress,
id: u32,
},
}
#[derive(Clone, Debug)]
pub struct Variable {
pub ship: ShipName,
pub strategy: Option<Action>,
}
pub fn get_strategies(
haystack: &Rules,
rat_ship: &str,
variable: String,
indirect_parent_rat: Option<&str>,
) -> Vec<ActionPlan> {
match haystack.raw().get(&variable) {
None => vec![ActionPlan::default()],
Some(plans) => {
let directly = plans
.iter()
.filter(|plan| plan.ship == rat_ship)
.filter_map(|el| el.strategy.clone())
.collect::<Vec<_>>();
let mut indirect = plans
.iter()
.filter(|plan| indirect_parent_rat.is_none_or(|parent_rat| plan.ship == parent_rat))
.filter_map(|plan| match plan.strategy.as_ref()? {
ActionPlan::Sail => None,
ActionPlan::Shoot { target, id } => target
.iter()
.find(|shoot_target| *shoot_target == rat_ship)
.map(|_| ActionPlan::Catch {
source: plan.ship.clone(),
id: *id,
}),
ActionPlan::Catch { source, id } => {
if source == rat_ship {
Some(ActionPlan::Shoot {
target: vec![source.clone()],
id: *id,
})
} else {
None
}
}
})
.collect::<Vec<_>>();
indirect.extend(directly);
indirect
}
}
}
#[async_trait::async_trait]
pub trait Ship: Send + Sync + 'static {
async fn ask_for_action(&self, variable_name: &str) -> anyhow::Result<(Action, bool)>;
async fn wait_for_wind(&self) -> anyhow::Result<Vec<WindData>>;
fn get_cannon(&self) -> &impl Cannon;
}
#[derive(Archive, Serialize, Deserialize, Debug, Clone, Copy, Default)]
pub enum VariableType {
#[default]
StaticOnly, U8,
I32,
F32,
F64,
}
impl From<u8> for VariableType {
fn from(value: u8) -> Self {
match value {
1 => Self::U8,
2 => Self::I32,
3 => Self::F32,
4 => Self::F64,
_ => Self::default(),
}
}
}
impl From<VariableType> for u8 {
fn from(value: VariableType) -> Self {
match value {
VariableType::StaticOnly => 0,
VariableType::U8 => 1,
VariableType::I32 => 2,
VariableType::F32 => 3,
VariableType::F64 => 4,
}
}
}
use rkyv::rancor::Error as RkyvError;
pub trait Sendable: Sized + Send + Sync + 'static
where
Self: for<'b> Serialize<HighSerializer<AlignedVec, ArenaHandle<'b>, RkyvError>>,
Self: Archive<
Archived: for<'a> CheckBytes<HighValidator<'a, rkyv::rancor::Error>>
+ Deserialize<Self, Strategy<Pool, rkyv::rancor::Error>>,
>,
{
}
impl<T> Sendable for T
where
T: Sized + Send + Sync + 'static,
T: for<'b> Serialize<HighSerializer<AlignedVec, ArenaHandle<'b>, RkyvError>>,
T: Archive<
Archived: for<'a> CheckBytes<HighValidator<'a, rkyv::rancor::Error>>
+ Deserialize<T, Strategy<Pool, rkyv::rancor::Error>>,
>,
{
}
#[async_trait::async_trait]
pub trait Cannon: Send + Sync + 'static {
async fn shoot<'b, T: Sendable>(
&self,
targets: &'b [crate::NetworkShipAddress],
id: u32,
data: &T,
variable_type: VariableType,
variable_name: &str,
) -> anyhow::Result<()>;
async fn retain<T: Sendable>(
&self,
data: &T,
variable_type: VariableType,
variable_name: &str,
) -> anyhow::Result<()> {
let _ = (data, variable_type, variable_name);
Ok(())
}
async fn catch<T: Sendable>(&self, id: u32) -> anyhow::Result<Vec<T>>;
async fn catch_archived<T: Sendable>(&self, id: u32)
-> anyhow::Result<Vec<ArchivedMessage<T>>>;
async fn catch_for_variable<T: Sendable>(
&self,
id: u32,
variable_name: &str,
drop_stale: bool,
) -> anyhow::Result<Vec<ArchivedMessage<T>>>;
async fn catch_dyn(&self, id: u32) -> anyhow::Result<Vec<(String, VariableType, String)>>;
}
#[derive(Clone, Debug, Default, Copy, Archive, Serialize, Deserialize, PartialEq)]
pub struct TimeMsg {
pub sec: i32,
pub nanosec: u32,
}
#[derive(Clone, Debug, Default, PartialEq, Archive, Serialize, Deserialize)]
pub struct Header {
pub seq: u32,
pub stamp: TimeMsg,
pub frame_id: String,
}
pub type WindData = BagMsg;
#[async_trait::async_trait]
pub trait Coordinator: Send + Sync + 'static {
async fn rat_action_request_queue(
&self,
ship: String,
) -> anyhow::Result<tokio::sync::broadcast::Receiver<String>>;
async fn blow_wind(&self, ship: String, data: Vec<WindData>) -> anyhow::Result<()>;
async fn rat_action_send(
&self,
ship: String,
variable: String,
action: ActionPlan,
lock_until_ack: bool,
best_effort: bool,
) -> anyhow::Result<()>;
async fn push_planned_routes(
&self,
variable: &str,
plans: Vec<(String, Vec<ActionPlan>)>,
) -> anyhow::Result<()>;
}
pub fn plan_routes_for_var(rules: &Rules, variable: &str) -> Vec<(String, Vec<ActionPlan>)> {
rules
.all_ships_for_var(variable)
.into_iter()
.map(|ship| {
let actions = get_strategies(rules, &ship, variable.to_string(), None);
(ship, actions)
})
.collect()
}
pub fn changed_routes(
before: &[(String, Vec<ActionPlan>)],
after: Vec<(String, Vec<ActionPlan>)>,
always: Option<&str>,
) -> Vec<(String, Vec<ActionPlan>)> {
after
.into_iter()
.filter(|(ship, actions)| {
Some(ship.as_str()) == always
|| before
.iter()
.find(|(b, _)| b == ship)
.is_none_or(|(_, prev)| prev != actions)
})
.collect()
}
#[cfg(test)]
mod route_push_tests {
use super::{changed_routes, plan_routes_for_var};
use mt_net::{RatPubRegisterKind::*, Rules};
fn ships(plans: &[(String, Vec<mt_net::ActionPlan>)]) -> Vec<&str> {
let mut v: Vec<&str> = plans.iter().map(|(s, _)| s.as_str()).collect();
v.sort();
v
}
fn reg(rules: &mut Rules, ship: &str, kind: mt_net::RatPubRegisterKind) -> Vec<String> {
let before = plan_routes_for_var(rules, "/t");
rules.register("/t".into(), ship.into(), kind);
let after = plan_routes_for_var(rules, "/t");
ships(&changed_routes(&before, after, Some(ship)))
.into_iter()
.map(String::from)
.collect()
}
fn unreg(rules: &mut Rules, ship: &str, kind: mt_net::RatPubRegisterKind) -> Vec<String> {
let before = plan_routes_for_var(rules, "/t");
rules.unregister("/t", ship, kind);
let after = plan_routes_for_var(rules, "/t");
ships(&changed_routes(&before, after, None))
.into_iter()
.map(String::from)
.collect()
}
#[test]
fn targeted_pushes_reach_exactly_the_changed_ships() {
let mut r = Rules::new();
assert_eq!(reg(&mut r, "pub", Publish), ["pub"]);
assert_eq!(reg(&mut r, "a", Subscribe), ["a", "pub"]);
assert_eq!(reg(&mut r, "b", Subscribe), ["b", "pub"]);
assert_eq!(reg(&mut r, "c", Subscribe), ["c", "pub"]);
assert_eq!(unreg(&mut r, "b", Subscribe), ["pub"]);
assert_eq!(reg(&mut r, "a", Subscribe), ["a"]);
}
}