microrti-client 0.2.0

Federate side of HLA 4 (IEEE 1516.1-2025): RtiAmbassador and FederateAmbassador over an abstract RTI link.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! The network link: an [`RtiLink`] over a Federate Protocol session (IEEE 1516.1-2025, 12.13), to this
//! project's RTI or to any other HLA 4 RTI.
//!
//! # RTI addresses
//!
//! [`FedProConnector`] opens a session for the RTI address of the [`RtiConfiguration`] given to Connect:
//!
//! | Address | Transport | Default port |
//! | --- | --- | --- |
//! | `tcp://host[:port]`, bare `host[:port]` | TCP | 15164 |
//! | `tls://host[:port]` | TLS 1.3 | 15165 |
//! | `ws://host[:port][/path]` | WebSocket | 80 |
//! | `wss://host[:port][/path]` | secure WebSocket | 443 |
//!
//! An empty address means [`DEFAULT_RTI_ADDRESS`]. An IPv6 address is written in brackets when a port
//! follows. With the cargo feature `fedpro` (enabled by default) a connector with default options is part
//! of the process-wide connectors, so this is all a federate needs:
//!
//! ```no_run
//! use microrti_client::{Callback, CallbackFn, CallbackModel, RtiAmbassador, RtiConfiguration, RtiResult};
//!
//! fn main() -> RtiResult<()> {
//!     let federate = CallbackFn::new(|callback: Callback| {
//!         println!("callback: {callback:?}");
//!         Ok(())
//!     });
//!     let configuration = RtiConfiguration::new()
//!         .with_rti_address("tcp://127.0.0.1:15164")
//!         .with_additional_settings("FED_TIMEOUT_RECONNECT=30");
//!     let rti = RtiAmbassador::new();
//!     rti.connect_with_configuration(federate, CallbackModel::Immediate, &configuration)?;
//!     println!("connected: {}", rti.is_connected());
//!     rti.disconnect()
//! }
//! ```
//!
//! # Settings of the federate
//!
//! The settings of Table 32 and the TLS behaviour of 12.13.5.1 are fields of [`FedProOptions`]. A federate
//! sets them in code (`RtiAmbassador::with_connector(FedProConnector::new(options))`) or, without code,
//! through the additional settings of the [`RtiConfiguration`]: one `KEY=VALUE` per line, blank lines and
//! lines starting with `#` are skipped, keys are not case sensitive, times are seconds and may have a
//! fraction.
//!
//! | Key | Meaning | Default |
//! | --- | --- | --- |
//! | `FED_INT_HEART` | idle time after which a heartbeat is sent (Table 32) | 60 |
//! | `FED_TIMEOUT_HEART` | RTI silence after which the connection is given up and resumed (Table 32) | 180 |
//! | `FED_TIMEOUT_RECONNECT` | time after which resuming is given up and the connection is lost (Table 32) | 600 |
//! | `FED_INT_RECONNECT` | pause between two reconnection attempts (not in the standard) | 1 |
//! | `FED_TIMEOUT_CONNECT` | bound on one connection attempt and on the session start-up (not in the standard) | 10 |
//! | `TLS_TRUST_ANCHORS` | PEM file with the certificates the RTI certificate must chain to; without it TLS only encrypts | none |
//! | `TLS_SERVER_NAME` | name the RTI certificate must match, when it is not the host of the address | host |
//!
//! Lines whose key does not start with `FED_` or `TLS_` are left to the RTI, which receives the additional
//! settings unchanged in the Connect request. An unknown `FED_`/`TLS_` key or an unusable value makes
//! Connect fail with `ConnectionFailed`.
//!
//! # Faults
//!
//! * The RTI cannot be reached, or refuses the session, at Connect: `ConnectionFailed`.
//! * A broken connection is repaired by the session layer (12.13.4.4): calls wait, nothing is lost, the
//!   federate does not notice.
//! * The session cannot be resumed within `FED_TIMEOUT_RECONNECT`, or the RTI has purged it: services
//!   fail with `NotConnected` and the federate ambassador receives Connection Lost (4.4).
//! * Disconnect terminates the session (`CTRL_TERMINATE_SESSION`) and closes the transport.
//!
//! The link owns a small I/O runtime with one thread. Its methods block and therefore must not be called
//! from inside an asynchronous task.

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;

/// The RTI address used when the federate gives none: TCP to the local host on the default port 15164.
pub const DEFAULT_RTI_ADDRESS: &str = "tcp://localhost:15164";

/// The address schemes served by [`FedProConnector`].
pub const SCHEMES: [&str; 4] = ["tcp", "tls", "ws", "wss"];

/// How long one wait inside an unbounded [`RtiLink::next_callback`] lasts before the link looks at its
/// own state again.
const UNBOUNDED_WAIT_SLICE: Duration = Duration::from_secs(1);

/// A setting of the federate side that cannot be used.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("additional settings, line {line}: {message}")]
pub struct SettingsError {
    /// Line of the additional settings text, starting at 1.
    pub line: usize,
    /// What is wrong with it.
    pub message: String,
}

/// The settings of the federate side of a Federate Protocol session.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FedProOptions {
    /// `FED_INT_HEART` (Table 32): a heartbeat is sent when nothing was sent for this long. Default 60 s.
    pub fed_int_heart: Duration,
    /// `FED_TIMEOUT_HEART` (Table 32): when the RTI was silent for this long the connection is given up
    /// and the session resumed on a new one. Default 180 s.
    pub fed_timeout_heart: Duration,
    /// `FED_TIMEOUT_RECONNECT` (Table 32): when the session could not be resumed within this time it is
    /// lost for good. Default 600 s.
    pub fed_timeout_reconnect: Duration,
    /// `FED_INT_RECONNECT`: pause between two reconnection attempts. Default 1 s.
    pub fed_int_reconnect: Duration,
    /// `FED_TIMEOUT_CONNECT`: bound on one connection attempt (handshakes included) and on the wait for
    /// the session to be confirmed. Default 10 s.
    pub fed_timeout_connect: Duration,
    /// TLS behaviour of the `tls` and `wss` transports (12.13.5.1): encryption only (the default), or
    /// validation of the RTI certificate against trust anchors.
    pub tls: TlsMode,
    /// Name the RTI certificate must match (also sent as SNI); the host of the address when `None`.
    pub tls_server_name: Option<String>,
    /// Largest message accepted from the RTI, in bytes, header included. Default 64 MiB.
    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 {
    /// The defaults of Table 32, TLS without certificate validation.
    pub fn new() -> Self {
        Self::default()
    }

    /// Validates the RTI certificate against the certificates of a PEM file (read at every connection
    /// attempt).
    #[must_use]
    pub fn with_trust_anchors_file(mut self, path: impl Into<PathBuf>) -> Self {
        self.tls = TlsMode::ServerAuth(TrustAnchors::PemFile(path.into()));
        self
    }

    /// Validates the RTI certificate against certificates given as PEM text.
    #[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
    }

    /// Sets the name the RTI certificate must match when it is not the host of the RTI address.
    #[must_use]
    pub fn with_tls_server_name(mut self, name: impl Into<String>) -> Self {
        self.tls_server_name = Some(name.into());
        self
    }

    /// Applies the `KEY=VALUE` lines of an additional settings text (see the [module documentation](self)
    /// for the keys). Returns how many settings were applied; lines meant for the RTI are skipped.
    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(())
    }

    /// The session settings for one endpoint.
    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
    }
}

/// Parses a time in seconds, with an optional fraction.
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"))
}

/// Opens Federate Protocol links: the connector for the address schemes `tcp`, `tls`, `ws`, `wss` and
/// for addresses without a scheme.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FedProConnector {
    options: FedProOptions,
}

impl FedProConnector {
    /// A connector whose links start from `options`; the additional settings of each Connect are applied
    /// on top of them.
    pub fn new(options: FedProOptions) -> Self {
        FedProConnector { options }
    }

    /// The options every link of this connector starts from.
    pub fn options(&self) -> &FedProOptions {
        &self.options
    }

    /// Registers this connector in `connectors` for the four schemes and as the default connector.
    pub fn register(&self, connectors: &mut Connectors) {
        for scheme in SCHEMES {
            connectors.register(scheme, self.clone());
        }
        connectors.register_default(self.clone());
    }

    /// A connector set holding only this connector, for
    /// [`RtiAmbassador::with_connectors`](crate::RtiAmbassador::with_connectors).
    pub fn connectors(&self) -> Connectors {
        let mut connectors = Connectors::new();
        self.register(&mut connectors);
        connectors
    }

    /// Makes this connector the process-wide one for the four schemes and for addresses without a scheme
    /// (used by [`RtiAmbassador::new`](crate::RtiAmbassador::new)), in place of the built-in connector
    /// with default options.
    pub fn register_globally(&self) {
        for scheme in SCHEMES {
            crate::link::register_connector(scheme, self.clone());
        }
        crate::link::register_default_connector(self.clone());
    }

    /// Establishes a session with the RTI at `endpoint`, using the options of this connector as they are
    /// except for the TLS behaviour, which is taken from the options and not from the endpoint.
    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))
    }
}

/// An [`RtiLink`] over one Federate Protocol session.
pub struct FedProLink {
    session: ClientSession,
    endpoint: String,
    /// The means to answer the callback requests handed out and not answered yet, by link token.
    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 {
    /// Connects to the RTI and establishes a session. Fails with [`LinkError::Unreachable`] when the RTI
    /// cannot be reached, refuses the session or the settings cannot be used.
    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}"))),
        }
    }

    /// The RTI endpoint of this link, in the textual form of an RTI address.
    pub fn endpoint(&self) -> &str {
        &self.endpoint
    }

    /// The session identifier the RTI assigned.
    pub fn session_id(&self) -> u64 {
        self.session.session_id()
    }

    /// `true` while the session is repairing a broken connection (invisible through [`RtiLink::state`]).
    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;
        }
        // CTRL_TERMINATE_SESSION, wait for the confirmation, close the transport (12.13.4.6 a) 6). This
        // also ends the callback stream, which wakes a blocked `next_callback`.
        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");
        }
        // The callbacks still unanswered belong to a session that is over.
        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:?}");
    }
}