mt_sea/
lib.rs

1pub mod client;
2pub mod coordinator;
3pub mod net;
4pub mod ship;
5
6use mt_net::{ActionPlan, BagMsg, Rules, VariableHuman};
7use rkyv::{
8    Archive, Deserialize, Serialize,
9    api::high::{HighSerializer, HighValidator},
10    bytecheck::CheckBytes,
11    de::Pool,
12    rancor::Strategy,
13    ser::allocator::ArenaHandle,
14    util::AlignedVec,
15};
16
17#[derive(Debug, Clone, PartialEq, Archive, Serialize, Deserialize, Hash, Eq, PartialOrd, Ord)]
18pub enum ShipKind {
19    Rat(String),
20    Wind(String),
21}
22
23pub type ShipName = i128;
24
25#[derive(Debug, Clone, Serialize, Deserialize, Archive, PartialEq, Eq)]
26pub struct NetworkShipAddress {
27    ip: [u8; 4],
28    port: u16,
29    ship: ShipName,
30    pub kind: ShipKind,
31}
32
33#[derive(Debug, Archive, Clone, Default, Serialize, Deserialize)]
34pub enum Action {
35    #[default]
36    Sail,
37    Shoot {
38        target: Vec<NetworkShipAddress>,
39        id: u32,
40    },
41    Catch {
42        source: NetworkShipAddress,
43        id: u32,
44    },
45}
46
47#[derive(Clone, Debug)]
48pub struct Variable {
49    pub ship: ShipName,
50    pub strategy: Option<Action>,
51}
52
53pub fn get_strategies(
54    haystack: &Rules,
55    rat_ship: &str,
56    variable: String,
57    indirect_parent_rat: Option<&str>,
58) -> Vec<ActionPlan> {
59    match haystack.raw().get(&variable) {
60        None => vec![ActionPlan::default()],
61        Some(plans) => {
62            // directly because rule was set
63            let directly = plans
64                .iter()
65                .filter(|plan| plan.ship == rat_ship)
66                .filter_map(|el| el.strategy.clone())
67                .collect::<Vec<_>>();
68
69            // as other part of a rule
70            let mut indirect = plans
71                .iter()
72                .filter(|plan| {
73                    indirect_parent_rat.is_some_and(|parent_rat| plan.ship == parent_rat)
74                })
75                .filter_map(|plan| match plan.strategy.as_ref()? {
76                    ActionPlan::Sail => None,
77                    ActionPlan::Shoot { target, id } => target
78                        .iter()
79                        .find(|shoot_target| *shoot_target == rat_ship)
80                        .map(|_| ActionPlan::Catch {
81                            source: plan.ship.clone(),
82                            id: *id,
83                        }),
84                    ActionPlan::Catch { source, id } => {
85                        if source == rat_ship {
86                            Some(ActionPlan::Shoot {
87                                target: vec![source.clone()],
88                                id: *id,
89                            })
90                        } else {
91                            None
92                        }
93                    }
94                })
95                .collect::<Vec<_>>();
96
97            indirect.extend(directly);
98            indirect
99        }
100    }
101}
102
103#[async_trait::async_trait]
104pub trait Ship: Send + Sync + 'static {
105    /// Indicate a trigger point and ask the link pilot what to do with the variable.
106    async fn ask_for_action(&self, variable_name: &str) -> anyhow::Result<(Action, bool)>;
107
108    // async fn wait_for_action(&self) -> anyhow::Result<crate::Action>;
109
110    async fn wait_for_wind(&self) -> anyhow::Result<Vec<WindData>>;
111
112    fn get_cannon(&self) -> &impl Cannon;
113}
114
115#[derive(Archive, Serialize, Deserialize, Debug, Clone, Copy, Default)]
116pub enum VariableType {
117    #[default]
118    StaticOnly, // statically supported but no dynamic conversion implemented
119    U8,
120    I32,
121    F32,
122    F64,
123}
124
125impl From<u8> for VariableType {
126    fn from(value: u8) -> Self {
127        match value {
128            1 => Self::U8,
129            2 => Self::I32,
130            3 => Self::F32,
131            4 => Self::F64,
132            _ => Self::default(),
133        }
134    }
135}
136
137impl From<VariableType> for u8 {
138    fn from(value: VariableType) -> Self {
139        match value {
140            VariableType::StaticOnly => 0,
141            VariableType::U8 => 1,
142            VariableType::I32 => 2,
143            VariableType::F32 => 3,
144            VariableType::F64 => 4,
145        }
146    }
147}
148
149use rkyv::rancor::Error as RkyvError;
150
151// Trait for types that can be Sent (Serialized).
152// Requires Sized, Send, Sync, 'static, and the specific rkyv Serialize bound.
153pub trait Sendable: Sized + Send + Sync + 'static
154where
155    Self: for<'b> Serialize<HighSerializer<AlignedVec, ArenaHandle<'b>, RkyvError>>,
156{
157}
158// Blanket implementation for Sendable. Any type meeting the bounds is Sendable.
159impl<T> Sendable for T
160where
161    T: Sized + Send + Sync + 'static,
162    T: for<'b> Serialize<HighSerializer<AlignedVec, ArenaHandle<'b>, RkyvError>>,
163{
164}
165
166#[async_trait::async_trait]
167pub trait Cannon: Send + Sync + 'static {
168    // Initialize a 1:1 connection to the target. Ports are shared using the sea network internally.
169
170    /// Dump the data to the target.
171    async fn shoot<'b, T: Sendable>(
172        &self,
173        targets: &'b [crate::NetworkShipAddress],
174        id: u32,
175        data: &T,
176        variable_type: VariableType,
177        variable_name: &str,
178    ) -> anyhow::Result<()>;
179
180    /// Catch the dumped data from the source.
181    /// The returning Vec can contain previously missed entities of T from existing sync connections.
182    /// The first item of T is the newest, followed by incremental older ones.
183    async fn catch<T>(&self, id: u32) -> anyhow::Result<Vec<T>>
184    where
185        T: Send,
186        T: Archive,
187        T::Archived: for<'a> CheckBytes<HighValidator<'a, rkyv::rancor::Error>>
188            + Deserialize<T, Strategy<Pool, rkyv::rancor::Error>>;
189
190    async fn catch_dyn(&self, id: u32) -> anyhow::Result<Vec<(String, VariableType, String)>>;
191}
192
193#[derive(Clone, Debug, Default, Copy, Archive, Serialize, Deserialize, PartialEq)]
194pub struct TimeMsg {
195    pub sec: i32,
196    pub nanosec: u32,
197}
198
199#[derive(Clone, Debug, Default, PartialEq, Archive, Serialize, Deserialize)]
200pub struct Header {
201    pub seq: u32,
202    pub stamp: TimeMsg,
203    pub frame_id: String,
204}
205
206pub type WindData = BagMsg;
207
208#[async_trait::async_trait]
209pub trait Coordinator: Send + Sync + 'static {
210    async fn rat_action_request_queue(
211        &self,
212        ship: String,
213    ) -> anyhow::Result<tokio::sync::broadcast::Receiver<String>>;
214
215    async fn blow_wind(&self, ship: String, data: Vec<WindData>) -> anyhow::Result<()>;
216
217    async fn rat_action_send(
218        &self,
219        ship: String,
220        action: ActionPlan,
221        lock_until_ack: bool,
222    ) -> anyhow::Result<()>;
223}