Skip to main content

rustorb_core/
poa.rs

1//! The POA: object adapters, their policies, POA managers and object keys.
2//!
3//! Object keys follow `docs/poa-design.md`:
4//!
5//! | POA | Key |
6//! | --- | --- |
7//! | PERSISTENT | `\xff` POA path `\x00` ObjectId (the omniORB format) |
8//! | TRANSIENT | `\xff` POA path `\xfe` boot id (8 bytes) ObjectId |
9//! | RootPOA | `\xfe` boot id ObjectId |
10//!
11//! The POA path is the names from below the RootPOA down, separated by
12//! `\xff`. The boot id is a random number chosen at each start of the ORB,
13//! so TRANSIENT references die with the process. System generated
14//! ObjectIds are the boot id and a 4-byte big-endian serial number.
15
16use std::cell::{Cell, RefCell};
17use std::collections::{HashMap, HashSet, VecDeque};
18use std::fmt;
19use std::panic::{self, AssertUnwindSafe};
20use std::sync::{Arc, Condvar, Mutex, MutexGuard, Weak};
21use std::thread::{self, ThreadId};
22
23use rustorb_giop::IiopProfile;
24
25use crate::pool::Job;
26use crate::servant::{Cookie, ServantLocator};
27use crate::server::Server;
28use crate::{
29    AdapterActivator, CompletionStatus, ObjectRef, Orb, Servant, ServantActivator, ServantManager,
30    ServantManagerError, SystemException, SystemExceptionKind, minor,
31};
32
33/// `PortableServer::ObjectId`.
34pub type ObjectId = Vec<u8>;
35
36const PATH_START: u8 = 0xff;
37const PATH_SEPARATOR: u8 = 0xff;
38const PERSISTENT_END: u8 = 0x00;
39const TRANSIENT_END: u8 = 0xfe;
40/// Length of the boot id in TRANSIENT keys and system generated ids.
41pub(crate) const BOOT_ID_LEN: usize = 8;
42
43/// `PortableServer::ThreadPolicyValue`.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
45pub enum ThreadPolicy {
46    /// `ORB_CTRL_MODEL`: requests run on the upcall thread pool, in
47    /// parallel and in no particular order.
48    OrbCtrl,
49    /// `SINGLE_THREAD_MODEL`: requests to the POA run one at a time, in
50    /// the order they arrive, on any upcall thread. A servant may call an
51    /// object of its own POA in the same ORB: the call runs at once on the
52    /// servant's thread.
53    SingleThread,
54    /// `MAIN_THREAD_MODEL`: requests to the POA run one at a time on a
55    /// thread that is in [`Orb::run`] or [`Orb::perform_work`], shared with
56    /// every other POA with this policy.
57    MainThread,
58}
59
60/// `PortableServer::LifespanPolicyValue`.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
62pub enum Lifespan {
63    /// References are valid while this ORB runs.
64    Transient,
65    /// References stay valid across restarts of a server that listens on
66    /// the same address and recreates the POA.
67    Persistent,
68}
69
70/// `PortableServer::IdUniquenessPolicyValue`.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
72pub enum IdUniqueness {
73    /// A servant is active under one ObjectId at most.
74    Unique,
75    /// A servant may be active under several ObjectIds.
76    Multiple,
77}
78
79/// `PortableServer::IdAssignmentPolicyValue`.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
81pub enum IdAssignment {
82    /// The application chooses the ObjectIds.
83    User,
84    /// The POA generates the ObjectIds.
85    System,
86}
87
88/// `PortableServer::ImplicitActivationPolicyValue`.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
90pub enum ImplicitActivation {
91    /// `servant_to_reference` activates an inactive servant.
92    Implicit,
93    /// Servants are activated explicitly only.
94    NoImplicit,
95}
96
97/// `PortableServer::ServantRetentionPolicyValue`.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
99pub enum ServantRetention {
100    /// Active servants are kept in the active object map.
101    Retain,
102    /// No active object map: every request goes to the default servant or
103    /// to a [`ServantLocator`].
104    NonRetain,
105}
106
107/// `PortableServer::RequestProcessingPolicyValue`.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
109pub enum RequestProcessing {
110    /// Requests go to servants in the active object map only.
111    ActiveObjectMapOnly,
112    /// Requests for objects not in the active object map go to the
113    /// default servant ([`Poa::set_servant`]).
114    UseDefaultServant,
115    /// Requests for objects not in the active object map go to the
116    /// servant manager ([`Poa::set_servant_manager`]).
117    UseServantManager,
118}
119
120/// A POA policy, given to [`Poa::create_poa`].
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
122pub enum Policy {
123    /// `ThreadPolicy`.
124    Thread(ThreadPolicy),
125    /// `LifespanPolicy`.
126    Lifespan(Lifespan),
127    /// `IdUniquenessPolicy`.
128    IdUniqueness(IdUniqueness),
129    /// `IdAssignmentPolicy`.
130    IdAssignment(IdAssignment),
131    /// `ImplicitActivationPolicy`.
132    ImplicitActivation(ImplicitActivation),
133    /// `ServantRetentionPolicy`.
134    ServantRetention(ServantRetention),
135    /// `RequestProcessingPolicy`.
136    RequestProcessing(RequestProcessing),
137}
138
139/// The policies of one POA.
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub struct Policies {
142    /// Thread policy.
143    pub thread: ThreadPolicy,
144    /// Lifespan policy.
145    pub lifespan: Lifespan,
146    /// ObjectId uniqueness policy.
147    pub id_uniqueness: IdUniqueness,
148    /// ObjectId assignment policy.
149    pub id_assignment: IdAssignment,
150    /// Implicit activation policy.
151    pub implicit_activation: ImplicitActivation,
152    /// Servant retention policy.
153    pub servant_retention: ServantRetention,
154    /// Request processing policy.
155    pub request_processing: RequestProcessing,
156}
157
158impl Default for Policies {
159    /// The policies of a POA created with no policies.
160    fn default() -> Policies {
161        Policies {
162            thread: ThreadPolicy::OrbCtrl,
163            lifespan: Lifespan::Transient,
164            id_uniqueness: IdUniqueness::Unique,
165            id_assignment: IdAssignment::System,
166            implicit_activation: ImplicitActivation::NoImplicit,
167            servant_retention: ServantRetention::Retain,
168            request_processing: RequestProcessing::ActiveObjectMapOnly,
169        }
170    }
171}
172
173impl Policies {
174    /// The policies of the RootPOA.
175    pub(crate) fn root() -> Policies {
176        Policies {
177            implicit_activation: ImplicitActivation::Implicit,
178            ..Policies::default()
179        }
180    }
181
182    /// The defaults overridden by `list`. Fails with the index of the first
183    /// policy that is repeated, or of one inconsistent with the others.
184    fn from_list(list: &[Policy]) -> Result<Policies, u16> {
185        let mut p = Policies::default();
186        let mut seen = Vec::new();
187        let index = |i: usize| u16::try_from(i).unwrap_or(u16::MAX);
188        for (i, policy) in list.iter().enumerate() {
189            let kind = std::mem::discriminant(policy);
190            if seen.contains(&kind) {
191                return Err(index(i));
192            }
193            seen.push(kind);
194            match *policy {
195                Policy::Thread(v) => p.thread = v,
196                Policy::Lifespan(v) => p.lifespan = v,
197                Policy::IdUniqueness(v) => p.id_uniqueness = v,
198                Policy::IdAssignment(v) => p.id_assignment = v,
199                Policy::ImplicitActivation(v) => p.implicit_activation = v,
200                Policy::ServantRetention(v) => p.servant_retention = v,
201                Policy::RequestProcessing(v) => p.request_processing = v,
202            }
203        }
204        // The index of the last policy of a kind in the list, as the one in
205        // conflict with the defaults or with the policies before it.
206        let position = |f: fn(&Policy) -> bool| index(list.iter().rposition(f).unwrap_or(0));
207        if p.implicit_activation == ImplicitActivation::Implicit
208            && (p.id_assignment != IdAssignment::System
209                || p.servant_retention != ServantRetention::Retain)
210        {
211            return Err(position(|q| matches!(q, Policy::ImplicitActivation(_))));
212        }
213        if p.servant_retention == ServantRetention::NonRetain
214            && p.request_processing == RequestProcessing::ActiveObjectMapOnly
215        {
216            return Err(position(|q| {
217                matches!(
218                    q,
219                    Policy::ServantRetention(_) | Policy::RequestProcessing(_)
220                )
221            }));
222        }
223        if p.request_processing == RequestProcessing::UseDefaultServant
224            && p.id_uniqueness != IdUniqueness::Multiple
225        {
226            return Err(position(|q| {
227                matches!(q, Policy::RequestProcessing(_) | Policy::IdUniqueness(_))
228            }));
229        }
230        Ok(p)
231    }
232}
233
234/// The exceptions of the `PortableServer::POA` and `POAManager`
235/// operations, and system exceptions.
236#[derive(Debug, Clone, PartialEq, Eq)]
237pub enum PoaError {
238    /// `AdapterAlreadyExists`.
239    AdapterAlreadyExists,
240    /// `AdapterNonExistent`.
241    AdapterNonExistent,
242    /// `InvalidPolicy`, with the index of the offending policy.
243    InvalidPolicy(u16),
244    /// `ServantAlreadyActive`.
245    ServantAlreadyActive,
246    /// `ObjectAlreadyActive`.
247    ObjectAlreadyActive,
248    /// `ServantNotActive`.
249    ServantNotActive,
250    /// `ObjectNotActive`.
251    ObjectNotActive,
252    /// `WrongPolicy`.
253    WrongPolicy,
254    /// `WrongAdapter`.
255    WrongAdapter,
256    /// `POAManager::AdapterInactive`.
257    AdapterInactive,
258    /// `POA::NoServant`: no default servant was set.
259    NoServant,
260    /// `Current::NoContext`: the thread is not running a request.
261    NoContext,
262    /// A system exception, such as `OBJECT_NOT_EXIST` for a destroyed POA.
263    System(SystemException),
264}
265
266impl fmt::Display for PoaError {
267    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268        match self {
269            PoaError::AdapterAlreadyExists => {
270                f.write_str("PortableServer::POA::AdapterAlreadyExists")
271            }
272            PoaError::AdapterNonExistent => f.write_str("PortableServer::POA::AdapterNonExistent"),
273            PoaError::InvalidPolicy(i) => {
274                write!(f, "PortableServer::POA::InvalidPolicy (index {i})")
275            }
276            PoaError::ServantAlreadyActive => {
277                f.write_str("PortableServer::POA::ServantAlreadyActive")
278            }
279            PoaError::ObjectAlreadyActive => {
280                f.write_str("PortableServer::POA::ObjectAlreadyActive")
281            }
282            PoaError::ServantNotActive => f.write_str("PortableServer::POA::ServantNotActive"),
283            PoaError::ObjectNotActive => f.write_str("PortableServer::POA::ObjectNotActive"),
284            PoaError::WrongPolicy => f.write_str("PortableServer::POA::WrongPolicy"),
285            PoaError::WrongAdapter => f.write_str("PortableServer::POA::WrongAdapter"),
286            PoaError::AdapterInactive => f.write_str("PortableServer::POAManager::AdapterInactive"),
287            PoaError::NoServant => f.write_str("PortableServer::POA::NoServant"),
288            PoaError::NoContext => f.write_str("PortableServer::Current::NoContext"),
289            PoaError::System(e) => e.fmt(f),
290        }
291    }
292}
293
294impl std::error::Error for PoaError {}
295
296impl From<SystemException> for PoaError {
297    fn from(e: SystemException) -> Self {
298        PoaError::System(e)
299    }
300}
301
302fn sys(kind: SystemExceptionKind, minor: u32) -> SystemException {
303    SystemException::new(kind, minor, CompletionStatus::No)
304}
305
306/// `OBJECT_NOT_EXIST` for a request whose key names no active object.
307pub(crate) fn no_such_object() -> SystemException {
308    sys(SystemExceptionKind::OBJECT_NOT_EXIST, minor::NO_SUCH_OBJECT)
309}
310
311// --- upcall bookkeeping ------------------------------------------------------
312
313thread_local! {
314    static UPCALL_DEPTH: Cell<usize> = const { Cell::new(0) };
315    static MAIN_DEPTH: Cell<usize> = const { Cell::new(0) };
316    static CURRENT: RefCell<Vec<CurrentEntry>> = const { RefCell::new(Vec::new()) };
317}
318
319/// The request a thread is running, for [`PoaCurrent`].
320#[derive(Clone)]
321struct CurrentEntry {
322    poa: Poa,
323    id: ObjectId,
324    servant: Arc<dyn Servant>,
325}
326
327/// Makes a request the current one of the thread while it lives.
328pub(crate) struct CurrentGuard(());
329
330impl CurrentGuard {
331    pub(crate) fn enter(poa: &Poa, id: &[u8], servant: &Arc<dyn Servant>) -> CurrentGuard {
332        CURRENT.with(|c| {
333            c.borrow_mut().push(CurrentEntry {
334                poa: poa.clone(),
335                id: id.to_vec(),
336                servant: Arc::clone(servant),
337            });
338        });
339        CurrentGuard(())
340    }
341}
342
343impl Drop for CurrentGuard {
344    fn drop(&mut self) {
345        CURRENT.with(|c| c.borrow_mut().pop());
346    }
347}
348
349/// `PortableServer::Current`: the POA and ObjectId of the request the
350/// calling thread is running. Outside a request, every method fails with
351/// [`PoaError::NoContext`].
352#[derive(Debug, Clone, Copy, Default)]
353pub struct PoaCurrent;
354
355impl PoaCurrent {
356    fn with<T>(f: impl FnOnce(&CurrentEntry) -> T) -> Result<T, PoaError> {
357        CURRENT.with(|c| c.borrow().last().map(f).ok_or(PoaError::NoContext))
358    }
359
360    /// `get_POA`: the POA of the target object.
361    pub fn get_poa() -> Result<Poa, PoaError> {
362        PoaCurrent::with(|e| e.poa.clone())
363    }
364
365    /// `get_object_id`: the ObjectId of the target object.
366    pub fn get_object_id() -> Result<ObjectId, PoaError> {
367        PoaCurrent::with(|e| e.id.clone())
368    }
369
370    /// `get_reference`: a reference to the target object.
371    pub fn get_reference() -> Result<ObjectRef, PoaError> {
372        let (poa, id, servant) =
373            PoaCurrent::with(|e| (e.poa.clone(), e.id.clone(), Arc::clone(&e.servant)))?;
374        poa.reference(&id, servant.repository_id())
375    }
376
377    /// `get_servant`: the servant running the request.
378    pub fn get_servant() -> Result<Arc<dyn Servant>, PoaError> {
379        PoaCurrent::with(|e| Arc::clone(&e.servant))
380    }
381}
382
383/// Marks the current thread as one that runs MAIN_THREAD_MODEL requests
384/// (in `Orb::run` or `Orb::perform_work`) while it lives.
385pub(crate) struct MainThreadGuard(());
386
387impl MainThreadGuard {
388    pub(crate) fn enter() -> MainThreadGuard {
389        MAIN_DEPTH.with(|d| d.set(d.get() + 1));
390        MainThreadGuard(())
391    }
392}
393
394impl Drop for MainThreadGuard {
395    fn drop(&mut self) {
396        MAIN_DEPTH.with(|d| d.set(d.get() - 1));
397    }
398}
399
400/// Whether the current thread runs MAIN_THREAD_MODEL requests.
401pub(crate) fn is_main_thread() -> bool {
402    MAIN_DEPTH.with(Cell::get) > 0
403}
404
405/// Whether the current thread is running a servant.
406pub(crate) fn in_upcall() -> bool {
407    UPCALL_DEPTH.with(Cell::get) > 0
408}
409
410/// Marks the current thread as running a servant while it lives.
411pub(crate) struct UpcallGuard(());
412
413impl UpcallGuard {
414    pub(crate) fn enter() -> UpcallGuard {
415        UPCALL_DEPTH.with(|d| d.set(d.get() + 1));
416        UpcallGuard(())
417    }
418}
419
420impl Drop for UpcallGuard {
421    fn drop(&mut self) {
422        UPCALL_DEPTH.with(|d| d.set(d.get() - 1));
423    }
424}
425
426/// A count of requests in progress that can be waited on.
427#[derive(Debug, Default)]
428pub(crate) struct Activity {
429    count: Mutex<usize>,
430    idle: Condvar,
431}
432
433impl Activity {
434    pub(crate) fn enter(self: &Arc<Self>) -> ActivityGuard {
435        *self.count.lock().unwrap() += 1;
436        ActivityGuard(Arc::clone(self))
437    }
438
439    pub(crate) fn wait_idle(&self) {
440        let mut count = self.count.lock().unwrap();
441        while *count > 0 {
442            count = self.idle.wait(count).unwrap();
443        }
444    }
445}
446
447pub(crate) struct ActivityGuard(Arc<Activity>);
448
449impl Drop for ActivityGuard {
450    fn drop(&mut self) {
451        let mut count = self.0.count.lock().unwrap();
452        *count -= 1;
453        if *count == 0 {
454            self.0.idle.notify_all();
455        }
456    }
457}
458
459/// Fails with `BAD_INV_ORDER` (would deadlock) when a servant asks to wait
460/// for the completion of requests.
461fn check_wait(wait_for_completion: bool) -> Result<(), SystemException> {
462    if wait_for_completion && in_upcall() {
463        return Err(sys(
464            SystemExceptionKind::BAD_INV_ORDER,
465            minor::WOULD_DEADLOCK,
466        ));
467    }
468    Ok(())
469}
470
471// --- POA manager -------------------------------------------------------------
472
473/// `PortableServer::POAManager::State`.
474#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
475pub enum PoaManagerState {
476    /// Requests are queued until the manager becomes active.
477    Holding,
478    /// Requests are processed.
479    Active,
480    /// Requests are refused with `TRANSIENT`.
481    Discarding,
482    /// Requests are refused with `OBJ_ADAPTER`; the manager cannot become
483    /// active again.
484    Inactive,
485}
486
487/// What happens to a request that reached its POA manager.
488pub(crate) enum Disposition {
489    /// Run it. The dispatch is called on whichever thread admitted the
490    /// request (an I/O thread, or the one activating the manager), so it
491    /// must only hand the request on, not run user code.
492    Run,
493    /// Answer it with this exception.
494    Reject(SystemException),
495}
496
497pub(crate) type Dispatch = Box<dyn FnOnce(Disposition) + Send>;
498
499/// Requests a holding POA manager keeps at most; more are refused with
500/// `TRANSIENT`.
501const MAX_HELD_REQUESTS: usize = 4096;
502
503/// `PortableServer::POAManager`: switches the processing of requests for
504/// the POAs it manages. A manager starts in the holding state.
505///
506/// A cheap handle; clones manage the same POAs.
507#[derive(Clone)]
508pub struct PoaManager {
509    pub(crate) inner: Arc<ManagerInner>,
510}
511
512pub(crate) struct ManagerInner {
513    state: Mutex<ManagerState>,
514    activity: Arc<Activity>,
515    server: Weak<Server>,
516    /// The POAs the manager manages, for `deactivate(etherealize)`.
517    poas: Mutex<Vec<Weak<PoaInner>>>,
518}
519
520struct ManagerState {
521    state: PoaManagerState,
522    held: VecDeque<Dispatch>,
523}
524
525impl fmt::Debug for PoaManager {
526    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
527        f.debug_struct("PoaManager")
528            .field("state", &self.state())
529            .finish_non_exhaustive()
530    }
531}
532
533impl PartialEq for PoaManager {
534    fn eq(&self, other: &Self) -> bool {
535        Arc::ptr_eq(&self.inner, &other.inner)
536    }
537}
538
539impl Eq for PoaManager {}
540
541impl PoaManager {
542    pub(crate) fn new(server: &Arc<Server>) -> PoaManager {
543        let inner = Arc::new(ManagerInner {
544            state: Mutex::new(ManagerState {
545                state: PoaManagerState::Holding,
546                held: VecDeque::new(),
547            }),
548            activity: Arc::default(),
549            server: Arc::downgrade(server),
550            poas: Mutex::new(Vec::new()),
551        });
552        server.register_manager(&inner);
553        PoaManager { inner }
554    }
555
556    /// The current state.
557    pub fn state(&self) -> PoaManagerState {
558        self.inner.state.lock().unwrap().state
559    }
560
561    /// Starts processing requests, including those held so far. Fails
562    /// with `AdapterInactive` after [`deactivate`](PoaManager::deactivate).
563    pub fn activate(&self) -> Result<(), PoaError> {
564        let held = {
565            let mut st = self.inner.state.lock().unwrap();
566            if st.state == PoaManagerState::Inactive {
567                return Err(PoaError::AdapterInactive);
568            }
569            st.state = PoaManagerState::Active;
570            std::mem::take(&mut st.held)
571        };
572        for dispatch in held {
573            dispatch(Disposition::Run);
574        }
575        Ok(())
576    }
577
578    /// Queues new requests until the manager is activated again. With
579    /// `wait_for_completion`, returns once the requests in progress have
580    /// finished (`BAD_INV_ORDER` when called from a servant).
581    pub fn hold_requests(&self, wait_for_completion: bool) -> Result<(), PoaError> {
582        check_wait(wait_for_completion)?;
583        self.set(PoaManagerState::Holding)?;
584        if wait_for_completion {
585            self.inner.activity.wait_idle();
586        }
587        Ok(())
588    }
589
590    /// Refuses new requests with `TRANSIENT`, and the held ones too.
591    pub fn discard_requests(&self, wait_for_completion: bool) -> Result<(), PoaError> {
592        check_wait(wait_for_completion)?;
593        self.set(PoaManagerState::Discarding)?;
594        if wait_for_completion {
595            self.inner.activity.wait_idle();
596        }
597        Ok(())
598    }
599
600    /// Refuses new requests with `OBJ_ADAPTER` for good, and the held ones
601    /// too. With `etherealize`, the objects of the POAs it manages that
602    /// have a [`ServantActivator`] are deactivated and etherealized once
603    /// their requests have finished (before this returns with
604    /// `wait_for_completion`).
605    pub fn deactivate(&self, etherealize: bool, wait_for_completion: bool) -> Result<(), PoaError> {
606        check_wait(wait_for_completion)?;
607        self.set(PoaManagerState::Inactive)?;
608        if etherealize {
609            let poas: Vec<_> = self
610                .inner
611                .poas
612                .lock()
613                .unwrap()
614                .iter()
615                .filter_map(Weak::upgrade)
616                .collect();
617            let mut work = Vec::new();
618            for poa in poas {
619                work.extend(poa.take_for_etherealize());
620            }
621            if let Some(server) = self.inner.server.upgrade() {
622                server.etherealize(work, wait_for_completion);
623            }
624        }
625        if wait_for_completion {
626            self.inner.activity.wait_idle();
627        }
628        Ok(())
629    }
630
631    fn set(&self, state: PoaManagerState) -> Result<(), PoaError> {
632        let held = {
633            let mut st = self.inner.state.lock().unwrap();
634            if st.state == PoaManagerState::Inactive {
635                return Err(PoaError::AdapterInactive);
636            }
637            st.state = state;
638            if state == PoaManagerState::Holding {
639                return Ok(());
640            }
641            std::mem::take(&mut st.held)
642        };
643        let e = refusal(state);
644        for dispatch in held {
645            dispatch(Disposition::Reject(e.clone()));
646        }
647        Ok(())
648    }
649}
650
651/// The exception for a request refused in `state`.
652fn refusal(state: PoaManagerState) -> SystemException {
653    match state {
654        PoaManagerState::Inactive => sys(SystemExceptionKind::OBJ_ADAPTER, minor::POA_INACTIVE),
655        _ => sys(SystemExceptionKind::TRANSIENT, minor::POA_DISCARDING),
656    }
657}
658
659impl ManagerInner {
660    /// Runs, holds or refuses a request according to the state.
661    pub(crate) fn dispatch(&self, dispatch: Dispatch) {
662        let mut st = self.state.lock().unwrap();
663        match st.state {
664            PoaManagerState::Active => {
665                drop(st);
666                dispatch(Disposition::Run);
667            }
668            PoaManagerState::Holding if st.held.len() < MAX_HELD_REQUESTS => {
669                st.held.push_back(dispatch);
670            }
671            PoaManagerState::Holding => {
672                drop(st);
673                dispatch(Disposition::Reject(sys(SystemExceptionKind::TRANSIENT, 0)));
674            }
675            state => {
676                drop(st);
677                dispatch(Disposition::Reject(refusal(state)));
678            }
679        }
680    }
681
682    /// Whether a `LocateRequest` may answer `OBJECT_HERE`.
683    pub(crate) fn is_inactive(&self) -> bool {
684        self.state.lock().unwrap().state == PoaManagerState::Inactive
685    }
686
687    pub(crate) fn activity(&self) -> &Arc<Activity> {
688        &self.activity
689    }
690
691    fn add_poa(&self, poa: &Arc<PoaInner>) {
692        let mut poas = self.poas.lock().unwrap();
693        poas.retain(|p| p.strong_count() > 0);
694        poas.push(Arc::downgrade(poa));
695    }
696
697    /// Stops the manager at ORB shutdown: held requests are dropped
698    /// without a reply (the connections are closed with `CloseConnection`,
699    /// which tells clients they were not processed).
700    pub(crate) fn shut_down(&self) {
701        let held = {
702            let mut st = self.state.lock().unwrap();
703            st.state = PoaManagerState::Inactive;
704            std::mem::take(&mut st.held)
705        };
706        drop(held);
707    }
708}
709
710// --- POA -----------------------------------------------------------------------
711
712/// `PortableServer::POA`: an object adapter, with its active object map
713/// and its child POAs.
714///
715/// A cheap handle; clones refer to the same POA.
716#[derive(Clone)]
717pub struct Poa {
718    pub(crate) orb: Orb,
719    pub(crate) inner: Arc<PoaInner>,
720}
721
722pub(crate) struct PoaInner {
723    name: String,
724    /// Names from below the RootPOA down to this POA; empty for the
725    /// RootPOA.
726    path: Vec<String>,
727    policies: Policies,
728    pub(crate) manager: PoaManager,
729    parent: Option<Weak<PoaInner>>,
730    /// The key up to the ObjectId.
731    key_prefix: Vec<u8>,
732    boot_id: [u8; BOOT_ID_LEN],
733    activity: Arc<Activity>,
734    state: Mutex<PoaState>,
735    /// Signalled when an `incarnate` or `unknown_adapter` call ends.
736    changed: Condvar,
737    /// The queue of a SINGLE_THREAD_MODEL POA.
738    serial: Mutex<Serial>,
739}
740
741#[derive(Default)]
742struct PoaState {
743    destroyed: bool,
744    children: HashMap<String, Arc<PoaInner>>,
745    active: HashMap<ObjectId, Arc<dyn Servant>>,
746    /// The ObjectId of each active servant, by address, for UNIQUE_ID.
747    ids: HashMap<usize, ObjectId>,
748    next_id: u32,
749    default_servant: Option<Arc<dyn Servant>>,
750    servant_manager: Option<ServantManager>,
751    activator: Option<Arc<dyn AdapterActivator>>,
752    /// ObjectIds whose `incarnate` call is under way.
753    incarnating: HashSet<ObjectId>,
754    /// Child names whose `unknown_adapter` call is under way.
755    activating: HashSet<String>,
756    /// Requests running on each object that was found in the active object
757    /// map or incarnated.
758    running: HashMap<ObjectId, usize>,
759    /// Deactivated objects to etherealize once their last request ends.
760    deactivated: HashMap<ObjectId, Arc<dyn Servant>>,
761}
762
763/// The queue of a SINGLE_THREAD_MODEL POA: at most one of its requests
764/// runs at a time.
765#[derive(Default)]
766struct Serial {
767    queue: VecDeque<Job>,
768    /// Whether a request of the POA is running or about to.
769    busy: bool,
770    /// The thread running it.
771    owner: Option<ThreadId>,
772}
773
774/// How a colocated call may enter a SINGLE_THREAD_MODEL POA.
775pub(crate) enum SerialEntry {
776    /// The thread already runs a request of the POA.
777    Reentrant,
778    /// The POA was idle and is now held by the thread until the guard is
779    /// dropped.
780    Acquired(SerialGuard),
781    /// Another thread runs a request of the POA: queue the call.
782    Busy,
783}
784
785pub(crate) struct SerialGuard {
786    poa: Arc<PoaInner>,
787    server: Arc<Server>,
788}
789
790impl Drop for SerialGuard {
791    fn drop(&mut self) {
792        self.poa.release_serial(&self.server);
793    }
794}
795
796/// An object to etherealize: its POA, ObjectId and servant.
797pub(crate) struct Etherealization {
798    poa: Arc<PoaInner>,
799    activator: Arc<dyn ServantActivator>,
800    id: ObjectId,
801    servant: Arc<dyn Servant>,
802    cleanup_in_progress: bool,
803}
804
805impl Etherealization {
806    pub(crate) fn poa(&self) -> &Arc<PoaInner> {
807        &self.poa
808    }
809
810    /// Calls `etherealize`. `remaining` says whether the servant is still
811    /// active under another ObjectId; `None` looks it up in the active
812    /// object map.
813    pub(crate) fn run(self, orb: &Orb, remaining: Option<bool>) {
814        let remaining = remaining.unwrap_or_else(|| {
815            let st = self.poa.state.lock().unwrap();
816            st.active.values().any(|s| same_servant(s, &self.servant))
817        });
818        let adapter = Poa {
819            orb: orb.clone(),
820            inner: self.poa,
821        };
822        let _upcall = UpcallGuard::enter();
823        let result = panic::catch_unwind(AssertUnwindSafe(|| {
824            self.activator.etherealize(
825                &self.id,
826                &adapter,
827                self.servant,
828                self.cleanup_in_progress,
829                remaining,
830            );
831        }));
832        if result.is_err() {
833            log::warn("servant activator panicked in etherealize");
834        }
835    }
836}
837
838/// Runs `etherealizations` in order, telling each whether its servant
839/// still has a later one.
840pub(crate) fn etherealize_all(orb: &Orb, etherealizations: Vec<Etherealization>) {
841    let mut rest = etherealizations;
842    while !rest.is_empty() {
843        let e = rest.remove(0);
844        let remaining = rest.iter().any(|r| same_servant(&r.servant, &e.servant));
845        e.run(orb, Some(remaining));
846    }
847}
848
849/// The servant found for a request, and what to do when it has run.
850pub(crate) struct Resolved {
851    pub(crate) servant: Arc<dyn Servant>,
852    /// Counts the request against its object while it runs (RETAIN).
853    _object: Option<ObjectGuard>,
854    /// The locator and cookie for `postinvoke` (NON_RETAIN).
855    locator: Option<(Arc<dyn ServantLocator>, Cookie)>,
856}
857
858impl Resolved {
859    /// Calls `postinvoke` if a servant locator provided the servant.
860    pub(crate) fn finish(self, adapter: &Poa, id: &[u8], operation: &str) {
861        if let Some((locator, cookie)) = self.locator {
862            let servant = self.servant;
863            let result = panic::catch_unwind(AssertUnwindSafe(|| {
864                locator.postinvoke(id, adapter, operation, cookie, servant);
865            }));
866            if result.is_err() {
867                log::warn("servant locator panicked in postinvoke");
868            }
869        }
870    }
871}
872
873pub(crate) struct ObjectGuard {
874    poa: Arc<PoaInner>,
875    server: Weak<Server>,
876    id: ObjectId,
877}
878
879impl Drop for ObjectGuard {
880    fn drop(&mut self) {
881        let pending = {
882            let mut st = self.poa.state.lock().unwrap();
883            let Some(count) = st.running.get_mut(&self.id) else {
884                return;
885            };
886            *count -= 1;
887            if *count > 0 {
888                return;
889            }
890            st.running.remove(&self.id);
891            if st.destroyed {
892                return;
893            }
894            let Some(servant) = st.deactivated.remove(&self.id) else {
895                return;
896            };
897            let Some(ServantManager::Activator(activator)) = st.servant_manager.clone() else {
898                return;
899            };
900            Etherealization {
901                poa: Arc::clone(&self.poa),
902                activator,
903                id: std::mem::take(&mut self.id),
904                servant,
905                cleanup_in_progress: false,
906            }
907        };
908        if let Some(server) = self.server.upgrade() {
909            server.etherealize_later(pending);
910        }
911    }
912}
913
914impl fmt::Debug for Poa {
915    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
916        f.debug_struct("Poa")
917            .field("name", &self.inner.name)
918            .field("path", &self.inner.path)
919            .field("policies", &self.inner.policies)
920            .finish_non_exhaustive()
921    }
922}
923
924impl PartialEq for Poa {
925    fn eq(&self, other: &Self) -> bool {
926        Arc::ptr_eq(&self.inner, &other.inner)
927    }
928}
929
930impl Eq for Poa {}
931
932fn servant_addr(servant: &Arc<dyn Servant>) -> usize {
933    Arc::as_ptr(servant).cast::<()>() as usize
934}
935
936fn same_servant(a: &Arc<dyn Servant>, b: &Arc<dyn Servant>) -> bool {
937    servant_addr(a) == servant_addr(b)
938}
939
940/// The objects taken out of a POA, in ObjectId order, and its servant
941/// activator.
942type Drained = (
943    Vec<(ObjectId, Arc<dyn Servant>)>,
944    Option<Arc<dyn ServantActivator>>,
945);
946
947/// Empties the active object map, deactivated objects included.
948fn drain(st: &mut PoaState) -> Drained {
949    st.ids.clear();
950    let mut entries: Vec<_> = std::mem::take(&mut st.active)
951        .into_iter()
952        .chain(std::mem::take(&mut st.deactivated))
953        .collect();
954    entries.sort_by(|a, b| a.0.cmp(&b.0));
955    let activator = match &st.servant_manager {
956        Some(ServantManager::Activator(a)) => Some(Arc::clone(a)),
957        _ => None,
958    };
959    (entries, activator)
960}
961
962fn catch<T>(
963    what: &str,
964    f: impl FnOnce() -> Result<T, ServantManagerError>,
965) -> Result<T, ServantManagerError> {
966    let _upcall = UpcallGuard::enter();
967    panic::catch_unwind(AssertUnwindSafe(f)).unwrap_or_else(|_| {
968        log::warn(&format!("servant manager panicked in {what}"));
969        Err(SystemException::new(SystemExceptionKind::UNKNOWN, 0, CompletionStatus::Maybe).into())
970    })
971}
972
973impl PoaInner {
974    fn new(
975        name: String,
976        path: Vec<String>,
977        policies: Policies,
978        manager: PoaManager,
979        parent: Option<Weak<PoaInner>>,
980        key_prefix: Vec<u8>,
981        boot_id: [u8; BOOT_ID_LEN],
982    ) -> Arc<PoaInner> {
983        let poa = Arc::new(PoaInner {
984            name,
985            path,
986            policies,
987            manager,
988            parent,
989            key_prefix,
990            boot_id,
991            activity: Arc::default(),
992            state: Mutex::default(),
993            changed: Condvar::new(),
994            serial: Mutex::default(),
995        });
996        poa.manager.inner.add_poa(&poa);
997        poa
998    }
999
1000    pub(crate) fn new_root(manager: PoaManager, boot_id: [u8; BOOT_ID_LEN]) -> Arc<PoaInner> {
1001        let mut key_prefix = vec![TRANSIENT_END];
1002        key_prefix.extend_from_slice(&boot_id);
1003        PoaInner::new(
1004            "RootPOA".into(),
1005            Vec::new(),
1006            Policies::root(),
1007            manager,
1008            None,
1009            key_prefix,
1010            boot_id,
1011        )
1012    }
1013
1014    fn new_child(
1015        parent: &Arc<PoaInner>,
1016        name: &str,
1017        manager: PoaManager,
1018        policies: Policies,
1019    ) -> Arc<PoaInner> {
1020        let mut path = parent.path.clone();
1021        path.push(name.to_owned());
1022        let mut key_prefix = vec![PATH_START];
1023        for (i, n) in path.iter().enumerate() {
1024            if i > 0 {
1025                key_prefix.push(PATH_SEPARATOR);
1026            }
1027            key_prefix.extend_from_slice(n.as_bytes());
1028        }
1029        match policies.lifespan {
1030            Lifespan::Persistent => key_prefix.push(PERSISTENT_END),
1031            Lifespan::Transient => {
1032                key_prefix.push(TRANSIENT_END);
1033                key_prefix.extend_from_slice(&parent.boot_id);
1034            }
1035        }
1036        PoaInner::new(
1037            name.to_owned(),
1038            path,
1039            policies,
1040            manager,
1041            Some(Arc::downgrade(parent)),
1042            key_prefix,
1043            parent.boot_id,
1044        )
1045    }
1046
1047    pub(crate) fn policies(&self) -> &Policies {
1048        &self.policies
1049    }
1050
1051    pub(crate) fn activity(&self) -> &Arc<Activity> {
1052        &self.activity
1053    }
1054
1055    pub(crate) fn key(&self, id: &[u8]) -> Vec<u8> {
1056        let mut key = self.key_prefix.clone();
1057        key.extend_from_slice(id);
1058        key
1059    }
1060
1061    /// The child `name`, or `Err(true)` if there is none but an adapter
1062    /// activator could create it.
1063    pub(crate) fn child(&self, name: &str) -> Result<Arc<PoaInner>, bool> {
1064        let st = self.state.lock().unwrap();
1065        if st.destroyed {
1066            return Err(false);
1067        }
1068        st.children.get(name).cloned().ok_or(st.activator.is_some())
1069    }
1070
1071    /// The child `name`, created by the adapter activator if there is none.
1072    /// Calls user code: only on an upcall thread or in a colocated call.
1073    pub(crate) fn find_or_activate_child(
1074        self: &Arc<Self>,
1075        orb: &Orb,
1076        name: &str,
1077    ) -> Option<Arc<PoaInner>> {
1078        let mut st = self.state.lock().unwrap();
1079        loop {
1080            if st.destroyed {
1081                return None;
1082            }
1083            if let Some(child) = st.children.get(name) {
1084                return Some(Arc::clone(child));
1085            }
1086            let activator = st.activator.clone()?;
1087            if st.activating.contains(name) {
1088                st = self.changed.wait(st).unwrap();
1089                continue;
1090            }
1091            st.activating.insert(name.to_owned());
1092            drop(st);
1093            let parent = Poa {
1094                orb: orb.clone(),
1095                inner: Arc::clone(self),
1096            };
1097            let created = {
1098                let _upcall = UpcallGuard::enter();
1099                panic::catch_unwind(AssertUnwindSafe(|| {
1100                    activator.unknown_adapter(&parent, name)
1101                }))
1102                .unwrap_or_else(|_| {
1103                    log::warn("adapter activator panicked in unknown_adapter");
1104                    false
1105                })
1106            };
1107            st = self.state.lock().unwrap();
1108            st.activating.remove(name);
1109            self.changed.notify_all();
1110            if !created {
1111                return None;
1112            }
1113            return st.children.get(name).cloned();
1114        }
1115    }
1116
1117    /// Whether a `LocateRequest` for `id` finds an object: one in the
1118    /// active object map, or any with a default servant or a servant
1119    /// manager (which are not asked).
1120    pub(crate) fn has_object(&self, id: &[u8]) -> bool {
1121        let st = self.state.lock().unwrap();
1122        !st.destroyed
1123            && (st.active.contains_key(id)
1124                || self.policies.request_processing != RequestProcessing::ActiveObjectMapOnly)
1125    }
1126
1127    pub(crate) fn is_destroyed(&self) -> bool {
1128        self.state.lock().unwrap().destroyed
1129    }
1130
1131    /// The servant for a request to `id`: from the active object map, the
1132    /// default servant or the servant manager. Calls user code.
1133    pub(crate) fn resolve(
1134        self: &Arc<Self>,
1135        adapter: &Poa,
1136        server: &Arc<Server>,
1137        id: &[u8],
1138        operation: &str,
1139    ) -> Result<Resolved, ServantManagerError> {
1140        let retain = self.policies.servant_retention == ServantRetention::Retain;
1141        let mut st = self.state.lock().unwrap();
1142        loop {
1143            if st.destroyed {
1144                return Err(no_such_object().into());
1145            }
1146            if retain {
1147                if let Some(servant) = st.active.get(id).cloned() {
1148                    return Ok(self.resolved(&mut st, server, id, servant));
1149                }
1150            }
1151            match self.policies.request_processing {
1152                RequestProcessing::ActiveObjectMapOnly => return Err(no_such_object().into()),
1153                RequestProcessing::UseDefaultServant => {
1154                    let servant = st.default_servant.clone().ok_or_else(|| {
1155                        sys(SystemExceptionKind::OBJ_ADAPTER, minor::NO_DEFAULT_SERVANT)
1156                    })?;
1157                    return Ok(Resolved {
1158                        servant,
1159                        _object: None,
1160                        locator: None,
1161                    });
1162                }
1163                RequestProcessing::UseServantManager => {}
1164            }
1165            match st.servant_manager.clone() {
1166                None => {
1167                    return Err(
1168                        sys(SystemExceptionKind::OBJ_ADAPTER, minor::NO_SERVANT_MANAGER).into(),
1169                    );
1170                }
1171                Some(ServantManager::Locator(locator)) => {
1172                    drop(st);
1173                    let (servant, cookie) =
1174                        catch("preinvoke", || locator.preinvoke(id, adapter, operation))?;
1175                    return Ok(Resolved {
1176                        servant,
1177                        _object: None,
1178                        locator: Some((locator, cookie)),
1179                    });
1180                }
1181                Some(ServantManager::Activator(activator)) => {
1182                    if st.incarnating.contains(id) {
1183                        st = self.changed.wait(st).unwrap();
1184                        continue;
1185                    }
1186                    st.incarnating.insert(id.to_vec());
1187                    drop(st);
1188                    let result = catch("incarnate", || activator.incarnate(id, adapter));
1189                    st = self.state.lock().unwrap();
1190                    st.incarnating.remove(id);
1191                    self.changed.notify_all();
1192                    let servant = result?;
1193                    if st.destroyed {
1194                        return Err(no_such_object().into());
1195                    }
1196                    match self.activate(&mut st, id.to_vec(), Arc::clone(&servant)) {
1197                        Ok(()) => return Ok(self.resolved(&mut st, server, id, servant)),
1198                        // Activated by the application meanwhile.
1199                        Err(PoaError::ObjectAlreadyActive) => continue,
1200                        Err(_) => {
1201                            return Err(sys(
1202                                SystemExceptionKind::OBJ_ADAPTER,
1203                                minor::SERVANT_ALREADY_ACTIVE,
1204                            )
1205                            .into());
1206                        }
1207                    }
1208                }
1209            }
1210        }
1211    }
1212
1213    fn resolved(
1214        self: &Arc<Self>,
1215        st: &mut PoaState,
1216        server: &Arc<Server>,
1217        id: &[u8],
1218        servant: Arc<dyn Servant>,
1219    ) -> Resolved {
1220        *st.running.entry(id.to_vec()).or_insert(0) += 1;
1221        Resolved {
1222            servant,
1223            _object: Some(ObjectGuard {
1224                poa: Arc::clone(self),
1225                server: Arc::downgrade(server),
1226                id: id.to_vec(),
1227            }),
1228            locator: None,
1229        }
1230    }
1231
1232    /// Marks this POA and its descendants destroyed, children first, and
1233    /// drops their servants. With `etherealize`, returns the objects to
1234    /// etherealize.
1235    pub(crate) fn destroy_tree(self: &Arc<Self>, etherealize: bool) -> Vec<Etherealization> {
1236        let (children, drained, rest) = {
1237            let mut st = self.state.lock().unwrap();
1238            if st.destroyed {
1239                return Vec::new();
1240            }
1241            st.destroyed = true;
1242            let children = std::mem::take(&mut st.children);
1243            let drained = drain(&mut st);
1244            // Dropped once the lock is released.
1245            let rest = (
1246                st.default_servant.take(),
1247                st.servant_manager.take(),
1248                st.activator.take(),
1249            );
1250            (children, drained, rest)
1251        };
1252        drop(rest);
1253        let mut all = Vec::new();
1254        for child in children.into_values() {
1255            all.extend(child.destroy_tree(etherealize));
1256        }
1257        all.extend(self.etherealizations(drained, etherealize));
1258        all
1259    }
1260
1261    /// Deactivates every object for `POAManager::deactivate(etherealize)`.
1262    fn take_for_etherealize(self: &Arc<Self>) -> Vec<Etherealization> {
1263        let drained = {
1264            let mut st = self.state.lock().unwrap();
1265            if st.destroyed {
1266                return Vec::new();
1267            }
1268            drain(&mut st)
1269        };
1270        self.etherealizations(drained, true)
1271    }
1272
1273    fn etherealizations(
1274        self: &Arc<Self>,
1275        (entries, activator): Drained,
1276        etherealize: bool,
1277    ) -> Vec<Etherealization> {
1278        let Some(activator) = activator.filter(|_| etherealize) else {
1279            return Vec::new();
1280        };
1281        entries
1282            .into_iter()
1283            .map(|(id, servant)| Etherealization {
1284                poa: Arc::clone(self),
1285                activator: Arc::clone(&activator),
1286                id,
1287                servant,
1288                cleanup_in_progress: true,
1289            })
1290            .collect()
1291    }
1292
1293    fn generate_id(&self, st: &mut PoaState) -> ObjectId {
1294        let serial = st.next_id;
1295        st.next_id = st.next_id.wrapping_add(1);
1296        let mut id = self.boot_id.to_vec();
1297        id.extend_from_slice(&serial.to_be_bytes());
1298        id
1299    }
1300
1301    fn activate(
1302        &self,
1303        st: &mut PoaState,
1304        id: ObjectId,
1305        servant: Arc<dyn Servant>,
1306    ) -> Result<(), PoaError> {
1307        if st.active.contains_key(&id) {
1308            return Err(PoaError::ObjectAlreadyActive);
1309        }
1310        if self.policies.id_uniqueness == IdUniqueness::Unique {
1311            let addr = servant_addr(&servant);
1312            if st.ids.contains_key(&addr) {
1313                return Err(PoaError::ServantAlreadyActive);
1314            }
1315            st.ids.insert(addr, id.clone());
1316        }
1317        st.active.insert(id, servant);
1318        Ok(())
1319    }
1320
1321    // --- SINGLE_THREAD_MODEL ---------------------------------------------------
1322
1323    /// Queues `job` behind the other requests of this POA.
1324    pub(crate) fn run_serially(self: &Arc<Self>, server: &Arc<Server>, job: Job) {
1325        let mut serial = self.serial.lock().unwrap();
1326        serial.queue.push_back(job);
1327        if !serial.busy {
1328            serial.busy = true;
1329            drop(serial);
1330            self.submit_serial(server);
1331        }
1332    }
1333
1334    fn submit_serial(self: &Arc<Self>, server: &Arc<Server>) {
1335        let poa = Arc::clone(self);
1336        let srv = Arc::clone(server);
1337        server.submit(Box::new(move || poa.run_one_serially(&srv)));
1338    }
1339
1340    /// Runs the first queued request; on an upcall thread.
1341    fn run_one_serially(self: &Arc<Self>, server: &Arc<Server>) {
1342        let job = {
1343            let mut serial = self.serial.lock().unwrap();
1344            let Some(job) = serial.queue.pop_front() else {
1345                serial.busy = false;
1346                return;
1347            };
1348            serial.owner = Some(thread::current().id());
1349            job
1350        };
1351        let _ = panic::catch_unwind(AssertUnwindSafe(job));
1352        self.release_serial(server);
1353    }
1354
1355    fn release_serial(self: &Arc<Self>, server: &Arc<Server>) {
1356        let mut serial = self.serial.lock().unwrap();
1357        serial.owner = None;
1358        if serial.queue.is_empty() {
1359            serial.busy = false;
1360        } else {
1361            drop(serial);
1362            self.submit_serial(server);
1363        }
1364    }
1365
1366    /// Lets a colocated call run on the calling thread if that keeps the
1367    /// requests of the POA one at a time.
1368    pub(crate) fn enter_serially(self: &Arc<Self>, server: &Arc<Server>) -> SerialEntry {
1369        let me = thread::current().id();
1370        let mut serial = self.serial.lock().unwrap();
1371        if serial.owner == Some(me) {
1372            SerialEntry::Reentrant
1373        } else if serial.busy {
1374            SerialEntry::Busy
1375        } else {
1376            serial.busy = true;
1377            serial.owner = Some(me);
1378            SerialEntry::Acquired(SerialGuard {
1379                poa: Arc::clone(self),
1380                server: Arc::clone(server),
1381            })
1382        }
1383    }
1384}
1385
1386/// How a request's object key splits up.
1387#[derive(Debug, PartialEq, Eq)]
1388pub(crate) enum ParsedKey<'a> {
1389    /// A key made by a POA of this format: the path of POA names, the boot
1390    /// id for a TRANSIENT POA, and the ObjectId.
1391    Poa {
1392        path: Vec<&'a str>,
1393        boot_id: Option<&'a [u8]>,
1394        id: &'a [u8],
1395    },
1396    /// Any other key, looked up among the objects registered by name.
1397    Simple(&'a [u8]),
1398    /// A key that starts like a POA key but is cut short or not UTF-8.
1399    Invalid,
1400}
1401
1402pub(crate) fn parse_key(key: &[u8]) -> ParsedKey<'_> {
1403    fn transient<'a>(rest: &'a [u8], path: Vec<&'a str>) -> ParsedKey<'a> {
1404        if rest.len() < BOOT_ID_LEN {
1405            return ParsedKey::Invalid;
1406        }
1407        let (boot_id, id) = rest.split_at(BOOT_ID_LEN);
1408        ParsedKey::Poa {
1409            path,
1410            boot_id: Some(boot_id),
1411            id,
1412        }
1413    }
1414    match key.first() {
1415        Some(&TRANSIENT_END) => transient(&key[1..], Vec::new()),
1416        Some(&PATH_START) => {
1417            let rest = &key[1..];
1418            let Some(end) = rest
1419                .iter()
1420                .position(|&b| b == PERSISTENT_END || b == TRANSIENT_END)
1421            else {
1422                return ParsedKey::Invalid;
1423            };
1424            let mut path = Vec::new();
1425            for name in rest[..end].split(|&b| b == PATH_SEPARATOR) {
1426                match std::str::from_utf8(name) {
1427                    Ok(name) if !name.is_empty() => path.push(name),
1428                    _ => return ParsedKey::Invalid,
1429                }
1430            }
1431            if rest[end] == PERSISTENT_END {
1432                ParsedKey::Poa {
1433                    path,
1434                    boot_id: None,
1435                    id: &rest[end + 1..],
1436                }
1437            } else {
1438                transient(&rest[end + 1..], path)
1439            }
1440        }
1441        _ => ParsedKey::Simple(key),
1442    }
1443}
1444
1445impl Poa {
1446    fn state(&self) -> Result<MutexGuard<'_, PoaState>, PoaError> {
1447        let st = self.inner.state.lock().unwrap();
1448        if st.destroyed {
1449            return Err(sys(SystemExceptionKind::OBJECT_NOT_EXIST, 0).into());
1450        }
1451        Ok(st)
1452    }
1453
1454    fn server(&self) -> Result<Arc<Server>, PoaError> {
1455        self.orb
1456            .server()
1457            .ok_or_else(|| sys(SystemExceptionKind::OBJECT_NOT_EXIST, 0).into())
1458    }
1459
1460    fn handle(&self, inner: Arc<PoaInner>) -> Poa {
1461        Poa {
1462            orb: self.orb.clone(),
1463            inner,
1464        }
1465    }
1466
1467    /// `the_name`.
1468    pub fn the_name(&self) -> &str {
1469        &self.inner.name
1470    }
1471
1472    /// `the_parent`; `None` for the RootPOA.
1473    pub fn the_parent(&self) -> Option<Poa> {
1474        let parent = self.inner.parent.as_ref()?.upgrade()?;
1475        Some(self.handle(parent))
1476    }
1477
1478    /// `the_children`, in no particular order.
1479    pub fn the_children(&self) -> Vec<Poa> {
1480        let st = self.inner.state.lock().unwrap();
1481        st.children
1482            .values()
1483            .map(|c| self.handle(Arc::clone(c)))
1484            .collect()
1485    }
1486
1487    /// `the_POAManager`.
1488    pub fn the_poa_manager(&self) -> PoaManager {
1489        self.inner.manager.clone()
1490    }
1491
1492    /// The policies of the POA.
1493    pub fn policies(&self) -> Policies {
1494        self.inner.policies
1495    }
1496
1497    /// `create_POA`: a child POA named `name`, managed by `manager` or, if
1498    /// `None`, by a new manager. Policies not in `policies` take their
1499    /// default values (not those of this POA). Inconsistent policies fail
1500    /// with `InvalidPolicy`, and a name containing NUL with `BAD_PARAM`.
1501    pub fn create_poa(
1502        &self,
1503        name: &str,
1504        manager: Option<&PoaManager>,
1505        policies: &[Policy],
1506    ) -> Result<Poa, PoaError> {
1507        if name.is_empty() || name.contains('\0') {
1508            return Err(sys(SystemExceptionKind::BAD_PARAM, 0).into());
1509        }
1510        let policies = Policies::from_list(policies).map_err(PoaError::InvalidPolicy)?;
1511        let server = self.server()?;
1512        let mut st = self.state()?;
1513        if st.children.contains_key(name) {
1514            return Err(PoaError::AdapterAlreadyExists);
1515        }
1516        let manager = match manager {
1517            Some(m) => m.clone(),
1518            None => PoaManager::new(&server),
1519        };
1520        if policies.lifespan == Lifespan::Persistent && !server.has_fixed_port() {
1521            log::warn(&format!(
1522                "PERSISTENT POA {name:?} on an endpoint without a fixed port: \
1523                 its references will not survive a restart"
1524            ));
1525        }
1526        let child = PoaInner::new_child(&self.inner, name, manager, policies);
1527        st.children.insert(name.to_owned(), Arc::clone(&child));
1528        Ok(self.handle(child))
1529    }
1530
1531    /// `find_POA`: the child `name`. With `activate_it`, a missing child
1532    /// is asked of the adapter activator, if the POA has one.
1533    pub fn find_poa(&self, name: &str, activate_it: bool) -> Result<Poa, PoaError> {
1534        drop(self.state()?);
1535        let child = if activate_it {
1536            self.inner.find_or_activate_child(&self.orb, name)
1537        } else {
1538            self.inner.child(name).ok()
1539        };
1540        child
1541            .map(|c| self.handle(c))
1542            .ok_or(PoaError::AdapterNonExistent)
1543    }
1544
1545    /// `the_activator`.
1546    pub fn the_activator(&self) -> Option<Arc<dyn AdapterActivator>> {
1547        self.inner.state.lock().unwrap().activator.clone()
1548    }
1549
1550    /// `the_activator` (set): the adapter activator for unknown children,
1551    /// or none.
1552    pub fn set_the_activator(
1553        &self,
1554        activator: Option<Arc<dyn AdapterActivator>>,
1555    ) -> Result<(), PoaError> {
1556        let old = std::mem::replace(&mut self.state()?.activator, activator);
1557        drop(old);
1558        Ok(())
1559    }
1560
1561    /// `get_servant_manager` (USE_SERVANT_MANAGER only).
1562    pub fn get_servant_manager(&self) -> Result<Option<ServantManager>, PoaError> {
1563        if self.inner.policies.request_processing != RequestProcessing::UseServantManager {
1564            return Err(PoaError::WrongPolicy);
1565        }
1566        Ok(self.state()?.servant_manager.clone())
1567    }
1568
1569    /// `set_servant_manager` (USE_SERVANT_MANAGER only): a
1570    /// [`ServantActivator`] with RETAIN, a [`ServantLocator`] with
1571    /// NON_RETAIN (otherwise `OBJ_ADAPTER`). It can be set once
1572    /// (`BAD_INV_ORDER` after that).
1573    pub fn set_servant_manager(&self, manager: ServantManager) -> Result<(), PoaError> {
1574        let p = self.inner.policies;
1575        if p.request_processing != RequestProcessing::UseServantManager {
1576            return Err(PoaError::WrongPolicy);
1577        }
1578        let fits = matches!(
1579            (&manager, p.servant_retention),
1580            (ServantManager::Activator(_), ServantRetention::Retain)
1581                | (ServantManager::Locator(_), ServantRetention::NonRetain)
1582        );
1583        if !fits {
1584            return Err(sys(SystemExceptionKind::OBJ_ADAPTER, minor::NO_SERVANT_MANAGER).into());
1585        }
1586        let mut st = self.state()?;
1587        if st.servant_manager.is_some() {
1588            return Err(sys(
1589                SystemExceptionKind::BAD_INV_ORDER,
1590                minor::SERVANT_MANAGER_ALREADY_SET,
1591            )
1592            .into());
1593        }
1594        st.servant_manager = Some(manager);
1595        Ok(())
1596    }
1597
1598    /// `get_servant`: the default servant (USE_DEFAULT_SERVANT only).
1599    pub fn get_servant(&self) -> Result<Arc<dyn Servant>, PoaError> {
1600        if self.inner.policies.request_processing != RequestProcessing::UseDefaultServant {
1601            return Err(PoaError::WrongPolicy);
1602        }
1603        self.state()?
1604            .default_servant
1605            .clone()
1606            .ok_or(PoaError::NoServant)
1607    }
1608
1609    /// `set_servant`: the default servant (USE_DEFAULT_SERVANT only), which
1610    /// runs the requests for objects not in the active object map.
1611    pub fn set_servant(&self, servant: Arc<dyn Servant>) -> Result<(), PoaError> {
1612        if self.inner.policies.request_processing != RequestProcessing::UseDefaultServant {
1613            return Err(PoaError::WrongPolicy);
1614        }
1615        let old = self.state()?.default_servant.replace(servant);
1616        drop(old);
1617        Ok(())
1618    }
1619
1620    /// `destroy`: destroys the POA and its descendants and drops their
1621    /// servants. Requests already running finish; later ones get
1622    /// `OBJECT_NOT_EXIST`. With `etherealize`, the objects of POAs with a
1623    /// [`ServantActivator`] are etherealized once their requests have
1624    /// finished. With `wait_for_completion`, returns once the running
1625    /// requests of this POA have finished and the objects are etherealized
1626    /// (`BAD_INV_ORDER` when called from a servant).
1627    pub fn destroy(&self, etherealize: bool, wait_for_completion: bool) -> Result<(), PoaError> {
1628        check_wait(wait_for_completion)?;
1629        if let Some(parent) = self.inner.parent.as_ref().and_then(Weak::upgrade) {
1630            let mut st = parent.state.lock().unwrap();
1631            if st
1632                .children
1633                .get(&self.inner.name)
1634                .is_some_and(|c| Arc::ptr_eq(c, &self.inner))
1635            {
1636                st.children.remove(&self.inner.name);
1637            }
1638        }
1639        let work = self.inner.destroy_tree(etherealize);
1640        if wait_for_completion {
1641            self.inner.activity.wait_idle();
1642        }
1643        if let Some(server) = self.orb.server() {
1644            server.etherealize(work, wait_for_completion);
1645        }
1646        Ok(())
1647    }
1648
1649    fn check_retain(&self) -> Result<(), PoaError> {
1650        if self.inner.policies.servant_retention != ServantRetention::Retain {
1651            return Err(PoaError::WrongPolicy);
1652        }
1653        Ok(())
1654    }
1655
1656    /// `activate_object`: activates `servant` under a new ObjectId
1657    /// (SYSTEM_ID and RETAIN only).
1658    pub fn activate_object(&self, servant: Arc<dyn Servant>) -> Result<ObjectId, PoaError> {
1659        self.check_retain()?;
1660        if self.inner.policies.id_assignment != IdAssignment::System {
1661            return Err(PoaError::WrongPolicy);
1662        }
1663        let mut st = self.state()?;
1664        let id = self.inner.generate_id(&mut st);
1665        self.inner.activate(&mut st, id.clone(), servant)?;
1666        Ok(id)
1667    }
1668
1669    /// `activate_object_with_id` (RETAIN only).
1670    pub fn activate_object_with_id(
1671        &self,
1672        id: &[u8],
1673        servant: Arc<dyn Servant>,
1674    ) -> Result<(), PoaError> {
1675        self.check_retain()?;
1676        let mut st = self.state()?;
1677        self.inner.activate(&mut st, id.to_vec(), servant)
1678    }
1679
1680    /// `deactivate_object` (RETAIN only): requests already running finish;
1681    /// later ones get `OBJECT_NOT_EXIST`, or incarnate the object again
1682    /// with a [`ServantActivator`]. The activator's `etherealize` is called
1683    /// on an upcall thread once the running requests have finished; this
1684    /// does not wait for it.
1685    pub fn deactivate_object(&self, id: &[u8]) -> Result<(), PoaError> {
1686        self.check_retain()?;
1687        let (servant, now) = {
1688            let mut st = self.state()?;
1689            let servant = st.active.remove(id).ok_or(PoaError::ObjectNotActive)?;
1690            let addr = servant_addr(&servant);
1691            if st.ids.get(&addr).is_some_and(|i| i == id) {
1692                st.ids.remove(&addr);
1693            }
1694            match st.servant_manager.clone() {
1695                Some(ServantManager::Activator(activator)) => {
1696                    if st.running.contains_key(id) {
1697                        st.deactivated.insert(id.to_vec(), servant);
1698                        (None, None)
1699                    } else {
1700                        (None, Some((activator, servant)))
1701                    }
1702                }
1703                _ => (Some(servant), None),
1704            }
1705        };
1706        drop(servant);
1707        if let Some((activator, servant)) = now {
1708            let work = Etherealization {
1709                poa: Arc::clone(&self.inner),
1710                activator,
1711                id: id.to_vec(),
1712                servant,
1713                cleanup_in_progress: false,
1714            };
1715            if let Some(server) = self.orb.server() {
1716                server.etherealize_later(work);
1717            }
1718        }
1719        Ok(())
1720    }
1721
1722    /// `servant_to_id`: the ObjectId of an active servant (UNIQUE_ID), a
1723    /// new one with IMPLICIT_ACTIVATION, or, for the default servant inside
1724    /// a request it runs, the ObjectId of that request.
1725    pub fn servant_to_id(&self, servant: &Arc<dyn Servant>) -> Result<ObjectId, PoaError> {
1726        let p = self.inner.policies;
1727        let retain = p.servant_retention == ServantRetention::Retain;
1728        let default_servant = p.request_processing == RequestProcessing::UseDefaultServant;
1729        if !default_servant
1730            && !(retain
1731                && (p.id_uniqueness == IdUniqueness::Unique
1732                    || p.implicit_activation == ImplicitActivation::Implicit))
1733        {
1734            return Err(PoaError::WrongPolicy);
1735        }
1736        let mut st = self.state()?;
1737        if retain && p.id_uniqueness == IdUniqueness::Unique {
1738            if let Some(id) = st.ids.get(&servant_addr(servant)) {
1739                return Ok(id.clone());
1740            }
1741        }
1742        if retain && p.implicit_activation == ImplicitActivation::Implicit {
1743            let id = self.inner.generate_id(&mut st);
1744            self.inner
1745                .activate(&mut st, id.clone(), Arc::clone(servant))?;
1746            return Ok(id);
1747        }
1748        let is_default = st
1749            .default_servant
1750            .as_ref()
1751            .is_some_and(|d| same_servant(d, servant));
1752        drop(st);
1753        if is_default {
1754            let current = CURRENT.with(|c| {
1755                c.borrow()
1756                    .last()
1757                    .filter(|e| e.poa == *self && same_servant(&e.servant, servant))
1758                    .map(|e| e.id.clone())
1759            });
1760            if let Some(id) = current {
1761                return Ok(id);
1762            }
1763        }
1764        Err(PoaError::ServantNotActive)
1765    }
1766
1767    /// `servant_to_reference`, activating the servant like
1768    /// [`servant_to_id`](Poa::servant_to_id).
1769    pub fn servant_to_reference(&self, servant: &Arc<dyn Servant>) -> Result<ObjectRef, PoaError> {
1770        let id = self.servant_to_id(servant)?;
1771        self.reference(&id, servant.repository_id())
1772    }
1773
1774    /// `id_to_servant` (RETAIN or USE_DEFAULT_SERVANT): the servant active
1775    /// under `id`, or else the default servant.
1776    pub fn id_to_servant(&self, id: &[u8]) -> Result<Arc<dyn Servant>, PoaError> {
1777        let p = self.inner.policies;
1778        let retain = p.servant_retention == ServantRetention::Retain;
1779        let default_servant = p.request_processing == RequestProcessing::UseDefaultServant;
1780        if !retain && !default_servant {
1781            return Err(PoaError::WrongPolicy);
1782        }
1783        let st = self.state()?;
1784        let active = retain.then(|| st.active.get(id).cloned()).flatten();
1785        active
1786            .or_else(|| st.default_servant.clone().filter(|_| default_servant))
1787            .ok_or(PoaError::ObjectNotActive)
1788    }
1789
1790    /// `id_to_reference` (RETAIN only): a reference to the active object
1791    /// `id`, with the servant's repository id as type id.
1792    pub fn id_to_reference(&self, id: &[u8]) -> Result<ObjectRef, PoaError> {
1793        self.check_retain()?;
1794        let servant = self
1795            .state()?
1796            .active
1797            .get(id)
1798            .cloned()
1799            .ok_or(PoaError::ObjectNotActive)?;
1800        self.reference(id, servant.repository_id())
1801    }
1802
1803    /// `create_reference`: a reference with a new ObjectId and the type id
1804    /// `intf`, without activating anything (SYSTEM_ID only).
1805    pub fn create_reference(&self, intf: &str) -> Result<ObjectRef, PoaError> {
1806        if self.inner.policies.id_assignment != IdAssignment::System {
1807            return Err(PoaError::WrongPolicy);
1808        }
1809        let id = {
1810            let mut st = self.state()?;
1811            self.inner.generate_id(&mut st)
1812        };
1813        self.reference(&id, intf)
1814    }
1815
1816    /// `create_reference_with_id`: a reference to `id` with the type id
1817    /// `intf`, without activating anything.
1818    pub fn create_reference_with_id(&self, id: &[u8], intf: &str) -> Result<ObjectRef, PoaError> {
1819        drop(self.state()?);
1820        self.reference(id, intf)
1821    }
1822
1823    /// `reference_to_id`: the ObjectId of a reference made by this POA
1824    /// (`WrongAdapter` for any other).
1825    pub fn reference_to_id(&self, reference: &ObjectRef) -> Result<ObjectId, PoaError> {
1826        drop(self.state()?);
1827        let prefix = &self.inner.key_prefix;
1828        reference
1829            .ior()
1830            .iiop_profiles()
1831            .filter_map(Result::ok)
1832            .map(|p: IiopProfile| p.object_key)
1833            .find(|key| key.starts_with(prefix))
1834            .map(|key| key[prefix.len()..].to_vec())
1835            .ok_or(PoaError::WrongAdapter)
1836    }
1837
1838    /// `reference_to_servant`.
1839    pub fn reference_to_servant(
1840        &self,
1841        reference: &ObjectRef,
1842    ) -> Result<Arc<dyn Servant>, PoaError> {
1843        let id = self.reference_to_id(reference)?;
1844        self.id_to_servant(&id)
1845    }
1846
1847    pub(crate) fn reference(&self, id: &[u8], type_id: &str) -> Result<ObjectRef, PoaError> {
1848        let server = self.server()?;
1849        let ior = server.ior(type_id, self.inner.key(id))?;
1850        Ok(ObjectRef::new(self.orb.clone(), ior))
1851    }
1852}
1853
1854pub(crate) mod log {
1855    /// Writes a warning to standard error, like omniORB's trace output.
1856    pub(crate) fn warn(msg: &str) {
1857        eprintln!("rustorb: warning: {msg}");
1858    }
1859}
1860
1861#[cfg(test)]
1862mod tests {
1863    use super::*;
1864
1865    #[test]
1866    fn keys_parse_back() {
1867        let boot = [1, 2, 3, 4, 5, 6, 7, 8];
1868        assert_eq!(
1869            parse_key(b"\xffpersistent_user\x00obj"),
1870            ParsedKey::Poa {
1871                path: vec!["persistent_user"],
1872                boot_id: None,
1873                id: b"obj"
1874            }
1875        );
1876        assert_eq!(
1877            parse_key(b"\xffa\xffnested\x00"),
1878            ParsedKey::Poa {
1879                path: vec!["a", "nested"],
1880                boot_id: None,
1881                id: b""
1882            }
1883        );
1884        let mut transient = b"\xffchild\xfe".to_vec();
1885        transient.extend_from_slice(&boot);
1886        transient.extend_from_slice(b"id");
1887        assert_eq!(
1888            parse_key(&transient),
1889            ParsedKey::Poa {
1890                path: vec!["child"],
1891                boot_id: Some(&boot),
1892                id: b"id"
1893            }
1894        );
1895        let mut root = vec![0xfe];
1896        root.extend_from_slice(&boot);
1897        assert_eq!(
1898            parse_key(&root),
1899            ParsedKey::Poa {
1900                path: vec![],
1901                boot_id: Some(&boot),
1902                id: b""
1903            }
1904        );
1905        assert_eq!(parse_key(b"NameService"), ParsedKey::Simple(b"NameService"));
1906        assert_eq!(parse_key(b""), ParsedKey::Simple(b""));
1907        assert_eq!(parse_key(b"\xffno-end"), ParsedKey::Invalid);
1908        assert_eq!(parse_key(b"\xfe\x01\x02"), ParsedKey::Invalid);
1909        assert_eq!(parse_key(b"\xff\xff\x00x"), ParsedKey::Invalid);
1910    }
1911
1912    #[test]
1913    fn policy_lists() {
1914        assert_eq!(Policies::from_list(&[]), Ok(Policies::default()));
1915        let p = Policies::from_list(&[
1916            Policy::Lifespan(Lifespan::Persistent),
1917            Policy::IdAssignment(IdAssignment::User),
1918        ])
1919        .unwrap();
1920        assert_eq!(p.lifespan, Lifespan::Persistent);
1921        assert_eq!(p.id_assignment, IdAssignment::User);
1922        assert_eq!(
1923            Policies::from_list(&[
1924                Policy::Lifespan(Lifespan::Persistent),
1925                Policy::Lifespan(Lifespan::Transient),
1926            ]),
1927            Err(1)
1928        );
1929        assert_eq!(
1930            Policies::from_list(&[
1931                Policy::IdAssignment(IdAssignment::User),
1932                Policy::ImplicitActivation(ImplicitActivation::Implicit),
1933            ]),
1934            Err(1)
1935        );
1936        assert_eq!(
1937            Policies::from_list(&[Policy::Thread(ThreadPolicy::MainThread)])
1938                .unwrap()
1939                .thread,
1940            ThreadPolicy::MainThread
1941        );
1942        // NON_RETAIN needs a default servant or a servant manager.
1943        assert_eq!(
1944            Policies::from_list(&[Policy::ServantRetention(ServantRetention::NonRetain)]),
1945            Err(0)
1946        );
1947        assert!(
1948            Policies::from_list(&[
1949                Policy::ServantRetention(ServantRetention::NonRetain),
1950                Policy::RequestProcessing(RequestProcessing::UseServantManager),
1951            ])
1952            .is_ok()
1953        );
1954        // A default servant serves many ObjectIds.
1955        assert_eq!(
1956            Policies::from_list(&[Policy::RequestProcessing(
1957                RequestProcessing::UseDefaultServant
1958            )]),
1959            Err(0)
1960        );
1961        assert!(
1962            Policies::from_list(&[
1963                Policy::RequestProcessing(RequestProcessing::UseDefaultServant),
1964                Policy::IdUniqueness(IdUniqueness::Multiple),
1965            ])
1966            .is_ok()
1967        );
1968        assert_eq!(
1969            Policies::from_list(&[
1970                Policy::ImplicitActivation(ImplicitActivation::Implicit),
1971                Policy::ServantRetention(ServantRetention::NonRetain),
1972                Policy::RequestProcessing(RequestProcessing::UseServantManager),
1973            ]),
1974            Err(0)
1975        );
1976    }
1977}