1use std::cell::{Cell, RefCell};
17use std::collections::{HashMap, HashSet, VecDeque};
18use std::fmt;
19use std::panic::{self, AssertUnwindSafe};
20use std::sync::{Arc, Condvar, Mutex, MutexGuard, Weak};
21use std::thread::{self, ThreadId};
22
23use rustorb_giop::IiopProfile;
24
25use crate::pool::Job;
26use crate::servant::{Cookie, ServantLocator};
27use crate::server::Server;
28use crate::{
29 AdapterActivator, CompletionStatus, ObjectRef, Orb, Servant, ServantActivator, ServantManager,
30 ServantManagerError, SystemException, SystemExceptionKind, minor,
31};
32
33pub type ObjectId = Vec<u8>;
35
36const PATH_START: u8 = 0xff;
37const PATH_SEPARATOR: u8 = 0xff;
38const PERSISTENT_END: u8 = 0x00;
39const TRANSIENT_END: u8 = 0xfe;
40pub(crate) const BOOT_ID_LEN: usize = 8;
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
45pub enum ThreadPolicy {
46 OrbCtrl,
49 SingleThread,
54 MainThread,
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
62pub enum Lifespan {
63 Transient,
65 Persistent,
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
72pub enum IdUniqueness {
73 Unique,
75 Multiple,
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
81pub enum IdAssignment {
82 User,
84 System,
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
90pub enum ImplicitActivation {
91 Implicit,
93 NoImplicit,
95}
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
99pub enum ServantRetention {
100 Retain,
102 NonRetain,
105}
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
109pub enum RequestProcessing {
110 ActiveObjectMapOnly,
112 UseDefaultServant,
115 UseServantManager,
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
122pub enum Policy {
123 Thread(ThreadPolicy),
125 Lifespan(Lifespan),
127 IdUniqueness(IdUniqueness),
129 IdAssignment(IdAssignment),
131 ImplicitActivation(ImplicitActivation),
133 ServantRetention(ServantRetention),
135 RequestProcessing(RequestProcessing),
137}
138
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub struct Policies {
142 pub thread: ThreadPolicy,
144 pub lifespan: Lifespan,
146 pub id_uniqueness: IdUniqueness,
148 pub id_assignment: IdAssignment,
150 pub implicit_activation: ImplicitActivation,
152 pub servant_retention: ServantRetention,
154 pub request_processing: RequestProcessing,
156}
157
158impl Default for Policies {
159 fn default() -> Policies {
161 Policies {
162 thread: ThreadPolicy::OrbCtrl,
163 lifespan: Lifespan::Transient,
164 id_uniqueness: IdUniqueness::Unique,
165 id_assignment: IdAssignment::System,
166 implicit_activation: ImplicitActivation::NoImplicit,
167 servant_retention: ServantRetention::Retain,
168 request_processing: RequestProcessing::ActiveObjectMapOnly,
169 }
170 }
171}
172
173impl Policies {
174 pub(crate) fn root() -> Policies {
176 Policies {
177 implicit_activation: ImplicitActivation::Implicit,
178 ..Policies::default()
179 }
180 }
181
182 fn from_list(list: &[Policy]) -> Result<Policies, u16> {
185 let mut p = Policies::default();
186 let mut seen = Vec::new();
187 let index = |i: usize| u16::try_from(i).unwrap_or(u16::MAX);
188 for (i, policy) in list.iter().enumerate() {
189 let kind = std::mem::discriminant(policy);
190 if seen.contains(&kind) {
191 return Err(index(i));
192 }
193 seen.push(kind);
194 match *policy {
195 Policy::Thread(v) => p.thread = v,
196 Policy::Lifespan(v) => p.lifespan = v,
197 Policy::IdUniqueness(v) => p.id_uniqueness = v,
198 Policy::IdAssignment(v) => p.id_assignment = v,
199 Policy::ImplicitActivation(v) => p.implicit_activation = v,
200 Policy::ServantRetention(v) => p.servant_retention = v,
201 Policy::RequestProcessing(v) => p.request_processing = v,
202 }
203 }
204 let position = |f: fn(&Policy) -> bool| index(list.iter().rposition(f).unwrap_or(0));
207 if p.implicit_activation == ImplicitActivation::Implicit
208 && (p.id_assignment != IdAssignment::System
209 || p.servant_retention != ServantRetention::Retain)
210 {
211 return Err(position(|q| matches!(q, Policy::ImplicitActivation(_))));
212 }
213 if p.servant_retention == ServantRetention::NonRetain
214 && p.request_processing == RequestProcessing::ActiveObjectMapOnly
215 {
216 return Err(position(|q| {
217 matches!(
218 q,
219 Policy::ServantRetention(_) | Policy::RequestProcessing(_)
220 )
221 }));
222 }
223 if p.request_processing == RequestProcessing::UseDefaultServant
224 && p.id_uniqueness != IdUniqueness::Multiple
225 {
226 return Err(position(|q| {
227 matches!(q, Policy::RequestProcessing(_) | Policy::IdUniqueness(_))
228 }));
229 }
230 Ok(p)
231 }
232}
233
234#[derive(Debug, Clone, PartialEq, Eq)]
237pub enum PoaError {
238 AdapterAlreadyExists,
240 AdapterNonExistent,
242 InvalidPolicy(u16),
244 ServantAlreadyActive,
246 ObjectAlreadyActive,
248 ServantNotActive,
250 ObjectNotActive,
252 WrongPolicy,
254 WrongAdapter,
256 AdapterInactive,
258 NoServant,
260 NoContext,
262 System(SystemException),
264}
265
266impl fmt::Display for PoaError {
267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268 match self {
269 PoaError::AdapterAlreadyExists => {
270 f.write_str("PortableServer::POA::AdapterAlreadyExists")
271 }
272 PoaError::AdapterNonExistent => f.write_str("PortableServer::POA::AdapterNonExistent"),
273 PoaError::InvalidPolicy(i) => {
274 write!(f, "PortableServer::POA::InvalidPolicy (index {i})")
275 }
276 PoaError::ServantAlreadyActive => {
277 f.write_str("PortableServer::POA::ServantAlreadyActive")
278 }
279 PoaError::ObjectAlreadyActive => {
280 f.write_str("PortableServer::POA::ObjectAlreadyActive")
281 }
282 PoaError::ServantNotActive => f.write_str("PortableServer::POA::ServantNotActive"),
283 PoaError::ObjectNotActive => f.write_str("PortableServer::POA::ObjectNotActive"),
284 PoaError::WrongPolicy => f.write_str("PortableServer::POA::WrongPolicy"),
285 PoaError::WrongAdapter => f.write_str("PortableServer::POA::WrongAdapter"),
286 PoaError::AdapterInactive => f.write_str("PortableServer::POAManager::AdapterInactive"),
287 PoaError::NoServant => f.write_str("PortableServer::POA::NoServant"),
288 PoaError::NoContext => f.write_str("PortableServer::Current::NoContext"),
289 PoaError::System(e) => e.fmt(f),
290 }
291 }
292}
293
294impl std::error::Error for PoaError {}
295
296impl From<SystemException> for PoaError {
297 fn from(e: SystemException) -> Self {
298 PoaError::System(e)
299 }
300}
301
302fn sys(kind: SystemExceptionKind, minor: u32) -> SystemException {
303 SystemException::new(kind, minor, CompletionStatus::No)
304}
305
306pub(crate) fn no_such_object() -> SystemException {
308 sys(SystemExceptionKind::OBJECT_NOT_EXIST, minor::NO_SUCH_OBJECT)
309}
310
311thread_local! {
314 static UPCALL_DEPTH: Cell<usize> = const { Cell::new(0) };
315 static MAIN_DEPTH: Cell<usize> = const { Cell::new(0) };
316 static CURRENT: RefCell<Vec<CurrentEntry>> = const { RefCell::new(Vec::new()) };
317}
318
319#[derive(Clone)]
321struct CurrentEntry {
322 poa: Poa,
323 id: ObjectId,
324 servant: Arc<dyn Servant>,
325}
326
327pub(crate) struct CurrentGuard(());
329
330impl CurrentGuard {
331 pub(crate) fn enter(poa: &Poa, id: &[u8], servant: &Arc<dyn Servant>) -> CurrentGuard {
332 CURRENT.with(|c| {
333 c.borrow_mut().push(CurrentEntry {
334 poa: poa.clone(),
335 id: id.to_vec(),
336 servant: Arc::clone(servant),
337 });
338 });
339 CurrentGuard(())
340 }
341}
342
343impl Drop for CurrentGuard {
344 fn drop(&mut self) {
345 CURRENT.with(|c| c.borrow_mut().pop());
346 }
347}
348
349#[derive(Debug, Clone, Copy, Default)]
353pub struct PoaCurrent;
354
355impl PoaCurrent {
356 fn with<T>(f: impl FnOnce(&CurrentEntry) -> T) -> Result<T, PoaError> {
357 CURRENT.with(|c| c.borrow().last().map(f).ok_or(PoaError::NoContext))
358 }
359
360 pub fn get_poa() -> Result<Poa, PoaError> {
362 PoaCurrent::with(|e| e.poa.clone())
363 }
364
365 pub fn get_object_id() -> Result<ObjectId, PoaError> {
367 PoaCurrent::with(|e| e.id.clone())
368 }
369
370 pub fn get_reference() -> Result<ObjectRef, PoaError> {
372 let (poa, id, servant) =
373 PoaCurrent::with(|e| (e.poa.clone(), e.id.clone(), Arc::clone(&e.servant)))?;
374 poa.reference(&id, servant.repository_id())
375 }
376
377 pub fn get_servant() -> Result<Arc<dyn Servant>, PoaError> {
379 PoaCurrent::with(|e| Arc::clone(&e.servant))
380 }
381}
382
383pub(crate) struct MainThreadGuard(());
386
387impl MainThreadGuard {
388 pub(crate) fn enter() -> MainThreadGuard {
389 MAIN_DEPTH.with(|d| d.set(d.get() + 1));
390 MainThreadGuard(())
391 }
392}
393
394impl Drop for MainThreadGuard {
395 fn drop(&mut self) {
396 MAIN_DEPTH.with(|d| d.set(d.get() - 1));
397 }
398}
399
400pub(crate) fn is_main_thread() -> bool {
402 MAIN_DEPTH.with(Cell::get) > 0
403}
404
405pub(crate) fn in_upcall() -> bool {
407 UPCALL_DEPTH.with(Cell::get) > 0
408}
409
410pub(crate) struct UpcallGuard(());
412
413impl UpcallGuard {
414 pub(crate) fn enter() -> UpcallGuard {
415 UPCALL_DEPTH.with(|d| d.set(d.get() + 1));
416 UpcallGuard(())
417 }
418}
419
420impl Drop for UpcallGuard {
421 fn drop(&mut self) {
422 UPCALL_DEPTH.with(|d| d.set(d.get() - 1));
423 }
424}
425
426#[derive(Debug, Default)]
428pub(crate) struct Activity {
429 count: Mutex<usize>,
430 idle: Condvar,
431}
432
433impl Activity {
434 pub(crate) fn enter(self: &Arc<Self>) -> ActivityGuard {
435 *self.count.lock().unwrap() += 1;
436 ActivityGuard(Arc::clone(self))
437 }
438
439 pub(crate) fn wait_idle(&self) {
440 let mut count = self.count.lock().unwrap();
441 while *count > 0 {
442 count = self.idle.wait(count).unwrap();
443 }
444 }
445}
446
447pub(crate) struct ActivityGuard(Arc<Activity>);
448
449impl Drop for ActivityGuard {
450 fn drop(&mut self) {
451 let mut count = self.0.count.lock().unwrap();
452 *count -= 1;
453 if *count == 0 {
454 self.0.idle.notify_all();
455 }
456 }
457}
458
459fn check_wait(wait_for_completion: bool) -> Result<(), SystemException> {
462 if wait_for_completion && in_upcall() {
463 return Err(sys(
464 SystemExceptionKind::BAD_INV_ORDER,
465 minor::WOULD_DEADLOCK,
466 ));
467 }
468 Ok(())
469}
470
471#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
475pub enum PoaManagerState {
476 Holding,
478 Active,
480 Discarding,
482 Inactive,
485}
486
487pub(crate) enum Disposition {
489 Run,
493 Reject(SystemException),
495}
496
497pub(crate) type Dispatch = Box<dyn FnOnce(Disposition) + Send>;
498
499const MAX_HELD_REQUESTS: usize = 4096;
502
503#[derive(Clone)]
508pub struct PoaManager {
509 pub(crate) inner: Arc<ManagerInner>,
510}
511
512pub(crate) struct ManagerInner {
513 state: Mutex<ManagerState>,
514 activity: Arc<Activity>,
515 server: Weak<Server>,
516 poas: Mutex<Vec<Weak<PoaInner>>>,
518}
519
520struct ManagerState {
521 state: PoaManagerState,
522 held: VecDeque<Dispatch>,
523}
524
525impl fmt::Debug for PoaManager {
526 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
527 f.debug_struct("PoaManager")
528 .field("state", &self.state())
529 .finish_non_exhaustive()
530 }
531}
532
533impl PartialEq for PoaManager {
534 fn eq(&self, other: &Self) -> bool {
535 Arc::ptr_eq(&self.inner, &other.inner)
536 }
537}
538
539impl Eq for PoaManager {}
540
541impl PoaManager {
542 pub(crate) fn new(server: &Arc<Server>) -> PoaManager {
543 let inner = Arc::new(ManagerInner {
544 state: Mutex::new(ManagerState {
545 state: PoaManagerState::Holding,
546 held: VecDeque::new(),
547 }),
548 activity: Arc::default(),
549 server: Arc::downgrade(server),
550 poas: Mutex::new(Vec::new()),
551 });
552 server.register_manager(&inner);
553 PoaManager { inner }
554 }
555
556 pub fn state(&self) -> PoaManagerState {
558 self.inner.state.lock().unwrap().state
559 }
560
561 pub fn activate(&self) -> Result<(), PoaError> {
564 let held = {
565 let mut st = self.inner.state.lock().unwrap();
566 if st.state == PoaManagerState::Inactive {
567 return Err(PoaError::AdapterInactive);
568 }
569 st.state = PoaManagerState::Active;
570 std::mem::take(&mut st.held)
571 };
572 for dispatch in held {
573 dispatch(Disposition::Run);
574 }
575 Ok(())
576 }
577
578 pub fn hold_requests(&self, wait_for_completion: bool) -> Result<(), PoaError> {
582 check_wait(wait_for_completion)?;
583 self.set(PoaManagerState::Holding)?;
584 if wait_for_completion {
585 self.inner.activity.wait_idle();
586 }
587 Ok(())
588 }
589
590 pub fn discard_requests(&self, wait_for_completion: bool) -> Result<(), PoaError> {
592 check_wait(wait_for_completion)?;
593 self.set(PoaManagerState::Discarding)?;
594 if wait_for_completion {
595 self.inner.activity.wait_idle();
596 }
597 Ok(())
598 }
599
600 pub fn deactivate(&self, etherealize: bool, wait_for_completion: bool) -> Result<(), PoaError> {
606 check_wait(wait_for_completion)?;
607 self.set(PoaManagerState::Inactive)?;
608 if etherealize {
609 let poas: Vec<_> = self
610 .inner
611 .poas
612 .lock()
613 .unwrap()
614 .iter()
615 .filter_map(Weak::upgrade)
616 .collect();
617 let mut work = Vec::new();
618 for poa in poas {
619 work.extend(poa.take_for_etherealize());
620 }
621 if let Some(server) = self.inner.server.upgrade() {
622 server.etherealize(work, wait_for_completion);
623 }
624 }
625 if wait_for_completion {
626 self.inner.activity.wait_idle();
627 }
628 Ok(())
629 }
630
631 fn set(&self, state: PoaManagerState) -> Result<(), PoaError> {
632 let held = {
633 let mut st = self.inner.state.lock().unwrap();
634 if st.state == PoaManagerState::Inactive {
635 return Err(PoaError::AdapterInactive);
636 }
637 st.state = state;
638 if state == PoaManagerState::Holding {
639 return Ok(());
640 }
641 std::mem::take(&mut st.held)
642 };
643 let e = refusal(state);
644 for dispatch in held {
645 dispatch(Disposition::Reject(e.clone()));
646 }
647 Ok(())
648 }
649}
650
651fn refusal(state: PoaManagerState) -> SystemException {
653 match state {
654 PoaManagerState::Inactive => sys(SystemExceptionKind::OBJ_ADAPTER, minor::POA_INACTIVE),
655 _ => sys(SystemExceptionKind::TRANSIENT, minor::POA_DISCARDING),
656 }
657}
658
659impl ManagerInner {
660 pub(crate) fn dispatch(&self, dispatch: Dispatch) {
662 let mut st = self.state.lock().unwrap();
663 match st.state {
664 PoaManagerState::Active => {
665 drop(st);
666 dispatch(Disposition::Run);
667 }
668 PoaManagerState::Holding if st.held.len() < MAX_HELD_REQUESTS => {
669 st.held.push_back(dispatch);
670 }
671 PoaManagerState::Holding => {
672 drop(st);
673 dispatch(Disposition::Reject(sys(SystemExceptionKind::TRANSIENT, 0)));
674 }
675 state => {
676 drop(st);
677 dispatch(Disposition::Reject(refusal(state)));
678 }
679 }
680 }
681
682 pub(crate) fn is_inactive(&self) -> bool {
684 self.state.lock().unwrap().state == PoaManagerState::Inactive
685 }
686
687 pub(crate) fn activity(&self) -> &Arc<Activity> {
688 &self.activity
689 }
690
691 fn add_poa(&self, poa: &Arc<PoaInner>) {
692 let mut poas = self.poas.lock().unwrap();
693 poas.retain(|p| p.strong_count() > 0);
694 poas.push(Arc::downgrade(poa));
695 }
696
697 pub(crate) fn shut_down(&self) {
701 let held = {
702 let mut st = self.state.lock().unwrap();
703 st.state = PoaManagerState::Inactive;
704 std::mem::take(&mut st.held)
705 };
706 drop(held);
707 }
708}
709
710#[derive(Clone)]
717pub struct Poa {
718 pub(crate) orb: Orb,
719 pub(crate) inner: Arc<PoaInner>,
720}
721
722pub(crate) struct PoaInner {
723 name: String,
724 path: Vec<String>,
727 policies: Policies,
728 pub(crate) manager: PoaManager,
729 parent: Option<Weak<PoaInner>>,
730 key_prefix: Vec<u8>,
732 boot_id: [u8; BOOT_ID_LEN],
733 activity: Arc<Activity>,
734 state: Mutex<PoaState>,
735 changed: Condvar,
737 serial: Mutex<Serial>,
739}
740
741#[derive(Default)]
742struct PoaState {
743 destroyed: bool,
744 children: HashMap<String, Arc<PoaInner>>,
745 active: HashMap<ObjectId, Arc<dyn Servant>>,
746 ids: HashMap<usize, ObjectId>,
748 next_id: u32,
749 default_servant: Option<Arc<dyn Servant>>,
750 servant_manager: Option<ServantManager>,
751 activator: Option<Arc<dyn AdapterActivator>>,
752 incarnating: HashSet<ObjectId>,
754 activating: HashSet<String>,
756 running: HashMap<ObjectId, usize>,
759 deactivated: HashMap<ObjectId, Arc<dyn Servant>>,
761}
762
763#[derive(Default)]
766struct Serial {
767 queue: VecDeque<Job>,
768 busy: bool,
770 owner: Option<ThreadId>,
772}
773
774pub(crate) enum SerialEntry {
776 Reentrant,
778 Acquired(SerialGuard),
781 Busy,
783}
784
785pub(crate) struct SerialGuard {
786 poa: Arc<PoaInner>,
787 server: Arc<Server>,
788}
789
790impl Drop for SerialGuard {
791 fn drop(&mut self) {
792 self.poa.release_serial(&self.server);
793 }
794}
795
796pub(crate) struct Etherealization {
798 poa: Arc<PoaInner>,
799 activator: Arc<dyn ServantActivator>,
800 id: ObjectId,
801 servant: Arc<dyn Servant>,
802 cleanup_in_progress: bool,
803}
804
805impl Etherealization {
806 pub(crate) fn poa(&self) -> &Arc<PoaInner> {
807 &self.poa
808 }
809
810 pub(crate) fn run(self, orb: &Orb, remaining: Option<bool>) {
814 let remaining = remaining.unwrap_or_else(|| {
815 let st = self.poa.state.lock().unwrap();
816 st.active.values().any(|s| same_servant(s, &self.servant))
817 });
818 let adapter = Poa {
819 orb: orb.clone(),
820 inner: self.poa,
821 };
822 let _upcall = UpcallGuard::enter();
823 let result = panic::catch_unwind(AssertUnwindSafe(|| {
824 self.activator.etherealize(
825 &self.id,
826 &adapter,
827 self.servant,
828 self.cleanup_in_progress,
829 remaining,
830 );
831 }));
832 if result.is_err() {
833 log::warn("servant activator panicked in etherealize");
834 }
835 }
836}
837
838pub(crate) fn etherealize_all(orb: &Orb, etherealizations: Vec<Etherealization>) {
841 let mut rest = etherealizations;
842 while !rest.is_empty() {
843 let e = rest.remove(0);
844 let remaining = rest.iter().any(|r| same_servant(&r.servant, &e.servant));
845 e.run(orb, Some(remaining));
846 }
847}
848
849pub(crate) struct Resolved {
851 pub(crate) servant: Arc<dyn Servant>,
852 _object: Option<ObjectGuard>,
854 locator: Option<(Arc<dyn ServantLocator>, Cookie)>,
856}
857
858impl Resolved {
859 pub(crate) fn finish(self, adapter: &Poa, id: &[u8], operation: &str) {
861 if let Some((locator, cookie)) = self.locator {
862 let servant = self.servant;
863 let result = panic::catch_unwind(AssertUnwindSafe(|| {
864 locator.postinvoke(id, adapter, operation, cookie, servant);
865 }));
866 if result.is_err() {
867 log::warn("servant locator panicked in postinvoke");
868 }
869 }
870 }
871}
872
873pub(crate) struct ObjectGuard {
874 poa: Arc<PoaInner>,
875 server: Weak<Server>,
876 id: ObjectId,
877}
878
879impl Drop for ObjectGuard {
880 fn drop(&mut self) {
881 let pending = {
882 let mut st = self.poa.state.lock().unwrap();
883 let Some(count) = st.running.get_mut(&self.id) else {
884 return;
885 };
886 *count -= 1;
887 if *count > 0 {
888 return;
889 }
890 st.running.remove(&self.id);
891 if st.destroyed {
892 return;
893 }
894 let Some(servant) = st.deactivated.remove(&self.id) else {
895 return;
896 };
897 let Some(ServantManager::Activator(activator)) = st.servant_manager.clone() else {
898 return;
899 };
900 Etherealization {
901 poa: Arc::clone(&self.poa),
902 activator,
903 id: std::mem::take(&mut self.id),
904 servant,
905 cleanup_in_progress: false,
906 }
907 };
908 if let Some(server) = self.server.upgrade() {
909 server.etherealize_later(pending);
910 }
911 }
912}
913
914impl fmt::Debug for Poa {
915 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
916 f.debug_struct("Poa")
917 .field("name", &self.inner.name)
918 .field("path", &self.inner.path)
919 .field("policies", &self.inner.policies)
920 .finish_non_exhaustive()
921 }
922}
923
924impl PartialEq for Poa {
925 fn eq(&self, other: &Self) -> bool {
926 Arc::ptr_eq(&self.inner, &other.inner)
927 }
928}
929
930impl Eq for Poa {}
931
932fn servant_addr(servant: &Arc<dyn Servant>) -> usize {
933 Arc::as_ptr(servant).cast::<()>() as usize
934}
935
936fn same_servant(a: &Arc<dyn Servant>, b: &Arc<dyn Servant>) -> bool {
937 servant_addr(a) == servant_addr(b)
938}
939
940type Drained = (
943 Vec<(ObjectId, Arc<dyn Servant>)>,
944 Option<Arc<dyn ServantActivator>>,
945);
946
947fn drain(st: &mut PoaState) -> Drained {
949 st.ids.clear();
950 let mut entries: Vec<_> = std::mem::take(&mut st.active)
951 .into_iter()
952 .chain(std::mem::take(&mut st.deactivated))
953 .collect();
954 entries.sort_by(|a, b| a.0.cmp(&b.0));
955 let activator = match &st.servant_manager {
956 Some(ServantManager::Activator(a)) => Some(Arc::clone(a)),
957 _ => None,
958 };
959 (entries, activator)
960}
961
962fn catch<T>(
963 what: &str,
964 f: impl FnOnce() -> Result<T, ServantManagerError>,
965) -> Result<T, ServantManagerError> {
966 let _upcall = UpcallGuard::enter();
967 panic::catch_unwind(AssertUnwindSafe(f)).unwrap_or_else(|_| {
968 log::warn(&format!("servant manager panicked in {what}"));
969 Err(SystemException::new(SystemExceptionKind::UNKNOWN, 0, CompletionStatus::Maybe).into())
970 })
971}
972
973impl PoaInner {
974 fn new(
975 name: String,
976 path: Vec<String>,
977 policies: Policies,
978 manager: PoaManager,
979 parent: Option<Weak<PoaInner>>,
980 key_prefix: Vec<u8>,
981 boot_id: [u8; BOOT_ID_LEN],
982 ) -> Arc<PoaInner> {
983 let poa = Arc::new(PoaInner {
984 name,
985 path,
986 policies,
987 manager,
988 parent,
989 key_prefix,
990 boot_id,
991 activity: Arc::default(),
992 state: Mutex::default(),
993 changed: Condvar::new(),
994 serial: Mutex::default(),
995 });
996 poa.manager.inner.add_poa(&poa);
997 poa
998 }
999
1000 pub(crate) fn new_root(manager: PoaManager, boot_id: [u8; BOOT_ID_LEN]) -> Arc<PoaInner> {
1001 let mut key_prefix = vec![TRANSIENT_END];
1002 key_prefix.extend_from_slice(&boot_id);
1003 PoaInner::new(
1004 "RootPOA".into(),
1005 Vec::new(),
1006 Policies::root(),
1007 manager,
1008 None,
1009 key_prefix,
1010 boot_id,
1011 )
1012 }
1013
1014 fn new_child(
1015 parent: &Arc<PoaInner>,
1016 name: &str,
1017 manager: PoaManager,
1018 policies: Policies,
1019 ) -> Arc<PoaInner> {
1020 let mut path = parent.path.clone();
1021 path.push(name.to_owned());
1022 let mut key_prefix = vec![PATH_START];
1023 for (i, n) in path.iter().enumerate() {
1024 if i > 0 {
1025 key_prefix.push(PATH_SEPARATOR);
1026 }
1027 key_prefix.extend_from_slice(n.as_bytes());
1028 }
1029 match policies.lifespan {
1030 Lifespan::Persistent => key_prefix.push(PERSISTENT_END),
1031 Lifespan::Transient => {
1032 key_prefix.push(TRANSIENT_END);
1033 key_prefix.extend_from_slice(&parent.boot_id);
1034 }
1035 }
1036 PoaInner::new(
1037 name.to_owned(),
1038 path,
1039 policies,
1040 manager,
1041 Some(Arc::downgrade(parent)),
1042 key_prefix,
1043 parent.boot_id,
1044 )
1045 }
1046
1047 pub(crate) fn policies(&self) -> &Policies {
1048 &self.policies
1049 }
1050
1051 pub(crate) fn activity(&self) -> &Arc<Activity> {
1052 &self.activity
1053 }
1054
1055 pub(crate) fn key(&self, id: &[u8]) -> Vec<u8> {
1056 let mut key = self.key_prefix.clone();
1057 key.extend_from_slice(id);
1058 key
1059 }
1060
1061 pub(crate) fn child(&self, name: &str) -> Result<Arc<PoaInner>, bool> {
1064 let st = self.state.lock().unwrap();
1065 if st.destroyed {
1066 return Err(false);
1067 }
1068 st.children.get(name).cloned().ok_or(st.activator.is_some())
1069 }
1070
1071 pub(crate) fn find_or_activate_child(
1074 self: &Arc<Self>,
1075 orb: &Orb,
1076 name: &str,
1077 ) -> Option<Arc<PoaInner>> {
1078 let mut st = self.state.lock().unwrap();
1079 loop {
1080 if st.destroyed {
1081 return None;
1082 }
1083 if let Some(child) = st.children.get(name) {
1084 return Some(Arc::clone(child));
1085 }
1086 let activator = st.activator.clone()?;
1087 if st.activating.contains(name) {
1088 st = self.changed.wait(st).unwrap();
1089 continue;
1090 }
1091 st.activating.insert(name.to_owned());
1092 drop(st);
1093 let parent = Poa {
1094 orb: orb.clone(),
1095 inner: Arc::clone(self),
1096 };
1097 let created = {
1098 let _upcall = UpcallGuard::enter();
1099 panic::catch_unwind(AssertUnwindSafe(|| {
1100 activator.unknown_adapter(&parent, name)
1101 }))
1102 .unwrap_or_else(|_| {
1103 log::warn("adapter activator panicked in unknown_adapter");
1104 false
1105 })
1106 };
1107 st = self.state.lock().unwrap();
1108 st.activating.remove(name);
1109 self.changed.notify_all();
1110 if !created {
1111 return None;
1112 }
1113 return st.children.get(name).cloned();
1114 }
1115 }
1116
1117 pub(crate) fn has_object(&self, id: &[u8]) -> bool {
1121 let st = self.state.lock().unwrap();
1122 !st.destroyed
1123 && (st.active.contains_key(id)
1124 || self.policies.request_processing != RequestProcessing::ActiveObjectMapOnly)
1125 }
1126
1127 pub(crate) fn is_destroyed(&self) -> bool {
1128 self.state.lock().unwrap().destroyed
1129 }
1130
1131 pub(crate) fn resolve(
1134 self: &Arc<Self>,
1135 adapter: &Poa,
1136 server: &Arc<Server>,
1137 id: &[u8],
1138 operation: &str,
1139 ) -> Result<Resolved, ServantManagerError> {
1140 let retain = self.policies.servant_retention == ServantRetention::Retain;
1141 let mut st = self.state.lock().unwrap();
1142 loop {
1143 if st.destroyed {
1144 return Err(no_such_object().into());
1145 }
1146 if retain {
1147 if let Some(servant) = st.active.get(id).cloned() {
1148 return Ok(self.resolved(&mut st, server, id, servant));
1149 }
1150 }
1151 match self.policies.request_processing {
1152 RequestProcessing::ActiveObjectMapOnly => return Err(no_such_object().into()),
1153 RequestProcessing::UseDefaultServant => {
1154 let servant = st.default_servant.clone().ok_or_else(|| {
1155 sys(SystemExceptionKind::OBJ_ADAPTER, minor::NO_DEFAULT_SERVANT)
1156 })?;
1157 return Ok(Resolved {
1158 servant,
1159 _object: None,
1160 locator: None,
1161 });
1162 }
1163 RequestProcessing::UseServantManager => {}
1164 }
1165 match st.servant_manager.clone() {
1166 None => {
1167 return Err(
1168 sys(SystemExceptionKind::OBJ_ADAPTER, minor::NO_SERVANT_MANAGER).into(),
1169 );
1170 }
1171 Some(ServantManager::Locator(locator)) => {
1172 drop(st);
1173 let (servant, cookie) =
1174 catch("preinvoke", || locator.preinvoke(id, adapter, operation))?;
1175 return Ok(Resolved {
1176 servant,
1177 _object: None,
1178 locator: Some((locator, cookie)),
1179 });
1180 }
1181 Some(ServantManager::Activator(activator)) => {
1182 if st.incarnating.contains(id) {
1183 st = self.changed.wait(st).unwrap();
1184 continue;
1185 }
1186 st.incarnating.insert(id.to_vec());
1187 drop(st);
1188 let result = catch("incarnate", || activator.incarnate(id, adapter));
1189 st = self.state.lock().unwrap();
1190 st.incarnating.remove(id);
1191 self.changed.notify_all();
1192 let servant = result?;
1193 if st.destroyed {
1194 return Err(no_such_object().into());
1195 }
1196 match self.activate(&mut st, id.to_vec(), Arc::clone(&servant)) {
1197 Ok(()) => return Ok(self.resolved(&mut st, server, id, servant)),
1198 Err(PoaError::ObjectAlreadyActive) => continue,
1200 Err(_) => {
1201 return Err(sys(
1202 SystemExceptionKind::OBJ_ADAPTER,
1203 minor::SERVANT_ALREADY_ACTIVE,
1204 )
1205 .into());
1206 }
1207 }
1208 }
1209 }
1210 }
1211 }
1212
1213 fn resolved(
1214 self: &Arc<Self>,
1215 st: &mut PoaState,
1216 server: &Arc<Server>,
1217 id: &[u8],
1218 servant: Arc<dyn Servant>,
1219 ) -> Resolved {
1220 *st.running.entry(id.to_vec()).or_insert(0) += 1;
1221 Resolved {
1222 servant,
1223 _object: Some(ObjectGuard {
1224 poa: Arc::clone(self),
1225 server: Arc::downgrade(server),
1226 id: id.to_vec(),
1227 }),
1228 locator: None,
1229 }
1230 }
1231
1232 pub(crate) fn destroy_tree(self: &Arc<Self>, etherealize: bool) -> Vec<Etherealization> {
1236 let (children, drained, rest) = {
1237 let mut st = self.state.lock().unwrap();
1238 if st.destroyed {
1239 return Vec::new();
1240 }
1241 st.destroyed = true;
1242 let children = std::mem::take(&mut st.children);
1243 let drained = drain(&mut st);
1244 let rest = (
1246 st.default_servant.take(),
1247 st.servant_manager.take(),
1248 st.activator.take(),
1249 );
1250 (children, drained, rest)
1251 };
1252 drop(rest);
1253 let mut all = Vec::new();
1254 for child in children.into_values() {
1255 all.extend(child.destroy_tree(etherealize));
1256 }
1257 all.extend(self.etherealizations(drained, etherealize));
1258 all
1259 }
1260
1261 fn take_for_etherealize(self: &Arc<Self>) -> Vec<Etherealization> {
1263 let drained = {
1264 let mut st = self.state.lock().unwrap();
1265 if st.destroyed {
1266 return Vec::new();
1267 }
1268 drain(&mut st)
1269 };
1270 self.etherealizations(drained, true)
1271 }
1272
1273 fn etherealizations(
1274 self: &Arc<Self>,
1275 (entries, activator): Drained,
1276 etherealize: bool,
1277 ) -> Vec<Etherealization> {
1278 let Some(activator) = activator.filter(|_| etherealize) else {
1279 return Vec::new();
1280 };
1281 entries
1282 .into_iter()
1283 .map(|(id, servant)| Etherealization {
1284 poa: Arc::clone(self),
1285 activator: Arc::clone(&activator),
1286 id,
1287 servant,
1288 cleanup_in_progress: true,
1289 })
1290 .collect()
1291 }
1292
1293 fn generate_id(&self, st: &mut PoaState) -> ObjectId {
1294 let serial = st.next_id;
1295 st.next_id = st.next_id.wrapping_add(1);
1296 let mut id = self.boot_id.to_vec();
1297 id.extend_from_slice(&serial.to_be_bytes());
1298 id
1299 }
1300
1301 fn activate(
1302 &self,
1303 st: &mut PoaState,
1304 id: ObjectId,
1305 servant: Arc<dyn Servant>,
1306 ) -> Result<(), PoaError> {
1307 if st.active.contains_key(&id) {
1308 return Err(PoaError::ObjectAlreadyActive);
1309 }
1310 if self.policies.id_uniqueness == IdUniqueness::Unique {
1311 let addr = servant_addr(&servant);
1312 if st.ids.contains_key(&addr) {
1313 return Err(PoaError::ServantAlreadyActive);
1314 }
1315 st.ids.insert(addr, id.clone());
1316 }
1317 st.active.insert(id, servant);
1318 Ok(())
1319 }
1320
1321 pub(crate) fn run_serially(self: &Arc<Self>, server: &Arc<Server>, job: Job) {
1325 let mut serial = self.serial.lock().unwrap();
1326 serial.queue.push_back(job);
1327 if !serial.busy {
1328 serial.busy = true;
1329 drop(serial);
1330 self.submit_serial(server);
1331 }
1332 }
1333
1334 fn submit_serial(self: &Arc<Self>, server: &Arc<Server>) {
1335 let poa = Arc::clone(self);
1336 let srv = Arc::clone(server);
1337 server.submit(Box::new(move || poa.run_one_serially(&srv)));
1338 }
1339
1340 fn run_one_serially(self: &Arc<Self>, server: &Arc<Server>) {
1342 let job = {
1343 let mut serial = self.serial.lock().unwrap();
1344 let Some(job) = serial.queue.pop_front() else {
1345 serial.busy = false;
1346 return;
1347 };
1348 serial.owner = Some(thread::current().id());
1349 job
1350 };
1351 let _ = panic::catch_unwind(AssertUnwindSafe(job));
1352 self.release_serial(server);
1353 }
1354
1355 fn release_serial(self: &Arc<Self>, server: &Arc<Server>) {
1356 let mut serial = self.serial.lock().unwrap();
1357 serial.owner = None;
1358 if serial.queue.is_empty() {
1359 serial.busy = false;
1360 } else {
1361 drop(serial);
1362 self.submit_serial(server);
1363 }
1364 }
1365
1366 pub(crate) fn enter_serially(self: &Arc<Self>, server: &Arc<Server>) -> SerialEntry {
1369 let me = thread::current().id();
1370 let mut serial = self.serial.lock().unwrap();
1371 if serial.owner == Some(me) {
1372 SerialEntry::Reentrant
1373 } else if serial.busy {
1374 SerialEntry::Busy
1375 } else {
1376 serial.busy = true;
1377 serial.owner = Some(me);
1378 SerialEntry::Acquired(SerialGuard {
1379 poa: Arc::clone(self),
1380 server: Arc::clone(server),
1381 })
1382 }
1383 }
1384}
1385
1386#[derive(Debug, PartialEq, Eq)]
1388pub(crate) enum ParsedKey<'a> {
1389 Poa {
1392 path: Vec<&'a str>,
1393 boot_id: Option<&'a [u8]>,
1394 id: &'a [u8],
1395 },
1396 Simple(&'a [u8]),
1398 Invalid,
1400}
1401
1402pub(crate) fn parse_key(key: &[u8]) -> ParsedKey<'_> {
1403 fn transient<'a>(rest: &'a [u8], path: Vec<&'a str>) -> ParsedKey<'a> {
1404 if rest.len() < BOOT_ID_LEN {
1405 return ParsedKey::Invalid;
1406 }
1407 let (boot_id, id) = rest.split_at(BOOT_ID_LEN);
1408 ParsedKey::Poa {
1409 path,
1410 boot_id: Some(boot_id),
1411 id,
1412 }
1413 }
1414 match key.first() {
1415 Some(&TRANSIENT_END) => transient(&key[1..], Vec::new()),
1416 Some(&PATH_START) => {
1417 let rest = &key[1..];
1418 let Some(end) = rest
1419 .iter()
1420 .position(|&b| b == PERSISTENT_END || b == TRANSIENT_END)
1421 else {
1422 return ParsedKey::Invalid;
1423 };
1424 let mut path = Vec::new();
1425 for name in rest[..end].split(|&b| b == PATH_SEPARATOR) {
1426 match std::str::from_utf8(name) {
1427 Ok(name) if !name.is_empty() => path.push(name),
1428 _ => return ParsedKey::Invalid,
1429 }
1430 }
1431 if rest[end] == PERSISTENT_END {
1432 ParsedKey::Poa {
1433 path,
1434 boot_id: None,
1435 id: &rest[end + 1..],
1436 }
1437 } else {
1438 transient(&rest[end + 1..], path)
1439 }
1440 }
1441 _ => ParsedKey::Simple(key),
1442 }
1443}
1444
1445impl Poa {
1446 fn state(&self) -> Result<MutexGuard<'_, PoaState>, PoaError> {
1447 let st = self.inner.state.lock().unwrap();
1448 if st.destroyed {
1449 return Err(sys(SystemExceptionKind::OBJECT_NOT_EXIST, 0).into());
1450 }
1451 Ok(st)
1452 }
1453
1454 fn server(&self) -> Result<Arc<Server>, PoaError> {
1455 self.orb
1456 .server()
1457 .ok_or_else(|| sys(SystemExceptionKind::OBJECT_NOT_EXIST, 0).into())
1458 }
1459
1460 fn handle(&self, inner: Arc<PoaInner>) -> Poa {
1461 Poa {
1462 orb: self.orb.clone(),
1463 inner,
1464 }
1465 }
1466
1467 pub fn the_name(&self) -> &str {
1469 &self.inner.name
1470 }
1471
1472 pub fn the_parent(&self) -> Option<Poa> {
1474 let parent = self.inner.parent.as_ref()?.upgrade()?;
1475 Some(self.handle(parent))
1476 }
1477
1478 pub fn the_children(&self) -> Vec<Poa> {
1480 let st = self.inner.state.lock().unwrap();
1481 st.children
1482 .values()
1483 .map(|c| self.handle(Arc::clone(c)))
1484 .collect()
1485 }
1486
1487 pub fn the_poa_manager(&self) -> PoaManager {
1489 self.inner.manager.clone()
1490 }
1491
1492 pub fn policies(&self) -> Policies {
1494 self.inner.policies
1495 }
1496
1497 pub fn create_poa(
1502 &self,
1503 name: &str,
1504 manager: Option<&PoaManager>,
1505 policies: &[Policy],
1506 ) -> Result<Poa, PoaError> {
1507 if name.is_empty() || name.contains('\0') {
1508 return Err(sys(SystemExceptionKind::BAD_PARAM, 0).into());
1509 }
1510 let policies = Policies::from_list(policies).map_err(PoaError::InvalidPolicy)?;
1511 let server = self.server()?;
1512 let mut st = self.state()?;
1513 if st.children.contains_key(name) {
1514 return Err(PoaError::AdapterAlreadyExists);
1515 }
1516 let manager = match manager {
1517 Some(m) => m.clone(),
1518 None => PoaManager::new(&server),
1519 };
1520 if policies.lifespan == Lifespan::Persistent && !server.has_fixed_port() {
1521 log::warn(&format!(
1522 "PERSISTENT POA {name:?} on an endpoint without a fixed port: \
1523 its references will not survive a restart"
1524 ));
1525 }
1526 let child = PoaInner::new_child(&self.inner, name, manager, policies);
1527 st.children.insert(name.to_owned(), Arc::clone(&child));
1528 Ok(self.handle(child))
1529 }
1530
1531 pub fn find_poa(&self, name: &str, activate_it: bool) -> Result<Poa, PoaError> {
1534 drop(self.state()?);
1535 let child = if activate_it {
1536 self.inner.find_or_activate_child(&self.orb, name)
1537 } else {
1538 self.inner.child(name).ok()
1539 };
1540 child
1541 .map(|c| self.handle(c))
1542 .ok_or(PoaError::AdapterNonExistent)
1543 }
1544
1545 pub fn the_activator(&self) -> Option<Arc<dyn AdapterActivator>> {
1547 self.inner.state.lock().unwrap().activator.clone()
1548 }
1549
1550 pub fn set_the_activator(
1553 &self,
1554 activator: Option<Arc<dyn AdapterActivator>>,
1555 ) -> Result<(), PoaError> {
1556 let old = std::mem::replace(&mut self.state()?.activator, activator);
1557 drop(old);
1558 Ok(())
1559 }
1560
1561 pub fn get_servant_manager(&self) -> Result<Option<ServantManager>, PoaError> {
1563 if self.inner.policies.request_processing != RequestProcessing::UseServantManager {
1564 return Err(PoaError::WrongPolicy);
1565 }
1566 Ok(self.state()?.servant_manager.clone())
1567 }
1568
1569 pub fn set_servant_manager(&self, manager: ServantManager) -> Result<(), PoaError> {
1574 let p = self.inner.policies;
1575 if p.request_processing != RequestProcessing::UseServantManager {
1576 return Err(PoaError::WrongPolicy);
1577 }
1578 let fits = matches!(
1579 (&manager, p.servant_retention),
1580 (ServantManager::Activator(_), ServantRetention::Retain)
1581 | (ServantManager::Locator(_), ServantRetention::NonRetain)
1582 );
1583 if !fits {
1584 return Err(sys(SystemExceptionKind::OBJ_ADAPTER, minor::NO_SERVANT_MANAGER).into());
1585 }
1586 let mut st = self.state()?;
1587 if st.servant_manager.is_some() {
1588 return Err(sys(
1589 SystemExceptionKind::BAD_INV_ORDER,
1590 minor::SERVANT_MANAGER_ALREADY_SET,
1591 )
1592 .into());
1593 }
1594 st.servant_manager = Some(manager);
1595 Ok(())
1596 }
1597
1598 pub fn get_servant(&self) -> Result<Arc<dyn Servant>, PoaError> {
1600 if self.inner.policies.request_processing != RequestProcessing::UseDefaultServant {
1601 return Err(PoaError::WrongPolicy);
1602 }
1603 self.state()?
1604 .default_servant
1605 .clone()
1606 .ok_or(PoaError::NoServant)
1607 }
1608
1609 pub fn set_servant(&self, servant: Arc<dyn Servant>) -> Result<(), PoaError> {
1612 if self.inner.policies.request_processing != RequestProcessing::UseDefaultServant {
1613 return Err(PoaError::WrongPolicy);
1614 }
1615 let old = self.state()?.default_servant.replace(servant);
1616 drop(old);
1617 Ok(())
1618 }
1619
1620 pub fn destroy(&self, etherealize: bool, wait_for_completion: bool) -> Result<(), PoaError> {
1628 check_wait(wait_for_completion)?;
1629 if let Some(parent) = self.inner.parent.as_ref().and_then(Weak::upgrade) {
1630 let mut st = parent.state.lock().unwrap();
1631 if st
1632 .children
1633 .get(&self.inner.name)
1634 .is_some_and(|c| Arc::ptr_eq(c, &self.inner))
1635 {
1636 st.children.remove(&self.inner.name);
1637 }
1638 }
1639 let work = self.inner.destroy_tree(etherealize);
1640 if wait_for_completion {
1641 self.inner.activity.wait_idle();
1642 }
1643 if let Some(server) = self.orb.server() {
1644 server.etherealize(work, wait_for_completion);
1645 }
1646 Ok(())
1647 }
1648
1649 fn check_retain(&self) -> Result<(), PoaError> {
1650 if self.inner.policies.servant_retention != ServantRetention::Retain {
1651 return Err(PoaError::WrongPolicy);
1652 }
1653 Ok(())
1654 }
1655
1656 pub fn activate_object(&self, servant: Arc<dyn Servant>) -> Result<ObjectId, PoaError> {
1659 self.check_retain()?;
1660 if self.inner.policies.id_assignment != IdAssignment::System {
1661 return Err(PoaError::WrongPolicy);
1662 }
1663 let mut st = self.state()?;
1664 let id = self.inner.generate_id(&mut st);
1665 self.inner.activate(&mut st, id.clone(), servant)?;
1666 Ok(id)
1667 }
1668
1669 pub fn activate_object_with_id(
1671 &self,
1672 id: &[u8],
1673 servant: Arc<dyn Servant>,
1674 ) -> Result<(), PoaError> {
1675 self.check_retain()?;
1676 let mut st = self.state()?;
1677 self.inner.activate(&mut st, id.to_vec(), servant)
1678 }
1679
1680 pub fn deactivate_object(&self, id: &[u8]) -> Result<(), PoaError> {
1686 self.check_retain()?;
1687 let (servant, now) = {
1688 let mut st = self.state()?;
1689 let servant = st.active.remove(id).ok_or(PoaError::ObjectNotActive)?;
1690 let addr = servant_addr(&servant);
1691 if st.ids.get(&addr).is_some_and(|i| i == id) {
1692 st.ids.remove(&addr);
1693 }
1694 match st.servant_manager.clone() {
1695 Some(ServantManager::Activator(activator)) => {
1696 if st.running.contains_key(id) {
1697 st.deactivated.insert(id.to_vec(), servant);
1698 (None, None)
1699 } else {
1700 (None, Some((activator, servant)))
1701 }
1702 }
1703 _ => (Some(servant), None),
1704 }
1705 };
1706 drop(servant);
1707 if let Some((activator, servant)) = now {
1708 let work = Etherealization {
1709 poa: Arc::clone(&self.inner),
1710 activator,
1711 id: id.to_vec(),
1712 servant,
1713 cleanup_in_progress: false,
1714 };
1715 if let Some(server) = self.orb.server() {
1716 server.etherealize_later(work);
1717 }
1718 }
1719 Ok(())
1720 }
1721
1722 pub fn servant_to_id(&self, servant: &Arc<dyn Servant>) -> Result<ObjectId, PoaError> {
1726 let p = self.inner.policies;
1727 let retain = p.servant_retention == ServantRetention::Retain;
1728 let default_servant = p.request_processing == RequestProcessing::UseDefaultServant;
1729 if !default_servant
1730 && !(retain
1731 && (p.id_uniqueness == IdUniqueness::Unique
1732 || p.implicit_activation == ImplicitActivation::Implicit))
1733 {
1734 return Err(PoaError::WrongPolicy);
1735 }
1736 let mut st = self.state()?;
1737 if retain && p.id_uniqueness == IdUniqueness::Unique {
1738 if let Some(id) = st.ids.get(&servant_addr(servant)) {
1739 return Ok(id.clone());
1740 }
1741 }
1742 if retain && p.implicit_activation == ImplicitActivation::Implicit {
1743 let id = self.inner.generate_id(&mut st);
1744 self.inner
1745 .activate(&mut st, id.clone(), Arc::clone(servant))?;
1746 return Ok(id);
1747 }
1748 let is_default = st
1749 .default_servant
1750 .as_ref()
1751 .is_some_and(|d| same_servant(d, servant));
1752 drop(st);
1753 if is_default {
1754 let current = CURRENT.with(|c| {
1755 c.borrow()
1756 .last()
1757 .filter(|e| e.poa == *self && same_servant(&e.servant, servant))
1758 .map(|e| e.id.clone())
1759 });
1760 if let Some(id) = current {
1761 return Ok(id);
1762 }
1763 }
1764 Err(PoaError::ServantNotActive)
1765 }
1766
1767 pub fn servant_to_reference(&self, servant: &Arc<dyn Servant>) -> Result<ObjectRef, PoaError> {
1770 let id = self.servant_to_id(servant)?;
1771 self.reference(&id, servant.repository_id())
1772 }
1773
1774 pub fn id_to_servant(&self, id: &[u8]) -> Result<Arc<dyn Servant>, PoaError> {
1777 let p = self.inner.policies;
1778 let retain = p.servant_retention == ServantRetention::Retain;
1779 let default_servant = p.request_processing == RequestProcessing::UseDefaultServant;
1780 if !retain && !default_servant {
1781 return Err(PoaError::WrongPolicy);
1782 }
1783 let st = self.state()?;
1784 let active = retain.then(|| st.active.get(id).cloned()).flatten();
1785 active
1786 .or_else(|| st.default_servant.clone().filter(|_| default_servant))
1787 .ok_or(PoaError::ObjectNotActive)
1788 }
1789
1790 pub fn id_to_reference(&self, id: &[u8]) -> Result<ObjectRef, PoaError> {
1793 self.check_retain()?;
1794 let servant = self
1795 .state()?
1796 .active
1797 .get(id)
1798 .cloned()
1799 .ok_or(PoaError::ObjectNotActive)?;
1800 self.reference(id, servant.repository_id())
1801 }
1802
1803 pub fn create_reference(&self, intf: &str) -> Result<ObjectRef, PoaError> {
1806 if self.inner.policies.id_assignment != IdAssignment::System {
1807 return Err(PoaError::WrongPolicy);
1808 }
1809 let id = {
1810 let mut st = self.state()?;
1811 self.inner.generate_id(&mut st)
1812 };
1813 self.reference(&id, intf)
1814 }
1815
1816 pub fn create_reference_with_id(&self, id: &[u8], intf: &str) -> Result<ObjectRef, PoaError> {
1819 drop(self.state()?);
1820 self.reference(id, intf)
1821 }
1822
1823 pub fn reference_to_id(&self, reference: &ObjectRef) -> Result<ObjectId, PoaError> {
1826 drop(self.state()?);
1827 let prefix = &self.inner.key_prefix;
1828 reference
1829 .ior()
1830 .iiop_profiles()
1831 .filter_map(Result::ok)
1832 .map(|p: IiopProfile| p.object_key)
1833 .find(|key| key.starts_with(prefix))
1834 .map(|key| key[prefix.len()..].to_vec())
1835 .ok_or(PoaError::WrongAdapter)
1836 }
1837
1838 pub fn reference_to_servant(
1840 &self,
1841 reference: &ObjectRef,
1842 ) -> Result<Arc<dyn Servant>, PoaError> {
1843 let id = self.reference_to_id(reference)?;
1844 self.id_to_servant(&id)
1845 }
1846
1847 pub(crate) fn reference(&self, id: &[u8], type_id: &str) -> Result<ObjectRef, PoaError> {
1848 let server = self.server()?;
1849 let ior = server.ior(type_id, self.inner.key(id))?;
1850 Ok(ObjectRef::new(self.orb.clone(), ior))
1851 }
1852}
1853
1854pub(crate) mod log {
1855 pub(crate) fn warn(msg: &str) {
1857 eprintln!("rustorb: warning: {msg}");
1858 }
1859}
1860
1861#[cfg(test)]
1862mod tests {
1863 use super::*;
1864
1865 #[test]
1866 fn keys_parse_back() {
1867 let boot = [1, 2, 3, 4, 5, 6, 7, 8];
1868 assert_eq!(
1869 parse_key(b"\xffpersistent_user\x00obj"),
1870 ParsedKey::Poa {
1871 path: vec!["persistent_user"],
1872 boot_id: None,
1873 id: b"obj"
1874 }
1875 );
1876 assert_eq!(
1877 parse_key(b"\xffa\xffnested\x00"),
1878 ParsedKey::Poa {
1879 path: vec!["a", "nested"],
1880 boot_id: None,
1881 id: b""
1882 }
1883 );
1884 let mut transient = b"\xffchild\xfe".to_vec();
1885 transient.extend_from_slice(&boot);
1886 transient.extend_from_slice(b"id");
1887 assert_eq!(
1888 parse_key(&transient),
1889 ParsedKey::Poa {
1890 path: vec!["child"],
1891 boot_id: Some(&boot),
1892 id: b"id"
1893 }
1894 );
1895 let mut root = vec![0xfe];
1896 root.extend_from_slice(&boot);
1897 assert_eq!(
1898 parse_key(&root),
1899 ParsedKey::Poa {
1900 path: vec![],
1901 boot_id: Some(&boot),
1902 id: b""
1903 }
1904 );
1905 assert_eq!(parse_key(b"NameService"), ParsedKey::Simple(b"NameService"));
1906 assert_eq!(parse_key(b""), ParsedKey::Simple(b""));
1907 assert_eq!(parse_key(b"\xffno-end"), ParsedKey::Invalid);
1908 assert_eq!(parse_key(b"\xfe\x01\x02"), ParsedKey::Invalid);
1909 assert_eq!(parse_key(b"\xff\xff\x00x"), ParsedKey::Invalid);
1910 }
1911
1912 #[test]
1913 fn policy_lists() {
1914 assert_eq!(Policies::from_list(&[]), Ok(Policies::default()));
1915 let p = Policies::from_list(&[
1916 Policy::Lifespan(Lifespan::Persistent),
1917 Policy::IdAssignment(IdAssignment::User),
1918 ])
1919 .unwrap();
1920 assert_eq!(p.lifespan, Lifespan::Persistent);
1921 assert_eq!(p.id_assignment, IdAssignment::User);
1922 assert_eq!(
1923 Policies::from_list(&[
1924 Policy::Lifespan(Lifespan::Persistent),
1925 Policy::Lifespan(Lifespan::Transient),
1926 ]),
1927 Err(1)
1928 );
1929 assert_eq!(
1930 Policies::from_list(&[
1931 Policy::IdAssignment(IdAssignment::User),
1932 Policy::ImplicitActivation(ImplicitActivation::Implicit),
1933 ]),
1934 Err(1)
1935 );
1936 assert_eq!(
1937 Policies::from_list(&[Policy::Thread(ThreadPolicy::MainThread)])
1938 .unwrap()
1939 .thread,
1940 ThreadPolicy::MainThread
1941 );
1942 assert_eq!(
1944 Policies::from_list(&[Policy::ServantRetention(ServantRetention::NonRetain)]),
1945 Err(0)
1946 );
1947 assert!(
1948 Policies::from_list(&[
1949 Policy::ServantRetention(ServantRetention::NonRetain),
1950 Policy::RequestProcessing(RequestProcessing::UseServantManager),
1951 ])
1952 .is_ok()
1953 );
1954 assert_eq!(
1956 Policies::from_list(&[Policy::RequestProcessing(
1957 RequestProcessing::UseDefaultServant
1958 )]),
1959 Err(0)
1960 );
1961 assert!(
1962 Policies::from_list(&[
1963 Policy::RequestProcessing(RequestProcessing::UseDefaultServant),
1964 Policy::IdUniqueness(IdUniqueness::Multiple),
1965 ])
1966 .is_ok()
1967 );
1968 assert_eq!(
1969 Policies::from_list(&[
1970 Policy::ImplicitActivation(ImplicitActivation::Implicit),
1971 Policy::ServantRetention(ServantRetention::NonRetain),
1972 Policy::RequestProcessing(RequestProcessing::UseServantManager),
1973 ]),
1974 Err(0)
1975 );
1976 }
1977}