Expand description
§net_io
The network IO substrate for the -net and -io crates: the entrance and
exit every service shares. It owns listeners and sockets, the life of each
connection, the limits and timeouts that keep a peer from holding what it
should not, graceful drain, and the seams a connection gate and a TLS engine
plug into. It is protocol-free and has no runtime dependencies.
§Quick start
fn main() -> Result<(), net_io::NetError> {
// An echo server: one handler call per connection on a bounded worker pool,
// with every default limit (idle, read, write, minimum rate, caps) applied.
let server = net_io::serve("127.0.0.1:7000", |conn| {
let mut buf = [0u8; 4096];
loop {
let n = conn.recv(&mut buf)?;
if n == 0 {
return Ok(()); // the peer closed its side
}
conn.send_all(&buf[..n])?;
}
})?;
// A client.
let mut conn = net_io::connect("127.0.0.1:7000")?;
conn.send_all(b"ping")?;
let mut reply = [0u8; 4];
conn.recv_exact(&mut reply)?;
assert_eq!(&reply, b"ping");
// Stop: close the door, drain open connections, join the workers.
server.handle().request_stop();
let report = server.wait_for_stop();
println!("{} closed gracefully, {} killed", report.graceful, report.killed);
Ok(())
}Everything else (several listeners, a gate, events, the control line) goes
through ServerBuilder. The full reference with every item, its errors,
and its cost is docs/API.md in the
repository.
§Status
0.3.0: TCP and the blocking driver on Linux, macOS, and Windows. PROXY
protocol, UDP, local sockets, the TLS server integration, inheritance, and
hand-off arrive in 0.4.0; the reactor in 0.5.0.
Structs§
- Admitted
- What admission grants.
- Allow
All - The explicit “no gate”: admits every connection in
Lane(0)withGateTag(0)and never denies. - Blocking
Handler - What
ServerBuilder::handlerproduces; programs never name it. - Buffer
- A byte buffer from a pool: a fixed capacity (its size class) and a filled length.
- Buffer
Pool - A worker’s buffer pool: free lists per size class, drawing new buffers from a budget shared by every worker of a server.
- Cidr
- A network block: a normalized network address and a prefix length.
- Completer
- A worker’s completion queue, for other threads to hand results back to a
connection that returned
Step::Park. - Connect
Options - Options for an outbound connection.
- Connection
Id - The identity of one connection, unique and never reused within a process.
- Connection
Info - What net-io knows about one connection, built at accept and completed as the handshake reveals more. It holds no heap memory.
- Denial
- A gate’s refusal of a write.
- Drain
Report - What a drain did.
- GateTag
- An opaque value the gate returns at admission, stored in
ConnectionInfo::gate. - Input
- The connection’s read buffer: a zero-copy view of what was read and not yet consumed.
- Keepalive
- Keepalive probes: idle time before the first, interval between them, and count.
- Kill
Handle - Closes one connection abortively from any thread.
- Kill
Reason - A caller-defined code for a kill.
- Lane
- An opaque importance class the gate assigns at admission; lower is more important.
- Limits
- Every bound net-io enforces. Unset values take the defaults of the driver that runs the connection.
- Limits
Builder - Builds
Limits; every setter is optional. - Listen
Options - Options set on a listening socket before
bindandlisten. - Listener
Id - The index of a listener within one server.
- Listener
Info - Facts about one bound listener.
- Listener
Spec - One listener of a server.
- Manual
Clock - A clock that moves only when told to, for deterministic timeout tests.
- MinRate
- A minimum transfer rate, checked per direction while that direction is active.
- Monotonic
Clock Instant::now().- NoControl
- A control line that never changes:
epoch()is always 0. - NoGate
- The unset gate (no
buildexists for it): nameAllowAllto run without a gate. - NoTls
- The builder’s default acceptor: no listener may enable TLS with it.
- NoWork
- What runs per connection; the unset state (no
buildexists for it). - Noop
Sink - Discards every event; the builder’s default. Compiles to nothing.
- Output
- What the session wants written: a bounded queue of chunks.
- Output
Full - The output budget was reached; return
Step::Writeand continue after the flush. - Peer
Credentials - Who is on the other end of a local socket. A field the platform cannot report is
None. - Pipe
Name - A Windows pipe name in a fixed array (up to 256 UTF-16 units).
- Pool
Stats - Counts of one pool.
- Prefix
Key - “This address at this prefix length” as a fixed-size
Copyhash key. - Prefix
Policy - The prefix lengths used to group addresses.
- Pressure
- Adaptive deadlines under pressure (applied from
0.6.0). - Proxy
Facts - Facts copied from a trusted PROXY header into fixed arrays.
- Server
- A running server. Dropping it stops it (with a drain), so keep it and call
Server::wait_for_stopto run until a stop is requested. - Server
Builder - Builds a
Server. A builder without a gate or withoutsessions/handlerhas nobuildmethod: forgetting either is a compile error. - Server
Handle - A cloneable handle to a running server, safe to use from any thread.
- Session
Context - Everything a session may touch, for one call.
- Sessions
- What
ServerBuilder::sessionsproduces; programs never name it. - Simple
Control - A control line for programs without their own.
- Size
Class - A buffer size class: a power of two from 1 KiB to 1 MiB.
- Socket
Options - Live get and set on an open socket.
- Stats
- Counters summed over the workers.
- TcpConnection
- A connected TCP socket that carries its own limits.
- TcpListener
- A listening TCP socket created by net-io, so options that must precede
bindcan be set. - TcpOptions
- Options applied to each accepted or dialed TCP connection.
Noneleaves the OS default. - TlsError
- A TLS engine error: codes only, never secret material.
- TlsInfo
- TLS facts after the handshake, in fixed arrays.
- TlsProgress
- What one
TlsSession::stepdid. - Trusted
Proxies - The proxies whose claims about the client address are believed: PROXY
headers here, and
X-Forwarded-For/Forwardedin the web layer, which should use the same value. Keep it minimal: a trusted proxy can claim any client address. - Unix
Path - A Unix socket path in a fixed array (up to 108 bytes).
- Worker
Id - The index of a worker within one server.
- Write
Check - The write the gate is asked about.
Enums§
- Addr
Error - An error parsing or building an address value.
- Admit
Stage - When
Gate::admitruns. - Close
Reason - Why a connection closed. Every connection ends with exactly one.
- Coalesced
Kind - What was folded into a
Event::Coalesced. - Config
Reason - The rule a configuration value broke.
- Control
State - What the control line asks for.
- Direction
- A direction of transfer.
- Door
State - Whether the server is accepting.
- Driver
Kind - Which driver moves the bytes.
- Endpoint
- One end of a connection.
- Error
Class - The broad kind of a
NetError, for policy decisions. - Event
- One event: fixed size,
Copy, borrowing nothing. - Handoff
Error - Why a listener hand-off failed. Nothing is adopted on any error.
- Inherit
Error - Why inherited descriptors were refused.
- Limit
Kind - Which configured bound was hit.
- Linger
- What happens to unsent data at close.
- NetError
- The one error type of the crate.
- NoTls
Session - The session type of
NoTls; it has no values. - Origin
- How a connection came to exist.
- OsError
Class - The class of an OS error, without its message text.
- Phase
- Which deadlines run.
- Post
Error - Why a post was refused.
- Proxy
Error - Why a PROXY header was refused.
- Proxy
Mode - Whether a listener expects a PROXY protocol header.
- Proxy
Versions - Which PROXY protocol versions a listener accepts.
- Refusal
- How a connection is refused.
- Refusal
Cause - Why a connection was refused.
- Step
- What the session wants next.
- Swap
Error - Why a swap was refused.
- Timeout
Kind - Which deadline passed.
- TlsClose
Kind - Whether a TLS stream ended with
close_notify. - TlsEvent
- The next thing the driver does after a step.
- TlsFailure
- What failed in a TLS engine.
- Transport
- The kind of socket a connection uses.
Constants§
- VERSION
- Crate version string, populated by Cargo at build time.
Traits§
- Clock
- A source of monotonic time.
- Control
Line - A process-wide signal (shed, lockdown, drain, stop) that net-io’s workers read at the top of each loop, before each accept batch, and before each admission.
- Event
Sink - Receives events. Runs on worker threads: copy what you need and return.
- Gate
- Decides who may connect and whether bytes may still leave.
- Session
- A sans-IO protocol engine bound to one connection.
- Session
Factory - Creates one session per admitted connection. Any
Fn(&ConnectionInfo) -> Sis one. - TlsAcceptor
- Creates one
TlsSessionper admitted connection. - TlsSession
- One connection’s TLS state machine. Never blocks, never does IO.
- Workload
- What runs per connection:
Sessionsor aBlockingHandler. Sealed.
Functions§
- connect
- Connects with a total timeout of 10 s across every resolved address,
TCP_NODELAYon, and default limits (read and write timeouts 30 s). - listen
- Binds a TCP listener with safe defaults: backlog 1,024 (capped by the OS);
SO_REUSEADDRon Unix;SO_EXCLUSIVEADDRUSEon Windows; IPv6-only for IPv6 addresses; close-on-exec. The first resolved address that binds wins. - normalize
- Turns an IPv4-mapped IPv6 address (
::ffff:a.b.c.d) into the IPv4 address. - normalize_
socket normalizefor a socket address; the port is kept.- serve
- Starts a server on the blocking driver that runs
handleronce per connection on a pool worker, with default limits andAllowAllas the gate; the door is open on return.Ok(())closes the connection gracefully;Errcloses it abortively. - serve_
sessions - Starts a server that drives sans-IO
Sessions, with default limits andAllowAllas the gate; the door is open on return. AnyFn(&ConnectionInfo) -> Sis a factory.