zonai 0.0.2

Synchronous packet-framed TCP clients and servers
Documentation

zonai

zonai provides synchronous packet-framed TCP client and server APIs.

Features

  • client enables zonai::client::Client.
  • server enables the zonai::server API.
  • serde enables Serde support for ClientConfig and ServerConfig when their respective modules are enabled.
  • stats enables client and server traffic counters when their respective modules are enabled.

client and server are enabled by default.

Server

It wraps mio with one background poll thread and exposes:

  • Server::poll() for Accept, Packet, and Lost events. Accept events include the peer's remote socket address.
  • Server::send() for non-blocking packet send commands.
  • Server::disconnect() for graceful disconnect after queued output flushes.
  • Server::disconnect_now() and Server::shutdown() for immediate close paths.
  • Server::shutdown_and_wait() for deterministic worker termination.
  • Server::from_listener() and configured variants for pre-bound listeners, including socket-activated and externally configured sockets.

The crate is protocol agnostic. Implement:

  • PacketIn to decode one incoming/serverbound packet from a Read.
  • PacketOut to encode one outgoing/clientbound packet into a Write.

Often one packet type implements both traits, but separate inbound/outbound types are supported.

Server Semantics

ServerClient handles are generational. A stale handle cannot send to a later connection that reused the same internal poll token.

send() is non-blocking. Ok(()) means the send command was accepted into the server command queue. It does not guarantee that the packet was accepted into that client's queue, written to the socket, or delivered to the peer. Stale handles, per client queue limits, encode errors, disconnects, and socket failures can still prevent delivery.

disconnect() processes send commands whose send() calls completed before the sequential disconnect() call, flushes the resulting output, then closes the client. Later send commands are rejected by the worker without encoding. Calls made concurrently from cloned server handles have no defined ordering. disconnect_now() closes immediately and discards queued output. shutdown() closes the whole server; queued output is not guaranteed to flush. shutdown_and_wait() also joins the background worker and reports a worker panic.

Server Limits

ServerConfig controls command and event queues, simultaneous clients, idle and packet-assembly timeouts, incoming buffers, and per-client and aggregate outgoing queues. The defaults disconnect clients after five minutes without a successful socket read or write and allow 30 seconds to assemble one packet. Either timeout can be disabled explicitly with None. Accepted sockets enable TCP_NODELAY and a 60-second TCP keepalive by default; set nodelay to false or keepalive_time to None to disable them.

The packet-assembly deadline starts when the decoder first reports an incomplete buffered packet. Incoming fragments do not extend it; successfully decoding a packet clears it before decoding the next frame. If the public event queue fills, accepts and socket reads pause until the application drains events. Lifecycle commands, queued socket writes, timeout expiration, and shutdown keep running. Pending public events preserve order and are internally bounded by the configured maximum-client count plus one intake event. Per-iteration accept, command, packet-decode, read-byte, and write-byte budgets prevent one continuously ready source from monopolizing the worker.

Use the peer address on Accept for connection attribution and application rate limits. Terminate TLS at a trusted proxy or load balancer, or pass a pre-bound listener when deployment requires socket activation or listener options not managed by this crate.

With stats, ServerStats counts successful socket reads and writes; bytes_consumed counts bytes accepted by successful packet decoders. Received packets count after decoding; sent packets count after all encoded bytes are written. All client and server counters saturate at u64::MAX.

Client

client::Client<I, O> connects directly to one server and provides blocking send() and receive() operations using the same PacketIn and PacketOut traits. It supports bounded outgoing encoding, socket timeouts, TCP_NODELAY, TCP keepalive, finite connect timeouts, address inspection, explicit shutdown, optional Serde configuration, and optional byte/packet counters.

With stats, ClientStats counts successful socket bytes even when the enclosing packet operation later fails. Packet counters increase only after a packet is fully written or successfully decoded.

Client send() and receive() block on socket I/O. A socket or decode error makes the client unusable because framing may be desynchronized. Encoding errors happen before socket I/O and may be corrected and retried. Client::connect() uses a 10-second TCP connect timeout by default, though DNS resolution may still block before socket connection attempts begin.

Framing Contract

PacketIn::read must decode exactly one packet. If more bytes are needed, return io::ErrorKind::UnexpectedEof; the server will keep the buffered bytes and retry when more data arrives. The blocking client treats any read or decode error, including UnexpectedEof, as terminal because framing may be desynchronized.

The server's incoming-buffer limit and packet-assembly timeout cannot prevent allocations performed inside PacketIn::read. Validate every untrusted length against a protocol-specific maximum before allocating.

On successful decode, the reader cursor position is treated as the number of bytes consumed. Decoders must leave following packet bytes unread.

On the server, any read error other than UnexpectedEof is fatal by default. With Server::bind_with_protocol_error or Server::bind_with_config_and_protocol_error, an InvalidData error invokes the protocol error hook. The hook packet is queued on a priority path, reads are disabled for that client, later ordinary sends are rejected, and the client is disconnected after the error packet flushes.

PacketOut::write encodes one packet. Both endpoints use bounded encoding: ClientConfig::outgoing_packet_limit for clients and ServerConfig::outgoing_buffer_limit for servers.

Example

Run the length-prefixed UTF-8 echo server with:

cargo run --example echo_server -- 127.0.0.1:4000

In another terminal, run the matching client:

cargo run --example echo_client -- 127.0.0.1:4000

Each client message is encoded as a four-byte big-endian length followed by UTF-8 bytes. Send quit to close one client or shutdown to stop the server.