rustorb-core 0.1.1

ORB core of rustorb: connections, request dispatch and POA
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Valuetypes and value boxes of generated code.
//!
//! A valuetype instance is shared: a [`ValueHandle`] is a reference to it,
//! and the handles the generator makes for each valuetype wrap one. The
//! state is a generated struct ([`ValueState`]) behind a mutex. An instance
//! written twice in a message is sent once and then as an indirection, and
//! is read back as one instance; instances may refer to each other in
//! cycles, which keep them alive until the cycle is broken.

use std::any::{Any, TypeId};
use std::borrow::Borrow;
use std::collections::BTreeMap;
use std::fmt;
use std::sync::{Arc, Mutex, MutexGuard, RwLock};

use rustorb_cdr::ValueHeader;

use super::{IdlType, Sys};
use crate::{InStream, OutStream, TypeCode};

/// What the generated code tells the runtime about a valuetype.
#[derive(Debug)]
pub struct ValueInfo {
    /// The repository id.
    pub id: &'static str,
    /// The repository ids a value is sent with: its own, then those of
    /// the base types it is truncatable to. A value with more than one is
    /// sent chunked.
    pub sent_ids: &'static [&'static str],
    /// The repository ids of the type and of all its concrete base types:
    /// where a value of this type may stand.
    pub ancestors: &'static [&'static str],
    /// Whether the type is custom marshaled: its state is written by
    /// [`CustomMarshal`], and is always chunked.
    pub custom: bool,
    /// Makes an instance with the default state, which is then read.
    pub make: fn() -> ValueHandle,
    /// The TypeCode.
    pub type_code: fn() -> TypeCode,
}

/// The state of a valuetype instance: the struct the generator makes for
/// each valuetype, with the state of its base type as a member.
pub trait ValueState: Send + 'static {
    /// The type of the instance.
    fn info(&self) -> &'static ValueInfo;
    /// Writes the state members, those of the base types first.
    fn write_state(&self, out: &mut OutStream<'_>) -> Sys<()>;
    /// Reads the state members, those of the base types first.
    fn read_state(&mut self, input: &mut InStream<'_>) -> Sys<()>;
    /// The state of the type `ty` (this type or a base type) in this one.
    fn view(&self, ty: TypeId) -> Option<&dyn Any>;
    /// The same, to change.
    fn view_mut(&mut self, ty: TypeId) -> Option<&mut dyn Any>;
}

struct ValueObj<S: ?Sized> {
    info: &'static ValueInfo,
    state: Mutex<S>,
}

/// A shared reference to a valuetype instance.
#[derive(Clone)]
pub struct ValueHandle(Arc<ValueObj<dyn ValueState>>);

impl fmt::Debug for ValueHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Not the state, which may refer back to this instance.
        write!(f, "ValueHandle({} @ {:#x})", self.0.info.id, self.key())
    }
}

impl ValueHandle {
    /// A new instance with the state `state`.
    pub fn new<S: ValueState>(state: S) -> ValueHandle {
        let info = state.info();
        let obj: Arc<ValueObj<dyn ValueState>> = Arc::new(ValueObj {
            info,
            state: Mutex::new(state),
        });
        ValueHandle(obj)
    }

    /// The type of the instance.
    pub fn info(&self) -> &'static ValueInfo {
        self.0.info
    }

    /// Whether the instance is of the valuetype `id` or of a type derived
    /// from it.
    pub fn is_a(&self, id: &str) -> bool {
        self.0.info.ancestors.contains(&id)
    }

    /// Whether both are the same instance.
    pub fn ptr_eq(&self, other: &ValueHandle) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }

    /// A number that identifies the instance while it is alive.
    pub fn key(&self) -> u64 {
        Arc::as_ptr(&self.0) as *const () as usize as u64
    }

    fn lock(&self) -> MutexGuard<'_, dyn ValueState> {
        self.0.state.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Runs `f` on the state `S` of the instance (its own, or that of a
    /// base type). Panics if the instance has no state `S`, which the
    /// generated handles rule out. Touching the same instance in `f`
    /// deadlocks.
    pub fn with<S: 'static, R>(&self, f: impl FnOnce(&S) -> R) -> R {
        let guard = self.lock();
        let state = guard
            .view(TypeId::of::<S>())
            .and_then(|s| s.downcast_ref::<S>())
            .expect("the state of a base type");
        f(state)
    }

    /// Runs `f` on the state `S` of the instance, to change it.
    pub fn with_mut<S: 'static, R>(&self, f: impl FnOnce(&mut S) -> R) -> R {
        let mut guard = self.lock();
        let state = guard
            .view_mut(TypeId::of::<S>())
            .and_then(|s| s.downcast_mut::<S>())
            .expect("the state of a base type");
        f(state)
    }

    /// Writes `v`, or `null`.
    pub fn write(v: Option<&ValueHandle>, out: &mut OutStream<'_>) -> Sys<()> {
        let Some(v) = v else {
            out.write_null_value();
            return Ok(());
        };
        let ids = v.0.info.sent_ids;
        // The key is checked before the state is locked, so that an
        // instance that refers to itself is written as an indirection.
        if !out.begin_value(v.key(), ids, ids.len() > 1 || v.0.info.custom)? {
            return Ok(());
        }
        v.lock().write_state(out)?;
        out.end_value()?;
        Ok(())
    }

    /// Reads a value where one of the valuetype `expected` (or `null`) is.
    ///
    /// A value is read as the first of the types it was sent with that is
    /// `expected` or a type registered with [`register_value`] derived
    /// from it, and is `MARSHAL` if there is none.
    pub fn read(
        input: &mut InStream<'_>,
        expected: &'static ValueInfo,
    ) -> Sys<Option<ValueHandle>> {
        let e = input.marshal_error();
        let header = input.read_value_header().map_err(|_| e.clone())?;
        let (slot, ids) = match header {
            ValueHeader::Null => return Ok(None),
            ValueHeader::Indirection(slot) => {
                let v = input
                    .typed_values
                    .get(slot)
                    .and_then(|v| v.as_ref())
                    .and_then(|v| v.downcast_ref::<ValueHandle>())
                    .filter(|v| v.is_a(expected.id))
                    .ok_or(e)?;
                return Ok(Some(v.clone()));
            }
            ValueHeader::Value { slot, ids, .. } => (slot, ids),
        };
        let info = if ids.is_empty() {
            expected
        } else {
            ids.iter()
                .find_map(|id| {
                    if id == expected.id {
                        Some(expected)
                    } else {
                        lookup(id).filter(|i| i.ancestors.contains(&expected.id))
                    }
                })
                .ok_or_else(|| e.clone())?
        };
        let v = (info.make)();
        set_slot(input, slot, Box::new(v.clone()));
        v.lock().read_state(input)?;
        input.end_value().map_err(|_| e)?;
        Ok(Some(v))
    }
}

fn set_slot(input: &mut InStream<'_>, slot: usize, v: Box<dyn Any>) {
    if input.typed_values.len() <= slot {
        input.typed_values.resize_with(slot + 1, || None);
    }
    input.typed_values[slot] = Some(v);
}

/// The valuetypes known to the readers of generated code, by repository
/// id.
static VALUES: RwLock<BTreeMap<&'static str, &'static ValueInfo>> = RwLock::new(BTreeMap::new());

/// Makes the valuetype `info` known to every ORB of the process, so that
/// a value of it is read as itself where a base type of it is expected
/// (rather than truncated). Its TypeCode is registered for anys as well
/// ([`crate::register_value_type`]). Generated files have a
/// `register_value_types` function that registers all of theirs.
pub fn register_value(info: &'static ValueInfo) {
    VALUES
        .write()
        .unwrap_or_else(|e| e.into_inner())
        .insert(info.id, info);
    crate::register_value_type(&(info.type_code)());
    if info.custom {
        crate::register_custom_reader(
            info.id,
            Arc::new(move |r, input| custom_reader(info, r, input)),
        );
    }
}

/// How the core reads the state of the custom valuetype `info` into an
/// Any: an instance runs its `unmarshal`, and the items it reads (through
/// [`DataInputStream`]) are the state of the core's instance `r`, which is
/// written from them. The instance itself is dropped: extracting the
/// value from the Any reads it again.
fn custom_reader(
    info: &'static ValueInfo,
    r: &crate::ValueRef,
    input: &mut InStream<'_>,
) -> Sys<()> {
    let v = (info.make)();
    let outer = input.custom_items.replace(Vec::new());
    let result = v.lock().read_state(input);
    let items = std::mem::replace(&mut input.custom_items, outer).unwrap_or_default();
    result?;
    r.set_members(items);
    Ok(())
}

fn lookup(id: &str) -> Option<&'static ValueInfo> {
    VALUES
        .read()
        .unwrap_or_else(|e| e.into_inner())
        .get(id)
        .copied()
}

/// Writes the value box `v` of the type `id`, holding a `T`, or `null`.
pub fn write_box<T: IdlType>(
    v: Option<&Arc<T::Rust>>,
    id: &str,
    out: &mut OutStream<'_>,
) -> Sys<()> {
    let Some(v) = v else {
        out.write_null_value();
        return Ok(());
    };
    let key = Arc::as_ptr(v) as *const () as usize as u64;
    if !out.begin_value(key, &[id], false)? {
        return Ok(());
    }
    T::write(v.as_ref().borrow(), out)?;
    out.end_value()?;
    Ok(())
}

/// Reads a value box of the type `id`, holding a `T`, or `null`.
pub fn read_box<T: IdlType>(input: &mut InStream<'_>, id: &str) -> Sys<Option<Arc<T::Rust>>> {
    let e = input.marshal_error();
    let header = input.read_value_header().map_err(|_| e.clone())?;
    match header {
        ValueHeader::Null => Ok(None),
        ValueHeader::Indirection(slot) => input
            .typed_values
            .get(slot)
            .and_then(|v| v.as_ref())
            .and_then(|v| v.downcast_ref::<Arc<T::Rust>>())
            .cloned()
            .map(Some)
            .ok_or(e),
        ValueHeader::Value { slot, ids, .. } => {
            if ids.first().is_some_and(|i| i != id) {
                return Err(e);
            }
            let v = Arc::new(T::read(input)?);
            set_slot(input, slot, Box::new(v.clone()));
            input.end_value().map_err(|_| e)?;
            Ok(Some(v))
        }
    }
}

/// The marshaling of a custom valuetype (`CORBA::CustomMarshal`), which
/// the application implements for the state struct the generator makes
/// for it: the generated code calls it to write and read the state.
///
/// ```ignore
/// impl CustomMarshal for BlobState {
///     fn marshal(&self, os: &mut DataOutputStream<'_, '_>) -> Sys<()> {
///         os.write::<Long>(&self.n)?;
///         os.write::<Point>(&self.pt)
///     }
///     fn unmarshal(&mut self, is: &mut DataInputStream<'_, '_>) -> Sys<()> {
///         self.n = is.read::<Long>()?;
///         self.pt = is.read::<Point>()?;
///         Ok(())
///     }
/// }
/// ```
pub trait CustomMarshal {
    /// Writes the state.
    fn marshal(&self, os: &mut DataOutputStream<'_, '_>) -> Sys<()>;
    /// Reads the state, in the order [`CustomMarshal::marshal`] writes it.
    fn unmarshal(&mut self, is: &mut DataInputStream<'_, '_>) -> Sys<()>;
}

/// What a custom valuetype writes its state to (`CORBA::DataOutputStream`):
/// items of IDL types, each written as CDR. Valuetypes written keep their
/// sharing with the rest of the message.
#[derive(Debug)]
pub struct DataOutputStream<'s, 'a> {
    out: &'s mut OutStream<'a>,
}

impl<'s, 'a> DataOutputStream<'s, 'a> {
    /// A stream over `out`, for generated code.
    pub fn new(out: &'s mut OutStream<'a>) -> Self {
        DataOutputStream { out }
    }

    /// Writes a value of the IDL type `T` (`write_long` is
    /// `write::<Long>`, `write_Value` of a `Point` is `write::<Point>`).
    pub fn write<T: IdlType>(&mut self, v: &T::Borrowed) -> Sys<()> {
        T::write(v, self.out)
    }

    /// Writes the elements of `items`, without a length
    /// (`write_long_array(seq, offset, length)` is
    /// `write_array::<Long>(&seq[offset..offset + length])`).
    pub fn write_array<T: IdlType>(&mut self, items: &[T::Rust]) -> Sys<()> {
        T::write_items(items, self.out)
    }

    /// The stream, for what the methods above do not cover.
    pub fn stream(&mut self) -> &mut OutStream<'a> {
        self.out
    }
}

/// What a custom valuetype reads its state from (`CORBA::DataInputStream`).
#[derive(Debug)]
pub struct DataInputStream<'s, 'a> {
    input: &'s mut InStream<'a>,
}

impl<'s, 'a> DataInputStream<'s, 'a> {
    /// A stream over `input`, for generated code.
    pub fn new(input: &'s mut InStream<'a>) -> Self {
        DataInputStream { input }
    }

    /// Reads a value of the IDL type `T`.
    pub fn read<T: IdlType>(&mut self) -> Sys<T::Rust> {
        if self.input.custom_items.is_none() {
            return T::read(self.input);
        }
        // The core reads the value into an Any (see `custom_reader`): the
        // item is kept, as the state of the core's instance, and given to
        // `unmarshal` converted.
        let e = self.input.marshal_error();
        let tc = T::type_code();
        let value = self.input.read_value(&tc)?;
        let item = crate::Any::new(tc, value);
        let v = item.extract::<T>().ok_or_else(|| e.clone())?;
        self.input
            .custom_items
            .as_mut()
            .ok_or(e)?
            .push(crate::Value::Any(Box::new(item)));
        Ok(v)
    }

    /// Reads `len` elements of the IDL type `T`, written without a length.
    pub fn read_array<T: IdlType>(&mut self, len: usize) -> Sys<Vec<T::Rust>> {
        let e = self.input.marshal_error();
        if len.saturating_mul(T::MIN_SIZE) > self.input.remaining() {
            return Err(e);
        }
        if self.input.custom_items.is_none() {
            return T::read_items(len, self.input);
        }
        (0..len).map(|_| self.read::<T>()).collect()
    }

    /// The stream, for what the methods above do not cover.
    pub fn stream(&mut self) -> &mut InStream<'a> {
        self.input
    }
}