zenoh_codec/transport/
batch.rs

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
//
// Copyright (c) 2023 ZettaScale Technology
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
//
// Contributors:
//   ZettaScale Zenoh Team, <zenoh@zettascale.tech>
//
use core::num::NonZeroUsize;

use zenoh_buffers::{
    reader::{BacktrackableReader, DidntRead, Reader, SiphonableReader},
    writer::{BacktrackableWriter, DidntWrite, Writer},
    ZBufReader,
};
use zenoh_protocol::{
    core::Reliability,
    network::NetworkMessage,
    transport::{
        Fragment, FragmentHeader, Frame, FrameHeader, TransportBody, TransportMessage, TransportSn,
    },
};

use crate::{RCodec, WCodec, Zenoh080};

#[derive(Clone, Copy, Debug)]
#[repr(u8)]
pub enum CurrentFrame {
    Reliable,
    BestEffort,
    None,
}

#[derive(Clone, Copy, Debug)]
pub struct LatestSn {
    pub reliable: Option<TransportSn>,
    pub best_effort: Option<TransportSn>,
}

impl LatestSn {
    const fn new() -> Self {
        Self {
            reliable: None,
            best_effort: None,
        }
    }
}

#[derive(Clone, Debug)]
pub struct Zenoh080Batch {
    // The current frame being serialized: BestEffort/Reliable
    pub current_frame: CurrentFrame,
    // The latest SN
    pub latest_sn: LatestSn,
}

impl Default for Zenoh080Batch {
    fn default() -> Self {
        Self::new()
    }
}

impl Zenoh080Batch {
    pub const fn new() -> Self {
        Self {
            current_frame: CurrentFrame::None,
            latest_sn: LatestSn::new(),
        }
    }

    pub fn clear(&mut self) {
        self.current_frame = CurrentFrame::None;
        self.latest_sn = LatestSn::new();
    }
}

#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BatchError {
    NewFrame,
    DidntWrite,
}

impl<W> WCodec<&TransportMessage, &mut W> for &mut Zenoh080Batch
where
    W: Writer + BacktrackableWriter,
    <W as BacktrackableWriter>::Mark: Copy,
{
    type Output = Result<(), DidntWrite>;

    fn write(self, writer: &mut W, x: &TransportMessage) -> Self::Output {
        // Mark the write operation
        let mark = writer.mark();

        let codec = Zenoh080::new();
        codec.write(&mut *writer, x).map_err(|e| {
            // Revert the write operation
            writer.rewind(mark);
            e
        })?;

        // Reset the current frame value
        self.current_frame = CurrentFrame::None;

        Ok(())
    }
}

impl<W> WCodec<&NetworkMessage, &mut W> for &mut Zenoh080Batch
where
    W: Writer + BacktrackableWriter,
    <W as BacktrackableWriter>::Mark: Copy,
{
    type Output = Result<(), BatchError>;

    fn write(self, writer: &mut W, x: &NetworkMessage) -> Self::Output {
        // Eventually update the current frame and sn based on the current status
        if let (CurrentFrame::Reliable, false)
        | (CurrentFrame::BestEffort, true)
        | (CurrentFrame::None, _) = (self.current_frame, x.is_reliable())
        {
            // We are not serializing on the right frame.
            return Err(BatchError::NewFrame);
        }

        // Mark the write operation
        let mark = writer.mark();

        let codec = Zenoh080::new();
        codec.write(&mut *writer, x).map_err(|_| {
            // Revert the write operation
            writer.rewind(mark);
            BatchError::DidntWrite
        })
    }
}

impl<W> WCodec<(&NetworkMessage, &FrameHeader), &mut W> for &mut Zenoh080Batch
where
    W: Writer + BacktrackableWriter,
    <W as BacktrackableWriter>::Mark: Copy,
{
    type Output = Result<(), BatchError>;

    fn write(self, writer: &mut W, x: (&NetworkMessage, &FrameHeader)) -> Self::Output {
        let (m, f) = x;

        if let (Reliability::Reliable, false) | (Reliability::BestEffort, true) =
            (f.reliability, m.is_reliable())
        {
            // We are not serializing on the right frame.
            return Err(BatchError::NewFrame);
        }

        // Mark the write operation
        let mark = writer.mark();

        let codec = Zenoh080::new();
        // Write the frame header
        codec.write(&mut *writer, f).map_err(|_| {
            // Revert the write operation
            writer.rewind(mark);
            BatchError::DidntWrite
        })?;
        // Write the zenoh message
        codec.write(&mut *writer, m).map_err(|_| {
            // Revert the write operation
            writer.rewind(mark);
            BatchError::DidntWrite
        })?;
        // Update the frame
        self.current_frame = match f.reliability {
            Reliability::Reliable => {
                self.latest_sn.reliable = Some(f.sn);
                CurrentFrame::Reliable
            }
            Reliability::BestEffort => {
                self.latest_sn.best_effort = Some(f.sn);
                CurrentFrame::BestEffort
            }
        };
        Ok(())
    }
}

impl<W> WCodec<(&mut ZBufReader<'_>, &mut FragmentHeader), &mut W> for &mut Zenoh080Batch
where
    W: Writer + BacktrackableWriter,
    <W as BacktrackableWriter>::Mark: Copy,
{
    type Output = Result<NonZeroUsize, DidntWrite>;

    fn write(self, writer: &mut W, x: (&mut ZBufReader<'_>, &mut FragmentHeader)) -> Self::Output {
        let (r, f) = x;

        // Mark the buffer for the writing operation
        let mark = writer.mark();

        let codec = Zenoh080::new();
        // Write the fragment header
        codec.write(&mut *writer, &*f).map_err(|e| {
            // Revert the write operation
            writer.rewind(mark);
            e
        })?;

        // Check if it is really the final fragment
        if r.remaining() <= writer.remaining() {
            // Revert the buffer
            writer.rewind(mark);
            // It is really the finally fragment, reserialize the header
            f.more = false;
            // Write the fragment header
            codec.write(&mut *writer, &*f).map_err(|e| {
                // Revert the write operation
                writer.rewind(mark);
                e
            })?;
        }

        // Write the fragment
        r.siphon(&mut *writer).map_err(|_| {
            // Revert the write operation
            writer.rewind(mark);
            DidntWrite
        })
    }
}

impl<R> RCodec<TransportMessage, &mut R> for &mut Zenoh080Batch
where
    R: Reader + BacktrackableReader,
{
    type Error = DidntRead;

    fn read(self, reader: &mut R) -> Result<TransportMessage, Self::Error> {
        let codec = Zenoh080::new();
        let x: TransportMessage = codec.read(reader)?;

        match &x.body {
            TransportBody::Frame(Frame {
                reliability, sn, ..
            })
            | TransportBody::Fragment(Fragment {
                reliability, sn, ..
            }) => match reliability {
                Reliability::Reliable => {
                    self.current_frame = CurrentFrame::Reliable;
                    self.latest_sn.reliable = Some(*sn);
                }
                Reliability::BestEffort => {
                    self.current_frame = CurrentFrame::BestEffort;
                    self.latest_sn.best_effort = Some(*sn);
                }
            },
            _ => self.current_frame = CurrentFrame::None,
        }

        Ok(x)
    }
}