rustorb-core 0.5.0

ORB core of rustorb: connections, request dispatch and POA
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
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
use std::fmt;
use std::future::Future;
use std::sync::atomic::{AtomicI32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use rustorb_cdr::CdrDecode;
use rustorb_giop::{
    AddressingDisposition, AlternateIiopAddress, Body, CancelRequestHeader, CodeSetComponentInfo,
    Ior, LocateRequestHeader, LocateStatus, Message, MessageEncoder, OutMessage, ReplyStatus,
    RequestHeader, ServiceContext, SslSecTrans, SystemExceptionBody, TAG_INTERNET_IOP,
    TAG_MULTIPLE_COMPONENTS, TargetAddress, UnixTrans, Version, component_tag, decode_message,
    response_flags,
};

use crate::connection::{Closed, Connection, SendError, Transport};
use crate::pi::{
    self, ClientEnding, ClientRequest, ClientRequestInfo, DiiParams, Interceptors, sync_scope,
};
use crate::policy;
use crate::server::Server;
use crate::stream::{InStream, OutStream, marshal};
use crate::trace;
use crate::{
    CodeSets, CompletionStatus, Exception, Orb, SystemException, SystemExceptionKind,
    UserException, minor, timeout,
};

/// A reference to a CORBA object, from an IOR.
///
/// Invocations try each IIOP profile of the IOR, and each address in it,
/// until one can be reached. An address of the ORB's own server side is
/// not reached through the network: the request is dispatched on the
/// calling thread. A `LOCATION_FORWARD` reply makes the
/// reference use the forwarded IOR from then on (shared by its clones);
/// when the forwarded object cannot be reached any more, the original IOR
/// is used again.
#[derive(Clone)]
pub struct ObjectRef {
    orb: Orb,
    ior: Arc<Ior>,
    forward: Arc<Mutex<Option<Arc<Ior>>>>,
    /// [`ObjectRef::set_call_timeout`], shared by clones.
    call_timeout: Arc<AtomicU64>,
    /// The `SyncScopePolicy` override, shared by clones.
    sync_scope: Arc<AtomicI32>,
}

impl fmt::Debug for ObjectRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ObjectRef")
            .field("type_id", &self.ior.type_id)
            .field("profiles", &self.ior.profiles.len())
            .finish_non_exhaustive()
    }
}

/// `==` is [`ObjectRef::is_equivalent`].
impl PartialEq for ObjectRef {
    fn eq(&self, other: &ObjectRef) -> bool {
        self.is_equivalent(other)
    }
}

type ArgsFn<'a> = dyn Fn(&mut OutStream<'_>) -> Result<(), SystemException> + 'a;

/// The arguments of an [`AsyncRequest`], whose future may move between
/// threads.
type SendArgsFn<'a> = dyn Fn(&mut OutStream<'_>) -> Result<(), SystemException> + Send + Sync + 'a;

/// Writes the `in` and `inout` arguments of a request: either kind of
/// argument function.
trait WriteArgs {
    fn write_args(&self, out: &mut OutStream<'_>) -> Result<(), SystemException>;
}

impl<F> WriteArgs for F
where
    F: Fn(&mut OutStream<'_>) -> Result<(), SystemException> + ?Sized,
{
    fn write_args(&self, out: &mut OutStream<'_>) -> Result<(), SystemException> {
        self(out)
    }
}

impl ObjectRef {
    pub(crate) fn new(orb: Orb, ior: Ior) -> ObjectRef {
        ObjectRef {
            orb,
            ior: Arc::new(ior),
            forward: Arc::new(Mutex::new(None)),
            call_timeout: Arc::new(AtomicU64::new(timeout::UNSET)),
            sync_scope: Arc::new(policy::new_sync_scope_cell(None)),
        }
    }

    /// A reference to the same object (sharing its forward) whose call
    /// timeout and sync scope are its own, starting from this one's.
    pub(crate) fn with_own_settings(&self) -> ObjectRef {
        ObjectRef {
            call_timeout: Arc::new(AtomicU64::new(self.call_timeout.load(Ordering::Relaxed))),
            sync_scope: Arc::new(policy::new_sync_scope_cell(self.sync_scope_override())),
            ..self.clone()
        }
    }

    /// The `SyncScopePolicy` override of the reference.
    pub(crate) fn sync_scope_override(&self) -> Option<i16> {
        policy::load_sync_scope(&self.sync_scope)
    }

    /// Sets the `SyncScopePolicy` override of the reference and its clones.
    pub(crate) fn set_sync_scope_override(&self, v: Option<i16>) {
        policy::store_sync_scope(&self.sync_scope, v);
    }

    pub(crate) fn ior_arc(&self) -> Arc<Ior> {
        Arc::clone(&self.ior)
    }

    /// The IOR the reference was created from.
    pub fn ior(&self) -> &Ior {
        &self.ior
    }

    /// The IOR invocations currently go to: the last forwarded one, or the
    /// original.
    pub fn effective_ior(&self) -> Ior {
        (*self.current_target()).clone()
    }

    /// The repository id in the IOR, which may be empty.
    pub fn type_id(&self) -> &str {
        &self.ior.type_id
    }

    /// The ORB the reference belongs to.
    pub fn orb(&self) -> &Orb {
        &self.orb
    }

    /// `CORBA::Object::_is_equivalent`: whether both references have the
    /// same profiles, so they certainly denote the same object. `false`
    /// does not mean they are different objects.
    pub fn is_equivalent(&self, other: &ObjectRef) -> bool {
        Arc::ptr_eq(&self.ior, &other.ior) || self.ior.profiles == other.ior.profiles
    }

    /// Starts a request for `operation`.
    pub fn request<'a>(&'a self, operation: &str) -> Request<'a> {
        Request {
            obj: self,
            operation: operation.to_owned(),
            args: None,
            timeout: None,
            dii: None,
        }
    }

    /// Starts a request for `operation` that runs as a future
    /// ([`AsyncRequest`]).
    pub fn request_async<'a>(&'a self, operation: &str) -> AsyncRequest<'a> {
        AsyncRequest {
            obj: self,
            operation: operation.to_owned(),
            args: None,
            timeout: None,
            dii: None,
            slots: None,
        }
    }

    /// Starts a request for `operation` whose reply goes to a callback
    /// ([`CallbackRequest`]): the base of the asynchronous method
    /// invocation (AMI) of the language bindings.
    pub fn request_callback(&self, operation: &str) -> CallbackRequest {
        CallbackRequest {
            obj: self.clone(),
            operation: operation.to_owned(),
            args: None,
            timeout: None,
        }
    }

    /// The slots of the calling thread for a request on this reference,
    /// if its ORB has client interceptors.
    pub(crate) fn request_slots(&self) -> Option<Vec<crate::Any>> {
        request_slots(self)
    }

    /// Sets how long calls on this reference and its clones wait for a
    /// reply: `Some(t)` (where `t` is `None` for no limit) overrides the
    /// ORB's [`call_timeout`](Orb::call_timeout) and the calling thread's
    /// ([`set_thread_call_timeout`](crate::set_thread_call_timeout)), and
    /// `None` unsets it. Like omniORB's `setClientCallTimeout(obj,
    /// millisecs)`. References made from the same IOR by
    /// [`Orb::string_to_object`] do not share it.
    pub fn set_call_timeout(&self, timeout: Option<Option<Duration>>) {
        let v = timeout.map_or(timeout::UNSET, timeout::encode);
        self.call_timeout.store(v, Ordering::Relaxed);
    }

    /// The setting of [`set_call_timeout`](ObjectRef::set_call_timeout).
    pub fn call_timeout(&self) -> Option<Option<Duration>> {
        match self.call_timeout.load(Ordering::Relaxed) {
            timeout::UNSET => None,
            v => Some(timeout::decode(v)),
        }
    }

    /// The timeout of a call on this reference from the calling thread:
    /// the reference's, else the thread's, else the ORB's (the order
    /// omniORB uses).
    pub(crate) fn effective_timeout(&self) -> Option<Duration> {
        self.call_timeout()
            .or_else(timeout::thread_call_timeout)
            .unwrap_or_else(|| self.orb.call_timeout())
    }

    /// `CORBA::Object::_is_a`.
    pub fn is_a(&self, repository_id: &str) -> Result<bool, Exception> {
        let reply = self
            .request("_is_a")
            .args(|out| out.write_string(repository_id))
            .invoke()?;
        Ok(reply.input().read::<bool>()?)
    }

    /// `CORBA::Object::_non_existent`. `OBJECT_NOT_EXIST` from the server
    /// counts as `true`.
    pub fn non_existent(&self) -> Result<bool, Exception> {
        match self.request("_non_existent").invoke() {
            Ok(reply) => Ok(reply.input().read::<bool>()?),
            Err(Exception::System(e)) if e.is(SystemExceptionKind::OBJECT_NOT_EXIST) => Ok(true),
            Err(e) => Err(e),
        }
    }

    /// The async form of [`is_a`](ObjectRef::is_a).
    pub async fn is_a_async(&self, repository_id: &str) -> Result<bool, Exception> {
        let id = repository_id.to_owned();
        let reply = self
            .request_async("_is_a")
            .args(move |out| out.write_string(&id))
            .invoke()
            .await?;
        Ok(reply.input().read::<bool>()?)
    }

    /// The async form of [`non_existent`](ObjectRef::non_existent).
    pub async fn non_existent_async(&self) -> Result<bool, Exception> {
        match self.request_async("_non_existent").invoke().await {
            Ok(reply) => Ok(reply.input().read::<bool>()?),
            Err(Exception::System(e)) if e.is(SystemExceptionKind::OBJECT_NOT_EXIST) => Ok(true),
            Err(e) => Err(e),
        }
    }

    /// Sends a `LocateRequest`, following forwards. Returns whether the
    /// server has the object (`OBJECT_HERE`) or not (`UNKNOWN_OBJECT`).
    pub fn locate(&self) -> Result<bool, Exception> {
        let kind = Kind::<ArgsFn<'_>>::Locate;
        let outcome = invoke(self, &kind, self.effective_timeout(), None)?;
        match outcome {
            Outcome::Located(here) => Ok(here),
            Outcome::Reply(_) => unreachable!("a locate request gives a locate outcome"),
        }
    }

    /// The async form of [`locate`](ObjectRef::locate).
    pub fn locate_async(&self) -> impl Future<Output = Result<bool, Exception>> + Send + '_ {
        let timeout = self.effective_timeout();
        self.orb.in_runtime(async move {
            let kind = Kind::<SendArgsFn<'_>>::Locate;
            match invoke_async(self, &kind, timeout, None).await? {
                Outcome::Located(here) => Ok(here),
                Outcome::Reply(_) => unreachable!("a locate request gives a locate outcome"),
            }
        })
    }

    /// `CORBA::Object::validate_connection`: binds the reference with a
    /// `LocateRequest` (following forwards) and returns true. rustorb has
    /// no policy that can forbid a call, so it never returns false. The
    /// failure to bind raises its exception (`TRANSIENT`, `TIMEOUT`...),
    /// and an object the server does not have `OBJECT_NOT_EXIST`.
    pub fn validate_connection(&self) -> Result<bool, Exception> {
        if self.locate()? {
            Ok(true)
        } else {
            Err(SystemException::new(
                SystemExceptionKind::OBJECT_NOT_EXIST,
                minor::NO_SUCH_OBJECT,
                CompletionStatus::No,
            )
            .into())
        }
    }

    fn current_target(&self) -> Arc<Ior> {
        match &*self.forward.lock().unwrap() {
            Some(ior) => Arc::clone(ior),
            None => Arc::clone(&self.ior),
        }
    }

    fn set_forward(&self, ior: Option<Arc<Ior>>) {
        *self.forward.lock().unwrap() = ior;
    }
}

/// A request being built: the operation, its arguments, and a timeout.
pub struct Request<'a> {
    obj: &'a ObjectRef,
    operation: String,
    args: Option<Box<ArgsFn<'a>>>,
    /// Set by [`Request::timeout`].
    timeout: Option<Option<Duration>>,
    /// The parameters of a DII request, for the interceptors.
    dii: Option<DiiParams>,
}

impl fmt::Debug for Request<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Request")
            .field("operation", &self.operation)
            .field("timeout", &self.timeout)
            .finish_non_exhaustive()
    }
}

impl<'a> Request<'a> {
    /// Sets the function that writes the `in` and `inout` arguments. It may
    /// run more than once, when the request is forwarded or retried.
    pub fn args<F>(mut self, f: F) -> Request<'a>
    where
        F: Fn(&mut OutStream<'_>) -> Result<(), SystemException> + 'a,
    {
        self.args = Some(Box::new(f));
        self
    }

    /// Sets how long this request waits for a reply (`None`: no limit),
    /// overriding the timeouts of the thread, the reference and the ORB
    /// (see [`Orb::set_call_timeout`]).
    pub fn timeout(mut self, timeout: Option<Duration>) -> Request<'a> {
        self.timeout = Some(timeout);
        self
    }

    fn effective_timeout(&self) -> Option<Duration> {
        self.timeout.unwrap_or_else(|| self.obj.effective_timeout())
    }

    /// The DII parameters, for the interceptors.
    pub(crate) fn dii(mut self, params: DiiParams) -> Request<'a> {
        self.dii = Some(params);
        self
    }

    /// Sends the request and waits for the reply.
    pub fn invoke(self) -> Result<Reply, Exception> {
        let kind = Kind::Request {
            operation: &self.operation,
            args: self.args.as_deref(),
            response: true,
            sync: sync_scope::SYNC_WITH_TARGET,
            dii: self.dii.as_ref(),
        };
        let slots = request_slots(self.obj);
        match invoke(self.obj, &kind, self.effective_timeout(), slots)? {
            Outcome::Reply(Some(reply)) => Ok(reply),
            _ => unreachable!("a two-way request gives a reply"),
        }
    }

    /// Sends the request as a oneway call, with no reply. When the call
    /// returns depends on the `Messaging::SyncScopePolicy` of the
    /// reference, the thread or the ORB (`docs/sync-scope.md`): by default
    /// (`SYNC_WITH_TRANSPORT`) once the message is written; with
    /// `SYNC_NONE` before; with `SYNC_WITH_SERVER` or `SYNC_WITH_TARGET`
    /// once the server answers, which may raise the system exceptions of
    /// a two-way call.
    pub fn send_oneway(self) -> Result<(), SystemException> {
        let kind = Kind::Request {
            operation: &self.operation,
            args: self.args.as_deref(),
            response: false,
            sync: self.obj.effective_sync_scope(),
            dii: self.dii.as_ref(),
        };
        let slots = request_slots(self.obj);
        match invoke(self.obj, &kind, self.effective_timeout(), slots) {
            Ok(_) => Ok(()),
            Err(Exception::System(e)) => Err(e),
            Err(Exception::User(_)) => unreachable!("a oneway request has no reply"),
        }
    }
}

/// A request that runs as a future: [`Request`] for async code.
///
/// The future can be polled by any executor, or none in particular: the
/// sockets and timers of the call belong to the ORB's runtime. It does not
/// block the thread that polls it, except that a call to an object of the
/// ORB's own server side runs the servant on an upcall thread and waits
/// for it without blocking. The timeout is taken when
/// [`invoke`](AsyncRequest::invoke) is called, so a timeout of the calling
/// thread ([`set_thread_call_timeout`](crate::set_thread_call_timeout))
/// counts as it does for [`Request`].
pub struct AsyncRequest<'a> {
    obj: &'a ObjectRef,
    operation: String,
    args: Option<Box<SendArgsFn<'a>>>,
    timeout: Option<Option<Duration>>,
    dii: Option<DiiParams>,
    /// The request scope slots, when taken on another thread.
    slots: Option<Option<Vec<crate::Any>>>,
}

impl fmt::Debug for AsyncRequest<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AsyncRequest")
            .field("operation", &self.operation)
            .field("timeout", &self.timeout)
            .finish_non_exhaustive()
    }
}

impl<'a> AsyncRequest<'a> {
    /// [`Request::args`]; the function must be `Send` and `Sync`, as the
    /// future may move between threads.
    pub fn args<F>(mut self, f: F) -> AsyncRequest<'a>
    where
        F: Fn(&mut OutStream<'_>) -> Result<(), SystemException> + Send + Sync + 'a,
    {
        self.args = Some(Box::new(f));
        self
    }

    /// [`Request::timeout`].
    pub fn timeout(mut self, timeout: Option<Duration>) -> AsyncRequest<'a> {
        self.timeout = Some(timeout);
        self
    }

    /// The DII parameters, for the interceptors.
    pub(crate) fn dii(mut self, params: DiiParams) -> AsyncRequest<'a> {
        self.dii = Some(params);
        self
    }

    /// The request scope slots, taken by
    /// [`ObjectRef::request_slots`] on the thread that made the call.
    pub(crate) fn slots(mut self, slots: Option<Vec<crate::Any>>) -> AsyncRequest<'a> {
        self.slots = Some(slots);
        self
    }

    /// Sends the request; the future resolves to the reply.
    pub fn invoke(mut self) -> impl Future<Output = Result<Reply, Exception>> + Send + 'a {
        let timeout = self.timeout.unwrap_or_else(|| self.obj.effective_timeout());
        // The slots of the thread that makes the call.
        let slots = self.slots.take().unwrap_or_else(|| request_slots(self.obj));
        let orb = self.obj.orb.clone();
        orb.in_runtime(async move {
            let kind = Kind::Request {
                operation: &self.operation,
                args: self.args.as_deref(),
                response: true,
                sync: sync_scope::SYNC_WITH_TARGET,
                dii: self.dii.as_ref(),
            };
            match invoke_async(self.obj, &kind, timeout, slots).await? {
                Outcome::Reply(Some(reply)) => Ok(reply),
                _ => unreachable!("a two-way request gives a reply"),
            }
        })
    }

    /// Sends the request as a oneway call; the future resolves when
    /// [`Request::send_oneway`] would return. The sync scope is taken when
    /// this is called, like the timeout.
    pub fn send_oneway(mut self) -> impl Future<Output = Result<(), SystemException>> + Send + 'a {
        let timeout = self.timeout.unwrap_or_else(|| self.obj.effective_timeout());
        let sync = self.obj.effective_sync_scope();
        let slots = self.slots.take().unwrap_or_else(|| request_slots(self.obj));
        let orb = self.obj.orb.clone();
        orb.in_runtime(async move {
            let kind = Kind::Request {
                operation: &self.operation,
                args: self.args.as_deref(),
                response: false,
                sync,
                dii: self.dii.as_ref(),
            };
            match invoke_async(self.obj, &kind, timeout, slots).await {
                Ok(_) => Ok(()),
                Err(Exception::System(e)) => Err(e),
                Err(Exception::User(_)) => unreachable!("a oneway request has no reply"),
            }
        })
    }
}

/// A request that returns at once and hands its reply to a callback: what
/// the `sendc_` operations of AMI (`docs/ami.md`) are built on.
///
/// The request is sent by the ORB's runtime, as [`AsyncRequest`] does,
/// and the callback runs on a thread of the ORB's reply pool, not on the
/// thread that sent it nor on a tokio worker, so it may use the
/// synchronous API (to call a `ReplyHandler`, say). The timeout and the
/// Portable Interceptors' request scope slots are those of the thread
/// that calls [`send`](CallbackRequest::send).
pub struct CallbackRequest {
    obj: ObjectRef,
    operation: String,
    args: Option<Box<SendArgsFn<'static>>>,
    timeout: Option<Option<Duration>>,
}

impl fmt::Debug for CallbackRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CallbackRequest")
            .field("operation", &self.operation)
            .field("timeout", &self.timeout)
            .finish_non_exhaustive()
    }
}

impl CallbackRequest {
    /// [`Request::args`]. The function owns what it writes: it runs after
    /// [`send`](CallbackRequest::send) has returned, on the ORB's runtime,
    /// once or more (when the request is forwarded or sent again).
    pub fn args<F>(mut self, f: F) -> CallbackRequest
    where
        F: Fn(&mut OutStream<'_>) -> Result<(), SystemException> + Send + Sync + 'static,
    {
        self.args = Some(Box::new(f));
        self
    }

    /// [`Request::timeout`].
    pub fn timeout(mut self, timeout: Option<Duration>) -> CallbackRequest {
        self.timeout = Some(timeout);
        self
    }

    /// Sends the request without waiting for it. `done` gets the reply or
    /// the exception exactly once, on a thread of the reply pool. Fails
    /// only when the ORB is shut down (`BAD_INV_ORDER`), and then `done`
    /// is not called.
    ///
    /// If the ORB is destroyed or its runtime ends before the reply
    /// arrives, `done` gets the exception of the failed call
    /// (`COMM_FAILURE` or `TRANSIENT`), on the thread that ends it.
    pub fn send<F>(self, done: F) -> Result<(), SystemException>
    where
        F: FnOnce(Result<Reply, Exception>) + Send + 'static,
    {
        let CallbackRequest {
            obj,
            operation,
            args,
            timeout,
        } = self;
        let orb = obj.orb.clone();
        orb.check_running()?;
        let timeout = timeout.unwrap_or_else(|| obj.effective_timeout());
        let slots = request_slots(&obj);
        let pending = PendingReply {
            orb: orb.clone(),
            done: Some(done),
            result: None,
        };
        orb.runtime_handle().spawn(async move {
            let mut pending = pending;
            let request = AsyncRequest {
                obj: &obj,
                operation,
                args: args.map(|a| a as Box<SendArgsFn<'_>>),
                timeout: Some(timeout),
                dii: None,
                slots: Some(slots),
            };
            pending.result = Some(request.invoke().await);
            pending.deliver();
        });
        Ok(())
    }
}

/// The callback of a [`CallbackRequest`] and, once known, its result.
/// Dropped without being delivered (its task or its job dropped by an
/// ending runtime or pool), it calls the callback where it is dropped.
struct PendingReply<F: FnOnce(Result<Reply, Exception>) + Send + 'static> {
    orb: Orb,
    done: Option<F>,
    result: Option<Result<Reply, Exception>>,
}

impl<F: FnOnce(Result<Reply, Exception>) + Send + 'static> PendingReply<F> {
    /// Runs the callback on the reply pool.
    fn deliver(self) {
        let orb = self.orb.clone();
        orb.submit_reply(Box::new(move || drop(self)));
    }
}

impl<F: FnOnce(Result<Reply, Exception>) + Send + 'static> Drop for PendingReply<F> {
    /// Calls the callback: on the reply pool through `deliver`; here when
    /// dropped undelivered (the task or the job was dropped), with
    /// `COMM_FAILURE`, off the threads of a runtime.
    fn drop(&mut self) {
        if let Some(done) = self.done.take() {
            let result = self.result.take().unwrap_or_else(|| {
                Err(sys(
                    SystemExceptionKind::COMM_FAILURE,
                    0,
                    CompletionStatus::Maybe,
                )
                .into())
            });
            crate::orb::run_reply_job(Box::new(move || done(result)));
        }
    }
}

/// A normal reply: the return value and the `out` and `inout` arguments.
#[derive(Debug, Clone)]
pub struct Reply {
    body: Body,
    code_sets: CodeSets,
    orb: Orb,
}

impl Reply {
    /// A stream over the reply body.
    pub fn input(&self) -> InStream<'_> {
        InStream {
            dec: self.body.decoder(),
            code_sets: self.code_sets,
            orb: Some(&self.orb),
            completed: CompletionStatus::Yes,
            wchar_needs_code_set: false,
            values: Vec::new(),
            typed_values: Vec::new(),
            custom_items: None,
            body: Some(&self.body),
        }
    }

    /// The raw reply body.
    pub fn body(&self) -> &Body {
        &self.body
    }
}

enum Kind<'k, A: ?Sized = ArgsFn<'k>> {
    Request {
        operation: &'k str,
        args: Option<&'k A>,
        /// A two-way request.
        response: bool,
        /// The `Messaging::SyncScope` of a oneway request
        /// (`SYNC_WITH_TARGET` for a two-way one).
        sync: i16,
        dii: Option<&'k DiiParams>,
    },
    Locate,
}

enum Outcome {
    Reply(Option<Reply>),
    Located(bool),
}

enum Attempt {
    Done(Result<Outcome, Exception>),
    /// The request was not processed here; try the next address.
    NotSent(SystemException),
    Forward(Ior),
    Addressing(AddressingDisposition),
    /// The server closed the connection before it processed the request:
    /// send it again to the same address. Only with client interceptors,
    /// which see each sending; without, [`attempt`] sends it again itself.
    Resend,
}

/// One address an object can be reached at.
struct Endpoint {
    profile_index: usize,
    version: Version,
    host: String,
    port: u16,
    /// TCP, TLS (from `TAG_SSL_SEC_TRANS`), or a Unix socket (from
    /// `TAG_OMNIORB_UNIX_TRANS`; `host` is then the socket's path).
    transport: Transport,
    object_key: Vec<u8>,
    code_sets: Option<CodeSetComponentInfo>,
}

/// Every IIOP address in `ior` this ORB can use, in order: for each
/// profile, its `giop:unix` sockets on this host (docs/unix-transport.md),
/// then its TLS endpoint if it has one and the ORB can use TLS
/// (docs/ssliop.md), else its own address and its alternate addresses.
/// A port of 0 is no address.
fn endpoints(ior: &Ior, can_tls: bool) -> Vec<Endpoint> {
    #[cfg(unix)]
    let local_host = Some(crate::unix::host());
    #[cfg(not(unix))]
    let local_host: Option<&str> = None;
    let shared: Vec<_> = ior
        .profiles
        .iter()
        .filter(|p| p.tag == TAG_MULTIPLE_COMPONENTS)
        .filter_map(|p| p.multiple_components().ok())
        .flatten()
        .collect();
    let mut out = Vec::new();
    for (index, profile) in ior.profiles.iter().enumerate() {
        if profile.tag != TAG_INTERNET_IOP {
            continue;
        }
        let Ok(iiop) = profile.iiop() else { continue };
        if iiop.version.major != 1 {
            continue;
        }
        // IIOP 1.0 profiles have no components of their own; they use
        // those of the TAG_MULTIPLE_COMPONENTS profile.
        let components = if iiop.version.minor == 0 {
            &shared
        } else {
            &iiop.components
        };
        let code_sets = components
            .iter()
            .find(|c| c.tag == component_tag::CODE_SETS)
            .and_then(|c| CodeSetComponentInfo::from_component(c).ok());
        let ssl = components
            .iter()
            .find(|c| c.tag == component_tag::SSL_SEC_TRANS)
            .and_then(|c| SslSecTrans::from_component(c).ok());
        let mut addrs = Vec::new();
        if let Some(local_host) = local_host {
            // Only sockets on this host can be reached; the host name is
            // compared like omniORB does (seen from outside).
            addrs.extend(
                components
                    .iter()
                    .filter(|c| c.tag == component_tag::OMNIORB_UNIX_TRANS)
                    .filter_map(|c| UnixTrans::from_component(c).ok())
                    .filter(|u| !u.path.is_empty() && u.host.eq_ignore_ascii_case(local_host))
                    .map(|u| (u.path, 0, Transport::Unix)),
            );
        }
        if let (Some(ssl), true) = (ssl, can_tls) {
            // Not unprotected instead, should the TLS endpoint fail.
            addrs.push((iiop.host.clone(), ssl.port, Transport::Tls));
        } else {
            addrs.push((iiop.host.clone(), iiop.port, Transport::Tcp));
            addrs.extend(
                components
                    .iter()
                    .filter(|c| c.tag == component_tag::ALTERNATE_IIOP_ADDRESS)
                    .filter_map(|c| AlternateIiopAddress::from_component(c).ok())
                    .map(|a| (a.host, a.port, Transport::Tcp)),
            );
        }
        for (host, port, transport) in addrs {
            if port == 0 && transport != Transport::Unix {
                continue;
            }
            out.push(Endpoint {
                profile_index: index,
                version: iiop.version,
                host,
                port,
                transport,
                object_key: iiop.object_key.clone(),
                code_sets: code_sets.clone(),
            });
        }
    }
    out
}

fn sys(kind: SystemExceptionKind, minor: u32, completed: CompletionStatus) -> SystemException {
    SystemException::new(kind, minor, completed)
}

/// The walk of a call over the addresses of its target, the forwards and
/// the addressing modes; the same for blocking and async calls.
struct Walk<'o> {
    obj: &'o ObjectRef,
    max_hops: u32,
    hops: u32,
    ior: Arc<Ior>,
    disposition: AddressingDisposition,
    endpoints: std::vec::IntoIter<Endpoint>,
    /// Why the addresses tried so far could not be used.
    last: SystemException,
    /// The target was just set (and is still to be checked for nil).
    fresh: bool,
}

enum Step {
    Try(Endpoint),
    Done(Result<Outcome, Exception>),
}

impl<'o> Walk<'o> {
    fn new(obj: &'o ObjectRef) -> Walk<'o> {
        let mut walk = Walk {
            obj,
            max_hops: obj.orb.inner.options.max_forwards,
            hops: 0,
            ior: obj.current_target(),
            disposition: AddressingDisposition::Key,
            endpoints: Vec::new().into_iter(),
            last: no_usable_profile(),
            fresh: true,
        };
        walk.retarget(Arc::clone(&walk.ior));
        walk
    }

    fn retarget(&mut self, ior: Arc<Ior>) {
        self.endpoints = endpoints(&ior, self.obj.orb.has_tls_client()).into_iter();
        self.ior = ior;
        self.last = no_usable_profile();
        self.fresh = true;
    }

    /// The next address to try, or the end of the call.
    fn next(&mut self) -> Step {
        loop {
            if std::mem::take(&mut self.fresh) && self.ior.is_nil() {
                return Step::Done(Err(sys(
                    SystemExceptionKind::INV_OBJREF,
                    0,
                    CompletionStatus::No,
                )
                .into()));
            }
            if let Some(ep) = self.endpoints.next() {
                return Step::Try(ep);
            }
            // Nothing could be reached. A forwarded target falls back to
            // the original reference.
            if !Arc::ptr_eq(&self.ior, &self.obj.ior) {
                self.hops += 1;
                if self.hops <= self.max_hops {
                    self.obj.set_forward(None);
                    self.disposition = AddressingDisposition::Key;
                    self.retarget(Arc::clone(&self.obj.ior));
                    continue;
                }
            }
            return Step::Done(Err(self.last.clone().into()));
        }
    }

    /// Takes in the attempt at the address [`next`](Walk::next) gave:
    /// `Some` ends the call.
    fn record(&mut self, attempt: Attempt) -> Option<Result<Outcome, Exception>> {
        match attempt {
            Attempt::Done(result) => Some(result),
            Attempt::NotSent(e) => {
                self.last = e;
                None
            }
            // The caller sends again; here only after too many tries.
            Attempt::Resend => {
                self.last = sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No);
                None
            }
            Attempt::Forward(next) => {
                trace::info!("LOCATION_FORWARD to {}", trace::IorSummary(&next));
                self.hops += 1;
                if self.hops > self.max_hops {
                    return Some(Err(sys(
                        SystemExceptionKind::TRANSIENT,
                        0,
                        CompletionStatus::No,
                    )
                    .into()));
                }
                let next = Arc::new(next);
                self.obj.set_forward(Some(Arc::clone(&next)));
                self.disposition = AddressingDisposition::Key;
                self.retarget(next);
                None
            }
            Attempt::Addressing(wanted) => {
                trace::debug!("NEEDS_ADDRESSING_MODE: {wanted:?}");
                self.hops += 1;
                if self.hops > self.max_hops || wanted == self.disposition {
                    return Some(Err(sys(
                        SystemExceptionKind::MARSHAL,
                        0,
                        CompletionStatus::No,
                    )
                    .into()));
                }
                self.disposition = wanted;
                self.retarget(Arc::clone(&self.ior));
                None
            }
        }
    }
}

fn no_usable_profile() -> SystemException {
    sys(
        SystemExceptionKind::TRANSIENT,
        minor::NO_USABLE_PROFILE,
        CompletionStatus::No,
    )
}

/// The slots of the calling thread for a request on `obj`, if its ORB has
/// client interceptors.
fn request_slots(obj: &ObjectRef) -> Option<Vec<crate::Any>> {
    obj.orb
        .interceptors()
        .filter(|pi| pi.has_client())
        .map(|pi| pi::thread_slots(&pi))
}

/// The client interceptors of a call, with the request scope slots.
struct ClientPi {
    pi: Arc<Interceptors>,
    slots: Vec<crate::Any>,
}

impl ClientPi {
    fn new<A: ?Sized>(
        obj: &ObjectRef,
        kind: &Kind<'_, A>,
        slots: Option<Vec<crate::Any>>,
    ) -> Option<ClientPi> {
        if !matches!(kind, Kind::Request { .. }) {
            return None;
        }
        let slots = slots?;
        let pi = obj.orb.interceptors().filter(|pi| pi.has_client())?;
        Some(ClientPi { pi, slots })
    }

    /// The information of an attempt at `ep`, and `send_request`. `Err`
    /// ends the attempt before anything is sent.
    fn start<'i, A: ?Sized>(
        &self,
        obj: &'i ObjectRef,
        kind: &Kind<'i, A>,
        ior: &Arc<Ior>,
        ep: &Endpoint,
        timeout: Option<Duration>,
    ) -> Result<ClientRequestInfo<'i>, Attempt> {
        let Kind::Request {
            operation,
            response,
            sync,
            dii,
            ..
        } = *kind
        else {
            unreachable!("interceptors only see requests");
        };
        let info = ClientRequestInfo::new(
            &self.pi,
            ClientRequest {
                operation,
                response_expected: response,
                sync_scope: sync,
                target: obj,
                effective: Arc::clone(ior),
                profile_index: Some(ep.profile_index),
                timeout,
                slots: self.slots.clone(),
                dii,
            },
        );
        match pi::send_request(&self.pi, &info) {
            Ok(()) => Ok(info),
            Err(ending) => Err(from_ending(ending, None, None)),
        }
    }

    /// Runs the ending points for `attempt`, and returns the attempt as
    /// they leave it.
    fn finish(
        &self,
        orb: &Orb,
        info: &ClientRequestInfo<'_>,
        attempt: Attempt,
        reply_contexts: Vec<ServiceContext>,
    ) -> Attempt {
        info.set_reply_contexts(reply_contexts);
        let mut not_sent = None;
        let mut addressing = None;
        let ending = match attempt {
            Attempt::Done(Ok(Outcome::Reply(Some(reply)))) => ClientEnding::Reply(reply),
            Attempt::Done(Ok(Outcome::Reply(None))) => ClientEnding::Oneway,
            Attempt::Done(Ok(Outcome::Located(_))) => return attempt,
            Attempt::Done(Err(e)) => ClientEnding::Exception(e),
            Attempt::NotSent(e) => {
                not_sent = Some(e.clone());
                ClientEnding::Exception(Exception::System(e))
            }
            Attempt::Forward(ior) => ClientEnding::Forward(ObjectRef::new(orb.clone(), ior)),
            Attempt::Addressing(d) => {
                addressing = Some(d);
                ClientEnding::Retry
            }
            Attempt::Resend => ClientEnding::Retry,
        };
        from_ending(pi::receive(&self.pi, info, ending), not_sent, addressing)
    }
}

/// The attempt an interception ended with. An exception that is still the
/// one of an attempt that sent nothing (`not_sent`) lets the call go on to
/// the next address; a retry is the one the ORB was about to make.
fn from_ending(
    ending: ClientEnding,
    not_sent: Option<SystemException>,
    addressing: Option<AddressingDisposition>,
) -> Attempt {
    match ending {
        ClientEnding::Reply(reply) => Attempt::Done(Ok(Outcome::Reply(Some(reply)))),
        ClientEnding::Oneway => Attempt::Done(Ok(Outcome::Reply(None))),
        ClientEnding::Exception(Exception::System(e)) if not_sent.as_ref() == Some(&e) => {
            Attempt::NotSent(e)
        }
        ClientEnding::Exception(e) => Attempt::Done(Err(e)),
        ClientEnding::Forward(to) => Attempt::Forward(to.ior().clone()),
        ClientEnding::Retry => match addressing {
            Some(d) => Attempt::Addressing(d),
            None => Attempt::Resend,
        },
    }
}

fn invoke<A: WriteArgs + ?Sized>(
    obj: &ObjectRef,
    kind: &Kind<'_, A>,
    timeout: Option<Duration>,
    slots: Option<Vec<crate::Any>>,
) -> Result<Outcome, Exception> {
    let orb = &obj.orb;
    orb.check_running()?;
    // The timeout covers the whole call: connecting, forwards and the
    // wait for the reply.
    let deadline = timeout.map(|t| Instant::now() + t);
    let pi = ClientPi::new(obj, kind, slots);
    let mut walk = Walk::new(obj);
    let mut again: Option<(Endpoint, usize)> = None;
    loop {
        let (ep, resent) = match again.take() {
            Some(again) => again,
            None => match walk.next() {
                Step::Try(ep) => (ep, 0),
                Step::Done(result) => return traced(kind, result),
            },
        };
        let (ior, disposition) = (Arc::clone(&walk.ior), walk.disposition);
        let info = match &pi {
            Some(pi) => match pi.start(obj, kind, &ior, &ep, timeout) {
                Ok(info) => Some(info),
                Err(done) => {
                    if let Some(result) = walk.record(done) {
                        return traced(kind, result);
                    }
                    continue;
                }
            },
            None => None,
        };
        let contexts = info
            .as_ref()
            .map(|i| i.take_request_contexts())
            .unwrap_or_default();
        let mut reply_contexts = Vec::new();
        let mut attempt = match orb.local_server(&ep.host, ep.port, ep.transport) {
            Some(server) => {
                match local_call(orb, &ior, &ep, kind, deadline, disposition, &contexts) {
                    Ok(call) => {
                        let result = call.run(&server);
                        local_outcome(orb, result, &mut reply_contexts)
                    }
                    Err(done) => done,
                }
            }
            None => orb.block_on(attempt(
                orb,
                &ior,
                &ep,
                kind,
                Exchange {
                    deadline,
                    disposition,
                    own_thread: true,
                    resend: info.is_none(),
                    contexts: &contexts,
                    reply_contexts: &mut reply_contexts,
                },
            ))?,
        };
        attempt = without_reply(kind, attempt);
        if let (Some(pi), Some(info)) = (&pi, &info) {
            attempt = pi.finish(orb, info, attempt, reply_contexts);
        }
        if let Attempt::Resend = attempt {
            if resent + 1 < CLOSED_ATTEMPTS {
                again = Some((ep, resent + 1));
                continue;
            }
            attempt =
                Attempt::NotSent(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No));
        }
        if let Some(result) = walk.record(attempt) {
            return traced(kind, result);
        }
    }
}

/// What one attempt sends besides the request, and what it brings back.
struct Exchange<'x> {
    deadline: Option<Instant>,
    disposition: AddressingDisposition,
    /// The caller is a thread of its own (a blocking call), which may
    /// block reading the reply.
    own_thread: bool,
    /// Send the request again after a `CloseConnection` (no client
    /// interceptors): else the attempt ends with [`Attempt::Resend`].
    resend: bool,
    /// The service contexts of the interceptors.
    contexts: &'x [ServiceContext],
    /// The service contexts of the reply.
    reply_contexts: &'x mut Vec<ServiceContext>,
}

/// [`invoke`] as a future, run inside the ORB's runtime
/// ([`Orb::in_runtime`]). A call to the ORB's own server side runs on an
/// upcall thread.
async fn invoke_async<A: WriteArgs + ?Sized>(
    obj: &ObjectRef,
    kind: &Kind<'_, A>,
    timeout: Option<Duration>,
    slots: Option<Vec<crate::Any>>,
) -> Result<Outcome, Exception> {
    let orb = &obj.orb;
    orb.check_running()?;
    let deadline = timeout.map(|t| Instant::now() + t);
    let pi = ClientPi::new(obj, kind, slots);
    let mut walk = Walk::new(obj);
    let mut again: Option<(Endpoint, usize)> = None;
    loop {
        let (ep, resent) = match again.take() {
            Some(again) => again,
            None => match walk.next() {
                Step::Try(ep) => (ep, 0),
                Step::Done(result) => return traced(kind, result),
            },
        };
        let (ior, disposition) = (Arc::clone(&walk.ior), walk.disposition);
        let info = match &pi {
            Some(pi) => match pi.start(obj, kind, &ior, &ep, timeout) {
                Ok(info) => Some(info),
                Err(done) => {
                    if let Some(result) = walk.record(done) {
                        return traced(kind, result);
                    }
                    continue;
                }
            },
            None => None,
        };
        let contexts = info
            .as_ref()
            .map(|i| i.take_request_contexts())
            .unwrap_or_default();
        let mut reply_contexts = Vec::new();
        let mut attempt = match orb.local_server(&ep.host, ep.port, ep.transport) {
            Some(server) => {
                match local_call(orb, &ior, &ep, kind, deadline, disposition, &contexts) {
                    Ok(call) => {
                        let (tx, rx) = tokio::sync::oneshot::channel();
                        let on_pool = Arc::clone(&server);
                        server.submit(Box::new(move || {
                            let _ = tx.send(call.run(&on_pool));
                        }));
                        // The pool is gone when the ORB is being destroyed.
                        let result = rx.await.unwrap_or_else(|_| {
                            Err(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No))
                        });
                        local_outcome(orb, result, &mut reply_contexts)
                    }
                    Err(done) => done,
                }
            }
            None => {
                attempt(
                    orb,
                    &ior,
                    &ep,
                    kind,
                    Exchange {
                        deadline,
                        disposition,
                        own_thread: false,
                        resend: info.is_none(),
                        contexts: &contexts,
                        reply_contexts: &mut reply_contexts,
                    },
                )
                .await
            }
        };
        attempt = without_reply(kind, attempt);
        if let (Some(pi), Some(info)) = (&pi, &info) {
            attempt = pi.finish(orb, info, attempt, reply_contexts);
        }
        if let Attempt::Resend = attempt {
            if resent + 1 < CLOSED_ATTEMPTS {
                again = Some((ep, resent + 1));
                continue;
            }
            attempt =
                Attempt::NotSent(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No));
        }
        if let Some(result) = walk.record(attempt) {
            return traced(kind, result);
        }
    }
}

/// The end of a call, with a trace line for a system exception.
fn traced<A: WriteArgs + ?Sized>(
    kind: &Kind<'_, A>,
    result: Result<Outcome, Exception>,
) -> Result<Outcome, Exception> {
    if let Err(Exception::System(e)) = &result {
        trace::debug!("{} raised {e}", KindName(kind));
    }
    result
}

/// What a call is in trace lines: `request "op"` or `LocateRequest`.
struct KindName<'a, 'k, A: ?Sized>(&'a Kind<'k, A>);

impl<A: ?Sized> fmt::Display for KindName<'_, '_, A> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            Kind::Request { operation, .. } => write!(f, "request {operation:?}"),
            Kind::Locate => f.write_str("LocateRequest"),
        }
    }
}

/// How long a `CancelRequest` after a timeout may take to go out.
const CANCEL_SEND_TIME: Duration = Duration::from_millis(100);

/// How many times one endpoint is tried when its connections close
/// before the reply: a request left without a reply by `CloseConnection`
/// was not processed, and a connection the server (or this ORB) chose to
/// close as idle may close under a request sent at the same moment.
const CLOSED_ATTEMPTS: usize = 4;

/// Sends the request to one endpoint. A `CloseConnection` before the reply
/// means the server did not process it, so it is sent again on a new
/// connection, up to [`CLOSED_ATTEMPTS`] times in all.
///
/// With `own_thread`, the caller is a thread of its own (a blocking call),
/// which may block reading the reply.
async fn attempt<A: WriteArgs + ?Sized>(
    orb: &Orb,
    ior: &Ior,
    ep: &Endpoint,
    kind: &Kind<'_, A>,
    mut x: Exchange<'_>,
) -> Attempt {
    let deadline = x.deadline;
    let mut result = Attempt::NotSent(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No));
    for _ in 0..CLOSED_ATTEMPTS {
        let conn = match orb
            .connection(&ep.host, ep.port, ep.transport, deadline)
            .await
        {
            Ok(conn) => conn,
            // Out of time: the other addresses are not tried.
            Err(e) if e.is(SystemExceptionKind::TIMEOUT) => return Attempt::Done(Err(e.into())),
            Err(e) => return Attempt::NotSent(e),
        };
        match attempt_on(orb, &conn, ior, ep, kind, &mut x).await {
            Ok(done) => return done,
            Err(Closed::Orderly) => {
                orb.discard(&conn);
                if !x.resend {
                    return Attempt::Resend;
                }
                result =
                    Attempt::NotSent(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No));
            }
            Err(Closed::Failed(_)) => {
                orb.discard(&conn);
                return Attempt::Done(Err(sys(
                    SystemExceptionKind::COMM_FAILURE,
                    0,
                    CompletionStatus::Maybe,
                )
                .into()));
            }
        }
    }
    result
}

/// `Err(Closed::Orderly)` asks for a retry on a new connection;
/// `Err(Closed::Failed)` after the request was sent is `COMM_FAILURE`.
async fn attempt_on<A: WriteArgs + ?Sized>(
    orb: &Orb,
    conn: &Arc<Connection>,
    ior: &Ior,
    ep: &Endpoint,
    kind: &Kind<'_, A>,
    x: &mut Exchange<'_>,
) -> Result<Attempt, Closed> {
    let (deadline, disposition, own_thread) = (x.deadline, x.disposition, x.own_thread);
    let options = &orb.inner.options;
    let order = options.byte_order;
    let version = ep.version.min(options.max_giop_version);
    let target = target_address(ior, ep, version, disposition);

    // Code sets: negotiated from the IOR for GIOP 1.1 and later, fixed for
    // the connection by its first request, and announced in every request.
    let (code_sets, context) = match (&ep.code_sets, version >= Version::V1_1) {
        (Some(info), true) => {
            let proposed = match conn.code_sets() {
                Some(cs) => cs,
                None => match CodeSets::negotiate(info) {
                    Ok(cs) => cs,
                    Err(e) => return Ok(Attempt::Done(Err(e.into()))),
                },
            };
            let cs = conn.claim_code_sets(proposed);
            (cs, vec![cs.context().to_service_context(order)])
        }
        _ => (CodeSets::DEFAULT, Vec::new()),
    };
    let mut context = context;
    context.extend_from_slice(x.contexts);
    // Bidirectional GIOP: the first GIOP 1.2 request offers the connection.
    let offer = version >= Version::V1_2 && matches!(kind, Kind::Request { .. });
    let offer = offer
        && conn.bidir_context().is_some_and(|c| {
            context.push(c.clone());
            true
        });

    let request_id = conn.next_request_id();
    let flags = flags_of(kind);
    // A reply comes to a two-way request, and to a oneway one sent with
    // SYNC_WITH_SERVER or SYNC_WITH_TARGET.
    let response = flags & 0x01 != 0;
    // SYNC_NONE: the call returns before the request is written.
    let detached = matches!(
        kind,
        Kind::Request {
            response: false,
            sync: sync_scope::SYNC_NONE,
            ..
        }
    );
    let msg = match kind {
        Kind::Request {
            operation, args, ..
        } => {
            let header = request_header(request_id, flags, target, operation, context);
            match encode_request(version, order, &header, *args, code_sets) {
                Ok(msg) if msg.len() > options.max_message_size => {
                    trace::warning!(
                        "request {operation:?} of {} bytes is over the largest GIOP message \
                         ({} bytes, -ORBgiopMaxMsgSize): not sent",
                        msg.len(),
                        options.max_message_size
                    );
                    return Ok(Attempt::Done(Err(sys(
                        SystemExceptionKind::MARSHAL,
                        0,
                        CompletionStatus::No,
                    )
                    .into())));
                }
                Ok(msg) if options.fragment_size > 0 => msg.fragment(options.fragment_size),
                Ok(msg) => msg,
                Err(e) => return Ok(Attempt::Done(Err(e))),
            }
        }
        Kind::Locate => match MessageEncoder::locate_request(
            version,
            order,
            &LocateRequestHeader { request_id, target },
        ) {
            Ok(msg) => msg.into(),
            Err(_) => {
                return Ok(Attempt::Done(Err(sys(
                    SystemExceptionKind::MARSHAL,
                    0,
                    CompletionStatus::No,
                )
                .into())));
            }
        },
    };

    trace::debug!(
        "{} (id {request_id}{}) to {}:{}, GIOP {}.{}",
        KindName(kind),
        OnewayNote(kind),
        ep.host,
        ep.port,
        version.major,
        version.minor
    );
    let rx = if response {
        match conn.expect_reply(request_id) {
            Ok(rx) => Some(rx),
            Err(Closed::Orderly) => return Err(Closed::Orderly),
            // The connection broke before anything was sent: not processed.
            Err(Closed::Failed(_)) => {
                orb.discard(conn);
                return Ok(Attempt::NotSent(sys(
                    SystemExceptionKind::COMM_FAILURE,
                    0,
                    CompletionStatus::No,
                )));
            }
        }
    } else {
        None
    };
    if detached {
        // The request goes out on the ORB's runtime after the call has
        // returned; a failure is only traced.
        let (orb, conn) = (orb.clone(), Arc::clone(conn));
        orb.inner.handle.clone().spawn(async move {
            match conn.send(&msg, deadline).await {
                Ok(()) if offer => conn.offered(),
                Ok(()) => {}
                Err(e) => {
                    trace::debug!("oneway request (id {request_id}, SYNC_NONE) not sent: {e:?}");
                    if matches!(e, SendError::Failed) || !conn.is_usable() {
                        orb.discard(&conn);
                    }
                }
            }
        });
        return Ok(Attempt::Done(Ok(Outcome::Reply(None))));
    }
    match conn.send(&msg, deadline).await {
        Ok(()) if offer => conn.offered(),
        Ok(()) => {}
        // Out of time before the whole request went out (a peer that
        // stopped reading, say): the server did not get it.
        Err(SendError::TimedOut) => {
            conn.forget(request_id);
            if !conn.is_usable() {
                orb.discard(conn);
            }
            return Ok(Attempt::Done(Err(sys(
                SystemExceptionKind::TIMEOUT,
                0,
                CompletionStatus::No,
            )
            .into())));
        }
        // Chosen to close as idle just now: nothing was written.
        Err(SendError::Closing) => {
            conn.forget(request_id);
            return Err(Closed::Orderly);
        }
        Err(SendError::Failed) => {
            conn.forget(request_id);
            orb.discard(conn);
            return Ok(Attempt::NotSent(sys(
                SystemExceptionKind::COMM_FAILURE,
                0,
                CompletionStatus::No,
            )));
        }
    }
    let Some(rx) = rx else {
        return Ok(Attempt::Done(Ok(Outcome::Reply(None))));
    };

    // A blocking call runs on the caller's own thread (`Orb::block_on`),
    // which may block reading the reply.
    let here = if own_thread {
        conn.read_reply_here(request_id, deadline)
    } else {
        None
    };
    let delivered = match here {
        Some(Some(message)) => Some(Ok(Ok(message))),
        Some(None) => None,
        None => match deadline {
            Some(at) => tokio::time::timeout_at(at.into(), rx).await.ok(),
            None => Some(rx.await),
        },
    };
    let delivered = match delivered {
        Some(delivered) => delivered,
        None => {
            trace::debug!("{} (id {request_id}) timed out", KindName(kind));
            conn.forget(request_id);
            if let Ok(cancel) =
                MessageEncoder::cancel_request(version, order, &CancelRequestHeader { request_id })
            {
                // The caller is out of time already, and the connection
                // may be the reason: a short wait at most.
                let at = Instant::now() + CANCEL_SEND_TIME;
                let _ = conn.send(&cancel.into(), Some(at)).await;
            }
            return Ok(Attempt::Done(Err(sys(
                SystemExceptionKind::TIMEOUT,
                0,
                CompletionStatus::Maybe,
            )
            .into())));
        }
    };
    let message = match delivered {
        Ok(Ok(message)) => message,
        Ok(Err(closed)) => return Err(closed),
        Err(_) => return Err(Closed::Failed("reply channel dropped".into())),
    };
    Ok(match message {
        Message::Reply { header, body } => {
            if !matches!(kind, Kind::Request { .. }) {
                return Err(Closed::Failed("Reply to a LocateRequest".into()));
            }
            *x.reply_contexts = header.service_context;
            trace::debug!(
                "reply to {} (id {request_id}): {:?}",
                KindName(kind),
                header.reply_status
            );
            reply_outcome(orb, header.reply_status, body, code_sets)
        }
        Message::LocateReply { header, body } => {
            if !matches!(kind, Kind::Locate) {
                return Err(Closed::Failed("LocateReply to a Request".into()));
            }
            trace::debug!("LocateReply (id {request_id}): {:?}", header.locate_status);
            locate_outcome(header.locate_status, &body)
        }
        _ => return Err(Closed::Failed("unexpected message".into())),
    })
}

/// How a request names its target, in the addressing disposition the
/// server asked for (GIOP 1.2), or by object key.
fn target_address(
    ior: &Ior,
    ep: &Endpoint,
    version: Version,
    disposition: AddressingDisposition,
) -> TargetAddress {
    if version < Version::V1_2 {
        return TargetAddress::Key(ep.object_key.clone());
    }
    match disposition {
        AddressingDisposition::Key => TargetAddress::Key(ep.object_key.clone()),
        AddressingDisposition::Profile => {
            TargetAddress::Profile(ior.profiles[ep.profile_index].clone())
        }
        AddressingDisposition::Reference => TargetAddress::Reference {
            selected_profile_index: ep.profile_index as u32,
            ior: ior.clone(),
        },
    }
}

/// The `response_flags` of a request: `SYNC_WITH_TARGET` for a two-way
/// request; for a oneway one, the flags of its sync scope (the
/// `RequestHeader` of GIOP 1.2). GIOP 1.0 and 1.1 send `response_expected`
/// for the low bit.
fn flags_of<A: ?Sized>(kind: &Kind<'_, A>) -> u8 {
    match *kind {
        Kind::Request { response: true, .. } | Kind::Locate => response_flags::SYNC_WITH_TARGET,
        Kind::Request { sync, .. } => match sync {
            sync_scope::SYNC_WITH_TARGET => response_flags::SYNC_WITH_TARGET,
            sync_scope::SYNC_WITH_SERVER => response_flags::SYNC_WITH_SERVER,
            _ => response_flags::NONE,
        },
    }
}

/// `, oneway` and its sync scope in trace lines, for a oneway request.
struct OnewayNote<'a, 'k, A: ?Sized>(&'a Kind<'k, A>);

impl<A: ?Sized> fmt::Display for OnewayNote<'_, '_, A> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self.0 {
            Kind::Request {
                response: false,
                sync,
                ..
            } => {
                let name = match sync {
                    sync_scope::SYNC_NONE => "SYNC_NONE",
                    sync_scope::SYNC_WITH_SERVER => "SYNC_WITH_SERVER",
                    sync_scope::SYNC_WITH_TARGET => "SYNC_WITH_TARGET",
                    _ => "SYNC_WITH_TRANSPORT",
                };
                write!(f, ", oneway {name}")
            }
            _ => Ok(()),
        }
    }
}

/// A oneway request answered by the server (`SYNC_WITH_SERVER`,
/// `SYNC_WITH_TARGET`) ends as one without a reply: the reply has no body,
/// and the interceptors see `receive_other` as for any oneway request.
fn without_reply<A: ?Sized>(kind: &Kind<'_, A>, attempt: Attempt) -> Attempt {
    match (kind, attempt) {
        (
            Kind::Request {
                response: false, ..
            },
            Attempt::Done(Ok(Outcome::Reply(Some(_)))),
        ) => Attempt::Done(Ok(Outcome::Reply(None))),
        (_, attempt) => attempt,
    }
}

fn request_header(
    request_id: u32,
    flags: u8,
    target: TargetAddress,
    operation: &str,
    service_context: Vec<rustorb_giop::ServiceContext>,
) -> RequestHeader {
    RequestHeader {
        request_id,
        response_flags: flags,
        target,
        operation: operation.to_owned(),
        service_context,
        requesting_principal: Vec::new(),
    }
}

/// The whole `Request` message, with the arguments `args` writes.
fn encode_request<A: WriteArgs + ?Sized>(
    version: Version,
    order: rustorb_cdr::ByteOrder,
    header: &RequestHeader,
    args: Option<&A>,
    code_sets: CodeSets,
) -> Result<OutMessage, Exception> {
    let marshal = || sys(SystemExceptionKind::MARSHAL, 0, CompletionStatus::No).into();
    let mut m = MessageEncoder::request(version, order, header).map_err(|_| marshal())?;
    if let Some(args) = args {
        let mut out = OutStream {
            enc: m.body(),
            code_sets,
            orb: None,
        };
        args.write_args(&mut out)?;
    }
    m.finish_shared().map_err(|_| marshal())
}

/// A request to an object of the ORB's own server side, without the
/// network: marshalled as for the server, which runs it on the calling
/// thread (or queues it, as its thread policy says) and answers with a
/// whole reply message.
enum LocalCall {
    Locate(TargetAddress),
    Request {
        version: Version,
        header: RequestHeader,
        body: Body,
        code_sets: CodeSets,
        timeout: Option<Duration>,
    },
}

/// The answer of the server side to a [`LocalCall`].
enum LocalAnswer {
    Located(bool),
    /// The reply message (none for a oneway request).
    Reply(Option<Vec<u8>>, CodeSets),
}

/// The [`LocalCall`] for `kind`, or the end of the attempt.
fn local_call<A: WriteArgs + ?Sized>(
    orb: &Orb,
    ior: &Ior,
    ep: &Endpoint,
    kind: &Kind<'_, A>,
    deadline: Option<Instant>,
    disposition: AddressingDisposition,
    contexts: &[ServiceContext],
) -> Result<LocalCall, Attempt> {
    let options = &orb.inner.options;
    let order = options.byte_order;
    let version = ep.version.min(options.max_giop_version);
    let target = target_address(ior, ep, version, disposition);
    let (code_sets, mut context) = match (&ep.code_sets, version >= Version::V1_1) {
        (Some(info), true) => match CodeSets::negotiate(info) {
            Ok(cs) => (cs, vec![cs.context().to_service_context(order)]),
            Err(e) => return Err(Attempt::Done(Err(e.into()))),
        },
        _ => (CodeSets::DEFAULT, Vec::new()),
    };
    context.extend_from_slice(contexts);
    let flags = flags_of(kind);
    let (operation, args) = match kind {
        Kind::Locate => return Ok(LocalCall::Locate(target)),
        Kind::Request {
            operation, args, ..
        } => (*operation, *args),
    };
    trace::debug!(
        "request {operation:?}{} to this ORB's own object (colocated)",
        OnewayNote(kind)
    );
    let header = request_header(0, flags, target, operation, context);
    let msg = match encode_request(version, order, &header, args, code_sets) {
        Ok(msg) => msg.into_vec(),
        Err(e) => return Err(Attempt::Done(Err(e))),
    };
    let Ok((_, Message::Request { header, body })) = decode_message(&msg) else {
        return Err(Attempt::Done(Err(local_internal())));
    };
    let timeout = deadline.map(|at| at.saturating_duration_since(Instant::now()));
    Ok(LocalCall::Request {
        version,
        header,
        body,
        code_sets,
        timeout,
    })
}

impl LocalCall {
    /// Runs the call on the calling thread.
    fn run(self, server: &Arc<Server>) -> Result<LocalAnswer, SystemException> {
        match self {
            LocalCall::Locate(target) => server.locate_local(&target).map(LocalAnswer::Located),
            LocalCall::Request {
                version,
                header,
                body,
                code_sets,
                timeout,
            } => server
                .call_local(version, header, body, code_sets, timeout)
                .map(|reply| LocalAnswer::Reply(reply, code_sets)),
        }
    }
}

fn local_outcome(
    orb: &Orb,
    answer: Result<LocalAnswer, SystemException>,
    reply_contexts: &mut Vec<ServiceContext>,
) -> Attempt {
    match answer {
        Ok(LocalAnswer::Located(here)) => Attempt::Done(Ok(Outcome::Located(here))),
        Ok(LocalAnswer::Reply(None, _)) => Attempt::Done(Ok(Outcome::Reply(None))),
        Ok(LocalAnswer::Reply(Some(reply), code_sets)) => match decode_message(&reply) {
            Ok((_, Message::Reply { header, body })) => {
                *reply_contexts = header.service_context;
                reply_outcome(orb, header.reply_status, body, code_sets)
            }
            _ => Attempt::Done(Err(local_internal())),
        },
        Err(e) => Attempt::Done(Err(e.into())),
    }
}

fn local_internal() -> Exception {
    sys(SystemExceptionKind::INTERNAL, 0, CompletionStatus::Maybe).into()
}

fn reply_outcome(orb: &Orb, status: ReplyStatus, body: Body, code_sets: CodeSets) -> Attempt {
    match status {
        ReplyStatus::NoException => Attempt::Done(Ok(Outcome::Reply(Some(Reply {
            body,
            code_sets,
            orb: orb.clone(),
        })))),
        ReplyStatus::UserException => {
            let reply = Reply {
                body,
                code_sets,
                orb: orb.clone(),
            };
            let id = reply.input().read_string();
            Attempt::Done(Err(match id {
                Ok(repository_id) => Exception::User(UserException {
                    repository_id,
                    reply,
                }),
                Err(e) => Exception::System(e),
            }))
        }
        ReplyStatus::SystemException => {
            let mut dec = body.decoder();
            Attempt::Done(Err(match SystemExceptionBody::decode(&mut dec) {
                Ok(e) => Exception::System(e.into()),
                Err(e) => Exception::System(marshal(e)),
            }))
        }
        ReplyStatus::LocationForward | ReplyStatus::LocationForwardPerm => forward(&body),
        ReplyStatus::NeedsAddressingMode => addressing(&body),
    }
}

fn locate_outcome(status: LocateStatus, body: &Body) -> Attempt {
    match status {
        LocateStatus::ObjectHere => Attempt::Done(Ok(Outcome::Located(true))),
        LocateStatus::UnknownObject => Attempt::Done(Ok(Outcome::Located(false))),
        LocateStatus::ObjectForward | LocateStatus::ObjectForwardPerm => forward(body),
        LocateStatus::LocSystemException => {
            let mut dec = body.decoder();
            Attempt::Done(Err(match SystemExceptionBody::decode(&mut dec) {
                Ok(e) => Exception::System(e.into()),
                Err(e) => Exception::System(marshal(e)),
            }))
        }
        LocateStatus::LocNeedsAddressingMode => addressing(body),
    }
}

fn forward(body: &Body) -> Attempt {
    let mut dec = body.decoder();
    match Ior::decode(&mut dec) {
        Ok(ior) if !ior.is_nil() => Attempt::Forward(ior),
        Ok(_) => Attempt::Done(Err(sys(
            SystemExceptionKind::INV_OBJREF,
            0,
            CompletionStatus::No,
        )
        .into())),
        Err(e) => Attempt::Done(Err(Exception::System(marshal(e)))),
    }
}

fn addressing(body: &Body) -> Attempt {
    let mut dec = body.decoder();
    match dec
        .read_i16()
        .ok()
        .and_then(|d| AddressingDisposition::from_i16(d).ok())
    {
        Some(d) => Attempt::Addressing(d),
        None => Attempt::Done(Err(sys(
            SystemExceptionKind::MARSHAL,
            0,
            CompletionStatus::No,
        )
        .into())),
    }
}