Skip to main content

rustorb_naming/
client.rs

1use std::fmt::Write as _;
2use std::ops::Deref;
3
4use rustorb_core::giop::{Corbaloc, ObjAddr};
5use rustorb_core::name::{self, Name, NameComponent};
6use rustorb_core::{ObjectRef, SystemException};
7
8use crate::NamingError;
9use crate::idl::cos_naming as idl;
10use crate::repository_id::{NAMING_CONTEXT, NAMING_CONTEXT_EXT};
11
12/// A name of the generated code.
13pub(crate) fn to_idl_name(n: &[NameComponent]) -> idl::Name {
14    n.iter()
15        .map(|c| idl::NameComponent {
16            id: c.id.clone(),
17            kind: c.kind.clone(),
18        })
19        .collect()
20}
21
22/// A name from the generated code.
23pub(crate) fn from_idl_name(n: idl::Name) -> Name {
24    n.into_iter()
25        .map(|c| NameComponent {
26            id: c.id,
27            kind: c.kind,
28        })
29        .collect()
30}
31
32/// `CosNaming::BindingType`: what a name is bound to.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34pub enum BindingType {
35    /// `nobject`: an object, bound with `bind` or `rebind`.
36    Object,
37    /// `ncontext`: a naming context, bound with `bind_context`,
38    /// `rebind_context` or `bind_new_context`.
39    Context,
40}
41
42impl BindingType {
43    /// The IDL name, `nobject` or `ncontext`.
44    pub fn name(self) -> &'static str {
45        match self {
46            BindingType::Object => "nobject",
47            BindingType::Context => "ncontext",
48        }
49    }
50}
51
52/// `CosNaming::Binding`: one entry of a context, from `list` or a
53/// [`BindingIterator`].
54#[derive(Debug, Clone, PartialEq, Eq, Hash)]
55pub struct Binding {
56    /// The name of the entry, one component long.
57    pub binding_name: Name,
58    /// What the name is bound to.
59    pub binding_type: BindingType,
60}
61
62impl From<idl::Binding> for Binding {
63    fn from(b: idl::Binding) -> Binding {
64        Binding {
65            binding_name: from_idl_name(b.binding_name),
66            binding_type: match b.binding_type {
67                idl::BindingType::Nobject => BindingType::Object,
68                idl::BindingType::Ncontext => BindingType::Context,
69            },
70        }
71    }
72}
73
74impl From<&Binding> for idl::Binding {
75    fn from(b: &Binding) -> idl::Binding {
76        idl::Binding {
77            binding_name: to_idl_name(&b.binding_name),
78            binding_type: match b.binding_type {
79                BindingType::Object => idl::BindingType::Nobject,
80                BindingType::Context => idl::BindingType::Ncontext,
81            },
82        }
83    }
84}
85
86fn bindings(list: idl::BindingList) -> Vec<Binding> {
87    list.into_iter().map(Binding::from).collect()
88}
89
90/// Whether `obj` supports `repository_id`: from the IOR's type id when it
91/// says so, otherwise by asking the object (`_is_a`).
92fn supports(obj: &ObjectRef, repository_id: &str, also: &[&str]) -> Result<bool, SystemException> {
93    if also.contains(&obj.type_id()) {
94        return Ok(true);
95    }
96    rustorb_core::idl::is_a(obj, repository_id)
97}
98
99/// A context the operation returns; nil is a broken reply.
100fn context(nc: Option<idl::NamingContext>) -> Result<NamingContext, NamingError> {
101    let nc = nc.ok_or_else(|| {
102        SystemException::new(
103            rustorb_core::SystemExceptionKind::MARSHAL,
104            0,
105            rustorb_core::CompletionStatus::Yes,
106        )
107    })?;
108    Ok(NamingContext::unchecked_narrow(nc.into_object()))
109}
110
111/// A stub for `CosNaming::NamingContext`, over the one `rustorb-idl -brust`
112/// generates ([`crate::idl::cos_naming::NamingContext`]) with the names of
113/// [`rustorb_core::name`] and the errors of [`NamingError`].
114///
115/// Names are given as slices of [`NameComponent`]; [`to_name`](crate::to_name)
116/// makes one from a string such as `"app/Echo"`.
117#[derive(Debug, Clone)]
118pub struct NamingContext {
119    stub: idl::NamingContext,
120}
121
122impl NamingContext {
123    /// Narrows `obj` to a naming context: `None` if it is not one. Asks
124    /// the object (`_is_a`) unless the IOR's type id is the repository id
125    /// of `NamingContext` or `NamingContextExt`.
126    pub fn narrow(obj: ObjectRef) -> Result<Option<NamingContext>, SystemException> {
127        Ok(supports(&obj, NAMING_CONTEXT, &[NAMING_CONTEXT_EXT])?
128            .then(|| NamingContext::unchecked_narrow(obj)))
129    }
130
131    /// Uses `obj` as a naming context without checking its type.
132    pub fn unchecked_narrow(obj: ObjectRef) -> NamingContext {
133        NamingContext {
134            stub: idl::NamingContext::unchecked_narrow(obj),
135        }
136    }
137
138    /// The object reference.
139    pub fn object(&self) -> &ObjectRef {
140        self.stub.object()
141    }
142
143    /// The object reference.
144    pub fn into_object(self) -> ObjectRef {
145        self.stub.into_object()
146    }
147
148    /// The generated stub.
149    pub fn stub(&self) -> &idl::NamingContext {
150        &self.stub
151    }
152
153    /// `bind`: binds `n` to `obj`. Raises `NotFound`, `CannotProceed`,
154    /// `InvalidName` or `AlreadyBound`.
155    pub fn bind(&self, n: &[NameComponent], obj: &ObjectRef) -> Result<(), NamingError> {
156        Ok(self.stub.bind(&to_idl_name(n), Some(obj))?)
157    }
158
159    /// `rebind`: binds `n` to `obj`, replacing an object binding. Raises
160    /// `NotFound`, `CannotProceed` or `InvalidName`.
161    pub fn rebind(&self, n: &[NameComponent], obj: &ObjectRef) -> Result<(), NamingError> {
162        Ok(self.stub.rebind(&to_idl_name(n), Some(obj))?)
163    }
164
165    /// `bind_context`: binds `n` to the context `nc`, so that names are
166    /// resolved through it. Raises `NotFound`, `CannotProceed`,
167    /// `InvalidName` or `AlreadyBound`.
168    pub fn bind_context(&self, n: &[NameComponent], nc: &NamingContext) -> Result<(), NamingError> {
169        Ok(self.stub.bind_context(&to_idl_name(n), Some(&nc.stub))?)
170    }
171
172    /// `rebind_context`: binds `n` to the context `nc`, replacing a context
173    /// binding. Raises `NotFound`, `CannotProceed` or `InvalidName`.
174    pub fn rebind_context(
175        &self,
176        n: &[NameComponent],
177        nc: &NamingContext,
178    ) -> Result<(), NamingError> {
179        Ok(self.stub.rebind_context(&to_idl_name(n), Some(&nc.stub))?)
180    }
181
182    /// `resolve`: the object `n` is bound to (`None` if it is bound to a
183    /// nil reference). Raises `NotFound`, `CannotProceed` or
184    /// `InvalidName`.
185    pub fn resolve(&self, n: &[NameComponent]) -> Result<Option<ObjectRef>, NamingError> {
186        Ok(self.stub.resolve(&to_idl_name(n))?)
187    }
188
189    /// `unbind`: removes the binding of `n`. Raises `NotFound`,
190    /// `CannotProceed` or `InvalidName`.
191    pub fn unbind(&self, n: &[NameComponent]) -> Result<(), NamingError> {
192        Ok(self.stub.unbind(&to_idl_name(n))?)
193    }
194
195    /// `new_context`: a new context, not bound to any name, in the same
196    /// naming service.
197    pub fn new_context(&self) -> Result<NamingContext, NamingError> {
198        context(self.stub.new_context()?)
199    }
200
201    /// `bind_new_context`: creates a context and binds it to `n`. Raises
202    /// `NotFound`, `CannotProceed`, `InvalidName` or `AlreadyBound`.
203    pub fn bind_new_context(&self, n: &[NameComponent]) -> Result<NamingContext, NamingError> {
204        context(self.stub.bind_new_context(&to_idl_name(n))?)
205    }
206
207    /// `destroy`: deletes this context, which must have no bindings (or
208    /// `NotEmpty` is raised). Names bound to it elsewhere are not unbound.
209    pub fn destroy(&self) -> Result<(), NamingError> {
210        Ok(self.stub.destroy()?)
211    }
212
213    /// `list`: up to `how_many` bindings of this context, and an iterator
214    /// over the rest if there are more.
215    pub fn list(
216        &self,
217        how_many: u32,
218    ) -> Result<(Vec<Binding>, Option<BindingIterator>), NamingError> {
219        let (list, iterator) = self.stub.list(how_many)?;
220        Ok((
221            bindings(list),
222            iterator.map(|stub| BindingIterator { stub }),
223        ))
224    }
225}
226
227/// A stub for `CosNaming::NamingContextExt`: a [`NamingContext`] (which it
228/// dereferences to) that also works with stringified names and
229/// `corbaname:` URLs.
230#[derive(Debug, Clone)]
231pub struct NamingContextExt {
232    ctx: NamingContext,
233    stub: idl::NamingContextExt,
234}
235
236impl NamingContextExt {
237    /// Narrows `obj` to a `NamingContextExt`: `None` if it is not one. Asks
238    /// the object (`_is_a`) unless the IOR's type id is the repository id
239    /// of `NamingContextExt`.
240    pub fn narrow(obj: ObjectRef) -> Result<Option<NamingContextExt>, SystemException> {
241        Ok(supports(&obj, NAMING_CONTEXT_EXT, &[])?
242            .then(|| NamingContextExt::unchecked_narrow(obj)))
243    }
244
245    /// Uses `obj` as a `NamingContextExt` without checking its type.
246    pub fn unchecked_narrow(obj: ObjectRef) -> NamingContextExt {
247        NamingContextExt {
248            ctx: NamingContext::unchecked_narrow(obj.clone()),
249            stub: idl::NamingContextExt::unchecked_narrow(obj),
250        }
251    }
252
253    /// The context as a plain [`NamingContext`].
254    pub fn context(&self) -> &NamingContext {
255        &self.ctx
256    }
257
258    /// The generated stub.
259    pub fn stub(&self) -> &idl::NamingContextExt {
260        &self.stub
261    }
262
263    /// `to_string`: the naming service writes `n` as a stringified name.
264    /// Raises `InvalidName`. [`to_string`](crate::to_string) does the same
265    /// locally.
266    pub fn to_string(&self, n: &[NameComponent]) -> Result<String, NamingError> {
267        Ok(self.stub.to_string(&to_idl_name(n))?)
268    }
269
270    /// `to_name`: the naming service parses a stringified name. Raises
271    /// `InvalidName`. [`to_name`](crate::to_name) does the same locally.
272    pub fn to_name(&self, sn: &str) -> Result<Name, NamingError> {
273        Ok(from_idl_name(self.stub.to_name(sn)?))
274    }
275
276    /// `to_url`: the naming service makes a `corbaname:` URL from a
277    /// `corbaloc` address list and a stringified name. Raises
278    /// `InvalidAddress` or `InvalidName`. [`to_url`](crate::to_url) does
279    /// the same locally.
280    pub fn to_url(&self, addr: &str, sn: &str) -> Result<String, NamingError> {
281        Ok(self.stub.to_url(addr, sn)?)
282    }
283
284    /// `resolve_str`: resolves a stringified name. Raises `NotFound`,
285    /// `CannotProceed` or `InvalidName`.
286    pub fn resolve_str(&self, sn: &str) -> Result<Option<ObjectRef>, NamingError> {
287        Ok(self.stub.resolve_str(sn)?)
288    }
289}
290
291impl Deref for NamingContextExt {
292    type Target = NamingContext;
293
294    fn deref(&self) -> &NamingContext {
295        &self.ctx
296    }
297}
298
299impl From<NamingContextExt> for NamingContext {
300    fn from(ext: NamingContextExt) -> NamingContext {
301        ext.ctx
302    }
303}
304
305/// A stub for `CosNaming::BindingIterator`, from [`NamingContext::list`].
306///
307/// Call [`destroy`](BindingIterator::destroy) when done; dropping the stub
308/// leaves the iterator in the naming service.
309#[derive(Debug, Clone)]
310pub struct BindingIterator {
311    stub: idl::BindingIterator,
312}
313
314impl BindingIterator {
315    /// Narrows `obj` to a binding iterator: `None` if it is not one.
316    pub fn narrow(obj: ObjectRef) -> Result<Option<BindingIterator>, SystemException> {
317        Ok(idl::BindingIterator::narrow(&obj)?.map(|stub| BindingIterator { stub }))
318    }
319
320    /// The object reference.
321    pub fn object(&self) -> &ObjectRef {
322        self.stub.object()
323    }
324
325    /// `next_one`: the next binding, or `None` at the end.
326    pub fn next_one(&self) -> Result<Option<Binding>, NamingError> {
327        let (more, binding) = self.stub.next_one()?;
328        Ok(more.then(|| binding.into()))
329    }
330
331    /// `next_n`: up to `how_many` more bindings, and whether any were
332    /// returned (`false` at the end).
333    pub fn next_n(&self, how_many: u32) -> Result<(bool, Vec<Binding>), NamingError> {
334        let (more, list) = self.stub.next_n(how_many)?;
335        Ok((more, bindings(list)))
336    }
337
338    /// `destroy`: releases the iterator in the naming service.
339    pub fn destroy(&self) -> Result<(), NamingError> {
340        Ok(self.stub.destroy()?)
341    }
342}
343
344/// Makes a `corbaname:` URL from a `corbaloc` address list (such as
345/// `:host:2809` or `iiop:1.2@host`) and a stringified name, escaping the
346/// name as a URL, like `NamingContextExt::to_url`: `to_url(":host:2809",
347/// "a/b c")` is `corbaname::host:2809#a/b%20c`.
348///
349/// An empty name gives the URL of the context itself, `corbaname:{addr}`.
350/// An address list that `corbaloc:` does not accept, or with a protocol
351/// other than `iiop` and `rir`, is `InvalidAddress`; a malformed name is
352/// `InvalidName`.
353pub fn to_url(addr: &str, sn: &str) -> Result<String, NamingError> {
354    let valid = !addr.contains(['/', '#'])
355        && Corbaloc::parse(&format!("corbaloc:{addr}/x")).is_ok_and(|loc| {
356            loc.addresses
357                .iter()
358                .all(|a| !matches!(a, ObjAddr::Other { .. }))
359        });
360    if !valid {
361        return Err(NamingError::InvalidAddress);
362    }
363    // An empty name is the context itself, as `corbaname:` without `#`
364    // (omniNames answers the same).
365    if sn.is_empty() {
366        return Ok(format!("corbaname:{addr}"));
367    }
368    name::to_name(sn)?;
369    let mut url = format!("corbaname:{addr}#");
370    for b in sn.bytes() {
371        if b.is_ascii_alphanumeric() || b";/:?@&=+$,-_.!~*'()".contains(&b) {
372            url.push(b as char);
373        } else {
374            let _ = write!(url, "%{b:02X}");
375        }
376    }
377    Ok(url)
378}
379
380#[cfg(test)]
381mod tests {
382    use super::*;
383
384    #[test]
385    fn to_url_escapes_the_name() {
386        assert_eq!(
387            to_url(":host:2809", "a/b c").unwrap(),
388            "corbaname::host:2809#a/b%20c"
389        );
390        assert_eq!(
391            to_url("iiop:1.2@host,:other", "x.y/z\\/w").unwrap(),
392            "corbaname:iiop:1.2@host,:other#x.y/z%5C/w"
393        );
394        assert_eq!(to_url("rir:", "a").unwrap(), "corbaname:rir:#a");
395        assert_eq!(to_url(":host", "").unwrap(), "corbaname::host");
396    }
397
398    #[test]
399    fn to_url_checks_address_and_name() {
400        for addr in ["host:2809", "", "iiop:host/x", ":host#a"] {
401            assert!(
402                matches!(to_url(addr, "a"), Err(NamingError::InvalidAddress)),
403                "{addr:?}"
404            );
405        }
406        assert!(matches!(
407            to_url(":host", "a//b"),
408            Err(NamingError::InvalidName)
409        ));
410    }
411}