Skip to main content

rustorb_core/
object.rs

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