kompact 0.12.0

Kompact is a Rust implementation of the Kompics component model combined with the Actor model.
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
use super::*;

use std::{error::Error, fmt};

use crate::runtime::BacktraceSuffix;
use snafu::IntoError;

/// Stable categories for serialisation and deserialisation failures.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SerErrorKind {
    /// The data was invalid, corrupted, or otherwise not as expected.
    InvalidData,
    /// The data represents the wrong type, or an unknown type.
    InvalidType,
    /// The buffer used for serialisation failed.
    Buffer,
    /// No buffer was available.
    ///
    /// Raised by actors attempting to send more messages than their buffers allow
    /// or what the network is able to handle.
    NoBuffersAvailable,
    /// The type can not be cloned.
    NoClone,
    /// An error forwarded from a third-party crate.
    ThirdParty,
    /// Any other kind of serialisation error.
    Unknown,
}

/// Errors that can be thrown during serialisation or deserialisation.
#[derive(Debug, snafu::Snafu)]
pub struct SerError(SerErrorInner);

#[derive(Debug, snafu::Snafu)]
#[snafu(module)]
enum SerErrorInner {
    #[snafu(display(
        "The provided data was not appropriate for (de-)serialisation: {message} ({location}){}",
        BacktraceSuffix(backtrace.as_ref())
    ))]
    InvalidData {
        message: String,
        #[snafu(implicit)]
        location: snafu::Location,
        backtrace: Option<snafu::Backtrace>,
    },
    #[snafu(display(
        "The provided type was not appropriate for (de-)serialisation: {message} ({location}){}",
        BacktraceSuffix(backtrace.as_ref())
    ))]
    InvalidType {
        message: String,
        #[snafu(implicit)]
        location: snafu::Location,
        backtrace: Option<snafu::Backtrace>,
    },
    #[snafu(display(
        "An issue occurred with the serialisation buffers: {message} ({location}){}",
        BacktraceSuffix(backtrace.as_ref())
    ))]
    Buffer {
        message: String,
        #[snafu(implicit)]
        location: snafu::Location,
        backtrace: Option<snafu::Backtrace>,
    },
    #[snafu(display(
        "Serialising into a BufferPool with no available buffers: {message} ({location}){}",
        BacktraceSuffix(backtrace.as_ref())
    ))]
    NoBuffersAvailable {
        message: String,
        #[snafu(implicit)]
        location: snafu::Location,
        backtrace: Option<snafu::Backtrace>,
    },
    #[snafu(display(
        "The provided type can not be cloned, but try_clone() was attempted ({location}){}",
        BacktraceSuffix(backtrace.as_ref())
    ))]
    NoClone {
        #[snafu(implicit)]
        location: snafu::Location,
        backtrace: Option<snafu::Backtrace>,
    },
    #[snafu(display(
        "A serialisation error occurred in a third-party crate while {context}: {source} ({location}){}",
        BacktraceSuffix(backtrace.as_ref())
    ))]
    ThirdParty {
        context: String,
        source: Box<dyn Error + 'static>,
        #[snafu(implicit)]
        location: snafu::Location,
        backtrace: Option<snafu::Backtrace>,
    },
    #[snafu(display(
        "A serialisation error occurred: {message} ({location}){}",
        BacktraceSuffix(backtrace.as_ref())
    ))]
    Unknown {
        message: String,
        #[snafu(implicit)]
        location: snafu::Location,
        backtrace: Option<snafu::Backtrace>,
    },
}

impl SerError {
    /// Return the stable category of this serialisation error.
    pub fn kind(&self) -> SerErrorKind {
        match &self.0 {
            SerErrorInner::InvalidData { .. } => SerErrorKind::InvalidData,
            SerErrorInner::InvalidType { .. } => SerErrorKind::InvalidType,
            SerErrorInner::Buffer { .. } => SerErrorKind::Buffer,
            SerErrorInner::NoBuffersAvailable { .. } => SerErrorKind::NoBuffersAvailable,
            SerErrorInner::NoClone { .. } => SerErrorKind::NoClone,
            SerErrorInner::ThirdParty { .. } => SerErrorKind::ThirdParty,
            SerErrorInner::Unknown { .. } => SerErrorKind::Unknown,
        }
    }

    /// Construct an invalid-data serialisation error.
    #[track_caller]
    pub fn invalid_data(message: impl Into<String>) -> Self {
        ser_error_inner::InvalidDataSnafu {
            message: message.into(),
        }
        .build()
        .into()
    }

    /// Construct an invalid-type serialisation error.
    #[track_caller]
    pub fn invalid_type(message: impl Into<String>) -> Self {
        ser_error_inner::InvalidTypeSnafu {
            message: message.into(),
        }
        .build()
        .into()
    }

    /// Construct a serialisation buffer error.
    #[track_caller]
    pub fn buffer(message: impl Into<String>) -> Self {
        ser_error_inner::BufferSnafu {
            message: message.into(),
        }
        .build()
        .into()
    }

    /// Construct a no-buffers-available serialisation error.
    #[track_caller]
    pub fn no_buffers_available(message: impl Into<String>) -> Self {
        ser_error_inner::NoBuffersAvailableSnafu {
            message: message.into(),
        }
        .build()
        .into()
    }

    /// Construct a no-clone serialisation error.
    #[track_caller]
    pub fn no_clone() -> Self {
        ser_error_inner::NoCloneSnafu.build().into()
    }

    /// Construct a third-party serialisation error.
    #[track_caller]
    pub fn third_party(context: impl Into<String>, source: impl Error + 'static) -> Self {
        let source: Box<dyn Error + 'static> = Box::new(source);
        ser_error_inner::ThirdPartySnafu {
            context: context.into(),
        }
        .into_error(source)
        .into()
    }

    /// Construct an unknown serialisation error.
    #[track_caller]
    pub fn unknown(message: impl Into<String>) -> Self {
        ser_error_inner::UnknownSnafu {
            message: message.into(),
        }
        .build()
        .into()
    }

    /// Create a serialisation error from any kind of error that
    /// implements the [Debug](std::fmt::Debug) trait
    ///
    /// This always produces the [Unknown](SerErrorKind::Unknown) kind.
    #[track_caller]
    pub fn from_debug<E: Debug>(error: E) -> SerError {
        let msg = format!("Wrapped error: {:?}", error);
        SerError::unknown(msg)
    }
}

/// A trait that acts like a stable `TypeId` for serialisation
///
/// Requires ids to be assigned manually in some consistent fashion
/// so they can be reliable compared between in different binaries and rust versions.
///
/// This trait is used with serialisers that can deal with a large number of types
/// but require some internal differentiation, such as [Serde](crate::serialisation::serde_serialisers),
/// for example.
pub trait SerialisationId {
    /// The serialisation id for this type
    const SER_ID: SerId;
}

/// A trait for types that can serialise data of type `T`
pub trait Serialiser<T>: Send + TryClone {
    /// The serialisation id for this serialiser
    ///
    /// Serialisation ids are used to determine the deserialiser to use with a particular byte buffer.
    /// They are prepended to the actual serialised data and read first during deserialisation.
    /// Serialisation ids must be globally unique within a distributed Kompact system.
    fn ser_id(&self) -> SerId;

    /// An indicator how many bytes must be reserved in a buffer for a value to be
    /// serialsed into it with this serialiser
    ///
    /// If the total size is unknown, `None` should be returned.
    ///
    /// Generally, size hints should be cheap to calculate, compared to the actual serialisation,
    /// since they are simply optimisations to avoid many small memory allocations during the serialisation process.
    fn size_hint(&self) -> Option<usize> {
        None
    }

    /// Serialise `v` into `buf`.
    ///
    /// Serialisation should produce a copy, and not consume the original value.
    ///
    /// Returns a [SerError](SerError) if unsuccessful.
    fn serialise(&self, v: &T, buf: &mut dyn BufMut) -> Result<(), SerError>;

    /// Produce a copy of `v`, if possible
    ///
    /// If it can't be done cheaply, simply return `None` (which is the default implementation).
    fn try_clone_data(&self, _v: &T) -> Option<T> {
        None
    }
}

/// A trait for values that can serialise themselves into a buffer
pub trait Serialisable: Send + Debug {
    /// The serialisation id for this serialisable
    ///
    /// Serialisation ids are used to determine the deserialiser to use with a particular byte buffer.
    /// They are prepended to the actual serialised data and read first during deserialisation.
    /// Serialisation ids must be globally unique within a *distributed* Kompact system.
    fn ser_id(&self) -> SerId;

    /// An indicator how many bytes must be reserved in a buffer for a value to be
    /// serialsed into it with this serialiser
    ///
    /// If the total size is unknown, `None` should be returned.
    ///
    /// Generally, size hints should be cheap to calculate, compared to the actual serialisation,
    /// since they are simply optimisations to avoid many small memory allocations during the serialisation process.
    fn size_hint(&self) -> Option<usize>;

    /// Serialises this object (`self`) into `buf`
    ///
    /// Serialisation should produce a copy, and not consume the original value.
    ///
    /// Returns a [SerError](SerError) if unsuccessful.
    fn serialise(&self, buf: &mut dyn BufMut) -> Result<(), SerError>;

    // TODO serialise owned...may need to rename some things here

    /// Try move this object onto the heap for reflection, instead of serialising
    ///
    /// Returns the original object if the move fails, so that it can still be serialised.
    fn local(self: Box<Self>) -> Result<Box<dyn Any + Send>, Box<dyn Serialisable>>;

    /// Serialise with a one-off buffer
    ///
    /// Calls [serialise](Serialisable::serialise) internally by default.
    fn serialised(&self) -> Result<crate::messaging::Serialised, SerError> {
        crate::serialisation::ser_helpers::serialise_to_serialised(self)
    }

    /// Try to produce a cheap in-memory copy of this
    ///
    /// The default implementation returns `None`.
    fn cloned(&self) -> Option<Box<dyn Serialisable>> {
        None
    }
}

/// Turns a pair of a [Serialiser](Serialiser) and value of it's type `T` into a
/// stack-allocated [Serialisable](Serialisable)
impl<T, S> From<(T, S)> for SerialisableValue<T, S>
where
    T: Send + Debug + 'static,
    S: Serialiser<T> + 'static,
{
    fn from(t: (T, S)) -> Self {
        SerialisableValue::from_tuple(t)
    }
}

/// Turns a pair of a [Serialiser](Serialiser) and value of it's type `T` into a
/// heap-allocated [Serialisable](Serialisable)
impl<T, S> From<(T, S)> for Box<dyn Serialisable>
where
    T: Send + Debug + 'static,
    S: Serialiser<T> + 'static,
{
    fn from(t: (T, S)) -> Self {
        let sv: SerialisableValue<T, S> = t.into();
        Box::new(sv) as Box<dyn Serialisable>
    }
}

/// Turns a stack-allocated [Serialisable](Serialisable) into a
/// heap-allocated [Serialisable](Serialisable)
impl<T> From<T> for Box<dyn Serialisable>
where
    T: Send + Debug + Serialisable + Sized + 'static,
{
    fn from(t: T) -> Self {
        Box::new(t) as Box<dyn Serialisable>
    }
}

/// A data type equivalent to a pair of value and a serialiser for it
pub struct SerialisableValue<T, S>
where
    T: Send + Debug,
    S: Serialiser<T>,
{
    /// The value to be serialised
    pub v: T,
    /// The serialise to use
    pub ser: S,
}
impl<T, S> SerialisableValue<T, S>
where
    T: Send + Debug + 'static,
    S: Serialiser<T>,
{
    /// Create a new Serialisable type from a `T` and a `Serialiser` for `T`
    pub fn new(v: T, ser: S) -> Self {
        SerialisableValue { v, ser }
    }

    /// Create a new `Serialisable` type from a pair of `T` and a `Serialiser` for `T`
    pub fn from_tuple(t: (T, S)) -> Self {
        Self::new(t.0, t.1)
    }
}

impl<T, S> Serialisable for SerialisableValue<T, S>
where
    T: Send + Debug + 'static,
    S: Serialiser<T> + 'static,
{
    fn ser_id(&self) -> SerId {
        self.ser.ser_id()
    }

    fn size_hint(&self) -> Option<usize> {
        self.ser.size_hint()
    }

    fn serialise(&self, buf: &mut dyn BufMut) -> Result<(), SerError> {
        self.ser.serialise(&self.v, buf)
    }

    fn local(self: Box<Self>) -> Result<Box<dyn Any + Send>, Box<dyn Serialisable>> {
        let b: Box<dyn Any + Send> = Box::new(self.v);
        Ok(b)
    }

    fn cloned(&self) -> Option<Box<dyn Serialisable>> {
        self.ser.try_clone().ok().and_then(|ser| {
            self.ser.try_clone_data(&self.v).map(|v| {
                let b: Box<dyn Serialisable> = Box::new(SerialisableValue::new(v, ser));
                b
            })
        })
    }
}

impl<T, S> Debug for SerialisableValue<T, S>
where
    T: Send + Debug,
    S: Serialiser<T>,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        write!(
            f,
            "Serialisable(id={:?},size={:?}, value={:?})",
            self.ser.ser_id(),
            self.ser.size_hint(),
            self.v
        )
    }
}

/// A trait to deserialise values of type `T` from buffers
///
/// There should be one deserialiser with the same serialisation id
/// for each [Serialiser](Serialiser) or [Serialisable](Serialisable)
/// implementation. It is recommended to implement both on the same type.
pub trait Deserialiser<T>: Send {
    /// The serialisation id for which this deserialiser is to be invoked
    const SER_ID: SerId;

    /// Try to deserialise a `T` from the given `buf`
    ///
    /// Returns a [SerError](SerError) if unsuccessful.
    fn deserialise(buf: &mut dyn Buf) -> Result<T, SerError>;
}

/// A trait for values that can get deserialised themselves
///
/// Can be used for serialisers that reuse already allocated memory
/// as the target, such as protocol buffers.
pub trait Deserialisable<T> {
    /// The serialisation id for which this deserialiser is to be invoked
    fn ser_id(&self) -> SerId;

    /// Try to deserialise this data into a `T`
    ///
    /// Returns a [SerError](SerError) if unsuccessful.
    fn get_deserialised(self) -> Result<T, SerError>;
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{error::Error, io};

    #[test]
    fn ser_error_reports_stable_kind() {
        let error = SerError::invalid_data("bad payload");

        assert_eq!(SerErrorKind::InvalidData, error.kind());
        assert!(error.to_string().contains("bad payload"));
        assert!(error.to_string().contains("core/src/serialisation/core.rs"));
    }

    #[test]
    fn ser_error_preserves_third_party_source() {
        let source = io::Error::new(io::ErrorKind::InvalidData, "external failure");
        let error = SerError::third_party("test", source);

        assert_eq!(SerErrorKind::ThirdParty, error.kind());
        assert_eq!(
            "external failure",
            error.source().expect("third-party source").to_string()
        );
    }
}