use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use microrti_fedpro::blocking::ClientSession;
use microrti_fedpro::frame::DEFAULT_MAX_MESSAGE_SIZE;
use microrti_fedpro::{CallbackResponder, ClientConfig, Endpoint, FedProError, SessionState};
pub use microrti_fedpro::{TlsMode, TrustAnchors};
use microrti_proto::{CallRequest, CallResponse, CallbackResponse};
use crate::link::{Connectors, LinkCallback, LinkError, LinkFactory, LinkState, RtiLink};
use crate::types::RtiConfiguration;
pub const DEFAULT_RTI_ADDRESS: &str = "tcp://localhost:15164";
pub const SCHEMES: [&str; 4] = ["tcp", "tls", "ws", "wss"];
const UNBOUNDED_WAIT_SLICE: Duration = Duration::from_secs(1);
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("additional settings, line {line}: {message}")]
pub struct SettingsError {
pub line: usize,
pub message: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FedProOptions {
pub fed_int_heart: Duration,
pub fed_timeout_heart: Duration,
pub fed_timeout_reconnect: Duration,
pub fed_int_reconnect: Duration,
pub fed_timeout_connect: Duration,
pub tls: TlsMode,
pub tls_server_name: Option<String>,
pub max_message_size: usize,
}
impl Default for FedProOptions {
fn default() -> Self {
FedProOptions {
fed_int_heart: microrti_fedpro::FED_INT_HEART,
fed_timeout_heart: microrti_fedpro::FED_TIMEOUT_HEART,
fed_timeout_reconnect: microrti_fedpro::FED_TIMEOUT_RECONNECT,
fed_int_reconnect: Duration::from_secs(1),
fed_timeout_connect: Duration::from_secs(10),
tls: TlsMode::EncryptionOnly,
tls_server_name: None,
max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
}
}
}
impl FedProOptions {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_trust_anchors_file(mut self, path: impl Into<PathBuf>) -> Self {
self.tls = TlsMode::ServerAuth(TrustAnchors::PemFile(path.into()));
self
}
#[must_use]
pub fn with_trust_anchors_pem(mut self, pem: impl Into<Vec<u8>>) -> Self {
self.tls = TlsMode::ServerAuth(TrustAnchors::Pem(pem.into()));
self
}
#[must_use]
pub fn with_tls_server_name(mut self, name: impl Into<String>) -> Self {
self.tls_server_name = Some(name.into());
self
}
pub fn apply_settings(&mut self, additional_settings: &str) -> Result<usize, SettingsError> {
let mut applied = 0;
for (index, raw) in additional_settings.lines().enumerate() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let Some((key, value)) = line.split_once('=') else { continue };
let key = key.trim().to_ascii_uppercase();
if !(key.starts_with("FED_") || key.starts_with("TLS_")) {
continue;
}
self.apply(&key, value.trim())
.map_err(|message| SettingsError { line: index + 1, message: format!("{key}: {message}") })?;
applied += 1;
}
Ok(applied)
}
fn apply(&mut self, key: &str, value: &str) -> Result<(), String> {
match key {
"FED_INT_HEART" => self.fed_int_heart = seconds(value, false)?,
"FED_TIMEOUT_HEART" => self.fed_timeout_heart = seconds(value, false)?,
"FED_TIMEOUT_RECONNECT" => self.fed_timeout_reconnect = seconds(value, true)?,
"FED_INT_RECONNECT" => self.fed_int_reconnect = seconds(value, true)?,
"FED_TIMEOUT_CONNECT" => self.fed_timeout_connect = seconds(value, false)?,
"TLS_TRUST_ANCHORS" => {
if value.is_empty() {
return Err("the path of a PEM file is expected".to_owned());
}
self.tls = TlsMode::ServerAuth(TrustAnchors::PemFile(PathBuf::from(value)));
}
"TLS_SERVER_NAME" => {
if value.is_empty() {
return Err("a host name is expected".to_owned());
}
self.tls_server_name = Some(value.to_owned());
}
_ => {
return Err("unknown setting (known: FED_INT_HEART, FED_TIMEOUT_HEART, \
FED_TIMEOUT_RECONNECT, FED_INT_RECONNECT, FED_TIMEOUT_CONNECT, \
TLS_TRUST_ANCHORS, TLS_SERVER_NAME)"
.to_owned());
}
}
Ok(())
}
pub fn client_config(&self, endpoint: Endpoint) -> ClientConfig {
let mut endpoint = endpoint.with_tls(self.tls.clone());
if let Some(name) = &self.tls_server_name {
endpoint = endpoint.with_server_name(name.clone());
}
let mut config = ClientConfig::new(endpoint);
config.fed_int_heart = self.fed_int_heart;
config.fed_timeout_heart = self.fed_timeout_heart;
config.fed_timeout_reconnect = self.fed_timeout_reconnect;
config.reconnect_interval = self.fed_int_reconnect;
config.connect_timeout = self.fed_timeout_connect;
config.new_session_timeout = self.fed_timeout_connect;
config.max_message_size = self.max_message_size;
config
}
}
fn seconds(value: &str, zero_allowed: bool) -> Result<Duration, String> {
let number: f64 = value.parse().map_err(|_| format!("`{value}` is not a number of seconds"))?;
if !number.is_finite() {
return Err(format!("`{value}` is not a number of seconds"));
}
if number < 0.0 || (number == 0.0 && !zero_allowed) {
let bound = if zero_allowed { "must not be negative" } else { "must be greater than zero" };
return Err(format!("`{value}`: the time {bound}"));
}
Duration::try_from_secs_f64(number).map_err(|_| format!("`{value}` is too large"))
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FedProConnector {
options: FedProOptions,
}
impl FedProConnector {
pub fn new(options: FedProOptions) -> Self {
FedProConnector { options }
}
pub fn options(&self) -> &FedProOptions {
&self.options
}
pub fn register(&self, connectors: &mut Connectors) {
for scheme in SCHEMES {
connectors.register(scheme, self.clone());
}
connectors.register_default(self.clone());
}
pub fn connectors(&self) -> Connectors {
let mut connectors = Connectors::new();
self.register(&mut connectors);
connectors
}
pub fn register_globally(&self) {
for scheme in SCHEMES {
crate::link::register_connector(scheme, self.clone());
}
crate::link::register_default_connector(self.clone());
}
pub fn connect(&self, endpoint: Endpoint) -> Result<FedProLink, LinkError> {
FedProLink::connect(self.options.client_config(endpoint))
}
}
impl LinkFactory for FedProConnector {
fn open(&self, configuration: &RtiConfiguration) -> Result<Arc<dyn RtiLink>, LinkError> {
let address = match configuration.rti_address().trim() {
"" => DEFAULT_RTI_ADDRESS,
address => address,
};
let endpoint: Endpoint =
address.parse().map_err(|error: FedProError| LinkError::Unreachable(error.to_string()))?;
let mut options = self.options.clone();
options
.apply_settings(configuration.additional_settings())
.map_err(|error| LinkError::Unreachable(error.to_string()))?;
let link = FedProLink::connect(options.client_config(endpoint))?;
Ok(Arc::new(link))
}
}
pub struct FedProLink {
session: ClientSession,
endpoint: String,
responders: Mutex<BTreeMap<u64, CallbackResponder>>,
next_token: AtomicU64,
closed: AtomicBool,
}
impl std::fmt::Debug for FedProLink {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FedProLink")
.field("endpoint", &self.endpoint)
.field("session_id", &format_args!("{:016x}", self.session.session_id()))
.field("state", &self.state())
.finish()
}
}
impl FedProLink {
pub fn connect(config: ClientConfig) -> Result<FedProLink, LinkError> {
let endpoint = config.endpoint.to_string();
match ClientSession::connect(config) {
Ok(session) => {
let id = format!("{:016x}", session.session_id());
tracing::debug!(%endpoint, session = %id, "session established");
Ok(FedProLink {
session,
endpoint,
responders: Mutex::new(BTreeMap::new()),
next_token: AtomicU64::new(1),
closed: AtomicBool::new(false),
})
}
Err(error) => Err(LinkError::Unreachable(format!("{endpoint}: {error}"))),
}
}
pub fn endpoint(&self) -> &str {
&self.endpoint
}
pub fn session_id(&self) -> u64 {
self.session.session_id()
}
pub fn is_reconnecting(&self) -> bool {
self.session.state() == SessionState::Reconnecting
}
fn is_closed(&self) -> bool {
self.closed.load(Ordering::SeqCst)
}
fn failure(error: FedProError) -> LinkError {
match error {
FedProError::Closed => LinkError::Closed,
other => LinkError::Lost(other.to_string()),
}
}
}
impl RtiLink for FedProLink {
fn call(&self, request: CallRequest) -> Result<CallResponse, LinkError> {
if self.is_closed() {
return Err(LinkError::Closed);
}
self.session.call(request).map_err(FedProLink::failure)
}
fn next_callback(&self, timeout: Option<Duration>) -> Result<Option<LinkCallback>, LinkError> {
loop {
if self.is_closed() {
return Err(LinkError::Closed);
}
match self.session.next_callback(timeout.unwrap_or(UNBOUNDED_WAIT_SLICE)) {
Ok(Some(callback)) => {
let (request, responder) = callback.into_parts();
let id = self.next_token.fetch_add(1, Ordering::Relaxed);
self.responders.lock().unwrap_or_else(PoisonError::into_inner).insert(id, responder);
return Ok(Some(LinkCallback { id, request }));
}
Ok(None) if timeout.is_some() => return Ok(None),
Ok(None) => {}
Err(_) if self.is_closed() => return Err(LinkError::Closed),
Err(error) => return Err(FedProLink::failure(error)),
}
}
}
fn respond(&self, id: u64, response: CallbackResponse) -> Result<(), LinkError> {
let responder = self.responders.lock().unwrap_or_else(PoisonError::into_inner).remove(&id);
match responder {
Some(responder) => {
responder.respond(response);
Ok(())
}
None if self.is_closed() => Err(LinkError::Closed),
None => Err(LinkError::Failed(format!("no callback request with token {id} awaits a response"))),
}
}
fn state(&self) -> LinkState {
if self.is_closed() {
return LinkState::Closed;
}
match self.session.state() {
SessionState::Connected | SessionState::Reconnecting | SessionState::Resumed => LinkState::Open,
SessionState::Terminated => LinkState::Closed,
SessionState::Lost(reason) => LinkState::Lost(reason.to_string()),
}
}
fn close(&self) {
if self.closed.swap(true, Ordering::SeqCst) {
return;
}
if let Err(error) = self.session.terminate() {
let endpoint = &self.endpoint;
tracing::debug!(%endpoint, %error, "the RTI did not confirm the end of the session");
}
let unanswered = std::mem::take(&mut *self.responders.lock().unwrap_or_else(PoisonError::into_inner));
drop(unanswered);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_are_the_ones_of_table_32() {
let options = FedProOptions::new();
assert_eq!(options.fed_int_heart, Duration::from_secs(60));
assert_eq!(options.fed_timeout_heart, Duration::from_secs(180));
assert_eq!(options.fed_timeout_reconnect, Duration::from_secs(600));
assert_eq!(options.tls, TlsMode::EncryptionOnly);
let config = options.client_config("tls://rti.example".parse().unwrap());
assert_eq!(config.fed_int_heart, Duration::from_secs(60));
assert_eq!(config.endpoint.port, 15165);
assert_eq!(config.endpoint.tls, TlsMode::EncryptionOnly);
assert_eq!(config.validate(), Ok(()));
}
#[test]
fn additional_settings_are_applied() {
let mut options = FedProOptions::new();
let text = "# federate side\n\
FED_INT_HEART=5\r\n\
fed_timeout_heart = 12.5\n\
\n\
FED_TIMEOUT_RECONNECT=0\n\
FED_INT_RECONNECT=0.05\n\
FED_TIMEOUT_CONNECT=3\n\
TLS_TRUST_ANCHORS=/etc/rti/ca.pem\n\
TLS_SERVER_NAME= rti.example \n\
vendorSetting=whatever\n\
a line for the RTI without key\n";
assert_eq!(options.apply_settings(text), Ok(7));
assert_eq!(options.fed_int_heart, Duration::from_secs(5));
assert_eq!(options.fed_timeout_heart, Duration::from_millis(12_500));
assert_eq!(options.fed_timeout_reconnect, Duration::ZERO);
assert_eq!(options.fed_int_reconnect, Duration::from_millis(50));
assert_eq!(options.fed_timeout_connect, Duration::from_secs(3));
assert_eq!(options.tls, TlsMode::ServerAuth(TrustAnchors::PemFile("/etc/rti/ca.pem".into())));
assert_eq!(options.tls_server_name.as_deref(), Some("rti.example"));
let config = options.client_config("wss://10.0.0.1:8443/fedpro".parse().unwrap());
assert_eq!(config.reconnect_interval, Duration::from_millis(50));
assert_eq!(config.connect_timeout, Duration::from_secs(3));
assert_eq!(config.endpoint.server_name.as_deref(), Some("rti.example"));
assert!(matches!(config.endpoint.tls, TlsMode::ServerAuth(_)));
assert_eq!(config.endpoint.path, "/fedpro");
}
#[test]
fn unusable_settings_are_reported_with_their_line() {
for (text, line, fragment) in [
("FED_INT_HEART=soon", 1, "not a number"),
("\nFED_INT_HEART=0", 2, "greater than zero"),
("FED_TIMEOUT_HEART=-1", 1, "greater than zero"),
("FED_TIMEOUT_RECONNECT=-0.5", 1, "must not be negative"),
("FED_TIMEOUT_RECONNECT=inf", 1, "not a number"),
("FED_TIMEOUT_CONNECT=1e300", 1, "too large"),
("x=1\nFED_TIMEOUT=3", 2, "unknown setting"),
("TLS_TRUST_ANCHORS=", 1, "PEM file"),
("TLS_SERVER_NAME=", 1, "host name"),
("TLS_VERSION=1.2", 1, "unknown setting"),
] {
let mut options = FedProOptions::new();
let error = options.apply_settings(text).unwrap_err();
assert_eq!(error.line, line, "{text:?}");
assert!(error.message.contains(fragment), "{text:?} gave {error}");
assert!(error.to_string().starts_with(&format!("additional settings, line {line}: ")));
}
}
#[test]
fn typed_options() {
let options = FedProOptions::new().with_trust_anchors_pem("PEM").with_tls_server_name("rti");
assert_eq!(options.tls, TlsMode::ServerAuth(TrustAnchors::Pem(b"PEM".to_vec())));
let options = options.with_trust_anchors_file("/ca.pem");
assert_eq!(options.tls, TlsMode::ServerAuth(TrustAnchors::PemFile("/ca.pem".into())));
let connector = FedProConnector::new(options.clone());
assert_eq!(connector.options(), &options);
assert_eq!(connector.connectors().schemes(), ["tcp", "tls", "ws", "wss"]);
assert!(connector.connectors().resolve("rti.example:15164").is_some());
assert!(connector.connectors().resolve("").is_some());
assert!(connector.connectors().resolve("http://rti.example").is_none());
}
#[test]
fn unusable_addresses_and_settings_are_unreachable() {
let connector = FedProConnector::default();
let open = |address: &str, settings: &str| {
let configuration =
RtiConfiguration::new().with_rti_address(address).with_additional_settings(settings);
match connector.open(&configuration) {
Ok(_) => panic!("{address:?} opened a link"),
Err(error) => error,
}
};
let bad_port = open("tcp://rti.example:port", "");
assert!(matches!(&bad_port, LinkError::Unreachable(text) if text.contains("port")), "{bad_port:?}");
assert!(matches!(open("tcp://", ""), LinkError::Unreachable(_)));
let error = open("tcp://127.0.0.1:1", "FED_INT_HEART=never");
assert!(matches!(&error, LinkError::Unreachable(text) if text.contains("line 1")), "{error:?}");
}
}