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    pub(crate) fn is_in(self) -> bool {
54        self != ArgMode::Out
55    }
56
57    pub(crate) 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    /// What the client interceptors see of the request, if the ORB has
219    /// any.
220    fn pi_params(&self) -> Option<crate::pi::DiiParams> {
221        let pi = self.target.orb().interceptors()?;
222        pi.has_client().then(|| crate::pi::DiiParams {
223            arguments: self.arguments.clone(),
224            result: self.result.typecode().clone(),
225            exceptions: self.exceptions.clone(),
226        })
227    }
228
229    fn check_idle(&self) -> Result<(), SystemException> {
230        match self.pending {
231            Some(_) => Err(bad_inv_order()),
232            None => Ok(()),
233        }
234    }
235
236    /// Sends the request and waits for the reply.
237    pub fn invoke(&mut self) -> Result<(), Exception> {
238        self.check_idle()?;
239        let values = self.in_values();
240        let mut request = self
241            .target
242            .request(&self.operation)
243            .args(move |out| write_values(out, &values));
244        if let Some(t) = self.timeout {
245            request = request.timeout(t);
246        }
247        if let Some(params) = self.pi_params() {
248            request = request.dii(params);
249        }
250        let reply = request.invoke()?;
251        self.take_reply(&reply)
252    }
253
254    /// [`invoke`](DiiRequest::invoke) as a future (see
255    /// [`AsyncRequest`](crate::AsyncRequest)).
256    pub async fn invoke_async(&mut self) -> Result<(), Exception> {
257        self.check_idle()?;
258        let values = self.in_values();
259        let mut request = self
260            .target
261            .request_async(&self.operation)
262            .args(move |out| write_values(out, &values));
263        if let Some(t) = self.timeout {
264            request = request.timeout(t);
265        }
266        if let Some(params) = self.pi_params() {
267            request = request.dii(params);
268        }
269        let reply = request.invoke().await?;
270        self.take_reply(&reply)
271    }
272
273    /// Sends the request as a oneway call.
274    pub fn send_oneway(&self) -> Result<(), SystemException> {
275        self.check_idle()?;
276        let values = self.in_values();
277        let mut request = self
278            .target
279            .request(&self.operation)
280            .args(move |out| write_values(out, &values));
281        if let Some(t) = self.timeout {
282            request = request.timeout(t);
283        }
284        if let Some(params) = self.pi_params() {
285            request = request.dii(params);
286        }
287        request.send_oneway()
288    }
289
290    /// Sends the request without waiting: the reply is collected by
291    /// [`poll_response`](DiiRequest::poll_response) and
292    /// [`get_response`](DiiRequest::get_response). The arguments are taken
293    /// now. A request still waiting for its response cannot be sent again
294    /// (`BAD_INV_ORDER`).
295    pub fn send_deferred(&mut self) -> Result<(), SystemException> {
296        self.check_idle()?;
297        let orb: Orb = self.target.orb().clone();
298        orb.check_running()?;
299        let values = self.in_values();
300        let target = self.target.clone();
301        let operation = self.operation.clone();
302        let timeout = self.timeout;
303        let (tx, rx) = mpsc::channel();
304        // The thread's timeout is that of the thread that sends.
305        let timeout = timeout.unwrap_or_else(|| target.effective_timeout());
306        let params = self.pi_params();
307        // The request scope slots are those of the thread that sends.
308        let slots = target.request_slots();
309        orb.runtime_handle().spawn(async move {
310            let mut request = target
311                .request_async(&operation)
312                .args(move |out| write_values(out, &values))
313                .timeout(timeout)
314                .slots(slots);
315            if let Some(params) = params {
316                request = request.dii(params);
317            }
318            let result = request.invoke().await;
319            let _ = tx.send(result);
320        });
321        self.pending = Some(rx);
322        Ok(())
323    }
324
325    /// Whether the response of [`send_deferred`](DiiRequest::send_deferred)
326    /// has arrived. `BAD_INV_ORDER` when nothing was sent deferred.
327    pub fn poll_response(&mut self) -> Result<bool, SystemException> {
328        let Some(rx) = &self.pending else {
329            return Err(bad_inv_order());
330        };
331        match rx.try_recv() {
332            Ok(result) => {
333                // Kept for get_response: put back as a ready channel.
334                let (tx, ready) = mpsc::channel();
335                let _ = tx.send(result);
336                self.pending = Some(ready);
337                Ok(true)
338            }
339            Err(mpsc::TryRecvError::Empty) => Ok(false),
340            Err(mpsc::TryRecvError::Disconnected) => Ok(true),
341        }
342    }
343
344    /// Waits for the response of [`send_deferred`](DiiRequest::send_deferred)
345    /// and takes it like [`invoke`](DiiRequest::invoke). `BAD_INV_ORDER`
346    /// when nothing was sent deferred.
347    pub fn get_response(&mut self) -> Result<(), Exception> {
348        let Some(rx) = self.pending.take() else {
349            return Err(bad_inv_order().into());
350        };
351        // A dropped sender: the runtime went away with the call.
352        let result = rx.recv().unwrap_or_else(|_| {
353            Err(sys(SystemExceptionKind::COMM_FAILURE, CompletionStatus::Maybe).into())
354        });
355        self.take_reply(&result?)
356    }
357
358    /// Reads the return value and the `out` and `inout` arguments.
359    fn take_reply(&mut self, reply: &Reply) -> Result<(), Exception> {
360        let mut input = reply.input();
361        let tc = self.result.typecode().clone();
362        let value = input.read_value(&tc)?;
363        self.result = Any::new(tc, value);
364        for nv in self.arguments.iter_mut().filter(|nv| nv.mode.is_out()) {
365            let tc = nv.value.typecode().clone();
366            let value = input.read_value(&tc)?;
367            nv.value = Any::new(tc, value);
368        }
369        Ok(())
370    }
371
372    /// The user exception `e` of a call of this request as an Any, with the
373    /// TypeCode of [`exceptions`](DiiRequest::exceptions) of the same
374    /// repository id. An exception that is not listed is `UNKNOWN`,
375    /// completed yes.
376    pub fn exception_value(&self, e: &UserException) -> Result<Any, SystemException> {
377        exception_any(&self.exceptions, e)
378    }
379}
380
381/// The user exception `e` as an Any, with the TypeCode of `exceptions`
382/// of the same repository id (`UNKNOWN` if none).
383pub(crate) fn exception_any(
384    exceptions: &[TypeCode],
385    e: &UserException,
386) -> Result<Any, SystemException> {
387    let tc = exceptions
388        .iter()
389        .find(|tc| tc.unaliased().id().ok() == Some(e.repository_id()))
390        .ok_or_else(|| sys(SystemExceptionKind::UNKNOWN, CompletionStatus::Yes))?;
391    let mut input = e.reply.input();
392    let value = input.read_value(tc)?;
393    Ok(Any::new(tc.clone(), value))
394}
395
396fn write_values(
397    out: &mut crate::OutStream<'_>,
398    values: &[(TypeCode, Value)],
399) -> Result<(), SystemException> {
400    for (tc, v) in values {
401        out.write_value(tc, v)?;
402    }
403    Ok(())
404}
405
406// --- the server side ---------------------------------------------------------
407
408/// `PortableServer::DynamicImplementation`: a servant that handles every
409/// operation itself, from a [`ServerRequest`]. Wrap it in
410/// [`DynamicServant`] to activate it.
411pub trait DynamicImplementation: Send + Sync {
412    /// `_primary_interface`: the repository id of the most derived
413    /// interface the servant implements, the type id of its references.
414    fn primary_interface(&self) -> &str;
415
416    /// Whether the servant implements `repository_id`; the default only
417    /// knows the primary interface.
418    fn is_a(&self, repository_id: &str) -> bool {
419        repository_id == self.primary_interface()
420    }
421
422    /// Runs `request`: calls [`ServerRequest::arguments`] once with the
423    /// types and modes of the parameters, and then
424    /// [`set_result`](ServerRequest::set_result) or
425    /// [`set_exception`](ServerRequest::set_exception), or returns a system
426    /// exception. An unknown operation is `BAD_OPERATION` with minor
427    /// [`UNKNOWN_OPERATION`](crate::minor::UNKNOWN_OPERATION).
428    fn invoke(&self, request: &mut ServerRequest) -> Result<(), SystemException>;
429}
430
431/// A [`DynamicImplementation`] as a [`Servant`].
432#[derive(Debug)]
433pub struct DynamicServant<T>(pub T);
434
435impl<T: DynamicImplementation> Servant for DynamicServant<T> {
436    fn repository_id(&self) -> &str {
437        self.0.primary_interface()
438    }
439
440    fn is_a(&self, repository_id: &str) -> bool {
441        self.0.is_a(repository_id)
442    }
443
444    fn dispatch(
445        &self,
446        operation: &str,
447        input: &mut InStream<'_>,
448        reply: &mut ServerReply,
449    ) -> Result<(), SystemException> {
450        let mut request = ServerRequest::new(operation, input)?;
451        self.0.invoke(&mut request)?;
452        request.write_reply(reply)
453    }
454}
455
456/// `CORBA::ServerRequest`: a request to a [`DynamicImplementation`].
457///
458/// It owns what it needs of the request, so a binding can keep it while it
459/// calls into its language.
460pub struct ServerRequest {
461    operation: String,
462    input: Option<crate::stream::DetachedInput>,
463    arguments: Option<Vec<NamedValue>>,
464    result: Option<Any>,
465    exception: Option<Any>,
466}
467
468impl fmt::Debug for ServerRequest {
469    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
470        f.debug_struct("ServerRequest")
471            .field("operation", &self.operation)
472            .field("arguments", &self.arguments)
473            .field("result", &self.result)
474            .field("exception", &self.exception)
475            .finish_non_exhaustive()
476    }
477}
478
479impl ServerRequest {
480    /// The request for `operation` whose arguments `input` (the stream a
481    /// servant's [`dispatch`](Servant::dispatch) gets, nothing read from it
482    /// yet) holds.
483    pub fn new(operation: &str, input: &InStream<'_>) -> Result<ServerRequest, SystemException> {
484        let input = input
485            .detach()
486            .ok_or_else(|| sys(SystemExceptionKind::INTERNAL, CompletionStatus::No))?;
487        Ok(ServerRequest {
488            operation: operation.to_owned(),
489            input: Some(input),
490            arguments: None,
491            result: None,
492            exception: None,
493        })
494    }
495
496    pub fn operation(&self) -> &str {
497        &self.operation
498    }
499
500    /// Reads the `in` and `inout` arguments into `parameters` (whose
501    /// TypeCodes and modes describe the operation's parameters, in order)
502    /// and keeps them; the servant then sets the `out` and `inout` values
503    /// in the returned slice (or later in
504    /// [`parameters_mut`](ServerRequest::parameters_mut)). Called once:
505    /// again is `BAD_INV_ORDER`. Arguments that do not match the types are
506    /// `MARSHAL`, completed no.
507    pub fn arguments(
508        &mut self,
509        mut parameters: Vec<NamedValue>,
510    ) -> Result<&mut [NamedValue], SystemException> {
511        let Some(input) = self.input.take() else {
512            return Err(bad_inv_order());
513        };
514        {
515            let mut stream = input.stream();
516            for nv in parameters.iter_mut().filter(|nv| nv.mode.is_in()) {
517                let tc = nv.value.typecode().clone();
518                let value = stream.read_value(&tc)?;
519                nv.value = Any::new(tc, value);
520            }
521        }
522        Ok(self.arguments.insert(parameters))
523    }
524
525    /// The parameters given to [`arguments`](ServerRequest::arguments).
526    pub fn parameters_mut(&mut self) -> Option<&mut [NamedValue]> {
527        self.arguments.as_deref_mut()
528    }
529
530    /// Sets the return value (for an operation with a `void` result, an
531    /// Any of type `void`, or none at all). `BAD_INV_ORDER` before
532    /// [`arguments`](ServerRequest::arguments) or after
533    /// [`set_exception`](ServerRequest::set_exception).
534    pub fn set_result(&mut self, value: Any) -> Result<(), SystemException> {
535        if self.arguments.is_none() || self.exception.is_some() {
536            return Err(bad_inv_order());
537        }
538        self.result = Some(value);
539        Ok(())
540    }
541
542    /// Makes the reply the user exception `value` (an Any of a `tk_except`
543    /// TypeCode; another is `BAD_PARAM`). A system exception is returned
544    /// from [`DynamicImplementation::invoke`] instead.
545    pub fn set_exception(&mut self, value: Any) -> Result<(), SystemException> {
546        if value.typecode().unaliased().kind() != TCKind::Except {
547            return Err(sys(SystemExceptionKind::BAD_PARAM, CompletionStatus::No));
548        }
549        self.exception = Some(value);
550        Ok(())
551    }
552
553    /// Writes the reply: the user exception, or the return value and the
554    /// `out` and `inout` arguments in order. A value that does not fit its
555    /// type (an `out` argument left without a value, say) is `BAD_PARAM`.
556    pub fn write_reply(self, reply: &mut ServerReply) -> Result<(), SystemException> {
557        // The server interceptors see what the servant set (the bindings'
558        // DSI servants come here too).
559        if crate::pi::wants_dsi_params() {
560            crate::pi::leave_dsi_params(crate::pi::DsiParams {
561                arguments: self.arguments.clone(),
562                result: self.result.clone(),
563                exception: self.exception.clone(),
564            });
565        }
566        if let Some(exception) = &self.exception {
567            let tc = exception.typecode().unaliased();
568            let id = tc.id().unwrap_or_default().to_owned();
569            let Value::List(members) = exception.value() else {
570                return Err(sys(SystemExceptionKind::BAD_PARAM, CompletionStatus::Maybe));
571            };
572            let mut out = reply.user_exception(&id)?;
573            for (i, member) in members.iter().enumerate() {
574                let member_tc = tc
575                    .member_type(i as u32)
576                    .map_err(|_| sys(SystemExceptionKind::BAD_PARAM, CompletionStatus::Maybe))?;
577                out.write_value(&member_tc, member)?;
578            }
579            return Ok(());
580        }
581        let mut out = reply.output();
582        if let Some(result) = &self.result {
583            out.write_value(result.typecode(), result.value())?;
584        }
585        for nv in self
586            .arguments
587            .iter()
588            .flatten()
589            .filter(|nv| nv.mode.is_out())
590        {
591            out.write_value(nv.value.typecode(), nv.value.value())?;
592        }
593        Ok(())
594    }
595}