Skip to main content

rustorb_core/
object.rs

1use std::fmt;
2use std::future::Future;
3use std::sync::atomic::{AtomicU64, Ordering};
4use std::sync::{Arc, Mutex};
5use std::time::{Duration, Instant};
6
7use rustorb_cdr::CdrDecode;
8use rustorb_giop::{
9    AddressingDisposition, AlternateIiopAddress, Body, CancelRequestHeader, CodeSetComponentInfo,
10    Ior, LocateRequestHeader, LocateStatus, Message, MessageEncoder, OutMessage, ReplyStatus,
11    RequestHeader, ServiceContext, SslSecTrans, SystemExceptionBody, TAG_INTERNET_IOP,
12    TAG_MULTIPLE_COMPONENTS, TargetAddress, Version, component_tag, decode_message, response_flags,
13};
14
15use crate::connection::{Closed, Connection, SendError};
16use crate::pi::{self, ClientEnding, ClientRequest, ClientRequestInfo, DiiParams, Interceptors};
17use crate::server::Server;
18use crate::stream::{InStream, OutStream, marshal};
19use crate::trace;
20use crate::{
21    CodeSets, CompletionStatus, Exception, Orb, SystemException, SystemExceptionKind,
22    UserException, minor, timeout,
23};
24
25/// A reference to a CORBA object, from an IOR.
26///
27/// Invocations try each IIOP profile of the IOR, and each address in it,
28/// until one can be reached. An address of the ORB's own server side is
29/// not reached through the network: the request is dispatched on the
30/// calling thread. A `LOCATION_FORWARD` reply makes the
31/// reference use the forwarded IOR from then on (shared by its clones);
32/// when the forwarded object cannot be reached any more, the original IOR
33/// is used again.
34#[derive(Clone)]
35pub struct ObjectRef {
36    orb: Orb,
37    ior: Arc<Ior>,
38    forward: Arc<Mutex<Option<Arc<Ior>>>>,
39    /// [`ObjectRef::set_call_timeout`], shared by clones.
40    call_timeout: Arc<AtomicU64>,
41}
42
43impl fmt::Debug for ObjectRef {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        f.debug_struct("ObjectRef")
46            .field("type_id", &self.ior.type_id)
47            .field("profiles", &self.ior.profiles.len())
48            .finish_non_exhaustive()
49    }
50}
51
52/// `==` is [`ObjectRef::is_equivalent`].
53impl PartialEq for ObjectRef {
54    fn eq(&self, other: &ObjectRef) -> bool {
55        self.is_equivalent(other)
56    }
57}
58
59type ArgsFn<'a> = dyn Fn(&mut OutStream<'_>) -> Result<(), SystemException> + 'a;
60
61/// The arguments of an [`AsyncRequest`], whose future may move between
62/// threads.
63type SendArgsFn<'a> = dyn Fn(&mut OutStream<'_>) -> Result<(), SystemException> + Send + Sync + 'a;
64
65/// Writes the `in` and `inout` arguments of a request: either kind of
66/// argument function.
67trait WriteArgs {
68    fn write_args(&self, out: &mut OutStream<'_>) -> Result<(), SystemException>;
69}
70
71impl<F> WriteArgs for F
72where
73    F: Fn(&mut OutStream<'_>) -> Result<(), SystemException> + ?Sized,
74{
75    fn write_args(&self, out: &mut OutStream<'_>) -> Result<(), SystemException> {
76        self(out)
77    }
78}
79
80impl ObjectRef {
81    pub(crate) fn new(orb: Orb, ior: Ior) -> ObjectRef {
82        ObjectRef {
83            orb,
84            ior: Arc::new(ior),
85            forward: Arc::new(Mutex::new(None)),
86            call_timeout: Arc::new(AtomicU64::new(timeout::UNSET)),
87        }
88    }
89
90    /// A reference to the same object (sharing its forward) whose call
91    /// timeout is its own, starting from this one's.
92    pub(crate) fn with_own_settings(&self) -> ObjectRef {
93        ObjectRef {
94            call_timeout: Arc::new(AtomicU64::new(self.call_timeout.load(Ordering::Relaxed))),
95            ..self.clone()
96        }
97    }
98
99    pub(crate) fn ior_arc(&self) -> Arc<Ior> {
100        Arc::clone(&self.ior)
101    }
102
103    /// The IOR the reference was created from.
104    pub fn ior(&self) -> &Ior {
105        &self.ior
106    }
107
108    /// The IOR invocations currently go to: the last forwarded one, or the
109    /// original.
110    pub fn effective_ior(&self) -> Ior {
111        (*self.current_target()).clone()
112    }
113
114    /// The repository id in the IOR, which may be empty.
115    pub fn type_id(&self) -> &str {
116        &self.ior.type_id
117    }
118
119    /// The ORB the reference belongs to.
120    pub fn orb(&self) -> &Orb {
121        &self.orb
122    }
123
124    /// `CORBA::Object::_is_equivalent`: whether both references have the
125    /// same profiles, so they certainly denote the same object. `false`
126    /// does not mean they are different objects.
127    pub fn is_equivalent(&self, other: &ObjectRef) -> bool {
128        Arc::ptr_eq(&self.ior, &other.ior) || self.ior.profiles == other.ior.profiles
129    }
130
131    /// Starts a request for `operation`.
132    pub fn request<'a>(&'a self, operation: &str) -> Request<'a> {
133        Request {
134            obj: self,
135            operation: operation.to_owned(),
136            args: None,
137            timeout: None,
138            dii: None,
139        }
140    }
141
142    /// Starts a request for `operation` that runs as a future
143    /// ([`AsyncRequest`]).
144    pub fn request_async<'a>(&'a self, operation: &str) -> AsyncRequest<'a> {
145        AsyncRequest {
146            obj: self,
147            operation: operation.to_owned(),
148            args: None,
149            timeout: None,
150            dii: None,
151            slots: None,
152        }
153    }
154
155    /// The slots of the calling thread for a request on this reference,
156    /// if its ORB has client interceptors.
157    pub(crate) fn request_slots(&self) -> Option<Vec<crate::Any>> {
158        request_slots(self)
159    }
160
161    /// Sets how long calls on this reference and its clones wait for a
162    /// reply: `Some(t)` (where `t` is `None` for no limit) overrides the
163    /// ORB's [`call_timeout`](Orb::call_timeout) and the calling thread's
164    /// ([`set_thread_call_timeout`](crate::set_thread_call_timeout)), and
165    /// `None` unsets it. Like omniORB's `setClientCallTimeout(obj,
166    /// millisecs)`. References made from the same IOR by
167    /// [`Orb::string_to_object`] do not share it.
168    pub fn set_call_timeout(&self, timeout: Option<Option<Duration>>) {
169        let v = timeout.map_or(timeout::UNSET, timeout::encode);
170        self.call_timeout.store(v, Ordering::Relaxed);
171    }
172
173    /// The setting of [`set_call_timeout`](ObjectRef::set_call_timeout).
174    pub fn call_timeout(&self) -> Option<Option<Duration>> {
175        match self.call_timeout.load(Ordering::Relaxed) {
176            timeout::UNSET => None,
177            v => Some(timeout::decode(v)),
178        }
179    }
180
181    /// The timeout of a call on this reference from the calling thread:
182    /// the reference's, else the thread's, else the ORB's (the order
183    /// omniORB uses).
184    pub(crate) fn effective_timeout(&self) -> Option<Duration> {
185        self.call_timeout()
186            .or_else(timeout::thread_call_timeout)
187            .unwrap_or_else(|| self.orb.call_timeout())
188    }
189
190    /// `CORBA::Object::_is_a`.
191    pub fn is_a(&self, repository_id: &str) -> Result<bool, Exception> {
192        let reply = self
193            .request("_is_a")
194            .args(|out| out.write_string(repository_id))
195            .invoke()?;
196        Ok(reply.input().read::<bool>()?)
197    }
198
199    /// `CORBA::Object::_non_existent`. `OBJECT_NOT_EXIST` from the server
200    /// counts as `true`.
201    pub fn non_existent(&self) -> Result<bool, Exception> {
202        match self.request("_non_existent").invoke() {
203            Ok(reply) => Ok(reply.input().read::<bool>()?),
204            Err(Exception::System(e)) if e.is(SystemExceptionKind::OBJECT_NOT_EXIST) => Ok(true),
205            Err(e) => Err(e),
206        }
207    }
208
209    /// The async form of [`is_a`](ObjectRef::is_a).
210    pub async fn is_a_async(&self, repository_id: &str) -> Result<bool, Exception> {
211        let id = repository_id.to_owned();
212        let reply = self
213            .request_async("_is_a")
214            .args(move |out| out.write_string(&id))
215            .invoke()
216            .await?;
217        Ok(reply.input().read::<bool>()?)
218    }
219
220    /// The async form of [`non_existent`](ObjectRef::non_existent).
221    pub async fn non_existent_async(&self) -> Result<bool, Exception> {
222        match self.request_async("_non_existent").invoke().await {
223            Ok(reply) => Ok(reply.input().read::<bool>()?),
224            Err(Exception::System(e)) if e.is(SystemExceptionKind::OBJECT_NOT_EXIST) => Ok(true),
225            Err(e) => Err(e),
226        }
227    }
228
229    /// Sends a `LocateRequest`, following forwards. Returns whether the
230    /// server has the object (`OBJECT_HERE`) or not (`UNKNOWN_OBJECT`).
231    pub fn locate(&self) -> Result<bool, Exception> {
232        let kind = Kind::<ArgsFn<'_>>::Locate;
233        let outcome = invoke(self, &kind, self.effective_timeout(), None)?;
234        match outcome {
235            Outcome::Located(here) => Ok(here),
236            Outcome::Reply(_) => unreachable!("a locate request gives a locate outcome"),
237        }
238    }
239
240    /// The async form of [`locate`](ObjectRef::locate).
241    pub fn locate_async(&self) -> impl Future<Output = Result<bool, Exception>> + Send + '_ {
242        let timeout = self.effective_timeout();
243        self.orb.in_runtime(async move {
244            let kind = Kind::<SendArgsFn<'_>>::Locate;
245            match invoke_async(self, &kind, timeout, None).await? {
246                Outcome::Located(here) => Ok(here),
247                Outcome::Reply(_) => unreachable!("a locate request gives a locate outcome"),
248            }
249        })
250    }
251
252    /// `CORBA::Object::validate_connection`: binds the reference with a
253    /// `LocateRequest` (following forwards) and returns true. rustorb has
254    /// no policy that can forbid a call, so it never returns false. The
255    /// failure to bind raises its exception (`TRANSIENT`, `TIMEOUT`...),
256    /// and an object the server does not have `OBJECT_NOT_EXIST`.
257    pub fn validate_connection(&self) -> Result<bool, Exception> {
258        if self.locate()? {
259            Ok(true)
260        } else {
261            Err(SystemException::new(
262                SystemExceptionKind::OBJECT_NOT_EXIST,
263                minor::NO_SUCH_OBJECT,
264                CompletionStatus::No,
265            )
266            .into())
267        }
268    }
269
270    fn current_target(&self) -> Arc<Ior> {
271        match &*self.forward.lock().unwrap() {
272            Some(ior) => Arc::clone(ior),
273            None => Arc::clone(&self.ior),
274        }
275    }
276
277    fn set_forward(&self, ior: Option<Arc<Ior>>) {
278        *self.forward.lock().unwrap() = ior;
279    }
280}
281
282/// A request being built: the operation, its arguments, and a timeout.
283pub struct Request<'a> {
284    obj: &'a ObjectRef,
285    operation: String,
286    args: Option<Box<ArgsFn<'a>>>,
287    /// Set by [`Request::timeout`].
288    timeout: Option<Option<Duration>>,
289    /// The parameters of a DII request, for the interceptors.
290    dii: Option<DiiParams>,
291}
292
293impl fmt::Debug for Request<'_> {
294    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
295        f.debug_struct("Request")
296            .field("operation", &self.operation)
297            .field("timeout", &self.timeout)
298            .finish_non_exhaustive()
299    }
300}
301
302impl<'a> Request<'a> {
303    /// Sets the function that writes the `in` and `inout` arguments. It may
304    /// run more than once, when the request is forwarded or retried.
305    pub fn args<F>(mut self, f: F) -> Request<'a>
306    where
307        F: Fn(&mut OutStream<'_>) -> Result<(), SystemException> + 'a,
308    {
309        self.args = Some(Box::new(f));
310        self
311    }
312
313    /// Sets how long this request waits for a reply (`None`: no limit),
314    /// overriding the timeouts of the thread, the reference and the ORB
315    /// (see [`Orb::set_call_timeout`]).
316    pub fn timeout(mut self, timeout: Option<Duration>) -> Request<'a> {
317        self.timeout = Some(timeout);
318        self
319    }
320
321    fn effective_timeout(&self) -> Option<Duration> {
322        self.timeout.unwrap_or_else(|| self.obj.effective_timeout())
323    }
324
325    /// The DII parameters, for the interceptors.
326    pub(crate) fn dii(mut self, params: DiiParams) -> Request<'a> {
327        self.dii = Some(params);
328        self
329    }
330
331    /// Sends the request and waits for the reply.
332    pub fn invoke(self) -> Result<Reply, Exception> {
333        let kind = Kind::Request {
334            operation: &self.operation,
335            args: self.args.as_deref(),
336            response: true,
337            dii: self.dii.as_ref(),
338        };
339        let slots = request_slots(self.obj);
340        match invoke(self.obj, &kind, self.effective_timeout(), slots)? {
341            Outcome::Reply(Some(reply)) => Ok(reply),
342            _ => unreachable!("a two-way request gives a reply"),
343        }
344    }
345
346    /// Sends the request as a oneway call: returns once the message is
347    /// written, with no reply.
348    pub fn send_oneway(self) -> Result<(), SystemException> {
349        let kind = Kind::Request {
350            operation: &self.operation,
351            args: self.args.as_deref(),
352            response: false,
353            dii: self.dii.as_ref(),
354        };
355        let slots = request_slots(self.obj);
356        match invoke(self.obj, &kind, self.effective_timeout(), slots) {
357            Ok(_) => Ok(()),
358            Err(Exception::System(e)) => Err(e),
359            Err(Exception::User(_)) => unreachable!("a oneway request has no reply"),
360        }
361    }
362}
363
364/// A request that runs as a future: [`Request`] for async code.
365///
366/// The future can be polled by any executor, or none in particular: the
367/// sockets and timers of the call belong to the ORB's runtime. It does not
368/// block the thread that polls it, except that a call to an object of the
369/// ORB's own server side runs the servant on an upcall thread and waits
370/// for it without blocking. The timeout is taken when
371/// [`invoke`](AsyncRequest::invoke) is called, so a timeout of the calling
372/// thread ([`set_thread_call_timeout`](crate::set_thread_call_timeout))
373/// counts as it does for [`Request`].
374pub struct AsyncRequest<'a> {
375    obj: &'a ObjectRef,
376    operation: String,
377    args: Option<Box<SendArgsFn<'a>>>,
378    timeout: Option<Option<Duration>>,
379    dii: Option<DiiParams>,
380    /// The request scope slots, when taken on another thread.
381    slots: Option<Option<Vec<crate::Any>>>,
382}
383
384impl fmt::Debug for AsyncRequest<'_> {
385    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
386        f.debug_struct("AsyncRequest")
387            .field("operation", &self.operation)
388            .field("timeout", &self.timeout)
389            .finish_non_exhaustive()
390    }
391}
392
393impl<'a> AsyncRequest<'a> {
394    /// [`Request::args`]; the function must be `Send` and `Sync`, as the
395    /// future may move between threads.
396    pub fn args<F>(mut self, f: F) -> AsyncRequest<'a>
397    where
398        F: Fn(&mut OutStream<'_>) -> Result<(), SystemException> + Send + Sync + 'a,
399    {
400        self.args = Some(Box::new(f));
401        self
402    }
403
404    /// [`Request::timeout`].
405    pub fn timeout(mut self, timeout: Option<Duration>) -> AsyncRequest<'a> {
406        self.timeout = Some(timeout);
407        self
408    }
409
410    /// The DII parameters, for the interceptors.
411    pub(crate) fn dii(mut self, params: DiiParams) -> AsyncRequest<'a> {
412        self.dii = Some(params);
413        self
414    }
415
416    /// The request scope slots, taken by
417    /// [`ObjectRef::request_slots`] on the thread that made the call.
418    pub(crate) fn slots(mut self, slots: Option<Vec<crate::Any>>) -> AsyncRequest<'a> {
419        self.slots = Some(slots);
420        self
421    }
422
423    /// Sends the request; the future resolves to the reply.
424    pub fn invoke(mut self) -> impl Future<Output = Result<Reply, Exception>> + Send + 'a {
425        let timeout = self.timeout.unwrap_or_else(|| self.obj.effective_timeout());
426        // The slots of the thread that makes the call.
427        let slots = self.slots.take().unwrap_or_else(|| request_slots(self.obj));
428        let orb = self.obj.orb.clone();
429        orb.in_runtime(async move {
430            let kind = Kind::Request {
431                operation: &self.operation,
432                args: self.args.as_deref(),
433                response: true,
434                dii: self.dii.as_ref(),
435            };
436            match invoke_async(self.obj, &kind, timeout, slots).await? {
437                Outcome::Reply(Some(reply)) => Ok(reply),
438                _ => unreachable!("a two-way request gives a reply"),
439            }
440        })
441    }
442
443    /// Sends the request as a oneway call; the future resolves once the
444    /// message is written.
445    pub fn send_oneway(mut self) -> impl Future<Output = Result<(), SystemException>> + Send + 'a {
446        let timeout = self.timeout.unwrap_or_else(|| self.obj.effective_timeout());
447        let slots = self.slots.take().unwrap_or_else(|| request_slots(self.obj));
448        let orb = self.obj.orb.clone();
449        orb.in_runtime(async move {
450            let kind = Kind::Request {
451                operation: &self.operation,
452                args: self.args.as_deref(),
453                response: false,
454                dii: self.dii.as_ref(),
455            };
456            match invoke_async(self.obj, &kind, timeout, slots).await {
457                Ok(_) => Ok(()),
458                Err(Exception::System(e)) => Err(e),
459                Err(Exception::User(_)) => unreachable!("a oneway request has no reply"),
460            }
461        })
462    }
463}
464
465/// A normal reply: the return value and the `out` and `inout` arguments.
466#[derive(Debug, Clone)]
467pub struct Reply {
468    body: Body,
469    code_sets: CodeSets,
470    orb: Orb,
471}
472
473impl Reply {
474    /// A stream over the reply body.
475    pub fn input(&self) -> InStream<'_> {
476        InStream {
477            dec: self.body.decoder(),
478            code_sets: self.code_sets,
479            orb: Some(&self.orb),
480            completed: CompletionStatus::Yes,
481            wchar_needs_code_set: false,
482            values: Vec::new(),
483            typed_values: Vec::new(),
484            custom_items: None,
485            body: Some(&self.body),
486        }
487    }
488
489    /// The raw reply body.
490    pub fn body(&self) -> &Body {
491        &self.body
492    }
493}
494
495enum Kind<'k, A: ?Sized = ArgsFn<'k>> {
496    Request {
497        operation: &'k str,
498        args: Option<&'k A>,
499        response: bool,
500        dii: Option<&'k DiiParams>,
501    },
502    Locate,
503}
504
505enum Outcome {
506    Reply(Option<Reply>),
507    Located(bool),
508}
509
510enum Attempt {
511    Done(Result<Outcome, Exception>),
512    /// The request was not processed here; try the next address.
513    NotSent(SystemException),
514    Forward(Ior),
515    Addressing(AddressingDisposition),
516    /// The server closed the connection before it processed the request:
517    /// send it again to the same address. Only with client interceptors,
518    /// which see each sending; without, [`attempt`] sends it again itself.
519    Resend,
520}
521
522/// One address an object can be reached at.
523struct Endpoint {
524    profile_index: usize,
525    version: Version,
526    host: String,
527    port: u16,
528    /// A TLS endpoint (from `TAG_SSL_SEC_TRANS`).
529    tls: bool,
530    object_key: Vec<u8>,
531    code_sets: Option<CodeSetComponentInfo>,
532}
533
534/// Every IIOP address in `ior` this ORB can use, in order: for each
535/// profile, its TLS endpoint if it has one and the ORB can use TLS
536/// (docs/ssliop.md), else its own address and its alternate addresses.
537/// A port of 0 is no address.
538fn endpoints(ior: &Ior, can_tls: bool) -> Vec<Endpoint> {
539    let shared: Vec<_> = ior
540        .profiles
541        .iter()
542        .filter(|p| p.tag == TAG_MULTIPLE_COMPONENTS)
543        .filter_map(|p| p.multiple_components().ok())
544        .flatten()
545        .collect();
546    let mut out = Vec::new();
547    for (index, profile) in ior.profiles.iter().enumerate() {
548        if profile.tag != TAG_INTERNET_IOP {
549            continue;
550        }
551        let Ok(iiop) = profile.iiop() else { continue };
552        if iiop.version.major != 1 {
553            continue;
554        }
555        // IIOP 1.0 profiles have no components of their own; they use
556        // those of the TAG_MULTIPLE_COMPONENTS profile.
557        let components = if iiop.version.minor == 0 {
558            &shared
559        } else {
560            &iiop.components
561        };
562        let code_sets = components
563            .iter()
564            .find(|c| c.tag == component_tag::CODE_SETS)
565            .and_then(|c| CodeSetComponentInfo::from_component(c).ok());
566        let ssl = components
567            .iter()
568            .find(|c| c.tag == component_tag::SSL_SEC_TRANS)
569            .and_then(|c| SslSecTrans::from_component(c).ok());
570        let mut addrs = Vec::new();
571        if let (Some(ssl), true) = (ssl, can_tls) {
572            // Not unprotected instead, should the TLS endpoint fail.
573            addrs.push((iiop.host.clone(), ssl.port, true));
574        } else {
575            addrs.push((iiop.host.clone(), iiop.port, false));
576            addrs.extend(
577                components
578                    .iter()
579                    .filter(|c| c.tag == component_tag::ALTERNATE_IIOP_ADDRESS)
580                    .filter_map(|c| AlternateIiopAddress::from_component(c).ok())
581                    .map(|a| (a.host, a.port, false)),
582            );
583        }
584        for (host, port, tls) in addrs {
585            if port == 0 {
586                continue;
587            }
588            out.push(Endpoint {
589                profile_index: index,
590                version: iiop.version,
591                host,
592                port,
593                tls,
594                object_key: iiop.object_key.clone(),
595                code_sets: code_sets.clone(),
596            });
597        }
598    }
599    out
600}
601
602fn sys(kind: SystemExceptionKind, minor: u32, completed: CompletionStatus) -> SystemException {
603    SystemException::new(kind, minor, completed)
604}
605
606/// The walk of a call over the addresses of its target, the forwards and
607/// the addressing modes; the same for blocking and async calls.
608struct Walk<'o> {
609    obj: &'o ObjectRef,
610    max_hops: u32,
611    hops: u32,
612    ior: Arc<Ior>,
613    disposition: AddressingDisposition,
614    endpoints: std::vec::IntoIter<Endpoint>,
615    /// Why the addresses tried so far could not be used.
616    last: SystemException,
617    /// The target was just set (and is still to be checked for nil).
618    fresh: bool,
619}
620
621enum Step {
622    Try(Endpoint),
623    Done(Result<Outcome, Exception>),
624}
625
626impl<'o> Walk<'o> {
627    fn new(obj: &'o ObjectRef) -> Walk<'o> {
628        let mut walk = Walk {
629            obj,
630            max_hops: obj.orb.inner.options.max_forwards,
631            hops: 0,
632            ior: obj.current_target(),
633            disposition: AddressingDisposition::Key,
634            endpoints: Vec::new().into_iter(),
635            last: no_usable_profile(),
636            fresh: true,
637        };
638        walk.retarget(Arc::clone(&walk.ior));
639        walk
640    }
641
642    fn retarget(&mut self, ior: Arc<Ior>) {
643        self.endpoints = endpoints(&ior, self.obj.orb.has_tls_client()).into_iter();
644        self.ior = ior;
645        self.last = no_usable_profile();
646        self.fresh = true;
647    }
648
649    /// The next address to try, or the end of the call.
650    fn next(&mut self) -> Step {
651        loop {
652            if std::mem::take(&mut self.fresh) && self.ior.is_nil() {
653                return Step::Done(Err(sys(
654                    SystemExceptionKind::INV_OBJREF,
655                    0,
656                    CompletionStatus::No,
657                )
658                .into()));
659            }
660            if let Some(ep) = self.endpoints.next() {
661                return Step::Try(ep);
662            }
663            // Nothing could be reached. A forwarded target falls back to
664            // the original reference.
665            if !Arc::ptr_eq(&self.ior, &self.obj.ior) {
666                self.hops += 1;
667                if self.hops <= self.max_hops {
668                    self.obj.set_forward(None);
669                    self.disposition = AddressingDisposition::Key;
670                    self.retarget(Arc::clone(&self.obj.ior));
671                    continue;
672                }
673            }
674            return Step::Done(Err(self.last.clone().into()));
675        }
676    }
677
678    /// Takes in the attempt at the address [`next`](Walk::next) gave:
679    /// `Some` ends the call.
680    fn record(&mut self, attempt: Attempt) -> Option<Result<Outcome, Exception>> {
681        match attempt {
682            Attempt::Done(result) => Some(result),
683            Attempt::NotSent(e) => {
684                self.last = e;
685                None
686            }
687            // The caller sends again; here only after too many tries.
688            Attempt::Resend => {
689                self.last = sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No);
690                None
691            }
692            Attempt::Forward(next) => {
693                trace::info!("LOCATION_FORWARD to {}", trace::IorSummary(&next));
694                self.hops += 1;
695                if self.hops > self.max_hops {
696                    return Some(Err(sys(
697                        SystemExceptionKind::TRANSIENT,
698                        0,
699                        CompletionStatus::No,
700                    )
701                    .into()));
702                }
703                let next = Arc::new(next);
704                self.obj.set_forward(Some(Arc::clone(&next)));
705                self.disposition = AddressingDisposition::Key;
706                self.retarget(next);
707                None
708            }
709            Attempt::Addressing(wanted) => {
710                trace::debug!("NEEDS_ADDRESSING_MODE: {wanted:?}");
711                self.hops += 1;
712                if self.hops > self.max_hops || wanted == self.disposition {
713                    return Some(Err(sys(
714                        SystemExceptionKind::MARSHAL,
715                        0,
716                        CompletionStatus::No,
717                    )
718                    .into()));
719                }
720                self.disposition = wanted;
721                self.retarget(Arc::clone(&self.ior));
722                None
723            }
724        }
725    }
726}
727
728fn no_usable_profile() -> SystemException {
729    sys(
730        SystemExceptionKind::TRANSIENT,
731        minor::NO_USABLE_PROFILE,
732        CompletionStatus::No,
733    )
734}
735
736/// The slots of the calling thread for a request on `obj`, if its ORB has
737/// client interceptors.
738fn request_slots(obj: &ObjectRef) -> Option<Vec<crate::Any>> {
739    obj.orb
740        .interceptors()
741        .filter(|pi| pi.has_client())
742        .map(|pi| pi::thread_slots(&pi))
743}
744
745/// The client interceptors of a call, with the request scope slots.
746struct ClientPi {
747    pi: Arc<Interceptors>,
748    slots: Vec<crate::Any>,
749}
750
751impl ClientPi {
752    fn new<A: ?Sized>(
753        obj: &ObjectRef,
754        kind: &Kind<'_, A>,
755        slots: Option<Vec<crate::Any>>,
756    ) -> Option<ClientPi> {
757        if !matches!(kind, Kind::Request { .. }) {
758            return None;
759        }
760        let slots = slots?;
761        let pi = obj.orb.interceptors().filter(|pi| pi.has_client())?;
762        Some(ClientPi { pi, slots })
763    }
764
765    /// The information of an attempt at `ep`, and `send_request`. `Err`
766    /// ends the attempt before anything is sent.
767    fn start<'i, A: ?Sized>(
768        &self,
769        obj: &'i ObjectRef,
770        kind: &Kind<'i, A>,
771        ior: &Arc<Ior>,
772        ep: &Endpoint,
773        timeout: Option<Duration>,
774    ) -> Result<ClientRequestInfo<'i>, Attempt> {
775        let Kind::Request {
776            operation,
777            response,
778            dii,
779            ..
780        } = *kind
781        else {
782            unreachable!("interceptors only see requests");
783        };
784        let info = ClientRequestInfo::new(
785            &self.pi,
786            ClientRequest {
787                operation,
788                response_expected: response,
789                target: obj,
790                effective: Arc::clone(ior),
791                profile_index: Some(ep.profile_index),
792                timeout,
793                slots: self.slots.clone(),
794                dii,
795            },
796        );
797        match pi::send_request(&self.pi, &info) {
798            Ok(()) => Ok(info),
799            Err(ending) => Err(from_ending(ending, None, None)),
800        }
801    }
802
803    /// Runs the ending points for `attempt`, and returns the attempt as
804    /// they leave it.
805    fn finish(
806        &self,
807        orb: &Orb,
808        info: &ClientRequestInfo<'_>,
809        attempt: Attempt,
810        reply_contexts: Vec<ServiceContext>,
811    ) -> Attempt {
812        info.set_reply_contexts(reply_contexts);
813        let mut not_sent = None;
814        let mut addressing = None;
815        let ending = match attempt {
816            Attempt::Done(Ok(Outcome::Reply(Some(reply)))) => ClientEnding::Reply(reply),
817            Attempt::Done(Ok(Outcome::Reply(None))) => ClientEnding::Oneway,
818            Attempt::Done(Ok(Outcome::Located(_))) => return attempt,
819            Attempt::Done(Err(e)) => ClientEnding::Exception(e),
820            Attempt::NotSent(e) => {
821                not_sent = Some(e.clone());
822                ClientEnding::Exception(Exception::System(e))
823            }
824            Attempt::Forward(ior) => ClientEnding::Forward(ObjectRef::new(orb.clone(), ior)),
825            Attempt::Addressing(d) => {
826                addressing = Some(d);
827                ClientEnding::Retry
828            }
829            Attempt::Resend => ClientEnding::Retry,
830        };
831        from_ending(pi::receive(&self.pi, info, ending), not_sent, addressing)
832    }
833}
834
835/// The attempt an interception ended with. An exception that is still the
836/// one of an attempt that sent nothing (`not_sent`) lets the call go on to
837/// the next address; a retry is the one the ORB was about to make.
838fn from_ending(
839    ending: ClientEnding,
840    not_sent: Option<SystemException>,
841    addressing: Option<AddressingDisposition>,
842) -> Attempt {
843    match ending {
844        ClientEnding::Reply(reply) => Attempt::Done(Ok(Outcome::Reply(Some(reply)))),
845        ClientEnding::Oneway => Attempt::Done(Ok(Outcome::Reply(None))),
846        ClientEnding::Exception(Exception::System(e)) if not_sent.as_ref() == Some(&e) => {
847            Attempt::NotSent(e)
848        }
849        ClientEnding::Exception(e) => Attempt::Done(Err(e)),
850        ClientEnding::Forward(to) => Attempt::Forward(to.ior().clone()),
851        ClientEnding::Retry => match addressing {
852            Some(d) => Attempt::Addressing(d),
853            None => Attempt::Resend,
854        },
855    }
856}
857
858fn invoke<A: WriteArgs + ?Sized>(
859    obj: &ObjectRef,
860    kind: &Kind<'_, A>,
861    timeout: Option<Duration>,
862    slots: Option<Vec<crate::Any>>,
863) -> Result<Outcome, Exception> {
864    let orb = &obj.orb;
865    orb.check_running()?;
866    // The timeout covers the whole call: connecting, forwards and the
867    // wait for the reply.
868    let deadline = timeout.map(|t| Instant::now() + t);
869    let pi = ClientPi::new(obj, kind, slots);
870    let mut walk = Walk::new(obj);
871    let mut again: Option<(Endpoint, usize)> = None;
872    loop {
873        let (ep, resent) = match again.take() {
874            Some(again) => again,
875            None => match walk.next() {
876                Step::Try(ep) => (ep, 0),
877                Step::Done(result) => return traced(kind, result),
878            },
879        };
880        let (ior, disposition) = (Arc::clone(&walk.ior), walk.disposition);
881        let info = match &pi {
882            Some(pi) => match pi.start(obj, kind, &ior, &ep, timeout) {
883                Ok(info) => Some(info),
884                Err(done) => {
885                    if let Some(result) = walk.record(done) {
886                        return traced(kind, result);
887                    }
888                    continue;
889                }
890            },
891            None => None,
892        };
893        let contexts = info
894            .as_ref()
895            .map(|i| i.take_request_contexts())
896            .unwrap_or_default();
897        let mut reply_contexts = Vec::new();
898        let mut attempt = match orb.local_server(&ep.host, ep.port, ep.tls) {
899            Some(server) => {
900                match local_call(orb, &ior, &ep, kind, deadline, disposition, &contexts) {
901                    Ok(call) => {
902                        let result = call.run(&server);
903                        local_outcome(orb, result, &mut reply_contexts)
904                    }
905                    Err(done) => done,
906                }
907            }
908            None => orb.block_on(attempt(
909                orb,
910                &ior,
911                &ep,
912                kind,
913                Exchange {
914                    deadline,
915                    disposition,
916                    own_thread: true,
917                    resend: info.is_none(),
918                    contexts: &contexts,
919                    reply_contexts: &mut reply_contexts,
920                },
921            ))?,
922        };
923        if let (Some(pi), Some(info)) = (&pi, &info) {
924            attempt = pi.finish(orb, info, attempt, reply_contexts);
925        }
926        if let Attempt::Resend = attempt {
927            if resent + 1 < CLOSED_ATTEMPTS {
928                again = Some((ep, resent + 1));
929                continue;
930            }
931            attempt =
932                Attempt::NotSent(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No));
933        }
934        if let Some(result) = walk.record(attempt) {
935            return traced(kind, result);
936        }
937    }
938}
939
940/// What one attempt sends besides the request, and what it brings back.
941struct Exchange<'x> {
942    deadline: Option<Instant>,
943    disposition: AddressingDisposition,
944    /// The caller is a thread of its own (a blocking call), which may
945    /// block reading the reply.
946    own_thread: bool,
947    /// Send the request again after a `CloseConnection` (no client
948    /// interceptors): else the attempt ends with [`Attempt::Resend`].
949    resend: bool,
950    /// The service contexts of the interceptors.
951    contexts: &'x [ServiceContext],
952    /// The service contexts of the reply.
953    reply_contexts: &'x mut Vec<ServiceContext>,
954}
955
956/// [`invoke`] as a future, run inside the ORB's runtime
957/// ([`Orb::in_runtime`]). A call to the ORB's own server side runs on an
958/// upcall thread.
959async fn invoke_async<A: WriteArgs + ?Sized>(
960    obj: &ObjectRef,
961    kind: &Kind<'_, A>,
962    timeout: Option<Duration>,
963    slots: Option<Vec<crate::Any>>,
964) -> Result<Outcome, Exception> {
965    let orb = &obj.orb;
966    orb.check_running()?;
967    let deadline = timeout.map(|t| Instant::now() + t);
968    let pi = ClientPi::new(obj, kind, slots);
969    let mut walk = Walk::new(obj);
970    let mut again: Option<(Endpoint, usize)> = None;
971    loop {
972        let (ep, resent) = match again.take() {
973            Some(again) => again,
974            None => match walk.next() {
975                Step::Try(ep) => (ep, 0),
976                Step::Done(result) => return traced(kind, result),
977            },
978        };
979        let (ior, disposition) = (Arc::clone(&walk.ior), walk.disposition);
980        let info = match &pi {
981            Some(pi) => match pi.start(obj, kind, &ior, &ep, timeout) {
982                Ok(info) => Some(info),
983                Err(done) => {
984                    if let Some(result) = walk.record(done) {
985                        return traced(kind, result);
986                    }
987                    continue;
988                }
989            },
990            None => None,
991        };
992        let contexts = info
993            .as_ref()
994            .map(|i| i.take_request_contexts())
995            .unwrap_or_default();
996        let mut reply_contexts = Vec::new();
997        let mut attempt = match orb.local_server(&ep.host, ep.port, ep.tls) {
998            Some(server) => {
999                match local_call(orb, &ior, &ep, kind, deadline, disposition, &contexts) {
1000                    Ok(call) => {
1001                        let (tx, rx) = tokio::sync::oneshot::channel();
1002                        let on_pool = Arc::clone(&server);
1003                        server.submit(Box::new(move || {
1004                            let _ = tx.send(call.run(&on_pool));
1005                        }));
1006                        // The pool is gone when the ORB is being destroyed.
1007                        let result = rx.await.unwrap_or_else(|_| {
1008                            Err(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No))
1009                        });
1010                        local_outcome(orb, result, &mut reply_contexts)
1011                    }
1012                    Err(done) => done,
1013                }
1014            }
1015            None => {
1016                attempt(
1017                    orb,
1018                    &ior,
1019                    &ep,
1020                    kind,
1021                    Exchange {
1022                        deadline,
1023                        disposition,
1024                        own_thread: false,
1025                        resend: info.is_none(),
1026                        contexts: &contexts,
1027                        reply_contexts: &mut reply_contexts,
1028                    },
1029                )
1030                .await
1031            }
1032        };
1033        if let (Some(pi), Some(info)) = (&pi, &info) {
1034            attempt = pi.finish(orb, info, attempt, reply_contexts);
1035        }
1036        if let Attempt::Resend = attempt {
1037            if resent + 1 < CLOSED_ATTEMPTS {
1038                again = Some((ep, resent + 1));
1039                continue;
1040            }
1041            attempt =
1042                Attempt::NotSent(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No));
1043        }
1044        if let Some(result) = walk.record(attempt) {
1045            return traced(kind, result);
1046        }
1047    }
1048}
1049
1050/// The end of a call, with a trace line for a system exception.
1051fn traced<A: WriteArgs + ?Sized>(
1052    kind: &Kind<'_, A>,
1053    result: Result<Outcome, Exception>,
1054) -> Result<Outcome, Exception> {
1055    if let Err(Exception::System(e)) = &result {
1056        trace::debug!("{} raised {e}", KindName(kind));
1057    }
1058    result
1059}
1060
1061/// What a call is in trace lines: `request "op"` or `LocateRequest`.
1062struct KindName<'a, 'k, A: ?Sized>(&'a Kind<'k, A>);
1063
1064impl<A: ?Sized> fmt::Display for KindName<'_, '_, A> {
1065    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1066        match self.0 {
1067            Kind::Request { operation, .. } => write!(f, "request {operation:?}"),
1068            Kind::Locate => f.write_str("LocateRequest"),
1069        }
1070    }
1071}
1072
1073/// How long a `CancelRequest` after a timeout may take to go out.
1074const CANCEL_SEND_TIME: Duration = Duration::from_millis(100);
1075
1076/// How many times one endpoint is tried when its connections close
1077/// before the reply: a request left without a reply by `CloseConnection`
1078/// was not processed, and a connection the server (or this ORB) chose to
1079/// close as idle may close under a request sent at the same moment.
1080const CLOSED_ATTEMPTS: usize = 4;
1081
1082/// Sends the request to one endpoint. A `CloseConnection` before the reply
1083/// means the server did not process it, so it is sent again on a new
1084/// connection, up to [`CLOSED_ATTEMPTS`] times in all.
1085///
1086/// With `own_thread`, the caller is a thread of its own (a blocking call),
1087/// which may block reading the reply.
1088async fn attempt<A: WriteArgs + ?Sized>(
1089    orb: &Orb,
1090    ior: &Ior,
1091    ep: &Endpoint,
1092    kind: &Kind<'_, A>,
1093    mut x: Exchange<'_>,
1094) -> Attempt {
1095    let deadline = x.deadline;
1096    let mut result = Attempt::NotSent(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No));
1097    for _ in 0..CLOSED_ATTEMPTS {
1098        let conn = match orb.connection(&ep.host, ep.port, ep.tls, deadline).await {
1099            Ok(conn) => conn,
1100            // Out of time: the other addresses are not tried.
1101            Err(e) if e.is(SystemExceptionKind::TIMEOUT) => return Attempt::Done(Err(e.into())),
1102            Err(e) => return Attempt::NotSent(e),
1103        };
1104        match attempt_on(orb, &conn, ior, ep, kind, &mut x).await {
1105            Ok(done) => return done,
1106            Err(Closed::Orderly) => {
1107                orb.discard(&conn);
1108                if !x.resend {
1109                    return Attempt::Resend;
1110                }
1111                result =
1112                    Attempt::NotSent(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No));
1113            }
1114            Err(Closed::Failed(_)) => {
1115                orb.discard(&conn);
1116                return Attempt::Done(Err(sys(
1117                    SystemExceptionKind::COMM_FAILURE,
1118                    0,
1119                    CompletionStatus::Maybe,
1120                )
1121                .into()));
1122            }
1123        }
1124    }
1125    result
1126}
1127
1128/// `Err(Closed::Orderly)` asks for a retry on a new connection;
1129/// `Err(Closed::Failed)` after the request was sent is `COMM_FAILURE`.
1130async fn attempt_on<A: WriteArgs + ?Sized>(
1131    orb: &Orb,
1132    conn: &Arc<Connection>,
1133    ior: &Ior,
1134    ep: &Endpoint,
1135    kind: &Kind<'_, A>,
1136    x: &mut Exchange<'_>,
1137) -> Result<Attempt, Closed> {
1138    let (deadline, disposition, own_thread) = (x.deadline, x.disposition, x.own_thread);
1139    let options = &orb.inner.options;
1140    let order = options.byte_order;
1141    let version = ep.version.min(options.max_giop_version);
1142    let target = target_address(ior, ep, version, disposition);
1143
1144    // Code sets: negotiated from the IOR for GIOP 1.1 and later, fixed for
1145    // the connection by its first request, and announced in every request.
1146    let (code_sets, context) = match (&ep.code_sets, version >= Version::V1_1) {
1147        (Some(info), true) => {
1148            let proposed = match conn.code_sets() {
1149                Some(cs) => cs,
1150                None => match CodeSets::negotiate(info) {
1151                    Ok(cs) => cs,
1152                    Err(e) => return Ok(Attempt::Done(Err(e.into()))),
1153                },
1154            };
1155            let cs = conn.claim_code_sets(proposed);
1156            (cs, vec![cs.context().to_service_context(order)])
1157        }
1158        _ => (CodeSets::DEFAULT, Vec::new()),
1159    };
1160    let mut context = context;
1161    context.extend_from_slice(x.contexts);
1162
1163    let request_id = conn.next_request_id();
1164    let response = match kind {
1165        Kind::Request { response, .. } => *response,
1166        Kind::Locate => true,
1167    };
1168    let msg = match kind {
1169        Kind::Request {
1170            operation,
1171            args,
1172            response,
1173            ..
1174        } => {
1175            let header = request_header(request_id, *response, target, operation, context);
1176            match encode_request(version, order, &header, *args, code_sets) {
1177                Ok(msg) if msg.len() > options.max_message_size => {
1178                    trace::warning!(
1179                        "request {operation:?} of {} bytes is over the largest GIOP message \
1180                         ({} bytes, -ORBgiopMaxMsgSize): not sent",
1181                        msg.len(),
1182                        options.max_message_size
1183                    );
1184                    return Ok(Attempt::Done(Err(sys(
1185                        SystemExceptionKind::MARSHAL,
1186                        0,
1187                        CompletionStatus::No,
1188                    )
1189                    .into())));
1190                }
1191                Ok(msg) if options.fragment_size > 0 => msg.fragment(options.fragment_size),
1192                Ok(msg) => msg,
1193                Err(e) => return Ok(Attempt::Done(Err(e))),
1194            }
1195        }
1196        Kind::Locate => match MessageEncoder::locate_request(
1197            version,
1198            order,
1199            &LocateRequestHeader { request_id, target },
1200        ) {
1201            Ok(msg) => msg.into(),
1202            Err(_) => {
1203                return Ok(Attempt::Done(Err(sys(
1204                    SystemExceptionKind::MARSHAL,
1205                    0,
1206                    CompletionStatus::No,
1207                )
1208                .into())));
1209            }
1210        },
1211    };
1212
1213    trace::debug!(
1214        "{} (id {request_id}{}) to {}:{}, GIOP {}.{}",
1215        KindName(kind),
1216        if response { "" } else { ", oneway" },
1217        ep.host,
1218        ep.port,
1219        version.major,
1220        version.minor
1221    );
1222    let rx = if response {
1223        match conn.expect_reply(request_id) {
1224            Ok(rx) => Some(rx),
1225            Err(Closed::Orderly) => return Err(Closed::Orderly),
1226            // The connection broke before anything was sent: not processed.
1227            Err(Closed::Failed(_)) => {
1228                orb.discard(conn);
1229                return Ok(Attempt::NotSent(sys(
1230                    SystemExceptionKind::COMM_FAILURE,
1231                    0,
1232                    CompletionStatus::No,
1233                )));
1234            }
1235        }
1236    } else {
1237        None
1238    };
1239    match conn.send(&msg, deadline).await {
1240        Ok(()) => {}
1241        // Out of time before the whole request went out (a peer that
1242        // stopped reading, say): the server did not get it.
1243        Err(SendError::TimedOut) => {
1244            conn.forget(request_id);
1245            if !conn.is_usable() {
1246                orb.discard(conn);
1247            }
1248            return Ok(Attempt::Done(Err(sys(
1249                SystemExceptionKind::TIMEOUT,
1250                0,
1251                CompletionStatus::No,
1252            )
1253            .into())));
1254        }
1255        // Chosen to close as idle just now: nothing was written.
1256        Err(SendError::Closing) => {
1257            conn.forget(request_id);
1258            return Err(Closed::Orderly);
1259        }
1260        Err(SendError::Failed) => {
1261            conn.forget(request_id);
1262            orb.discard(conn);
1263            return Ok(Attempt::NotSent(sys(
1264                SystemExceptionKind::COMM_FAILURE,
1265                0,
1266                CompletionStatus::No,
1267            )));
1268        }
1269    }
1270    let Some(rx) = rx else {
1271        return Ok(Attempt::Done(Ok(Outcome::Reply(None))));
1272    };
1273
1274    // A blocking call runs on the caller's own thread (`Orb::block_on`),
1275    // which may block reading the reply.
1276    let here = if own_thread {
1277        conn.read_reply_here(request_id, deadline)
1278    } else {
1279        None
1280    };
1281    let delivered = match here {
1282        Some(Some(message)) => Some(Ok(Ok(message))),
1283        Some(None) => None,
1284        None => match deadline {
1285            Some(at) => tokio::time::timeout_at(at.into(), rx).await.ok(),
1286            None => Some(rx.await),
1287        },
1288    };
1289    let delivered = match delivered {
1290        Some(delivered) => delivered,
1291        None => {
1292            trace::debug!("{} (id {request_id}) timed out", KindName(kind));
1293            conn.forget(request_id);
1294            if let Ok(cancel) =
1295                MessageEncoder::cancel_request(version, order, &CancelRequestHeader { request_id })
1296            {
1297                // The caller is out of time already, and the connection
1298                // may be the reason: a short wait at most.
1299                let at = Instant::now() + CANCEL_SEND_TIME;
1300                let _ = conn.send(&cancel.into(), Some(at)).await;
1301            }
1302            return Ok(Attempt::Done(Err(sys(
1303                SystemExceptionKind::TIMEOUT,
1304                0,
1305                CompletionStatus::Maybe,
1306            )
1307            .into())));
1308        }
1309    };
1310    let message = match delivered {
1311        Ok(Ok(message)) => message,
1312        Ok(Err(closed)) => return Err(closed),
1313        Err(_) => return Err(Closed::Failed("reply channel dropped".into())),
1314    };
1315    Ok(match message {
1316        Message::Reply { header, body } => {
1317            if !matches!(kind, Kind::Request { .. }) {
1318                return Err(Closed::Failed("Reply to a LocateRequest".into()));
1319            }
1320            *x.reply_contexts = header.service_context;
1321            trace::debug!(
1322                "reply to {} (id {request_id}): {:?}",
1323                KindName(kind),
1324                header.reply_status
1325            );
1326            reply_outcome(orb, header.reply_status, body, code_sets)
1327        }
1328        Message::LocateReply { header, body } => {
1329            if !matches!(kind, Kind::Locate) {
1330                return Err(Closed::Failed("LocateReply to a Request".into()));
1331            }
1332            trace::debug!("LocateReply (id {request_id}): {:?}", header.locate_status);
1333            locate_outcome(header.locate_status, &body)
1334        }
1335        _ => return Err(Closed::Failed("unexpected message".into())),
1336    })
1337}
1338
1339/// How a request names its target, in the addressing disposition the
1340/// server asked for (GIOP 1.2), or by object key.
1341fn target_address(
1342    ior: &Ior,
1343    ep: &Endpoint,
1344    version: Version,
1345    disposition: AddressingDisposition,
1346) -> TargetAddress {
1347    if version < Version::V1_2 {
1348        return TargetAddress::Key(ep.object_key.clone());
1349    }
1350    match disposition {
1351        AddressingDisposition::Key => TargetAddress::Key(ep.object_key.clone()),
1352        AddressingDisposition::Profile => {
1353            TargetAddress::Profile(ior.profiles[ep.profile_index].clone())
1354        }
1355        AddressingDisposition::Reference => TargetAddress::Reference {
1356            selected_profile_index: ep.profile_index as u32,
1357            ior: ior.clone(),
1358        },
1359    }
1360}
1361
1362fn request_header(
1363    request_id: u32,
1364    response: bool,
1365    target: TargetAddress,
1366    operation: &str,
1367    service_context: Vec<rustorb_giop::ServiceContext>,
1368) -> RequestHeader {
1369    RequestHeader {
1370        request_id,
1371        response_flags: if response {
1372            response_flags::SYNC_WITH_TARGET
1373        } else {
1374            response_flags::NONE
1375        },
1376        target,
1377        operation: operation.to_owned(),
1378        service_context,
1379        requesting_principal: Vec::new(),
1380    }
1381}
1382
1383/// The whole `Request` message, with the arguments `args` writes.
1384fn encode_request<A: WriteArgs + ?Sized>(
1385    version: Version,
1386    order: rustorb_cdr::ByteOrder,
1387    header: &RequestHeader,
1388    args: Option<&A>,
1389    code_sets: CodeSets,
1390) -> Result<OutMessage, Exception> {
1391    let marshal = || sys(SystemExceptionKind::MARSHAL, 0, CompletionStatus::No).into();
1392    let mut m = MessageEncoder::request(version, order, header).map_err(|_| marshal())?;
1393    if let Some(args) = args {
1394        let mut out = OutStream {
1395            enc: m.body(),
1396            code_sets,
1397            orb: None,
1398        };
1399        args.write_args(&mut out)?;
1400    }
1401    m.finish_shared().map_err(|_| marshal())
1402}
1403
1404/// A request to an object of the ORB's own server side, without the
1405/// network: marshalled as for the server, which runs it on the calling
1406/// thread (or queues it, as its thread policy says) and answers with a
1407/// whole reply message.
1408enum LocalCall {
1409    Locate(TargetAddress),
1410    Request {
1411        version: Version,
1412        header: RequestHeader,
1413        body: Body,
1414        code_sets: CodeSets,
1415        timeout: Option<Duration>,
1416    },
1417}
1418
1419/// The answer of the server side to a [`LocalCall`].
1420enum LocalAnswer {
1421    Located(bool),
1422    /// The reply message (none for a oneway request).
1423    Reply(Option<Vec<u8>>, CodeSets),
1424}
1425
1426/// The [`LocalCall`] for `kind`, or the end of the attempt.
1427fn local_call<A: WriteArgs + ?Sized>(
1428    orb: &Orb,
1429    ior: &Ior,
1430    ep: &Endpoint,
1431    kind: &Kind<'_, A>,
1432    deadline: Option<Instant>,
1433    disposition: AddressingDisposition,
1434    contexts: &[ServiceContext],
1435) -> Result<LocalCall, Attempt> {
1436    let options = &orb.inner.options;
1437    let order = options.byte_order;
1438    let version = ep.version.min(options.max_giop_version);
1439    let target = target_address(ior, ep, version, disposition);
1440    let (code_sets, mut context) = match (&ep.code_sets, version >= Version::V1_1) {
1441        (Some(info), true) => match CodeSets::negotiate(info) {
1442            Ok(cs) => (cs, vec![cs.context().to_service_context(order)]),
1443            Err(e) => return Err(Attempt::Done(Err(e.into()))),
1444        },
1445        _ => (CodeSets::DEFAULT, Vec::new()),
1446    };
1447    context.extend_from_slice(contexts);
1448    let (operation, args, response) = match kind {
1449        Kind::Locate => return Ok(LocalCall::Locate(target)),
1450        Kind::Request {
1451            operation,
1452            args,
1453            response,
1454            ..
1455        } => (*operation, *args, *response),
1456    };
1457    trace::debug!(
1458        "request {operation:?}{} to this ORB's own object (colocated)",
1459        if response { "" } else { ", oneway" }
1460    );
1461    let header = request_header(0, response, target, operation, context);
1462    let msg = match encode_request(version, order, &header, args, code_sets) {
1463        Ok(msg) => msg.into_vec(),
1464        Err(e) => return Err(Attempt::Done(Err(e))),
1465    };
1466    let Ok((_, Message::Request { header, body })) = decode_message(&msg) else {
1467        return Err(Attempt::Done(Err(local_internal())));
1468    };
1469    let timeout = deadline.map(|at| at.saturating_duration_since(Instant::now()));
1470    Ok(LocalCall::Request {
1471        version,
1472        header,
1473        body,
1474        code_sets,
1475        timeout,
1476    })
1477}
1478
1479impl LocalCall {
1480    /// Runs the call on the calling thread.
1481    fn run(self, server: &Arc<Server>) -> Result<LocalAnswer, SystemException> {
1482        match self {
1483            LocalCall::Locate(target) => server.locate_local(&target).map(LocalAnswer::Located),
1484            LocalCall::Request {
1485                version,
1486                header,
1487                body,
1488                code_sets,
1489                timeout,
1490            } => server
1491                .call_local(version, header, body, code_sets, timeout)
1492                .map(|reply| LocalAnswer::Reply(reply, code_sets)),
1493        }
1494    }
1495}
1496
1497fn local_outcome(
1498    orb: &Orb,
1499    answer: Result<LocalAnswer, SystemException>,
1500    reply_contexts: &mut Vec<ServiceContext>,
1501) -> Attempt {
1502    match answer {
1503        Ok(LocalAnswer::Located(here)) => Attempt::Done(Ok(Outcome::Located(here))),
1504        Ok(LocalAnswer::Reply(None, _)) => Attempt::Done(Ok(Outcome::Reply(None))),
1505        Ok(LocalAnswer::Reply(Some(reply), code_sets)) => match decode_message(&reply) {
1506            Ok((_, Message::Reply { header, body })) => {
1507                *reply_contexts = header.service_context;
1508                reply_outcome(orb, header.reply_status, body, code_sets)
1509            }
1510            _ => Attempt::Done(Err(local_internal())),
1511        },
1512        Err(e) => Attempt::Done(Err(e.into())),
1513    }
1514}
1515
1516fn local_internal() -> Exception {
1517    sys(SystemExceptionKind::INTERNAL, 0, CompletionStatus::Maybe).into()
1518}
1519
1520fn reply_outcome(orb: &Orb, status: ReplyStatus, body: Body, code_sets: CodeSets) -> Attempt {
1521    match status {
1522        ReplyStatus::NoException => Attempt::Done(Ok(Outcome::Reply(Some(Reply {
1523            body,
1524            code_sets,
1525            orb: orb.clone(),
1526        })))),
1527        ReplyStatus::UserException => {
1528            let reply = Reply {
1529                body,
1530                code_sets,
1531                orb: orb.clone(),
1532            };
1533            let id = reply.input().read_string();
1534            Attempt::Done(Err(match id {
1535                Ok(repository_id) => Exception::User(UserException {
1536                    repository_id,
1537                    reply,
1538                }),
1539                Err(e) => Exception::System(e),
1540            }))
1541        }
1542        ReplyStatus::SystemException => {
1543            let mut dec = body.decoder();
1544            Attempt::Done(Err(match SystemExceptionBody::decode(&mut dec) {
1545                Ok(e) => Exception::System(e.into()),
1546                Err(e) => Exception::System(marshal(e)),
1547            }))
1548        }
1549        ReplyStatus::LocationForward | ReplyStatus::LocationForwardPerm => forward(&body),
1550        ReplyStatus::NeedsAddressingMode => addressing(&body),
1551    }
1552}
1553
1554fn locate_outcome(status: LocateStatus, body: &Body) -> Attempt {
1555    match status {
1556        LocateStatus::ObjectHere => Attempt::Done(Ok(Outcome::Located(true))),
1557        LocateStatus::UnknownObject => Attempt::Done(Ok(Outcome::Located(false))),
1558        LocateStatus::ObjectForward | LocateStatus::ObjectForwardPerm => forward(body),
1559        LocateStatus::LocSystemException => {
1560            let mut dec = body.decoder();
1561            Attempt::Done(Err(match SystemExceptionBody::decode(&mut dec) {
1562                Ok(e) => Exception::System(e.into()),
1563                Err(e) => Exception::System(marshal(e)),
1564            }))
1565        }
1566        LocateStatus::LocNeedsAddressingMode => addressing(body),
1567    }
1568}
1569
1570fn forward(body: &Body) -> Attempt {
1571    let mut dec = body.decoder();
1572    match Ior::decode(&mut dec) {
1573        Ok(ior) if !ior.is_nil() => Attempt::Forward(ior),
1574        Ok(_) => Attempt::Done(Err(sys(
1575            SystemExceptionKind::INV_OBJREF,
1576            0,
1577            CompletionStatus::No,
1578        )
1579        .into())),
1580        Err(e) => Attempt::Done(Err(Exception::System(marshal(e)))),
1581    }
1582}
1583
1584fn addressing(body: &Body) -> Attempt {
1585    let mut dec = body.decoder();
1586    match dec
1587        .read_i16()
1588        .ok()
1589        .and_then(|d| AddressingDisposition::from_i16(d).ok())
1590    {
1591        Some(d) => Attempt::Addressing(d),
1592        None => Attempt::Done(Err(sys(
1593            SystemExceptionKind::MARSHAL,
1594            0,
1595            CompletionStatus::No,
1596        )
1597        .into())),
1598    }
1599}