kompact 0.11.3

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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! Message framing (serialization and deserialization into and from byte buffers)

use crate::{
    actors::{ActorPath, NamedPath, SystemField, SystemPath, Transport, UniquePath},
    messaging::bitfields::{BitField, BitFieldExt},
    serialisation::{serialisation_ids, Deserialiser, SerError, SerId, Serialisable},
};
use bytes::{Buf, BufMut};
use std::{any::Any, convert::TryFrom, net::IpAddr};
use uuid::Uuid;

/// The type of address used
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum AddressType {
    /// An IPv4 address
    IPv4 = 0,
    /// An IPv6 address
    IPv6 = 1,
    /// A domain name
    Domain = 2,
}

/// The type of path used
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum PathType {
    /// A [unique path](ActorPath::Unique)
    Unique = 0,
    /// A [named path](ActorPath::Named)
    Named = 1,
}

impl BitField for AddressType {
    const POS: usize = 2;
    const WIDTH: usize = 2;
}

impl BitField for PathType {
    const POS: usize = 7;
    const WIDTH: usize = 1;
}

impl BitField for Transport {
    const POS: usize = 0;
    const WIDTH: usize = 5;
}

// other direction is try_from
#[allow(clippy::from_over_into)]
impl Into<u8> for AddressType {
    fn into(self) -> u8 {
        self as u8
    }
}

// other direction is try_from
#[allow(clippy::from_over_into)]
impl Into<u8> for PathType {
    fn into(self) -> u8 {
        self as u8
    }
}

// other direction is try_from
#[allow(clippy::from_over_into)]
impl Into<u8> for Transport {
    fn into(self) -> u8 {
        self as u8
    }
}

impl TryFrom<u8> for AddressType {
    type Error = SerError;

    fn try_from(x: u8) -> Result<Self, Self::Error> {
        match x {
            x if x == AddressType::IPv4 as u8 => Ok(AddressType::IPv4),
            x if x == AddressType::IPv6 as u8 => Ok(AddressType::IPv6),
            _ => Err(SerError::InvalidType("Unsupported AddressType".into())),
        }
    }
}

impl TryFrom<u8> for PathType {
    type Error = SerError;

    fn try_from(x: u8) -> Result<Self, Self::Error> {
        match x {
            x if x == PathType::Unique as u8 => Ok(PathType::Unique),
            x if x == PathType::Named as u8 => Ok(PathType::Named),
            _ => Err(SerError::InvalidType("Unsupported PathType".into())),
        }
    }
}

impl TryFrom<u8> for Transport {
    type Error = SerError;

    fn try_from(x: u8) -> Result<Self, Self::Error> {
        match x {
            x if x == Transport::Local as u8 => Ok(Transport::Local),
            x if x == Transport::Udp as u8 => Ok(Transport::Udp),
            x if x == Transport::Tcp as u8 => Ok(Transport::Tcp),
            _ => Err(SerError::InvalidType(
                "Unsupported transport protocol".into(),
            )),
        }
    }
}

impl<'a> From<&'a IpAddr> for AddressType {
    fn from(addr: &'a IpAddr) -> Self {
        match addr {
            IpAddr::V4(_) => AddressType::IPv4,
            IpAddr::V6(_) => AddressType::IPv6,
        }
    }
}

/// The header for a [system path](SystemPath)
#[derive(Debug)]
pub struct SystemPathHeader {
    storage: [u8; 1],
    pub(crate) path_type: PathType,
    pub(crate) protocol: Transport,
    pub(crate) address_type: AddressType,
}

impl SystemPathHeader {
    /// Create header from an actor path
    pub fn from_path(sys: &ActorPath) -> Self {
        let path_type = match sys {
            ActorPath::Unique(_) => PathType::Unique,
            ActorPath::Named(_) => PathType::Named,
        };
        let address_type: AddressType = sys.address().into();

        let mut storage = [0u8];
        storage
            .store(path_type)
            .expect("path_type could not be stored");
        storage
            .store(sys.protocol())
            .expect("protocol could not be stored");
        storage
            .store(address_type)
            .expect("address could not be stored");

        SystemPathHeader {
            storage,
            path_type,
            protocol: sys.protocol(),
            address_type: sys.address().into(),
        }
    }

    /// Create header from a system path
    pub fn from_system(sys: &SystemPath) -> Self {
        let path_type = PathType::Unique; // doesn't matter, will be ignored anyway
        let address_type: AddressType = sys.address().into();

        let mut storage = [0u8];
        storage
            .store(path_type)
            .expect("path_type could not be stored");
        storage
            .store(sys.protocol())
            .expect("protocol could not be stored");
        storage
            .store(address_type)
            .expect("address could not be stored");

        SystemPathHeader {
            storage,
            path_type,
            protocol: sys.protocol(),
            address_type: sys.address().into(),
        }
    }

    /// Put this header's data into the give buffer
    pub fn put_into(&self, buf: &mut dyn BufMut) {
        buf.put_u8(self.storage[0])
    }
}

impl TryFrom<u8> for SystemPathHeader {
    type Error = SerError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        let storage = [value];
        let path_type = storage
            .get_as::<PathType>()
            .map_err(|_| SerError::InvalidData("System Path could not be read.".to_owned()))?;
        let protocol = storage.get_as::<Transport>().map_err(|_| {
            SerError::InvalidData("System Path Transport could not be read.".to_owned())
        })?;
        let address_type = storage.get_as::<AddressType>().map_err(|_| {
            SerError::InvalidData("System Path AddressType could not be read.".to_owned())
        })?;

        let header = SystemPathHeader {
            storage,
            path_type,
            protocol,
            address_type,
        };
        Ok(header)
    }
}

/// # Actor Path Serialization
/// An actor path is either Unique or Named and contains a [SystemPath].
/// The SystemPath's header disambiguates the type (Path type).
///
/// # Unique Actor Paths
///  ```text
/// +---------------------------+
/// | System path (*)         ...
/// +---------------+-----------+
/// |      UUID (16 bytes)      |
/// +---------------------------+
/// ```
/// # Named Actor Paths
/// ```text
/// +---------------------------+
/// | System path (*)         ...
/// +---------------+-----------+-------------------------------+
/// |      Named path (2 bytes prefix + variable length)      ...
/// +-----------------------------------------------------------+
/// ```
///
/// # System Paths
/// ```text
/// +-------------------+-------------------+-----------------------+
/// | Path type (1 bit) | Protocol (5 bits) | Address Type (2 bits) |
/// +-------------------+-------------------+-----------------------+----------------+
/// |                   Address (4/16/ * bytes)                  ...| Port (2 bytes) |
/// +---------------------------------------------------------------+----------------+
/// ```
impl Serialisable for SystemPath {
    fn ser_id(&self) -> SerId {
        serialisation_ids::SYSTEM_PATH
    }

    fn size_hint(&self) -> Option<usize> {
        let mut size: usize = 0;
        size += 1; // header
        size += match self.address() {
            IpAddr::V4(_) => 4,  // IPv4 uses 4 bytes
            IpAddr::V6(_) => 16, // IPv4 uses 16 bytes
        };
        size += 2; // port # (0-65_535)
        Some(size)
    }

    fn serialise(&self, buf: &mut dyn BufMut) -> Result<(), SerError> {
        let header = SystemPathHeader::from_system(self);
        header.put_into(buf);

        system_path_put_into_buf(self, buf);

        Ok(())
    }

    fn local(self: Box<Self>) -> Result<Box<dyn Any + Send>, Box<dyn Serialisable>> {
        unimplemented!()
    }
}

#[inline(always)]
fn system_path_put_into_buf(path: &SystemPath, buf: &mut dyn BufMut) -> () {
    match *path.address() {
        IpAddr::V4(ref ip) => buf.put_slice(&ip.octets()),
        IpAddr::V6(ref ip) => buf.put_slice(&ip.octets()),
        // TODO support named Domain
    }
    buf.put_u16(path.port());
}
#[inline(always)]
fn system_path_from_buf(buf: &mut dyn Buf) -> Result<(SystemPathHeader, SystemPath), SerError> {
    // Deserialize system path
    let fields: u8 = buf.get_u8();
    let header = SystemPathHeader::try_from(fields)?;
    let address: IpAddr = match header.address_type {
        AddressType::IPv4 => {
            if buf.remaining() < 4 {
                return Err(SerError::InvalidData(
                    "Could not parse 4 bytes for IPv4 address".into(),
                ));
            } else {
                let mut ip_bytes = [0u8; 4];
                buf.copy_to_slice(&mut ip_bytes);
                IpAddr::from(ip_bytes)
            }
        }
        AddressType::IPv6 => {
            if buf.remaining() < 16 {
                return Err(SerError::InvalidData(
                    "Could not parse 16 bytes for IPv6 address".into(),
                ));
            } else {
                let mut ip_bytes = [0u8; 16];
                buf.copy_to_slice(&mut ip_bytes);
                IpAddr::from(ip_bytes)
            }
        }
        AddressType::Domain => {
            unimplemented!();
        }
    };
    let port = buf.get_u16();
    let system_path = SystemPath::new(header.protocol, address, port);
    Ok((header, system_path))
}

impl Deserialiser<SystemPath> for SystemPath {
    const SER_ID: SerId = serialisation_ids::SYSTEM_PATH;

    fn deserialise(buf: &mut dyn Buf) -> Result<SystemPath, SerError> {
        system_path_from_buf(buf).map(|t| t.1)
    }
}

impl Serialisable for ActorPath {
    fn ser_id(&self) -> SerId {
        serialisation_ids::ACTOR_PATH
    }

    // Returns the total size for this actor path, including system path information.
    // Returns `None` if `ActorPath::Named` and the name overflows the designated 2 bytes.
    fn size_hint(&self) -> Option<usize> {
        let mut size: usize = 0;
        size += self.system().size_hint()?; // def. returns Some

        size += match *self {
            ActorPath::Unique(_) => {
                // UUIDs are 16 bytes long (see [UuidBytes])
                16
            }
            ActorPath::Named(ref np) => {
                // Named paths are length-prefixed (2 bytes)
                // followed by variable-length name
                let path_len: u16 = 2;
                // Use 5 bytes per segment as base heuristic.
                // This is much cheaper than calculating the actual length there.
                let name_len = np.path_ref().len() * 5;
                let name_len = u16::try_from(name_len).ok()?;
                path_len.checked_add(name_len)? as usize
            }
        };
        Some(size)
    }

    /// Serializes a Unique or Named actor path.
    fn serialise(&self, buf: &mut dyn BufMut) -> Result<(), SerError> {
        // System Path
        let header = SystemPathHeader::from_path(self);
        header.put_into(buf);
        system_path_put_into_buf(self.system(), buf);

        // Actor Path
        match self {
            ActorPath::Unique(up) => {
                let uuid = up.id();
                buf.put_slice(uuid.as_bytes())
            }
            ActorPath::Named(np) => {
                let path = np.path_ref().join("/");
                let data = path.as_bytes();
                let name_len: u16 = u16::try_from(data.len()).map_err(|_| {
                    SerError::InvalidData("Named path overflows designated 2 bytes length.".into())
                })?;
                buf.put_u16(name_len);
                buf.put_slice(data);
            }
        }
        Ok(())
    }

    fn local(self: Box<Self>) -> Result<Box<dyn Any + Send>, Box<dyn Serialisable>> {
        Ok(self)
    }
}
impl Deserialiser<ActorPath> for ActorPath {
    const SER_ID: SerId = serialisation_ids::ACTOR_PATH;

    fn deserialise(buf: &mut dyn Buf) -> Result<ActorPath, SerError> {
        let (header, system_path) = system_path_from_buf(buf)?;

        let path = match header.path_type {
            PathType::Unique => {
                if buf.remaining() < 16 {
                    return Err(SerError::InvalidData(
                        "Could not get 16 bytes for UUID".into(),
                    ));
                } else {
                    let mut uuid_bytes = [0u8; 16];
                    buf.copy_to_slice(&mut uuid_bytes);
                    let uuid = Uuid::from_bytes(uuid_bytes);
                    ActorPath::Unique(UniquePath::with_system(system_path, uuid))
                }
            }
            PathType::Named => {
                let name_len = buf.get_u16() as usize;
                if buf.remaining() < name_len {
                    return Err(SerError::InvalidData(format!(
                        "Could not get {} bytes for path name",
                        name_len
                    )));
                } else {
                    let mut name_bytes = vec![0u8; name_len];
                    buf.copy_to_slice(&mut name_bytes);
                    let name = unsafe {
                        // since we serialised it ourselves, this should be fine
                        String::from_utf8_unchecked(name_bytes)
                    };
                    let parts: Vec<&str> = name.split('/').collect();
                    if parts.is_empty() {
                        return Err(SerError::InvalidData(
                            "Could not determine name for Named path type".into(),
                        ));
                    } else {
                        let path = parts.into_iter().map(|s| s.to_string()).collect();
                        ActorPath::Named(NamedPath::with_system(system_path, path))
                    }
                }
            }
        };
        Ok(path)
    }
}

#[cfg(test)]
mod serialisation_tests {
    use super::*;
    use crate::actors::SystemField;
    use bytes::BytesMut; //IntoBuf

    #[test]
    fn system_path_serequiv() {
        use super::{PathType, SystemPathHeader};
        use crate::{
            actors::{ActorPath, NamedPath, SystemPath, Transport},
            messaging::framing::AddressType,
        };

        let system_path = SystemPath::new(Transport::Tcp, "127.0.0.1".parse().unwrap(), 8080u16);
        let named_path = ActorPath::Named(NamedPath::with_system(
            system_path.clone(),
            vec!["actor-name".into()],
        ));
        let unique_path =
            ActorPath::Unique(UniquePath::with_system(system_path.clone(), Uuid::new_v4()));
        {
            let header = SystemPathHeader::from_path(&named_path);
            assert_eq!(header.path_type, PathType::Named);
            assert_eq!(header.protocol, Transport::Tcp);
            assert_eq!(header.address_type, AddressType::IPv4);
        }
        {
            let header = SystemPathHeader::from_path(&unique_path);
            assert_eq!(header.path_type, PathType::Unique);
            assert_eq!(header.protocol, Transport::Tcp);
            assert_eq!(header.address_type, AddressType::IPv4);
        }

        let mut buf = BytesMut::with_capacity(system_path.size_hint().unwrap());
        system_path
            .serialise(&mut buf)
            .expect("SystemPath should serialise!");

        //let mut buf = buf.into();
        let deserialised =
            SystemPath::deserialise(&mut buf).expect("SystemPath should deserialise!");

        assert_eq!(system_path, deserialised);
    }

    #[test]
    fn actor_path_serequiv() {
        let expected_transport: Transport = Transport::Tcp;
        let expected_addr: IpAddr = "12.0.0.1".parse().unwrap();
        let unique_id: Uuid = Uuid::new_v4();
        let port: u16 = 1234;

        let unique_path = ActorPath::Unique(UniquePath::new(
            expected_transport,
            expected_addr,
            port,
            unique_id,
        ));

        let name: Vec<String> = vec!["test", "me", "please"]
            .into_iter()
            .map(|s| s.to_string())
            .collect();
        let named_path = ActorPath::Named(NamedPath::new(
            expected_transport,
            expected_addr,
            port,
            name.clone(),
        ));

        // unique paths
        {
            let size = Serialisable::size_hint(&unique_path).expect("Paths should have size hints");
            let mut buf = BytesMut::with_capacity(size);
            Serialisable::serialise(&unique_path, &mut buf)
                .expect("UUID ActorPath Serialisation should succeed");

            // Deserialise
            //let mut buf: Buf = buf.into();
            let deser_path = ActorPath::deserialise(&mut buf)
                .expect("UUID ActorPath Deserialisation should succeed");
            assert_eq!(buf.len(), 0);
            let deser_sys: &SystemPath = SystemField::system(&deser_path);
            assert_eq!(deser_sys.address(), &expected_addr);
            match deser_path {
                ActorPath::Unique(ref up) => {
                    assert_eq!(up.id(), unique_id);
                }
                ActorPath::Named(_) => panic!("expected Unique path, got Named path"),
            }
        }

        // named paths
        {
            let size = Serialisable::size_hint(&named_path).expect("Paths should have size hints");
            let mut buf = BytesMut::with_capacity(size);
            Serialisable::serialise(&named_path, &mut buf)
                .expect("Named ActorPath Serialisation should succeed");

            // Deserialise
            let mut buf = buf.copy_to_bytes(buf.remaining());
            let deser_path = ActorPath::deserialise(&mut buf)
                .expect("Named ActorPath Deserialisation should succeed");
            assert_eq!(buf.len(), 0);
            let deser_sys: &SystemPath = SystemField::system(&deser_path);
            assert_eq!(deser_sys.address(), &expected_addr);
            match deser_path {
                ActorPath::Unique(_) => panic!("expected Named path, got Unique path"),
                ActorPath::Named(ref np) => {
                    assert_eq!(np.path_ref(), name.as_slice());
                }
            }
        }
    }
}