Skip to main content

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