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, SslSecTrans, SystemExceptionBody, TAG_INTERNET_IOP, TAG_MULTIPLE_COMPONENTS,
12    TargetAddress, Version, component_tag, decode_message, response_flags,
13};
14
15use crate::connection::{Closed, Connection, SendError};
16use crate::server::Server;
17use crate::stream::{InStream, OutStream, marshal};
18use crate::{
19    CodeSets, CompletionStatus, Exception, Orb, SystemException, SystemExceptionKind,
20    UserException, minor, timeout,
21};
22
23/// A reference to a CORBA object, from an IOR.
24///
25/// Invocations try each IIOP profile of the IOR, and each address in it,
26/// until one can be reached. An address of the ORB's own server side is
27/// not reached through the network: the request is dispatched on the
28/// calling thread. A `LOCATION_FORWARD` reply makes the
29/// reference use the forwarded IOR from then on (shared by its clones);
30/// when the forwarded object cannot be reached any more, the original IOR
31/// is used again.
32#[derive(Clone)]
33pub struct ObjectRef {
34    orb: Orb,
35    ior: Arc<Ior>,
36    forward: Arc<Mutex<Option<Arc<Ior>>>>,
37    /// [`ObjectRef::set_call_timeout`], shared by clones.
38    call_timeout: Arc<AtomicU64>,
39}
40
41impl fmt::Debug for ObjectRef {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        f.debug_struct("ObjectRef")
44            .field("type_id", &self.ior.type_id)
45            .field("profiles", &self.ior.profiles.len())
46            .finish_non_exhaustive()
47    }
48}
49
50/// `==` is [`ObjectRef::is_equivalent`].
51impl PartialEq for ObjectRef {
52    fn eq(&self, other: &ObjectRef) -> bool {
53        self.is_equivalent(other)
54    }
55}
56
57type ArgsFn<'a> = dyn Fn(&mut OutStream<'_>) -> Result<(), SystemException> + 'a;
58
59/// The arguments of an [`AsyncRequest`], whose future may move between
60/// threads.
61type SendArgsFn<'a> = dyn Fn(&mut OutStream<'_>) -> Result<(), SystemException> + Send + Sync + 'a;
62
63/// Writes the `in` and `inout` arguments of a request: either kind of
64/// argument function.
65trait WriteArgs {
66    fn write_args(&self, out: &mut OutStream<'_>) -> Result<(), SystemException>;
67}
68
69impl<F> WriteArgs for F
70where
71    F: Fn(&mut OutStream<'_>) -> Result<(), SystemException> + ?Sized,
72{
73    fn write_args(&self, out: &mut OutStream<'_>) -> Result<(), SystemException> {
74        self(out)
75    }
76}
77
78impl ObjectRef {
79    pub(crate) fn new(orb: Orb, ior: Ior) -> ObjectRef {
80        ObjectRef {
81            orb,
82            ior: Arc::new(ior),
83            forward: Arc::new(Mutex::new(None)),
84            call_timeout: Arc::new(AtomicU64::new(timeout::UNSET)),
85        }
86    }
87
88    /// A reference to the same object (sharing its forward) whose call
89    /// timeout is its own, starting from this one's.
90    pub(crate) fn with_own_settings(&self) -> ObjectRef {
91        ObjectRef {
92            call_timeout: Arc::new(AtomicU64::new(self.call_timeout.load(Ordering::Relaxed))),
93            ..self.clone()
94        }
95    }
96
97    /// The IOR the reference was created from.
98    pub fn ior(&self) -> &Ior {
99        &self.ior
100    }
101
102    /// The IOR invocations currently go to: the last forwarded one, or the
103    /// original.
104    pub fn effective_ior(&self) -> Ior {
105        (*self.current_target()).clone()
106    }
107
108    /// The repository id in the IOR, which may be empty.
109    pub fn type_id(&self) -> &str {
110        &self.ior.type_id
111    }
112
113    /// The ORB the reference belongs to.
114    pub fn orb(&self) -> &Orb {
115        &self.orb
116    }
117
118    /// `CORBA::Object::_is_equivalent`: whether both references have the
119    /// same profiles, so they certainly denote the same object. `false`
120    /// does not mean they are different objects.
121    pub fn is_equivalent(&self, other: &ObjectRef) -> bool {
122        Arc::ptr_eq(&self.ior, &other.ior) || self.ior.profiles == other.ior.profiles
123    }
124
125    /// Starts a request for `operation`.
126    pub fn request<'a>(&'a self, operation: &str) -> Request<'a> {
127        Request {
128            obj: self,
129            operation: operation.to_owned(),
130            args: None,
131            timeout: None,
132        }
133    }
134
135    /// Starts a request for `operation` that runs as a future
136    /// ([`AsyncRequest`]).
137    pub fn request_async<'a>(&'a self, operation: &str) -> AsyncRequest<'a> {
138        AsyncRequest {
139            obj: self,
140            operation: operation.to_owned(),
141            args: None,
142            timeout: None,
143        }
144    }
145
146    /// Sets how long calls on this reference and its clones wait for a
147    /// reply: `Some(t)` (where `t` is `None` for no limit) overrides the
148    /// ORB's [`call_timeout`](Orb::call_timeout) and the calling thread's
149    /// ([`set_thread_call_timeout`](crate::set_thread_call_timeout)), and
150    /// `None` unsets it. Like omniORB's `setClientCallTimeout(obj,
151    /// millisecs)`. References made from the same IOR by
152    /// [`Orb::string_to_object`] do not share it.
153    pub fn set_call_timeout(&self, timeout: Option<Option<Duration>>) {
154        let v = timeout.map_or(timeout::UNSET, timeout::encode);
155        self.call_timeout.store(v, Ordering::Relaxed);
156    }
157
158    /// The setting of [`set_call_timeout`](ObjectRef::set_call_timeout).
159    pub fn call_timeout(&self) -> Option<Option<Duration>> {
160        match self.call_timeout.load(Ordering::Relaxed) {
161            timeout::UNSET => None,
162            v => Some(timeout::decode(v)),
163        }
164    }
165
166    /// The timeout of a call on this reference from the calling thread:
167    /// the reference's, else the thread's, else the ORB's (the order
168    /// omniORB uses).
169    pub(crate) fn effective_timeout(&self) -> Option<Duration> {
170        self.call_timeout()
171            .or_else(timeout::thread_call_timeout)
172            .unwrap_or_else(|| self.orb.call_timeout())
173    }
174
175    /// `CORBA::Object::_is_a`.
176    pub fn is_a(&self, repository_id: &str) -> Result<bool, Exception> {
177        let reply = self
178            .request("_is_a")
179            .args(|out| out.write_string(repository_id))
180            .invoke()?;
181        Ok(reply.input().read::<bool>()?)
182    }
183
184    /// `CORBA::Object::_non_existent`. `OBJECT_NOT_EXIST` from the server
185    /// counts as `true`.
186    pub fn non_existent(&self) -> Result<bool, Exception> {
187        match self.request("_non_existent").invoke() {
188            Ok(reply) => Ok(reply.input().read::<bool>()?),
189            Err(Exception::System(e)) if e.is(SystemExceptionKind::OBJECT_NOT_EXIST) => Ok(true),
190            Err(e) => Err(e),
191        }
192    }
193
194    /// The async form of [`is_a`](ObjectRef::is_a).
195    pub async fn is_a_async(&self, repository_id: &str) -> Result<bool, Exception> {
196        let id = repository_id.to_owned();
197        let reply = self
198            .request_async("_is_a")
199            .args(move |out| out.write_string(&id))
200            .invoke()
201            .await?;
202        Ok(reply.input().read::<bool>()?)
203    }
204
205    /// The async form of [`non_existent`](ObjectRef::non_existent).
206    pub async fn non_existent_async(&self) -> Result<bool, Exception> {
207        match self.request_async("_non_existent").invoke().await {
208            Ok(reply) => Ok(reply.input().read::<bool>()?),
209            Err(Exception::System(e)) if e.is(SystemExceptionKind::OBJECT_NOT_EXIST) => Ok(true),
210            Err(e) => Err(e),
211        }
212    }
213
214    /// Sends a `LocateRequest`, following forwards. Returns whether the
215    /// server has the object (`OBJECT_HERE`) or not (`UNKNOWN_OBJECT`).
216    pub fn locate(&self) -> Result<bool, Exception> {
217        let kind = Kind::<ArgsFn<'_>>::Locate;
218        let outcome = invoke(self, &kind, self.effective_timeout())?;
219        match outcome {
220            Outcome::Located(here) => Ok(here),
221            Outcome::Reply(_) => unreachable!("a locate request gives a locate outcome"),
222        }
223    }
224
225    /// The async form of [`locate`](ObjectRef::locate).
226    pub fn locate_async(&self) -> impl Future<Output = Result<bool, Exception>> + Send + '_ {
227        let timeout = self.effective_timeout();
228        self.orb.in_runtime(async move {
229            let kind = Kind::<SendArgsFn<'_>>::Locate;
230            match invoke_async(self, &kind, timeout).await? {
231                Outcome::Located(here) => Ok(here),
232                Outcome::Reply(_) => unreachable!("a locate request gives a locate outcome"),
233            }
234        })
235    }
236
237    /// `CORBA::Object::validate_connection`: binds the reference with a
238    /// `LocateRequest` (following forwards) and returns true. rustorb has
239    /// no policy that can forbid a call, so it never returns false. The
240    /// failure to bind raises its exception (`TRANSIENT`, `TIMEOUT`...),
241    /// and an object the server does not have `OBJECT_NOT_EXIST`.
242    pub fn validate_connection(&self) -> Result<bool, Exception> {
243        if self.locate()? {
244            Ok(true)
245        } else {
246            Err(SystemException::new(
247                SystemExceptionKind::OBJECT_NOT_EXIST,
248                minor::NO_SUCH_OBJECT,
249                CompletionStatus::No,
250            )
251            .into())
252        }
253    }
254
255    fn current_target(&self) -> Arc<Ior> {
256        match &*self.forward.lock().unwrap() {
257            Some(ior) => Arc::clone(ior),
258            None => Arc::clone(&self.ior),
259        }
260    }
261
262    fn set_forward(&self, ior: Option<Arc<Ior>>) {
263        *self.forward.lock().unwrap() = ior;
264    }
265}
266
267/// A request being built: the operation, its arguments, and a timeout.
268pub struct Request<'a> {
269    obj: &'a ObjectRef,
270    operation: String,
271    args: Option<Box<ArgsFn<'a>>>,
272    /// Set by [`Request::timeout`].
273    timeout: Option<Option<Duration>>,
274}
275
276impl fmt::Debug for Request<'_> {
277    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
278        f.debug_struct("Request")
279            .field("operation", &self.operation)
280            .field("timeout", &self.timeout)
281            .finish_non_exhaustive()
282    }
283}
284
285impl<'a> Request<'a> {
286    /// Sets the function that writes the `in` and `inout` arguments. It may
287    /// run more than once, when the request is forwarded or retried.
288    pub fn args<F>(mut self, f: F) -> Request<'a>
289    where
290        F: Fn(&mut OutStream<'_>) -> Result<(), SystemException> + 'a,
291    {
292        self.args = Some(Box::new(f));
293        self
294    }
295
296    /// Sets how long this request waits for a reply (`None`: no limit),
297    /// overriding the timeouts of the thread, the reference and the ORB
298    /// (see [`Orb::set_call_timeout`]).
299    pub fn timeout(mut self, timeout: Option<Duration>) -> Request<'a> {
300        self.timeout = Some(timeout);
301        self
302    }
303
304    fn effective_timeout(&self) -> Option<Duration> {
305        self.timeout.unwrap_or_else(|| self.obj.effective_timeout())
306    }
307
308    /// Sends the request and waits for the reply.
309    pub fn invoke(self) -> Result<Reply, Exception> {
310        let kind = Kind::Request {
311            operation: &self.operation,
312            args: self.args.as_deref(),
313            response: true,
314        };
315        match invoke(self.obj, &kind, self.effective_timeout())? {
316            Outcome::Reply(Some(reply)) => Ok(reply),
317            _ => unreachable!("a two-way request gives a reply"),
318        }
319    }
320
321    /// Sends the request as a oneway call: returns once the message is
322    /// written, with no reply.
323    pub fn send_oneway(self) -> Result<(), SystemException> {
324        let kind = Kind::Request {
325            operation: &self.operation,
326            args: self.args.as_deref(),
327            response: false,
328        };
329        match invoke(self.obj, &kind, self.effective_timeout()) {
330            Ok(_) => Ok(()),
331            Err(Exception::System(e)) => Err(e),
332            Err(Exception::User(_)) => unreachable!("a oneway request has no reply"),
333        }
334    }
335}
336
337/// A request that runs as a future: [`Request`] for async code.
338///
339/// The future can be polled by any executor, or none in particular: the
340/// sockets and timers of the call belong to the ORB's runtime. It does not
341/// block the thread that polls it, except that a call to an object of the
342/// ORB's own server side runs the servant on an upcall thread and waits
343/// for it without blocking. The timeout is taken when
344/// [`invoke`](AsyncRequest::invoke) is called, so a timeout of the calling
345/// thread ([`set_thread_call_timeout`](crate::set_thread_call_timeout))
346/// counts as it does for [`Request`].
347pub struct AsyncRequest<'a> {
348    obj: &'a ObjectRef,
349    operation: String,
350    args: Option<Box<SendArgsFn<'a>>>,
351    timeout: Option<Option<Duration>>,
352}
353
354impl fmt::Debug for AsyncRequest<'_> {
355    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356        f.debug_struct("AsyncRequest")
357            .field("operation", &self.operation)
358            .field("timeout", &self.timeout)
359            .finish_non_exhaustive()
360    }
361}
362
363impl<'a> AsyncRequest<'a> {
364    /// [`Request::args`]; the function must be `Send` and `Sync`, as the
365    /// future may move between threads.
366    pub fn args<F>(mut self, f: F) -> AsyncRequest<'a>
367    where
368        F: Fn(&mut OutStream<'_>) -> Result<(), SystemException> + Send + Sync + 'a,
369    {
370        self.args = Some(Box::new(f));
371        self
372    }
373
374    /// [`Request::timeout`].
375    pub fn timeout(mut self, timeout: Option<Duration>) -> AsyncRequest<'a> {
376        self.timeout = Some(timeout);
377        self
378    }
379
380    /// Sends the request; the future resolves to the reply.
381    pub fn invoke(self) -> impl Future<Output = Result<Reply, Exception>> + Send + 'a {
382        let timeout = self.timeout.unwrap_or_else(|| self.obj.effective_timeout());
383        let orb = self.obj.orb.clone();
384        orb.in_runtime(async move {
385            let kind = Kind::Request {
386                operation: &self.operation,
387                args: self.args.as_deref(),
388                response: true,
389            };
390            match invoke_async(self.obj, &kind, timeout).await? {
391                Outcome::Reply(Some(reply)) => Ok(reply),
392                _ => unreachable!("a two-way request gives a reply"),
393            }
394        })
395    }
396
397    /// Sends the request as a oneway call; the future resolves once the
398    /// message is written.
399    pub fn send_oneway(self) -> impl Future<Output = Result<(), SystemException>> + Send + 'a {
400        let timeout = self.timeout.unwrap_or_else(|| self.obj.effective_timeout());
401        let orb = self.obj.orb.clone();
402        orb.in_runtime(async move {
403            let kind = Kind::Request {
404                operation: &self.operation,
405                args: self.args.as_deref(),
406                response: false,
407            };
408            match invoke_async(self.obj, &kind, timeout).await {
409                Ok(_) => Ok(()),
410                Err(Exception::System(e)) => Err(e),
411                Err(Exception::User(_)) => unreachable!("a oneway request has no reply"),
412            }
413        })
414    }
415}
416
417/// A normal reply: the return value and the `out` and `inout` arguments.
418#[derive(Debug, Clone)]
419pub struct Reply {
420    body: Body,
421    code_sets: CodeSets,
422    orb: Orb,
423}
424
425impl Reply {
426    /// A stream over the reply body.
427    pub fn input(&self) -> InStream<'_> {
428        InStream {
429            dec: self.body.decoder(),
430            code_sets: self.code_sets,
431            orb: Some(&self.orb),
432            completed: CompletionStatus::Yes,
433            wchar_needs_code_set: false,
434            values: Vec::new(),
435            typed_values: Vec::new(),
436            custom_items: None,
437            body: Some(&self.body),
438        }
439    }
440
441    /// The raw reply body.
442    pub fn body(&self) -> &Body {
443        &self.body
444    }
445}
446
447enum Kind<'k, A: ?Sized = ArgsFn<'k>> {
448    Request {
449        operation: &'k str,
450        args: Option<&'k A>,
451        response: bool,
452    },
453    Locate,
454}
455
456enum Outcome {
457    Reply(Option<Reply>),
458    Located(bool),
459}
460
461enum Attempt {
462    Done(Result<Outcome, Exception>),
463    /// The request was not processed here; try the next address.
464    NotSent(SystemException),
465    Forward(Ior),
466    Addressing(AddressingDisposition),
467}
468
469/// One address an object can be reached at.
470struct Endpoint {
471    profile_index: usize,
472    version: Version,
473    host: String,
474    port: u16,
475    /// A TLS endpoint (from `TAG_SSL_SEC_TRANS`).
476    tls: bool,
477    object_key: Vec<u8>,
478    code_sets: Option<CodeSetComponentInfo>,
479}
480
481/// Every IIOP address in `ior` this ORB can use, in order: for each
482/// profile, its TLS endpoint if it has one and the ORB can use TLS
483/// (docs/ssliop.md), else its own address and its alternate addresses.
484/// A port of 0 is no address.
485fn endpoints(ior: &Ior, can_tls: bool) -> Vec<Endpoint> {
486    let shared: Vec<_> = ior
487        .profiles
488        .iter()
489        .filter(|p| p.tag == TAG_MULTIPLE_COMPONENTS)
490        .filter_map(|p| p.multiple_components().ok())
491        .flatten()
492        .collect();
493    let mut out = Vec::new();
494    for (index, profile) in ior.profiles.iter().enumerate() {
495        if profile.tag != TAG_INTERNET_IOP {
496            continue;
497        }
498        let Ok(iiop) = profile.iiop() else { continue };
499        if iiop.version.major != 1 {
500            continue;
501        }
502        // IIOP 1.0 profiles have no components of their own; they use
503        // those of the TAG_MULTIPLE_COMPONENTS profile.
504        let components = if iiop.version.minor == 0 {
505            &shared
506        } else {
507            &iiop.components
508        };
509        let code_sets = components
510            .iter()
511            .find(|c| c.tag == component_tag::CODE_SETS)
512            .and_then(|c| CodeSetComponentInfo::from_component(c).ok());
513        let ssl = components
514            .iter()
515            .find(|c| c.tag == component_tag::SSL_SEC_TRANS)
516            .and_then(|c| SslSecTrans::from_component(c).ok());
517        let mut addrs = Vec::new();
518        if let (Some(ssl), true) = (ssl, can_tls) {
519            // Not unprotected instead, should the TLS endpoint fail.
520            addrs.push((iiop.host.clone(), ssl.port, true));
521        } else {
522            addrs.push((iiop.host.clone(), iiop.port, false));
523            addrs.extend(
524                components
525                    .iter()
526                    .filter(|c| c.tag == component_tag::ALTERNATE_IIOP_ADDRESS)
527                    .filter_map(|c| AlternateIiopAddress::from_component(c).ok())
528                    .map(|a| (a.host, a.port, false)),
529            );
530        }
531        for (host, port, tls) in addrs {
532            if port == 0 {
533                continue;
534            }
535            out.push(Endpoint {
536                profile_index: index,
537                version: iiop.version,
538                host,
539                port,
540                tls,
541                object_key: iiop.object_key.clone(),
542                code_sets: code_sets.clone(),
543            });
544        }
545    }
546    out
547}
548
549fn sys(kind: SystemExceptionKind, minor: u32, completed: CompletionStatus) -> SystemException {
550    SystemException::new(kind, minor, completed)
551}
552
553/// The walk of a call over the addresses of its target, the forwards and
554/// the addressing modes; the same for blocking and async calls.
555struct Walk<'o> {
556    obj: &'o ObjectRef,
557    max_hops: u32,
558    hops: u32,
559    ior: Arc<Ior>,
560    disposition: AddressingDisposition,
561    endpoints: std::vec::IntoIter<Endpoint>,
562    /// Why the addresses tried so far could not be used.
563    last: SystemException,
564    /// The target was just set (and is still to be checked for nil).
565    fresh: bool,
566}
567
568enum Step {
569    Try(Endpoint),
570    Done(Result<Outcome, Exception>),
571}
572
573impl<'o> Walk<'o> {
574    fn new(obj: &'o ObjectRef) -> Walk<'o> {
575        let mut walk = Walk {
576            obj,
577            max_hops: obj.orb.inner.options.max_forwards,
578            hops: 0,
579            ior: obj.current_target(),
580            disposition: AddressingDisposition::Key,
581            endpoints: Vec::new().into_iter(),
582            last: no_usable_profile(),
583            fresh: true,
584        };
585        walk.retarget(Arc::clone(&walk.ior));
586        walk
587    }
588
589    fn retarget(&mut self, ior: Arc<Ior>) {
590        self.endpoints = endpoints(&ior, self.obj.orb.has_tls_client()).into_iter();
591        self.ior = ior;
592        self.last = no_usable_profile();
593        self.fresh = true;
594    }
595
596    /// The next address to try, or the end of the call.
597    fn next(&mut self) -> Step {
598        loop {
599            if std::mem::take(&mut self.fresh) && self.ior.is_nil() {
600                return Step::Done(Err(sys(
601                    SystemExceptionKind::INV_OBJREF,
602                    0,
603                    CompletionStatus::No,
604                )
605                .into()));
606            }
607            if let Some(ep) = self.endpoints.next() {
608                return Step::Try(ep);
609            }
610            // Nothing could be reached. A forwarded target falls back to
611            // the original reference.
612            if !Arc::ptr_eq(&self.ior, &self.obj.ior) {
613                self.hops += 1;
614                if self.hops <= self.max_hops {
615                    self.obj.set_forward(None);
616                    self.disposition = AddressingDisposition::Key;
617                    self.retarget(Arc::clone(&self.obj.ior));
618                    continue;
619                }
620            }
621            return Step::Done(Err(self.last.clone().into()));
622        }
623    }
624
625    /// Takes in the attempt at the address [`next`](Walk::next) gave:
626    /// `Some` ends the call.
627    fn record(&mut self, attempt: Attempt) -> Option<Result<Outcome, Exception>> {
628        match attempt {
629            Attempt::Done(result) => Some(result),
630            Attempt::NotSent(e) => {
631                self.last = e;
632                None
633            }
634            Attempt::Forward(next) => {
635                self.hops += 1;
636                if self.hops > self.max_hops {
637                    return Some(Err(sys(
638                        SystemExceptionKind::TRANSIENT,
639                        0,
640                        CompletionStatus::No,
641                    )
642                    .into()));
643                }
644                let next = Arc::new(next);
645                self.obj.set_forward(Some(Arc::clone(&next)));
646                self.disposition = AddressingDisposition::Key;
647                self.retarget(next);
648                None
649            }
650            Attempt::Addressing(wanted) => {
651                self.hops += 1;
652                if self.hops > self.max_hops || wanted == self.disposition {
653                    return Some(Err(sys(
654                        SystemExceptionKind::MARSHAL,
655                        0,
656                        CompletionStatus::No,
657                    )
658                    .into()));
659                }
660                self.disposition = wanted;
661                self.retarget(Arc::clone(&self.ior));
662                None
663            }
664        }
665    }
666}
667
668fn no_usable_profile() -> SystemException {
669    sys(
670        SystemExceptionKind::TRANSIENT,
671        minor::NO_USABLE_PROFILE,
672        CompletionStatus::No,
673    )
674}
675
676fn invoke<A: WriteArgs + ?Sized>(
677    obj: &ObjectRef,
678    kind: &Kind<'_, A>,
679    timeout: Option<Duration>,
680) -> Result<Outcome, Exception> {
681    let orb = &obj.orb;
682    orb.check_running()?;
683    // The timeout covers the whole call: connecting, forwards and the
684    // wait for the reply.
685    let deadline = timeout.map(|t| Instant::now() + t);
686    let mut walk = Walk::new(obj);
687    loop {
688        let ep = match walk.next() {
689            Step::Try(ep) => ep,
690            Step::Done(result) => return result,
691        };
692        let (ior, disposition) = (Arc::clone(&walk.ior), walk.disposition);
693        let attempt = match orb.local_server(&ep.host, ep.port, ep.tls) {
694            Some(server) => match local_call(orb, &ior, &ep, kind, deadline, disposition) {
695                Ok(call) => {
696                    let result = call.run(&server);
697                    local_outcome(orb, result)
698                }
699                Err(done) => done,
700            },
701            None => orb.block_on(attempt(orb, &ior, &ep, kind, deadline, disposition, true))?,
702        };
703        if let Some(result) = walk.record(attempt) {
704            return result;
705        }
706    }
707}
708
709/// [`invoke`] as a future, run inside the ORB's runtime
710/// ([`Orb::in_runtime`]). A call to the ORB's own server side runs on an
711/// upcall thread.
712async fn invoke_async<A: WriteArgs + ?Sized>(
713    obj: &ObjectRef,
714    kind: &Kind<'_, A>,
715    timeout: Option<Duration>,
716) -> Result<Outcome, Exception> {
717    let orb = &obj.orb;
718    orb.check_running()?;
719    let deadline = timeout.map(|t| Instant::now() + t);
720    let mut walk = Walk::new(obj);
721    loop {
722        let ep = match walk.next() {
723            Step::Try(ep) => ep,
724            Step::Done(result) => return result,
725        };
726        let (ior, disposition) = (Arc::clone(&walk.ior), walk.disposition);
727        let attempt = match orb.local_server(&ep.host, ep.port, ep.tls) {
728            Some(server) => match local_call(orb, &ior, &ep, kind, deadline, disposition) {
729                Ok(call) => {
730                    let (tx, rx) = tokio::sync::oneshot::channel();
731                    let on_pool = Arc::clone(&server);
732                    server.submit(Box::new(move || {
733                        let _ = tx.send(call.run(&on_pool));
734                    }));
735                    // The pool is gone when the ORB is being destroyed.
736                    let result = rx.await.unwrap_or_else(|_| {
737                        Err(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No))
738                    });
739                    local_outcome(orb, result)
740                }
741                Err(done) => done,
742            },
743            None => attempt(orb, &ior, &ep, kind, deadline, disposition, false).await,
744        };
745        if let Some(result) = walk.record(attempt) {
746            return result;
747        }
748    }
749}
750
751/// How long a `CancelRequest` after a timeout may take to go out.
752const CANCEL_SEND_TIME: Duration = Duration::from_millis(100);
753
754/// Sends the request to one endpoint. A `CloseConnection` before the reply
755/// means the server did not process it, so it is sent once more on a new
756/// connection.
757///
758/// With `own_thread`, the caller is a thread of its own (a blocking call),
759/// which may block reading the reply.
760async fn attempt<A: WriteArgs + ?Sized>(
761    orb: &Orb,
762    ior: &Ior,
763    ep: &Endpoint,
764    kind: &Kind<'_, A>,
765    deadline: Option<Instant>,
766    disposition: AddressingDisposition,
767    own_thread: bool,
768) -> Attempt {
769    let mut result = Attempt::NotSent(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No));
770    for _ in 0..2 {
771        let conn = match orb.connection(&ep.host, ep.port, ep.tls, deadline).await {
772            Ok(conn) => conn,
773            // Out of time: the other addresses are not tried.
774            Err(e) if e.is(SystemExceptionKind::TIMEOUT) => return Attempt::Done(Err(e.into())),
775            Err(e) => return Attempt::NotSent(e),
776        };
777        match attempt_on(orb, &conn, ior, ep, kind, deadline, disposition, own_thread).await {
778            Ok(done) => return done,
779            Err(Closed::Orderly) => {
780                orb.discard(&conn);
781                result =
782                    Attempt::NotSent(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No));
783            }
784            Err(Closed::Failed(_)) => {
785                orb.discard(&conn);
786                return Attempt::Done(Err(sys(
787                    SystemExceptionKind::COMM_FAILURE,
788                    0,
789                    CompletionStatus::Maybe,
790                )
791                .into()));
792            }
793        }
794    }
795    result
796}
797
798/// `Err(Closed::Orderly)` asks for a retry on a new connection;
799/// `Err(Closed::Failed)` after the request was sent is `COMM_FAILURE`.
800#[allow(clippy::too_many_arguments)]
801async fn attempt_on<A: WriteArgs + ?Sized>(
802    orb: &Orb,
803    conn: &Arc<Connection>,
804    ior: &Ior,
805    ep: &Endpoint,
806    kind: &Kind<'_, A>,
807    deadline: Option<Instant>,
808    disposition: AddressingDisposition,
809    own_thread: bool,
810) -> Result<Attempt, Closed> {
811    let options = &orb.inner.options;
812    let order = options.byte_order;
813    let version = ep.version.min(options.max_giop_version);
814    let target = target_address(ior, ep, version, disposition);
815
816    // Code sets: negotiated from the IOR for GIOP 1.1 and later, fixed for
817    // the connection by its first request, and announced in every request.
818    let (code_sets, context) = match (&ep.code_sets, version >= Version::V1_1) {
819        (Some(info), true) => {
820            let proposed = match conn.code_sets() {
821                Some(cs) => cs,
822                None => match CodeSets::negotiate(info) {
823                    Ok(cs) => cs,
824                    Err(e) => return Ok(Attempt::Done(Err(e.into()))),
825                },
826            };
827            let cs = conn.claim_code_sets(proposed);
828            (cs, vec![cs.context().to_service_context(order)])
829        }
830        _ => (CodeSets::DEFAULT, Vec::new()),
831    };
832
833    let request_id = conn.next_request_id();
834    let response = match kind {
835        Kind::Request { response, .. } => *response,
836        Kind::Locate => true,
837    };
838    let msg = match kind {
839        Kind::Request {
840            operation,
841            args,
842            response,
843        } => {
844            let header = request_header(request_id, *response, target, operation, context);
845            match encode_request(version, order, &header, *args, code_sets) {
846                Ok(msg) => msg,
847                Err(e) => return Ok(Attempt::Done(Err(e))),
848            }
849        }
850        Kind::Locate => match MessageEncoder::locate_request(
851            version,
852            order,
853            &LocateRequestHeader { request_id, target },
854        ) {
855            Ok(msg) => msg.into(),
856            Err(_) => {
857                return Ok(Attempt::Done(Err(sys(
858                    SystemExceptionKind::MARSHAL,
859                    0,
860                    CompletionStatus::No,
861                )
862                .into())));
863            }
864        },
865    };
866
867    let rx = if response {
868        match conn.expect_reply(request_id) {
869            Ok(rx) => Some(rx),
870            Err(Closed::Orderly) => return Err(Closed::Orderly),
871            // The connection broke before anything was sent: not processed.
872            Err(Closed::Failed(_)) => {
873                orb.discard(conn);
874                return Ok(Attempt::NotSent(sys(
875                    SystemExceptionKind::COMM_FAILURE,
876                    0,
877                    CompletionStatus::No,
878                )));
879            }
880        }
881    } else {
882        None
883    };
884    match conn.send(&msg, deadline).await {
885        Ok(()) => {}
886        // Out of time before the whole request went out (a peer that
887        // stopped reading, say): the server did not get it.
888        Err(SendError::TimedOut) => {
889            conn.forget(request_id);
890            if !conn.is_usable() {
891                orb.discard(conn);
892            }
893            return Ok(Attempt::Done(Err(sys(
894                SystemExceptionKind::TIMEOUT,
895                0,
896                CompletionStatus::No,
897            )
898            .into())));
899        }
900        Err(SendError::Failed) => {
901            conn.forget(request_id);
902            orb.discard(conn);
903            return Ok(Attempt::NotSent(sys(
904                SystemExceptionKind::COMM_FAILURE,
905                0,
906                CompletionStatus::No,
907            )));
908        }
909    }
910    let Some(rx) = rx else {
911        return Ok(Attempt::Done(Ok(Outcome::Reply(None))));
912    };
913
914    // A blocking call runs on the caller's own thread (`Orb::block_on`),
915    // which may block reading the reply.
916    let here = if own_thread {
917        conn.read_reply_here(request_id, deadline)
918    } else {
919        None
920    };
921    let delivered = match here {
922        Some(Some(message)) => Some(Ok(Ok(message))),
923        Some(None) => None,
924        None => match deadline {
925            Some(at) => tokio::time::timeout_at(at.into(), rx).await.ok(),
926            None => Some(rx.await),
927        },
928    };
929    let delivered = match delivered {
930        Some(delivered) => delivered,
931        None => {
932            conn.forget(request_id);
933            if let Ok(cancel) =
934                MessageEncoder::cancel_request(version, order, &CancelRequestHeader { request_id })
935            {
936                // The caller is out of time already, and the connection
937                // may be the reason: a short wait at most.
938                let at = Instant::now() + CANCEL_SEND_TIME;
939                let _ = conn.send(&cancel.into(), Some(at)).await;
940            }
941            return Ok(Attempt::Done(Err(sys(
942                SystemExceptionKind::TIMEOUT,
943                0,
944                CompletionStatus::Maybe,
945            )
946            .into())));
947        }
948    };
949    let message = match delivered {
950        Ok(Ok(message)) => message,
951        Ok(Err(closed)) => return Err(closed),
952        Err(_) => return Err(Closed::Failed("reply channel dropped".into())),
953    };
954    Ok(match message {
955        Message::Reply { header, body } => {
956            if !matches!(kind, Kind::Request { .. }) {
957                return Err(Closed::Failed("Reply to a LocateRequest".into()));
958            }
959            reply_outcome(orb, header.reply_status, body, code_sets)
960        }
961        Message::LocateReply { header, body } => {
962            if !matches!(kind, Kind::Locate) {
963                return Err(Closed::Failed("LocateReply to a Request".into()));
964            }
965            locate_outcome(header.locate_status, &body)
966        }
967        _ => return Err(Closed::Failed("unexpected message".into())),
968    })
969}
970
971/// How a request names its target, in the addressing disposition the
972/// server asked for (GIOP 1.2), or by object key.
973fn target_address(
974    ior: &Ior,
975    ep: &Endpoint,
976    version: Version,
977    disposition: AddressingDisposition,
978) -> TargetAddress {
979    if version < Version::V1_2 {
980        return TargetAddress::Key(ep.object_key.clone());
981    }
982    match disposition {
983        AddressingDisposition::Key => TargetAddress::Key(ep.object_key.clone()),
984        AddressingDisposition::Profile => {
985            TargetAddress::Profile(ior.profiles[ep.profile_index].clone())
986        }
987        AddressingDisposition::Reference => TargetAddress::Reference {
988            selected_profile_index: ep.profile_index as u32,
989            ior: ior.clone(),
990        },
991    }
992}
993
994fn request_header(
995    request_id: u32,
996    response: bool,
997    target: TargetAddress,
998    operation: &str,
999    service_context: Vec<rustorb_giop::ServiceContext>,
1000) -> RequestHeader {
1001    RequestHeader {
1002        request_id,
1003        response_flags: if response {
1004            response_flags::SYNC_WITH_TARGET
1005        } else {
1006            response_flags::NONE
1007        },
1008        target,
1009        operation: operation.to_owned(),
1010        service_context,
1011        requesting_principal: Vec::new(),
1012    }
1013}
1014
1015/// The whole `Request` message, with the arguments `args` writes.
1016fn encode_request<A: WriteArgs + ?Sized>(
1017    version: Version,
1018    order: rustorb_cdr::ByteOrder,
1019    header: &RequestHeader,
1020    args: Option<&A>,
1021    code_sets: CodeSets,
1022) -> Result<OutMessage, Exception> {
1023    let marshal = || sys(SystemExceptionKind::MARSHAL, 0, CompletionStatus::No).into();
1024    let mut m = MessageEncoder::request(version, order, header).map_err(|_| marshal())?;
1025    if let Some(args) = args {
1026        let mut out = OutStream {
1027            enc: m.body(),
1028            code_sets,
1029            orb: None,
1030        };
1031        args.write_args(&mut out)?;
1032    }
1033    m.finish_shared().map_err(|_| marshal())
1034}
1035
1036/// A request to an object of the ORB's own server side, without the
1037/// network: marshalled as for the server, which runs it on the calling
1038/// thread (or queues it, as its thread policy says) and answers with a
1039/// whole reply message.
1040enum LocalCall {
1041    Locate(TargetAddress),
1042    Request {
1043        version: Version,
1044        header: RequestHeader,
1045        body: Body,
1046        code_sets: CodeSets,
1047        timeout: Option<Duration>,
1048    },
1049}
1050
1051/// The answer of the server side to a [`LocalCall`].
1052enum LocalAnswer {
1053    Located(bool),
1054    /// The reply message (none for a oneway request).
1055    Reply(Option<Vec<u8>>, CodeSets),
1056}
1057
1058/// The [`LocalCall`] for `kind`, or the end of the attempt.
1059fn local_call<A: WriteArgs + ?Sized>(
1060    orb: &Orb,
1061    ior: &Ior,
1062    ep: &Endpoint,
1063    kind: &Kind<'_, A>,
1064    deadline: Option<Instant>,
1065    disposition: AddressingDisposition,
1066) -> Result<LocalCall, Attempt> {
1067    let options = &orb.inner.options;
1068    let order = options.byte_order;
1069    let version = ep.version.min(options.max_giop_version);
1070    let target = target_address(ior, ep, version, disposition);
1071    let (code_sets, context) = match (&ep.code_sets, version >= Version::V1_1) {
1072        (Some(info), true) => match CodeSets::negotiate(info) {
1073            Ok(cs) => (cs, vec![cs.context().to_service_context(order)]),
1074            Err(e) => return Err(Attempt::Done(Err(e.into()))),
1075        },
1076        _ => (CodeSets::DEFAULT, Vec::new()),
1077    };
1078    let (operation, args, response) = match kind {
1079        Kind::Locate => return Ok(LocalCall::Locate(target)),
1080        Kind::Request {
1081            operation,
1082            args,
1083            response,
1084        } => (*operation, *args, *response),
1085    };
1086    let header = request_header(0, response, target, operation, context);
1087    let msg = match encode_request(version, order, &header, args, code_sets) {
1088        Ok(msg) => msg.into_vec(),
1089        Err(e) => return Err(Attempt::Done(Err(e))),
1090    };
1091    let Ok((_, Message::Request { header, body })) = decode_message(&msg) else {
1092        return Err(Attempt::Done(Err(local_internal())));
1093    };
1094    let timeout = deadline.map(|at| at.saturating_duration_since(Instant::now()));
1095    Ok(LocalCall::Request {
1096        version,
1097        header,
1098        body,
1099        code_sets,
1100        timeout,
1101    })
1102}
1103
1104impl LocalCall {
1105    /// Runs the call on the calling thread.
1106    fn run(self, server: &Arc<Server>) -> Result<LocalAnswer, SystemException> {
1107        match self {
1108            LocalCall::Locate(target) => server.locate_local(&target).map(LocalAnswer::Located),
1109            LocalCall::Request {
1110                version,
1111                header,
1112                body,
1113                code_sets,
1114                timeout,
1115            } => server
1116                .call_local(version, header, body, code_sets, timeout)
1117                .map(|reply| LocalAnswer::Reply(reply, code_sets)),
1118        }
1119    }
1120}
1121
1122fn local_outcome(orb: &Orb, answer: Result<LocalAnswer, SystemException>) -> Attempt {
1123    match answer {
1124        Ok(LocalAnswer::Located(here)) => Attempt::Done(Ok(Outcome::Located(here))),
1125        Ok(LocalAnswer::Reply(None, _)) => Attempt::Done(Ok(Outcome::Reply(None))),
1126        Ok(LocalAnswer::Reply(Some(reply), code_sets)) => match decode_message(&reply) {
1127            Ok((_, Message::Reply { header, body })) => {
1128                reply_outcome(orb, header.reply_status, body, code_sets)
1129            }
1130            _ => Attempt::Done(Err(local_internal())),
1131        },
1132        Err(e) => Attempt::Done(Err(e.into())),
1133    }
1134}
1135
1136fn local_internal() -> Exception {
1137    sys(SystemExceptionKind::INTERNAL, 0, CompletionStatus::Maybe).into()
1138}
1139
1140fn reply_outcome(orb: &Orb, status: ReplyStatus, body: Body, code_sets: CodeSets) -> Attempt {
1141    match status {
1142        ReplyStatus::NoException => Attempt::Done(Ok(Outcome::Reply(Some(Reply {
1143            body,
1144            code_sets,
1145            orb: orb.clone(),
1146        })))),
1147        ReplyStatus::UserException => {
1148            let reply = Reply {
1149                body,
1150                code_sets,
1151                orb: orb.clone(),
1152            };
1153            let id = reply.input().read_string();
1154            Attempt::Done(Err(match id {
1155                Ok(repository_id) => Exception::User(UserException {
1156                    repository_id,
1157                    reply,
1158                }),
1159                Err(e) => Exception::System(e),
1160            }))
1161        }
1162        ReplyStatus::SystemException => {
1163            let mut dec = body.decoder();
1164            Attempt::Done(Err(match SystemExceptionBody::decode(&mut dec) {
1165                Ok(e) => Exception::System(e.into()),
1166                Err(e) => Exception::System(marshal(e)),
1167            }))
1168        }
1169        ReplyStatus::LocationForward | ReplyStatus::LocationForwardPerm => forward(&body),
1170        ReplyStatus::NeedsAddressingMode => addressing(&body),
1171    }
1172}
1173
1174fn locate_outcome(status: LocateStatus, body: &Body) -> Attempt {
1175    match status {
1176        LocateStatus::ObjectHere => Attempt::Done(Ok(Outcome::Located(true))),
1177        LocateStatus::UnknownObject => Attempt::Done(Ok(Outcome::Located(false))),
1178        LocateStatus::ObjectForward | LocateStatus::ObjectForwardPerm => forward(body),
1179        LocateStatus::LocSystemException => {
1180            let mut dec = body.decoder();
1181            Attempt::Done(Err(match SystemExceptionBody::decode(&mut dec) {
1182                Ok(e) => Exception::System(e.into()),
1183                Err(e) => Exception::System(marshal(e)),
1184            }))
1185        }
1186        LocateStatus::LocNeedsAddressingMode => addressing(body),
1187    }
1188}
1189
1190fn forward(body: &Body) -> Attempt {
1191    let mut dec = body.decoder();
1192    match Ior::decode(&mut dec) {
1193        Ok(ior) if !ior.is_nil() => Attempt::Forward(ior),
1194        Ok(_) => Attempt::Done(Err(sys(
1195            SystemExceptionKind::INV_OBJREF,
1196            0,
1197            CompletionStatus::No,
1198        )
1199        .into())),
1200        Err(e) => Attempt::Done(Err(Exception::System(marshal(e)))),
1201    }
1202}
1203
1204fn addressing(body: &Body) -> Attempt {
1205    let mut dec = body.decoder();
1206    match dec
1207        .read_i16()
1208        .ok()
1209        .and_then(|d| AddressingDisposition::from_i16(d).ok())
1210    {
1211        Some(d) => Attempt::Addressing(d),
1212        None => Attempt::Done(Err(sys(
1213            SystemExceptionKind::MARSHAL,
1214            0,
1215            CompletionStatus::No,
1216        )
1217        .into())),
1218    }
1219}