microrti-client 0.1.2

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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
//! [`RtiAmbassador`]: connection handling, callback delivery and the plumbing shared by every service.
//!
//! The service methods themselves are generated into `services.rs`; this file holds everything that is
//! implemented in the client library and not by the RTI: the callback models and the four services of
//! 12.13.3.2, the checks of 12.8, and the bookkeeping around Connect, Disconnect, Join and Resign.

use std::collections::VecDeque;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError, Weak};
use std::thread::{self, JoinHandle, ThreadId};
use std::time::{Duration, Instant};

use microrti_core::{ExceptionKind, HLA_VERSION, RtiError, RtiResult, TimeKind};
use microrti_proto as proto;
pub(crate) use proto::call_request::CallRequest as Call;
pub(crate) use proto::call_response::CallResponse as Reply;
use proto::callback_response::CallbackResponse as CallbackReply;

use crate::callback::{Callback, FederateAmbassador};
use crate::federate::{CallbackResult, FederateInternalError};
use crate::handles::FederateHandle;
use crate::link::{Connectors, LinkCallback, LinkError, LinkFactory, LinkState, RtiLink, global_connectors};
use crate::types::{
    CallbackModel, ConfigurationResult, Credentials, FomModule, JoinResult, ResignAction, RtiConfiguration,
};
use crate::wire::{FromWire, ToWire, WireCx, malformed};

/// Defines one service method of [`RtiAmbassador`]: build the request message from the arguments, exchange
/// it over the link, check the response alternative and decode the result.
macro_rules! service {
    (
        $(#[$doc:meta])*
        fn $name:ident($($arg:ident : $ty:ty),* $(,)?) -> $ret:ty;
        $request:ident { $($field:ident : $value:expr),* $(,)? } => $response:ident $(. $result:ident)?
    ) => {
        $(#[$doc])*
        pub fn $name(&self, $($arg: $ty),*) -> $crate::RtiResult<$ret> {
            let cx = self.wire_cx();
            let request = $crate::proto::$request { $($field: $crate::wire::ToWire::to_wire($value, &cx)?),* };
            match self.invoke($crate::ambassador::Call::$request(request))? {
                $crate::ambassador::Reply::$response(response) => {
                    $crate::ambassador::service!(@result response, cx $(, $result)?)
                }
                _ => Err($crate::ambassador::unexpected_response(stringify!($request))),
            }
        }
    };
    (@result $response:ident, $cx:ident) => {{
        let _ = ($response, $cx);
        Ok(())
    }};
    (@result $response:ident, $cx:ident, $result:ident) => {
        $crate::wire::FromWire::from_wire($response.$result, &$cx)
    };
}
pub(crate) use service;

/// The error for a response that is neither the expected alternative nor an exception.
pub(crate) fn unexpected_response(request: &str) -> RtiError {
    RtiError::internal(format!("the RTI answered {request} with a response of another service"))
}

fn not_allowed(service: &str) -> RtiError {
    RtiError::new(
        ExceptionKind::CallNotAllowedFromWithinCallback,
        format!("{service} cannot be invoked from within a callback"),
    )
}

/// Longest time a waiting thread goes without looking at the ambassador state again.
const POLL_INTERVAL: Duration = Duration::from_millis(50);

/// Longest time the delivery of a callback waits for a Join Federation Execution in flight.
const JOIN_WAIT: Duration = Duration::from_secs(5);

type BoxedFederate = Box<dyn FederateAmbassador + Send>;

/// Where Connect gets its link from.
enum LinkSource {
    /// The process-wide connectors, looked up at connect time.
    Global,
    /// Connectors given to this ambassador.
    Connectors(Connectors),
    /// One connector given to this ambassador, used for every RTI address.
    Factory(Box<dyn LinkFactory>),
    /// A link built by the application; it serves one connection.
    Link(Mutex<Option<Arc<dyn RtiLink>>>),
}

impl LinkSource {
    fn open(&self, configuration: &RtiConfiguration) -> Result<Arc<dyn RtiLink>, LinkError> {
        match self {
            LinkSource::Global => global_connectors().open(configuration),
            LinkSource::Connectors(connectors) => connectors.open(configuration),
            LinkSource::Factory(factory) => factory.open(configuration),
            LinkSource::Link(slot) => {
                slot.lock().unwrap_or_else(PoisonError::into_inner).take().ok_or_else(|| {
                    LinkError::Unreachable(
                        "the link given to RtiAmbassador::with_link was already used".to_owned(),
                    )
                })
            }
        }
    }
}

/// Everything that changes while the ambassador is used. One mutex guards it; it is never held while the
/// link or the federate ambassador is called.
struct State {
    /// The link; `Some` exactly while in the Connected state.
    link: Option<Arc<dyn RtiLink>>,
    /// A Connect invocation is in progress.
    connecting: bool,
    /// Incremented when a connection is established or released; waiting threads of an older connection
    /// notice it and stop.
    generation: u64,
    model: CallbackModel,
    callbacks_enabled: bool,
    /// Time representation of the joined federation execution; `Some` exactly while joined.
    time_kind: Option<TimeKind>,
    /// Time representation used to decode callbacks: the one of the latest join on this connection. It
    /// outlives a resignation, because callbacks sent before it may still be queued.
    callback_time: Option<TimeKind>,
    /// Number of Join Federation Execution invocations in flight.
    joining: u32,
    /// The thread that is executing a callback right now.
    in_callback: Option<ThreadId>,
    /// Fault description of a lost connection the federate has not been told about yet.
    lost: Option<String>,
    /// Callbacks pulled from the link and not delivered yet, oldest first.
    pending: VecDeque<LinkCallback>,
    /// The delivery thread of the IMMEDIATE model.
    thread: Option<JoinHandle<()>>,
    save_in_progress: bool,
    restore_in_progress: bool,
}

impl State {
    fn within_callback(&self) -> bool {
        self.in_callback == Some(thread::current().id())
    }

    /// Forgets everything tied to a federation execution membership.
    fn leave_federation(&mut self) {
        self.time_kind = None;
        self.save_in_progress = false;
        self.restore_in_progress = false;
    }

    /// Forgets everything tied to a connection.
    fn leave_connection(&mut self) -> Option<Arc<dyn RtiLink>> {
        self.leave_federation();
        self.callback_time = None;
        self.pending.clear();
        self.link.take()
    }

    fn check_save_restore(&self) -> RtiResult<()> {
        if self.save_in_progress {
            return Err(RtiError::new(ExceptionKind::SaveInProgress, "a federate save is in progress"));
        }
        if self.restore_in_progress {
            return Err(RtiError::new(ExceptionKind::RestoreInProgress, "a federate restore is in progress"));
        }
        Ok(())
    }
}

/// Something to hand to the federate ambassador.
enum Item {
    /// The link reported a fault: Connection Lost (4.4), produced locally.
    Lost(String),
    /// A callback request from the RTI.
    Callback(Box<LinkCallback>),
}

/// What remains to be done once a callback has returned.
enum After {
    Nothing,
    /// The RTI resigned the federate: it is no longer joined.
    Resigned,
    /// The RTI announced the end of the connection.
    Severed,
}

struct Shared {
    source: LinkSource,
    state: Mutex<State>,
    /// Signalled on every change of `state` a waiting thread may care about.
    changed: Condvar,
    /// The federate ambassador. Its mutex is the delivery lock: whoever holds it is the only one pulling
    /// callbacks from the link and invoking the federate (12.8). Always taken before `state`.
    federate: Mutex<Option<BoxedFederate>>,
}

impl Shared {
    fn new(source: LinkSource) -> Self {
        Shared {
            source,
            state: Mutex::new(State {
                link: None,
                connecting: false,
                generation: 0,
                model: CallbackModel::Evoked,
                callbacks_enabled: true,
                time_kind: None,
                callback_time: None,
                joining: 0,
                in_callback: None,
                lost: None,
                pending: VecDeque::new(),
                thread: None,
                save_in_progress: false,
                restore_in_progress: false,
            }),
            changed: Condvar::new(),
            federate: Mutex::new(None),
        }
    }

    fn lock(&self) -> MutexGuard<'_, State> {
        self.state.lock().unwrap_or_else(PoisonError::into_inner)
    }

    fn lock_federate(&self) -> MutexGuard<'_, Option<BoxedFederate>> {
        self.federate.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// The link reported a fault: enter the Not Connected state and remember that the federate has to be
    /// told with Connection Lost (4.4). Does nothing if `link` is not the current link any more.
    fn mark_lost(&self, link: &Arc<dyn RtiLink>, reason: String) {
        {
            let mut state = self.lock();
            if !state.link.as_ref().is_some_and(|current| Arc::ptr_eq(current, link)) {
                return;
            }
            state.leave_connection();
            state.lost = Some(reason);
            self.changed.notify_all();
        }
        link.close();
    }

    /// The RTI itself announced the end of the connection: enter the Not Connected state silently.
    fn sever(&self, link: &Arc<dyn RtiLink>) {
        {
            let mut state = self.lock();
            if !state.link.as_ref().is_some_and(|current| Arc::ptr_eq(current, link)) {
                return;
            }
            state.leave_connection();
            self.changed.notify_all();
        }
        link.close();
    }

    /// Leaves the Connected state on purpose (Disconnect or drop): closes the link, stops the delivery
    /// thread and drops the federate ambassador.
    fn release(&self) {
        let (link, thread, on_callback_thread) = {
            let mut state = self.lock();
            state.generation += 1;
            state.lost = None;
            state.callbacks_enabled = true;
            let link = state.leave_connection();
            let thread = state.thread.take();
            self.changed.notify_all();
            (link, thread, state.within_callback())
        };
        if let Some(link) = link {
            link.close();
        }
        if let Some(thread) = thread
            && thread.thread().id() != thread::current().id()
        {
            let _ = thread.join();
        }
        if !on_callback_thread {
            let federate = self.lock_federate().take();
            drop(federate);
        }
    }

    /// Waits up to `wait` for the next thing to deliver and marks the calling thread as executing a
    /// callback. Must be called with the delivery lock held. Returns `None` on timeout and when the
    /// connection `generation` belongs to is gone.
    fn take_deliverable(&self, generation: u64, wait: Duration) -> Option<Item> {
        let deadline = Instant::now() + wait;
        loop {
            let link = {
                let mut state = self.lock();
                loop {
                    if state.generation != generation {
                        return None;
                    }
                    if state.callbacks_enabled {
                        if let Some(reason) = state.lost.take() {
                            state.in_callback = Some(thread::current().id());
                            return Some(Item::Lost(reason));
                        }
                        if let Some(callback) = state.pending.pop_front() {
                            state.in_callback = Some(thread::current().id());
                            return Some(Item::Callback(Box::new(callback)));
                        }
                        if let Some(link) = state.link.clone() {
                            break link;
                        }
                    }
                    // Callbacks are disabled or there is no connection: wait for that to change.
                    let now = Instant::now();
                    if now >= deadline {
                        return None;
                    }
                    state = self
                        .changed
                        .wait_timeout(state, deadline - now)
                        .unwrap_or_else(PoisonError::into_inner)
                        .0;
                }
            };
            let remaining = deadline.saturating_duration_since(Instant::now());
            match link.next_callback(Some(remaining.min(POLL_INTERVAL))) {
                Ok(Some(callback)) => {
                    let mut state = self.lock();
                    if state.generation == generation {
                        state.pending.push_back(callback);
                    }
                }
                Ok(None) => {
                    if Instant::now() >= deadline {
                        return None;
                    }
                }
                Err(LinkError::Lost(reason)) => self.mark_lost(&link, reason),
                Err(error) => self.mark_lost(&link, error.to_string()),
            }
        }
    }

    /// The pending callback indicator of 10.57 and 10.58. Must be called with the delivery lock held.
    fn has_pending(&self, generation: u64) -> bool {
        let link = {
            let state = self.lock();
            if state.generation != generation {
                return false;
            }
            if !state.pending.is_empty() || state.lost.is_some() {
                return true;
            }
            match state.link.clone() {
                Some(link) => link,
                None => return false,
            }
        };
        match link.next_callback(Some(Duration::ZERO)) {
            Ok(Some(callback)) => {
                let mut state = self.lock();
                if state.generation == generation {
                    state.pending.push_back(callback);
                }
                true
            }
            Ok(None) => false,
            Err(LinkError::Lost(reason)) => {
                self.mark_lost(&link, reason);
                true
            }
            Err(error) => {
                self.mark_lost(&link, error.to_string());
                true
            }
        }
    }

    /// Hands one item to the federate ambassador and answers the RTI. `take_deliverable` has already
    /// marked the calling thread as executing a callback.
    fn deliver(&self, federate: &mut Option<BoxedFederate>, item: Item) {
        match item {
            Item::Lost(fault_description) => {
                if let Some(federate) = federate.as_mut()
                    && let Err(error) = run(federate, Callback::ConnectionLost { fault_description })
                {
                    tracing::warn!(%error, "the Connection Lost callback failed");
                }
            }
            Item::Callback(delivery) => self.deliver_request(federate, *delivery),
        }
        self.lock().in_callback = None;
        self.changed.notify_all();
    }

    fn deliver_request(&self, federate: &mut Option<BoxedFederate>, delivery: LinkCallback) {
        let (link, cx) = {
            let mut state = self.lock();
            // A join in flight decides how logical times are decoded: wait for its outcome (bounded, so
            // that an RTI holding back the join response cannot block delivery for good).
            let deadline = Instant::now() + JOIN_WAIT;
            while state.joining > 0 {
                let now = Instant::now();
                if now >= deadline {
                    break;
                }
                state = self
                    .changed
                    .wait_timeout(state, deadline - now)
                    .unwrap_or_else(PoisonError::into_inner)
                    .0;
            }
            (state.link.clone(), WireCx { time: state.callback_time })
        };
        let decoded = match delivery.request.callback_request {
            Some(wire) => Callback::from_wire(wire, &cx)
                .map_err(|error| FederateInternalError::new(format!("cannot decode the callback: {error}"))),
            None => Err(FederateInternalError::new("callback request without a known alternative")),
        };
        let mut after = After::Nothing;
        let outcome = match decoded {
            Ok(callback) => {
                after = self.note(&callback);
                match federate.as_mut() {
                    Some(federate) => run(federate, callback),
                    None => Ok(()),
                }
            }
            Err(error) => Err(error),
        };
        let response = match outcome {
            Ok(()) => CallbackReply::CallbackSucceeded(proto::CallbackSucceeded {}),
            Err(error) => {
                tracing::warn!(%error, "a callback failed");
                CallbackReply::CallbackFailed(proto::ExceptionData {
                    exception_name: FederateInternalError::NAME.to_owned(),
                    details: error.message,
                })
            }
        };
        if let Some(link) = &link {
            let response = proto::CallbackResponse { callback_response: Some(response) };
            if let Err(error) = link.respond(delivery.id, response) {
                tracing::debug!(%error, "could not send a callback response");
            }
        }
        match after {
            After::Nothing => {}
            After::Resigned => self.lock().leave_federation(),
            After::Severed => {
                if let Some(link) = &link {
                    self.sever(link);
                }
            }
        }
    }

    /// Bookkeeping driven by the callbacks themselves: whether a federate save or restore is in progress
    /// (needed by 10.59 and 10.60) and whether the federate stays joined and connected.
    fn note(&self, callback: &Callback) -> After {
        let mut state = self.lock();
        match callback {
            Callback::InitiateFederateSave { .. } | Callback::InitiateFederateSaveWithTime { .. } => {
                state.save_in_progress = true;
            }
            Callback::FederationSaved | Callback::FederationNotSaved { .. } => state.save_in_progress = false,
            Callback::FederationRestoreBegun => state.restore_in_progress = true,
            Callback::FederationRestored | Callback::FederationNotRestored { .. } => {
                state.restore_in_progress = false;
            }
            Callback::FederateResigned { .. } => return After::Resigned,
            Callback::ConnectionLost { .. } => return After::Severed,
            _ => {}
        }
        After::Nothing
    }
}

/// Runs the federate's code. A panic in it is reported like a failed callback instead of tearing down the
/// delivery thread.
fn run(federate: &mut BoxedFederate, callback: Callback) -> CallbackResult {
    match catch_unwind(AssertUnwindSafe(|| federate.handle_callback(callback))) {
        Ok(result) => result,
        Err(_) => Err(FederateInternalError::new("the federate ambassador panicked")),
    }
}

/// Body of the delivery thread of the IMMEDIATE callback model.
fn immediate_loop(shared: &Shared, generation: u64) {
    loop {
        {
            let state = shared.lock();
            if state.generation != generation || (state.link.is_none() && state.lost.is_none()) {
                return;
            }
        }
        let mut federate = shared.lock_federate();
        if let Some(item) = shared.take_deliverable(generation, POLL_INTERVAL) {
            shared.deliver(&mut federate, item);
        }
    }
}

/// Releases the connection when the last [`RtiAmbassador`] clone goes away.
struct Owner {
    shared: Arc<Shared>,
}

impl Drop for Owner {
    fn drop(&mut self) {
        self.shared.release();
    }
}

/// The federate's access to the RTI: every federate-initiated service of clauses 4 to 10 as a method.
///
/// The ambassador is `Send + Sync` and cheap to clone; all clones are the same ambassador and services may
/// be invoked from several threads at once (12.8). Each ambassador has at most one connection to an RTI
/// and one federate ambassador (12.7). Dropping the last clone releases the connection.
///
/// A federate ambassador that wants to invoke services from inside its callbacks should keep a
/// [`WeakRtiAmbassador`] (see [`RtiAmbassador::downgrade`]): a strong clone stored inside the federate
/// ambassador keeps the connection alive until Disconnect is invoked.
#[derive(Clone)]
pub struct RtiAmbassador {
    owner: Arc<Owner>,
}

/// A reference to an [`RtiAmbassador`] that does not keep its connection alive.
#[derive(Clone)]
pub struct WeakRtiAmbassador {
    owner: Weak<Owner>,
}

impl WeakRtiAmbassador {
    /// The ambassador, unless its last clone was dropped.
    pub fn upgrade(&self) -> Option<RtiAmbassador> {
        self.owner.upgrade().map(|owner| RtiAmbassador { owner })
    }
}

impl std::fmt::Debug for WeakRtiAmbassador {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("WeakRtiAmbassador")
    }
}

impl Default for RtiAmbassador {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for RtiAmbassador {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let state = self.shared().lock();
        f.debug_struct("RtiAmbassador")
            .field("connected", &state.link.is_some())
            .field("callback_model", &state.model)
            .field("callbacks_enabled", &state.callbacks_enabled)
            .field("time_kind", &state.time_kind)
            .finish()
    }
}

impl RtiAmbassador {
    fn from_source(source: LinkSource) -> Self {
        RtiAmbassador { owner: Arc::new(Owner { shared: Arc::new(Shared::new(source)) }) }
    }

    /// An ambassador whose Connect opens its link with the process-wide connectors (see
    /// [`register_connector`](crate::register_connector)), selected by the scheme of the RTI address.
    pub fn new() -> Self {
        Self::from_source(LinkSource::Global)
    }

    /// An ambassador whose Connect opens its link with the given connectors.
    pub fn with_connectors(connectors: Connectors) -> Self {
        Self::from_source(LinkSource::Connectors(connectors))
    }

    /// An ambassador whose Connect opens its link with `factory`, whatever the RTI address.
    pub fn with_connector(factory: impl LinkFactory + 'static) -> Self {
        Self::from_source(LinkSource::Factory(Box::new(factory)))
    }

    /// An ambassador whose Connect uses a link the application has already built. The link serves one
    /// connection: after Disconnect, a second Connect fails with `ConnectionFailed`.
    pub fn with_link(link: Arc<dyn RtiLink>) -> Self {
        Self::from_source(LinkSource::Link(Mutex::new(Some(link))))
    }

    /// A reference that does not keep the connection alive, for use inside a federate ambassador.
    pub fn downgrade(&self) -> WeakRtiAmbassador {
        WeakRtiAmbassador { owner: Arc::downgrade(&self.owner) }
    }

    fn shared(&self) -> &Arc<Shared> {
        &self.owner.shared
    }

    /// The HLA version this API implements (`getHLAversion` of the standard APIs).
    pub fn hla_version(&self) -> &'static str {
        HLA_VERSION
    }

    /// True while in the Connected state. Also notices a fault the link has reported in the meantime.
    pub fn is_connected(&self) -> bool {
        let Some(link) = self.shared().lock().link.clone() else {
            return false;
        };
        match link.state() {
            LinkState::Open => true,
            LinkState::Lost(reason) => {
                self.shared().mark_lost(&link, reason);
                false
            }
            LinkState::Closed => {
                self.shared().mark_lost(&link, "the link to the RTI was closed".to_owned());
                false
            }
        }
    }

    /// The callback model chosen at Connect, while connected.
    pub fn callback_model(&self) -> Option<CallbackModel> {
        let state = self.shared().lock();
        state.link.as_ref().map(|_| state.model)
    }

    /// The time representation of the federation execution the federate is joined to (the role of
    /// `getTimeFactory` in the standard APIs): use it to create and interpret logical times.
    ///
    /// Fails with `NotConnected` or `FederateNotExecutionMember`.
    pub fn time_kind(&self) -> RtiResult<TimeKind> {
        let state = self.shared().lock();
        if state.link.is_none() {
            return Err(RtiError::new(ExceptionKind::NotConnected, "not connected to an RTI"));
        }
        state.time_kind.ok_or_else(|| {
            RtiError::new(ExceptionKind::FederateNotExecutionMember, "not joined to a federation execution")
        })
    }

    pub(crate) fn wire_cx(&self) -> WireCx {
        WireCx { time: self.shared().lock().time_kind }
    }

    /// Exchanges one request over the link. Exceptions raised by the RTI and link failures become errors;
    /// anything else is the response alternative for the caller to check.
    pub(crate) fn invoke(&self, request: Call) -> RtiResult<Reply> {
        let Some(link) = self.shared().lock().link.clone() else {
            return Err(RtiError::new(ExceptionKind::NotConnected, "not connected to an RTI"));
        };
        match link.call(proto::CallRequest { call_request: Some(request) }) {
            Ok(response) => match response.call_response {
                Some(Reply::ExceptionData(data)) => Err(RtiError::from_exception_data(&data)),
                Some(reply) => Ok(reply),
                None => Err(malformed("call response without a known alternative")),
            },
            Err(LinkError::Lost(reason)) => {
                let error = RtiError::new(ExceptionKind::NotConnected, format!("connection lost: {reason}"));
                self.shared().mark_lost(&link, reason);
                Err(error)
            }
            Err(LinkError::Closed) => {
                Err(RtiError::new(ExceptionKind::NotConnected, "the link to the RTI is closed"))
            }
            Err(error) => Err(RtiError::internal(error.to_string())),
        }
    }

    fn forbid_within_callback(&self, service: &str) -> RtiResult<()> {
        if self.shared().lock().within_callback() { Err(not_allowed(service)) } else { Ok(()) }
    }

    // ---- Connect and Disconnect (4.2, 4.3) ----

    /// Connect service (4.2) without configuration and credentials; wire message `ConnectRequest`.
    ///
    /// `federate_ambassador` receives the callbacks of this connection according to `callback_model`. The
    /// link is opened for the default (empty) RTI address.
    pub fn connect(
        &self,
        federate_ambassador: impl FederateAmbassador + Send + 'static,
        callback_model: CallbackModel,
    ) -> RtiResult<ConfigurationResult> {
        self.connect_impl(Box::new(federate_ambassador), callback_model, None, None)
    }

    /// Connect service (4.2) with credentials; wire message `ConnectWithCredentialsRequest`.
    pub fn connect_with_credentials(
        &self,
        federate_ambassador: impl FederateAmbassador + Send + 'static,
        callback_model: CallbackModel,
        credentials: &Credentials,
    ) -> RtiResult<ConfigurationResult> {
        self.connect_impl(Box::new(federate_ambassador), callback_model, None, Some(credentials))
    }

    /// Connect service (4.2) with a configuration; wire message `ConnectWithConfigurationRequest`.
    ///
    /// The RTI address of the configuration selects the connector that opens the link.
    pub fn connect_with_configuration(
        &self,
        federate_ambassador: impl FederateAmbassador + Send + 'static,
        callback_model: CallbackModel,
        configuration: &RtiConfiguration,
    ) -> RtiResult<ConfigurationResult> {
        self.connect_impl(Box::new(federate_ambassador), callback_model, Some(configuration), None)
    }

    /// Connect service (4.2) with a configuration and credentials; wire message
    /// `ConnectWithConfigurationAndCredentialsRequest`.
    pub fn connect_with_configuration_and_credentials(
        &self,
        federate_ambassador: impl FederateAmbassador + Send + 'static,
        callback_model: CallbackModel,
        configuration: &RtiConfiguration,
        credentials: &Credentials,
    ) -> RtiResult<ConfigurationResult> {
        self.connect_impl(
            Box::new(federate_ambassador),
            callback_model,
            Some(configuration),
            Some(credentials),
        )
    }

    fn connect_impl(
        &self,
        federate: BoxedFederate,
        model: CallbackModel,
        configuration: Option<&RtiConfiguration>,
        credentials: Option<&Credentials>,
    ) -> RtiResult<ConfigurationResult> {
        let shared = self.shared();
        let stale_thread = {
            let mut state = shared.lock();
            if state.within_callback() {
                return Err(not_allowed("Connect"));
            }
            if state.link.is_some() || state.connecting {
                return Err(RtiError::new(
                    ExceptionKind::AlreadyConnected,
                    "this RTI ambassador is already connected",
                ));
            }
            state.connecting = true;
            state.lost = None;
            state.thread.take()
        };
        // The delivery thread of a connection that was lost earlier has nothing left to do.
        if let Some(thread) = stale_thread {
            let _ = thread.join();
        }
        let opened = self.open(configuration, credentials);
        let mut federate_slot = shared.lock_federate();
        let mut state = shared.lock();
        state.connecting = false;
        let (link, result) = opened?;
        state.generation += 1;
        state.model = model;
        state.callbacks_enabled = true;
        state.lost = None;
        state.leave_connection();
        if model == CallbackModel::Immediate {
            let generation = state.generation;
            let thread_shared = Arc::clone(shared);
            let spawned = thread::Builder::new()
                .name("microrti-callbacks".to_owned())
                .spawn(move || immediate_loop(&thread_shared, generation));
            match spawned {
                Ok(thread) => state.thread = Some(thread),
                Err(error) => {
                    drop(state);
                    link.close();
                    return Err(RtiError::internal(format!("cannot start the callback thread: {error}")));
                }
            }
        }
        state.link = Some(link);
        *federate_slot = Some(federate);
        shared.changed.notify_all();
        Ok(result)
    }

    /// Opens the link and performs the Connect exchange on it.
    fn open(
        &self,
        configuration: Option<&RtiConfiguration>,
        credentials: Option<&Credentials>,
    ) -> RtiResult<(Arc<dyn RtiLink>, ConfigurationResult)> {
        let cx = WireCx::default();
        let request = match (configuration, credentials) {
            (None, None) => Call::ConnectRequest(proto::ConnectRequest {}),
            (None, Some(credentials)) => {
                Call::ConnectWithCredentialsRequest(proto::ConnectWithCredentialsRequest {
                    credentials: credentials.to_wire(&cx)?,
                })
            }
            (Some(configuration), None) => {
                Call::ConnectWithConfigurationRequest(proto::ConnectWithConfigurationRequest {
                    rti_configuration: configuration.to_wire(&cx)?,
                })
            }
            (Some(configuration), Some(credentials)) => Call::ConnectWithConfigurationAndCredentialsRequest(
                proto::ConnectWithConfigurationAndCredentialsRequest {
                    rti_configuration: configuration.to_wire(&cx)?,
                    credentials: credentials.to_wire(&cx)?,
                },
            ),
        };
        let connection_failed =
            |error: LinkError| RtiError::new(ExceptionKind::ConnectionFailed, error.to_string());
        let default_configuration = RtiConfiguration::default();
        let link = self
            .shared()
            .source
            .open(configuration.unwrap_or(&default_configuration))
            .map_err(connection_failed)?;
        let outcome = match link.call(proto::CallRequest { call_request: Some(request) }) {
            Ok(response) => match (configuration.is_some(), credentials.is_some(), response.call_response) {
                (_, _, Some(Reply::ExceptionData(data))) => Err(RtiError::from_exception_data(&data)),
                (false, false, Some(Reply::ConnectResponse(response))) => Ok(response.configuration_result),
                (false, true, Some(Reply::ConnectWithCredentialsResponse(response))) => {
                    Ok(response.configuration_result)
                }
                (true, false, Some(Reply::ConnectWithConfigurationResponse(response))) => {
                    Ok(response.configuration_result)
                }
                (true, true, Some(Reply::ConnectWithConfigurationAndCredentialsResponse(response))) => {
                    Ok(response.configuration_result)
                }
                _ => Err(unexpected_response("Connect")),
            },
            Err(error) => Err(connection_failed(error)),
        };
        match outcome.and_then(|result| ConfigurationResult::from_wire(result, &cx)) {
            Ok(result) => Ok((link, result)),
            Err(error) => {
                link.close();
                Err(error)
            }
        }
    }

    /// Disconnect service (4.3); wire message `DisconnectRequest`.
    ///
    /// On success the link is closed, the delivery thread of the IMMEDIATE model has ended and the
    /// federate ambassador is dropped. Does nothing when not connected.
    pub fn disconnect(&self) -> RtiResult<()> {
        let shared = self.shared();
        let link = {
            let state = shared.lock();
            if state.within_callback() {
                return Err(not_allowed("Disconnect"));
            }
            state.link.clone()
        };
        if let Some(link) = &link {
            let request = Call::DisconnectRequest(proto::DisconnectRequest {});
            match link.call(proto::CallRequest { call_request: Some(request) }) {
                Ok(response) => match response.call_response {
                    Some(Reply::DisconnectResponse(_)) => {}
                    Some(Reply::ExceptionData(data)) => return Err(RtiError::from_exception_data(&data)),
                    _ => return Err(unexpected_response("DisconnectRequest")),
                },
                // The connection is gone already: there is nothing left to disconnect from.
                Err(LinkError::Lost(_) | LinkError::Closed) => {}
                Err(error) => return Err(RtiError::internal(error.to_string())),
            }
        }
        shared.release();
        Ok(())
    }

    // ---- Join and Resign (4.11, 4.12) ----

    /// Join Federation Execution service (4.11); wire message `JoinFederationExecutionRequest`.
    ///
    /// On success the ambassador knows the time representation of the federation execution (see
    /// [`RtiAmbassador::time_kind`]). If the RTI names a logical time implementation other than the two
    /// standardized ones, the federate is resigned again and `CouldNotCreateLogicalTimeFactory` is raised.
    pub fn join_federation_execution(
        &self,
        federate_type: &str,
        federation_name: &str,
    ) -> RtiResult<JoinResult> {
        let cx = self.wire_cx();
        self.join(Call::JoinFederationExecutionRequest(proto::JoinFederationExecutionRequest {
            federate_type: federate_type.to_wire(&cx)?,
            federation_name: federation_name.to_wire(&cx)?,
        }))
    }

    /// Join Federation Execution service (4.11) with additional FOM modules; wire message
    /// `JoinFederationExecutionWithModulesRequest`.
    pub fn join_federation_execution_with_modules(
        &self,
        federate_type: &str,
        federation_name: &str,
        additional_fom_modules: &[FomModule],
    ) -> RtiResult<JoinResult> {
        let cx = self.wire_cx();
        self.join(Call::JoinFederationExecutionWithModulesRequest(
            proto::JoinFederationExecutionWithModulesRequest {
                federate_type: federate_type.to_wire(&cx)?,
                federation_name: federation_name.to_wire(&cx)?,
                additional_fom_modules: additional_fom_modules.to_wire(&cx)?,
            },
        ))
    }

    /// Join Federation Execution service (4.11) with a federate name; wire message
    /// `JoinFederationExecutionWithNameRequest`.
    pub fn join_federation_execution_with_name(
        &self,
        federate_name: &str,
        federate_type: &str,
        federation_name: &str,
    ) -> RtiResult<JoinResult> {
        let cx = self.wire_cx();
        self.join(Call::JoinFederationExecutionWithNameRequest(
            proto::JoinFederationExecutionWithNameRequest {
                federate_name: federate_name.to_wire(&cx)?,
                federate_type: federate_type.to_wire(&cx)?,
                federation_name: federation_name.to_wire(&cx)?,
            },
        ))
    }

    /// Join Federation Execution service (4.11) with a federate name and additional FOM modules; wire
    /// message `JoinFederationExecutionWithNameAndModulesRequest`.
    pub fn join_federation_execution_with_name_and_modules(
        &self,
        federate_name: &str,
        federate_type: &str,
        federation_name: &str,
        additional_fom_modules: &[FomModule],
    ) -> RtiResult<JoinResult> {
        let cx = self.wire_cx();
        self.join(Call::JoinFederationExecutionWithNameAndModulesRequest(
            proto::JoinFederationExecutionWithNameAndModulesRequest {
                federate_name: federate_name.to_wire(&cx)?,
                federate_type: federate_type.to_wire(&cx)?,
                federation_name: federation_name.to_wire(&cx)?,
                additional_fom_modules: additional_fom_modules.to_wire(&cx)?,
            },
        ))
    }

    fn join(&self, request: Call) -> RtiResult<JoinResult> {
        self.forbid_within_callback("Join Federation Execution")?;
        let shared = self.shared();
        // Callbacks pulled while the join is in flight wait for its outcome, see `deliver_request`.
        shared.lock().joining += 1;
        let outcome = self.exchange_join(request);
        let mut state = shared.lock();
        state.joining -= 1;
        if let Ok(joined) = &outcome {
            state.leave_federation();
            state.time_kind = Some(joined.time_kind);
            state.callback_time = Some(joined.time_kind);
        }
        shared.changed.notify_all();
        drop(state);
        outcome
    }

    fn exchange_join(&self, request: Call) -> RtiResult<JoinResult> {
        let result = match self.invoke(request)? {
            Reply::JoinFederationExecutionResponse(response) => response.result,
            Reply::JoinFederationExecutionWithModulesResponse(response) => response.result,
            Reply::JoinFederationExecutionWithNameResponse(response) => response.result,
            Reply::JoinFederationExecutionWithNameAndModulesResponse(response) => response.result,
            _ => return Err(unexpected_response("JoinFederationExecution")),
        };
        decode_join_result(result).inspect_err(|_| {
            // The RTI considers the federate joined, but this ambassador cannot serve it: undo the join.
            let undo =
                proto::ResignFederationExecutionRequest { resign_action: ResignAction::NoAction.to_i32() };
            if let Err(resign_error) = self.invoke(Call::ResignFederationExecutionRequest(undo)) {
                tracing::warn!(error = %resign_error, "could not resign after a join that cannot be used");
            }
        })
    }

    /// Resign Federation Execution service (4.12); wire message `ResignFederationExecutionRequest`.
    pub fn resign_federation_execution(&self, resign_action: ResignAction) -> RtiResult<()> {
        self.forbid_within_callback("Resign Federation Execution")?;
        let cx = self.wire_cx();
        let request = proto::ResignFederationExecutionRequest { resign_action: resign_action.to_wire(&cx)? };
        match self.invoke(Call::ResignFederationExecutionRequest(request))? {
            Reply::ResignFederationExecutionResponse(_) => {
                self.shared().lock().leave_federation();
                Ok(())
            }
            _ => Err(unexpected_response("ResignFederationExecutionRequest")),
        }
    }

    // ---- Callback delivery (10.57 to 10.60), implemented here and not by the RTI (12.13.3.2) ----

    /// Evoke Callback service (10.57).
    ///
    /// Delivers at most one callback on the calling thread. If none is available it waits for one for up to
    /// `approximate_minimum_time`. Returns whether more callbacks are pending. Has no effect in the
    /// IMMEDIATE callback model.
    pub fn evoke_callback(&self, approximate_minimum_time: Duration) -> RtiResult<bool> {
        self.evoke(approximate_minimum_time, None)
    }

    /// Evoke Multiple Callbacks service (10.58).
    ///
    /// Delivers callbacks on the calling thread as they become available until
    /// `approximate_minimum_time` has passed, then goes on only while callbacks are immediately available
    /// and `approximate_maximum_time` has not passed. Returns whether more callbacks are pending. Has no
    /// effect in the IMMEDIATE callback model.
    pub fn evoke_multiple_callbacks(
        &self,
        approximate_minimum_time: Duration,
        approximate_maximum_time: Duration,
    ) -> RtiResult<bool> {
        self.evoke(approximate_minimum_time, Some(approximate_maximum_time))
    }

    fn evoke(&self, minimum: Duration, maximum: Option<Duration>) -> RtiResult<bool> {
        let shared = self.shared();
        let generation = {
            let state = shared.lock();
            if state.within_callback() {
                return Err(not_allowed("Evoke Callback"));
            }
            if state.link.is_some() && state.model == CallbackModel::Immediate {
                return Ok(false);
            }
            state.generation
        };
        let start = Instant::now();
        let minimum_deadline = start + minimum;
        let mut federate = shared.lock_federate();
        match maximum {
            None => {
                if let Some(item) = shared.take_deliverable(generation, minimum) {
                    shared.deliver(&mut federate, item);
                }
            }
            Some(maximum) => {
                let maximum_deadline = start + maximum.max(minimum);
                loop {
                    let wait = minimum_deadline.saturating_duration_since(Instant::now());
                    match shared.take_deliverable(generation, wait) {
                        Some(item) => shared.deliver(&mut federate, item),
                        None => {
                            if Instant::now() >= minimum_deadline || shared.lock().generation != generation {
                                break;
                            }
                        }
                    }
                    if Instant::now() >= maximum_deadline {
                        break;
                    }
                }
            }
        }
        Ok(shared.has_pending(generation))
    }

    /// Enable Callbacks service (10.59): callbacks are delivered again (the initial condition).
    ///
    /// Fails with `SaveInProgress` or `RestoreInProgress` between the callbacks that start and end a
    /// federate save or restore.
    pub fn enable_callbacks(&self) -> RtiResult<()> {
        let shared = self.shared();
        let mut state = shared.lock();
        state.check_save_restore()?;
        state.callbacks_enabled = true;
        shared.changed.notify_all();
        Ok(())
    }

    /// Disable Callbacks service (10.60): callbacks stay queued until Enable Callbacks.
    ///
    /// When invoked from another thread than the one executing a callback, it returns once that callback
    /// has finished, so that no callback is in progress afterwards. Fails with `SaveInProgress` or
    /// `RestoreInProgress` like Enable Callbacks.
    pub fn disable_callbacks(&self) -> RtiResult<()> {
        let shared = self.shared();
        let mut state = shared.lock();
        state.check_save_restore()?;
        state.callbacks_enabled = false;
        shared.changed.notify_all();
        let current = thread::current().id();
        while state.in_callback.is_some_and(|busy| busy != current) {
            state = shared.changed.wait(state).unwrap_or_else(PoisonError::into_inner);
        }
        Ok(())
    }
}

fn decode_join_result(result: Option<proto::JoinResult>) -> RtiResult<JoinResult> {
    let result = result.ok_or_else(|| malformed("missing join result"))?;
    let Some(time_kind) = TimeKind::from_name(&result.logical_time_implementation_name) else {
        return Err(RtiError::new(
            ExceptionKind::CouldNotCreateLogicalTimeFactory,
            format!(
                "the federation execution uses logical time implementation {:?}; this API provides {} and {}",
                result.logical_time_implementation_name,
                TimeKind::Integer64,
                TimeKind::Float64
            ),
        ));
    };
    Ok(JoinResult {
        federate_handle: FederateHandle::from_wire(result.federate_handle, &WireCx::default())?,
        logical_time_implementation_name: result.logical_time_implementation_name,
        time_kind,
    })
}