Skip to main content

Crate tokio_tcp_pool

Crate tokio_tcp_pool 

Source
Expand description

§tokio-tcp-pool

Reuse TCP/TLS connections to one destination over a direct connection, SOCKS5, or HTTP CONNECT. Each acquired connection implements Tokio’s AsyncRead and AsyncWrite, so ordinary Tokio I/O works without a protocol adapter. It also implements futures_io::AsyncRead and futures_io::AsyncWrite for futures I/O.

A connection returns to the pool only through release(). Dropping it discards it. This lets a protocol implementation reuse a fully consumed response stream without accidentally recycling a failed or partially consumed exchange.

The pool creates connections on demand and starts no background tasks.

§Installation

Requires Rust 1.85 or newer and a Tokio runtime with I/O and time enabled.

[dependencies]
tokio-tcp-pool = "0.1.3"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util", "time"] }

§Acquiring and reusing a stream

Each pool has one immutable route. Cloning a pool shares its connections and limits. Separate destinations require separate pools.

use tokio_tcp_pool::{Pool, Route};
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

let pool = Pool::builder(Route::Direct {
    target: "127.0.0.1:9000".parse()?,
})
.max_open(8)
.connect_timeout(Duration::from_secs(5))
.idle_timeout(Duration::from_secs(60))
.max_lifetime(Duration::from_secs(3600))
.build()?;

let mut connection = pool.acquire().await?;
connection.write_all(b"ping").await?;
connection.flush().await?;
let mut response = [0; 4];
connection.read_exact(&mut response).await?;

// Release only when the application protocol permits another exchange.
connection.release();

discard() destroys the connection immediately. close().await attempts an orderly shutdown, including TLS close_notify, and then destroys it. Dropping a connection, including through ? or cancellation, has the same effect as discard(). Observed I/O errors, read EOF and write shutdown prevent reuse even if release() is called afterward.

§Proxies and TLS

The default features enable TLS, SOCKS5 and HTTP CONNECT. TLS is applied to the destination after establishing the transport. The caller supplies the rustls configuration, including trusted roots and any ALPN protocols.

use tokio_tcp_pool::{Pool, Route, Socks5Dns};

let pool = Pool::builder(Route::Socks5 {
    proxy: "127.0.0.1:1080".parse()?,
    target: "storage.example.com:443".parse()?,
    dns: Socks5Dns::Proxy,
})
.tls(client)
.build()?;

Socks5Dns::Proxy sends the hostname to the proxy without resolving it locally. Socks5Dns::Local resolves it for each new connection. Direct connections and proxy endpoints use the system resolver through Tokio. No DNS cache is added.

Route::HttpConnect { proxy, target } establishes an unauthenticated CONNECT tunnel over plain TCP. TLS always validates the destination identity, never the proxy identity. TlsConfig::server_name provides an explicit override when connecting to an IP address that serves a DNS certificate.

Use Route::Socks5Auth for a proxy that requires a username and password. Use Route::HttpConnectAuth to send Proxy-Authorization on each CONNECT request. ProxyAuthorization::basic encodes Basic credentials; new accepts a complete header value for another scheme.

use tokio_tcp_pool::{ProxyAuthorization, Route, Socks5Credentials, Socks5Dns};

let socks = Route::Socks5Auth {
    proxy: "127.0.0.1:1080".parse()?,
    target: "storage.example.com:443".parse()?,
    dns: Socks5Dns::Proxy,
    credentials: Socks5Credentials::new("user", "password")?,
};
let http = Route::HttpConnectAuth {
    proxy: "127.0.0.1:3128".parse()?,
    target: "storage.example.com:443".parse()?,
    authorization: ProxyAuthorization::basic("user", "password")?,
};
FeatureEffect
tlsrustls through tokio-rustls, with the ring provider and TLS 1.2/1.3
socks5SOCKS5 with optional username/password authentication
http-connectHTTP CONNECT with optional Proxy-Authorization, and httparse for response validation

For only TCP and pooling, set default-features = false. This removes TLS and HTTP parser dependencies.

§Limits and deadlines

max_open counts idle connections, active leases and connections being established. Acquisition waits when every slot is occupied. The default is 8.

connect_timeout covers the complete DNS, TCP, proxy and TLS establishment, with a default of 10 seconds. It starts after acquiring capacity. There is no implicit acquisition or read/write timeout. An application can wrap any operation in tokio::time::timeout.

Idle connections expire lazily, by default after 60 seconds. max_lifetime is optional and limits reuse without interrupting an active lease. Dropping the last pool handle closes idle connections; existing leases can finish but cannot return to the pool.

A nonblocking socket peek detects some closed idle connections without consuming application data. It cannot prove that a peer is alive, and the peer can fail immediately after the check. The next I/O operation can still fail.

See the guide for configuration and error semantics, the local echo example, and the acceptance coverage. No benchmarks are included in this version.

§License

MIT.

Re-exports§

pub use tokio_rustls::rustls;

Structs§

Connection
An opaque pooled byte stream implementing Tokio I/O and futures I/O.
Endpoint
A validated hostname or IP address and a TCP port.
EndpointError
An invalid endpoint, hostname, or port syntax.
HttpConnectStatusError
An HTTP proxy returned a non-success status.
Pool
A cheaply cloned pool for exactly one immutable route.
PoolBuilder
Builds a pool without performing DNS or network I/O.
PoolConfig
Connection limits and lazy expiration policy.
ProxyAuthorization
A validated value for the HTTP CONNECT Proxy-Authorization header.
Socks5Credentials
SOCKS5 username/password credentials (RFC 1929).
Socks5ReplyError
A SOCKS5 proxy refused the CONNECT request.
TlsConfig
Caller-supplied TLS trust, protocol, and optional identity configuration.

Enums§

AcquireError
Failure to acquire a usable connection.
ConfigError
A rejected pool configuration.
ConnectError
The stage at which connection establishment failed.
Host
An IP address or an ASCII DNS hostname.
ProxyAuthError
Invalid proxy credentials or authorization header.
Route
One immutable path to one destination.
Socks5Dns
Where a SOCKS5 target hostname is resolved.