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