microrti_client/link.rs
1//! The seam between the RTI ambassador and whatever carries the service messages to an RTI.
2//!
3//! An [`RtiLink`] moves `CallRequest` / `CallResponse` and `CallbackRequest` / `CallbackResponse`
4//! messages (12.13.3.1) and knows nothing about HLA semantics. Two kinds of links are expected: a Federate
5//! Protocol session to any HLA 4 RTI, and an in-process RTI (see [`crate::local`]).
6//!
7//! A [`LinkFactory`] opens a link for the RTI address of an [`RtiConfiguration`]; [`Connectors`] selects the
8//! factory by address scheme.
9
10use std::collections::BTreeMap;
11use std::sync::{Arc, Mutex, PoisonError};
12use std::time::Duration;
13
14use microrti_proto::{CallRequest, CallResponse, CallbackRequest, CallbackResponse};
15
16use crate::types::RtiConfiguration;
17
18/// Failure of an [`RtiLink`] or of a [`LinkFactory`].
19#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
20pub enum LinkError {
21 /// The connection to the RTI broke; the text describes the fault. The RTI ambassador reports it to the
22 /// federate with the Connection Lost callback (4.4).
23 #[error("connection to the RTI lost: {0}")]
24 Lost(String),
25 /// The link was closed on purpose by [`RtiLink::close`].
26 #[error("the link to the RTI is closed")]
27 Closed,
28 /// No link could be opened: no connector for the address, or the RTI cannot be reached.
29 #[error("cannot reach the RTI: {0}")]
30 Unreachable(String),
31 /// Any other failure, for example a message that could not be encoded.
32 #[error("link failure: {0}")]
33 Failed(String),
34}
35
36/// Condition of an [`RtiLink`].
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub enum LinkState {
39 /// Messages can be exchanged.
40 Open,
41 /// [`RtiLink::close`] was called.
42 Closed,
43 /// The connection broke; the text describes the fault.
44 Lost(String),
45}
46
47/// A callback request pulled from a link, with the token needed to answer it.
48#[derive(Clone, Debug, PartialEq)]
49pub struct LinkCallback {
50 /// Opaque token chosen by the link (for a Federate Protocol session: the sequence number of the
51 /// callback request message). Passed back to [`RtiLink::respond`].
52 pub id: u64,
53 /// The RTI-initiated service invocation.
54 pub request: CallbackRequest,
55}
56
57/// Transport of service messages between one federate and its RTI.
58///
59/// All methods take `&self`: the RTI ambassador calls [`RtiLink::call`] from several threads at once
60/// (12.8) while another thread waits in [`RtiLink::next_callback`]. The ambassador itself never calls
61/// `next_callback` from two threads at the same time.
62pub trait RtiLink: Send + Sync {
63 /// Sends one federate-initiated service invocation and blocks until its response arrives.
64 ///
65 /// An exception raised by the RTI is a successful exchange: it comes back as the `ExceptionData`
66 /// alternative of the response.
67 fn call(&self, request: CallRequest) -> Result<CallResponse, LinkError>;
68
69 /// Removes the oldest undelivered callback request, waiting for one if necessary.
70 ///
71 /// `None` waits without limit, `Some(Duration::ZERO)` only polls. Returns `Ok(None)` when the timeout
72 /// expires. Callbacks that arrived before a fault are still handed out; after that the fault is
73 /// reported as [`LinkError::Lost`]. A blocked call must return promptly once [`RtiLink::close`] is
74 /// called (with [`LinkError::Closed`]).
75 fn next_callback(&self, timeout: Option<Duration>) -> Result<Option<LinkCallback>, LinkError>;
76
77 /// Answers the callback request identified by `id` (the federate ambassador returned or failed).
78 fn respond(&self, id: u64, response: CallbackResponse) -> Result<(), LinkError>;
79
80 /// Current condition of the link.
81 fn state(&self) -> LinkState;
82
83 /// Releases the link. Idempotent; wakes every blocked [`RtiLink::next_callback`].
84 fn close(&self);
85}
86
87/// Opens links: the connector abstraction used by the Connect service (4.2).
88pub trait LinkFactory: Send + Sync {
89 /// Opens a link to the RTI designated by `configuration` (usually by its RTI address).
90 fn open(&self, configuration: &RtiConfiguration) -> Result<Arc<dyn RtiLink>, LinkError>;
91}
92
93impl<F> LinkFactory for F
94where
95 F: Fn(&RtiConfiguration) -> Result<Arc<dyn RtiLink>, LinkError> + Send + Sync,
96{
97 fn open(&self, configuration: &RtiConfiguration) -> Result<Arc<dyn RtiLink>, LinkError> {
98 self(configuration)
99 }
100}
101
102/// A set of [`LinkFactory`] connectors selected by the scheme of the RTI address.
103///
104/// The scheme is the text before the first `:` of the address (`tcp://host:15164` has scheme `tcp`). An
105/// address without a registered scheme, such as `host:15164` or the empty address, goes to the default
106/// connector. An address of the form `scheme://...` whose scheme is not registered is an error.
107#[derive(Clone, Default)]
108pub struct Connectors {
109 by_scheme: BTreeMap<String, Arc<dyn LinkFactory>>,
110 fallback: Option<Arc<dyn LinkFactory>>,
111}
112
113impl Connectors {
114 /// Creates an empty set.
115 pub const fn new() -> Self {
116 Self { by_scheme: BTreeMap::new(), fallback: None }
117 }
118
119 /// Registers (or replaces) the connector of an address scheme. Schemes are case insensitive.
120 pub fn register(&mut self, scheme: &str, factory: impl LinkFactory + 'static) -> &mut Self {
121 self.by_scheme.insert(scheme.to_ascii_lowercase(), Arc::new(factory));
122 self
123 }
124
125 /// Registers (or replaces) the connector used for addresses without a registered scheme.
126 pub fn register_default(&mut self, factory: impl LinkFactory + 'static) -> &mut Self {
127 self.fallback = Some(Arc::new(factory));
128 self
129 }
130
131 /// Registered schemes, sorted.
132 pub fn schemes(&self) -> Vec<String> {
133 self.by_scheme.keys().cloned().collect()
134 }
135
136 /// Selects the connector for an RTI address.
137 pub fn resolve(&self, rti_address: &str) -> Option<Arc<dyn LinkFactory>> {
138 if let Some((scheme, rest)) = rti_address.split_once(':')
139 && is_scheme(scheme)
140 {
141 if let Some(factory) = self.by_scheme.get(&scheme.to_ascii_lowercase()) {
142 return Some(Arc::clone(factory));
143 }
144 if rest.starts_with("//") {
145 return None;
146 }
147 }
148 self.fallback.clone()
149 }
150
151 /// Opens a link with the connector selected by the RTI address of `configuration`.
152 pub fn open(&self, configuration: &RtiConfiguration) -> Result<Arc<dyn RtiLink>, LinkError> {
153 let address = configuration.rti_address();
154 match self.resolve(address) {
155 Some(factory) => factory.open(configuration),
156 None => {
157 Err(LinkError::Unreachable(format!("no connector registered for RTI address {address:?}")))
158 }
159 }
160 }
161}
162
163impl std::fmt::Debug for Connectors {
164 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165 f.debug_struct("Connectors")
166 .field("schemes", &self.schemes())
167 .field("default", &self.fallback.is_some())
168 .finish()
169 }
170}
171
172fn is_scheme(text: &str) -> bool {
173 let mut chars = text.chars();
174 chars.next().is_some_and(|c| c.is_ascii_alphabetic())
175 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
176}
177
178static GLOBAL: Mutex<Connectors> = Mutex::new(Connectors::new());
179
180/// The process-wide set. With the feature `fedpro` it starts out with the Federate Protocol connectors
181/// for `tcp`, `tls`, `ws`, `wss` and for addresses without a scheme (see [`crate::fedpro`]); whatever the
182/// application registers afterwards replaces them.
183fn global() -> std::sync::MutexGuard<'static, Connectors> {
184 #[cfg(feature = "fedpro")]
185 {
186 static BUILT_IN: std::sync::Once = std::sync::Once::new();
187 BUILT_IN.call_once(|| {
188 let mut connectors = GLOBAL.lock().unwrap_or_else(PoisonError::into_inner);
189 crate::fedpro::FedProConnector::default().register(&mut connectors);
190 });
191 }
192 GLOBAL.lock().unwrap_or_else(PoisonError::into_inner)
193}
194
195/// Registers a connector for an address scheme in the process-wide set used by
196/// [`RtiAmbassador::new`](crate::RtiAmbassador::new).
197pub fn register_connector(scheme: &str, factory: impl LinkFactory + 'static) {
198 global().register(scheme, factory);
199}
200
201/// Registers the process-wide connector for addresses without a registered scheme.
202pub fn register_default_connector(factory: impl LinkFactory + 'static) {
203 global().register_default(factory);
204}
205
206/// A snapshot of the process-wide connector set.
207pub fn global_connectors() -> Connectors {
208 global().clone()
209}