rustorb_core/orb.rs
1use std::collections::{BTreeMap, HashMap, VecDeque};
2use std::fmt;
3use std::future::Future;
4use std::panic::{self, AssertUnwindSafe};
5use std::path::PathBuf;
6use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
7use std::sync::{Arc, Condvar, Mutex, OnceLock};
8use std::time::{Duration, Instant};
9
10use rustorb_cdr::ByteOrder;
11use rustorb_giop::{CorbaName, Corbaloc, Ior, ObjectUrl, Version};
12use tokio::runtime::{Handle, Runtime};
13
14use crate::connection::{Connection, EndpointKey};
15use crate::poa::{self, MainThreadGuard, Poa};
16use crate::pool::Job;
17use crate::server::Server;
18use crate::tls;
19use crate::{
20 CompletionStatus, Exception, ObjectRef, SystemException, SystemExceptionKind, minor, name,
21 timeout,
22};
23
24/// Settings of an [`Orb`].
25#[derive(Debug, Clone)]
26pub struct OrbOptions {
27 /// The highest GIOP version used for requests. A request uses the
28 /// lower of this and the version of the target's IIOP profile.
29 pub max_giop_version: Version,
30 /// Byte order of the messages rustorb sends.
31 pub byte_order: ByteOrder,
32 /// How long to wait for a TCP connection; `None` waits until the call
33 /// timeout expires, or as long as the operating system does. Expiry
34 /// raises `TIMEOUT`, completed no. The initial value of
35 /// [`Orb::set_connect_timeout`].
36 pub connect_timeout: Option<Duration>,
37 /// How long to wait for a reply; `None` waits forever. Expiry raises
38 /// `TIMEOUT`, completed maybe. The initial value of
39 /// [`Orb::set_call_timeout`]; see there for the timeouts that override
40 /// it.
41 pub request_timeout: Option<Duration>,
42 /// Largest message accepted from a server, fragments joined.
43 pub max_message_size: usize,
44 /// How many `LOCATION_FORWARD` replies one invocation follows before
45 /// it gives up with `TRANSIENT`.
46 pub max_forwards: u32,
47 /// Initial references by name (`-ORBInitRef Name=URL`).
48 pub init_refs: HashMap<String, String>,
49 /// Base URL for initial references not in `init_refs`
50 /// (`-ORBDefaultInitRef URL`); the name is appended after a `/`.
51 pub default_init_ref: Option<String>,
52 /// Number of tokio worker threads for network I/O.
53 pub io_threads: usize,
54 /// Addresses to listen on for requests (`-ORBendPoint giop:tcp:HOST:PORT`).
55 /// Empty means one endpoint on every interface with a port the
56 /// operating system chooses. The server side starts listening when the
57 /// RootPOA is first used.
58 pub endpoints: Vec<EndpointAddr>,
59 /// Address published in IORs instead of the listening one
60 /// (`-ORBendPointPublish giop:tcp:HOST:PORT`); a port of 0 keeps the
61 /// listening port.
62 pub endpoint_publish: Option<EndpointAddr>,
63 /// Upcall threads kept running even when idle.
64 pub min_server_threads: usize,
65 /// Most upcall threads running at once (`-ORBmaxServerThreadPoolSize`).
66 /// Requests beyond that wait in a queue.
67 pub max_server_threads: usize,
68 /// How long an upcall thread beyond `min_server_threads` waits for work
69 /// before it ends.
70 pub server_thread_idle_timeout: Duration,
71 /// How long an upcall thread that answered a request waits for the
72 /// next request of the same connection, to read and run it itself
73 /// (`-ORBfollowLinger US`, in microseconds; docs/read-ownership.md).
74 /// Zero turns this off: the I/O task reads every request.
75 pub follow_linger: Duration,
76 /// How many requests of one connection an upcall thread reads in a
77 /// row before it lets the I/O task read again (`-ORBfollowLimit N`).
78 /// Zero turns this off.
79 pub follow_limit: usize,
80 /// Requests of one connection that may wait or run at once. Beyond
81 /// that the connection is not read until one completes.
82 pub max_requests_per_connection: usize,
83 /// The socket send buffer of each connection (`SO_SNDBUF`), client and
84 /// server; `None` leaves the operating system's default (which on
85 /// Linux grows as needed).
86 pub socket_send_buffer: Option<usize>,
87 /// The socket receive buffer of each connection (`SO_RCVBUF`); `None`
88 /// leaves the operating system's default.
89 pub socket_receive_buffer: Option<usize>,
90 /// Addresses to listen on for requests over TLS (SSLIOP,
91 /// `-ORBendPoint giop:ssl:HOST:PORT`). Published in the
92 /// `TAG_SSL_SEC_TRANS` component of IORs; with TLS endpoints and none
93 /// in [`endpoints`](OrbOptions::endpoints), the ORB has no unprotected
94 /// endpoint. Needs [`tls`](OrbOptions::tls) with a key file.
95 pub tls_endpoints: Vec<EndpointAddr>,
96 /// Address published for the first TLS endpoint instead of the
97 /// listening one (`-ORBendPointPublish giop:ssl:HOST:PORT`).
98 pub tls_endpoint_publish: Option<EndpointAddr>,
99 /// Certificates, key and checks of TLS connections, client and server.
100 pub tls: TlsOptions,
101}
102
103/// The TLS settings of an ORB (docs/ssliop.md). Files are PEM.
104///
105/// A client connects with TLS to the objects whose IORs offer it when
106/// [`ca_file`](TlsOptions::ca_file) is set; a server listens on the
107/// [TLS endpoints](OrbOptions::tls_endpoints).
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct TlsOptions {
110 /// The CA certificates trusted for the peer's certificate
111 /// (`-ORBsslCAFile`). A client needs it to use TLS, a server to check
112 /// client certificates.
113 pub ca_file: Option<PathBuf>,
114 /// This ORB's certificate, followed by its intermediate CAs
115 /// (`-ORBsslCertFile`). Without it the certificates are read from
116 /// [`key_file`](TlsOptions::key_file), which may hold both.
117 pub cert_file: Option<PathBuf>,
118 /// This ORB's private key, unencrypted (`-ORBsslKeyFile`). A server
119 /// needs it; a client sends its certificate when it has one.
120 pub key_file: Option<PathBuf>,
121 /// Whether a server asks clients for a certificate
122 /// (`-ORBsslVerifyClient none|optional|required`).
123 pub client_auth: ClientAuth,
124 /// Whether a client checks that the server's certificate is for the
125 /// host it connects to, as named in the IOR (`-ORBsslVerifyHost 0|1`).
126 /// The chain is checked either way.
127 pub verify_host: bool,
128}
129
130impl Default for TlsOptions {
131 fn default() -> TlsOptions {
132 TlsOptions {
133 ca_file: None,
134 cert_file: None,
135 key_file: None,
136 client_auth: ClientAuth::None,
137 verify_host: true,
138 }
139 }
140}
141
142/// Whether a TLS server asks clients for a certificate. A certificate a
143/// client sends is checked against [`TlsOptions::ca_file`].
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
145pub enum ClientAuth {
146 /// Clients are not asked.
147 #[default]
148 None,
149 /// Clients are asked; one without a certificate is accepted.
150 Optional,
151 /// Clients without a valid certificate are refused.
152 Required,
153}
154
155/// A TCP address of an endpoint, as in `giop:tcp:HOST:PORT` (or
156/// `giop:ssl:HOST:PORT` for a TLS endpoint).
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct EndpointAddr {
159 /// Host name or address. Empty means every interface when listening,
160 /// and the host name of the machine when published.
161 pub host: String,
162 /// TCP port; 0 lets the operating system choose.
163 pub port: u16,
164}
165
166impl EndpointAddr {
167 /// Parses `giop:tcp:HOST:PORT`; the host and the port may be empty, and
168 /// an IPv6 address is written in brackets.
169 pub fn parse(s: &str) -> Option<EndpointAddr> {
170 EndpointAddr::parse_after(s.strip_prefix("giop:tcp:")?)
171 }
172
173 /// Parses `giop:ssl:HOST:PORT`, a TLS endpoint, like
174 /// [`parse`](EndpointAddr::parse).
175 pub fn parse_tls(s: &str) -> Option<EndpointAddr> {
176 EndpointAddr::parse_after(s.strip_prefix("giop:ssl:")?)
177 }
178
179 fn parse_after(rest: &str) -> Option<EndpointAddr> {
180 let (host, port) = rest.rsplit_once(':')?;
181 let port = if port.is_empty() {
182 0
183 } else {
184 port.parse().ok()?
185 };
186 let host = match host.strip_prefix('[') {
187 Some(h) => h.strip_suffix(']')?,
188 None if host.contains(':') => return None,
189 None => host,
190 };
191 Some(EndpointAddr {
192 host: host.to_owned(),
193 port,
194 })
195 }
196}
197
198impl Default for OrbOptions {
199 fn default() -> OrbOptions {
200 OrbOptions {
201 max_giop_version: Version::V1_2,
202 byte_order: ByteOrder::NATIVE,
203 connect_timeout: None,
204 request_timeout: None,
205 max_message_size: 64 * 1024 * 1024,
206 max_forwards: 16,
207 init_refs: HashMap::new(),
208 default_init_ref: None,
209 io_threads: 2,
210 endpoints: Vec::new(),
211 endpoint_publish: None,
212 min_server_threads: 4,
213 max_server_threads: 100,
214 server_thread_idle_timeout: Duration::from_secs(60),
215 follow_linger: Duration::from_millis(1),
216 follow_limit: 64,
217 max_requests_per_connection: 256,
218 socket_send_buffer: None,
219 socket_receive_buffer: None,
220 tls_endpoints: Vec::new(),
221 tls_endpoint_publish: None,
222 tls: TlsOptions::default(),
223 }
224 }
225}
226
227impl OrbOptions {
228 /// Reads ORB options from command line arguments and removes them,
229 /// like `CORBA::ORB_init`. Other arguments are left in place.
230 ///
231 /// | Option | Setting |
232 /// | --- | --- |
233 /// | `-ORBInitRef Name=URL` | [`init_refs`](OrbOptions::init_refs) |
234 /// | `-ORBDefaultInitRef URL` | [`default_init_ref`](OrbOptions::default_init_ref) |
235 /// | `-ORBmaxGIOPVersion 1.1` | [`max_giop_version`](OrbOptions::max_giop_version) |
236 /// | `-ORBclientConnectTimeOutPeriod MS` | [`connect_timeout`](OrbOptions::connect_timeout) (0 for none) |
237 /// | `-ORBclientCallTimeOutPeriod MS` | [`request_timeout`](OrbOptions::request_timeout) (0 for none) |
238 /// | `-ORBsupportPerThreadTimeOut 0\|1` | accepted and ignored: per-thread timeouts always work |
239 /// | `-ORBendPoint giop:tcp:HOST:PORT` | [`endpoints`](OrbOptions::endpoints) (repeatable) |
240 /// | `-ORBendPointPublish giop:tcp:HOST:PORT` | [`endpoint_publish`](OrbOptions::endpoint_publish) (`all(addr)` for the default) |
241 /// | `-ORBmaxServerThreadPoolSize N` | [`max_server_threads`](OrbOptions::max_server_threads) |
242 /// | `-ORBfollowLinger US` | [`follow_linger`](OrbOptions::follow_linger), in microseconds |
243 /// | `-ORBfollowLimit N` | [`follow_limit`](OrbOptions::follow_limit) |
244 /// | `-ORBendPoint giop:ssl:HOST:PORT` | [`tls_endpoints`](OrbOptions::tls_endpoints) (repeatable) |
245 /// | `-ORBendPointPublish giop:ssl:HOST:PORT` | [`tls_endpoint_publish`](OrbOptions::tls_endpoint_publish) |
246 /// | `-ORBsslCAFile PATH` | [`TlsOptions::ca_file`] |
247 /// | `-ORBsslCertFile PATH` | [`TlsOptions::cert_file`] |
248 /// | `-ORBsslKeyFile PATH` | [`TlsOptions::key_file`] |
249 /// | `-ORBsslVerifyClient none\|optional\|required` | [`TlsOptions::client_auth`] |
250 /// | `-ORBsslVerifyHost 0\|1` | [`TlsOptions::verify_host`] |
251 ///
252 /// The value may also follow the option name after `=`, as in
253 /// `-ORBmaxGIOPVersion=1.1`.
254 pub fn parse_args(&mut self, args: &mut Vec<String>) -> Result<(), SystemException> {
255 let mut rest = Vec::with_capacity(args.len());
256 let mut iter = std::mem::take(args).into_iter();
257 while let Some(arg) = iter.next() {
258 let Some(option) = arg.strip_prefix("-ORB") else {
259 rest.push(arg);
260 continue;
261 };
262 let (name, inline) = match option.split_once('=') {
263 Some((name, value))
264 if matches!(
265 name,
266 "maxGIOPVersion"
267 | "clientConnectTimeOutPeriod"
268 | "clientCallTimeOutPeriod"
269 | "supportPerThreadTimeOut"
270 | "maxServerThreadPoolSize"
271 | "followLinger"
272 | "followLimit"
273 | "sslCAFile"
274 | "sslCertFile"
275 | "sslKeyFile"
276 | "sslVerifyClient"
277 | "sslVerifyHost"
278 ) =>
279 {
280 (name.to_owned(), Some(value.to_owned()))
281 }
282 _ => (option.to_owned(), None),
283 };
284 if !matches!(
285 name.as_str(),
286 "InitRef"
287 | "DefaultInitRef"
288 | "maxGIOPVersion"
289 | "clientConnectTimeOutPeriod"
290 | "clientCallTimeOutPeriod"
291 | "supportPerThreadTimeOut"
292 | "endPoint"
293 | "endPointPublish"
294 | "maxServerThreadPoolSize"
295 | "followLinger"
296 | "followLimit"
297 | "sslCAFile"
298 | "sslCertFile"
299 | "sslKeyFile"
300 | "sslVerifyClient"
301 | "sslVerifyHost"
302 ) {
303 rest.push(arg);
304 continue;
305 }
306 let value = match inline.or_else(|| iter.next()) {
307 Some(value) => value,
308 None => return Err(bad_option()),
309 };
310 match name.as_str() {
311 "InitRef" => {
312 let (id, url) = value.split_once('=').ok_or_else(bad_option)?;
313 self.init_refs.insert(id.to_owned(), url.to_owned());
314 }
315 "DefaultInitRef" => self.default_init_ref = Some(value),
316 "maxGIOPVersion" => {
317 let (major, minor) = value.split_once('.').ok_or_else(bad_option)?;
318 let version = Version {
319 major: major.parse().map_err(|_| bad_option())?,
320 minor: minor.parse().map_err(|_| bad_option())?,
321 };
322 if !version.is_supported() {
323 return Err(bad_option());
324 }
325 self.max_giop_version = version;
326 }
327 "clientConnectTimeOutPeriod" => self.connect_timeout = millis(&value)?,
328 "clientCallTimeOutPeriod" => self.request_timeout = millis(&value)?,
329 // rustorb always honours per-thread timeouts.
330 "supportPerThreadTimeOut" => {
331 if !matches!(value.as_str(), "0" | "1") {
332 return Err(bad_option());
333 }
334 }
335 "endPoint" if value.starts_with("giop:ssl:") => self
336 .tls_endpoints
337 .push(EndpointAddr::parse_tls(&value).ok_or_else(bad_option)?),
338 "endPoint" => self
339 .endpoints
340 .push(EndpointAddr::parse(&value).ok_or_else(bad_option)?),
341 // `all(addr)` (every address of the host, omniORB's
342 // spelling) is what the ORB publishes anyway.
343 "endPointPublish" if value == "all(addr)" => self.endpoint_publish = None,
344 "endPointPublish" if value.starts_with("giop:ssl:") => {
345 self.tls_endpoint_publish =
346 Some(EndpointAddr::parse_tls(&value).ok_or_else(bad_option)?);
347 }
348 "endPointPublish" => {
349 self.endpoint_publish =
350 Some(EndpointAddr::parse(&value).ok_or_else(bad_option)?);
351 }
352 "maxServerThreadPoolSize" => {
353 let n: usize = value.parse().map_err(|_| bad_option())?;
354 if n == 0 {
355 return Err(bad_option());
356 }
357 self.max_server_threads = n;
358 }
359 "followLinger" => {
360 let us: u64 = value.parse().map_err(|_| bad_option())?;
361 self.follow_linger = Duration::from_micros(us);
362 }
363 "followLimit" => {
364 self.follow_limit = value.parse().map_err(|_| bad_option())?;
365 }
366 "sslCAFile" => self.tls.ca_file = Some(value.into()),
367 "sslCertFile" => self.tls.cert_file = Some(value.into()),
368 "sslKeyFile" => self.tls.key_file = Some(value.into()),
369 "sslVerifyClient" => {
370 self.tls.client_auth = match value.as_str() {
371 "none" => ClientAuth::None,
372 "optional" => ClientAuth::Optional,
373 "required" => ClientAuth::Required,
374 _ => return Err(bad_option()),
375 };
376 }
377 "sslVerifyHost" => {
378 self.tls.verify_host = match value.as_str() {
379 "0" => false,
380 "1" => true,
381 _ => return Err(bad_option()),
382 };
383 }
384 _ => unreachable!(),
385 }
386 }
387 *args = rest;
388 Ok(())
389 }
390}
391
392fn millis(value: &str) -> Result<Option<Duration>, SystemException> {
393 let ms: u64 = value.parse().map_err(|_| bad_option())?;
394 Ok((ms > 0).then(|| Duration::from_millis(ms)))
395}
396
397fn bad_param() -> SystemException {
398 SystemException::new(SystemExceptionKind::BAD_PARAM, 0, CompletionStatus::No)
399}
400
401fn bad_option() -> SystemException {
402 SystemException::new(SystemExceptionKind::BAD_PARAM, 0, CompletionStatus::No)
403}
404
405/// Why `resolve_initial_references` failed.
406#[derive(Debug, Clone, PartialEq, Eq)]
407pub enum ResolveError {
408 /// `CORBA::ORB::InvalidName`: no initial reference has this name.
409 InvalidName(String),
410 /// The configured URL could not be turned into a reference.
411 System(SystemException),
412}
413
414impl fmt::Display for ResolveError {
415 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
416 match self {
417 ResolveError::InvalidName(name) => write!(f, "no initial reference named {name:?}"),
418 ResolveError::System(e) => e.fmt(f),
419 }
420 }
421}
422
423impl std::error::Error for ResolveError {}
424
425impl From<SystemException> for ResolveError {
426 fn from(e: SystemException) -> Self {
427 ResolveError::System(e)
428 }
429}
430
431/// An ORB: the client side, and the server side once the RootPOA is used.
432///
433/// Network I/O runs on a tokio runtime owned by the ORB, or on one the
434/// application shares with it ([`with_runtime`](Orb::with_runtime)); the
435/// methods here and on [`ObjectRef`] block the calling thread. They must
436/// not be called from inside a tokio runtime, the threads of
437/// `spawn_blocking` included (they fail with `BAD_INV_ORDER`): async code
438/// uses [`ObjectRef::request_async`] and [`run_async`](Orb::run_async)
439/// instead. Servants run on a pool of upcall threads owned by the ORB.
440///
441/// `Orb` is a cheap handle: clones share the same ORB, which shuts down
442/// when the last clone and the last [`ObjectRef`] are gone. Servants that
443/// hold the ORB keep it alive until [`shutdown`](Orb::shutdown) or
444/// [`destroy`](Orb::destroy) drops them.
445#[derive(Clone)]
446pub struct Orb {
447 pub(crate) inner: Arc<OrbInner>,
448}
449
450pub(crate) struct OrbInner {
451 runtime: Option<Runtime>,
452 pub(crate) handle: Handle,
453 pub(crate) options: OrbOptions,
454 /// [`Orb::set_call_timeout`] and [`Orb::set_connect_timeout`], as
455 /// [`timeout::encode`](crate::timeout::encode) stores them.
456 call_timeout: AtomicU64,
457 connect_timeout: AtomicU64,
458 connections: Mutex<HashMap<EndpointKey, Arc<Connection>>>,
459 /// The configuration of client TLS connections, made when first used.
460 tls_client: OnceLock<Result<Arc<rustls::ClientConfig>, String>>,
461 /// [`Orb::register_initial_reference`] and
462 /// [`Orb::register_local_initial_reference`]. IORs rather than
463 /// references, which would hold the ORB.
464 registered: Mutex<BTreeMap<String, Registered>>,
465 shut_down: AtomicBool,
466 server: Mutex<Option<Arc<Server>>>,
467 /// The MAIN_THREAD_MODEL requests, and whether shutdown has completed;
468 /// `run` waits for both.
469 main: Mutex<MainQueue>,
470 main_cond: Condvar,
471 /// Wakes [`Orb::run_async`] when shutdown has completed.
472 stopped: tokio::sync::Notify,
473}
474
475/// An initial reference registered at run time.
476enum Registered {
477 Object(Ior),
478 Local(Arc<dyn std::any::Any + Send + Sync>),
479}
480
481#[derive(Default)]
482struct MainQueue {
483 jobs: VecDeque<Job>,
484 /// No more requests are queued (the server is shutting down).
485 closed: bool,
486 /// Shutdown has completed.
487 stopped: bool,
488}
489
490impl OrbInner {
491 /// Queues a MAIN_THREAD_MODEL request.
492 pub(crate) fn push_main(&self, job: Job) {
493 let mut main = self.main.lock().unwrap();
494 if main.closed {
495 return;
496 }
497 main.jobs.push_back(job);
498 self.main_cond.notify_one();
499 }
500
501 /// Drops the queued MAIN_THREAD_MODEL requests and refuses new ones.
502 pub(crate) fn close_main(&self) {
503 let jobs = {
504 let mut main = self.main.lock().unwrap();
505 main.closed = true;
506 std::mem::take(&mut main.jobs)
507 };
508 drop(jobs);
509 }
510}
511
512impl Drop for OrbInner {
513 fn drop(&mut self) {
514 if let Some(runtime) = self.runtime.take() {
515 runtime.shutdown_background();
516 }
517 }
518}
519
520/// Clones of one ORB are equal.
521impl PartialEq for Orb {
522 fn eq(&self, other: &Self) -> bool {
523 Arc::ptr_eq(&self.inner, &other.inner)
524 }
525}
526
527impl Eq for Orb {}
528
529impl fmt::Debug for Orb {
530 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
531 f.debug_struct("Orb")
532 .field("options", &self.inner.options)
533 .finish_non_exhaustive()
534 }
535}
536
537impl Orb {
538 /// Initialises an ORB from command line arguments, removing the ORB
539 /// options (see [`OrbOptions::parse_args`]).
540 pub fn init(args: &mut Vec<String>) -> Result<Orb, SystemException> {
541 let mut options = OrbOptions::default();
542 options.parse_args(args)?;
543 Orb::with_options(options)
544 }
545
546 /// Initialises an ORB with `options`.
547 pub fn with_options(options: OrbOptions) -> Result<Orb, SystemException> {
548 let runtime = tokio::runtime::Builder::new_multi_thread()
549 .worker_threads(options.io_threads.max(1))
550 .thread_name("rustorb-io")
551 .enable_io()
552 .enable_time()
553 .build()
554 .map_err(|_| {
555 SystemException::new(SystemExceptionKind::INITIALIZE, 0, CompletionStatus::No)
556 })?;
557 let handle = runtime.handle().clone();
558 Ok(Orb::new(options, Some(runtime), handle))
559 }
560
561 /// Initialises an ORB with `options` whose network I/O runs on the
562 /// application's runtime `handle` instead of a runtime of its own
563 /// ([`OrbOptions::io_threads`] is not used). The runtime must have I/O
564 /// and time enabled. A `current_thread` runtime does I/O only while a
565 /// thread runs its `block_on`, so blocking calls (from servants, say)
566 /// wait until one does; a multi-thread runtime has no such limit.
567 ///
568 /// Shutting the ORB down needs the runtime to run. On a
569 /// `current_thread` runtime, a blocking [`shutdown(true)`](Orb::shutdown)
570 /// or [`destroy`](Orb::destroy) outside its `block_on` waits for it, and
571 /// inside it blocks the runtime: shut down from inside instead, with
572 /// `shutdown(false)` and [`run_async`](Orb::run_async), and destroy
573 /// after that.
574 ///
575 /// Destroy the ORB before the runtime shuts down. Destroying it closes
576 /// its connections and stops its listening tasks; the runtime keeps no
577 /// task of the ORB. Once the runtime is gone, calls fail with
578 /// `COMM_FAILURE` or `TRANSIENT`.
579 pub fn with_runtime(options: OrbOptions, handle: Handle) -> Orb {
580 Orb::new(options, None, handle)
581 }
582
583 fn new(options: OrbOptions, runtime: Option<Runtime>, handle: Handle) -> Orb {
584 Orb {
585 inner: Arc::new(OrbInner {
586 runtime,
587 handle,
588 call_timeout: AtomicU64::new(timeout::encode(options.request_timeout)),
589 connect_timeout: AtomicU64::new(timeout::encode(options.connect_timeout)),
590 options,
591 connections: Mutex::new(HashMap::new()),
592 tls_client: OnceLock::new(),
593 registered: Mutex::default(),
594 shut_down: AtomicBool::new(false),
595 server: Mutex::new(None),
596 main: Mutex::default(),
597 main_cond: Condvar::new(),
598 stopped: tokio::sync::Notify::new(),
599 }),
600 }
601 }
602
603 /// The handle of the runtime the ORB's network I/O runs on: its own,
604 /// or the one given to [`with_runtime`](Orb::with_runtime).
605 pub fn runtime_handle(&self) -> &Handle {
606 &self.inner.handle
607 }
608
609 /// The options the ORB was created with.
610 pub fn options(&self) -> &OrbOptions {
611 &self.inner.options
612 }
613
614 /// Sets how long calls through this ORB may take (`None`: no limit),
615 /// like omniORB's `setClientCallTimeout(millisecs)`. The time covers
616 /// connecting (unless a [connect timeout](Orb::set_connect_timeout)
617 /// is set), following forwards and waiting for the reply. When it
618 /// expires the call raises `TIMEOUT`: completed maybe once the request
619 /// was sent, and then a `CancelRequest` goes to the server; completed
620 /// no before.
621 ///
622 /// A timeout of the calling thread
623 /// ([`set_thread_call_timeout`](crate::set_thread_call_timeout))
624 /// overrides it, one of the object reference
625 /// ([`ObjectRef::set_call_timeout`]) overrides both, and one given for
626 /// the request ([`Request::timeout`](crate::Request::timeout)) all of
627 /// them.
628 pub fn set_call_timeout(&self, timeout: Option<Duration>) {
629 self.inner
630 .call_timeout
631 .store(timeout::encode(timeout), Ordering::Relaxed);
632 }
633
634 /// The timeout [`set_call_timeout`](Orb::set_call_timeout) set, or
635 /// [`OrbOptions::request_timeout`].
636 pub fn call_timeout(&self) -> Option<Duration> {
637 timeout::decode(self.inner.call_timeout.load(Ordering::Relaxed))
638 }
639
640 /// Sets how long to wait for a new TCP connection, like omniORB's
641 /// `setClientConnectTimeout`: while connecting it replaces the call
642 /// timeout. `None` connects until the call timeout expires, or as long
643 /// as the operating system waits. Expiry raises `TIMEOUT`, completed
644 /// no.
645 pub fn set_connect_timeout(&self, timeout: Option<Duration>) {
646 self.inner
647 .connect_timeout
648 .store(timeout::encode(timeout), Ordering::Relaxed);
649 }
650
651 /// The timeout [`set_connect_timeout`](Orb::set_connect_timeout) set,
652 /// or [`OrbOptions::connect_timeout`].
653 pub fn connect_timeout(&self) -> Option<Duration> {
654 timeout::decode(self.inner.connect_timeout.load(Ordering::Relaxed))
655 }
656
657 /// Turns a stringified IOR, a `corbaloc:` or a `corbaname:` URL into a
658 /// reference. Returns `None` for a nil IOR, or a name bound to nil.
659 ///
660 /// `corbaloc:rir:` goes through
661 /// [`resolve_initial_references`](Orb::resolve_initial_references).
662 /// `corbaname:` resolves the name after `#` in the naming context the
663 /// rest of the URL denotes (with no name, the context itself is
664 /// returned). The name must be a valid stringified name
665 /// (`BAD_PARAM`, minor `BAD_SCHEME_SPECIFIC_PART`); a name the naming
666 /// service cannot resolve raises `BAD_PARAM` with minor
667 /// `STRING_TO_OBJECT_OTHER`, and system exceptions from the naming
668 /// service are passed on.
669 pub fn string_to_object(&self, s: &str) -> Result<Option<ObjectRef>, SystemException> {
670 self.check_running()?;
671 let url = ObjectUrl::parse(s).map_err(|_| {
672 let trimmed = s.trim_ascii_start();
673 let known = ["IOR:", "corbaloc:", "corbaname:"].iter().any(|scheme| {
674 trimmed
675 .get(..scheme.len())
676 .is_some_and(|head| head.eq_ignore_ascii_case(scheme))
677 });
678 let minor = if known {
679 minor::BAD_SCHEME_SPECIFIC_PART
680 } else {
681 minor::BAD_SCHEME_NAME
682 };
683 SystemException::new(SystemExceptionKind::BAD_PARAM, minor, CompletionStatus::No)
684 })?;
685 match url {
686 ObjectUrl::Ior(ior) if ior.is_nil() => Ok(None),
687 ObjectUrl::Ior(ior) => Ok(Some(ObjectRef::new(self.clone(), ior))),
688 ObjectUrl::Corbaloc(loc) => self.corbaloc_to_object(loc).map(Some),
689 ObjectUrl::CorbaName(url) => self.resolve_corbaname(url),
690 }
691 }
692
693 fn corbaloc_to_object(&self, loc: Corbaloc) -> Result<ObjectRef, SystemException> {
694 if loc.is_rir() {
695 let name = String::from_utf8(loc.key).map_err(|_| {
696 SystemException::new(
697 SystemExceptionKind::BAD_PARAM,
698 minor::BAD_SCHEME_SPECIFIC_PART,
699 CompletionStatus::No,
700 )
701 })?;
702 return match self.resolve_initial_references(&name) {
703 Ok(obj) => Ok(obj),
704 Err(ResolveError::System(e)) => Err(e),
705 Err(ResolveError::InvalidName(_)) => Err(SystemException::new(
706 SystemExceptionKind::BAD_PARAM,
707 minor::STRING_TO_OBJECT_OTHER,
708 CompletionStatus::No,
709 )),
710 };
711 }
712 let ior = loc.to_ior(self.inner.options.byte_order).map_err(|_| {
713 SystemException::new(
714 SystemExceptionKind::BAD_PARAM,
715 minor::BAD_ADDRESS,
716 CompletionStatus::No,
717 )
718 })?;
719 Ok(ObjectRef::new(self.clone(), ior))
720 }
721
722 /// Resolves a `corbaname:` URL: the `corbaloc` part gives the naming
723 /// context, and the name after `#`, if any, is resolved in it with
724 /// `CosNaming::NamingContext::resolve`.
725 fn resolve_corbaname(&self, url: CorbaName) -> Result<Option<ObjectRef>, SystemException> {
726 let context = self.corbaloc_to_object(url.context)?;
727 if url.name.is_empty() {
728 return Ok(Some(context));
729 }
730 let name = name::to_name(&url.name).map_err(|_| {
731 SystemException::new(
732 SystemExceptionKind::BAD_PARAM,
733 minor::BAD_SCHEME_SPECIFIC_PART,
734 CompletionStatus::No,
735 )
736 })?;
737 let reply = context
738 .request("resolve")
739 .args(|out| name::write_name(out, &name))
740 .invoke();
741 match reply {
742 Ok(reply) => reply.input().read_object(),
743 Err(Exception::System(e)) => Err(e),
744 // NotFound, CannotProceed or InvalidName.
745 Err(Exception::User(_)) => Err(SystemException::new(
746 SystemExceptionKind::BAD_PARAM,
747 minor::STRING_TO_OBJECT_OTHER,
748 CompletionStatus::No,
749 )),
750 }
751 }
752
753 /// Writes a reference as a stringified IOR; `None` gives the nil IOR.
754 pub fn object_to_string(&self, obj: Option<&ObjectRef>) -> Result<String, SystemException> {
755 let nil = Ior::nil();
756 let ior = obj.map_or(&nil, |obj| obj.ior());
757 ior.to_ior_string(self.inner.options.byte_order)
758 .map_err(|_| {
759 SystemException::new(SystemExceptionKind::MARSHAL, 0, CompletionStatus::No)
760 })
761 }
762
763 /// Looks up an initial reference: first among those
764 /// [registered](Orb::register_initial_reference), then in
765 /// [`init_refs`](OrbOptions::init_refs), then under
766 /// [`default_init_ref`](OrbOptions::default_init_ref).
767 pub fn resolve_initial_references(&self, name: &str) -> Result<ObjectRef, ResolveError> {
768 match self.inner.registered.lock().unwrap().get(name) {
769 Some(Registered::Object(ior)) => {
770 return Ok(ObjectRef::new(self.clone(), ior.clone()));
771 }
772 Some(Registered::Local(_)) => {
773 return Err(ResolveError::InvalidName(name.to_owned()));
774 }
775 None => {}
776 }
777 let options = &self.inner.options;
778 let url = match (options.init_refs.get(name), &options.default_init_ref) {
779 (Some(url), _) => url.clone(),
780 (None, Some(base)) => format!("{}/{name}", base.trim_end_matches('/')),
781 (None, None) => return Err(ResolveError::InvalidName(name.to_owned())),
782 };
783 // An init ref pointing at rir: again would loop.
784 if url
785 .trim_ascii()
786 .to_ascii_lowercase()
787 .starts_with("corbaloc:rir:")
788 {
789 return Err(ResolveError::InvalidName(name.to_owned()));
790 }
791 self.string_to_object(&url)?
792 .ok_or_else(|| ResolveError::InvalidName(name.to_owned()))
793 }
794
795 /// The names [`resolve_initial_references`](Orb::resolve_initial_references)
796 /// knows without the default URL, sorted.
797 pub fn list_initial_services(&self) -> Vec<String> {
798 let mut names: Vec<_> = self.inner.options.init_refs.keys().cloned().collect();
799 names.extend(self.inner.registered.lock().unwrap().keys().cloned());
800 names.sort();
801 names.dedup();
802 names
803 }
804
805 /// `CORBA::ORB::register_initial_reference`: makes
806 /// [`resolve_initial_references`](Orb::resolve_initial_references)
807 /// return `obj` for `name`. `InvalidName` if `name` is empty or
808 /// already an initial reference (registered or given with
809 /// `-ORBInitRef`), `BAD_PARAM` (minor
810 /// [`NIL_INITIAL_REFERENCE`](crate::minor::NIL_INITIAL_REFERENCE)) for
811 /// a nil `obj`. The names a binding resolves itself, such as
812 /// `RootPOA`, are the binding's to refuse.
813 pub fn register_initial_reference(
814 &self,
815 name: &str,
816 obj: Option<&ObjectRef>,
817 ) -> Result<(), ResolveError> {
818 let obj = obj.ok_or_else(|| {
819 SystemException::new(
820 SystemExceptionKind::BAD_PARAM,
821 minor::NIL_INITIAL_REFERENCE,
822 CompletionStatus::No,
823 )
824 });
825 self.register(name, || Ok(Registered::Object(obj?.ior().clone())))
826 }
827
828 /// [`register_initial_reference`](Orb::register_initial_reference) for
829 /// an object of a binding that has no reference, such as a local
830 /// object: the ORB keeps `obj` under `name` until it is destroyed, for
831 /// [`resolve_local_initial_reference`](Orb::resolve_local_initial_reference).
832 /// `resolve_initial_references` does not resolve it.
833 pub fn register_local_initial_reference(
834 &self,
835 name: &str,
836 obj: Arc<dyn std::any::Any + Send + Sync>,
837 ) -> Result<(), ResolveError> {
838 self.register(name, || Ok(Registered::Local(obj)))
839 }
840
841 /// An object registered with
842 /// [`register_local_initial_reference`](Orb::register_local_initial_reference).
843 pub fn resolve_local_initial_reference(
844 &self,
845 name: &str,
846 ) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
847 match self.inner.registered.lock().unwrap().get(name) {
848 Some(Registered::Local(obj)) => Some(Arc::clone(obj)),
849 _ => None,
850 }
851 }
852
853 fn register(
854 &self,
855 name: &str,
856 entry: impl FnOnce() -> Result<Registered, SystemException>,
857 ) -> Result<(), ResolveError> {
858 let mut registered = self.inner.registered.lock().unwrap();
859 if name.is_empty()
860 || registered.contains_key(name)
861 || self.inner.options.init_refs.contains_key(name)
862 {
863 return Err(ResolveError::InvalidName(name.to_owned()));
864 }
865 registered.insert(name.to_owned(), entry()?);
866 Ok(())
867 }
868
869 /// The RootPOA. The first call starts the server side: it opens the
870 /// [`endpoints`](OrbOptions::endpoints) (`INITIALIZE` if one cannot be
871 /// opened) and the upcall thread pool.
872 pub fn root_poa(&self) -> Result<Poa, SystemException> {
873 self.check_running()?;
874 let mut server = self.inner.server.lock().unwrap();
875 let server = match &*server {
876 Some(s) => Arc::clone(s),
877 None => {
878 let s = Server::start(self)?;
879 *server = Some(Arc::clone(&s));
880 s
881 }
882 };
883 Ok(Poa {
884 orb: self.clone(),
885 inner: Arc::clone(server.root()),
886 })
887 }
888
889 /// Makes `obj`, an object of this ORB's POAs, answer to the simple
890 /// object key `key`, as in `corbaloc::host:port/NameService`, and
891 /// returns a reference with that key. Requests with the key are
892 /// dispatched to `obj` as if they had its own key: no
893 /// `LOCATION_FORWARD` is involved, so the reference stays valid as
894 /// long as the key is registered, also across restarts that register
895 /// it again.
896 ///
897 /// `BAD_PARAM` if `key` is empty or `obj` is not an object of this
898 /// ORB's POAs.
899 pub fn register_object_key(
900 &self,
901 key: &str,
902 obj: &ObjectRef,
903 ) -> Result<ObjectRef, SystemException> {
904 let server = self.server().ok_or_else(bad_param)?;
905 if key.is_empty() {
906 return Err(bad_param());
907 }
908 let target = obj
909 .ior()
910 .iiop_profiles()
911 .filter_map(Result::ok)
912 .find(|p| {
913 server.is_own_profile(p)
914 && matches!(poa::parse_key(&p.object_key), poa::ParsedKey::Poa { .. })
915 })
916 .map(|p| p.object_key)
917 .ok_or_else(bad_param)?;
918 let ior = server.ior(obj.type_id(), key.as_bytes().to_vec())?;
919 server.set_simple_key(key.as_bytes(), Some(target));
920 Ok(ObjectRef::new(self.clone(), ior))
921 }
922
923 /// Removes a key registered with
924 /// [`register_object_key`](Orb::register_object_key); requests with it
925 /// then raise `OBJECT_NOT_EXIST`.
926 pub fn unregister_object_key(&self, key: &str) {
927 if let Some(server) = self.server() {
928 server.set_simple_key(key.as_bytes(), None);
929 }
930 }
931
932 /// The server side, if the RootPOA was used.
933 pub(crate) fn server(&self) -> Option<Arc<Server>> {
934 self.inner.server.lock().unwrap().clone()
935 }
936
937 /// The server side, if `host:port` is one of its endpoints (a TLS one
938 /// if `tls`).
939 pub(crate) fn local_server(&self, host: &str, port: u16, tls: bool) -> Option<Arc<Server>> {
940 self.server().filter(|s| s.is_local(host, port, tls))
941 }
942
943 /// The addresses the server side publishes in IORs, as host and port;
944 /// empty until the RootPOA is used.
945 pub fn endpoints(&self) -> Vec<(String, u16)> {
946 self.server()
947 .map(|s| s.published().to_vec())
948 .unwrap_or_default()
949 }
950
951 /// The TLS endpoints the server side publishes in IORs, as host and
952 /// port; empty until the RootPOA is used.
953 pub fn tls_endpoints(&self) -> Vec<(String, u16)> {
954 self.server()
955 .map(|s| s.published_tls().to_vec())
956 .unwrap_or_default()
957 }
958
959 /// `CORBA::ORB::run`: blocks until the ORB has shut down, running the
960 /// requests of MAIN_THREAD_MODEL POAs meanwhile. Other requests are
961 /// processed on the upcall threads whether or not a thread runs this.
962 /// Several threads may run it at once.
963 pub fn run(&self) {
964 while !self.run_timeout(None) {}
965 }
966
967 /// [`run`](Orb::run) for at most `timeout` (`None` for no limit).
968 /// Returns true when the ORB has shut down, false when the time ran
969 /// out. For a binding that must look at its own events, such as
970 /// signals, while it runs the ORB.
971 pub fn run_timeout(&self, timeout: Option<Duration>) -> bool {
972 let deadline = timeout.map(|t| Instant::now() + t);
973 let _main = MainThreadGuard::enter();
974 let mut main = self.inner.main.lock().unwrap();
975 loop {
976 if let Some(job) = main.jobs.pop_front() {
977 drop(main);
978 run_job(job);
979 main = self.inner.main.lock().unwrap();
980 continue;
981 }
982 if main.stopped {
983 return true;
984 }
985 main = match deadline {
986 None => self.inner.main_cond.wait(main).unwrap(),
987 Some(deadline) => {
988 let now = Instant::now();
989 if now >= deadline {
990 return false;
991 }
992 self.inner
993 .main_cond
994 .wait_timeout(main, deadline - now)
995 .unwrap()
996 .0
997 }
998 };
999 }
1000 }
1001
1002 /// [`run`](Orb::run) for async code: resolves when the ORB has shut
1003 /// down. It does not run MAIN_THREAD_MODEL requests, which need
1004 /// [`run`](Orb::run) or [`perform_work`](Orb::perform_work) on a
1005 /// thread. With [`shutdown(false)`](Orb::shutdown), the way to shut the
1006 /// ORB down from async code and wait for it.
1007 pub async fn run_async(&self) {
1008 loop {
1009 let notified = std::pin::pin!(self.inner.stopped.notified());
1010 let mut notified = notified;
1011 notified.as_mut().enable();
1012 let stopped = self.inner.main.lock().unwrap().stopped;
1013 if stopped {
1014 return;
1015 }
1016 notified.await;
1017 }
1018 }
1019
1020 /// `CORBA::ORB::work_pending`: whether a MAIN_THREAD_MODEL request
1021 /// waits for [`perform_work`](Orb::perform_work). `BAD_INV_ORDER` after
1022 /// shutdown.
1023 pub fn work_pending(&self) -> Result<bool, SystemException> {
1024 self.check_running()?;
1025 Ok(!self.inner.main.lock().unwrap().jobs.is_empty())
1026 }
1027
1028 /// `CORBA::ORB::perform_work`: runs one waiting MAIN_THREAD_MODEL
1029 /// request on the calling thread, if there is one, and returns without
1030 /// waiting otherwise. For an application's own event loop.
1031 /// `BAD_INV_ORDER` after shutdown.
1032 pub fn perform_work(&self) -> Result<(), SystemException> {
1033 self.check_running()?;
1034 let job = self.inner.main.lock().unwrap().jobs.pop_front();
1035 if let Some(job) = job {
1036 let _main = MainThreadGuard::enter();
1037 run_job(job);
1038 }
1039 Ok(())
1040 }
1041
1042 /// `CORBA::ORB::shutdown`. Refuses new invocations (`BAD_INV_ORDER`)
1043 /// and new requests, drops the requests the POA managers hold, lets the
1044 /// running ones finish and send their replies, destroys every POA, and
1045 /// then closes every connection, client and server side, with
1046 /// `CloseConnection`. Invocations still waiting for a reply fail with
1047 /// `COMM_FAILURE` or `TRANSIENT`.
1048 ///
1049 /// With `wait_for_completion`, returns when all that is done; called
1050 /// from a servant it fails with `BAD_INV_ORDER` (would deadlock).
1051 /// Without it, the shutdown runs on another thread and the call returns
1052 /// at once, so a servant can call it and still send its reply.
1053 pub fn shutdown(&self, wait_for_completion: bool) -> Result<(), SystemException> {
1054 if wait_for_completion && poa::in_upcall() {
1055 return Err(SystemException::new(
1056 SystemExceptionKind::BAD_INV_ORDER,
1057 minor::WOULD_DEADLOCK,
1058 CompletionStatus::No,
1059 ));
1060 }
1061 if self.inner.shut_down.swap(true, Ordering::AcqRel) {
1062 if wait_for_completion {
1063 self.run();
1064 }
1065 return Ok(());
1066 }
1067 if wait_for_completion {
1068 // The shutdown blocks on the runtime, which cannot be done from
1069 // inside a runtime (the caller's own, say).
1070 if Handle::try_current().is_ok() {
1071 std::thread::scope(|s| {
1072 let _ = s.spawn(|| self.complete_shutdown()).join();
1073 });
1074 } else {
1075 self.complete_shutdown();
1076 }
1077 } else {
1078 let orb = self.clone();
1079 std::thread::Builder::new()
1080 .name("rustorb-shutdown".into())
1081 .spawn(move || orb.complete_shutdown())
1082 .map_err(|_| {
1083 SystemException::new(SystemExceptionKind::NO_RESOURCES, 0, CompletionStatus::No)
1084 })?;
1085 }
1086 Ok(())
1087 }
1088
1089 fn complete_shutdown(&self) {
1090 if let Some(server) = self.server() {
1091 server.shutdown(&self.inner.handle);
1092 }
1093 let conns: Vec<_> = self
1094 .inner
1095 .connections
1096 .lock()
1097 .unwrap()
1098 .drain()
1099 .map(|(_, c)| c)
1100 .collect();
1101 let version = self.inner.options.max_giop_version;
1102 let order = self.inner.options.byte_order;
1103 let _ = self.block_on(async move {
1104 for conn in conns {
1105 conn.close(version, order).await;
1106 }
1107 });
1108 self.inner.close_main();
1109 self.inner.main.lock().unwrap().stopped = true;
1110 self.inner.main_cond.notify_all();
1111 self.inner.stopped.notify_waiters();
1112 }
1113
1114 /// `CORBA::ORB::destroy`: [`shutdown(true)`](Orb::shutdown), and then
1115 /// ends the upcall threads. Fails like `shutdown(true)` when called
1116 /// from a servant.
1117 pub fn destroy(&self) -> Result<(), SystemException> {
1118 self.shutdown(true)?;
1119 if let Some(server) = self.inner.server.lock().unwrap().take() {
1120 server.stop_pool();
1121 }
1122 // Local objects may hold the ORB.
1123 let registered = std::mem::take(&mut *self.inner.registered.lock().unwrap());
1124 drop(registered);
1125 Ok(())
1126 }
1127
1128 pub(crate) fn check_running(&self) -> Result<(), SystemException> {
1129 if self.inner.shut_down.load(Ordering::Acquire) {
1130 return Err(SystemException::new(
1131 SystemExceptionKind::BAD_INV_ORDER,
1132 minor::ORB_SHUT_DOWN,
1133 CompletionStatus::No,
1134 ));
1135 }
1136 Ok(())
1137 }
1138
1139 /// `fut`, polled inside the ORB's runtime: the sockets, timers and
1140 /// tasks it makes belong to that runtime whichever executor polls it.
1141 pub(crate) fn in_runtime<F: Future>(&self, fut: F) -> InRuntime<F> {
1142 InRuntime {
1143 handle: self.inner.handle.clone(),
1144 fut: Box::pin(fut),
1145 }
1146 }
1147
1148 /// Runs `fut` on the ORB's runtime and waits for it.
1149 pub(crate) fn block_on<F: Future>(&self, fut: F) -> Result<F::Output, SystemException> {
1150 if Handle::try_current().is_ok() {
1151 return Err(SystemException::new(
1152 SystemExceptionKind::BAD_INV_ORDER,
1153 0,
1154 CompletionStatus::No,
1155 ));
1156 }
1157 Ok(self.inner.handle.block_on(fut))
1158 }
1159
1160 /// Whether this ORB can make TLS connections: it has CA certificates
1161 /// to check servers with.
1162 pub(crate) fn has_tls_client(&self) -> bool {
1163 self.inner.options.tls.ca_file.is_some()
1164 }
1165
1166 /// The configuration of client TLS connections. A configuration that
1167 /// cannot be loaded makes every TLS connection fail with `TRANSIENT`.
1168 fn tls_client(&self) -> Result<Arc<rustls::ClientConfig>, SystemException> {
1169 self.inner
1170 .tls_client
1171 .get_or_init(|| tls::client_config(&self.inner.options.tls))
1172 .clone()
1173 .map_err(|_| {
1174 SystemException::new(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No)
1175 })
1176 }
1177
1178 /// A usable connection to `host:port`, with TLS if `tls`, opened if
1179 /// needed.
1180 ///
1181 /// Connecting stops at the connect timeout, else at `deadline` (the
1182 /// end of the call), with `TIMEOUT`, completed no, like omniORB. The
1183 /// TLS handshake counts as part of connecting.
1184 pub(crate) async fn connection(
1185 &self,
1186 host: &str,
1187 port: u16,
1188 tls: bool,
1189 deadline: Option<Instant>,
1190 ) -> Result<Arc<Connection>, SystemException> {
1191 self.check_running()?;
1192 let key = (host.to_owned(), port, tls);
1193 if let Some(conn) = self.inner.connections.lock().unwrap().get(&key) {
1194 if conn.is_usable() {
1195 return Ok(Arc::clone(conn));
1196 }
1197 }
1198 let config = if tls { Some(self.tls_client()?) } else { None };
1199 let connect = Connection::connect(host, port, config, &self.inner.options);
1200 let limit = match self.connect_timeout() {
1201 Some(t) => Some(Instant::now() + t),
1202 None => deadline,
1203 };
1204 let result = match limit {
1205 Some(at) => match tokio::time::timeout_at(at.into(), connect).await {
1206 Ok(result) => result,
1207 Err(_) => {
1208 return Err(SystemException::new(
1209 SystemExceptionKind::TIMEOUT,
1210 0,
1211 CompletionStatus::No,
1212 ));
1213 }
1214 },
1215 None => connect.await,
1216 };
1217 let conn = result.map_err(|_| {
1218 SystemException::new(SystemExceptionKind::TRANSIENT, 0, CompletionStatus::No)
1219 })?;
1220 let mut conns = self.inner.connections.lock().unwrap();
1221 match conns.get(&key) {
1222 // Another caller connected first: use its connection, and let
1223 // this one close when it is dropped.
1224 Some(existing) if existing.is_usable() => Ok(Arc::clone(existing)),
1225 _ => {
1226 conns.insert(key, Arc::clone(&conn));
1227 Ok(conn)
1228 }
1229 }
1230 }
1231
1232 /// Drops `conn` from the pool, if it is still the pooled one.
1233 pub(crate) fn discard(&self, conn: &Arc<Connection>) {
1234 let mut conns = self.inner.connections.lock().unwrap();
1235 if conns
1236 .get(conn.endpoint())
1237 .is_some_and(|c| Arc::ptr_eq(c, conn))
1238 {
1239 conns.remove(conn.endpoint());
1240 }
1241 }
1242}
1243
1244/// Runs a MAIN_THREAD_MODEL request. Requests catch the panics of user
1245/// code themselves; this keeps the loop going if anything else panics.
1246fn run_job(job: Job) {
1247 let _ = panic::catch_unwind(AssertUnwindSafe(job));
1248}
1249
1250/// See [`Orb::in_runtime`].
1251pub(crate) struct InRuntime<F> {
1252 handle: Handle,
1253 fut: std::pin::Pin<Box<F>>,
1254}
1255
1256impl<F: Future> Future for InRuntime<F> {
1257 type Output = F::Output;
1258
1259 fn poll(
1260 mut self: std::pin::Pin<&mut Self>,
1261 cx: &mut std::task::Context<'_>,
1262 ) -> std::task::Poll<F::Output> {
1263 let this = &mut *self;
1264 let _runtime = this.handle.enter();
1265 this.fut.as_mut().poll(cx)
1266 }
1267}