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