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