Skip to main content

rustorb_core/
servant.rs

1//! Servants, the replies they write, servant managers and adapter
2//! activators.
3
4use std::any::Any;
5use std::fmt;
6use std::sync::Arc;
7
8use rustorb_cdr::{ByteOrder, CdrEncode};
9use rustorb_giop::{
10    Ior, MessageEncoder, OutMessage, ReplyHeader, ReplyStatus, ServiceContext, SystemExceptionBody,
11    Version,
12};
13
14use crate::stream::{InStream, OutStream};
15use crate::{CodeSets, CompletionStatus, ObjectRef, Poa, SystemException, SystemExceptionKind};
16
17/// The repository id every object is (`CORBA::Object`).
18pub(crate) const OBJECT_ID: &str = "IDL:omg.org/CORBA/Object:1.0";
19
20/// The implementation of a CORBA object, called by a POA.
21///
22/// Generated skeletons (and the adapters of the language bindings)
23/// implement it. Servants are called on the ORB's upcall threads, possibly
24/// on several at once, so they must be `Send + Sync`.
25pub trait Servant: Send + Sync {
26    /// Repository id of the most derived interface, used as the type id of
27    /// the servant's references and for `_is_a`.
28    fn repository_id(&self) -> &str;
29
30    /// Whether the servant implements the interface `repository_id`. The
31    /// default only knows [`repository_id`](Servant::repository_id);
32    /// `IDL:omg.org/CORBA/Object:1.0` is answered by the ORB.
33    fn is_a(&self, repository_id: &str) -> bool {
34        repository_id == self.repository_id()
35    }
36
37    /// Runs `operation`: reads the `in` and `inout` arguments from `input`
38    /// and writes the result to `reply`. An operation the servant does not
39    /// know should return `BAD_OPERATION` with minor
40    /// [`UNKNOWN_OPERATION`](crate::minor::UNKNOWN_OPERATION), and a user
41    /// exception is written with [`ServerReply::user_exception`].
42    ///
43    /// `_is_a`, `_non_existent`, `_interface` and `_repository_id` are
44    /// answered by the ORB and do not reach the servant.
45    fn dispatch(
46        &self,
47        operation: &str,
48        input: &mut InStream<'_>,
49        reply: &mut ServerReply,
50    ) -> Result<(), SystemException>;
51}
52
53/// What a servant manager raises instead of providing a servant.
54#[derive(Debug, Clone)]
55pub enum ServantManagerError {
56    /// `PortableServer::ForwardRequest`: the client is sent to this object
57    /// with a `LOCATION_FORWARD` reply.
58    ForwardRequest(ObjectRef),
59    /// A system exception, returned to the client as it is.
60    System(SystemException),
61}
62
63impl From<SystemException> for ServantManagerError {
64    fn from(e: SystemException) -> Self {
65        ServantManagerError::System(e)
66    }
67}
68
69impl fmt::Display for ServantManagerError {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        match self {
72            ServantManagerError::ForwardRequest(_) => f.write_str("PortableServer::ForwardRequest"),
73            ServantManagerError::System(e) => e.fmt(f),
74        }
75    }
76}
77
78impl std::error::Error for ServantManagerError {}
79
80/// `PortableServer::ServantActivator`: the servant manager of a POA with
81/// the RETAIN and USE_SERVANT_MANAGER policies. It is asked for a servant
82/// the first time an object that is not in the active object map gets a
83/// request, and the servant stays in the map until the object is
84/// deactivated.
85///
86/// Both methods are called on the ORB's upcall threads.
87pub trait ServantActivator: Send + Sync {
88    /// The servant for the object `id` of `adapter`. Called once per
89    /// activation: requests for the same object that arrive meanwhile wait
90    /// for the result.
91    fn incarnate(&self, id: &[u8], adapter: &Poa) -> Result<Arc<dyn Servant>, ServantManagerError>;
92
93    /// The object `id` was deactivated, and its last request finished.
94    /// `cleanup_in_progress` is true when the POA is destroyed or its
95    /// manager deactivated; `remaining_activations` whether `servant` is
96    /// still active under other ObjectIds.
97    fn etherealize(
98        &self,
99        id: &[u8],
100        adapter: &Poa,
101        servant: Arc<dyn Servant>,
102        cleanup_in_progress: bool,
103        remaining_activations: bool,
104    ) {
105        let _ = (
106            id,
107            adapter,
108            servant,
109            cleanup_in_progress,
110            remaining_activations,
111        );
112    }
113}
114
115/// The cookie a [`ServantLocator`] passes from `preinvoke` to `postinvoke`.
116pub type Cookie = Box<dyn Any + Send>;
117
118/// `PortableServer::ServantLocator`: the servant manager of a POA with the
119/// NON_RETAIN and USE_SERVANT_MANAGER policies, asked for a servant for
120/// every request.
121///
122/// Both methods are called on the thread that runs the request.
123pub trait ServantLocator: Send + Sync {
124    /// The servant to run `operation` on the object `id` of `adapter`, and
125    /// a cookie for [`postinvoke`](ServantLocator::postinvoke).
126    fn preinvoke(
127        &self,
128        id: &[u8],
129        adapter: &Poa,
130        operation: &str,
131    ) -> Result<(Arc<dyn Servant>, Cookie), ServantManagerError>;
132
133    /// The request that `preinvoke` provided `servant` for has run, whatever
134    /// its outcome. Not called when `preinvoke` failed.
135    fn postinvoke(
136        &self,
137        id: &[u8],
138        adapter: &Poa,
139        operation: &str,
140        cookie: Cookie,
141        servant: Arc<dyn Servant>,
142    ) {
143        let _ = (id, adapter, operation, cookie, servant);
144    }
145}
146
147/// `PortableServer::ServantManager`: one of the two kinds.
148#[derive(Clone)]
149pub enum ServantManager {
150    /// For a POA with RETAIN.
151    Activator(Arc<dyn ServantActivator>),
152    /// For a POA with NON_RETAIN.
153    Locator(Arc<dyn ServantLocator>),
154}
155
156impl fmt::Debug for ServantManager {
157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158        match self {
159            ServantManager::Activator(_) => f.write_str("ServantManager::Activator"),
160            ServantManager::Locator(_) => f.write_str("ServantManager::Locator"),
161        }
162    }
163}
164
165/// `PortableServer::AdapterActivator`: creates child POAs on demand, when
166/// a request or [`Poa::find_poa`] names a child that does not exist.
167pub trait AdapterActivator: Send + Sync {
168    /// Creates the child `name` of `parent` (with [`Poa::create_poa`]) and
169    /// returns true, or returns false if there is no such POA. Called on an
170    /// upcall thread; calls for the same name are made one at a time, and
171    /// requests for it wait for the result.
172    fn unknown_adapter(&self, parent: &Poa, name: &str) -> bool;
173}
174
175/// The reply a servant writes: the return value and the `out` and `inout`
176/// arguments, in order, or a user exception.
177#[derive(Debug)]
178pub struct ServerReply {
179    version: Version,
180    order: ByteOrder,
181    request_id: u32,
182    code_sets: CodeSets,
183    msg: MessageEncoder,
184    status: ReplyStatus,
185    /// The service contexts in the header (from server interceptors).
186    contexts: Vec<ServiceContext>,
187    /// The repository id of the user exception written, if one was.
188    exception_id: Option<String>,
189}
190
191impl ServerReply {
192    pub(crate) fn new(
193        version: Version,
194        order: ByteOrder,
195        request_id: u32,
196        code_sets: CodeSets,
197    ) -> Result<ServerReply, SystemException> {
198        ServerReply::with_contexts(version, order, request_id, code_sets, Vec::new())
199    }
200
201    /// A reply whose header has the service contexts `contexts`.
202    pub(crate) fn with_contexts(
203        version: Version,
204        order: ByteOrder,
205        request_id: u32,
206        code_sets: CodeSets,
207        contexts: Vec<ServiceContext>,
208    ) -> Result<ServerReply, SystemException> {
209        Ok(ServerReply {
210            version,
211            order,
212            request_id,
213            code_sets,
214            msg: start(
215                version,
216                order,
217                request_id,
218                ReplyStatus::NoException,
219                &contexts,
220            )?,
221            status: ReplyStatus::NoException,
222            contexts,
223            exception_id: None,
224        })
225    }
226
227    /// The stream for the result. Each call continues where the last one
228    /// stopped.
229    pub fn output(&mut self) -> OutStream<'_> {
230        OutStream {
231            enc: self.msg.body(),
232            code_sets: self.code_sets,
233            orb: None,
234            values: None,
235        }
236    }
237
238    /// Replaces the reply with the user exception `repository_id`, and
239    /// returns the stream its members are written to.
240    pub fn user_exception(
241        &mut self,
242        repository_id: &str,
243    ) -> Result<OutStream<'_>, SystemException> {
244        self.msg = start(
245            self.version,
246            self.order,
247            self.request_id,
248            ReplyStatus::UserException,
249            &self.contexts,
250        )?;
251        self.status = ReplyStatus::UserException;
252        self.exception_id = Some(repository_id.to_owned());
253        let mut out = self.output();
254        out.write_string(repository_id)?;
255        Ok(out)
256    }
257
258    /// The status the reply has so far.
259    pub fn status(&self) -> ReplyStatus {
260        self.status
261    }
262
263    /// The repository id of the user exception written, if one was.
264    pub(crate) fn exception_id(&self) -> Option<&str> {
265        self.exception_id.as_deref()
266    }
267
268    /// The whole reply; large octet sequences written with
269    /// `write_octet_seq_shared` are not copied into it.
270    pub(crate) fn finish(self) -> Result<OutMessage, SystemException> {
271        self.msg.finish_shared().map_err(|_| internal())
272    }
273
274    /// The whole reply with the service contexts `contexts` in its header
275    /// instead of those it was made with. Before GIOP 1.2, contexts that
276    /// would move the body off its alignment cannot be sent: the reply
277    /// keeps the ones it was made with (docs/portable-interceptors.md).
278    pub(crate) fn finish_with(
279        self,
280        contexts: Vec<ServiceContext>,
281    ) -> Result<OutMessage, SystemException> {
282        if contexts == self.contexts {
283            return self.finish();
284        }
285        let header = ReplyHeader {
286            request_id: self.request_id,
287            reply_status: self.status,
288            service_context: contexts,
289        };
290        let msg = self.msg.finish_shared().map_err(|_| internal())?;
291        Ok(match msg.with_reply_header(&header) {
292            Ok(msg) => msg,
293            Err(msg) => {
294                crate::trace::warning!(
295                    "reply to request id {}: the service contexts added after the servant ran \
296                     would misalign the GIOP 1.0/1.1 body, and are not sent",
297                    header.request_id
298                );
299                msg
300            }
301        })
302    }
303}
304
305fn start(
306    version: Version,
307    order: ByteOrder,
308    request_id: u32,
309    reply_status: ReplyStatus,
310    contexts: &[ServiceContext],
311) -> Result<MessageEncoder, SystemException> {
312    let header = ReplyHeader {
313        request_id,
314        reply_status,
315        service_context: contexts.to_vec(),
316    };
317    MessageEncoder::reply(version, order, &header).map_err(|_| internal())
318}
319
320fn internal() -> SystemException {
321    SystemException::new(SystemExceptionKind::INTERNAL, 0, CompletionStatus::Maybe)
322}
323
324/// A whole `Reply` sending the client to `ior` (`LOCATION_FORWARD`).
325pub(crate) fn location_forward_reply(
326    version: Version,
327    order: ByteOrder,
328    request_id: u32,
329    ior: &Ior,
330    contexts: &[ServiceContext],
331) -> Option<Vec<u8>> {
332    let mut m = start(
333        version,
334        order,
335        request_id,
336        ReplyStatus::LocationForward,
337        contexts,
338    )
339    .ok()?;
340    ior.encode(m.body()).ok()?;
341    m.finish().ok()
342}
343
344/// A whole `Reply` carrying the system exception `e`.
345pub(crate) fn system_exception_reply(
346    version: Version,
347    order: ByteOrder,
348    request_id: u32,
349    e: &SystemException,
350    contexts: &[ServiceContext],
351) -> Option<Vec<u8>> {
352    let mut m = start(
353        version,
354        order,
355        request_id,
356        ReplyStatus::SystemException,
357        contexts,
358    )
359    .ok()?;
360    SystemExceptionBody::from(e).encode(m.body()).ok()?;
361    m.finish().ok()
362}