zonai 0.0.2

Synchronous packet-framed TCP clients and servers
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
//! Synchronous packet-framed TCP client.
//!
//! [`Client`] connects to one TCP server and exposes blocking [`Client::send`]
//! and [`Client::receive`] operations. It uses the shared [`PacketIn`] and
//! [`PacketOut`] traits, so protocol packet types can be used by both client
//! and server applications.
//!
//! ## Quick start
//!
//! ```no_run
//! use std::io::{self, Read, Write};
//! use zonai::{
//!     client::Client,
//!     packet::{PacketIn, PacketOut},
//! };
//!
//! struct Packet(String);
//!
//! impl PacketIn for Packet {
//!     fn read(reader: &mut impl Read) -> io::Result<Self> {
//!         let mut length = [0; 2];
//!         reader.read_exact(&mut length)?;
//!         let mut bytes = vec![0; u16::from_be_bytes(length) as usize];
//!         reader.read_exact(&mut bytes)?;
//!         String::from_utf8(bytes)
//!             .map(Packet)
//!             .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
//!     }
//! }
//!
//! impl PacketOut for Packet {
//!     fn write(&self, writer: &mut impl Write) -> io::Result<()> {
//!         let bytes = self.0.as_bytes();
//!         writer.write_all(&(bytes.len() as u16).to_be_bytes())?;
//!         writer.write_all(bytes)
//!     }
//! }
//!
//! fn main() -> io::Result<()> {
//!     let mut client = Client::<Packet, Packet>::connect("127.0.0.1:4000")?;
//!     client.send(&Packet("hello".to_owned()))?;
//!     let reply = client.receive()?;
//!     println!("{}", reply.0);
//!     client.shutdown()
//! }
//! ```
//!
//! ## Framing contract
//!
//! - `PacketOut::write` must encode exactly one complete packet. Encoding is
//!   buffered and rejected if it exceeds
//!   [`ClientConfig::outgoing_packet_limit`] or produces zero bytes.
//! - `PacketIn::read` must decode exactly one packet directly from the TCP
//!   stream. Unlike the server, the blocking client does not buffer and retry
//!   `UnexpectedEof`; a read or decode error makes the client unusable because
//!   the next packet boundary may no longer be known.
//! - Separate inbound and outbound packet types are supported through
//!   `Client<I, O>`.
//!
//! ## Blocking and timeouts
//!
//! `connect()` uses a finite TCP connect timeout by default. DNS resolution can
//! still block before socket connection attempts begin. `send()` and
//! `receive()` block on socket I/O. Configure operating-system read and write
//! timeouts with [`ClientConfig`]. A send or receive timeout is an I/O error
//! and therefore makes the client unusable. Use [`Client::is_usable`] to
//! inspect that state.
//!
//! Packet encoding errors occur before socket I/O and do not make the client
//! unusable, so callers may correct the packet and retry.
//!
//! Client sockets enable `TCP_NODELAY` and TCP keepalive by default. Both are
//! configurable through [`ClientConfig`].
//!
//! ## Features
//!
//! - `serde` implements `Serialize` and `Deserialize` for [`ClientConfig`].
#![cfg_attr(
    feature = "stats",
    doc = "- `stats` enables [`ClientStats`] and [`Client::stats`]. Byte counters include successful socket reads and writes even when the enclosing packet later fails; packet counters include only completed packets."
)]
#![cfg_attr(
    not(feature = "stats"),
    doc = "- `stats` enables `ClientStats` and `Client::stats`. Byte counters include successful socket reads and writes even when the enclosing packet later fails; packet counters include only completed packets."
)]

use std::{
    io::{self, Write},
    marker::PhantomData,
    net::{Shutdown, SocketAddr, TcpStream, ToSocketAddrs},
    time::Duration,
};

use socket2::{SockRef, TcpKeepalive};

#[cfg(feature = "stats")]
use std::io::Read;

use crate::packet::encode_bounded;
pub use crate::packet::{PacketIn, PacketOut};

/// Default maximum encoded outgoing packet size.
pub const DEFAULT_OUTGOING_PACKET_LIMIT: usize = 1024 * 1024;
/// Default TCP connect timeout.
pub const DEFAULT_CLIENT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
/// Default TCP keepalive idle time.
pub const DEFAULT_CLIENT_KEEPALIVE_TIME: Duration = Duration::from_secs(60);

/// Connection settings and packet limits for a [`Client`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, better_default::Default)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct ClientConfig {
    /// Maximum encoded size of one outgoing packet.
    #[default(DEFAULT_OUTGOING_PACKET_LIMIT)]
    pub outgoing_packet_limit: usize,
    /// TCP connect timeout, or `None` to use the operating-system default.
    #[default(Some(DEFAULT_CLIENT_CONNECT_TIMEOUT))]
    pub connect_timeout: Option<Duration>,
    /// Socket read timeout used by [`Client::receive`].
    pub read_timeout: Option<Duration>,
    /// Socket write timeout used by [`Client::send`].
    pub write_timeout: Option<Duration>,
    /// Whether to disable Nagle's algorithm.
    #[default(true)]
    pub nodelay: bool,
    /// TCP keepalive idle time, or `None` to disable TCP keepalive.
    #[default(Some(DEFAULT_CLIENT_KEEPALIVE_TIME))]
    pub keepalive_time: Option<Duration>,
}

/// A point-in-time snapshot of client traffic counters.
///
/// Counters saturate at [`u64::MAX`].
#[cfg(feature = "stats")]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ClientStats {
    /// Bytes successfully read from the socket.
    pub bytes_received: u64,
    /// Bytes successfully written to the socket.
    pub bytes_sent: u64,
    /// Packets successfully decoded.
    pub packets_received: u64,
    /// Packets whose encoded bytes were fully written.
    pub packets_sent: u64,
}

impl ClientConfig {
    fn validate(self) -> io::Result<Self> {
        if self.outgoing_packet_limit == 0 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "outgoing_packet_limit must be greater than zero",
            ));
        }
        for (timeout, name) in [
            (self.connect_timeout, "connect_timeout"),
            (self.read_timeout, "read_timeout"),
            (self.write_timeout, "write_timeout"),
            (self.keepalive_time, "keepalive_time"),
        ] {
            if timeout.is_some_and(|timeout| timeout.is_zero()) {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!("{name} must be greater than zero when enabled"),
                ));
            }
        }
        Ok(self)
    }
}

/// A blocking packet-framed TCP client.
///
/// `I` is the packet type received from the server and `O` is the packet type
/// sent to the server. One type may implement both directions.
pub struct Client<I, O> {
    stream: TcpStream,
    config: ClientConfig,
    usable: bool,
    #[cfg(feature = "stats")]
    stats: ClientStats,
    packet_types: PhantomData<fn() -> (I, O)>,
}

impl<I, O> Client<I, O>
where
    I: PacketIn,
    O: PacketOut,
{
    /// Connect using [`ClientConfig::default`].
    pub fn connect(addr: impl ToSocketAddrs) -> io::Result<Self> {
        Self::connect_with_config(addr, ClientConfig::default())
    }

    /// Connect using explicit connection settings and packet limits.
    pub fn connect_with_config(addr: impl ToSocketAddrs, config: ClientConfig) -> io::Result<Self> {
        let config = config.validate()?;
        let stream = connect_stream(addr, config.connect_timeout)?;
        configure_stream(&stream, config)?;
        Ok(Self {
            stream,
            config,
            usable: true,
            #[cfg(feature = "stats")]
            stats: ClientStats::default(),
            packet_types: PhantomData,
        })
    }

    /// Encode and send one packet.
    pub fn send(&mut self, packet: &O) -> io::Result<()> {
        self.ensure_usable()?;
        let encoded = encode_bounded(packet, self.config.outgoing_packet_limit)?;
        #[cfg(feature = "stats")]
        let result = {
            let mut writer = CountingWriter::new(&mut self.stream);
            let result = writer.write_all(&encoded);
            self.stats.bytes_sent = self.stats.bytes_sent.saturating_add(writer.count);
            result
        };
        #[cfg(not(feature = "stats"))]
        let result = self.stream.write_all(&encoded);

        if let Err(error) = result {
            self.usable = false;
            return Err(error);
        }
        #[cfg(feature = "stats")]
        {
            self.stats.packets_sent = self.stats.packets_sent.saturating_add(1);
        }
        Ok(())
    }

    /// Block until one packet is decoded from the server.
    ///
    /// Any decode or socket error marks the client unusable because the packet
    /// boundary may no longer be known.
    pub fn receive(&mut self) -> io::Result<I> {
        self.ensure_usable()?;
        #[cfg(feature = "stats")]
        let result = {
            let mut reader = CountingReader::new(&mut self.stream);
            let result = I::read(&mut reader);
            self.stats.bytes_received = self.stats.bytes_received.saturating_add(reader.count);
            result
        };
        #[cfg(not(feature = "stats"))]
        let result = I::read(&mut self.stream);

        match result {
            Ok(packet) => {
                #[cfg(feature = "stats")]
                {
                    self.stats.packets_received = self.stats.packets_received.saturating_add(1);
                }
                Ok(packet)
            }
            Err(error) => {
                self.usable = false;
                Err(error)
            }
        }
    }

    /// Shut down both directions of the TCP connection.
    pub fn shutdown(&self) -> io::Result<()> {
        self.stream.shutdown(Shutdown::Both)
    }

    /// Return the active client configuration.
    pub fn config(&self) -> ClientConfig {
        self.config
    }

    /// Return whether packet I/O may continue after previous operations.
    pub fn is_usable(&self) -> bool {
        self.usable
    }

    /// Return a point-in-time snapshot of client traffic counters.
    #[cfg(feature = "stats")]
    pub fn stats(&self) -> ClientStats {
        self.stats
    }

    /// Return the local socket address.
    pub fn local_addr(&self) -> io::Result<SocketAddr> {
        self.stream.local_addr()
    }

    /// Return the remote socket address.
    pub fn peer_addr(&self) -> io::Result<SocketAddr> {
        self.stream.peer_addr()
    }

    /// Consume the client and return its TCP stream.
    pub fn into_stream(self) -> TcpStream {
        self.stream
    }

    fn ensure_usable(&self) -> io::Result<()> {
        if self.usable {
            Ok(())
        } else {
            Err(io::Error::new(
                io::ErrorKind::NotConnected,
                "client is unusable after a previous packet I/O error",
            ))
        }
    }
}

fn connect_stream(addr: impl ToSocketAddrs, timeout: Option<Duration>) -> io::Result<TcpStream> {
    if let Some(timeout) = timeout {
        let mut last_error = None;
        for addr in addr.to_socket_addrs()? {
            match TcpStream::connect_timeout(&addr, timeout) {
                Ok(stream) => return Ok(stream),
                Err(error) => last_error = Some(error),
            }
        }
        Err(last_error.unwrap_or_else(|| {
            io::Error::new(io::ErrorKind::InvalidInput, "no socket addresses resolved")
        }))
    } else {
        TcpStream::connect(addr)
    }
}

fn configure_stream(stream: &TcpStream, config: ClientConfig) -> io::Result<()> {
    stream.set_read_timeout(config.read_timeout)?;
    stream.set_write_timeout(config.write_timeout)?;
    if let Err(error) = stream.set_nodelay(config.nodelay)
        && !is_best_effort_socket_option_error(&error)
    {
        return Err(error);
    }
    let socket = SockRef::from(stream);
    let keepalive_result = if let Some(time) = config.keepalive_time {
        socket.set_tcp_keepalive(&TcpKeepalive::new().with_time(time))
    } else {
        socket.set_keepalive(false)
    };
    if let Err(error) = keepalive_result
        && !is_best_effort_socket_option_error(&error)
    {
        return Err(error);
    }
    Ok(())
}

fn is_best_effort_socket_option_error(error: &io::Error) -> bool {
    matches!(
        error.kind(),
        io::ErrorKind::PermissionDenied | io::ErrorKind::Unsupported
    )
}

#[cfg(feature = "stats")]
struct CountingReader<R> {
    inner: R,
    count: u64,
}

#[cfg(feature = "stats")]
impl<R> CountingReader<R> {
    fn new(inner: R) -> Self {
        Self { inner, count: 0 }
    }
}

#[cfg(feature = "stats")]
impl<R: Read> Read for CountingReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let read = self.inner.read(buf)?;
        self.count = self.count.saturating_add(read as u64);
        Ok(read)
    }
}

#[cfg(feature = "stats")]
struct CountingWriter<W> {
    inner: W,
    count: u64,
}

#[cfg(feature = "stats")]
impl<W> CountingWriter<W> {
    fn new(inner: W) -> Self {
        Self { inner, count: 0 }
    }
}

#[cfg(feature = "stats")]
impl<W: Write> Write for CountingWriter<W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let written = self.inner.write(buf)?;
        self.count = self.count.saturating_add(written as u64);
        Ok(written)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}