Skip to main content

tilo_render_protocol/patch/
unix.rs

1//! The patch transport between processes: a [`Channel`] (one batch a packet) for what fits a
2//! packet, and an immutable shared buffer ([`sealed_blob`]) riding along for a larger batch (a
3//! window's first tree of a long list), so no batch is split or streamed. The receiver copies a
4//! batch out of the buffer once, into its own memory, before it reads it: the sender cannot
5//! change what the receiver validated.
6
7use std::io;
8
9use serde::{Deserialize, Serialize};
10
11use super::{MAX_BATCH_BYTES, Transport};
12use crate::WireError;
13use crate::channel::{Channel, ChannelError};
14use crate::shm::{Mapping, sealed_blob};
15
16/// Largest batch carried in the packet itself; a larger one comes in a sealed memfd.
17pub const INLINE_BYTES: usize = 12 * 1024;
18
19/// What one packet carries.
20#[derive(Serialize, Deserialize)]
21enum Carried {
22    /// The batch itself.
23    Inline(Vec<u8>),
24    /// A batch of `len` bytes, in the sealed memfd that comes with the packet.
25    Sealed { len: u32 },
26}
27
28/// One end of a patch connection between processes.
29pub struct ChannelTransport {
30    channel: Channel,
31}
32
33impl ChannelTransport {
34    /// Batches over `channel`, which receives without waiting from now on.
35    pub fn new(channel: Channel) -> io::Result<Self> {
36        channel.set_nonblocking(true)?;
37        Ok(Self { channel })
38    }
39
40    /// The channel, to wait on.
41    #[must_use]
42    pub fn channel(&self) -> &Channel {
43        &self.channel
44    }
45}
46
47fn wire(error: ChannelError) -> WireError {
48    match error {
49        ChannelError::Wire(error) => error,
50        ChannelError::Closed => WireError::Closed,
51        ChannelError::Io(_) => WireError::Malformed("the connection failed"),
52    }
53}
54
55impl Transport for ChannelTransport {
56    fn send(&mut self, batch: Vec<u8>) -> Result<(), WireError> {
57        if batch.len() > MAX_BATCH_BYTES {
58            return Err(WireError::OverLimit("batch size"));
59        }
60        if batch.len() <= INLINE_BYTES {
61            return self
62                .channel
63                .send(&Carried::Inline(batch), &[])
64                .map_err(wire);
65        }
66        let len = u32::try_from(batch.len()).map_err(|_| WireError::Overflow)?;
67        let fd = sealed_blob("tilo-patch-batch", &batch)
68            .map_err(|_| WireError::Malformed("a batch's memfd"))?;
69        self.channel
70            .send(&Carried::Sealed { len }, &[std::os::fd::AsFd::as_fd(&fd)])
71            .map_err(wire)
72    }
73
74    fn recv(&mut self) -> Result<Option<Vec<u8>>, WireError> {
75        let received = match self.channel.recv::<Carried>() {
76            Ok(received) => received,
77            Err(ChannelError::Io(error)) if error.kind() == io::ErrorKind::WouldBlock => {
78                return Ok(None);
79            }
80            Err(error) => return Err(wire(error)),
81        };
82        match received.message {
83            Carried::Inline(batch) => {
84                if !received.fds.is_empty() {
85                    return Err(WireError::Malformed("a descriptor with an inline batch"));
86                }
87                Ok(Some(batch))
88            }
89            Carried::Sealed { len } => {
90                let [fd] = <[_; 1]>::try_from(received.fds)
91                    .map_err(|_| WireError::Malformed("a sealed batch without its memfd"))?;
92                let len = len as usize;
93                if len > MAX_BATCH_BYTES {
94                    return Err(WireError::OverLimit("batch size"));
95                }
96                let mapping = Mapping::map_sealed(&fd, true, len, len.saturating_add(1 << 16))
97                    .map_err(|_| WireError::Malformed("a batch's memfd"))?;
98                let bytes = mapping.get(0, len).ok_or(WireError::Truncated)?;
99                Ok(Some(bytes.to_vec()))
100            }
101        }
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108
109    #[test]
110    fn small_and_large_batches_arrive_whole_and_in_order() {
111        let (a, b) = Channel::pair().expect("a pair");
112        let mut app = ChannelTransport::new(a).expect("an end");
113        let mut window = ChannelTransport::new(b).expect("an end");
114        assert_eq!(window.recv(), Ok(None), "nothing sent yet");
115        let small = vec![7_u8; 100];
116        let large: Vec<u8> = (0..200_000_u32).map(|i| (i % 251) as u8).collect();
117        app.send(small.clone()).expect("sends");
118        app.send(large.clone()).expect("sends");
119        assert_eq!(window.recv(), Ok(Some(small)));
120        assert_eq!(window.recv(), Ok(Some(large)));
121        assert_eq!(window.recv(), Ok(None));
122        drop(app);
123        assert_eq!(window.recv(), Err(WireError::Closed), "the app went away");
124        assert_eq!(window.recv(), Err(WireError::Closed), "and stays gone");
125        assert_eq!(
126            window.send(vec![1]),
127            Err(WireError::Closed),
128            "nothing reaches it"
129        );
130    }
131}