Skip to main content

rustorb_core/
dii.rs

1//! The Dynamic Invocation Interface (DII) and the Dynamic Skeleton
2//! Interface (DSI): calls and servants whose operations are described at
3//! run time, by TypeCodes, instead of by generated code.
4//!
5//! - [`DiiRequest`] (`CORBA::Request`): a call built from [`NamedValue`]s,
6//!   made by [`ObjectRef::create_request`]. It can be invoked, sent
7//!   oneway, or sent deferred and its response collected later.
8//! - [`DynamicImplementation`] (`PortableServer::DynamicImplementation`):
9//!   a servant that gets each request as a [`ServerRequest`], reads the
10//!   arguments with the TypeCodes it gives, and sets the result or a user
11//!   exception. [`DynamicServant`] makes it a [`Servant`].
12//!
13//! Contexts (`Context`, `ctx`) are not supported. The values are
14//! [`Any`]s, so an argument's type is the TypeCode of its Any.
15
16use std::fmt;
17use std::sync::mpsc;
18use std::time::Duration;
19
20use crate::{
21    Any, CompletionStatus, Exception, InStream, ObjectRef, Orb, Reply, Servant, ServerReply,
22    SystemException, SystemExceptionKind, TCKind, TypeCode, UserException, Value,
23};
24
25/// The direction of an argument (`CORBA::ARG_IN`, `ARG_OUT`, `ARG_INOUT`).
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum ArgMode {
28    In,
29    Out,
30    InOut,
31}
32
33impl ArgMode {
34    /// The `CORBA::Flags` value: 1, 2 or 3.
35    pub fn flags(self) -> u32 {
36        match self {
37            ArgMode::In => 1,
38            ArgMode::Out => 2,
39            ArgMode::InOut => 3,
40        }
41    }
42
43    /// The mode of a `CORBA::Flags` value (other flags ignored).
44    pub fn from_flags(flags: u32) -> Option<ArgMode> {
45        match flags & 3 {
46            1 => Some(ArgMode::In),
47            2 => Some(ArgMode::Out),
48            3 => Some(ArgMode::InOut),
49            _ => None,
50        }
51    }
52
53    fn is_in(self) -> bool {
54        self != ArgMode::Out
55    }
56
57    fn is_out(self) -> bool {
58        self != ArgMode::In
59    }
60}
61
62/// An argument (`CORBA::NamedValue`): a name, a value and a mode. The
63/// value of an `out` argument is only its type until the value arrives:
64/// an Any of that TypeCode holding [`Value::Void`].
65#[derive(Debug, Clone, PartialEq)]
66pub struct NamedValue {
67    pub name: String,
68    pub value: Any,
69    pub mode: ArgMode,
70}
71
72impl NamedValue {
73    pub fn new(name: impl Into<String>, value: Any, mode: ArgMode) -> NamedValue {
74        NamedValue {
75            name: name.into(),
76            value,
77            mode,
78        }
79    }
80
81    /// An `out` argument of type `tc`, still without a value.
82    pub fn out(name: impl Into<String>, tc: TypeCode) -> NamedValue {
83        NamedValue::new(name, Any::new(tc, Value::Void), ArgMode::Out)
84    }
85}
86
87fn sys(kind: SystemExceptionKind, completed: CompletionStatus) -> SystemException {
88    SystemException::new(kind, 0, completed)
89}
90
91fn bad_inv_order() -> SystemException {
92    sys(SystemExceptionKind::BAD_INV_ORDER, CompletionStatus::No)
93}
94
95// --- the client side ---------------------------------------------------------
96
97/// The result of a call sent deferred.
98type Pending = mpsc::Receiver<Result<Reply, Exception>>;
99
100/// `CORBA::Request`: a call whose operation, arguments, result type and
101/// user exceptions are given at run time.
102///
103/// After a call the `out` and `inout` arguments hold the values the server
104/// sent and [`result`](DiiRequest::result) the return value. A user
105/// exception comes back as [`Exception::User`];
106/// [`exception_value`](DiiRequest::exception_value) decodes it with the
107/// TypeCodes given by [`add_exception`](DiiRequest::add_exception).
108pub struct DiiRequest {
109    target: ObjectRef,
110    operation: String,
111    arguments: Vec<NamedValue>,
112    result: Any,
113    exceptions: Vec<TypeCode>,
114    timeout: Option<Option<Duration>>,
115    pending: Option<Pending>,
116}
117
118impl fmt::Debug for DiiRequest {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        f.debug_struct("DiiRequest")
121            .field("operation", &self.operation)
122            .field("arguments", &self.arguments)
123            .field("result", &self.result)
124            .field("pending", &self.pending.is_some())
125            .finish_non_exhaustive()
126    }
127}
128
129impl ObjectRef {
130    /// `CORBA::Object::_request`: a [`DiiRequest`] for `operation`, with
131    /// no arguments and a `void` result.
132    pub fn create_request(&self, operation: &str) -> DiiRequest {
133        DiiRequest {
134            target: self.clone(),
135            operation: operation.to_owned(),
136            arguments: Vec::new(),
137            result: Any::new(TypeCode::void(), Value::Void),
138            exceptions: Vec::new(),
139            timeout: None,
140            pending: None,
141        }
142    }
143}
144
145impl DiiRequest {
146    pub fn target(&self) -> &ObjectRef {
147        &self.target
148    }
149
150    pub fn operation(&self) -> &str {
151        &self.operation
152    }
153
154    /// The arguments (`CORBA::NVList`), in order.
155    pub fn arguments(&self) -> &[NamedValue] {
156        &self.arguments
157    }
158
159    /// The arguments, to change or add to before a call.
160    pub fn arguments_mut(&mut self) -> &mut Vec<NamedValue> {
161        &mut self.arguments
162    }
163
164    pub fn add_in_arg(&mut self, name: &str, value: Any) -> &mut DiiRequest {
165        self.arguments
166            .push(NamedValue::new(name, value, ArgMode::In));
167        self
168    }
169
170    pub fn add_inout_arg(&mut self, name: &str, value: Any) -> &mut DiiRequest {
171        self.arguments
172            .push(NamedValue::new(name, value, ArgMode::InOut));
173        self
174    }
175
176    pub fn add_out_arg(&mut self, name: &str, tc: TypeCode) -> &mut DiiRequest {
177        self.arguments.push(NamedValue::out(name, tc));
178        self
179    }
180
181    /// The type of the return value (`void` until set).
182    pub fn set_return_type(&mut self, tc: TypeCode) -> &mut DiiRequest {
183        self.result = Any::new(tc, Value::Void);
184        self
185    }
186
187    /// The return value after a call (its type before).
188    pub fn result(&self) -> &Any {
189        &self.result
190    }
191
192    /// Adds a user exception the operation may raise (`CORBA::ExceptionList`).
193    pub fn add_exception(&mut self, tc: TypeCode) -> &mut DiiRequest {
194        self.exceptions.push(tc);
195        self
196    }
197
198    pub fn exceptions(&self) -> &[TypeCode] {
199        &self.exceptions
200    }
201
202    /// [`Request::timeout`](crate::Request::timeout) for the calls of this
203    /// request.
204    pub fn set_timeout(&mut self, timeout: Option<Duration>) -> &mut DiiRequest {
205        self.timeout = Some(timeout);
206        self
207    }
208
209    /// The `in` and `inout` values, as the arguments function writes them.
210    fn in_values(&self) -> Vec<(TypeCode, Value)> {
211        self.arguments
212            .iter()
213            .filter(|nv| nv.mode.is_in())
214            .map(|nv| (nv.value.typecode().clone(), nv.value.value().clone()))
215            .collect()
216    }
217
218    fn check_idle(&self) -> Result<(), SystemException> {
219        match self.pending {
220            Some(_) => Err(bad_inv_order()),
221            None => Ok(()),
222        }
223    }
224
225    /// Sends the request and waits for the reply.
226    pub fn invoke(&mut self) -> Result<(), Exception> {
227        self.check_idle()?;
228        let values = self.in_values();
229        let mut request = self
230            .target
231            .request(&self.operation)
232            .args(move |out| write_values(out, &values));
233        if let Some(t) = self.timeout {
234            request = request.timeout(t);
235        }
236        let reply = request.invoke()?;
237        self.take_reply(&reply)
238    }
239
240    /// [`invoke`](DiiRequest::invoke) as a future (see
241    /// [`AsyncRequest`](crate::AsyncRequest)).
242    pub async fn invoke_async(&mut self) -> Result<(), Exception> {
243        self.check_idle()?;
244        let values = self.in_values();
245        let mut request = self
246            .target
247            .request_async(&self.operation)
248            .args(move |out| write_values(out, &values));
249        if let Some(t) = self.timeout {
250            request = request.timeout(t);
251        }
252        let reply = request.invoke().await?;
253        self.take_reply(&reply)
254    }
255
256    /// Sends the request as a oneway call.
257    pub fn send_oneway(&self) -> Result<(), SystemException> {
258        self.check_idle()?;
259        let values = self.in_values();
260        let mut request = self
261            .target
262            .request(&self.operation)
263            .args(move |out| write_values(out, &values));
264        if let Some(t) = self.timeout {
265            request = request.timeout(t);
266        }
267        request.send_oneway()
268    }
269
270    /// Sends the request without waiting: the reply is collected by
271    /// [`poll_response`](DiiRequest::poll_response) and
272    /// [`get_response`](DiiRequest::get_response). The arguments are taken
273    /// now. A request still waiting for its response cannot be sent again
274    /// (`BAD_INV_ORDER`).
275    pub fn send_deferred(&mut self) -> Result<(), SystemException> {
276        self.check_idle()?;
277        let orb: Orb = self.target.orb().clone();
278        orb.check_running()?;
279        let values = self.in_values();
280        let target = self.target.clone();
281        let operation = self.operation.clone();
282        let timeout = self.timeout;
283        let (tx, rx) = mpsc::channel();
284        // The thread's timeout is that of the thread that sends.
285        let timeout = timeout.unwrap_or_else(|| target.effective_timeout());
286        orb.runtime_handle().spawn(async move {
287            let result = target
288                .request_async(&operation)
289                .args(move |out| write_values(out, &values))
290                .timeout(timeout)
291                .invoke()
292                .await;
293            let _ = tx.send(result);
294        });
295        self.pending = Some(rx);
296        Ok(())
297    }
298
299    /// Whether the response of [`send_deferred`](DiiRequest::send_deferred)
300    /// has arrived. `BAD_INV_ORDER` when nothing was sent deferred.
301    pub fn poll_response(&mut self) -> Result<bool, SystemException> {
302        let Some(rx) = &self.pending else {
303            return Err(bad_inv_order());
304        };
305        match rx.try_recv() {
306            Ok(result) => {
307                // Kept for get_response: put back as a ready channel.
308                let (tx, ready) = mpsc::channel();
309                let _ = tx.send(result);
310                self.pending = Some(ready);
311                Ok(true)
312            }
313            Err(mpsc::TryRecvError::Empty) => Ok(false),
314            Err(mpsc::TryRecvError::Disconnected) => Ok(true),
315        }
316    }
317
318    /// Waits for the response of [`send_deferred`](DiiRequest::send_deferred)
319    /// and takes it like [`invoke`](DiiRequest::invoke). `BAD_INV_ORDER`
320    /// when nothing was sent deferred.
321    pub fn get_response(&mut self) -> Result<(), Exception> {
322        let Some(rx) = self.pending.take() else {
323            return Err(bad_inv_order().into());
324        };
325        // A dropped sender: the runtime went away with the call.
326        let result = rx.recv().unwrap_or_else(|_| {
327            Err(sys(SystemExceptionKind::COMM_FAILURE, CompletionStatus::Maybe).into())
328        });
329        self.take_reply(&result?)
330    }
331
332    /// Reads the return value and the `out` and `inout` arguments.
333    fn take_reply(&mut self, reply: &Reply) -> Result<(), Exception> {
334        let mut input = reply.input();
335        let tc = self.result.typecode().clone();
336        let value = input.read_value(&tc)?;
337        self.result = Any::new(tc, value);
338        for nv in self.arguments.iter_mut().filter(|nv| nv.mode.is_out()) {
339            let tc = nv.value.typecode().clone();
340            let value = input.read_value(&tc)?;
341            nv.value = Any::new(tc, value);
342        }
343        Ok(())
344    }
345
346    /// The user exception `e` of a call of this request as an Any, with the
347    /// TypeCode of [`exceptions`](DiiRequest::exceptions) of the same
348    /// repository id. An exception that is not listed is `UNKNOWN`,
349    /// completed yes.
350    pub fn exception_value(&self, e: &UserException) -> Result<Any, SystemException> {
351        let tc = self
352            .exceptions
353            .iter()
354            .find(|tc| tc.unaliased().id().ok() == Some(e.repository_id()))
355            .ok_or_else(|| sys(SystemExceptionKind::UNKNOWN, CompletionStatus::Yes))?;
356        let mut input = e.reply.input();
357        let value = input.read_value(tc)?;
358        Ok(Any::new(tc.clone(), value))
359    }
360}
361
362fn write_values(
363    out: &mut crate::OutStream<'_>,
364    values: &[(TypeCode, Value)],
365) -> Result<(), SystemException> {
366    for (tc, v) in values {
367        out.write_value(tc, v)?;
368    }
369    Ok(())
370}
371
372// --- the server side ---------------------------------------------------------
373
374/// `PortableServer::DynamicImplementation`: a servant that handles every
375/// operation itself, from a [`ServerRequest`]. Wrap it in
376/// [`DynamicServant`] to activate it.
377pub trait DynamicImplementation: Send + Sync {
378    /// `_primary_interface`: the repository id of the most derived
379    /// interface the servant implements, the type id of its references.
380    fn primary_interface(&self) -> &str;
381
382    /// Whether the servant implements `repository_id`; the default only
383    /// knows the primary interface.
384    fn is_a(&self, repository_id: &str) -> bool {
385        repository_id == self.primary_interface()
386    }
387
388    /// Runs `request`: calls [`ServerRequest::arguments`] once with the
389    /// types and modes of the parameters, and then
390    /// [`set_result`](ServerRequest::set_result) or
391    /// [`set_exception`](ServerRequest::set_exception), or returns a system
392    /// exception. An unknown operation is `BAD_OPERATION` with minor
393    /// [`UNKNOWN_OPERATION`](crate::minor::UNKNOWN_OPERATION).
394    fn invoke(&self, request: &mut ServerRequest) -> Result<(), SystemException>;
395}
396
397/// A [`DynamicImplementation`] as a [`Servant`].
398#[derive(Debug)]
399pub struct DynamicServant<T>(pub T);
400
401impl<T: DynamicImplementation> Servant for DynamicServant<T> {
402    fn repository_id(&self) -> &str {
403        self.0.primary_interface()
404    }
405
406    fn is_a(&self, repository_id: &str) -> bool {
407        self.0.is_a(repository_id)
408    }
409
410    fn dispatch(
411        &self,
412        operation: &str,
413        input: &mut InStream<'_>,
414        reply: &mut ServerReply,
415    ) -> Result<(), SystemException> {
416        let mut request = ServerRequest::new(operation, input)?;
417        self.0.invoke(&mut request)?;
418        request.write_reply(reply)
419    }
420}
421
422/// `CORBA::ServerRequest`: a request to a [`DynamicImplementation`].
423///
424/// It owns what it needs of the request, so a binding can keep it while it
425/// calls into its language.
426pub struct ServerRequest {
427    operation: String,
428    input: Option<crate::stream::DetachedInput>,
429    arguments: Option<Vec<NamedValue>>,
430    result: Option<Any>,
431    exception: Option<Any>,
432}
433
434impl fmt::Debug for ServerRequest {
435    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
436        f.debug_struct("ServerRequest")
437            .field("operation", &self.operation)
438            .field("arguments", &self.arguments)
439            .field("result", &self.result)
440            .field("exception", &self.exception)
441            .finish_non_exhaustive()
442    }
443}
444
445impl ServerRequest {
446    /// The request for `operation` whose arguments `input` (the stream a
447    /// servant's [`dispatch`](Servant::dispatch) gets, nothing read from it
448    /// yet) holds.
449    pub fn new(operation: &str, input: &InStream<'_>) -> Result<ServerRequest, SystemException> {
450        let input = input
451            .detach()
452            .ok_or_else(|| sys(SystemExceptionKind::INTERNAL, CompletionStatus::No))?;
453        Ok(ServerRequest {
454            operation: operation.to_owned(),
455            input: Some(input),
456            arguments: None,
457            result: None,
458            exception: None,
459        })
460    }
461
462    pub fn operation(&self) -> &str {
463        &self.operation
464    }
465
466    /// Reads the `in` and `inout` arguments into `parameters` (whose
467    /// TypeCodes and modes describe the operation's parameters, in order)
468    /// and keeps them; the servant then sets the `out` and `inout` values
469    /// in the returned slice (or later in
470    /// [`parameters_mut`](ServerRequest::parameters_mut)). Called once:
471    /// again is `BAD_INV_ORDER`. Arguments that do not match the types are
472    /// `MARSHAL`, completed no.
473    pub fn arguments(
474        &mut self,
475        mut parameters: Vec<NamedValue>,
476    ) -> Result<&mut [NamedValue], SystemException> {
477        let Some(input) = self.input.take() else {
478            return Err(bad_inv_order());
479        };
480        {
481            let mut stream = input.stream();
482            for nv in parameters.iter_mut().filter(|nv| nv.mode.is_in()) {
483                let tc = nv.value.typecode().clone();
484                let value = stream.read_value(&tc)?;
485                nv.value = Any::new(tc, value);
486            }
487        }
488        Ok(self.arguments.insert(parameters))
489    }
490
491    /// The parameters given to [`arguments`](ServerRequest::arguments).
492    pub fn parameters_mut(&mut self) -> Option<&mut [NamedValue]> {
493        self.arguments.as_deref_mut()
494    }
495
496    /// Sets the return value (for an operation with a `void` result, an
497    /// Any of type `void`, or none at all). `BAD_INV_ORDER` before
498    /// [`arguments`](ServerRequest::arguments) or after
499    /// [`set_exception`](ServerRequest::set_exception).
500    pub fn set_result(&mut self, value: Any) -> Result<(), SystemException> {
501        if self.arguments.is_none() || self.exception.is_some() {
502            return Err(bad_inv_order());
503        }
504        self.result = Some(value);
505        Ok(())
506    }
507
508    /// Makes the reply the user exception `value` (an Any of a `tk_except`
509    /// TypeCode; another is `BAD_PARAM`). A system exception is returned
510    /// from [`DynamicImplementation::invoke`] instead.
511    pub fn set_exception(&mut self, value: Any) -> Result<(), SystemException> {
512        if value.typecode().unaliased().kind() != TCKind::Except {
513            return Err(sys(SystemExceptionKind::BAD_PARAM, CompletionStatus::No));
514        }
515        self.exception = Some(value);
516        Ok(())
517    }
518
519    /// Writes the reply: the user exception, or the return value and the
520    /// `out` and `inout` arguments in order. A value that does not fit its
521    /// type (an `out` argument left without a value, say) is `BAD_PARAM`.
522    pub fn write_reply(self, reply: &mut ServerReply) -> Result<(), SystemException> {
523        if let Some(exception) = &self.exception {
524            let tc = exception.typecode().unaliased();
525            let id = tc.id().unwrap_or_default().to_owned();
526            let Value::List(members) = exception.value() else {
527                return Err(sys(SystemExceptionKind::BAD_PARAM, CompletionStatus::Maybe));
528            };
529            let mut out = reply.user_exception(&id)?;
530            for (i, member) in members.iter().enumerate() {
531                let member_tc = tc
532                    .member_type(i as u32)
533                    .map_err(|_| sys(SystemExceptionKind::BAD_PARAM, CompletionStatus::Maybe))?;
534                out.write_value(&member_tc, member)?;
535            }
536            return Ok(());
537        }
538        let mut out = reply.output();
539        if let Some(result) = &self.result {
540            out.write_value(result.typecode(), result.value())?;
541        }
542        for nv in self
543            .arguments
544            .iter()
545            .flatten()
546            .filter(|nv| nv.mode.is_out())
547        {
548            out.write_value(nv.value.typecode(), nv.value.value())?;
549        }
550        Ok(())
551    }
552}