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 result = rx.await.unwrap_or_else(|_| {
1197 Err(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No))
1198 });
1199 local_outcome(orb, result, &mut reply_contexts)
1200 }
1201 Err(done) => done,
1202 }
1203 }
1204 None => {
1205 attempt(
1206 orb,
1207 &ior,
1208 &ep,
1209 kind,
1210 Exchange {
1211 deadline,
1212 disposition,
1213 own_thread: false,
1214 resend: info.is_none(),
1215 contexts: &contexts,
1216 reply_contexts: &mut reply_contexts,
1217 },
1218 )
1219 .await
1220 }
1221 };
1222 attempt = without_reply(kind, attempt);
1223 if let (Some(pi), Some(info)) = (&pi, &info) {
1224 attempt = pi.finish(orb, info, attempt, reply_contexts);
1225 }
1226 if let Attempt::Resend = attempt {
1227 if resent + 1 < CLOSED_ATTEMPTS {
1228 again = Some((ep, resent + 1));
1229 continue;
1230 }
1231 attempt =
1232 Attempt::NotSent(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No));
1233 }
1234 if let Some(result) = walk.record(attempt) {
1235 return traced(kind, result);
1236 }
1237 }
1238}
1239
1240fn traced<A: WriteArgs + ?Sized>(
1242 kind: &Kind<'_, A>,
1243 result: Result<Outcome, Exception>,
1244) -> Result<Outcome, Exception> {
1245 if let Err(Exception::System(e)) = &result {
1246 trace::debug!("{} raised {e}", KindName(kind));
1247 }
1248 result
1249}
1250
1251struct KindName<'a, 'k, A: ?Sized>(&'a Kind<'k, A>);
1253
1254impl<A: ?Sized> fmt::Display for KindName<'_, '_, A> {
1255 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1256 match self.0 {
1257 Kind::Request { operation, .. } => write!(f, "request {operation:?}"),
1258 Kind::Locate => f.write_str("LocateRequest"),
1259 }
1260 }
1261}
1262
1263const CANCEL_SEND_TIME: Duration = Duration::from_millis(100);
1265
1266const CLOSED_ATTEMPTS: usize = 4;
1271
1272async fn attempt<A: WriteArgs + ?Sized>(
1279 orb: &Orb,
1280 ior: &Ior,
1281 ep: &Endpoint,
1282 kind: &Kind<'_, A>,
1283 mut x: Exchange<'_>,
1284) -> Attempt {
1285 let deadline = x.deadline;
1286 let mut result = Attempt::NotSent(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No));
1287 for _ in 0..CLOSED_ATTEMPTS {
1288 let conn = match orb
1289 .connection(&ep.host, ep.port, ep.transport, deadline)
1290 .await
1291 {
1292 Ok(conn) => conn,
1293 Err(e) if e.is(SystemExceptionKind::TIMEOUT) => return Attempt::Done(Err(e.into())),
1295 Err(e) => return Attempt::NotSent(e),
1296 };
1297 match attempt_on(orb, &conn, ior, ep, kind, &mut x).await {
1298 Ok(done) => return done,
1299 Err(Closed::Orderly) => {
1300 orb.discard(&conn);
1301 if !x.resend {
1302 return Attempt::Resend;
1303 }
1304 result =
1305 Attempt::NotSent(sys(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No));
1306 }
1307 Err(Closed::Failed(_)) => {
1308 orb.discard(&conn);
1309 return Attempt::Done(Err(sys(
1310 SystemExceptionKind::COMM_FAILURE,
1311 0,
1312 CompletionStatus::Maybe,
1313 )
1314 .into()));
1315 }
1316 }
1317 }
1318 result
1319}
1320
1321async fn attempt_on<A: WriteArgs + ?Sized>(
1324 orb: &Orb,
1325 conn: &Arc<Connection>,
1326 ior: &Ior,
1327 ep: &Endpoint,
1328 kind: &Kind<'_, A>,
1329 x: &mut Exchange<'_>,
1330) -> Result<Attempt, Closed> {
1331 let (deadline, disposition, own_thread) = (x.deadline, x.disposition, x.own_thread);
1332 let options = &orb.inner.options;
1333 let order = options.byte_order;
1334 let version = ep.version.min(options.max_giop_version);
1335 let target = target_address(ior, ep, version, disposition);
1336
1337 let (code_sets, context) = match (&ep.code_sets, version >= Version::V1_1) {
1340 (Some(info), true) => {
1341 let proposed = match conn.code_sets() {
1342 Some(cs) => cs,
1343 None => match CodeSets::negotiate(info) {
1344 Ok(cs) => cs,
1345 Err(e) => return Ok(Attempt::Done(Err(e.into()))),
1346 },
1347 };
1348 let cs = conn.claim_code_sets(proposed);
1349 (cs, vec![cs.context().to_service_context(order)])
1350 }
1351 _ => (CodeSets::DEFAULT, Vec::new()),
1352 };
1353 let mut context = context;
1354 context.extend_from_slice(x.contexts);
1355 let offer = version >= Version::V1_2 && matches!(kind, Kind::Request { .. });
1357 let offer = offer
1358 && conn.bidir_context().is_some_and(|c| {
1359 context.push(c.clone());
1360 true
1361 });
1362
1363 let request_id = conn.next_request_id();
1364 let flags = flags_of(kind);
1365 let response = flags & 0x01 != 0;
1368 let detached = matches!(
1370 kind,
1371 Kind::Request {
1372 response: false,
1373 sync: sync_scope::SYNC_NONE,
1374 ..
1375 }
1376 );
1377 let msg = match kind {
1378 Kind::Request {
1379 operation, args, ..
1380 } => {
1381 let header = request_header(request_id, flags, target, operation, context);
1382 match encode_request(version, order, &header, *args, code_sets) {
1383 Ok(msg) if msg.len() > options.max_message_size => {
1384 trace::warning!(
1385 "request {operation:?} of {} bytes is over the largest GIOP message \
1386 ({} bytes, -ORBgiopMaxMsgSize): not sent",
1387 msg.len(),
1388 options.max_message_size
1389 );
1390 return Ok(Attempt::Done(Err(sys(
1391 SystemExceptionKind::MARSHAL,
1392 0,
1393 CompletionStatus::No,
1394 )
1395 .into())));
1396 }
1397 Ok(msg) if options.fragment_size > 0 => msg.fragment(options.fragment_size),
1398 Ok(msg) => msg,
1399 Err(e) => return Ok(Attempt::Done(Err(e))),
1400 }
1401 }
1402 Kind::Locate => match MessageEncoder::locate_request(
1403 version,
1404 order,
1405 &LocateRequestHeader { request_id, target },
1406 ) {
1407 Ok(msg) => msg.into(),
1408 Err(_) => {
1409 return Ok(Attempt::Done(Err(sys(
1410 SystemExceptionKind::MARSHAL,
1411 0,
1412 CompletionStatus::No,
1413 )
1414 .into())));
1415 }
1416 },
1417 };
1418
1419 trace::debug!(
1420 "{} (id {request_id}{}) to {}:{}, GIOP {}.{}",
1421 KindName(kind),
1422 OnewayNote(kind),
1423 ep.host,
1424 ep.port,
1425 version.major,
1426 version.minor
1427 );
1428 let rx = if response {
1429 match conn.expect_reply(request_id) {
1430 Ok(rx) => Some(rx),
1431 Err(Closed::Orderly) => return Err(Closed::Orderly),
1432 Err(Closed::Failed(_)) => {
1434 orb.discard(conn);
1435 return Ok(Attempt::NotSent(sys(
1436 SystemExceptionKind::COMM_FAILURE,
1437 0,
1438 CompletionStatus::No,
1439 )));
1440 }
1441 }
1442 } else {
1443 None
1444 };
1445 if detached {
1446 let (orb, conn) = (orb.clone(), Arc::clone(conn));
1449 orb.inner.handle.clone().spawn(async move {
1450 match conn.send(&msg, deadline).await {
1451 Ok(()) if offer => conn.offered(),
1452 Ok(()) => {}
1453 Err(e) => {
1454 trace::debug!("oneway request (id {request_id}, SYNC_NONE) not sent: {e:?}");
1455 if matches!(e, SendError::Failed) || !conn.is_usable() {
1456 orb.discard(&conn);
1457 }
1458 }
1459 }
1460 });
1461 return Ok(Attempt::Done(Ok(Outcome::Reply(None))));
1462 }
1463 match conn.send(&msg, deadline).await {
1464 Ok(()) if offer => conn.offered(),
1465 Ok(()) => {}
1466 Err(SendError::TimedOut) => {
1469 conn.forget(request_id);
1470 if !conn.is_usable() {
1471 orb.discard(conn);
1472 }
1473 return Ok(Attempt::Done(Err(sys(
1474 SystemExceptionKind::TIMEOUT,
1475 0,
1476 CompletionStatus::No,
1477 )
1478 .into())));
1479 }
1480 Err(SendError::Closing) => {
1482 conn.forget(request_id);
1483 return Err(Closed::Orderly);
1484 }
1485 Err(SendError::Failed) => {
1486 conn.forget(request_id);
1487 orb.discard(conn);
1488 return Ok(Attempt::NotSent(sys(
1489 SystemExceptionKind::COMM_FAILURE,
1490 0,
1491 CompletionStatus::No,
1492 )));
1493 }
1494 }
1495 let Some(rx) = rx else {
1496 return Ok(Attempt::Done(Ok(Outcome::Reply(None))));
1497 };
1498
1499 let here = if own_thread {
1502 conn.read_reply_here(request_id, deadline)
1503 } else {
1504 None
1505 };
1506 let delivered = match here {
1507 Some(Some(message)) => Some(Ok(Ok(message))),
1508 Some(None) => None,
1509 None => match deadline {
1510 Some(at) => tokio::time::timeout_at(at.into(), rx).await.ok(),
1511 None => Some(rx.await),
1512 },
1513 };
1514 let delivered = match delivered {
1515 Some(delivered) => delivered,
1516 None => {
1517 trace::debug!("{} (id {request_id}) timed out", KindName(kind));
1518 conn.forget(request_id);
1519 if let Ok(cancel) =
1520 MessageEncoder::cancel_request(version, order, &CancelRequestHeader { request_id })
1521 {
1522 let at = Instant::now() + CANCEL_SEND_TIME;
1525 let _ = conn.send(&cancel.into(), Some(at)).await;
1526 }
1527 return Ok(Attempt::Done(Err(sys(
1528 SystemExceptionKind::TIMEOUT,
1529 0,
1530 CompletionStatus::Maybe,
1531 )
1532 .into())));
1533 }
1534 };
1535 let message = match delivered {
1536 Ok(Ok(message)) => message,
1537 Ok(Err(closed)) => return Err(closed),
1538 Err(_) => return Err(Closed::Failed("reply channel dropped".into())),
1539 };
1540 Ok(match message {
1541 Message::Reply { header, body } => {
1542 if !matches!(kind, Kind::Request { .. }) {
1543 return Err(Closed::Failed("Reply to a LocateRequest".into()));
1544 }
1545 *x.reply_contexts = header.service_context;
1546 trace::debug!(
1547 "reply to {} (id {request_id}): {:?}",
1548 KindName(kind),
1549 header.reply_status
1550 );
1551 reply_outcome(orb, header.reply_status, body, code_sets)
1552 }
1553 Message::LocateReply { header, body } => {
1554 if !matches!(kind, Kind::Locate) {
1555 return Err(Closed::Failed("LocateReply to a Request".into()));
1556 }
1557 trace::debug!("LocateReply (id {request_id}): {:?}", header.locate_status);
1558 locate_outcome(header.locate_status, &body)
1559 }
1560 _ => return Err(Closed::Failed("unexpected message".into())),
1561 })
1562}
1563
1564fn target_address(
1567 ior: &Ior,
1568 ep: &Endpoint,
1569 version: Version,
1570 disposition: AddressingDisposition,
1571) -> TargetAddress {
1572 if version < Version::V1_2 {
1573 return TargetAddress::Key(ep.object_key.clone());
1574 }
1575 match disposition {
1576 AddressingDisposition::Key => TargetAddress::Key(ep.object_key.clone()),
1577 AddressingDisposition::Profile => {
1578 TargetAddress::Profile(ior.profiles[ep.profile_index].clone())
1579 }
1580 AddressingDisposition::Reference => TargetAddress::Reference {
1581 selected_profile_index: ep.profile_index as u32,
1582 ior: ior.clone(),
1583 },
1584 }
1585}
1586
1587fn flags_of<A: ?Sized>(kind: &Kind<'_, A>) -> u8 {
1592 match *kind {
1593 Kind::Request { response: true, .. } | Kind::Locate => response_flags::SYNC_WITH_TARGET,
1594 Kind::Request { sync, .. } => match sync {
1595 sync_scope::SYNC_WITH_TARGET => response_flags::SYNC_WITH_TARGET,
1596 sync_scope::SYNC_WITH_SERVER => response_flags::SYNC_WITH_SERVER,
1597 _ => response_flags::NONE,
1598 },
1599 }
1600}
1601
1602struct OnewayNote<'a, 'k, A: ?Sized>(&'a Kind<'k, A>);
1604
1605impl<A: ?Sized> fmt::Display for OnewayNote<'_, '_, A> {
1606 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1607 match *self.0 {
1608 Kind::Request {
1609 response: false,
1610 sync,
1611 ..
1612 } => {
1613 let name = match sync {
1614 sync_scope::SYNC_NONE => "SYNC_NONE",
1615 sync_scope::SYNC_WITH_SERVER => "SYNC_WITH_SERVER",
1616 sync_scope::SYNC_WITH_TARGET => "SYNC_WITH_TARGET",
1617 _ => "SYNC_WITH_TRANSPORT",
1618 };
1619 write!(f, ", oneway {name}")
1620 }
1621 _ => Ok(()),
1622 }
1623 }
1624}
1625
1626fn without_reply<A: ?Sized>(kind: &Kind<'_, A>, attempt: Attempt) -> Attempt {
1630 match (kind, attempt) {
1631 (
1632 Kind::Request {
1633 response: false, ..
1634 },
1635 Attempt::Done(Ok(Outcome::Reply(Some(_)))),
1636 ) => Attempt::Done(Ok(Outcome::Reply(None))),
1637 (_, attempt) => attempt,
1638 }
1639}
1640
1641fn request_header(
1642 request_id: u32,
1643 flags: u8,
1644 target: TargetAddress,
1645 operation: &str,
1646 service_context: Vec<rustorb_giop::ServiceContext>,
1647) -> RequestHeader {
1648 RequestHeader {
1649 request_id,
1650 response_flags: flags,
1651 target,
1652 operation: operation.to_owned(),
1653 service_context,
1654 requesting_principal: Vec::new(),
1655 }
1656}
1657
1658fn encode_request<A: WriteArgs + ?Sized>(
1660 version: Version,
1661 order: rustorb_cdr::ByteOrder,
1662 header: &RequestHeader,
1663 args: Option<&A>,
1664 code_sets: CodeSets,
1665) -> Result<OutMessage, Exception> {
1666 let marshal = || sys(SystemExceptionKind::MARSHAL, 0, CompletionStatus::No).into();
1667 let mut m = MessageEncoder::request(version, order, header).map_err(|_| marshal())?;
1668 if let Some(args) = args {
1669 let mut out = OutStream {
1670 enc: m.body(),
1671 code_sets,
1672 orb: None,
1673 values: None,
1674 };
1675 args.write_args(&mut out)?;
1676 }
1677 m.finish_shared().map_err(|_| marshal())
1678}
1679
1680enum LocalCall {
1685 Locate(TargetAddress),
1686 Request {
1687 version: Version,
1688 header: RequestHeader,
1689 body: Body,
1690 code_sets: CodeSets,
1691 timeout: Option<Duration>,
1692 },
1693}
1694
1695enum LocalAnswer {
1697 Located(bool),
1698 Reply(Option<Vec<u8>>, CodeSets),
1700}
1701
1702fn local_call<A: WriteArgs + ?Sized>(
1704 orb: &Orb,
1705 ior: &Ior,
1706 ep: &Endpoint,
1707 kind: &Kind<'_, A>,
1708 deadline: Option<Instant>,
1709 disposition: AddressingDisposition,
1710 contexts: &[ServiceContext],
1711) -> Result<LocalCall, Attempt> {
1712 let options = &orb.inner.options;
1713 let order = options.byte_order;
1714 let version = ep.version.min(options.max_giop_version);
1715 let target = target_address(ior, ep, version, disposition);
1716 let (code_sets, mut context) = match (&ep.code_sets, version >= Version::V1_1) {
1717 (Some(info), true) => match CodeSets::negotiate(info) {
1718 Ok(cs) => (cs, vec![cs.context().to_service_context(order)]),
1719 Err(e) => return Err(Attempt::Done(Err(e.into()))),
1720 },
1721 _ => (CodeSets::DEFAULT, Vec::new()),
1722 };
1723 context.extend_from_slice(contexts);
1724 let flags = flags_of(kind);
1725 let (operation, args) = match kind {
1726 Kind::Locate => return Ok(LocalCall::Locate(target)),
1727 Kind::Request {
1728 operation, args, ..
1729 } => (*operation, *args),
1730 };
1731 trace::debug!(
1732 "request {operation:?}{} to this ORB's own object (colocated)",
1733 OnewayNote(kind)
1734 );
1735 let header = request_header(0, flags, target, operation, context);
1736 let msg = match encode_request(version, order, &header, args, code_sets) {
1737 Ok(msg) => msg.into_vec(),
1738 Err(e) => return Err(Attempt::Done(Err(e))),
1739 };
1740 let Ok((_, Message::Request { header, body })) = decode_message(&msg) else {
1741 return Err(Attempt::Done(Err(local_internal())));
1742 };
1743 let timeout = deadline.map(|at| at.saturating_duration_since(Instant::now()));
1744 Ok(LocalCall::Request {
1745 version,
1746 header,
1747 body,
1748 code_sets,
1749 timeout,
1750 })
1751}
1752
1753impl LocalCall {
1754 fn run(self, server: &Arc<Server>) -> Result<LocalAnswer, SystemException> {
1756 match self {
1757 LocalCall::Locate(target) => server.locate_local(&target).map(LocalAnswer::Located),
1758 LocalCall::Request {
1759 version,
1760 header,
1761 body,
1762 code_sets,
1763 timeout,
1764 } => server
1765 .call_local(version, header, body, code_sets, timeout)
1766 .map(|reply| LocalAnswer::Reply(reply, code_sets)),
1767 }
1768 }
1769}
1770
1771fn local_outcome(
1772 orb: &Orb,
1773 answer: Result<LocalAnswer, SystemException>,
1774 reply_contexts: &mut Vec<ServiceContext>,
1775) -> Attempt {
1776 match answer {
1777 Ok(LocalAnswer::Located(here)) => Attempt::Done(Ok(Outcome::Located(here))),
1778 Ok(LocalAnswer::Reply(None, _)) => Attempt::Done(Ok(Outcome::Reply(None))),
1779 Ok(LocalAnswer::Reply(Some(reply), code_sets)) => match decode_message(&reply) {
1780 Ok((_, Message::Reply { header, body })) => {
1781 *reply_contexts = header.service_context;
1782 reply_outcome(orb, header.reply_status, body, code_sets)
1783 }
1784 _ => Attempt::Done(Err(local_internal())),
1785 },
1786 Err(e) => Attempt::Done(Err(e.into())),
1787 }
1788}
1789
1790fn local_internal() -> Exception {
1791 sys(SystemExceptionKind::INTERNAL, 0, CompletionStatus::Maybe).into()
1792}
1793
1794fn reply_outcome(orb: &Orb, status: ReplyStatus, body: Body, code_sets: CodeSets) -> Attempt {
1795 match status {
1796 ReplyStatus::NoException => Attempt::Done(Ok(Outcome::Reply(Some(Reply {
1797 body,
1798 code_sets,
1799 orb: orb.clone(),
1800 })))),
1801 ReplyStatus::UserException => {
1802 let reply = Reply {
1803 body,
1804 code_sets,
1805 orb: orb.clone(),
1806 };
1807 let id = reply.input().read_string();
1808 Attempt::Done(Err(match id {
1809 Ok(repository_id) => Exception::User(UserException {
1810 repository_id,
1811 reply,
1812 }),
1813 Err(e) => Exception::System(e),
1814 }))
1815 }
1816 ReplyStatus::SystemException => {
1817 let mut dec = body.decoder();
1818 Attempt::Done(Err(match SystemExceptionBody::decode(&mut dec) {
1819 Ok(e) => Exception::System(e.into()),
1820 Err(e) => Exception::System(marshal(e)),
1821 }))
1822 }
1823 ReplyStatus::LocationForward | ReplyStatus::LocationForwardPerm => forward(&body),
1824 ReplyStatus::NeedsAddressingMode => addressing(&body),
1825 }
1826}
1827
1828fn locate_outcome(status: LocateStatus, body: &Body) -> Attempt {
1829 match status {
1830 LocateStatus::ObjectHere => Attempt::Done(Ok(Outcome::Located(true))),
1831 LocateStatus::UnknownObject => Attempt::Done(Ok(Outcome::Located(false))),
1832 LocateStatus::ObjectForward | LocateStatus::ObjectForwardPerm => forward(body),
1833 LocateStatus::LocSystemException => {
1834 let mut dec = body.decoder();
1835 Attempt::Done(Err(match SystemExceptionBody::decode(&mut dec) {
1836 Ok(e) => Exception::System(e.into()),
1837 Err(e) => Exception::System(marshal(e)),
1838 }))
1839 }
1840 LocateStatus::LocNeedsAddressingMode => addressing(body),
1841 }
1842}
1843
1844fn forward(body: &Body) -> Attempt {
1845 let mut dec = body.decoder();
1846 match Ior::decode(&mut dec) {
1847 Ok(ior) if !ior.is_nil() => Attempt::Forward(ior),
1848 Ok(_) => Attempt::Done(Err(sys(
1849 SystemExceptionKind::INV_OBJREF,
1850 0,
1851 CompletionStatus::No,
1852 )
1853 .into())),
1854 Err(e) => Attempt::Done(Err(Exception::System(marshal(e)))),
1855 }
1856}
1857
1858fn addressing(body: &Body) -> Attempt {
1859 let mut dec = body.decoder();
1860 match dec
1861 .read_i16()
1862 .ok()
1863 .and_then(|d| AddressingDisposition::from_i16(d).ok())
1864 {
1865 Some(d) => Attempt::Addressing(d),
1866 None => Attempt::Done(Err(sys(
1867 SystemExceptionKind::MARSHAL,
1868 0,
1869 CompletionStatus::No,
1870 )
1871 .into())),
1872 }
1873}