Skip to main content

rustorb_core/
object.rs

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