1use std::collections::VecDeque;
5use std::collections::hash_map::RandomState;
6use std::fmt;
7use std::hash::{BuildHasher, Hasher};
8use std::io;
9use std::sync::atomic::{AtomicU64, Ordering};
10use std::sync::{Arc, Mutex, MutexGuard};
11
12use rustorb_core::name::{self, Name, NameComponent};
13use rustorb_core::{
14 CompletionStatus, Cookie, IdAssignment, Lifespan, ObjectRef, Orb, Poa, PoaCurrent, PoaError,
15 Policy, RequestProcessing, Servant, ServantLocator, ServantManager, ServantManagerError,
16 ServantRetention, SystemException, SystemExceptionKind, minor,
17};
18
19use crate::client::{Binding, BindingType, NamingContext, from_idl_name, to_idl_name};
20use crate::idl::cos_naming::{self as idl, naming_context as nc, naming_context_ext as nce};
21use crate::repository_id::NAMING_CONTEXT_EXT;
22use crate::store::{Change, Snapshot, Store, StoredBinding};
23use crate::{NamingError, NotFoundReason};
24
25pub const ROOT_KEY: &str = "NameService";
28
29const CONTEXT_POA: &str = "rustorb-naming";
32const ITERATOR_POA: &str = "rustorb-naming-iterators";
34const MAX_ITERATORS: usize = 1000;
36
37#[derive(Debug)]
39pub enum StartError {
40 Store(io::Error),
42 Poa(PoaError),
44}
45
46impl fmt::Display for StartError {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 match self {
49 StartError::Store(e) => write!(f, "cannot load the naming data: {e}"),
50 StartError::Poa(e) => write!(f, "cannot create the POAs: {e}"),
51 }
52 }
53}
54
55impl std::error::Error for StartError {}
56
57impl From<PoaError> for StartError {
58 fn from(e: PoaError) -> Self {
59 StartError::Poa(e)
60 }
61}
62
63impl From<SystemException> for StartError {
64 fn from(e: SystemException) -> Self {
65 StartError::Poa(PoaError::System(e))
66 }
67}
68
69#[derive(Debug, Clone)]
91pub struct NamingService {
92 service: Arc<Service>,
93}
94
95impl NamingService {
96 pub fn start(orb: &Orb, mut store: impl Store + 'static) -> Result<NamingService, StartError> {
102 let mut snapshot = store.load().map_err(StartError::Store)?;
103 let root = orb.root_poa()?;
104 let manager = root.the_poa_manager();
105 let contexts = root.create_poa(
106 CONTEXT_POA,
107 Some(&manager),
108 &[
109 Policy::Lifespan(Lifespan::Persistent),
110 Policy::IdAssignment(IdAssignment::User),
111 Policy::ServantRetention(ServantRetention::NonRetain),
112 Policy::RequestProcessing(RequestProcessing::UseServantManager),
113 ],
114 )?;
115 let iterators = root.create_poa(ITERATOR_POA, Some(&manager), &[])?;
116 let root_ref =
117 contexts.create_reference_with_id(ROOT_KEY.as_bytes(), NAMING_CONTEXT_EXT)?;
118 let key_prefix = profile_key(&root_ref)
119 .and_then(|key| key.strip_suffix(ROOT_KEY.as_bytes()).map(<[u8]>::to_vec))
120 .expect("a POA reference has an IIOP profile with the ObjectId at the end");
121 let root_ref = orb.register_object_key(ROOT_KEY, &root_ref)?;
122 if !snapshot.contexts.contains_key(ROOT_KEY) {
123 let change = Change::CreateContext(ROOT_KEY.to_owned());
124 store.record(&change).map_err(StartError::Store)?;
125 snapshot.apply(&change);
126 }
127 let service = Arc::new(Service {
128 orb: orb.clone(),
129 contexts: contexts.clone(),
130 iterators,
131 key_prefix,
132 root: root_ref,
133 state: Mutex::new(State {
134 snapshot,
135 store: Box::new(store),
136 iterators: VecDeque::new(),
137 }),
138 next_id: AtomicU64::new(0),
139 });
140 contexts.set_servant_manager(ServantManager::Locator(Arc::new(Locator {
141 service: Arc::downgrade(&service),
142 })))?;
143 manager.activate()?;
144 Ok(NamingService { service })
145 }
146
147 pub fn root_context(&self) -> crate::NamingContextExt {
149 crate::NamingContextExt::unchecked_narrow(self.service.root.clone())
150 }
151
152 pub fn snapshot(&self) -> Snapshot {
154 self.service.lock().snapshot.clone()
155 }
156}
157
158fn profile_key(obj: &ObjectRef) -> Option<Vec<u8>> {
160 obj.ior()
161 .iiop_profiles()
162 .find_map(Result::ok)
163 .map(|p| p.object_key)
164}
165
166struct Service {
167 orb: Orb,
168 contexts: Poa,
169 iterators: Poa,
170 key_prefix: Vec<u8>,
172 root: ObjectRef,
174 state: Mutex<State>,
175 next_id: AtomicU64,
176}
177
178impl fmt::Debug for Service {
179 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180 f.debug_struct("NamingService").finish_non_exhaustive()
181 }
182}
183
184struct State {
185 snapshot: Snapshot,
186 store: Box<dyn Store>,
187 iterators: VecDeque<Vec<u8>>,
189}
190
191impl State {
192 fn update(&mut self, changes: &[Change]) -> Result<(), SystemException> {
194 for change in changes {
195 self.store.record(change).map_err(|e| {
196 eprintln!("rustorb-naming: cannot record an update: {e}");
197 SystemException::new(SystemExceptionKind::PERSIST_STORE, 0, CompletionStatus::No)
198 })?;
199 self.snapshot.apply(change);
200 }
201 if let Err(e) = self.store.checkpoint(&self.snapshot) {
202 eprintln!("rustorb-naming: cannot write a checkpoint: {e}");
204 }
205 Ok(())
206 }
207}
208
209fn no_such_object() -> SystemException {
212 SystemException::new(
213 SystemExceptionKind::OBJECT_NOT_EXIST,
214 minor::NO_SUCH_OBJECT,
215 CompletionStatus::No,
216 )
217}
218
219fn invalid_ior() -> SystemException {
220 SystemException::new(SystemExceptionKind::INTERNAL, 0, CompletionStatus::No)
221}
222
223enum Target {
225 Local(String),
227 Remote(NamingContext, Name),
230}
231
232impl Service {
233 fn lock(&self) -> MutexGuard<'_, State> {
234 self.state.lock().unwrap_or_else(|e| e.into_inner())
235 }
236
237 fn context_ref(&self, id: &str) -> Result<ObjectRef, SystemException> {
239 if id == ROOT_KEY {
240 return Ok(self.root.clone());
241 }
242 self.contexts
243 .create_reference_with_id(id.as_bytes(), NAMING_CONTEXT_EXT)
244 .map_err(|e| match e {
245 PoaError::System(e) => e,
246 _ => invalid_ior(),
247 })
248 }
249
250 fn to_ior(&self, obj: Option<&ObjectRef>) -> Result<String, SystemException> {
251 self.orb.object_to_string(obj)
252 }
253
254 fn object_of(&self, ior: &str) -> Result<Option<ObjectRef>, SystemException> {
255 self.orb.string_to_object(ior)
256 }
257
258 fn local_id(&self, obj: &ObjectRef) -> Option<String> {
262 let endpoints = self.orb.endpoints();
263 obj.ior()
264 .iiop_profiles()
265 .filter_map(Result::ok)
266 .filter(|p| {
267 endpoints
268 .iter()
269 .any(|(host, port)| *port == p.port && host.eq_ignore_ascii_case(&p.host))
270 })
271 .find_map(|p| {
272 if p.object_key == ROOT_KEY.as_bytes() {
273 return Some(ROOT_KEY.to_owned());
274 }
275 let id = p.object_key.strip_prefix(&self.key_prefix[..])?;
276 String::from_utf8(id.to_vec()).ok()
277 })
278 }
279
280 fn new_id(&self, st: &State) -> String {
283 loop {
284 let mut h = RandomState::new().build_hasher();
285 h.write_u64(self.next_id.fetch_add(1, Ordering::Relaxed));
286 let id = format!("{:016x}", h.finish());
287 if !st.snapshot.contexts.contains_key(&id) {
288 return id;
289 }
290 }
291 }
292
293 fn target(&self, st: &State, id: &str, n: &[NameComponent]) -> Result<Target, NamingError> {
295 let Some((_, path)) = n.split_last() else {
296 return Err(NamingError::InvalidName);
297 };
298 let mut current = id.to_owned();
299 for (i, component) in path.iter().enumerate() {
300 let bindings = st
301 .snapshot
302 .contexts
303 .get(¤t)
304 .ok_or_else(no_such_object)?;
305 let binding = bindings
306 .get(component)
307 .ok_or_else(|| NamingError::NotFound {
308 why: NotFoundReason::MissingNode,
309 rest_of_name: n[i..].to_vec(),
310 })?;
311 if binding.binding_type == BindingType::Object {
312 return Err(NamingError::NotFound {
313 why: NotFoundReason::NotContext,
314 rest_of_name: n[i..].to_vec(),
315 });
316 }
317 let next = self.object_of(&binding.ior)?.ok_or_else(no_such_object)?;
318 match self.local_id(&next) {
319 Some(next_id) => current = next_id,
320 None => {
321 return Ok(Target::Remote(
322 NamingContext::unchecked_narrow(next),
323 n[i + 1..].to_vec(),
324 ));
325 }
326 }
327 }
328 if !st.snapshot.contexts.contains_key(¤t) {
329 return Err(no_such_object().into());
330 }
331 Ok(Target::Local(current))
332 }
333
334 fn bind(
335 &self,
336 id: &str,
337 n: &[NameComponent],
338 obj: Option<&ObjectRef>,
339 binding_type: BindingType,
340 rebind: bool,
341 ) -> Result<(), NamingError> {
342 let ior = self.to_ior(obj)?;
343 let mut st = self.lock();
344 let context = match self.target(&st, id, n)? {
345 Target::Local(context) => context,
346 Target::Remote(ctx, rest) => {
347 drop(st);
348 let (stub, rest) = (ctx.stub(), to_idl_name(&rest));
349 let nc = || obj.map(|o| idl::NamingContext::unchecked_narrow(o.clone()));
350 match (binding_type, rebind) {
351 (BindingType::Object, false) => stub.bind(&rest, obj)?,
352 (BindingType::Object, true) => stub.rebind(&rest, obj)?,
353 (BindingType::Context, false) => stub.bind_context(&rest, nc().as_ref())?,
354 (BindingType::Context, true) => stub.rebind_context(&rest, nc().as_ref())?,
355 }
356 return Ok(());
357 }
358 };
359 let component = n.last().expect("checked by target").clone();
360 if !rebind && st.snapshot.contexts[&context].contains_key(&component) {
363 return Err(NamingError::AlreadyBound);
364 }
365 st.update(&[Change::Bind {
366 context,
367 component,
368 binding: StoredBinding { binding_type, ior },
369 }])?;
370 Ok(())
371 }
372
373 fn resolve(&self, id: &str, n: &[NameComponent]) -> Result<Option<ObjectRef>, NamingError> {
374 let st = self.lock();
375 let context = match self.target(&st, id, n)? {
376 Target::Local(context) => context,
377 Target::Remote(ctx, rest) => {
378 drop(st);
379 return ctx.resolve(&rest);
380 }
381 };
382 let component = n.last().expect("checked by target");
383 let binding = st.snapshot.contexts[&context]
384 .get(component)
385 .ok_or_else(|| NamingError::NotFound {
386 why: NotFoundReason::MissingNode,
387 rest_of_name: vec![component.clone()],
388 })?;
389 Ok(self.object_of(&binding.ior)?)
390 }
391
392 fn unbind(&self, id: &str, n: &[NameComponent]) -> Result<(), NamingError> {
393 let mut st = self.lock();
394 let context = match self.target(&st, id, n)? {
395 Target::Local(context) => context,
396 Target::Remote(ctx, rest) => {
397 drop(st);
398 return ctx.unbind(&rest);
399 }
400 };
401 let component = n.last().expect("checked by target").clone();
402 if !st.snapshot.contexts[&context].contains_key(&component) {
403 return Err(NamingError::NotFound {
404 why: NotFoundReason::MissingNode,
405 rest_of_name: vec![component],
406 });
407 }
408 st.update(&[Change::Unbind { context, component }])?;
409 Ok(())
410 }
411
412 fn new_context(&self) -> Result<ObjectRef, NamingError> {
413 let mut st = self.lock();
414 let id = self.new_id(&st);
415 let reference = self.context_ref(&id)?;
416 st.update(&[Change::CreateContext(id)])?;
417 Ok(reference)
418 }
419
420 fn bind_new_context(&self, id: &str, n: &[NameComponent]) -> Result<ObjectRef, NamingError> {
421 let mut st = self.lock();
422 let context = match self.target(&st, id, n)? {
423 Target::Local(context) => context,
424 Target::Remote(ctx, rest) => {
425 drop(st);
426 return Ok(ctx.bind_new_context(&rest)?.into_object());
427 }
428 };
429 let component = n.last().expect("checked by target").clone();
430 if st.snapshot.contexts[&context].contains_key(&component) {
431 return Err(NamingError::AlreadyBound);
432 }
433 let new_id = self.new_id(&st);
434 let reference = self.context_ref(&new_id)?;
435 let ior = self.to_ior(Some(&reference))?;
436 st.update(&[
437 Change::CreateContext(new_id),
438 Change::Bind {
439 context,
440 component,
441 binding: StoredBinding {
442 binding_type: BindingType::Context,
443 ior,
444 },
445 },
446 ])?;
447 Ok(reference)
448 }
449
450 fn destroy(&self, id: &str) -> Result<(), NamingError> {
451 let mut st = self.lock();
452 let bindings = st.snapshot.contexts.get(id).ok_or_else(no_such_object)?;
453 if !bindings.is_empty() {
454 return Err(NamingError::NotEmpty);
455 }
456 st.update(&[Change::DestroyContext(id.to_owned())])?;
457 Ok(())
458 }
459
460 fn bindings(&self, id: &str) -> Result<Vec<Binding>, SystemException> {
462 let st = self.lock();
463 let bindings = st.snapshot.contexts.get(id).ok_or_else(no_such_object)?;
464 Ok(bindings
465 .iter()
466 .map(|(component, binding)| Binding {
467 binding_name: vec![component.clone()],
468 binding_type: binding.binding_type,
469 })
470 .collect())
471 }
472
473 fn new_iterator(self: &Arc<Self>, rest: Vec<Binding>) -> Result<ObjectRef, SystemException> {
476 let servant: Arc<dyn Servant> = Arc::new(idl::BindingIteratorPoa(IteratorServant {
477 rest: Mutex::new(rest.into()),
478 service: Arc::downgrade(self),
479 }));
480 let poa_error = |e: PoaError| match e {
481 PoaError::System(e) => e,
482 _ => invalid_ior(),
483 };
484 let oid = self
485 .iterators
486 .activate_object(Arc::clone(&servant))
487 .map_err(poa_error)?;
488 let reference = self.iterators.id_to_reference(&oid).map_err(poa_error)?;
489 let evicted = {
490 let mut st = self.lock();
491 st.iterators.push_back(oid);
492 (st.iterators.len() > MAX_ITERATORS)
493 .then(|| st.iterators.pop_front())
494 .flatten()
495 };
496 if let Some(old) = evicted {
497 let _ = self.iterators.deactivate_object(&old);
498 }
499 Ok(reference)
500 }
501}
502
503struct Locator {
506 service: std::sync::Weak<Service>,
507}
508
509impl ServantLocator for Locator {
510 fn preinvoke(
511 &self,
512 id: &[u8],
513 _adapter: &Poa,
514 _operation: &str,
515 ) -> Result<(Arc<dyn Servant>, Cookie), ServantManagerError> {
516 let service = self.service.upgrade().ok_or_else(no_such_object)?;
517 let id = std::str::from_utf8(id).map_err(|_| no_such_object())?;
518 if !service.lock().snapshot.contexts.contains_key(id) {
519 return Err(no_such_object().into());
520 }
521 let servant = idl::NamingContextExtPoa(ContextServant {
522 service,
523 id: id.to_owned(),
524 });
525 Ok((Arc::new(servant), Box::new(())))
526 }
527}
528
529struct ContextServant {
531 service: Arc<Service>,
532 id: String,
533}
534
535fn idl_context(obj: ObjectRef) -> Option<idl::NamingContext> {
537 Some(idl::NamingContext::unchecked_narrow(obj))
538}
539
540impl idl::NamingContextServant for ContextServant {
541 fn bind(&self, n: &[idl::NameComponent], obj: Option<&ObjectRef>) -> Result<(), nc::BindError> {
542 let n = from_idl_name(n.to_vec());
543 Ok(self
544 .service
545 .bind(&self.id, &n, obj, BindingType::Object, false)?)
546 }
547
548 fn rebind(
549 &self,
550 n: &[idl::NameComponent],
551 obj: Option<&ObjectRef>,
552 ) -> Result<(), nc::RebindError> {
553 let n = from_idl_name(n.to_vec());
554 Ok(self
555 .service
556 .bind(&self.id, &n, obj, BindingType::Object, true)?)
557 }
558
559 fn bind_context(
560 &self,
561 n: &[idl::NameComponent],
562 ctx: Option<&idl::NamingContext>,
563 ) -> Result<(), nc::BindContextError> {
564 let n = from_idl_name(n.to_vec());
565 let obj = ctx.map(idl::NamingContext::object);
566 Ok(self
567 .service
568 .bind(&self.id, &n, obj, BindingType::Context, false)?)
569 }
570
571 fn rebind_context(
572 &self,
573 n: &[idl::NameComponent],
574 ctx: Option<&idl::NamingContext>,
575 ) -> Result<(), nc::RebindContextError> {
576 let n = from_idl_name(n.to_vec());
577 let obj = ctx.map(idl::NamingContext::object);
578 Ok(self
579 .service
580 .bind(&self.id, &n, obj, BindingType::Context, true)?)
581 }
582
583 fn resolve(&self, n: &[idl::NameComponent]) -> Result<Option<ObjectRef>, nc::ResolveError> {
584 Ok(self.service.resolve(&self.id, &from_idl_name(n.to_vec()))?)
585 }
586
587 fn unbind(&self, n: &[idl::NameComponent]) -> Result<(), nc::UnbindError> {
588 Ok(self.service.unbind(&self.id, &from_idl_name(n.to_vec()))?)
589 }
590
591 fn new_context(&self) -> Result<Option<idl::NamingContext>, SystemException> {
592 match self.service.new_context() {
593 Ok(obj) => Ok(idl_context(obj)),
594 Err(NamingError::System(e)) => Err(e),
595 Err(_) => Err(unlisted()),
596 }
597 }
598
599 fn bind_new_context(
600 &self,
601 n: &[idl::NameComponent],
602 ) -> Result<Option<idl::NamingContext>, nc::BindNewContextError> {
603 let n = from_idl_name(n.to_vec());
604 Ok(idl_context(self.service.bind_new_context(&self.id, &n)?))
605 }
606
607 fn destroy(&self) -> Result<(), nc::DestroyError> {
608 Ok(self.service.destroy(&self.id)?)
609 }
610
611 fn list(
612 &self,
613 how_many: u32,
614 ) -> Result<(idl::BindingList, Option<idl::BindingIterator>), SystemException> {
615 let s = &self.service;
616 let mut bindings = s.bindings(&self.id)?;
617 let rest = bindings.split_off(bindings.len().min(how_many as usize));
618 let iterator = if rest.is_empty() {
619 None
620 } else {
621 Some(idl::BindingIterator::unchecked_narrow(
622 s.new_iterator(rest)?,
623 ))
624 };
625 Ok((bindings.iter().map(idl::Binding::from).collect(), iterator))
626 }
627}
628
629impl idl::NamingContextExtServant for ContextServant {
630 fn to_string(&self, n: &[idl::NameComponent]) -> Result<String, nce::ToStringError> {
631 Ok(name::to_string(&from_idl_name(n.to_vec())).map_err(NamingError::from)?)
632 }
633
634 fn to_name(&self, sn: &str) -> Result<idl::Name, nce::ToNameError> {
635 let n = name::to_name(sn).map_err(NamingError::from)?;
636 Ok(to_idl_name(&n))
637 }
638
639 fn to_url(&self, addr: &str, sn: &str) -> Result<String, nce::ToUrlError> {
640 Ok(crate::to_url(addr, sn)?)
641 }
642
643 fn resolve_str(&self, sn: &str) -> Result<Option<ObjectRef>, nce::ResolveStrError> {
644 let n = name::to_name(sn).map_err(NamingError::from)?;
645 Ok(self.service.resolve(&self.id, &n)?)
646 }
647}
648
649fn unlisted() -> SystemException {
651 SystemException::new(
652 SystemExceptionKind::UNKNOWN,
653 minor::UNLISTED_USER_EXCEPTION,
654 CompletionStatus::Maybe,
655 )
656}
657
658struct IteratorServant {
660 rest: Mutex<VecDeque<Binding>>,
661 service: std::sync::Weak<Service>,
662}
663
664impl idl::BindingIteratorServant for IteratorServant {
665 fn next_one(&self) -> Result<(bool, idl::Binding), SystemException> {
666 let next = self.rest.lock().unwrap().pop_front();
667 Ok(match next {
670 Some(b) => (true, idl::Binding::from(&b)),
671 None => (false, idl::Binding::default()),
672 })
673 }
674
675 fn next_n(&self, how_many: u32) -> Result<(bool, idl::BindingList), SystemException> {
676 let chunk: Vec<idl::Binding> = {
677 let mut rest = self.rest.lock().unwrap();
678 let n = (how_many as usize).min(rest.len());
679 rest.drain(..n).map(|b| idl::Binding::from(&b)).collect()
680 };
681 Ok((!chunk.is_empty(), chunk))
682 }
683
684 fn destroy(&self) -> Result<(), SystemException> {
685 let oid = PoaCurrent::get_object_id().map_err(|_| no_such_object())?;
686 if let Some(service) = self.service.upgrade() {
687 service.lock().iterators.retain(|o| *o != oid);
688 service
689 .iterators
690 .deactivate_object(&oid)
691 .map_err(|_| no_such_object())?;
692 }
693 Ok(())
694 }
695}