open-net
open-net is a cross-platform asynchronous networking library for Rust. It gives your application one small owner object, OpenNet, and lets you create named clients for HTTP, WebSocket, and network-status monitoring.
This guide is written for a developer who is new to Rust or is using an AI coding assistant. Each example uses the public API of the crate. Copy one complete example first, make it compile, and then add optional pieces one at a time.
What you get
OpenNetowns the library runtime and named client instances.HttpClientprovides bounded asynchronous HTTP requests with buffered or streaming responses.WebSocketClientprovides WebSocket sessions, text/binary messages, bounded sending, reconnects, heartbeats, subscriptions, and optional request/response routing.NetStatusClientmonitors host reachability and IPv4/IPv6 capability.- Structured errors and logs let you classify failures with
ErrorKindand opt in to callback-based logs.
A useful mental model is:
OpenNet engine
├── named HttpClient(s)
├── named WebSocketClient(s)
└── named NetStatusClient(s)
A named client is a reusable handle. Creating it starts its worker, but does not make an HTTP request or open a WebSocket connection. The name is reserved until you call the matching destroy_* method or drop the engine.
Install it
open-net 0.1.0-beta.2 requires Rust 1.89 or newer. The repository also pins toolchain 1.89.0 in rust-toolchain.toml.
Add Tokio because your application owns the async entry point:
[]
= { = "0.1.0-beta.2", = ["http-client"] }
= { = "1", = ["macros", "rt-multi-thread", "fs", "io-util", "time"] }
= { = "1", = ["derive"] }
= "1"
Features are opt-in except for the default WebSocket feature:
| Dependency declaration | Included API |
|---|---|
open-net = "0.1.0-beta.2" |
WebSocket client plus network status |
open-net = { version = "0.1.0-beta.2", features = ["http-client"] } |
WebSocket, HTTP, and network status |
open-net = { version = "0.1.0-beta.2", default-features = false, features = ["http-client"] } |
HTTP and network status, without WebSocket |
open-net = { version = "0.1.0-beta.2", default-features = false } |
Network status and shared configuration only |
The feature name is http-client. There is no separate http feature. The default feature is ws-client.
Your first OpenNet program
All clients are created from an engine. OpenNet::new() validates the default configuration and returns a Result, so use ? in your application instead of unwrapping immediately.
use ;
async
OpenNet defaults to management queue capacities of 128 for asynchronous and synchronous submissions. You can change them before creating the engine:
use ;
The worker count must be between 1 and 256. Queue capacities must be non-zero and within Tokio's semaphore limit. Invalid values return an InvalidConfig error before workers are created.
Client names are trimmed and must not be empty. Names are unique per engine:
use ;
async
destroy_http_client, destroy_ws_client, and destroy_net_status_client wait for worker cleanup and release the name. Calling a client's own shutdown() closes its worker but does not release the engine registration; destroy the named client when you are finished.
HTTP client
The HTTP API is behind the http-client Cargo feature and is asynchronous (tokio). The examples use the public API in open_net::api::http; they are intentionally small enough to copy into a new binary and then grow with your application.
Add the dependency
In the application Cargo.toml:
[]
= { = "0.1.0-beta.2", = ["http-client"] }
= { = "1", = ["macros", "rt-multi-thread", "fs", "io-util", "time"] }
= { = "1", = ["derive"] }
# Only needed for the explicit builder/callback snippets below:
= "1"
= "1"
= "0.1"
open-net has ws-client in its default feature set, but http-client is separate. Listing the feature explicitly makes the dependency work even when the application disables default features. The first complete program needs only open-net, tokio, and serde; the explicit builder and callback snippets use the public bytes, http, and async-trait crates, so add those dependencies when copying those snippets.
Mental model: OpenNet owns named clients
Create one OpenNet value, then create a named HttpClient from a validated HttpClientConfig. The name is a registry key, not a URL and not a request ID. HttpClient is cloneable; clones share the same worker queues and shutdown state.
Requests use relative paths such as /users?limit=10. The client joins that path to base_url and rejects absolute URLs, //host paths, backslashes, fragments (#...), credentials, and cross-origin targets. Configure an origin such as https://api.example.com/v1/ and keep every request under that origin.
get, post, and request buffer the complete response body in memory. stream and sse expose response chunks as they arrive. There is currently no request-body upload stream API: request bodies are owned bytes::Bytes and are sent as a complete body. For a very large upload, split it into application-level chunks or use a separate upload mechanism; do not assume stream streams an upload.
Complete program: GET, POST, JSON, and cleanup
The following is a complete src/main.rs. It uses https://httpbin.org, so it needs network access when run. The important pattern is also valid for an internal API.
use ;
use OpenNet;
use Deserialize;
use Duration;
type BoxError = ;
async
HttpResponse contains status, headers, body (bytes::Bytes), attempts, and request_id. text() borrows the body as UTF-8 and returns a Utf8Error for binary data. json::<T>() uses serde_json; it does not check the status for you. Decode only after check_status unless your protocol intentionally uses error JSON.
The convenience methods are:
let response = client.get.await?;
let response = client.get_with_headers.await?;
let response = client.post.await?;
let response = client.post_with_headers.await?;
post accepts anything implementing AsRef<[u8]> (&[u8], Vec<u8>, a byte string, and so on). get_bytes and get_bytes_with_headers are compatibility aliases for get and get_with_headers.
Headers and request builder
Client-wide headers are copied onto every request. Request-specific headers replace a matching common header. Hop-by-hop headers such as host, connection, content-length, and transfer-encoding are rejected by configuration/dispatch.
use Bytes;
use ;
use HttpRequest;
let mut headers = new;
headers.insert;
let request = builder
.method
.path
.headers
.body
.build?;
let response = client.request.await?;
response.check_status?;
The builder starts with GET, empty headers, an empty body, and an inherited retry setting. Its compatibility retry_policy field starts at RetryPolicy::no_retry(); an inherited request uses the client's configured default. build() rejects an empty path; the client performs the same-origin path checks when the request is submitted. To add one header without constructing a HeaderMap, use .header("x-trace-id", "abc")? before .build().
Handling HTTP errors versus transport errors
There are two different failure layers:
Err(NetError)means the request could not produce a complete buffered response (bad configuration/path, DNS/I/O failure, timeout, cancellation, body limit, or exhausted retry attempts).Ok(HttpResponse)means the peer returned an HTTP response, even when its status is 400, 404, or 500. Inspectresponse.statusand callcheck_status(HttpStatusPolicy::Success2xx)(orAny/Exact(code)). The response body and headers remain available before you propagate the status error.
use HttpStatusPolicy;
match client.get.await
HttpStatusPolicy::Any accepts every status, Success2xx accepts the 2xx range, and Exact(StatusCode::NO_CONTENT) accepts one code. NetError::kind() and NetError::context().stage are useful when logging or classifying failures; never log secrets from request headers or bodies.
Complete program: streaming a large response
Use stream when buffering the complete response would be too expensive, or use sse for a server-sent-events endpoint. The response status and headers are available immediately; then repeatedly await next_chunk().
use ;
use OpenNet;
use Duration;
use AsyncWriteExt;
async
next_chunk() returns None at clean EOF, Some(Ok(Bytes)) for a chunk, and Some(Err(NetError)) for a terminal stream/transport error. A delivered stream response is never replayed, even before its first body poll. Errors are delivered once and subsequent polls return EOF. Absolute attempt/config timeouts and total deadlines continue while consumption is paused; total deadlines also cover admission. Capacity is returned on the terminal poll or drop, so a retained unpolled stream can keep drain() waiting. Call response.check_status(...) before writing data if non-2xx responses should not be saved. HttpClient::sse(path, headers) is a convenience for opening a GET stream with an Accept: text/event-stream header supplied by you; it does not parse SSE frames. Decode lines/events in your application.
Upload bodies and “streaming upload” expectations
The public request model is an owned body (Bytes). post, post_with_headers, and HttpRequest::builder().body(...) therefore buffer the upload before dispatch. HttpRequestTrait::get_req_body() is called once per transport attempt and must return equivalent bytes when retries are enabled; it is a replay hook, not a socket-level upload stream. There is no AsyncRead/chunk producer parameter in this API.
For a large payload, prefer a multipart/object-storage client designed for upload streaming, or divide the data into multiple application requests. If you must use this API, set a suitable max_response_bytes (that limit applies to received responses) and ensure your own body fits available memory.
Timeouts, response limits, retries, and backpressure
HttpClientConfig::new defaults to a 30-second timeout for each network attempt (headers and body, excluding SDK admission), an enabled 15-second TCP keepalive, 1024 MiB maximum buffered response body, and request/response/callback queue capacities of 128. Override them with:
let config = new?
.with_timeout?
.with_max_response_bytes?
.with_request_queue_capacity?
.with_response_queue_capacity?
.with_callback_queue_capacity?;
A zero timeout, zero limit, or zero queue capacity is rejected. with_tcp_keepalive(Duration::ZERO) disables keepalive; without_tcp_keepalive() is equivalent.
Retries
The safe default is no retry. RetryPolicy::new(n) allows up to n retries (capped at 32), retries transient statuses 408, 425, 429, 500, 502, 503, and 504, and retries transient transport failures. GET/HEAD/OPTIONS/PUT/DELETE are considered idempotent. POST and other non-idempotent methods require both .with_non_idempotent(true) and a replayable body.
Attach a policy to a specific request:
use ;
use Duration;
let policy = new
.with_max_delay;
let request = builder
.path
.retry_policy
.build?;
let response = client.request.await?;
For a custom request sent through send_with_options, use HttpRequestOptions::with_retry_policy(...) and, when appropriate, .with_replayable_body(true). A non-idempotent request is never made retryable merely by setting a retry count; explicitly opt in and return the same body on every attempt. Retry backoff can be interrupted by cancellation. A streaming response is never replayed after it has been returned to the caller.
get, post, request, and stream inherit HttpClientConfig.default_retry_policy unless the request explicitly replaces or disables it. A one-attempt default still supplies its timeout, deadline, and observer. Use HttpRequestBuilder::retry_setting(RetrySetting::None) or an explicit retry_policy(RetryPolicy::no_retry()) to disable inheritance for a concrete request. Callback submissions can use HttpRequestOptions::with_retry_policy(RetryPolicy::no_retry()) for the same explicit override.
Queue admission and send_wait
send fails quickly when the bounded request queue cannot admit a job. send_wait(...).await waits for capacity (backpressure) and returns a client-local HttpRequestId after admission. An accepted request owns exactly one terminal callback, including during shutdown. Keep the returned ID if you need cancellation or correlation.
Cancellation and lifecycle
let request_id = client.send?;
client.cancel?; // best effort if a callback is already running
client.cancel_all?; // cancel every accepted request owned by this client
client.drain.await?; // wait for admitted requests; admission stays open
client.shutdown_graceful.await?; // cancel accepted requests, then join workers
client.shutdown().await closes admission and waits for worker shutdown. client.request_shutdown() only publishes the shutdown signal and returns immediately; use it when synchronous notification is required, then await shutdown() if you need completion. Cloned handles observe the same shutdown. Finally, OpenNet::destroy_http_client(name).await permanently removes the named registry entry after the worker exits. Destroying a client is the normal application cleanup path.
Optional advanced API: custom callback request
Most applications should use request, get, post, or stream. Implement HttpRequestTrait only when you need a callback that runs on the client's callback lane, custom request state, or access to a request ID without awaiting a response future. This is a fragment: enable the http-client feature and import bytes/http as shown. The async_trait attribute is re-exported by open_net.
use Bytes;
use HeaderMap;
use ;
let request_id: HttpRequestId = client.send_with_options?;
println!;
A callback is invoked once after the final attempt, including cancellation or an error. Keep callbacks short and non-blocking; they run on a bounded callback lane. The trait's on_response_headers hook can observe headers before the final callback. get_req_body() may be called again for retries, so never consume a one-shot reader there.
TLS, proxy, and security configuration
HttpClientConfig::new uses reqwest's rustls transport. HttpTlsConfig can append or replace built-in roots and can configure a PEM client identity; all PEM is validated before worker startup. HttpProxyConfig configures an explicit HTTP CONNECT proxy. Environment proxy variables are disabled by default; opt in with .with_environment_proxy(true). Keep credentials out of URLs and do not print bodies/authorization headers in logs.
The response body limit is a safety bound for buffered responses. Streaming responses are consumed incrementally, but still surface transport/framing errors through next_chunk().
WebSocket client
WebSocketClient is OpenNet's long-lived WebSocket API. It separates a reusable
client from a logical connection session:
- The client owns configuration and the background worker. It can be cloned and
is shut down permanently with
client.shutdown().await. - A session owns one connection intent (including automatic reconnects). Keep the
Sessionvalue alive while the feature is running. Dropping it requests cancellation, even if aSender, receiver, or request handle was cloned from it. Callsession.close().awaitfor an orderly close, then destroy the client when the client name is no longer needed. - A client has at most one active session across all of its clones. Close the old session and wait for it to finish before starting another target.
These examples use Tokio:
[]
= { = "0.1.0-beta.2", = ["ws-client"] }
= { = "1", = ["macros", "rt-multi-thread", "time"] }
The ws-client feature is enabled by default in this release. A WebSocket URL
must use ws:// or wss:// and include a host.
The smallest working program (text echo)
The following is a complete program. Run it against an ordinary WebSocket echo
server: the server must send each received WebSocket data message back unchanged.
It sends the text hello, waits for the echoed data message, and closes cleanly.
use ;
async
sender.send(...) waits for the local WebSocket write to finish. A successful
local write is not an acknowledgement that the server processed the application
message. For a trackable write, use sender.enqueue(...) and await
receipt.written(); for a server response, use the request API below.
Data messages and application protocols
WebSocket defines text and binary payloads, not JSON, topics, authentication messages, or request IDs. OpenNet does not add an application protocol. Convert your own values explicitly:
use Message;
let text = text;
let bytes = binary;
assert_eq!;
assert_eq!;
IncomingMessage::message() returns a borrowed Message. Match on
message.as_text() when the server's protocol is text, or use as_bytes() for
binary. Parse JSON with your chosen serde type, and validate fields before using
them. A text payload from the server is not automatically a Rust String or a
deserialized struct.
Receiving with a subscription
take_messages() takes the one initial inbox created by default in
ConnectOptions. It can only be taken once. For additional independent
receivers, call subscribe_messages with a bounded ReceiveOptions:
use ;
use ;
async
Every receive queue is bounded by both item count and payload bytes. The default
is 256 messages or 64 MiB, with ReceiveOverflow::Disconnect: if a consumer
cannot keep up, the current connection is failed rather than silently losing
business messages. DropOldest keeps the connection alive but recv() reports a
lag error, so the application must resynchronize. include_control_frames is
false by default; set it to true only when you need to inspect Ping/Pong/Close
frames.
For callbacks, convert a receiver into a Subscription. The callback must be
Send + Sync + 'static because it runs on OpenNet's callback pool; keep the
returned subscription alive for as long as the callback is wanted:
use ;
use ReceiveOptions;
async
The same pattern is available for lifecycle events (subscribe_events or
on_event), state snapshots (watch_state or on_state), and terminal task
events (subscribe_tasks or on_task). session.state() is a point-in-time
snapshot; session.wait_connected().await waits for a usable physical
connection, and session.closed().await waits for the terminal session result.
One-way messaging versus request/response
For notifications, telemetry, and commands that do not have a correlated reply,
leave the default ResponseRouting::Disabled and use Sender. Calling
session.requests() in that mode returns RoutingDisabled.
For request/response, your wire format must contain a request identifier and you
must teach OpenNet how to classify incoming messages. The following complete
example uses the deliberately simple protocol request-id|payload; an echo
server returns the same string. A production protocol should parse its real JSON
or binary envelope and validate IDs before returning Final.
use ;
use ;
;
async
RequestClient::execute registers the request, sends it, and waits for the
ResponseRoute::Final message matching that RequestId. A successful response
means that OpenNet routed a message to this request; it does not prove that a
separate business transaction was committed. Set ResponseRoute::Intermediate
for progress messages and return Final only for the terminal response.
Request IDs are application-level values and must be encoded in the payload or
headers understood by the server.
Use ResponseRouting::Manual when classification needs application state or
when a dedicated reader owns the protocol. Obtain a resolver with
session.response_resolver(), enqueue a request, then pass each matching
IncomingMessage and receipt.handle().registration() to
resolver.resolve(...). Resolved completes the request; StaleOrFinished
means it already timed out or completed; ForeignOrigin means the registration
belongs to another session. Manual routing requires a lossless initial inbox, so
do not combine it with ReceiveOverflow::DropOldest.
Here is the same id|body protocol with manual dispatch. This is useful when a
reader must apply application state before deciding whether a message is the
final response:
use ;
use ;
async
Reconnect, timeouts, and heartbeats
ConnectOptions::new uses these defaults:
- handshake timeout: 10 seconds per attempt;
- first-connection timeout: 30 seconds for all attempts and backoff (
Noneremoves this extra overall limit); - reconnect:
BackoffConfig { max_retries: 6, initial_delay: 250 ms, max_delay: 8 s, max_elapsed: Some(30 s) }. Delays use full jitter from zero to each exponential cap.
The same session follows its reconnect policy after a later disconnect. To fail
immediately instead, set options.reconnect = ReconnectPolicy::Disabled. A
session reconnect does not change its logical session ID; each physical
connection has its own connection ID in events and responses.
The client config enables WebSocket Ping/Pong heartbeats by default:
WebSocketClientConfig::default().heartbeat is Some(HeartbeatConfig { interval: 20 s, pong_timeout: 45 s }). Set heartbeat = None only when the
server or deployment supplies its own liveness mechanism. Heartbeat control
frames are separate from application text messages and are excluded from receive
queues unless include_control_frames is enabled.
Sending has separate policies. SendOptions::default() rejects a message when
the session is disconnected, uses a 10-second write timeout, and never retries a
message that was already attempted. DisconnectedPolicy::WaitForReconnect can
hold an unsent message until the session reconnects. SendRetryPolicy::Idempotent
allows bounded redelivery only when your server operation is safe to repeat; do
not enable it for non-idempotent payments or mutations without an idempotency key.
Proxy and TLS policy
Network policy is explicit and immutable for each client. The default is a direct connection with built-in WebPKI roots; OpenNet does not read proxy environment variables. Configure a proxy when creating the client:
use ;
use ;
async
ProxyConfig::http_connect accepts only an HTTP CONNECT endpoint. Basic proxy
credentials are sent to the proxy and should be protected with a trusted network
path; a plain HTTP proxy does not encrypt those credentials, even when the target
URL is wss://. For private CAs, build a TlsConfig with
TlsConfig::with_root_certificates(pem, RootCertificateMode::Append) (or
Replace when intentionally removing WebPKI roots), then pass it with
NetworkConfig::with_tls. Use TlsConfig::with_client_identity for mutual TLS.
Certificates and private keys are validated in memory; never commit private key
material to source control.
Closing and errors
Handle every Result. Common lifecycle errors include SessionAlreadyExists,
RoutingDisabled, QueueFull, TimedOut, Cancelled, and Closed. A receive
error can represent lag or a source/connection failure; inspect it before deciding
whether to resubscribe or terminate. session.cancel() requests cooperative
cancellation and session.closed().await reports the final SessionEnd.
At application shutdown, stop producing work, await important message receipts or
responses, call session.close().await, then call client.shutdown().await (or
net.destroy_ws_client(name).await to also release the engine's name). Shutdown
does not promise that queued messages were processed by the peer, so use your
protocol's acknowledgement when business delivery matters.
Network status monitoring
Network status is always available, even when ws-client and http-client are disabled. Each OpenNet owns one shared network monitor. Its named status clients, network-aware WebSocket clients, and HTTP observations use the same network facts; separate engines have independent monitors. Each named status client keeps its own start, stop, shutdown, and subscription lifecycle. Stopping one client leaves other active consumers running. The first start() waits for a coherent snapshot:
use ;
async
reachability and ip_stack can be None while the monitor is stopped or before an observation exists. on_change is a callback alternative; retain its returned Subscription for as long as you need updates.
With the http-client feature, HTTP clients created by OpenNet receive its network context automatically. network_snapshot() reads committed cached facts without starting, refreshing, or retrying the monitor. subscribe_network_status() and on_network_status_change() register an observation synchronously and start monitoring in the background. Initialization errors appear as MonitorState::Failed in the stream; a new observation registration can request another attempt. Monitoring does not pause or reject HTTP requests.
use ;
use ;
async
HTTP clones and all active observations on one logical client share one monitoring lease. Dropping or unsubscribing the last observation releases that lease; later subscriptions can start observing again. Converting a receiver with into_callback transfers its existing observation. HTTP shutdown and the final client drop close that client's observations, while other clients remain independent. A retained receiver or callback handle does not keep the HTTP workers alive, although an application callback that captures a client clone does retain that clone.
HTTP shutdown waits for request workers and request callbacks, and releases its network observation resources. It does not wait for a running network callback. A network callback can therefore call HTTP shutdown; call Subscription::close from outside the callback when you need to wait for its retirement. Calling close from that same callback would wait for itself.
The synchronous HttpClient::new(config, thread_name) constructor still creates standalone request workers. Its network observation APIs return InvalidConfig because it has no network context. An explicitly supplied context always belongs to its original engine: dropping that engine closes network observation and preserves the final cached state, while standalone HTTP request workers keep their independent lifecycle.
On Linux (kernel 5.x and later), monitoring uses kernel interface/route information through Netlink and procfs; it needs neither NetworkManager nor external commands or root privileges. Linux also requests a fresh interface sample every two seconds to recover from missing link notifications. Updates include the underlying monitor's debounce and scheduling delay.
Linux Available means a default-route interface has an operational link and a
usable local address. IPv6 defaults with and without a gateway are supported.
This is a host configuration observation, not an Internet or service probe.
ip_stack continues to describe the local address capability reported by
netwatch, so a link outage can change reachability without changing ip_stack.
network_name is None on Linux. Restricted environments must permit interface
queries and access to procfs; query failures are reported through the existing
monitor error/lifecycle API.
The Linux network-change regression test creates its own user/network namespace
and modifies only interfaces inside it. Run it explicitly on a Linux test host
with unshare, ip (iproute2), and unprivileged user/network namespaces enabled:
The test fails if namespace isolation or network configuration is unavailable;
ordinary cargo test leaves it ignored. The library itself does not depend on
these test tools.
Logging and errors
The library does not print or persist logs automatically. Register a filtered callback when debugging a problem:
use ;
The returned LogSubscription must stay alive. It owns a bounded queue; call dropped_count() when diagnosing overload. Callbacks run sequentially on the subscription's worker thread.
Use NetError like this:
use ;
ErrorKind is non-exhaustive, so include a wildcard arm. error.context() contains the processing stage and optional protocol identifiers. error.config_error() exposes a configuration field and reason when the error is InvalidConfig. The default Display and Debug representations intentionally redact arbitrary underlying source text, response bodies, credentials, and peer details; call source() only when you explicitly need the underlying cause.
Vibecoding checklist
When asking an AI coding assistant to add networking code, include these constraints in the prompt:
- Use the public API (
OpenNet,open_net::api::http, andopen_net::ws); do not importsrc/moduleorsrc/inner. - Preserve the owning
Sessionuntil all WebSocket sends and receives finish. - Treat an HTTP 4xx/5xx as
Ok(HttpResponse)untilcheck_status(...)is called. - Add an explicit retry policy only when the operation is safe to repeat.
- Keep queue limits bounded and decide whether
send()orsend_wait()matches the desired backpressure. - Keep
Subscription,MessageReceiver, andLogSubscriptionvariables alive; dropping them unsubscribes or stops delivery. - Close the session/client, then destroy the named client so its name can be reused.
- Never paste passwords, private keys, or access tokens into source code or diagnostic logs.
- Ask the assistant to compile after each small change with
cargo check.
Build and test
From the crate directory:
The examples shipped with the crate are useful smoke tests: examples_messages demonstrates one-way traffic, and examples_requests demonstrates protocol-routed responses.
Those commands require a compatible WebSocket echo service. Network tests that depend on a local server, TLS certificates, or a particular operating system need the environment described by the repository's test fixtures.
License
open-net is released under the Apache-2.0 license. See LICENSE.