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
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
//! Callback delivery: the EVOKED and IMMEDIATE models with their timing (10.57, 10.58), Enable and Disable
//! Callbacks (10.59, 10.60), reentrancy and concurrency (12.8), failed callbacks, Connection Lost (4.4) and
//! shutdown.

mod common;

use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Condvar, mpsc};
use std::thread::{self, ThreadId};

use common::*;

const LONG: Duration = Duration::from_secs(5);

fn discover(n: u8) -> WireCallback {
    WireCallback::DiscoverObjectInstance(proto::DiscoverObjectInstance {
        object_instance: p_object_instance_handle(n),
        object_class: p_object_class_handle(1),
        object_instance_name: format!("object-{n}"),
        producing_federate: p_federate_handle(2),
    })
}

fn discovered(n: u8) -> Callback {
    Callback::DiscoverObjectInstance {
        object_instance: t_object_instance_handle(n),
        object_class: t_object_class_handle(1),
        object_instance_name: format!("object-{n}"),
        producing_federate: t_federate_handle(2),
    }
}

fn succeeded() -> CallbackReply {
    CallbackReply::CallbackSucceeded(proto::CallbackSucceeded {})
}

fn lost(fault_description: &str) -> Callback {
    Callback::ConnectionLost { fault_description: fault_description.to_owned() }
}

/// Evokes until nothing is pending.
fn drain(rti: &RtiAmbassador) {
    while rti.evoke_multiple_callbacks(Duration::ZERO, LONG).unwrap() {}
}

#[test]
fn evoked_callbacks_wait_for_evoke_callback() {
    let (seen, federate) = collector();
    let h = Harness::connected_with(federate, CallbackModel::Evoked);
    for n in 1..=3 {
        h.link.push_callback(discover(n));
    }
    thread::sleep(Duration::from_millis(30));
    assert!(seen.lock().unwrap().is_empty(), "nothing is delivered before Evoke Callback");
    assert!(h.link.callback_responses().is_empty());

    // One callback per invocation; the result tells whether more are pending.
    assert!(h.rti.evoke_callback(Duration::ZERO).unwrap());
    assert_eq!(*seen.lock().unwrap(), [discovered(1)]);
    assert!(h.rti.evoke_callback(Duration::ZERO).unwrap());
    assert!(!h.rti.evoke_callback(Duration::ZERO).unwrap());
    assert_eq!(*seen.lock().unwrap(), [discovered(1), discovered(2), discovered(3)]);
    assert_eq!(h.link.callback_responses(), [(1, succeeded()), (2, succeeded()), (3, succeeded())]);

    assert!(!h.rti.evoke_callback(Duration::ZERO).unwrap());
    assert_eq!(seen.lock().unwrap().len(), 3);
}

#[test]
fn evoke_callback_waits_up_to_the_minimum_time() {
    let h = Harness::connected();
    let start = Instant::now();
    assert!(!h.rti.evoke_callback(Duration::from_millis(60)).unwrap());
    let waited = start.elapsed();
    assert!(waited >= Duration::from_millis(60), "returned after {waited:?}");
    assert!(waited < Duration::from_secs(3), "returned after {waited:?}");

    // A callback arriving during the wait ends it.
    let link = h.link.clone();
    let pusher = thread::spawn(move || {
        thread::sleep(Duration::from_millis(30));
        link.push_callback(discover(1));
    });
    let start = Instant::now();
    assert!(!h.rti.evoke_callback(LONG).unwrap());
    assert!(start.elapsed() < Duration::from_secs(4), "returned after {:?}", start.elapsed());
    pusher.join().unwrap();
    assert_eq!(h.link.callback_responses(), [(1, succeeded())]);

    // Without a connection there is nothing to deliver, the wait is the same.
    let (rti, _link) = unconnected();
    let start = Instant::now();
    assert!(!rti.evoke_callback(Duration::from_millis(20)).unwrap());
    assert!(start.elapsed() >= Duration::from_millis(20));
}

#[test]
fn evoke_multiple_callbacks_delivers_what_arrives_within_the_minimum_time() {
    let (seen, federate) = collector();
    let link = Arc::new(ObservedLink::new());
    let rti = RtiAmbassador::with_link(link.clone());
    rti.connect(federate, CallbackModel::Evoked).unwrap();
    for n in 1..=5 {
        link.inner.push_callback(discover(n));
    }
    let start = Instant::now();
    assert!(!rti.evoke_multiple_callbacks(Duration::from_millis(50), LONG).unwrap());
    let elapsed = start.elapsed();
    assert_eq!(seen.lock().unwrap().len(), 5);
    assert!(elapsed >= Duration::from_millis(50), "returned after {elapsed:?}");
    assert!(elapsed < Duration::from_secs(4), "returned after {elapsed:?}");

    // A callback that reaches the link while the service is waiting is delivered by the same invocation,
    // which still lasts for the minimum time: the ambassador pulls once, finds nothing, and the
    // callback is there when it pulls again. The arrival is tied to the pulls themselves and not to a
    // sleep in another thread: nothing orders two independent timers.
    let polls = link.polls.load(Ordering::SeqCst);
    link.arrive_after_an_empty_poll(discover(6));
    let start = Instant::now();
    assert!(!rti.evoke_multiple_callbacks(Duration::from_millis(120), LONG).unwrap());
    let elapsed = start.elapsed();
    assert!(elapsed >= Duration::from_millis(120), "returned after {elapsed:?}");
    assert!(elapsed < Duration::from_secs(4), "returned after {elapsed:?}");
    assert_eq!(seen.lock().unwrap().len(), 6);
    assert_eq!(seen.lock().unwrap().last(), Some(&discovered(6)));
    assert_eq!(link.inner.callback_responses().last(), Some(&(6, succeeded())));
    assert!(link.polls.load(Ordering::SeqCst) >= polls + 2, "the link was pulled again during the wait");

    // With a zero minimum the call returns as soon as nothing is available.
    let start = Instant::now();
    assert!(!rti.evoke_multiple_callbacks(Duration::ZERO, LONG).unwrap());
    assert!(start.elapsed() < Duration::from_secs(2));
    assert_eq!(seen.lock().unwrap().len(), 6);
}

#[test]
fn evoke_multiple_callbacks_stops_at_the_maximum_time() {
    // Every callback causes another one: the supply never ends. All but the first two take a few
    // milliseconds; those two return at once, so that the number delivered before the maximum time does
    // not depend on how late a short sleep ends.
    let link = MockLink::new();
    let rti = RtiAmbassador::with_link(link.clone());
    let count = Arc::new(AtomicUsize::new(0));
    let (source, counter) = (link.clone(), count.clone());
    let federate = CallbackFn::new(move |_: Callback| {
        if counter.fetch_add(1, Ordering::SeqCst) >= 2 {
            thread::sleep(Duration::from_millis(5));
        }
        source.push_callback(discover(1));
        Ok(())
    });
    rti.connect(federate, CallbackModel::Evoked).unwrap();
    link.push_callback(discover(1));

    let start = Instant::now();
    let pending =
        rti.evoke_multiple_callbacks(Duration::from_millis(20), Duration::from_millis(100)).unwrap();
    let elapsed = start.elapsed();
    assert!(pending, "callbacks are still pending when the maximum time is reached");
    assert!(elapsed >= Duration::from_millis(100), "returned after {elapsed:?}");
    assert!(elapsed < Duration::from_secs(3), "returned after {elapsed:?}");
    let delivered = count.load(Ordering::SeqCst);
    assert!(delivered > 1, "delivered {delivered}");
    assert_eq!(link.callback_responses().len(), delivered);
}

#[test]
fn evoked_callbacks_run_on_the_evoking_thread() {
    let threads: Arc<Mutex<Vec<ThreadId>>> = Arc::default();
    let sink = threads.clone();
    let federate = CallbackFn::new(move |_: Callback| {
        sink.lock().unwrap().push(thread::current().id());
        Ok(())
    });
    let h = Harness::connected_with(federate, CallbackModel::Evoked);
    h.link.push_callback(discover(1));
    h.link.push_callback(discover(2));
    assert!(h.rti.evoke_callback(Duration::ZERO).unwrap());
    let rti = h.rti.clone();
    let other = thread::spawn(move || {
        rti.evoke_callback(Duration::ZERO).unwrap();
        thread::current().id()
    })
    .join()
    .unwrap();
    assert_eq!(*threads.lock().unwrap(), [thread::current().id(), other]);
}

#[test]
fn immediate_callbacks_are_delivered_by_the_ambassador_thread() {
    let seen: Arc<Mutex<Vec<(ThreadId, Callback)>>> = Arc::default();
    let sink = seen.clone();
    let federate = CallbackFn::new(move |callback: Callback| {
        sink.lock().unwrap().push((thread::current().id(), callback));
        Ok(())
    });
    let h = Harness::connected_with(federate, CallbackModel::Immediate);
    assert_eq!(h.rti.callback_model(), Some(CallbackModel::Immediate));
    for n in 1..=4 {
        h.link.push_callback(discover(n));
    }
    assert!(h.link.wait_for_callback_responses(4, LONG));
    let seen = seen.lock().unwrap().clone();
    let callbacks: Vec<Callback> = seen.iter().map(|(_, callback)| callback.clone()).collect();
    assert_eq!(callbacks, [discovered(1), discovered(2), discovered(3), discovered(4)]);
    let delivery_thread = seen[0].0;
    assert_ne!(delivery_thread, thread::current().id());
    assert!(seen.iter().all(|(thread, _)| *thread == delivery_thread));
    assert_eq!(h.link.callback_responses()[3], (4, succeeded()));

    // The evoke services have no effect in this model: they return at once.
    let start = Instant::now();
    assert!(!h.rti.evoke_callback(LONG).unwrap());
    assert!(!h.rti.evoke_multiple_callbacks(LONG, LONG).unwrap());
    assert!(start.elapsed() < Duration::from_secs(2));
    h.rti.disconnect().unwrap();
}

#[test]
fn disabled_callbacks_stay_queued_in_the_evoked_model() {
    let (seen, federate) = collector();
    let h = Harness::connected_with(federate, CallbackModel::Evoked);
    h.link.push_callback(discover(1));
    h.rti.disable_callbacks().unwrap();

    let start = Instant::now();
    assert!(h.rti.evoke_callback(Duration::from_millis(40)).unwrap(), "the callback stays pending");
    assert!(start.elapsed() >= Duration::from_millis(40));
    assert!(h.rti.evoke_multiple_callbacks(Duration::ZERO, Duration::from_millis(20)).unwrap());
    assert!(seen.lock().unwrap().is_empty());
    assert!(h.link.callback_responses().is_empty());

    h.rti.enable_callbacks().unwrap();
    assert!(!h.rti.evoke_callback(Duration::ZERO).unwrap());
    assert_eq!(*seen.lock().unwrap(), [discovered(1)]);

    // Enable Callbacks releases an Evoke Callback that is already waiting.
    h.rti.disable_callbacks().unwrap();
    h.link.push_callback(discover(2));
    let rti = h.rti.clone();
    let enabler = thread::spawn(move || {
        thread::sleep(Duration::from_millis(30));
        rti.enable_callbacks().unwrap();
    });
    let start = Instant::now();
    h.rti.evoke_callback(LONG).unwrap();
    assert!(start.elapsed() < Duration::from_secs(4));
    enabler.join().unwrap();
    assert_eq!(*seen.lock().unwrap(), [discovered(1), discovered(2)]);
}

#[test]
fn disabled_callbacks_stay_queued_in_the_immediate_model() {
    let (seen, federate) = collector();
    let h = Harness::connected_with(federate, CallbackModel::Immediate);
    h.rti.disable_callbacks().unwrap();
    h.link.push_callback(discover(1));
    h.link.push_callback(discover(2));
    thread::sleep(Duration::from_millis(150));
    assert!(seen.lock().unwrap().is_empty());
    assert!(h.link.callback_responses().is_empty());

    h.rti.enable_callbacks().unwrap();
    assert!(h.link.wait_for_callback_responses(2, LONG));
    assert_eq!(*seen.lock().unwrap(), [discovered(1), discovered(2)]);
}

#[test]
fn disable_callbacks_waits_for_the_callback_in_progress() {
    let (entered_tx, entered_rx) = mpsc::channel::<()>();
    let (release_tx, release_rx) = mpsc::channel::<()>();
    let federate = CallbackFn::new(move |_: Callback| {
        entered_tx.send(()).ok();
        release_rx.recv_timeout(LONG).ok();
        Ok(())
    });
    let h = Harness::connected_with(federate, CallbackModel::Immediate);
    h.link.push_callback(discover(1));
    entered_rx.recv_timeout(LONG).unwrap();

    let done = Arc::new(AtomicBool::new(false));
    let (rti, flag) = (h.rti.clone(), done.clone());
    let disabler = thread::spawn(move || {
        rti.disable_callbacks().unwrap();
        flag.store(true, Ordering::SeqCst);
    });
    thread::sleep(Duration::from_millis(60));
    assert!(!done.load(Ordering::SeqCst), "Disable Callbacks returned while a callback was in progress");
    release_tx.send(()).unwrap();
    disabler.join().unwrap();
    assert!(done.load(Ordering::SeqCst));
    assert!(h.link.wait_for_callback_responses(1, LONG));

    // Nothing more is delivered until callbacks are enabled again.
    h.link.push_callback(discover(2));
    thread::sleep(Duration::from_millis(120));
    assert_eq!(h.link.callback_responses().len(), 1);
    release_tx.send(()).unwrap();
    h.rti.enable_callbacks().unwrap();
    assert!(h.link.wait_for_callback_responses(2, LONG));
}

#[test]
fn enable_and_disable_callbacks_fail_during_a_federate_save_or_restore() {
    let h = Harness::joined();
    let deliver = |callback: WireCallback| {
        h.link.push_callback(callback);
        assert!(!h.rti.evoke_callback(Duration::ZERO).unwrap());
    };

    deliver(WireCallback::InitiateFederateSave(proto::InitiateFederateSave { label: "noon".to_owned() }));
    assert_eq!(h.rti.disable_callbacks().unwrap_err().kind, ExceptionKind::SaveInProgress);
    assert_eq!(h.rti.enable_callbacks().unwrap_err().kind, ExceptionKind::SaveInProgress);
    deliver(WireCallback::FederationSaved(proto::FederationSaved {}));
    h.rti.disable_callbacks().unwrap();
    h.rti.enable_callbacks().unwrap();

    deliver(WireCallback::FederationRestoreBegun(proto::FederationRestoreBegun {}));
    assert_eq!(h.rti.disable_callbacks().unwrap_err().kind, ExceptionKind::RestoreInProgress);
    assert_eq!(h.rti.enable_callbacks().unwrap_err().kind, ExceptionKind::RestoreInProgress);
    deliver(WireCallback::FederationNotRestored(proto::FederationNotRestored {
        reason: proto::RestoreFailureReason::RestoreAborted as i32,
    }));
    h.rti.disable_callbacks().unwrap();
    h.rti.enable_callbacks().unwrap();

    // Leaving the federation execution ends the save as far as this federate is concerned.
    deliver(WireCallback::InitiateFederateSaveWithTime(proto::InitiateFederateSaveWithTime {
        label: "evening".to_owned(),
        time: p_logical_time(1),
    }));
    assert_eq!(h.rti.disable_callbacks().unwrap_err().kind, ExceptionKind::SaveInProgress);
    h.rti.resign_federation_execution(ResignAction::NoAction).unwrap();
    h.rti.disable_callbacks().unwrap();
}

/// 12.8: from inside a callback every service works, except the six that raise
/// `CallNotAllowedFromWithinCallback`.
fn services_invoked_from_inside_a_callback(model: CallbackModel) {
    type Outcome = (&'static str, Result<(), ExceptionKind>);
    let link = MockLink::new();
    let rti = RtiAmbassador::with_link(link.clone());
    let weak = rti.downgrade();
    let outcomes: Arc<Mutex<Vec<Outcome>>> = Arc::default();
    let sink = outcomes.clone();
    let federate = CallbackFn::new(move |callback: Callback| {
        let Callback::DiscoverObjectInstance { object_instance, .. } = callback else {
            return Ok(());
        };
        let rti = weak.upgrade().ok_or("the RTI ambassador is gone")?;
        let record = |name: &'static str, result: RtiResult<()>| {
            sink.lock().unwrap().push((name, result.map_err(|error| error.kind)));
        };
        let no_values = AttributeHandleValueMap::new();
        record("get_object_instance_name", rti.get_object_instance_name(&object_instance).map(drop));
        record(
            "update_attribute_values",
            rti.update_attribute_values(&object_instance, &no_values, b"reply"),
        );
        record("query_lookahead", rti.query_lookahead().map(drop));
        record("disable_callbacks", rti.disable_callbacks());
        record("enable_callbacks", rti.enable_callbacks());
        record("connect", rti.connect(NullFederateAmbassador, CallbackModel::Evoked).map(drop));
        record("disconnect", rti.disconnect());
        record("join_federation_execution", rti.join_federation_execution("Chef", "Lunch").map(drop));
        record("resign_federation_execution", rti.resign_federation_execution(ResignAction::NoAction));
        record("evoke_callback", rti.evoke_callback(Duration::ZERO).map(drop));
        record(
            "evoke_multiple_callbacks",
            rti.evoke_multiple_callbacks(Duration::ZERO, Duration::ZERO).map(drop),
        );
        Ok(())
    });
    rti.connect(federate, model).unwrap();
    link.push_reply(join_reply("HLAfloat64Time"));
    rti.join_federation_execution("Chef", "Lunch").unwrap();
    link.take_requests();

    link.push_callback(discover(1));
    if model == CallbackModel::Evoked {
        rti.evoke_callback(LONG).unwrap();
    }
    assert!(link.wait_for_callback_responses(1, LONG));
    assert_eq!(link.callback_responses(), [(1, succeeded())]);

    let forbidden = Err(ExceptionKind::CallNotAllowedFromWithinCallback);
    let expected: [Outcome; 11] = [
        ("get_object_instance_name", Ok(())),
        ("update_attribute_values", Ok(())),
        ("query_lookahead", Ok(())),
        ("disable_callbacks", Ok(())),
        ("enable_callbacks", Ok(())),
        ("connect", forbidden),
        ("disconnect", forbidden),
        ("join_federation_execution", forbidden),
        ("resign_federation_execution", forbidden),
        ("evoke_callback", forbidden),
        ("evoke_multiple_callbacks", forbidden),
    ];
    assert_eq!(*outcomes.lock().unwrap(), expected);
    // The allowed services reached the RTI, the forbidden ones never left the ambassador.
    let sent: Vec<&str> = link.requests().iter().map(request_name).collect();
    assert_eq!(
        sent,
        ["GetObjectInstanceNameRequest", "UpdateAttributeValuesRequest", "QueryLookaheadRequest"]
    );

    // Outside a callback the same services are available again.
    assert_eq!(rti.time_kind().unwrap(), TimeKind::Float64);
    rti.resign_federation_execution(ResignAction::NoAction).unwrap();
    rti.disconnect().unwrap();
    assert!(link.is_closed());
}

#[test]
fn services_may_be_invoked_from_inside_an_evoked_callback() {
    services_invoked_from_inside_a_callback(CallbackModel::Evoked);
}

#[test]
fn services_may_be_invoked_from_inside_an_immediate_callback() {
    services_invoked_from_inside_a_callback(CallbackModel::Immediate);
}

#[test]
fn failed_callbacks_are_reported_to_the_rti() {
    let federate = CallbackFn::new(|callback: Callback| match callback {
        Callback::TurnInteractionsOn { .. } => Err(FederateInternalError::new("cannot comply")),
        Callback::TurnInteractionsOff { .. } => panic!("deliberate panic of the test federate"),
        _ => Ok(()),
    });
    let h = Harness::connected_with(federate, CallbackModel::Evoked);
    h.link.push_callback(WireCallback::TurnInteractionsOn(proto::TurnInteractionsOn {
        interaction_class: p_interaction_class_handle(1),
    }));
    h.link.push_callback(WireCallback::TurnInteractionsOff(proto::TurnInteractionsOff {
        interaction_class: p_interaction_class_handle(1),
    }));
    // A message without a known alternative, and one that cannot be decoded (a time while not joined).
    h.link.push_raw_callback(proto::CallbackRequest { callback_request: None });
    h.link.push_callback(WireCallback::TimeAdvanceGrant(proto::TimeAdvanceGrant { time: p_logical_time(1) }));
    h.link.push_callback(WireCallback::TurnInteractionsOn(proto::TurnInteractionsOn {
        interaction_class: None,
    }));
    h.link.push_callback(discover(6));
    drain(&h.rti);

    let responses = h.link.callback_responses();
    assert_eq!(responses.len(), 6);
    let failure = |index: usize| match &responses[index] {
        (id, CallbackReply::CallbackFailed(data)) => {
            assert_eq!(*id, index as u64 + 1);
            assert_eq!(data.exception_name, "FederateInternalError");
            data.details.clone()
        }
        other => panic!("callback {index} did not fail: {other:?}"),
    };
    assert_eq!(failure(0), "cannot comply");
    assert!(failure(1).contains("panicked"));
    assert!(failure(2).contains("alternative"));
    assert!(failure(3).contains("decode"));
    assert!(failure(4).contains("InteractionClassHandle"));
    assert_eq!(responses[5], (6, succeeded()), "delivery goes on after failures");
}

#[test]
fn services_can_be_invoked_from_several_threads_at_once() {
    let h = Harness::connected();
    // (calls in flight, highest number of calls in flight)
    let in_flight = Arc::new((Mutex::new((0usize, 0usize)), Condvar::new()));
    let gate = in_flight.clone();
    h.link.set_responder(move |request| {
        let Call::GetFederateHandleRequest(request) = request else {
            return None;
        };
        let (counts, changed) = &*gate;
        let mut counts = counts.lock().unwrap();
        counts.0 += 1;
        counts.1 = counts.1.max(counts.0);
        changed.notify_all();
        // Stay inside the call until a second call is in flight (bounded, in case calls were serialized).
        let deadline = Instant::now() + LONG;
        while counts.1 < 2 && Instant::now() < deadline {
            counts = changed.wait_timeout(counts, Duration::from_millis(50)).unwrap().0;
        }
        counts.0 -= 1;
        drop(counts);
        let handle = proto::FederateHandle { data: Bytes::from(request.federate_name.clone()) };
        Some(Reply::GetFederateHandleResponse(proto::GetFederateHandleResponse { result: Some(handle) }))
    });

    let lookups = |rti: &RtiAmbassador, thread: usize| {
        for call in 0..50 {
            let name = format!("federate-{thread}-{call}");
            let handle = rti.get_federate_handle(&name).unwrap();
            assert_eq!(handle.as_bytes(), name.as_bytes(), "a thread received the answer of another call");
        }
    };
    thread::scope(|scope| {
        // Four threads share one ambassador by reference, four use their own clone.
        for thread in 0..4 {
            let rti = &h.rti;
            scope.spawn(move || lookups(rti, thread));
        }
        for thread in 4..8 {
            let rti = h.rti.clone();
            scope.spawn(move || lookups(&rti, thread));
        }
    });
    assert!(in_flight.0.lock().unwrap().1 >= 2, "the calls never overlapped");
    assert_eq!(h.link.requests().len(), 1 + 8 * 50);
}

#[test]
fn callbacks_of_one_federate_never_overlap() {
    let active = Arc::new(AtomicUsize::new(0));
    let overlapped = Arc::new(AtomicBool::new(false));
    let names: Arc<Mutex<Vec<String>>> = Arc::default();
    let (busy, flag, sink) = (active.clone(), overlapped.clone(), names.clone());
    let federate = CallbackFn::new(move |callback: Callback| {
        if busy.fetch_add(1, Ordering::SeqCst) != 0 {
            flag.store(true, Ordering::SeqCst);
        }
        thread::sleep(Duration::from_millis(3));
        if let Callback::DiscoverObjectInstance { object_instance_name, .. } = callback {
            sink.lock().unwrap().push(object_instance_name);
        }
        busy.fetch_sub(1, Ordering::SeqCst);
        Ok(())
    });
    let h = Harness::connected_with(federate, CallbackModel::Evoked);
    for n in 1..=12 {
        h.link.push_callback(discover(n));
    }
    thread::scope(|scope| {
        for _ in 0..3 {
            scope.spawn(|| drain(&h.rti));
        }
    });
    drain(&h.rti);
    assert!(!overlapped.load(Ordering::SeqCst), "two callbacks ran at the same time");
    let expected: Vec<String> = (1..=12).map(|n| format!("object-{n}")).collect();
    assert_eq!(*names.lock().unwrap(), expected, "callbacks keep their order");
}

#[test]
fn a_lost_connection_is_reported_through_evoke_callback() {
    // The fault is noticed by a service invocation.
    let (seen, federate) = collector();
    let h = Harness::joined_with(federate, CallbackModel::Evoked, TimeKind::Float64);
    h.link.lose_connection("heartbeat timeout");
    let error = h.rti.query_logical_time().unwrap_err();
    assert_eq!(error.kind, ExceptionKind::NotConnected);
    assert!(error.message.contains("heartbeat timeout"), "{error}");
    assert!(!h.rti.is_connected());
    assert!(h.link.is_closed());
    assert!(seen.lock().unwrap().is_empty(), "EVOKED: Connection Lost waits for Evoke Callback");
    assert_eq!(h.rti.time_kind().unwrap_err().kind, ExceptionKind::NotConnected);

    assert!(!h.rti.evoke_callback(Duration::ZERO).unwrap());
    assert_eq!(*seen.lock().unwrap(), [lost("heartbeat timeout")]);
    assert_eq!(h.rti.get_federate_handle("chef").unwrap_err().kind, ExceptionKind::NotConnected);
    h.rti.disconnect().unwrap();
    assert!(!h.rti.evoke_callback(Duration::ZERO).unwrap());
    assert_eq!(seen.lock().unwrap().len(), 1, "Connection Lost is delivered once");

    // The fault is noticed while evoking: callbacks received before the fault come first.
    let (seen, federate) = collector();
    let h = Harness::connected_with(federate, CallbackModel::Evoked);
    h.link.push_callback(discover(1));
    h.link.lose_connection("cable unplugged");
    drain(&h.rti);
    assert_eq!(*seen.lock().unwrap(), [discovered(1), lost("cable unplugged")]);
    assert!(!h.rti.is_connected());

    // The fault is noticed by looking at the link state.
    let (seen, federate) = collector();
    let h = Harness::connected_with(federate, CallbackModel::Evoked);
    assert!(h.rti.is_connected());
    h.link.lose_connection("RTI stopped");
    assert!(!h.rti.is_connected());
    assert!(h.rti.evoke_callback(Duration::ZERO).is_ok());
    assert_eq!(*seen.lock().unwrap(), [lost("RTI stopped")]);
}

#[test]
fn a_lost_connection_is_reported_at_once_in_the_immediate_model() {
    let (seen, federate) = collector();
    let h = Harness::joined_with(federate, CallbackModel::Immediate, TimeKind::Float64);
    h.link.lose_connection("RTI crashed");
    assert!(wait_until(LONG, || seen.lock().unwrap().len() == 1));
    assert_eq!(*seen.lock().unwrap(), [lost("RTI crashed")]);
    assert!(!h.rti.is_connected());
    assert_eq!(
        h.rti.join_federation_execution("Chef", "Lunch").unwrap_err().kind,
        ExceptionKind::NotConnected
    );
    assert!(h.link.is_closed());
    h.rti.disconnect().unwrap();
}

#[test]
fn connection_lost_sent_by_the_rti_ends_the_connection() {
    let (seen, federate) = collector();
    let h = Harness::joined_with(federate, CallbackModel::Evoked, TimeKind::Float64);
    h.link.push_callback(WireCallback::ConnectionLost(proto::ConnectionLost {
        fault_description: "RTI is shutting down".to_owned(),
    }));
    assert!(!h.rti.evoke_callback(Duration::ZERO).unwrap());
    assert_eq!(*seen.lock().unwrap(), [lost("RTI is shutting down")]);
    assert_eq!(h.link.callback_responses(), [(1, succeeded())]);
    assert!(!h.rti.is_connected());
    assert!(h.link.is_closed());
    assert_eq!(h.rti.time_kind().unwrap_err().kind, ExceptionKind::NotConnected);
}

#[test]
fn a_federate_resigned_by_the_rti_is_no_longer_joined() {
    let (seen, federate) = collector();
    let h = Harness::joined_with(federate, CallbackModel::Evoked, TimeKind::Integer64);
    assert_eq!(h.rti.time_kind().unwrap(), TimeKind::Integer64);
    h.link.push_callback(WireCallback::FederateResigned(proto::FederateResigned {
        reason_for_resign_description: "resigned through the MOM".to_owned(),
    }));
    assert!(!h.rti.evoke_callback(Duration::ZERO).unwrap());
    let expected =
        Callback::FederateResigned { reason_for_resign_description: "resigned through the MOM".to_owned() };
    assert_eq!(*seen.lock().unwrap(), [expected]);
    assert_eq!(h.rti.time_kind().unwrap_err().kind, ExceptionKind::FederateNotExecutionMember);
    assert!(h.rti.is_connected(), "the federate stays connected");
}

#[test]
fn callbacks_arriving_during_a_join_use_its_time_representation() {
    let (seen, federate) = collector();
    let h = Harness::connected_with(federate, CallbackModel::Immediate);
    let link = Arc::downgrade(&h.link);
    h.link.set_responder(move |request| {
        let Call::JoinFederationExecutionRequest(_) = request else {
            return None;
        };
        // The RTI sends a timestamped callback before the federate has seen the join response.
        let grant = proto::TimeAdvanceGrant {
            time: Some(proto::LogicalTime { data: Bytes::copy_from_slice(&9i64.to_be_bytes()) }),
        };
        link.upgrade()?.push_callback(WireCallback::TimeAdvanceGrant(grant));
        thread::sleep(Duration::from_millis(120));
        Some(join_reply("HLAinteger64Time"))
    });
    h.rti.join_federation_execution("Chef", "Lunch").unwrap();
    assert!(h.link.wait_for_callback_responses(1, LONG));
    assert_eq!(h.link.callback_responses(), [(1, succeeded())]);
    assert_eq!(*seen.lock().unwrap(), [Callback::TimeAdvanceGrant { time: LogicalTime::Integer64(9) }]);
}

#[test]
fn callbacks_queued_before_a_resignation_are_still_decoded() {
    let (seen, federate) = collector();
    let h = Harness::joined_with(federate, CallbackModel::Evoked, TimeKind::Float64);
    h.link.push_callback(WireCallback::TimeAdvanceGrant(proto::TimeAdvanceGrant { time: p_logical_time(2) }));
    h.rti.resign_federation_execution(ResignAction::NoAction).unwrap();
    assert!(!h.rti.evoke_callback(Duration::ZERO).unwrap());
    assert_eq!(*seen.lock().unwrap(), [Callback::TimeAdvanceGrant { time: t_logical_time(2) }]);
    assert_eq!(h.link.callback_responses(), [(1, succeeded())]);
}

/// A link that counts how often callbacks are pulled from it and can let a callback arrive between two
/// pulls of the ambassador.
struct ObservedLink {
    inner: Arc<MockLink>,
    polls: AtomicUsize,
    /// The callback on its way, and whether the pull that found the link empty has happened.
    arriving: Mutex<Option<(WireCallback, bool)>>,
}

impl ObservedLink {
    fn new() -> Self {
        ObservedLink { inner: MockLink::new(), polls: AtomicUsize::new(0), arriving: Mutex::new(None) }
    }

    /// The next pull of the ambassador finds the link empty; `callback` is there at the pull after it.
    fn arrive_after_an_empty_poll(&self, callback: WireCallback) {
        *self.arriving.lock().unwrap() = Some((callback, false));
    }
}

impl RtiLink for ObservedLink {
    fn call(&self, request: proto::CallRequest) -> Result<proto::CallResponse, LinkError> {
        self.inner.call(request)
    }

    fn next_callback(&self, timeout: Option<Duration>) -> Result<Option<LinkCallback>, LinkError> {
        self.polls.fetch_add(1, Ordering::SeqCst);
        let mut arriving = self.arriving.lock().unwrap();
        match arriving.take() {
            Some((callback, false)) => {
                assert_eq!(
                    self.inner.queued_callbacks(),
                    0,
                    "the ambassador pulled before the link was empty"
                );
                // Nothing yet: answer at once, the wait is the business of the ambassador.
                *arriving = Some((callback, true));
                return Ok(None);
            }
            Some((callback, true)) => {
                self.inner.push_callback(callback);
            }
            None => {}
        }
        drop(arriving);
        self.inner.next_callback(timeout)
    }

    fn respond(&self, id: u64, response: proto::CallbackResponse) -> Result<(), LinkError> {
        self.inner.respond(id, response)
    }

    fn state(&self) -> LinkState {
        self.inner.state()
    }

    fn close(&self) {
        self.inner.close();
    }
}

/// A federate ambassador that tells when it is dropped.
struct Guarded(Arc<AtomicBool>);

impl FederateAmbassador for Guarded {}

impl Drop for Guarded {
    fn drop(&mut self) {
        self.0.store(true, Ordering::SeqCst);
    }
}

#[test]
fn disconnect_and_drop_end_the_delivery_thread() {
    for by_drop in [false, true] {
        let link = Arc::new(ObservedLink::new());
        let dropped = Arc::new(AtomicBool::new(false));
        let rti = RtiAmbassador::with_link(link.clone());
        rti.connect(Guarded(dropped.clone()), CallbackModel::Immediate).unwrap();
        assert!(wait_until(LONG, || link.polls.load(Ordering::SeqCst) > 0), "the delivery thread is running");
        let clone = rti.clone();
        if by_drop {
            drop(clone);
            assert!(!link.inner.is_closed(), "a clone of the ambassador is still alive");
            drop(rti);
        } else {
            rti.disconnect().unwrap();
            assert!(!clone.is_connected());
        }
        assert!(link.inner.is_closed());
        assert!(dropped.load(Ordering::SeqCst), "the federate ambassador is dropped");
        let polls = link.polls.load(Ordering::SeqCst);
        thread::sleep(Duration::from_millis(160));
        assert_eq!(link.polls.load(Ordering::SeqCst), polls, "something still pulls callbacks from the link");
        assert_eq!(Arc::strong_count(&link), 1, "the ambassador still holds the link");
    }
}

#[test]
fn dropping_the_last_clone_inside_a_callback_does_not_deadlock() {
    let link = MockLink::new();
    let rti = RtiAmbassador::with_link(link.clone());
    let slot: Arc<Mutex<Option<RtiAmbassador>>> = Arc::default();
    let owner = slot.clone();
    let federate = CallbackFn::new(move |_: Callback| {
        // The federate ambassador gives up the only clone of the RTI ambassador while it is being called.
        let last = owner.lock().unwrap().take();
        drop(last);
        Ok(())
    });
    rti.connect(federate, CallbackModel::Immediate).unwrap();
    *slot.lock().unwrap() = Some(rti);
    link.push_callback(discover(1));
    assert!(wait_until(LONG, || link.is_closed()), "dropping the ambassador closes the link");
    assert!(
        wait_until(LONG, || Arc::strong_count(&link) == 1),
        "the delivery thread ended and released the link"
    );
}