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        }
235    }
236
237    /// Replaces the reply with the user exception `repository_id`, and
238    /// returns the stream its members are written to.
239    pub fn user_exception(
240        &mut self,
241        repository_id: &str,
242    ) -> Result<OutStream<'_>, SystemException> {
243        self.msg = start(
244            self.version,
245            self.order,
246            self.request_id,
247            ReplyStatus::UserException,
248            &self.contexts,
249        )?;
250        self.status = ReplyStatus::UserException;
251        self.exception_id = Some(repository_id.to_owned());
252        let mut out = self.output();
253        out.write_string(repository_id)?;
254        Ok(out)
255    }
256
257    /// The status the reply has so far.
258    pub fn status(&self) -> ReplyStatus {
259        self.status
260    }
261
262    /// The repository id of the user exception written, if one was.
263    pub(crate) fn exception_id(&self) -> Option<&str> {
264        self.exception_id.as_deref()
265    }
266
267    /// The whole reply; large octet sequences written with
268    /// `write_octet_seq_shared` are not copied into it.
269    pub(crate) fn finish(self) -> Result<OutMessage, SystemException> {
270        self.msg.finish_shared().map_err(|_| internal())
271    }
272
273    /// The whole reply with the service contexts `contexts` in its header
274    /// instead of those it was made with. Before GIOP 1.2, contexts that
275    /// would move the body off its alignment cannot be sent: the reply
276    /// keeps the ones it was made with (docs/portable-interceptors.md).
277    pub(crate) fn finish_with(
278        self,
279        contexts: Vec<ServiceContext>,
280    ) -> Result<OutMessage, SystemException> {
281        if contexts == self.contexts {
282            return self.finish();
283        }
284        let header = ReplyHeader {
285            request_id: self.request_id,
286            reply_status: self.status,
287            service_context: contexts,
288        };
289        let msg = self.msg.finish_shared().map_err(|_| internal())?;
290        Ok(match msg.with_reply_header(&header) {
291            Ok(msg) => msg,
292            Err(msg) => {
293                crate::trace::warning!(
294                    "reply to request id {}: the service contexts added after the servant ran \
295                     would misalign the GIOP 1.0/1.1 body, and are not sent",
296                    header.request_id
297                );
298                msg
299            }
300        })
301    }
302}
303
304fn start(
305    version: Version,
306    order: ByteOrder,
307    request_id: u32,
308    reply_status: ReplyStatus,
309    contexts: &[ServiceContext],
310) -> Result<MessageEncoder, SystemException> {
311    let header = ReplyHeader {
312        request_id,
313        reply_status,
314        service_context: contexts.to_vec(),
315    };
316    MessageEncoder::reply(version, order, &header).map_err(|_| internal())
317}
318
319fn internal() -> SystemException {
320    SystemException::new(SystemExceptionKind::INTERNAL, 0, CompletionStatus::Maybe)
321}
322
323/// A whole `Reply` sending the client to `ior` (`LOCATION_FORWARD`).
324pub(crate) fn location_forward_reply(
325    version: Version,
326    order: ByteOrder,
327    request_id: u32,
328    ior: &Ior,
329    contexts: &[ServiceContext],
330) -> Option<Vec<u8>> {
331    let mut m = start(
332        version,
333        order,
334        request_id,
335        ReplyStatus::LocationForward,
336        contexts,
337    )
338    .ok()?;
339    ior.encode(m.body()).ok()?;
340    m.finish().ok()
341}
342
343/// A whole `Reply` carrying the system exception `e`.
344pub(crate) fn system_exception_reply(
345    version: Version,
346    order: ByteOrder,
347    request_id: u32,
348    e: &SystemException,
349    contexts: &[ServiceContext],
350) -> Option<Vec<u8>> {
351    let mut m = start(
352        version,
353        order,
354        request_id,
355        ReplyStatus::SystemException,
356        contexts,
357    )
358    .ok()?;
359    SystemExceptionBody::from(e).encode(m.body()).ok()?;
360    m.finish().ok()
361}