Skip to main content

rat/
lib.rs

1use anyhow::anyhow;
2use log::{error, info};
3use rkyv::{
4    api::high::{HighSerializer, HighValidator},
5    bytecheck::CheckBytes,
6    de::Pool,
7    rancor::Strategy,
8    ser::allocator::ArenaHandle,
9    util::AlignedVec,
10};
11use std::sync::{Arc, LazyLock, Mutex};
12
13use mt_sea::{ship::NetworkShipImpl, *};
14
15pub use mt_sea::VariableType;
16pub use mt_sea::net::NetArray;
17pub use rkyv::{Archive, Deserialize, Serialize};
18
19pub struct Rat {
20    name: String,
21    ship: Option<Arc<NetworkShipImpl>>,
22    /// Keeps the coordinator's per-client handler alive while this Rat is idle.
23    heartbeat: Option<tokio::task::JoinHandle<()>>,
24}
25
26impl Drop for Rat {
27    fn drop(&mut self) {
28        if let Some(heartbeat) = self.heartbeat.take() {
29            heartbeat.abort();
30        }
31    }
32}
33
34pub fn rfalse() -> NetArray<u8> {
35    nalgebra::DMatrix::<u8>::zeros(1, 1).into()
36}
37
38pub fn rtrue() -> NetArray<u8> {
39    let rf = rfalse();
40    let mut rf = nalgebra::DMatrix::<u8>::from(rf);
41    unsafe { *rf.get_unchecked_mut((0, 0)) = 1 };
42    rf.into()
43}
44
45static RT: LazyLock<Mutex<Option<Arc<tokio::runtime::Runtime>>>> =
46    LazyLock::new(|| Mutex::new(None));
47static RAT: LazyLock<Mutex<Option<Rat>>> = LazyLock::new(|| Mutex::new(None));
48
49impl Rat {
50    async fn create(name: &str, timeout: Option<std::time::Duration>) -> anyhow::Result<Self> {
51        let init_future = mt_sea::ship::NetworkShipImpl::init(
52            ShipKind::Rat(name.to_string()),
53            false,
54            mt_sea::Qos::Reliable,
55            // Rat traffic is what the comparison node reads, and it is told
56            // about a variable only when a ship asks the coordinator for that
57            // variable's route. So this path must never answer from the cache.
58            mt_sea::NodeOptions::default().with_route_cache_bypassed(),
59        );
60
61        let ship = match timeout {
62            None => Some(init_future.await?),
63            Some(t) => match tokio::time::timeout(t, init_future).await {
64                Err(_) => None,
65                Ok(ship) => Some(ship?),
66            },
67        };
68
69        let ship = ship.map(Arc::new);
70        // A Rat only speaks when it reaches a watched variable, so without this
71        // the coordinator drops it during any pause longer than its disconnect
72        // timeout and the next `bacon` waits forever.
73        let heartbeat = ship.as_ref().map(NetworkShipImpl::spawn_heartbeat);
74
75        Ok(Self {
76            name: name.to_string(),
77            ship,
78            heartbeat,
79        })
80    }
81}
82
83fn store_rat(new_rat: Rat) -> anyhow::Result<()> {
84    let mut rat = RAT
85        .lock()
86        .map_err(|e| anyhow::anyhow!("Failed to lock rat: {}", e))?;
87    if rat.is_some() {
88        return Err(anyhow::anyhow!("Rat already initialized"));
89    }
90    rat.replace(new_rat);
91    Ok(())
92}
93
94/// Initialize a Rat using the caller's active Tokio runtime.
95pub async fn init_async(
96    node_name: &str,
97    timeout: Option<std::time::Duration>,
98) -> anyhow::Result<()> {
99    let new_rat = Rat::create(node_name, timeout).await?;
100    store_rat(new_rat)
101}
102
103pub fn init(
104    node_name: &str,
105    timeout: Option<std::time::Duration>,
106    runtime: Option<Arc<tokio::runtime::Runtime>>,
107) -> anyhow::Result<()> {
108    if tokio::runtime::Handle::try_current().is_ok() {
109        return Err(anyhow!("call init_async().await from a Tokio runtime"));
110    }
111
112    let mut srt = RT.lock().unwrap();
113    if let Some(rt) = runtime {
114        srt.replace(rt);
115    }
116
117    if srt.is_none() {
118        // Multi-threaded so the heartbeat task keeps running between `bacon`
119        // calls. A current-thread runtime only polls tasks inside `block_on`,
120        // which is exactly when the Rat does not need to be kept alive.
121        srt.replace(Arc::new(
122            tokio::runtime::Builder::new_multi_thread()
123                .worker_threads(1)
124                .enable_all()
125                .build()
126                .unwrap(),
127        ));
128    }
129
130    let rt = srt.as_ref().expect("just set").clone();
131    drop(srt);
132    let new_rat = rt.block_on(Rat::create(node_name, timeout))?;
133    store_rat(new_rat)
134}
135
136pub fn deinit() -> anyhow::Result<()> {
137    let mut rat_arc = RAT
138        .lock()
139        .map_err(|e| anyhow::anyhow!("Failed to lock rat: {}", e))?;
140
141    if rat_arc.is_none() {
142        return Err(anyhow::anyhow!("Rat not initialized"));
143    }
144
145    rat_arc.take();
146    Ok(())
147}
148
149/// When the code reaches a variable that is watched, call this function to communicate synchronously with the link.
150/// It syncs with the other rats and gets the action to be taken for the current var.
151/// It then applies the action to the variable and returns.
152pub fn bacon<T>(
153    variable_name: &str,
154    data: &mut T,
155    variable_type: VariableType,
156) -> anyhow::Result<()>
157where
158    T: Archive,
159    T::Archived: for<'a> CheckBytes<HighValidator<'a, rkyv::rancor::Error>>
160        + Deserialize<T, Strategy<Pool, rkyv::rancor::Error>>,
161    T: 'static + Send,
162    T: for<'a> Serialize<HighSerializer<AlignedVec, ArenaHandle<'a>, rkyv::rancor::Error>>,
163    T: Send + Sync,
164{
165    if tokio::runtime::Handle::try_current().is_ok() {
166        return Err(anyhow!("call bacon_async().await from a Tokio runtime"));
167    }
168
169    let srt = RT.lock().unwrap();
170    let rt = srt.as_ref().cloned().ok_or(anyhow!(
171        "Async Runtime not initialized. Call init() before calling bacon()."
172    ))?;
173    drop(srt);
174
175    rt.block_on(bacon_async(variable_name, data, variable_type))
176}
177
178/// Synchronize a watched variable using the caller's active Tokio runtime.
179pub async fn bacon_async<T>(
180    variable_name: &str,
181    data: &mut T,
182    variable_type: VariableType,
183) -> anyhow::Result<()>
184where
185    T: Archive,
186    T::Archived: for<'a> CheckBytes<HighValidator<'a, rkyv::rancor::Error>>
187        + Deserialize<T, Strategy<Pool, rkyv::rancor::Error>>,
188    T: 'static + Send,
189    T: for<'a> Serialize<HighSerializer<AlignedVec, ArenaHandle<'a>, rkyv::rancor::Error>>,
190    T: Send + Sync,
191{
192    let (rat_name, rat_ship) = {
193        let rat = RAT
194            .lock()
195            .map_err(|e| anyhow::anyhow!("Failed to lock rat: {}", e))?;
196        let rat = rat.as_ref().ok_or(anyhow::anyhow!("Rat not initialized"))?;
197        (rat.name.clone(), rat.ship.clone())
198    };
199
200    if let Some(rat_ship) = rat_ship {
201        match rat_ship.ask_for_action(variable_name).await {
202            Ok((mt_sea::Action::Sail, lock_until_ack)) => {
203                log::debug!("Rat {} sails for variable {}", rat_name, variable_name);
204                let receiver = lock_until_ack.then_some({
205                    let client = rat_ship.client.lock().await;
206                    let sender = client.coordinator_receive.read().unwrap();
207                    sender
208                        .as_ref()
209                        .expect("How are we receiving anything in the client? :)")
210                        .subscribe()
211                });
212
213                if let Some(mut receiver) = receiver {
214                    info!("Locked...");
215                    loop {
216                        let (packet, _) = receiver.recv().await?;
217                        if matches!(packet.data, net::PacketKind::Acknowledge) {
218                            break;
219                        }
220                    }
221                    info!("Unlocked");
222                }
223
224                Ok(())
225            }
226            Ok((mt_sea::Action::Shoot { target, id }, lock_until_ack)) => {
227                info!("Rat {} shoots {} at {:?}", rat_name, variable_name, target);
228
229                let receiver = lock_until_ack.then_some({
230                    let client = rat_ship.client.lock().await;
231                    let sender = client.coordinator_receive.read().unwrap();
232                    sender
233                        .as_ref()
234                        .expect("How are we receiving anything in the client? :)")
235                        .subscribe()
236                });
237
238                rat_ship
239                    .get_cannon()
240                    .shoot(&target, id, data, variable_type, variable_name)
241                    .await?;
242
243                if let Some(mut receiver) = receiver {
244                    info!("Locked...");
245                    loop {
246                        let (packet, _) = receiver.recv().await?;
247                        if matches!(packet.data, net::PacketKind::Acknowledge) {
248                            break;
249                        }
250                    }
251                    info!("Unlocked");
252                }
253
254                info!(
255                    "Rat {} finished shooting {} at {:?}",
256                    rat_name, variable_name, target
257                );
258
259                Ok(())
260            }
261            Ok((mt_sea::Action::Catch { source, id }, lock_until_ack)) => {
262                info!(
263                    "Rat {} catches {} from {:?}",
264                    rat_name, variable_name, source
265                );
266
267                let receiver = lock_until_ack.then_some({
268                    let client = rat_ship.client.lock().await;
269                    let sender = client.coordinator_receive.read().unwrap();
270                    sender
271                        .as_ref()
272                        .expect("How are we receiving anything in the client? :)")
273                        .subscribe()
274                });
275
276                let mut recv_data = rat_ship.get_cannon().catch::<T>(id).await?;
277
278                info!(
279                    "Rat {} finished catching {} from {:?}",
280                    rat_name, variable_name, source
281                );
282
283                // The first index is the newest
284                *data = recv_data.remove(0);
285
286                if let Some(mut receiver) = receiver {
287                    info!("Locked...");
288                    loop {
289                        let (packet, _) = receiver.recv().await?;
290                        if matches!(packet.data, net::PacketKind::Acknowledge) {
291                            break;
292                        }
293                    }
294                    info!("Unlocked");
295                }
296
297                Ok(())
298            }
299            Err(e) => {
300                error!("Failed to get action: {}", e);
301                Err(e)
302            }
303        }
304    } else {
305        Ok(())
306    }
307}
308
309// C FFI
310#[cfg(all(target_arch = "aarch64", target_vendor = "apple"))]
311type CFfiString = i8;
312
313#[cfg(all(
314    not(target_arch = "x86"),
315    not(target_arch = "x86_64"),
316    not(target_vendor = "apple")
317))]
318type CFfiString = u8;
319
320#[cfg(any(
321    target_arch = "x86",
322    target_arch = "x86_64",
323    all(target_vendor = "apple", not(target_arch = "aarch64"))
324))]
325type CFfiString = i8;
326
327#[unsafe(no_mangle)]
328/// # Safety
329/// C interop
330pub unsafe extern "C" fn rat_init(node_name: *const CFfiString, timeout_secs: i32) -> i32 {
331    let init = || {
332        let node_name = unsafe { std::ffi::CStr::from_ptr(node_name) };
333        let node_name = node_name.to_str().unwrap();
334
335        let timeout = if timeout_secs <= 0 {
336            None
337        } else {
338            Some(std::time::Duration::from_secs(timeout_secs as u64))
339        };
340
341        init(node_name, timeout, None)
342    };
343
344    #[cfg(panic = "unwind")]
345    {
346        let catch = std::panic::catch_unwind(init);
347
348        match catch {
349            Ok(Ok(_)) => 0,
350            Ok(Err(e)) => {
351                error!("Could not initialize Rat: {e}.");
352                -1
353            }
354            Err(_) => {
355                error!("Rust did panic unexpectedly.");
356                -2
357            }
358        }
359    }
360
361    #[cfg(not(panic = "unwind"))]
362    {
363        let d = init();
364        match d {
365            Ok(_) => 0,
366            Err(e) => {
367                error!("Could not initialize Rat: {e}.");
368                -1
369            }
370        }
371    }
372}
373
374#[unsafe(no_mangle)]
375/// # Safety
376/// C interop
377pub unsafe extern "C" fn rat_deinit() -> i32 {
378    #[cfg(panic = "unwind")]
379    {
380        let catch = std::panic::catch_unwind(deinit);
381
382        match catch {
383            Ok(Ok(_)) => 0,
384            Ok(Err(e)) => {
385                error!("Could not deinitialize Rat: {e}.");
386                -1
387            }
388            Err(_) => {
389                error!("Rust did panic unexpectedly.");
390                -2
391            }
392        }
393    }
394
395    #[cfg(not(panic = "unwind"))]
396    {
397        let d = deinit();
398        match d {
399            Ok(_) => 0,
400            Err(e) => {
401                error!("Could not deinitialize Rat: {e}.");
402                -1
403            }
404        }
405    }
406}
407
408#[unsafe(no_mangle)]
409/// Matrix must be in column-major order.
410/// # Safety
411/// C interop
412pub unsafe extern "C" fn rat_bacon_f32(
413    variable_name: *const CFfiString,
414    data: *mut f32,
415    rows: usize,
416    cols: usize,
417) -> i32 {
418    let f = || {
419        let variable_name = unsafe { std::ffi::CStr::from_ptr(variable_name) };
420        let variable_name = variable_name.to_str().unwrap();
421
422        let data = unsafe { std::slice::from_raw_parts_mut(data, rows * cols) };
423        let matrix = nalgebra::DMatrix::from_column_slice(rows, cols, data);
424
425        let mut net_mat = NetArray::from(matrix);
426        bacon(variable_name, &mut net_mat, VariableType::F32).map(|_| {
427            let matrix: nalgebra::DMatrix<f32> = net_mat.into();
428            for c in 0..cols {
429                for r in 0..rows {
430                    data[c * rows + r] = matrix[(r, c)];
431                }
432            }
433        })
434    };
435
436    #[cfg(panic = "unwind")]
437    {
438        let catch = std::panic::catch_unwind(f);
439
440        match catch {
441            Ok(Ok(_)) => 0,
442            Ok(Err(e)) => {
443                error!("Failed to bacon: {}", e);
444                -1
445            }
446            Err(_) => {
447                error!("Rust did panic unexpectedly.");
448                -2
449            }
450        }
451    }
452
453    #[cfg(not(panic = "unwind"))]
454    {
455        let d = f();
456        match d {
457            Ok(_) => 0,
458            Err(e) => {
459                error!("Could not deinitialize Rat: {e}.");
460                -1
461            }
462        }
463    }
464}
465
466#[unsafe(no_mangle)]
467/// Matrix must be in column-major order.
468/// # Safety
469/// C interop
470pub unsafe extern "C" fn rat_bacon_f64(
471    variable_name: *const CFfiString,
472    data: *mut f64,
473    rows: usize,
474    cols: usize,
475) -> i32 {
476    let f = || {
477        let variable_name = unsafe { std::ffi::CStr::from_ptr(variable_name) };
478        let variable_name = variable_name.to_str().unwrap();
479
480        let data = unsafe { std::slice::from_raw_parts_mut(data, rows * cols) };
481        let matrix = nalgebra::DMatrix::from_column_slice(rows, cols, data);
482
483        let mut net_mat = NetArray::from(matrix);
484        bacon(variable_name, &mut net_mat, VariableType::F64).map(|_| {
485            let matrix: nalgebra::DMatrix<f64> = net_mat.into();
486            for c in 0..cols {
487                for r in 0..rows {
488                    data[c * rows + r] = matrix[(r, c)];
489                }
490            }
491        })
492    };
493
494    #[cfg(panic = "unwind")]
495    {
496        let catch = std::panic::catch_unwind(f);
497
498        match catch {
499            Ok(Ok(_)) => 0,
500            Ok(Err(e)) => {
501                error!("Failed to bacon: {}", e);
502                -1
503            }
504            Err(_) => {
505                error!("Rust did panic unexpectedly.");
506                -2
507            }
508        }
509    }
510    #[cfg(not(panic = "unwind"))]
511    {
512        let d = f();
513        match d {
514            Ok(_) => 0,
515            Err(e) => {
516                error!("Could not deinitialize Rat: {e}.");
517                -1
518            }
519        }
520    }
521}
522
523#[unsafe(no_mangle)]
524/// Matrix must be in column-major order.
525/// # Safety
526/// C interop
527pub unsafe extern "C" fn rat_bacon_i32(
528    variable_name: *const CFfiString,
529    data: *mut i32,
530    rows: usize,
531    cols: usize,
532) -> i32 {
533    let f = || {
534        let variable_name = unsafe { std::ffi::CStr::from_ptr(variable_name) };
535        let variable_name = variable_name.to_str().unwrap();
536
537        let data = unsafe { std::slice::from_raw_parts_mut(data, rows * cols) };
538        let matrix = nalgebra::DMatrix::from_column_slice(rows, cols, data);
539
540        let mut net_mat = NetArray::from(matrix);
541        bacon(variable_name, &mut net_mat, VariableType::I32).map(|_| {
542            let matrix: nalgebra::DMatrix<i32> = net_mat.into();
543            for c in 0..cols {
544                for r in 0..rows {
545                    data[c * rows + r] = matrix[(r, c)];
546                }
547            }
548        })
549    };
550
551    #[cfg(panic = "unwind")]
552    {
553        let catch = std::panic::catch_unwind(f);
554
555        match catch {
556            Ok(Ok(_)) => 0,
557            Ok(Err(e)) => {
558                error!("Failed to bacon: {}", e);
559                -1
560            }
561            Err(_) => {
562                error!("Rust did panic unexpectedly.");
563                -2
564            }
565        }
566    }
567    #[cfg(not(panic = "unwind"))]
568    {
569        let d = f();
570        match d {
571            Ok(_) => 0,
572            Err(e) => {
573                error!("Could not deinitialize Rat: {e}.");
574                -1
575            }
576        }
577    }
578}
579
580#[unsafe(no_mangle)]
581/// Matrix must be in column-major order.
582/// # Safety
583/// C interop
584pub unsafe extern "C" fn rat_bacon_u8(
585    variable_name: *const CFfiString,
586    data: *mut u8,
587    rows: usize,
588    cols: usize,
589) -> i32 {
590    let f = || {
591        let variable_name = unsafe { std::ffi::CStr::from_ptr(variable_name) };
592        let variable_name = variable_name.to_str().unwrap();
593
594        let data = unsafe { std::slice::from_raw_parts_mut(data, rows * cols) };
595        let matrix = nalgebra::DMatrix::from_column_slice(rows, cols, data);
596
597        let mut net_mat = NetArray::from(matrix);
598        bacon(variable_name, &mut net_mat, VariableType::U8).map(|_| {
599            let matrix: nalgebra::DMatrix<u8> = net_mat.into();
600            for c in 0..cols {
601                for r in 0..rows {
602                    data[c * rows + r] = matrix[(r, c)];
603                }
604            }
605        })
606    };
607
608    #[cfg(panic = "unwind")]
609    {
610        let catch = std::panic::catch_unwind(f);
611
612        match catch {
613            Ok(Ok(_)) => 0,
614            Ok(Err(e)) => {
615                error!("Failed to bacon: {}", e);
616                -1
617            }
618            Err(_) => {
619                error!("Rust did panic unexpectedly.");
620                -2
621            }
622        }
623    }
624    #[cfg(not(panic = "unwind"))]
625    {
626        let d = f();
627        match d {
628            Ok(_) => 0,
629            Err(e) => {
630                error!("Could not deinitialize Rat: {e}.");
631                -1
632            }
633        }
634    }
635}