Skip to main content

cu29_logstream_udp/
lib.rs

1//! Nonblocking UDP carriers for Copper's packet-oriented log streaming traits.
2//!
3//! Socket setup happens once, before endpoints enter the output worker. Packet calls
4//! perform one socket operation with no allocation, locking, retry, or acknowledgement.
5//! FEC, pacing, and session policy belong to logstream, above this resource.
6//! Packet integrity relies on external network/link checks; socket setup preserves
7//! OS checksum defaults. The LogStream envelope carries no duplicate checksum.
8
9use cu29::bundle_resources;
10use cu29::config::ComponentConfig;
11use cu29::resource::{BundleContext, ResourceBundle, ResourceManager};
12use cu29::{CuError, CuResult};
13use cu29_logstream::{
14    CuFeedbackRx, CuFeedbackTx, CuStreamRx, CuStreamRxError, CuStreamTx, CuStreamTxError,
15};
16use socket2::{Domain, MaybeUninitSlice, Protocol, SockAddr, Socket, Type};
17use std::io;
18use std::mem::MaybeUninit;
19use std::net::SocketAddr;
20use std::sync::Arc;
21
22/// Conservative capacity for any ordinary UDP datagram (IPv6 jumbograms excluded).
23/// Used for truncation reports on OSes that do not return the original packet size.
24const UDP_DATAGRAM_CAPACITY: usize = 65_535;
25
26/// Explicit socket configuration, shared by the RON bundle and standalone receivers.
27///
28/// `bind_addr` is required. `remote_addr` enables the `tx` slot; the `rx` slot always
29/// exists. Both slots share one bound socket. Addresses must be numeric IPv4/IPv6
30/// socket addresses: setup does not perform DNS resolution. Optional socket options
31/// retain OS defaults when absent. Kernel buffer sizes are requests, subject to OS
32/// rounding and limits; they are unrelated to the stream's MTU or FEC memory budget.
33#[derive(Clone, Debug)]
34pub struct CuUdpLogStreamConfig {
35    pub bind_addr: SocketAddr,
36    pub remote_addr: Option<SocketAddr>,
37    pub send_buffer_bytes: Option<usize>,
38    pub recv_buffer_bytes: Option<usize>,
39    /// IPv4 unicast TTL or IPv6 unicast hop limit, in 1..=255.
40    pub ttl: Option<u32>,
41    /// Six-bit DSCP value, in 0..=63. ECN bits remain zero.
42    pub dscp: Option<u8>,
43}
44
45impl CuUdpLogStreamConfig {
46    /// Listen on this address with OS socket defaults and no transmit destination.
47    pub const fn new(bind_addr: SocketAddr) -> Self {
48        Self {
49            bind_addr,
50            remote_addr: None,
51            send_buffer_bytes: None,
52            recv_buffer_bytes: None,
53            ttl: None,
54            dscp: None,
55        }
56    }
57
58    /// Parse the resource-bundle configuration, rejecting unknown or mistyped keys.
59    pub fn from_component(config: &ComponentConfig) -> CuResult<Self> {
60        for key in config.0.keys() {
61            if !matches!(
62                key.as_str(),
63                "bind_addr"
64                    | "remote_addr"
65                    | "send_buffer_bytes"
66                    | "recv_buffer_bytes"
67                    | "ttl"
68                    | "dscp"
69            ) {
70                return Err(CuError::from(format!(
71                    "Unknown UDP resource option '{key}'"
72                )));
73            }
74        }
75        let bind = config
76            .get::<String>("bind_addr")?
77            .ok_or_else(|| CuError::from("UDP resource requires bind_addr"))?;
78        let mut parsed = Self::new(parse_addr(&bind)?);
79        parsed.remote_addr = config
80            .get::<String>("remote_addr")?
81            .map(|value| parse_addr(&value))
82            .transpose()?;
83        parsed.send_buffer_bytes = config.get_value("send_buffer_bytes")?;
84        parsed.recv_buffer_bytes = config.get_value("recv_buffer_bytes")?;
85        parsed.ttl = config.get_value("ttl")?;
86        parsed.dscp = config.get_value("dscp")?;
87        parsed.validate()?;
88        Ok(parsed)
89    }
90
91    fn validate(&self) -> CuResult<()> {
92        if let Some(remote) = self.remote_addr
93            && (remote.is_ipv4() != self.bind_addr.is_ipv4() || remote.port() == 0)
94        {
95            return Err(CuError::from(
96                "UDP remote_addr must match the bind address family and have a nonzero port",
97            ));
98        }
99        if [self.send_buffer_bytes, self.recv_buffer_bytes]
100            .into_iter()
101            .flatten()
102            .any(|size| size == 0 || i32::try_from(size).is_err())
103        {
104            return Err(CuError::from(
105                "UDP socket buffer sizes must be in 1..=2147483647",
106            ));
107        }
108        if self.ttl.is_some_and(|ttl| !(1..=255).contains(&ttl)) {
109            return Err(CuError::from("UDP ttl must be in 1..=255"));
110        }
111        if self.dscp.is_some_and(|dscp| dscp > 63) {
112            return Err(CuError::from("UDP dscp must be in 0..=63"));
113        }
114        #[cfg(windows)]
115        if self.dscp.is_some() {
116            // Winsock requires the separate QoS API; IP_TOS is not a portable
117            // way to honor an explicitly requested DSCP value on Windows.
118            return Err(CuError::from(
119                "UDP DSCP configuration is unsupported on Windows",
120            ));
121        }
122        Ok(())
123    }
124
125    /// Open one nonblocking socket and create its typed endpoints.
126    ///
127    /// Clones share the socket without a userspace mutex. Receive clones compete
128    /// for datagrams; they do not subscribe to copies of the same traffic. The socket
129    /// is unconnected, so reception accepts any sender and creates no reverse channel.
130    pub fn open(&self) -> CuResult<(Option<CuUdpLogStreamTx>, CuUdpLogStreamRx)> {
131        self.validate()?;
132        let socket = self.open_socket().map_err(|error| {
133            CuError::new_with_cause("Failed to configure UDP stream socket", error)
134        })?;
135        let socket = Arc::new(socket);
136        let tx = self.remote_addr.map(|remote| CuUdpLogStreamTx {
137            socket: socket.clone(),
138            remote: remote.into(),
139        });
140        Ok((tx, CuUdpLogStreamRx { socket }))
141    }
142
143    fn open_socket(&self) -> io::Result<Socket> {
144        let socket = Socket::new(
145            Domain::for_address(self.bind_addr),
146            Type::DGRAM,
147            Some(Protocol::UDP),
148        )?;
149        socket.set_nonblocking(true)?;
150        if self.bind_addr.is_ipv6() {
151            socket.set_only_v6(true)?;
152        }
153        if let Some(size) = self.send_buffer_bytes {
154            socket.set_send_buffer_size(size)?;
155        }
156        if let Some(size) = self.recv_buffer_bytes {
157            socket.set_recv_buffer_size(size)?;
158        }
159        if let Some(ttl) = self.ttl {
160            if self.bind_addr.is_ipv4() {
161                socket.set_ttl_v4(ttl)?;
162            } else {
163                socket.set_unicast_hops_v6(ttl)?;
164            }
165        }
166        if let Some(dscp) = self.dscp {
167            let traffic_class = u32::from(dscp) << 2;
168            if self.bind_addr.is_ipv4() {
169                socket.set_tos_v4(traffic_class)?;
170            } else {
171                set_ipv6_traffic_class(&socket, traffic_class)?;
172            }
173        }
174        socket.bind(&self.bind_addr.into())?;
175        Ok(socket)
176    }
177}
178
179fn parse_addr(value: &str) -> CuResult<SocketAddr> {
180    value.parse().map_err(|error| {
181        CuError::new_with_cause("UDP address must be a numeric IP address and port", error)
182    })
183}
184
185#[cfg(any(target_os = "linux", target_os = "macos", target_os = "android"))]
186fn set_ipv6_traffic_class(socket: &Socket, value: u32) -> io::Result<()> {
187    socket.set_tclass_v6(value)
188}
189
190#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "android")))]
191fn set_ipv6_traffic_class(_socket: &Socket, _value: u32) -> io::Result<()> {
192    Err(io::Error::new(
193        io::ErrorKind::Unsupported,
194        "IPv6 DSCP is unsupported on this platform",
195    ))
196}
197
198/// Cloneable, one-way UDP transmitter. Success means local socket acceptance only.
199#[derive(Clone, Debug)]
200pub struct CuUdpLogStreamTx {
201    socket: Arc<Socket>,
202    remote: SockAddr,
203}
204
205impl CuUdpLogStreamTx {
206    pub fn local_addr(&self) -> io::Result<SocketAddr> {
207        local_addr(&self.socket)
208    }
209}
210
211impl CuStreamTx for CuUdpLogStreamTx {
212    fn try_send(&mut self, packet: &[u8]) -> Result<(), CuStreamTxError> {
213        submit_once(packet, |packet| self.socket.send_to(packet, &self.remote))
214    }
215}
216
217// Keeping the one-call boundary explicit also lets tests force WouldBlock and
218// Interrupted without assuming that a real UDP kernel queue reports saturation.
219fn submit_once(
220    packet: &[u8],
221    send: impl FnOnce(&[u8]) -> io::Result<usize>,
222) -> Result<(), CuStreamTxError> {
223    match send(packet) {
224        Ok(len) if len == packet.len() => Ok(()),
225        Ok(_) => Err(CuStreamTxError::Failed(
226            "UDP socket accepted an incomplete datagram",
227        )),
228        Err(error) if error.kind() == io::ErrorKind::WouldBlock => Err(CuStreamTxError::WouldBlock),
229        Err(_) => Err(CuStreamTxError::Failed("UDP datagram submission failed")),
230    }
231}
232
233/// Cloneable nonblocking receiver with no internal packet buffer.
234///
235/// An oversized datagram is consumed and rejected, never returned as a partial
236/// packet. Linux/Android report its exact length in `BufferTooSmall::needed`;
237/// other supported OSes report a conservative sufficient capacity of 65,535 bytes.
238/// The caller must ignore buffer contents on error. Empty datagrams are `Some(0)`.
239#[derive(Clone, Debug)]
240pub struct CuUdpLogStreamRx {
241    socket: Arc<Socket>,
242}
243
244impl CuUdpLogStreamRx {
245    pub fn local_addr(&self) -> io::Result<SocketAddr> {
246        local_addr(&self.socket)
247    }
248}
249
250impl CuStreamRx for CuUdpLogStreamRx {
251    fn try_recv(&mut self, packet: &mut [u8]) -> Result<Option<usize>, CuStreamRxError> {
252        let capacity = packet.len();
253        // Darwin can return success without consuming a datagram for a zero-length
254        // receive. Give it one byte of space, but validate against caller capacity.
255        #[cfg(target_os = "macos")]
256        let mut empty_buffer = [0u8; 1];
257        #[cfg(target_os = "macos")]
258        let packet = if packet.is_empty() {
259            &mut empty_buffer[..]
260        } else {
261            packet
262        };
263        // SAFETY: u8 and MaybeUninit<u8> have identical layout. The exclusive borrow
264        // lives only for this call. socket2 guarantees recv_from_vectored_with_flags
265        // writes only initialized bytes, preserving validity even when receive fails.
266        let buffer = unsafe { &mut *(packet as *mut [u8] as *mut [MaybeUninit<u8>]) };
267        let mut buffers = [MaybeUninitSlice::new(buffer)];
268        #[cfg(any(target_os = "linux", target_os = "android"))]
269        let flags = libc::MSG_TRUNC;
270        #[cfg(not(any(target_os = "linux", target_os = "android")))]
271        let flags = 0;
272        match self
273            .socket
274            .recv_from_vectored_with_flags(&mut buffers, flags)
275        {
276            Ok((len, flags, _)) if flags.is_truncated() || len > capacity => {
277                #[cfg(any(target_os = "linux", target_os = "android"))]
278                let needed = if len > capacity {
279                    len
280                } else {
281                    UDP_DATAGRAM_CAPACITY
282                };
283                #[cfg(not(any(target_os = "linux", target_os = "android")))]
284                let needed = UDP_DATAGRAM_CAPACITY;
285                Err(CuStreamRxError::BufferTooSmall { needed })
286            }
287            Ok((len, _, _)) => Ok(Some(len)),
288            Err(error) if error.kind() == io::ErrorKind::WouldBlock => Ok(None),
289            Err(_) => Err(CuStreamRxError::Failed("UDP datagram reception failed")),
290        }
291    }
292}
293
294fn local_addr(socket: &Socket) -> io::Result<SocketAddr> {
295    socket
296        .local_addr()?
297        .as_socket()
298        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "UDP socket has no IP address"))
299}
300
301/// Copper bundle exposing statically named `tx` and `rx` resource slots.
302/// `tx` is populated only when `remote_addr` is configured; `rx` is always populated.
303pub struct CuUdpLogStreamResources;
304
305bundle_resources!(CuUdpLogStreamResources: Tx, Rx);
306
307impl ResourceBundle for CuUdpLogStreamResources {
308    fn build(
309        bundle: BundleContext<Self>,
310        config: Option<&ComponentConfig>,
311        manager: &mut ResourceManager,
312    ) -> CuResult<()> {
313        let config = config.ok_or_else(|| CuError::from("UDP resource requires configuration"))?;
314        let (tx, rx) = CuUdpLogStreamConfig::from_component(config)?.open()?;
315        if let Some(tx) = tx {
316            manager.add_owned(bundle.key(CuUdpLogStreamResourcesId::Tx), tx)?;
317        }
318        manager.add_owned(bundle.key(CuUdpLogStreamResourcesId::Rx), rx)
319    }
320}
321
322#[cfg(test)]
323mod tests;
324
325// Logical direction is enabled by explicit resource wiring, not by trait presence.
326impl CuFeedbackTx for CuUdpLogStreamTx {
327    fn try_send_feedback(&mut self, packet: &[u8]) -> Result<(), CuStreamTxError> {
328        self.try_send(packet)
329    }
330}
331impl CuFeedbackRx for CuUdpLogStreamRx {
332    fn try_recv_feedback(&mut self, packet: &mut [u8]) -> Result<Option<usize>, CuStreamRxError> {
333        self.try_recv(packet)
334    }
335}