lightyear 0.3.0

Server-client networking library for the Bevy game engine
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
use std::collections::{BTreeMap, HashMap};

use bitcode::encoding::{Fixed, Gamma};

use crate::netcode::MAX_PACKET_SIZE;
use crate::packet::header::PacketHeader;
use crate::packet::message::{FragmentData, MessageAck, MessageContainer, SingleData};
use crate::packet::packet_type::PacketType;
use crate::protocol::channel::ChannelId;
use crate::protocol::registry::NetId;
use crate::protocol::BitSerializable;
use crate::serialize::reader::ReadBuffer;
use crate::serialize::writer::WriteBuffer;
use crate::utils::wrapping_id::wrapping_id;

// Internal id that we assign to each packet sent over the network
wrapping_id!(PacketId);

/// Maximum number of bytes to write the header
/// PacketType: 2 bits
/// Rest: 10 bytes
const HEADER_BYTES: usize = 11;
/// The maximum of bytes that the payload of the packet can contain (excluding the header)
/// remove 1 byte for byte alignment at the end
pub(crate) const MTU_PAYLOAD_BYTES: usize = MAX_PACKET_SIZE - HEADER_BYTES - 1;

/// The maximum number of bytes for a message before it is fragmented
/// The final size of the fragmented packet (channel_id: 2, fragment_id: 1, message_id: 2, num_fragments: 1, number of bytes in fragment: 2)
/// must be lower than MTU_PAYLOAD_BYTES
pub(crate) const FRAGMENT_SIZE: usize = MTU_PAYLOAD_BYTES - 8;

// TODO: we don't need SinglePacket vs FragmentPacket; we can just re-use the same thing
//  because MessageContainer already has the information about whether it is a fragment or not
//  we just have an underlying assumption that in a fragment packet, the first message will be a fragment message,
//  and all others will be normal messages
//  The reason we do this is we dont want to pay 1 bit on every message to know if it's fragmented or not

// pub(crate) struct Packet<const C: usize = MTU_PACKET_BYTES> {
//     pub(crate) data: BTreeMap<NetId, Vec<MessageContainer>>
// }

/// Single individual packet sent over the network
/// Contains multiple small messages
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct SinglePacket {
    pub(crate) data: BTreeMap<NetId, Vec<SingleData>>,
    // num_bits: usize,
}

impl SinglePacket {
    pub(crate) fn new() -> Self {
        Self {
            data: Default::default(),
            // TODO: maybe this should include the header? maybe the header size depends on packet type, so that
            //  normal packets use only 1 bit for the packet type, as an optimization like naia
            // num_bits: 0,
        }
    }

    pub fn add_channel(&mut self, channel: NetId) {
        self.data.entry(channel).or_default();
        // match self.data.entry(channel) {
        //     Entry::Vacant(_) => {}
        //     Entry::Occupied(entry) => {
        //         entry.insert(Vec::new());
        //         // how many bits does the channel id take?
        //         // u16::encode()
        //
        //         // is this approach possible? we need to know what we align.
        //         // do we byte-align every SingleData, it is easier? so that we can copy Bytes more easily?
        //         // self.num_bits += 1;
        //     }
        // }
    }

    pub fn add_message(&mut self, channel: NetId, message: SingleData) {
        self.data.entry(channel).or_default().push(message);
    }

    /// Return the list of message ids in the packet
    pub fn message_acks(&self) -> HashMap<NetId, Vec<MessageAck>> {
        self.data
            .iter()
            .map(|(&net_id, messages)| {
                let message_acks: Vec<MessageAck> = messages
                    .iter()
                    .filter(|message| message.id.is_some())
                    .map(|message| MessageAck {
                        message_id: message.id.unwrap(),
                        fragment_id: None,
                    })
                    .collect();
                (net_id, message_acks)
            })
            .collect()
    }

    // TODO: this should not be public
    // #[cfg(test)]
    pub(crate) fn num_messages(&self) -> usize {
        self.data.values().map(|messages| messages.len()).sum()
    }
}

impl BitSerializable for SinglePacket {
    /// An expectation of the encoding is that we always have at least one channel that we can encode per packet.
    /// However, some channels might not have any messages (for example if we start writing the channel at the very end of the packet)
    fn encode(&self, writer: &mut impl WriteBuffer) -> anyhow::Result<()> {
        self.data
            .iter()
            .enumerate()
            .map(|(i, v)| (i == self.data.len() - 1, v))
            .try_for_each(|(is_last_channel, (channel_id, messages))| {
                writer.encode(channel_id, Gamma)?;

                // initial continue bit for messages (are there messages for this channel or not?)
                writer.serialize(&!messages.is_empty())?;
                messages
                    .iter()
                    .enumerate()
                    .map(|(j, w)| (j == messages.len() - 1, w))
                    .try_for_each(|(is_last_message, message)| {
                        message.encode(writer)?;
                        // write message continue bit (1 if there is another message to writer after)
                        writer.serialize(&!is_last_message)?;
                        Ok::<(), anyhow::Error>(())
                    })?;
                // write channel continue bit (1 if there is another channel to writer after)
                writer.serialize(&!is_last_channel)?;
                Ok::<(), anyhow::Error>(())
            })
    }

    fn decode(reader: &mut impl ReadBuffer) -> anyhow::Result<Self>
    where
        Self: Sized,
    {
        let mut data = BTreeMap::new();
        let mut continue_read_channel = true;

        // check channel continue bit to see if there are more channels
        while continue_read_channel {
            let channel_id = reader.decode::<NetId>(Gamma)?;
            let mut messages = Vec::new();

            // are there messages for this channel?
            let mut continue_read_message = reader.deserialize::<bool>()?;
            // check message continue bit to see if there are more messages
            while continue_read_message {
                // TODO: we use decode here because we write Bytes directly (we already serialized from the object to Bytes)
                //  Could we do a memcpy instead?
                let message = SingleData::decode(reader)?;
                // let message = reader.decode::<SingleData>(Fixed)?;
                // let message = <SingleData>::decode(reader)?;
                messages.push(message);
                continue_read_message = reader.deserialize::<bool>()?;
            }
            data.insert(channel_id, messages);
            continue_read_channel = reader.deserialize::<bool>()?;
        }
        Ok(Self { data })
    }
}

/// A packet that is split into multiple fragments
/// because it contains a message that is too big
#[derive(Clone, Debug, PartialEq)]
pub struct FragmentedPacket {
    pub(crate) channel_id: ChannelId,
    pub(crate) fragment: FragmentData,
    // TODO: change this as option? only the last fragment might have this
    /// Normal packet data: header + eventual non-fragmented messages included in the packet
    pub(crate) packet: SinglePacket,
}

impl FragmentedPacket {
    pub(crate) fn new(channel_id: ChannelId, fragment: FragmentData) -> Self {
        Self {
            channel_id,
            fragment,
            packet: SinglePacket::new(),
        }
    }

    /// Return the list of message ids in the packet
    pub(crate) fn message_acks(&self) -> HashMap<ChannelId, Vec<MessageAck>> {
        let mut data: HashMap<_, _> = self.packet.message_acks();
        data.entry(self.channel_id).or_default().push(MessageAck {
            message_id: self.fragment.message_id,
            fragment_id: Some(self.fragment.fragment_id),
        });
        data
    }
}

impl BitSerializable for FragmentedPacket {
    /// An expectation of the encoding is that we always have at least one channel that we can encode per packet.
    /// However, some channels might not have any messages (for example if we start writing the channel at the very end of the packet)
    fn encode(&self, writer: &mut impl WriteBuffer) -> anyhow::Result<()> {
        writer.encode(&self.channel_id, Gamma)?;
        self.fragment.encode(writer)?;
        // continuation bit: is there single packet data?
        writer.encode(&!self.packet.data.is_empty(), Fixed)?;
        self.packet.encode(writer)
    }

    fn decode(reader: &mut impl ReadBuffer) -> anyhow::Result<Self>
    where
        Self: Sized,
    {
        let channel_id = reader.decode::<NetId>(Gamma)?;
        let fragment = FragmentData::decode(reader)?;
        let is_single_packet = reader.decode::<bool>(Fixed)?;
        let packet = if is_single_packet {
            SinglePacket::decode(reader)?
        } else {
            SinglePacket::new()
        };
        Ok(Self {
            channel_id,
            fragment,
            packet,
        })
    }
}

/// Abstraction for data that is sent over the network
///
/// Every packet knows how to serialize itself into a list of Single Packets that can
/// directly be sent through a Socket
#[derive(Debug)]
pub(crate) enum PacketData {
    Single(SinglePacket),
    Fragmented(FragmentedPacket),
}

impl PacketData {
    pub(crate) fn num_messages(&self) -> usize {
        match self {
            PacketData::Single(single_packet) => single_packet.num_messages(),
            PacketData::Fragmented(fragmented_packet) => {
                1 + fragmented_packet.packet.num_messages()
            }
        }
    }
    pub(crate) fn contents(self) -> HashMap<NetId, Vec<MessageContainer>> {
        let mut res = HashMap::new();
        match self {
            PacketData::Single(data) => {
                for (channel_id, messages) in data.data {
                    res.insert(
                        channel_id,
                        messages.into_iter().map(|data| data.into()).collect(),
                    );
                }
            }
            PacketData::Fragmented(data) => {
                // add fragment
                res.insert(data.channel_id, vec![data.fragment.into()]);
                // add other single messages (if there are any)
                for (channel_id, messages) in data.packet.data {
                    let message_containers: Vec<MessageContainer> =
                        messages.into_iter().map(|data| data.into()).collect();
                    res.entry(channel_id)
                        .or_default()
                        .extend(message_containers);
                }
            }
        }
        res
    }
}

#[derive(Debug)]
pub(crate) struct Packet {
    pub(crate) header: PacketHeader,
    pub(crate) data: PacketData,
}

impl Packet {
    pub(crate) fn is_empty(&self) -> bool {
        match &self.data {
            PacketData::Single(single_packet) => single_packet.data.is_empty(),
            PacketData::Fragmented(fragmented_packet) => fragmented_packet.packet.data.is_empty(),
        }
    }

    /// Encode a packet into the write buffer
    pub fn encode(&self, writer: &mut impl WriteBuffer) -> anyhow::Result<()> {
        // use encode to force Fixed encoding
        // should still use gamma for packet type
        // TODO: add test
        writer.encode(&self.header, Fixed)?;
        match &self.data {
            PacketData::Single(single_packet) => single_packet.encode(writer),
            PacketData::Fragmented(fragmented_packet) => fragmented_packet.encode(writer),
        }
    }

    /// Decode a packet from the read buffer. The read buffer will only contain the bytes for a single packet
    pub fn decode(reader: &mut impl ReadBuffer) -> anyhow::Result<Packet> {
        let header = reader.decode::<PacketHeader>(Fixed)?;
        let packet_type = header.get_packet_type();
        match packet_type {
            PacketType::Data => {
                let single_packet = SinglePacket::decode(reader)?;
                Ok(Self {
                    header,
                    data: PacketData::Single(single_packet),
                })
            }
            PacketType::DataFragment => {
                let fragmented_packet = FragmentedPacket::decode(reader)?;
                Ok(Self {
                    header,
                    data: PacketData::Fragmented(fragmented_packet),
                })
            }
            _ => Err(anyhow::anyhow!("Packet type not supported")),
        }
    }

    // #[cfg(test)]
    pub fn header(&self) -> &PacketHeader {
        &self.header
    }

    pub fn add_channel(&mut self, channel: NetId) {
        match &mut self.data {
            PacketData::Single(single_packet) => {
                single_packet.add_channel(channel);
            }
            PacketData::Fragmented(fragmented_packet) => {
                fragmented_packet.packet.add_channel(channel);
            }
        }
    }

    pub fn add_message(&mut self, channel: NetId, message: SingleData) {
        match &mut self.data {
            PacketData::Single(single_packet) => single_packet.add_message(channel, message),
            PacketData::Fragmented(fragmented_packet) => {
                fragmented_packet.packet.add_message(channel, message);
            }
        }
    }

    /// Number of messages currently written in the packet
    #[cfg(test)]
    pub fn num_messages(&self) -> usize {
        match &self.data {
            PacketData::Single(single_packet) => single_packet.num_messages(),
            PacketData::Fragmented(fragmented_packet) => fragmented_packet.packet.num_messages(),
        }
    }

    pub fn message_acks(&self) -> HashMap<ChannelId, Vec<MessageAck>> {
        match &self.data {
            PacketData::Single(single_packet) => single_packet.message_acks(),
            PacketData::Fragmented(fragmented_packet) => fragmented_packet.message_acks(),
        }
    }
}

#[cfg(test)]
mod tests {
    use bitcode::encoding::Gamma;
    use bytes::Bytes;

    use lightyear_macros::ChannelInternal;

    use crate::_reexport::{ReadWordBuffer, WriteWordBuffer};
    use crate::packet::message::{FragmentData, MessageId, SingleData};
    use crate::packet::packet::{FragmentedPacket, SinglePacket};
    use crate::packet::packet_manager::PacketBuilder;
    use crate::prelude::{ChannelDirection, ChannelMode, ChannelRegistry, ChannelSettings};
    use crate::protocol::channel::ChannelKind;

    use super::*;

    #[derive(ChannelInternal)]
    struct Channel1;

    #[derive(ChannelInternal)]
    struct Channel2;

    fn get_channel_registry() -> ChannelRegistry {
        let settings = ChannelSettings {
            mode: ChannelMode::UnorderedUnreliable,
            direction: ChannelDirection::Bidirectional,
        };
        let mut c = ChannelRegistry::new();
        c.add::<Channel1>(settings.clone());
        c.add::<Channel2>(settings.clone());
        c
    }

    #[test]
    fn test_single_packet_add_messages() {
        let channel_registry = get_channel_registry();
        let manager = PacketBuilder::new();
        let mut packet = SinglePacket::new();

        packet.add_message(0, SingleData::new(None, Bytes::from("hello")));
        packet.add_message(0, SingleData::new(None, Bytes::from("world")));
        packet.add_message(1, SingleData::new(None, Bytes::from("!")));

        assert_eq!(packet.num_messages(), 3);
    }

    #[test]
    fn test_encode_single_packet() -> anyhow::Result<()> {
        let channel_registry = get_channel_registry();
        let manager = PacketBuilder::new();
        let mut packet = SinglePacket::new();

        let mut write_buffer = WriteWordBuffer::with_capacity(50);
        let message1 = SingleData::new(None, Bytes::from("hello"));
        let message2 = SingleData::new(None, Bytes::from("world"));
        let message3 = SingleData::new(None, Bytes::from("!"));

        packet.add_message(0, message1.clone());
        packet.add_message(0, message2.clone());
        packet.add_message(1, message3.clone());
        // add a channel with no messages
        packet.add_channel(2);

        packet.encode(&mut write_buffer)?;
        let packet_bytes = write_buffer.finish_write();

        // Encode manually
        let mut expected_write_buffer = WriteWordBuffer::with_capacity(50);
        // channel id
        expected_write_buffer.encode(&0u16, Gamma)?;
        // messages, with continuation bit
        expected_write_buffer.serialize(&true)?;
        message1.encode(&mut expected_write_buffer)?;
        expected_write_buffer.serialize(&true)?;
        message2.encode(&mut expected_write_buffer)?;
        expected_write_buffer.serialize(&false)?;
        // channel continue bit
        expected_write_buffer.serialize(&true)?;
        // channel id
        expected_write_buffer.encode(&1u16, Gamma)?;
        // messages with continuation bit
        expected_write_buffer.serialize(&true)?;
        message3.encode(&mut expected_write_buffer)?;
        expected_write_buffer.serialize(&false)?;
        // channel continue bit
        expected_write_buffer.serialize(&true)?;
        // channel id
        expected_write_buffer.encode(&2u16, Gamma)?;
        // messages with continuation bit
        expected_write_buffer.serialize(&false)?;
        // channel continue bit
        expected_write_buffer.serialize(&false)?;

        let expected_packet_bytes = expected_write_buffer.finish_write();

        assert_eq!(packet_bytes, expected_packet_bytes);

        let mut reader = ReadWordBuffer::start_read(packet_bytes);
        let decoded_packet = SinglePacket::decode(&mut reader)?;

        assert_eq!(decoded_packet.num_messages(), 3);
        assert_eq!(packet, decoded_packet);
        Ok(())
    }

    #[test]
    fn test_encode_fragmented_packet() -> anyhow::Result<()> {
        let channel_registry = get_channel_registry();
        let manager = PacketBuilder::new();
        let channel_kind = ChannelKind::of::<Channel1>();
        let channel_id = channel_registry.get_net_from_kind(&channel_kind).unwrap();
        let bytes = Bytes::from(vec![0; 10]);
        let fragment = FragmentData {
            message_id: MessageId(0),
            tick: None,
            fragment_id: 2,
            num_fragments: 3,
            bytes: bytes.clone(),
        };
        let mut packet = FragmentedPacket::new(*channel_id, fragment.clone());

        let mut write_buffer = WriteWordBuffer::with_capacity(100);
        let message1 = SingleData::new(None, Bytes::from("hello"));
        let message2 = SingleData::new(None, Bytes::from("world"));
        let message3 = SingleData::new(None, Bytes::from("!"));

        packet.packet.add_message(0, message1.clone());
        packet.packet.add_message(0, message2.clone());
        packet.packet.add_message(1, message3.clone());
        // add a channel with no messages
        packet.packet.add_channel(2);

        packet.encode(&mut write_buffer)?;
        let packet_bytes = write_buffer.finish_write();

        let mut reader = ReadWordBuffer::start_read(packet_bytes);
        let decoded_packet = FragmentedPacket::decode(&mut reader)?;

        assert_eq!(decoded_packet.packet.num_messages(), 3);
        assert_eq!(packet, decoded_packet);
        Ok(())
    }

    #[test]
    fn test_encode_fragmented_packet_no_single_data() -> anyhow::Result<()> {
        let channel_registry = get_channel_registry();
        let manager = PacketBuilder::new();
        let channel_kind = ChannelKind::of::<Channel1>();
        let channel_id = channel_registry.get_net_from_kind(&channel_kind).unwrap();
        let bytes = Bytes::from(vec![0; 10]);
        let fragment = FragmentData {
            message_id: MessageId(0),
            tick: None,
            fragment_id: 2,
            num_fragments: 3,
            bytes: bytes.clone(),
        };
        let packet = FragmentedPacket::new(*channel_id, fragment.clone());

        let mut write_buffer = WriteWordBuffer::with_capacity(100);

        packet.encode(&mut write_buffer)?;
        let packet_bytes = write_buffer.finish_write();

        let mut reader = ReadWordBuffer::start_read(packet_bytes);
        let decoded_packet = FragmentedPacket::decode(&mut reader)?;

        assert_eq!(decoded_packet.packet.num_messages(), 0);
        assert_eq!(packet, decoded_packet);
        Ok(())
    }
}