tracing_gelf/connection/
udp.rs

1use std::net::SocketAddr;
2
3use bytes::Bytes;
4use futures_util::{Stream, StreamExt};
5use tokio::net::UdpSocket;
6use tokio_util::{codec::BytesCodec, udp::UdpFramed};
7
8/// A UDP connection to Graylog.
9#[derive(Debug)]
10pub struct UdpConnection;
11
12impl UdpConnection {
13    pub(super) async fn handle<S>(
14        &self,
15        addr: SocketAddr,
16        receiver: &mut S,
17    ) -> Result<(), std::io::Error>
18    where
19        S: Stream<Item = Bytes>,
20        S: Unpin,
21    {
22        // Bind address version must match address version
23        let bind_addr = if addr.is_ipv4() {
24            "0.0.0.0:0"
25        } else {
26            "[::]:0"
27        };
28        // Try connect
29        let udp_socket = UdpSocket::bind(bind_addr).await?;
30
31        // Writer
32        let udp_stream = UdpFramed::new(udp_socket, BytesCodec::new());
33        let (sink, _) = udp_stream.split();
34        receiver
35            .map(|bytes| Ok((bytes, addr)))
36            .forward(sink)
37            .await?;
38
39        Ok(())
40    }
41}