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