| Crates.io | network-protocol |
| lib.rs | network-protocol |
| version | 1.0.1 |
| created_at | 2025-07-29 06:05:40.936417+00 |
| updated_at | 2026-01-23 13:26:17.510821+00 |
| description | Secure, high-performance protocol core with backpressure control, structured logging, timeout handling, TLS support, and comprehensive benchmarking for robust Rust networked applications and services. |
| homepage | https://github.com/jamesgober/network-protocol |
| repository | https://github.com/jamesgober/network-protocol |
| max_upload_size | |
| id | 1771963 |
| size | 498,237 |
A battle-hardened, security-first network protocol implementation for Rust. Built for production systems requiring both high performance and strong security guarantees. Features include comprehensive DoS protection, memory safety guarantees, and extensive testing infrastructure (77+ tests, fuzzing, stress tests).
Designed for zero-compromise reliability in high-load environments with built-in backpressure control, automatic connection health monitoring, and graceful degradation. Supports multiple transport modes with consistent APIs and TLS 1.2+/1.3 encryption by default.
unsafe in protocol core), fuzz-testedunwrap()/expect() confined to test code onlycargo-deny + cargo-audit in CI, vetted crypto dependencies (RustCrypto/Rustls)Threat Model: See THREAT_MODEL.md for comprehensive security analysis and attack scenarios.
ECDH) key exchangemTLS)LZ4, Zstd)TCP, Unix socket, TLS, cluster syncTOML files and environment variable overrides
REPS (Rust Efficiency & Performance Standards)
⚡ Rust Performance Collection
Add the library to your Cargo.toml:
[dependencies]
network-protocol = "1.0.1"
use network_protocol::utils::logging;
use network_protocol::service::daemon::{self, ServerConfig};
use network_protocol::config::NetworkConfig;
use network_protocol::protocol::dispatcher::Dispatcher;
use network_protocol::error::Result;
use std::sync::Arc;
use std::time::Duration;
use tracing::{info, warn};
#[tokio::main]
async fn main() -> Result<()> {
// Initialize structured logging
logging::init_logging(Some("info"), None).expect("Failed to initialize logging");
// Create a dispatcher
let dispatcher = Arc::new(Dispatcher::default());
// Register message handlers
dispatcher.register("ECHO", |msg| {
info!(message_type = "ECHO", "Processing echo request");
Ok(msg.clone())
});
// Option 1: Load configuration from file
// let config = NetworkConfig::from_file("config.toml")?.server;
// Option 2: Load configuration from environment variables
// let config = NetworkConfig::from_env()?.server;
// Option 3: Configure server with custom settings
let config = ServerConfig {
address: "127.0.0.1:9000".to_string(),
backpressure_limit: 100, // Limit pending messages
connection_timeout: Duration::from_secs(30),
heartbeat_interval: Duration::from_secs(15),
shutdown_timeout: Duration::from_secs(10),
max_connections: 1000,
};
// Start server with configuration
let server = daemon::new_with_config(config, dispatcher);
// Handle Ctrl+C for graceful shutdown
tokio::spawn(async move {
tokio::signal::ctrl_c().await.expect("Failed to listen for ctrl+c");
info!("Initiating graceful shutdown...");
server.shutdown(Some(Duration::from_secs(10))).await;
});
// Run server until stopped
info!("Server starting on 127.0.0.1:9000");
server.run().await
}
#[tokio::main]
async fn main() -> Result<()> {
// Generate or load certificates
let cert_config = TlsConfig {
cert_path: "server_cert.pem",
key_path: "server_key.pem",
ca_path: Some("ca_cert.pem"), // For mTLS
verify_client: true, // Enable mTLS
};
// Start TLS server
network_protocol::service::tls_daemon::start("127.0.0.1:9443", cert_config).await?;
Ok(())
}
use network_protocol::utils::logging;
use network_protocol::service::client::{self, ClientConfig};
use network_protocol::config::NetworkConfig;
use network_protocol::protocol::message::Message;
use network_protocol::error::ProtocolError;
use std::time::Duration;
use tracing::{info, error};
use tokio::time::timeout;
#[tokio::main]
async fn main() -> Result<(), ProtocolError> {
// Initialize structured logging
logging::init_logging(Some("info"), None)?;
// Option 1: Load configuration from file
// let config = NetworkConfig::from_file("config.toml")?.client;
// Option 2: Load from environment variables
// let config = NetworkConfig::from_env()?.client;
// Option 3: Configure client with custom settings
let config = ClientConfig {
address: "127.0.0.1:9000".to_string(),
connection_timeout: Duration::from_secs(5),
operation_timeout: Duration::from_secs(3),
response_timeout: Duration::from_secs(30),
heartbeat_interval: Duration::from_secs(15),
auto_reconnect: true,
max_reconnect_attempts: 3,
reconnect_delay: Duration::from_secs(1),
};
// Connect with timeout handling
info!("Connecting to server...");
let mut conn = match timeout(Duration::from_secs(5), client::connect_with_config(config)).await {
Ok(Ok(conn)) => conn,
Ok(Err(e)) => {
error!(error = ?e, "Failed to connect to server");
return Err(e);
}
Err(_) => {
error!("Connection timeout");
return Err(ProtocolError::Timeout);
}
};
info!("Connected successfully");
// Send message with timeout
match timeout(Duration::from_secs(3), conn.secure_send(Message::Echo("hello".into()))).await {
Ok(Ok(_)) => info!("Message sent successfully"),
Ok(Err(e)) => {
error!(error = ?e, "Failed to send message");
return Err(e);
}
Err(_) => {
error!("Send timeout");
return Err(ProtocolError::Timeout);
}
}
// Receive reply with timeout
let reply = match timeout(Duration::from_secs(3), conn.secure_recv()).await {
Ok(Ok(msg)) => msg,
Ok(Err(e)) => {
error!(error = ?e, "Failed to receive reply");
return Err(e);
}
Err(_) => {
error!("Receive timeout");
return Err(ProtocolError::Timeout);
}
};
info!(reply = ?reply, "Received reply");
// Close connection gracefully
conn.close().await?
Ok(())
}
use network_protocol::service::client::{self, TlsClientConfig};
use network_protocol::protocol::message::Message;
use network_protocol::error::Result;
use tracing::info;
#[tokio::main]
async fn main() -> Result<()> {
// Configure TLS client
let tls_config = TlsClientConfig {
cert_path: Some("client_cert.pem"), // For mTLS
key_path: Some("client_key.pem"), // For mTLS
ca_path: Some("ca_cert.pem"), // Server verification
server_name: "example.com", // SNI
};
// Connect with TLS
let mut conn = client::connect_tls(
"127.0.0.1:9443",
tls_config
).await?;
info!("Connected securely to TLS server");
// Communicate securely
conn.send(Message::Echo("secure message".into())).await?;
let reply = conn.receive().await?;
info!(response = ?reply, "Received secure response");
// Close connection properly
conn.close().await?
}
Built-in messages include:
HandshakeInit / HandshakeAckPing / PongEcho(String)UnknownYou can extend this list with your own enums or handlers.
Run microbenchmarks (Criterion):
cargo bench
Highlights:
See detailed results and recommendations in docs/PERFORMANCE.md.
Full test suite:
cargo test --all --all-features
Fuzz smoke tests (nightly):
rustup install nightly
cargo install cargo-fuzz
cargo +nightly fuzz build
cargo +nightly fuzz run fuzz_target_1 -- -max_total_time=30
cargo +nightly fuzz run fuzz_handshake -- -max_total_time=30
cargo +nightly fuzz run fuzz_compression -- -max_total_time=30
Stress tests:
cargo test --test stress -- --nocapture
cargo test --test concurrency -- --nocapture
Production build profile (already configured): LTO, codegen-units=1, opt-level=3, stripped symbols. Run with cargo build --release.
Register your own handlers with the dispatcher to process different message types:
use network_protocol::protocol::dispatcher::Dispatcher;
use network_protocol::protocol::message::Message;
use network_protocol::error::Result;
use std::sync::Arc;
use tracing::info;
// Create a dispatcher (typically shared between connections)
let dispatcher = Arc::new(Dispatcher::default());
// Basic handlers for built-in message types
dispatcher.register("PING", |_| {
info!("Ping received, sending pong");
Ok(Message::Pong)
});
dispatcher.register("ECHO", |msg| {
info!(content = ?msg, "Echo request received");
Ok(msg.clone())
});
// Custom message type handler with complex processing
dispatcher.register("DATA_PROCESS", |msg| {
if let Message::Custom(data) = msg {
// Process custom data
info!(bytes = data.len(), "Processing custom data");
// Return a response based on processing outcome
if data.len() > 100 {
Ok(Message::Custom(vec![1, 0, 1])) // Success code
} else {
Ok(Message::Custom(vec![0, 0, 1])) // Error code
}
} else {
// Handle unexpected message type
info!("Received incorrect message type for DATA_PROCESS");
Ok(Message::Unknown)
}
});
The dispatcher automatically routes incoming messages based on their message_type(). You can register handlers for both built-in message types and your own custom message types.
cargo test
Runs full unit + integration tests.
# Run all benchmarks with output
cargo test --test perf -- --nocapture
# Run specific benchmark
cargo test --test perf benchmark_roundtrip_latency -- --nocapture
cargo test --test perf benchmark_throughput -- --nocapture
| Metric | Result | Environment |
|---|---|---|
| Roundtrip Latency | <1ms avg | Local transport |
| Throughput | ~5,000 msg/sec | Standard payload |
| TLS Overhead | +2-5ms | With certificate validation |
The library includes comprehensive benchmarking tools that measure:
For detailed benchmarking documentation, see the API Reference.
src/
├── config.rs # Configuration structures and loading
├── core/ # Codec, packet structure
├── protocol/ # Handshake, heartbeat, message types
├── transport/ # TCP, Unix socket, TLS, Cluster
├── service/ # Daemon + client APIs
├── utils/ # Compression, crypto, timers
benches/ # Criterion benchmarks
fuzz/ # Fuzzing targets (cargo-fuzz)
tests/ # Integration and stress tests
Contributions welcome! Please:
cargo fmt && cargo clippy --workspace -- -D warnings before committingFor security issues, see SECURITY.md.
Documentation | API Reference | Performance | Principles
Licensed under the Apache License, version 2.0 (the "License"); you may not use this software, including, but not limited to the source code, media files, ideas, techniques, or any other associated property or concept belonging to, associated with, or otherwise packaged with this software except in compliance with the License.
You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the LICENSE file included with this project for the specific language governing permissions and limitations under the License.