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#[derive(Clone)]
39pub struct ObjectRef {
40 orb: Orb,
41 ior: Arc<Ior>,
42 forward: Arc<Mutex<Option<Arc<Ior>>>>,
43 call_timeout: Arc<AtomicU64>,
45 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
58impl 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
67type SendArgsFn<'a> = dyn Fn(&mut OutStream<'_>) -> Result<(), SystemException> + Send + Sync + 'a;
70
71trait 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 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 pub(crate) fn sync_scope_override(&self) -> Option<i16> {
109 policy::load_sync_scope(&self.sync_scope)
110 }
111
112 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 pub fn ior(&self) -> &Ior {
123 &self.ior
124 }
125
126 pub fn effective_ior(&self) -> Ior {
129 (*self.current_target()).clone()
130 }
131
132 pub fn type_id(&self) -> &str {
134 &self.ior.type_id
135 }
136
137 pub fn orb(&self) -> &Orb {
139 &self.orb
140 }
141
142 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 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 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 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 pub(crate) fn request_slots(&self) -> Option<Vec<crate::Any>> {
188 request_slots(self)
189 }
190
191 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 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 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 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 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 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 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 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 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 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
312pub struct Request<'a> {
314 obj: &'a ObjectRef,
315 operation: String,
316 args: Option<Box<ArgsFn<'a>>>,
317 timeout: Option<Option<Duration>>,
319 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 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 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 pub(crate) fn dii(mut self, params: DiiParams) -> Request<'a> {
357 self.dii = Some(params);
358 self
359 }
360
361 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 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
401pub 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 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 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 pub fn timeout(mut self, timeout: Option<Duration>) -> AsyncRequest<'a> {
443 self.timeout = Some(timeout);
444 self
445 }
446
447 pub(crate) fn dii(mut self, params: DiiParams) -> AsyncRequest<'a> {
449 self.dii = Some(params);
450 self
451 }
452
453 pub(crate) fn slots(mut self, slots: Option<Vec<crate::Any>>) -> AsyncRequest<'a> {
456 self.slots = Some(slots);
457 self
458 }
459
460 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 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 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
506pub 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 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 pub fn timeout(mut self, timeout: Option<Duration>) -> CallbackRequest {
545 self.timeout = Some(timeout);
546 self
547 }
548
549 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
593struct 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 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 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#[derive(Debug, Clone)]
631pub struct Reply {
632 body: Body,
633 code_sets: CodeSets,
634 orb: Orb,
635}
636
637impl Reply {
638 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 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 response: bool,
665 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 NotSent(SystemException),
682 Forward(Ior),
683 Addressing(AddressingDisposition),
684 Resend,
688}
689
690struct Endpoint {
692 profile_index: usize,
693 version: Version,
694 host: String,
695 port: u16,
696 transport: Transport,
699 object_key: Vec<u8>,
700 code_sets: Option<CodeSetComponentInfo>,
701}
702
703fn 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 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 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 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
792struct 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 last: SystemException,
803 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 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 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 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 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
922fn 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
931struct 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 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 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
1023fn 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 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
1129struct Exchange<'x> {
1131 deadline: Option<Instant>,
1132 disposition: AddressingDisposition,
1133 own_thread: bool,
1136 resend: bool,
1139 contexts: &'x [ServiceContext],
1141 reply_contexts: &'x mut Vec<ServiceContext>,
1143}
1144
1145async 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 let gone =
1197 || Err(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No));
1198 let result = match deadline {
1201 Some(at) => match tokio::time::timeout_at(at.into(), rx).await {
1202 Ok(r) => r.unwrap_or_else(|_| gone()),
1203 Err(_) => Err(sys(
1204 SystemExceptionKind::TIMEOUT,
1205 0,
1206 CompletionStatus::Maybe,
1207 )),
1208 },
1209 None => rx.await.unwrap_or_else(|_| gone()),
1210 };
1211 local_outcome(orb, result, &mut reply_contexts)
1212 }
1213 Err(done) => done,
1214 }
1215 }
1216 None => {
1217 attempt(
1218 orb,
1219 &ior,
1220 &ep,
1221 kind,
1222 Exchange {
1223 deadline,
1224 disposition,
1225 own_thread: false,
1226 resend: info.is_none(),
1227 contexts: &contexts,
1228 reply_contexts: &mut reply_contexts,
1229 },
1230 )
1231 .await
1232 }
1233 };
1234 attempt = without_reply(kind, attempt);
1235 if let (Some(pi), Some(info)) = (&pi, &info) {
1236 attempt = pi.finish(orb, info, attempt, reply_contexts);
1237 }
1238 if let Attempt::Resend = attempt {
1239 if resent + 1 < CLOSED_ATTEMPTS {
1240 again = Some((ep, resent + 1));
1241 continue;
1242 }
1243 attempt =
1244 Attempt::NotSent(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No));
1245 }
1246 if let Some(result) = walk.record(attempt) {
1247 return traced(kind, result);
1248 }
1249 }
1250}
1251
1252fn traced<A: WriteArgs + ?Sized>(
1254 kind: &Kind<'_, A>,
1255 result: Result<Outcome, Exception>,
1256) -> Result<Outcome, Exception> {
1257 if let Err(Exception::System(e)) = &result {
1258 trace::debug!("{} raised {e}", KindName(kind));
1259 }
1260 result
1261}
1262
1263struct KindName<'a, 'k, A: ?Sized>(&'a Kind<'k, A>);
1265
1266impl<A: ?Sized> fmt::Display for KindName<'_, '_, A> {
1267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1268 match self.0 {
1269 Kind::Request { operation, .. } => write!(f, "request {operation:?}"),
1270 Kind::Locate => f.write_str("LocateRequest"),
1271 }
1272 }
1273}
1274
1275const CANCEL_SEND_TIME: Duration = Duration::from_millis(100);
1277
1278const CLOSED_ATTEMPTS: usize = 4;
1283
1284async fn attempt<A: WriteArgs + ?Sized>(
1291 orb: &Orb,
1292 ior: &Ior,
1293 ep: &Endpoint,
1294 kind: &Kind<'_, A>,
1295 mut x: Exchange<'_>,
1296) -> Attempt {
1297 let deadline = x.deadline;
1298 let mut result = Attempt::NotSent(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No));
1299 for _ in 0..CLOSED_ATTEMPTS {
1300 let conn = match orb
1301 .connection(&ep.host, ep.port, ep.transport, deadline)
1302 .await
1303 {
1304 Ok(conn) => conn,
1305 Err(e) if e.is(SystemExceptionKind::TIMEOUT) => return Attempt::Done(Err(e.into())),
1307 Err(e) => return Attempt::NotSent(e),
1308 };
1309 match attempt_on(orb, &conn, ior, ep, kind, &mut x).await {
1310 Ok(done) => return done,
1311 Err(Closed::Orderly) => {
1312 orb.discard(&conn);
1313 if !x.resend {
1314 return Attempt::Resend;
1315 }
1316 result =
1317 Attempt::NotSent(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No));
1318 }
1319 Err(Closed::Failed(_)) => {
1320 orb.discard(&conn);
1321 return Attempt::Done(Err(sys(
1322 SystemExceptionKind::COMM_FAILURE,
1323 0,
1324 CompletionStatus::Maybe,
1325 )
1326 .into()));
1327 }
1328 }
1329 }
1330 result
1331}
1332
1333async fn attempt_on<A: WriteArgs + ?Sized>(
1336 orb: &Orb,
1337 conn: &Arc<Connection>,
1338 ior: &Ior,
1339 ep: &Endpoint,
1340 kind: &Kind<'_, A>,
1341 x: &mut Exchange<'_>,
1342) -> Result<Attempt, Closed> {
1343 let (deadline, disposition, own_thread) = (x.deadline, x.disposition, x.own_thread);
1344 let options = &orb.inner.options;
1345 let order = options.byte_order;
1346 let version = ep.version.min(options.max_giop_version);
1347 let target = target_address(ior, ep, version, disposition);
1348
1349 let (code_sets, context) = match (&ep.code_sets, version >= Version::V1_1) {
1352 (Some(info), true) => {
1353 let proposed = match conn.code_sets() {
1354 Some(cs) => cs,
1355 None => match CodeSets::negotiate(info) {
1356 Ok(cs) => cs,
1357 Err(e) => return Ok(Attempt::Done(Err(e.into()))),
1358 },
1359 };
1360 let cs = conn.claim_code_sets(proposed);
1361 (cs, vec![cs.context().to_service_context(order)])
1362 }
1363 _ => (CodeSets::DEFAULT, Vec::new()),
1364 };
1365 let mut context = context;
1366 context.extend_from_slice(x.contexts);
1367 let offer = version >= Version::V1_2 && matches!(kind, Kind::Request { .. });
1369 let offer = offer
1370 && conn.bidir_context().is_some_and(|c| {
1371 context.push(c.clone());
1372 true
1373 });
1374
1375 let request_id = conn.next_request_id();
1376 let flags = flags_of(kind);
1377 let response = flags & 0x01 != 0;
1380 let detached = matches!(
1382 kind,
1383 Kind::Request {
1384 response: false,
1385 sync: sync_scope::SYNC_NONE,
1386 ..
1387 }
1388 );
1389 let msg = match kind {
1390 Kind::Request {
1391 operation, args, ..
1392 } => {
1393 let header = request_header(request_id, flags, target, operation, context);
1394 match encode_request(version, order, &header, *args, code_sets) {
1395 Ok(msg) if msg.len() > options.max_message_size => {
1396 trace::warning!(
1397 "request {operation:?} of {} bytes is over the largest GIOP message \
1398 ({} bytes, -ORBgiopMaxMsgSize): not sent",
1399 msg.len(),
1400 options.max_message_size
1401 );
1402 return Ok(Attempt::Done(Err(sys(
1403 SystemExceptionKind::MARSHAL,
1404 0,
1405 CompletionStatus::No,
1406 )
1407 .into())));
1408 }
1409 Ok(msg) if options.fragment_size > 0 => msg.fragment(options.fragment_size),
1410 Ok(msg) => msg,
1411 Err(e) => return Ok(Attempt::Done(Err(e))),
1412 }
1413 }
1414 Kind::Locate => match MessageEncoder::locate_request(
1415 version,
1416 order,
1417 &LocateRequestHeader { request_id, target },
1418 ) {
1419 Ok(msg) => msg.into(),
1420 Err(_) => {
1421 return Ok(Attempt::Done(Err(sys(
1422 SystemExceptionKind::MARSHAL,
1423 0,
1424 CompletionStatus::No,
1425 )
1426 .into())));
1427 }
1428 },
1429 };
1430
1431 trace::debug!(
1432 "{} (id {request_id}{}) to {}:{}, GIOP {}.{}",
1433 KindName(kind),
1434 OnewayNote(kind),
1435 ep.host,
1436 ep.port,
1437 version.major,
1438 version.minor
1439 );
1440 let rx = if response {
1441 match conn.expect_reply(request_id) {
1442 Ok(rx) => Some(rx),
1443 Err(Closed::Orderly) => return Err(Closed::Orderly),
1444 Err(Closed::Failed(_)) => {
1446 orb.discard(conn);
1447 return Ok(Attempt::NotSent(sys(
1448 SystemExceptionKind::COMM_FAILURE,
1449 0,
1450 CompletionStatus::No,
1451 )));
1452 }
1453 }
1454 } else {
1455 None
1456 };
1457 if detached {
1458 let (orb, conn) = (orb.clone(), Arc::clone(conn));
1461 orb.inner.handle.clone().spawn(async move {
1462 match conn.send(&msg, deadline).await {
1463 Ok(()) if offer => conn.offered(),
1464 Ok(()) => {}
1465 Err(e) => {
1466 trace::debug!("oneway request (id {request_id}, SYNC_NONE) not sent: {e:?}");
1467 if matches!(e, SendError::Failed) || !conn.is_usable() {
1468 orb.discard(&conn);
1469 }
1470 }
1471 }
1472 });
1473 return Ok(Attempt::Done(Ok(Outcome::Reply(None))));
1474 }
1475 match conn.send(&msg, deadline).await {
1476 Ok(()) if offer => conn.offered(),
1477 Ok(()) => {}
1478 Err(SendError::TimedOut) => {
1481 conn.forget(request_id);
1482 if !conn.is_usable() {
1483 orb.discard(conn);
1484 }
1485 return Ok(Attempt::Done(Err(sys(
1486 SystemExceptionKind::TIMEOUT,
1487 0,
1488 CompletionStatus::No,
1489 )
1490 .into())));
1491 }
1492 Err(SendError::Closing) => {
1494 conn.forget(request_id);
1495 return Err(Closed::Orderly);
1496 }
1497 Err(SendError::Failed) => {
1498 conn.forget(request_id);
1499 orb.discard(conn);
1500 return Ok(Attempt::NotSent(sys(
1501 SystemExceptionKind::COMM_FAILURE,
1502 0,
1503 CompletionStatus::No,
1504 )));
1505 }
1506 }
1507 let Some(rx) = rx else {
1508 return Ok(Attempt::Done(Ok(Outcome::Reply(None))));
1509 };
1510
1511 let here = if own_thread {
1514 conn.read_reply_here(request_id, deadline)
1515 } else {
1516 None
1517 };
1518 let delivered = match here {
1519 Some(Some(message)) => Some(Ok(Ok(message))),
1520 Some(None) => None,
1521 None => match deadline {
1522 Some(at) => tokio::time::timeout_at(at.into(), rx).await.ok(),
1523 None => Some(rx.await),
1524 },
1525 };
1526 let delivered = match delivered {
1527 Some(delivered) => delivered,
1528 None => {
1529 trace::debug!("{} (id {request_id}) timed out", KindName(kind));
1530 conn.forget(request_id);
1531 if let Ok(cancel) =
1532 MessageEncoder::cancel_request(version, order, &CancelRequestHeader { request_id })
1533 {
1534 let at = Instant::now() + CANCEL_SEND_TIME;
1537 let _ = conn.send(&cancel.into(), Some(at)).await;
1538 }
1539 return Ok(Attempt::Done(Err(sys(
1540 SystemExceptionKind::TIMEOUT,
1541 0,
1542 CompletionStatus::Maybe,
1543 )
1544 .into())));
1545 }
1546 };
1547 let message = match delivered {
1548 Ok(Ok(message)) => message,
1549 Ok(Err(closed)) => return Err(closed),
1550 Err(_) => return Err(Closed::Failed("reply channel dropped".into())),
1551 };
1552 Ok(match message {
1553 Message::Reply { header, body } => {
1554 if !matches!(kind, Kind::Request { .. }) {
1555 return Err(Closed::Failed("Reply to a LocateRequest".into()));
1556 }
1557 *x.reply_contexts = header.service_context;
1558 trace::debug!(
1559 "reply to {} (id {request_id}): {:?}",
1560 KindName(kind),
1561 header.reply_status
1562 );
1563 reply_outcome(orb, header.reply_status, body, code_sets)
1564 }
1565 Message::LocateReply { header, body } => {
1566 if !matches!(kind, Kind::Locate) {
1567 return Err(Closed::Failed("LocateReply to a Request".into()));
1568 }
1569 trace::debug!("LocateReply (id {request_id}): {:?}", header.locate_status);
1570 locate_outcome(header.locate_status, &body)
1571 }
1572 _ => return Err(Closed::Failed("unexpected message".into())),
1573 })
1574}
1575
1576fn target_address(
1579 ior: &Ior,
1580 ep: &Endpoint,
1581 version: Version,
1582 disposition: AddressingDisposition,
1583) -> TargetAddress {
1584 if version < Version::V1_2 {
1585 return TargetAddress::Key(ep.object_key.clone());
1586 }
1587 match disposition {
1588 AddressingDisposition::Key => TargetAddress::Key(ep.object_key.clone()),
1589 AddressingDisposition::Profile => {
1590 TargetAddress::Profile(ior.profiles[ep.profile_index].clone())
1591 }
1592 AddressingDisposition::Reference => TargetAddress::Reference {
1593 selected_profile_index: ep.profile_index as u32,
1594 ior: ior.clone(),
1595 },
1596 }
1597}
1598
1599fn flags_of<A: ?Sized>(kind: &Kind<'_, A>) -> u8 {
1604 match *kind {
1605 Kind::Request { response: true, .. } | Kind::Locate => response_flags::SYNC_WITH_TARGET,
1606 Kind::Request { sync, .. } => match sync {
1607 sync_scope::SYNC_WITH_TARGET => response_flags::SYNC_WITH_TARGET,
1608 sync_scope::SYNC_WITH_SERVER => response_flags::SYNC_WITH_SERVER,
1609 _ => response_flags::NONE,
1610 },
1611 }
1612}
1613
1614struct OnewayNote<'a, 'k, A: ?Sized>(&'a Kind<'k, A>);
1616
1617impl<A: ?Sized> fmt::Display for OnewayNote<'_, '_, A> {
1618 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1619 match *self.0 {
1620 Kind::Request {
1621 response: false,
1622 sync,
1623 ..
1624 } => {
1625 let name = match sync {
1626 sync_scope::SYNC_NONE => "SYNC_NONE",
1627 sync_scope::SYNC_WITH_SERVER => "SYNC_WITH_SERVER",
1628 sync_scope::SYNC_WITH_TARGET => "SYNC_WITH_TARGET",
1629 _ => "SYNC_WITH_TRANSPORT",
1630 };
1631 write!(f, ", oneway {name}")
1632 }
1633 _ => Ok(()),
1634 }
1635 }
1636}
1637
1638fn without_reply<A: ?Sized>(kind: &Kind<'_, A>, attempt: Attempt) -> Attempt {
1642 match (kind, attempt) {
1643 (
1644 Kind::Request {
1645 response: false, ..
1646 },
1647 Attempt::Done(Ok(Outcome::Reply(Some(_)))),
1648 ) => Attempt::Done(Ok(Outcome::Reply(None))),
1649 (_, attempt) => attempt,
1650 }
1651}
1652
1653fn request_header(
1654 request_id: u32,
1655 flags: u8,
1656 target: TargetAddress,
1657 operation: &str,
1658 service_context: Vec<rustorb_giop::ServiceContext>,
1659) -> RequestHeader {
1660 RequestHeader {
1661 request_id,
1662 response_flags: flags,
1663 target,
1664 operation: operation.to_owned(),
1665 service_context,
1666 requesting_principal: Vec::new(),
1667 }
1668}
1669
1670fn encode_request<A: WriteArgs + ?Sized>(
1672 version: Version,
1673 order: rustorb_cdr::ByteOrder,
1674 header: &RequestHeader,
1675 args: Option<&A>,
1676 code_sets: CodeSets,
1677) -> Result<OutMessage, Exception> {
1678 let marshal = || sys(SystemExceptionKind::MARSHAL, 0, CompletionStatus::No).into();
1679 let mut m = MessageEncoder::request(version, order, header).map_err(|_| marshal())?;
1680 if let Some(args) = args {
1681 let mut out = OutStream {
1682 enc: m.body(),
1683 code_sets,
1684 orb: None,
1685 values: None,
1686 };
1687 args.write_args(&mut out)?;
1688 }
1689 m.finish_shared().map_err(|_| marshal())
1690}
1691
1692enum LocalCall {
1697 Locate(TargetAddress),
1698 Request {
1699 version: Version,
1700 header: RequestHeader,
1701 body: Body,
1702 code_sets: CodeSets,
1703 timeout: Option<Duration>,
1704 },
1705}
1706
1707enum LocalAnswer {
1709 Located(bool),
1710 Reply(Option<Vec<u8>>, CodeSets),
1712}
1713
1714fn local_call<A: WriteArgs + ?Sized>(
1716 orb: &Orb,
1717 ior: &Ior,
1718 ep: &Endpoint,
1719 kind: &Kind<'_, A>,
1720 deadline: Option<Instant>,
1721 disposition: AddressingDisposition,
1722 contexts: &[ServiceContext],
1723) -> Result<LocalCall, Attempt> {
1724 let options = &orb.inner.options;
1725 let order = options.byte_order;
1726 let version = ep.version.min(options.max_giop_version);
1727 let target = target_address(ior, ep, version, disposition);
1728 let (code_sets, mut context) = match (&ep.code_sets, version >= Version::V1_1) {
1729 (Some(info), true) => match CodeSets::negotiate(info) {
1730 Ok(cs) => (cs, vec![cs.context().to_service_context(order)]),
1731 Err(e) => return Err(Attempt::Done(Err(e.into()))),
1732 },
1733 _ => (CodeSets::DEFAULT, Vec::new()),
1734 };
1735 context.extend_from_slice(contexts);
1736 let flags = flags_of(kind);
1737 let (operation, args) = match kind {
1738 Kind::Locate => return Ok(LocalCall::Locate(target)),
1739 Kind::Request {
1740 operation, args, ..
1741 } => (*operation, *args),
1742 };
1743 trace::debug!(
1744 "request {operation:?}{} to this ORB's own object (colocated)",
1745 OnewayNote(kind)
1746 );
1747 let header = request_header(0, flags, target, operation, context);
1748 let msg = match encode_request(version, order, &header, args, code_sets) {
1749 Ok(msg) => msg.into_vec(),
1750 Err(e) => return Err(Attempt::Done(Err(e))),
1751 };
1752 let Ok((_, Message::Request { header, body })) = decode_message(&msg) else {
1753 return Err(Attempt::Done(Err(local_internal())));
1754 };
1755 let timeout = deadline.map(|at| at.saturating_duration_since(Instant::now()));
1756 Ok(LocalCall::Request {
1757 version,
1758 header,
1759 body,
1760 code_sets,
1761 timeout,
1762 })
1763}
1764
1765impl LocalCall {
1766 fn run(self, server: &Arc<Server>) -> Result<LocalAnswer, SystemException> {
1768 match self {
1769 LocalCall::Locate(target) => server.locate_local(&target).map(LocalAnswer::Located),
1770 LocalCall::Request {
1771 version,
1772 header,
1773 body,
1774 code_sets,
1775 timeout,
1776 } => server
1777 .call_local(version, header, body, code_sets, timeout)
1778 .map(|reply| LocalAnswer::Reply(reply, code_sets)),
1779 }
1780 }
1781}
1782
1783fn local_outcome(
1784 orb: &Orb,
1785 answer: Result<LocalAnswer, SystemException>,
1786 reply_contexts: &mut Vec<ServiceContext>,
1787) -> Attempt {
1788 match answer {
1789 Ok(LocalAnswer::Located(here)) => Attempt::Done(Ok(Outcome::Located(here))),
1790 Ok(LocalAnswer::Reply(None, _)) => Attempt::Done(Ok(Outcome::Reply(None))),
1791 Ok(LocalAnswer::Reply(Some(reply), code_sets)) => match decode_message(&reply) {
1792 Ok((_, Message::Reply { header, body })) => {
1793 *reply_contexts = header.service_context;
1794 reply_outcome(orb, header.reply_status, body, code_sets)
1795 }
1796 _ => Attempt::Done(Err(local_internal())),
1797 },
1798 Err(e) => Attempt::Done(Err(e.into())),
1799 }
1800}
1801
1802fn local_internal() -> Exception {
1803 sys(SystemExceptionKind::INTERNAL, 0, CompletionStatus::Maybe).into()
1804}
1805
1806fn reply_outcome(orb: &Orb, status: ReplyStatus, body: Body, code_sets: CodeSets) -> Attempt {
1807 match status {
1808 ReplyStatus::NoException => Attempt::Done(Ok(Outcome::Reply(Some(Reply {
1809 body,
1810 code_sets,
1811 orb: orb.clone(),
1812 })))),
1813 ReplyStatus::UserException => {
1814 let reply = Reply {
1815 body,
1816 code_sets,
1817 orb: orb.clone(),
1818 };
1819 let id = reply.input().read_string();
1820 Attempt::Done(Err(match id {
1821 Ok(repository_id) => Exception::User(UserException {
1822 repository_id,
1823 reply,
1824 }),
1825 Err(e) => Exception::System(e),
1826 }))
1827 }
1828 ReplyStatus::SystemException => {
1829 let mut dec = body.decoder();
1830 Attempt::Done(Err(match SystemExceptionBody::decode(&mut dec) {
1831 Ok(e) => Exception::System(e.into()),
1832 Err(e) => Exception::System(marshal(e)),
1833 }))
1834 }
1835 ReplyStatus::LocationForward | ReplyStatus::LocationForwardPerm => forward(&body),
1836 ReplyStatus::NeedsAddressingMode => addressing(&body),
1837 }
1838}
1839
1840fn locate_outcome(status: LocateStatus, body: &Body) -> Attempt {
1841 match status {
1842 LocateStatus::ObjectHere => Attempt::Done(Ok(Outcome::Located(true))),
1843 LocateStatus::UnknownObject => Attempt::Done(Ok(Outcome::Located(false))),
1844 LocateStatus::ObjectForward | LocateStatus::ObjectForwardPerm => forward(body),
1845 LocateStatus::LocSystemException => {
1846 let mut dec = body.decoder();
1847 Attempt::Done(Err(match SystemExceptionBody::decode(&mut dec) {
1848 Ok(e) => Exception::System(e.into()),
1849 Err(e) => Exception::System(marshal(e)),
1850 }))
1851 }
1852 LocateStatus::LocNeedsAddressingMode => addressing(body),
1853 }
1854}
1855
1856fn forward(body: &Body) -> Attempt {
1857 let mut dec = body.decoder();
1858 match Ior::decode(&mut dec) {
1859 Ok(ior) if !ior.is_nil() => Attempt::Forward(ior),
1860 Ok(_) => Attempt::Done(Err(sys(
1861 SystemExceptionKind::INV_OBJREF,
1862 0,
1863 CompletionStatus::No,
1864 )
1865 .into())),
1866 Err(e) => Attempt::Done(Err(Exception::System(marshal(e)))),
1867 }
1868}
1869
1870fn addressing(body: &Body) -> Attempt {
1871 let mut dec = body.decoder();
1872 match dec
1873 .read_i16()
1874 .ok()
1875 .and_then(|d| AddressingDisposition::from_i16(d).ok())
1876 {
1877 Some(d) => Attempt::Addressing(d),
1878 None => Attempt::Done(Err(sys(
1879 SystemExceptionKind::MARSHAL,
1880 0,
1881 CompletionStatus::No,
1882 )
1883 .into())),
1884 }
1885}