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    // Bidirectional GIOP: the first GIOP 1.2 request offers the connection.
1163    let offer = version >= Version::V1_2 && matches!(kind, Kind::Request { .. });
1164    let offer = offer
1165        && conn.bidir_context().is_some_and(|c| {
1166            context.push(c.clone());
1167            true
1168        });
1169
1170    let request_id = conn.next_request_id();
1171    let response = match kind {
1172        Kind::Request { response, .. } => *response,
1173        Kind::Locate => true,
1174    };
1175    let msg = match kind {
1176        Kind::Request {
1177            operation,
1178            args,
1179            response,
1180            ..
1181        } => {
1182            let header = request_header(request_id, *response, target, operation, context);
1183            match encode_request(version, order, &header, *args, code_sets) {
1184                Ok(msg) if msg.len() > options.max_message_size => {
1185                    trace::warning!(
1186                        "request {operation:?} of {} bytes is over the largest GIOP message \
1187                         ({} bytes, -ORBgiopMaxMsgSize): not sent",
1188                        msg.len(),
1189                        options.max_message_size
1190                    );
1191                    return Ok(Attempt::Done(Err(sys(
1192                        SystemExceptionKind::MARSHAL,
1193                        0,
1194                        CompletionStatus::No,
1195                    )
1196                    .into())));
1197                }
1198                Ok(msg) if options.fragment_size > 0 => msg.fragment(options.fragment_size),
1199                Ok(msg) => msg,
1200                Err(e) => return Ok(Attempt::Done(Err(e))),
1201            }
1202        }
1203        Kind::Locate => match MessageEncoder::locate_request(
1204            version,
1205            order,
1206            &LocateRequestHeader { request_id, target },
1207        ) {
1208            Ok(msg) => msg.into(),
1209            Err(_) => {
1210                return Ok(Attempt::Done(Err(sys(
1211                    SystemExceptionKind::MARSHAL,
1212                    0,
1213                    CompletionStatus::No,
1214                )
1215                .into())));
1216            }
1217        },
1218    };
1219
1220    trace::debug!(
1221        "{} (id {request_id}{}) to {}:{}, GIOP {}.{}",
1222        KindName(kind),
1223        if response { "" } else { ", oneway" },
1224        ep.host,
1225        ep.port,
1226        version.major,
1227        version.minor
1228    );
1229    let rx = if response {
1230        match conn.expect_reply(request_id) {
1231            Ok(rx) => Some(rx),
1232            Err(Closed::Orderly) => return Err(Closed::Orderly),
1233            // The connection broke before anything was sent: not processed.
1234            Err(Closed::Failed(_)) => {
1235                orb.discard(conn);
1236                return Ok(Attempt::NotSent(sys(
1237                    SystemExceptionKind::COMM_FAILURE,
1238                    0,
1239                    CompletionStatus::No,
1240                )));
1241            }
1242        }
1243    } else {
1244        None
1245    };
1246    match conn.send(&msg, deadline).await {
1247        Ok(()) if offer => conn.offered(),
1248        Ok(()) => {}
1249        // Out of time before the whole request went out (a peer that
1250        // stopped reading, say): the server did not get it.
1251        Err(SendError::TimedOut) => {
1252            conn.forget(request_id);
1253            if !conn.is_usable() {
1254                orb.discard(conn);
1255            }
1256            return Ok(Attempt::Done(Err(sys(
1257                SystemExceptionKind::TIMEOUT,
1258                0,
1259                CompletionStatus::No,
1260            )
1261            .into())));
1262        }
1263        // Chosen to close as idle just now: nothing was written.
1264        Err(SendError::Closing) => {
1265            conn.forget(request_id);
1266            return Err(Closed::Orderly);
1267        }
1268        Err(SendError::Failed) => {
1269            conn.forget(request_id);
1270            orb.discard(conn);
1271            return Ok(Attempt::NotSent(sys(
1272                SystemExceptionKind::COMM_FAILURE,
1273                0,
1274                CompletionStatus::No,
1275            )));
1276        }
1277    }
1278    let Some(rx) = rx else {
1279        return Ok(Attempt::Done(Ok(Outcome::Reply(None))));
1280    };
1281
1282    // A blocking call runs on the caller's own thread (`Orb::block_on`),
1283    // which may block reading the reply.
1284    let here = if own_thread {
1285        conn.read_reply_here(request_id, deadline)
1286    } else {
1287        None
1288    };
1289    let delivered = match here {
1290        Some(Some(message)) => Some(Ok(Ok(message))),
1291        Some(None) => None,
1292        None => match deadline {
1293            Some(at) => tokio::time::timeout_at(at.into(), rx).await.ok(),
1294            None => Some(rx.await),
1295        },
1296    };
1297    let delivered = match delivered {
1298        Some(delivered) => delivered,
1299        None => {
1300            trace::debug!("{} (id {request_id}) timed out", KindName(kind));
1301            conn.forget(request_id);
1302            if let Ok(cancel) =
1303                MessageEncoder::cancel_request(version, order, &CancelRequestHeader { request_id })
1304            {
1305                // The caller is out of time already, and the connection
1306                // may be the reason: a short wait at most.
1307                let at = Instant::now() + CANCEL_SEND_TIME;
1308                let _ = conn.send(&cancel.into(), Some(at)).await;
1309            }
1310            return Ok(Attempt::Done(Err(sys(
1311                SystemExceptionKind::TIMEOUT,
1312                0,
1313                CompletionStatus::Maybe,
1314            )
1315            .into())));
1316        }
1317    };
1318    let message = match delivered {
1319        Ok(Ok(message)) => message,
1320        Ok(Err(closed)) => return Err(closed),
1321        Err(_) => return Err(Closed::Failed("reply channel dropped".into())),
1322    };
1323    Ok(match message {
1324        Message::Reply { header, body } => {
1325            if !matches!(kind, Kind::Request { .. }) {
1326                return Err(Closed::Failed("Reply to a LocateRequest".into()));
1327            }
1328            *x.reply_contexts = header.service_context;
1329            trace::debug!(
1330                "reply to {} (id {request_id}): {:?}",
1331                KindName(kind),
1332                header.reply_status
1333            );
1334            reply_outcome(orb, header.reply_status, body, code_sets)
1335        }
1336        Message::LocateReply { header, body } => {
1337            if !matches!(kind, Kind::Locate) {
1338                return Err(Closed::Failed("LocateReply to a Request".into()));
1339            }
1340            trace::debug!("LocateReply (id {request_id}): {:?}", header.locate_status);
1341            locate_outcome(header.locate_status, &body)
1342        }
1343        _ => return Err(Closed::Failed("unexpected message".into())),
1344    })
1345}
1346
1347/// How a request names its target, in the addressing disposition the
1348/// server asked for (GIOP 1.2), or by object key.
1349fn target_address(
1350    ior: &Ior,
1351    ep: &Endpoint,
1352    version: Version,
1353    disposition: AddressingDisposition,
1354) -> TargetAddress {
1355    if version < Version::V1_2 {
1356        return TargetAddress::Key(ep.object_key.clone());
1357    }
1358    match disposition {
1359        AddressingDisposition::Key => TargetAddress::Key(ep.object_key.clone()),
1360        AddressingDisposition::Profile => {
1361            TargetAddress::Profile(ior.profiles[ep.profile_index].clone())
1362        }
1363        AddressingDisposition::Reference => TargetAddress::Reference {
1364            selected_profile_index: ep.profile_index as u32,
1365            ior: ior.clone(),
1366        },
1367    }
1368}
1369
1370fn request_header(
1371    request_id: u32,
1372    response: bool,
1373    target: TargetAddress,
1374    operation: &str,
1375    service_context: Vec<rustorb_giop::ServiceContext>,
1376) -> RequestHeader {
1377    RequestHeader {
1378        request_id,
1379        response_flags: if response {
1380            response_flags::SYNC_WITH_TARGET
1381        } else {
1382            response_flags::NONE
1383        },
1384        target,
1385        operation: operation.to_owned(),
1386        service_context,
1387        requesting_principal: Vec::new(),
1388    }
1389}
1390
1391/// The whole `Request` message, with the arguments `args` writes.
1392fn encode_request<A: WriteArgs + ?Sized>(
1393    version: Version,
1394    order: rustorb_cdr::ByteOrder,
1395    header: &RequestHeader,
1396    args: Option<&A>,
1397    code_sets: CodeSets,
1398) -> Result<OutMessage, Exception> {
1399    let marshal = || sys(SystemExceptionKind::MARSHAL, 0, CompletionStatus::No).into();
1400    let mut m = MessageEncoder::request(version, order, header).map_err(|_| marshal())?;
1401    if let Some(args) = args {
1402        let mut out = OutStream {
1403            enc: m.body(),
1404            code_sets,
1405            orb: None,
1406        };
1407        args.write_args(&mut out)?;
1408    }
1409    m.finish_shared().map_err(|_| marshal())
1410}
1411
1412/// A request to an object of the ORB's own server side, without the
1413/// network: marshalled as for the server, which runs it on the calling
1414/// thread (or queues it, as its thread policy says) and answers with a
1415/// whole reply message.
1416enum LocalCall {
1417    Locate(TargetAddress),
1418    Request {
1419        version: Version,
1420        header: RequestHeader,
1421        body: Body,
1422        code_sets: CodeSets,
1423        timeout: Option<Duration>,
1424    },
1425}
1426
1427/// The answer of the server side to a [`LocalCall`].
1428enum LocalAnswer {
1429    Located(bool),
1430    /// The reply message (none for a oneway request).
1431    Reply(Option<Vec<u8>>, CodeSets),
1432}
1433
1434/// The [`LocalCall`] for `kind`, or the end of the attempt.
1435fn local_call<A: WriteArgs + ?Sized>(
1436    orb: &Orb,
1437    ior: &Ior,
1438    ep: &Endpoint,
1439    kind: &Kind<'_, A>,
1440    deadline: Option<Instant>,
1441    disposition: AddressingDisposition,
1442    contexts: &[ServiceContext],
1443) -> Result<LocalCall, Attempt> {
1444    let options = &orb.inner.options;
1445    let order = options.byte_order;
1446    let version = ep.version.min(options.max_giop_version);
1447    let target = target_address(ior, ep, version, disposition);
1448    let (code_sets, mut context) = match (&ep.code_sets, version >= Version::V1_1) {
1449        (Some(info), true) => match CodeSets::negotiate(info) {
1450            Ok(cs) => (cs, vec![cs.context().to_service_context(order)]),
1451            Err(e) => return Err(Attempt::Done(Err(e.into()))),
1452        },
1453        _ => (CodeSets::DEFAULT, Vec::new()),
1454    };
1455    context.extend_from_slice(contexts);
1456    let (operation, args, response) = match kind {
1457        Kind::Locate => return Ok(LocalCall::Locate(target)),
1458        Kind::Request {
1459            operation,
1460            args,
1461            response,
1462            ..
1463        } => (*operation, *args, *response),
1464    };
1465    trace::debug!(
1466        "request {operation:?}{} to this ORB's own object (colocated)",
1467        if response { "" } else { ", oneway" }
1468    );
1469    let header = request_header(0, response, target, operation, context);
1470    let msg = match encode_request(version, order, &header, args, code_sets) {
1471        Ok(msg) => msg.into_vec(),
1472        Err(e) => return Err(Attempt::Done(Err(e))),
1473    };
1474    let Ok((_, Message::Request { header, body })) = decode_message(&msg) else {
1475        return Err(Attempt::Done(Err(local_internal())));
1476    };
1477    let timeout = deadline.map(|at| at.saturating_duration_since(Instant::now()));
1478    Ok(LocalCall::Request {
1479        version,
1480        header,
1481        body,
1482        code_sets,
1483        timeout,
1484    })
1485}
1486
1487impl LocalCall {
1488    /// Runs the call on the calling thread.
1489    fn run(self, server: &Arc<Server>) -> Result<LocalAnswer, SystemException> {
1490        match self {
1491            LocalCall::Locate(target) => server.locate_local(&target).map(LocalAnswer::Located),
1492            LocalCall::Request {
1493                version,
1494                header,
1495                body,
1496                code_sets,
1497                timeout,
1498            } => server
1499                .call_local(version, header, body, code_sets, timeout)
1500                .map(|reply| LocalAnswer::Reply(reply, code_sets)),
1501        }
1502    }
1503}
1504
1505fn local_outcome(
1506    orb: &Orb,
1507    answer: Result<LocalAnswer, SystemException>,
1508    reply_contexts: &mut Vec<ServiceContext>,
1509) -> Attempt {
1510    match answer {
1511        Ok(LocalAnswer::Located(here)) => Attempt::Done(Ok(Outcome::Located(here))),
1512        Ok(LocalAnswer::Reply(None, _)) => Attempt::Done(Ok(Outcome::Reply(None))),
1513        Ok(LocalAnswer::Reply(Some(reply), code_sets)) => match decode_message(&reply) {
1514            Ok((_, Message::Reply { header, body })) => {
1515                *reply_contexts = header.service_context;
1516                reply_outcome(orb, header.reply_status, body, code_sets)
1517            }
1518            _ => Attempt::Done(Err(local_internal())),
1519        },
1520        Err(e) => Attempt::Done(Err(e.into())),
1521    }
1522}
1523
1524fn local_internal() -> Exception {
1525    sys(SystemExceptionKind::INTERNAL, 0, CompletionStatus::Maybe).into()
1526}
1527
1528fn reply_outcome(orb: &Orb, status: ReplyStatus, body: Body, code_sets: CodeSets) -> Attempt {
1529    match status {
1530        ReplyStatus::NoException => Attempt::Done(Ok(Outcome::Reply(Some(Reply {
1531            body,
1532            code_sets,
1533            orb: orb.clone(),
1534        })))),
1535        ReplyStatus::UserException => {
1536            let reply = Reply {
1537                body,
1538                code_sets,
1539                orb: orb.clone(),
1540            };
1541            let id = reply.input().read_string();
1542            Attempt::Done(Err(match id {
1543                Ok(repository_id) => Exception::User(UserException {
1544                    repository_id,
1545                    reply,
1546                }),
1547                Err(e) => Exception::System(e),
1548            }))
1549        }
1550        ReplyStatus::SystemException => {
1551            let mut dec = body.decoder();
1552            Attempt::Done(Err(match SystemExceptionBody::decode(&mut dec) {
1553                Ok(e) => Exception::System(e.into()),
1554                Err(e) => Exception::System(marshal(e)),
1555            }))
1556        }
1557        ReplyStatus::LocationForward | ReplyStatus::LocationForwardPerm => forward(&body),
1558        ReplyStatus::NeedsAddressingMode => addressing(&body),
1559    }
1560}
1561
1562fn locate_outcome(status: LocateStatus, body: &Body) -> Attempt {
1563    match status {
1564        LocateStatus::ObjectHere => Attempt::Done(Ok(Outcome::Located(true))),
1565        LocateStatus::UnknownObject => Attempt::Done(Ok(Outcome::Located(false))),
1566        LocateStatus::ObjectForward | LocateStatus::ObjectForwardPerm => forward(body),
1567        LocateStatus::LocSystemException => {
1568            let mut dec = body.decoder();
1569            Attempt::Done(Err(match SystemExceptionBody::decode(&mut dec) {
1570                Ok(e) => Exception::System(e.into()),
1571                Err(e) => Exception::System(marshal(e)),
1572            }))
1573        }
1574        LocateStatus::LocNeedsAddressingMode => addressing(body),
1575    }
1576}
1577
1578fn forward(body: &Body) -> Attempt {
1579    let mut dec = body.decoder();
1580    match Ior::decode(&mut dec) {
1581        Ok(ior) if !ior.is_nil() => Attempt::Forward(ior),
1582        Ok(_) => Attempt::Done(Err(sys(
1583            SystemExceptionKind::INV_OBJREF,
1584            0,
1585            CompletionStatus::No,
1586        )
1587        .into())),
1588        Err(e) => Attempt::Done(Err(Exception::System(marshal(e)))),
1589    }
1590}
1591
1592fn addressing(body: &Body) -> Attempt {
1593    let mut dec = body.decoder();
1594    match dec
1595        .read_i16()
1596        .ok()
1597        .and_then(|d| AddressingDisposition::from_i16(d).ok())
1598    {
1599        Some(d) => Attempt::Addressing(d),
1600        None => Attempt::Done(Err(sys(
1601            SystemExceptionKind::MARSHAL,
1602            0,
1603            CompletionStatus::No,
1604        )
1605        .into())),
1606    }
1607}