Skip to main content

Crate net_io

Crate net_io 

Source
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.
AllowAll
The explicit “no gate”: admits every connection in Lane(0) with GateTag(0) and never denies.
BlockingHandler
What ServerBuilder::handler produces; programs never name it.
Buffer
A byte buffer from a pool: a fixed capacity (its size class) and a filled length.
BufferPool
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.
ConnectOptions
Options for an outbound connection.
ConnectionId
The identity of one connection, unique and never reused within a process.
ConnectionInfo
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.
DrainReport
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.
KillHandle
Closes one connection abortively from any thread.
KillReason
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.
LimitsBuilder
Builds Limits; every setter is optional.
ListenOptions
Options set on a listening socket before bind and listen.
ListenerId
The index of a listener within one server.
ListenerInfo
Facts about one bound listener.
ListenerSpec
One listener of a server.
ManualClock
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.
MonotonicClock
Instant::now().
NoControl
A control line that never changes: epoch() is always 0.
NoGate
The unset gate (no build exists for it): name AllowAll to 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 build exists for it).
NoopSink
Discards every event; the builder’s default. Compiles to nothing.
Output
What the session wants written: a bounded queue of chunks.
OutputFull
The output budget was reached; return Step::Write and continue after the flush.
PeerCredentials
Who is on the other end of a local socket. A field the platform cannot report is None.
PipeName
A Windows pipe name in a fixed array (up to 256 UTF-16 units).
PoolStats
Counts of one pool.
PrefixKey
“This address at this prefix length” as a fixed-size Copy hash key.
PrefixPolicy
The prefix lengths used to group addresses.
Pressure
Adaptive deadlines under pressure (applied from 0.6.0).
ProxyFacts
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_stop to run until a stop is requested.
ServerBuilder
Builds a Server. A builder without a gate or without sessions/handler has no build method: forgetting either is a compile error.
ServerHandle
A cloneable handle to a running server, safe to use from any thread.
SessionContext
Everything a session may touch, for one call.
Sessions
What ServerBuilder::sessions produces; programs never name it.
SimpleControl
A control line for programs without their own.
SizeClass
A buffer size class: a power of two from 1 KiB to 1 MiB.
SocketOptions
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 bind can be set.
TcpOptions
Options applied to each accepted or dialed TCP connection. None leaves 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::step did.
TrustedProxies
The proxies whose claims about the client address are believed: PROXY headers here, and X-Forwarded-For / Forwarded in the web layer, which should use the same value. Keep it minimal: a trusted proxy can claim any client address.
UnixPath
A Unix socket path in a fixed array (up to 108 bytes).
WorkerId
The index of a worker within one server.
WriteCheck
The write the gate is asked about.

Enums§

AddrError
An error parsing or building an address value.
AdmitStage
When Gate::admit runs.
CloseReason
Why a connection closed. Every connection ends with exactly one.
CoalescedKind
What was folded into a Event::Coalesced.
ConfigReason
The rule a configuration value broke.
ControlState
What the control line asks for.
Direction
A direction of transfer.
DoorState
Whether the server is accepting.
DriverKind
Which driver moves the bytes.
Endpoint
One end of a connection.
ErrorClass
The broad kind of a NetError, for policy decisions.
Event
One event: fixed size, Copy, borrowing nothing.
HandoffError
Why a listener hand-off failed. Nothing is adopted on any error.
InheritError
Why inherited descriptors were refused.
LimitKind
Which configured bound was hit.
Linger
What happens to unsent data at close.
NetError
The one error type of the crate.
NoTlsSession
The session type of NoTls; it has no values.
Origin
How a connection came to exist.
OsErrorClass
The class of an OS error, without its message text.
Phase
Which deadlines run.
PostError
Why a post was refused.
ProxyError
Why a PROXY header was refused.
ProxyMode
Whether a listener expects a PROXY protocol header.
ProxyVersions
Which PROXY protocol versions a listener accepts.
Refusal
How a connection is refused.
RefusalCause
Why a connection was refused.
Step
What the session wants next.
SwapError
Why a swap was refused.
TimeoutKind
Which deadline passed.
TlsCloseKind
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.
ControlLine
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.
EventSink
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.
SessionFactory
Creates one session per admitted connection. Any Fn(&ConnectionInfo) -> S is one.
TlsAcceptor
Creates one TlsSession per admitted connection.
TlsSession
One connection’s TLS state machine. Never blocks, never does IO.
Workload
What runs per connection: Sessions or a BlockingHandler. Sealed.

Functions§

connect
Connects with a total timeout of 10 s across every resolved address, TCP_NODELAY on, 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_REUSEADDR on Unix; SO_EXCLUSIVEADDRUSE on 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
normalize for a socket address; the port is kept.
serve
Starts a server on the blocking driver that runs handler once per connection on a pool worker, with default limits and AllowAll as the gate; the door is open on return. Ok(()) closes the connection gracefully; Err closes it abortively.
serve_sessions
Starts a server that drives sans-IO Sessions, with default limits and AllowAll as the gate; the door is open on return. Any Fn(&ConnectionInfo) -> S is a factory.