Skip to main content

network_protocol/
error.rs

1//! # Error Types
2//!
3//! Comprehensive error handling for the network protocol.
4//!
5//! This module defines all error variants that can occur during protocol operations,
6//! from low-level I/O errors to high-level protocol violations.
7//!
8//! ## Error Categories
9//! - **I/O Errors**: Network and file system failures
10//! - **Protocol Errors**: Invalid packets, handshake failures, timeouts
11//! - **Cryptographic Errors**: Encryption/decryption failures
12//! - **TLS Errors**: Certificate and connection issues
13//! - **Compression Errors**: Decompression failures, size limit violations
14//!
15//! All errors implement `std::error::Error` for interoperability.
16//!
17//! ## Example Usage
18//! ```rust
19//! use network_protocol::error::{ProtocolError, Result};
20//! use std::fs::File;
21//! use std::io::Read;
22//! use tracing::{info, error};
23//!
24//! fn read_file(path: &str) -> Result<String> {
25//!     let mut file = File::open(path).map_err(ProtocolError::Io)?;
26//!     let mut contents = String::new();
27//!     file.read_to_string(&mut contents).map_err(ProtocolError::Io)?;
28//!     Ok(contents)
29//! }
30//!
31//! fn main() {
32//!     match read_file("example.txt") {
33//!         Ok(contents) => info!(contents, "Successfully read file"),
34//!         Err(e) => error!(error=%e, "Error reading file"),
35//!     }
36//! }
37//! ```
38
39use serde::{Deserialize, Serialize};
40use std::io;
41use thiserror::Error;
42
43/// Error message constants to reduce allocations in error paths.
44/// Static strings are borrowed, avoiding heap allocations for common error cases.
45pub mod constants {
46    /// Dispatcher-related error messages
47    pub const ERR_DISPATCHER_WRITE_LOCK: &str = "Failed to acquire write lock on dispatcher";
48    pub const ERR_DISPATCHER_READ_LOCK: &str = "Failed to acquire read lock on dispatcher";
49
50    /// Protocol validation errors
51    pub const ERR_INVALID_HEADER: &str = "Invalid protocol header";
52    pub const ERR_INVALID_PACKET: &str = "Invalid packet structure";
53    pub const ERR_OVERSIZED_PACKET: &str = "Packet exceeds maximum size";
54
55    /// Connection errors
56    pub const ERR_CONNECTION_CLOSED: &str = "Connection closed";
57    pub const ERR_CONNECTION_TIMEOUT: &str = "Connection timed out (no activity)";
58    pub const ERR_TIMEOUT: &str = "Operation timed out";
59
60    /// Cryptographic errors
61    pub const ERR_ENCRYPTION_FAILED: &str = "Encryption failed";
62    pub const ERR_DECRYPTION_FAILED: &str = "Decryption failed";
63
64    /// Compression errors
65    pub const ERR_COMPRESSION_FAILED: &str = "Compression failed";
66    pub const ERR_DECOMPRESSION_FAILED: &str = "Decompression failed";
67
68    /// Protocol negotiation errors
69    pub const ERR_UNSUPPORTED_VERSION: &str = "Unsupported protocol version";
70    pub const ERR_HANDSHAKE_FAILED: &str = "Handshake failed";
71    pub const ERR_UNEXPECTED_MESSAGE: &str = "Unexpected message type";
72
73    /// Security errors
74    pub const ERR_SECURITY_ERROR: &str = "Security violation detected";
75    pub const ERR_LOCK_POISONED: &str = "Synchronization primitive poisoned";
76
77    /// Handshake-specific errors
78    pub const ERR_SYSTEM_TIME: &str = "System time error: time went backwards";
79    pub const ERR_INVALID_TIMESTAMP: &str = "Invalid or stale timestamp";
80    pub const ERR_REPLAY_ATTACK: &str = "Replay attack detected - nonce/timestamp already seen";
81    pub const ERR_CLIENT_NONCE_NOT_FOUND: &str = "Client nonce not found";
82    pub const ERR_SERVER_NONCE_NOT_FOUND: &str = "Server nonce not found";
83    pub const ERR_CLIENT_SECRET_NOT_FOUND: &str = "Client secret not found";
84    pub const ERR_SERVER_SECRET_NOT_FOUND: &str = "Server secret not found";
85    pub const ERR_CLIENT_PUBLIC_NOT_FOUND: &str = "Client public key not found";
86    pub const ERR_SERVER_PUBLIC_NOT_FOUND: &str = "Server public key not found";
87    pub const ERR_NONCE_VERIFICATION_FAILED: &str = "Server failed to verify client nonce";
88    pub const ERR_SERVER_VERIFICATION_FAILED: &str = "Client failed to verify server nonce";
89}
90
91// ProtocolError is the primary error type for all protocol operations
92#[derive(Error, Debug, Serialize, Deserialize)]
93pub enum ProtocolError {
94    #[error("I/O error: {0}")]
95    #[serde(skip_serializing, skip_deserializing)]
96    Io(#[from] io::Error),
97
98    #[error("Serialization error: {0}")]
99    #[serde(skip_serializing, skip_deserializing)]
100    Serialization(#[from] bincode::Error),
101
102    #[error("Serialize error: {0}")]
103    SerializeError(String),
104
105    #[error("Deserialize error: {0}")]
106    DeserializeError(String),
107
108    #[error("Serialization error: {0}")]
109    SerializationError(String),
110
111    #[error("Transport error: {0}")]
112    TransportError(String),
113
114    #[error("Connection closed")]
115    ConnectionClosed,
116
117    #[error("Security error: {0}")]
118    SecurityError(String),
119
120    #[error("Invalid protocol header")]
121    InvalidHeader,
122
123    #[error("Unsupported protocol version: {0}")]
124    UnsupportedVersion(u8),
125
126    #[error("Packet too large: {0} bytes")]
127    OversizedPacket(usize),
128
129    #[error("Decryption failed")]
130    DecryptionFailure,
131
132    #[error("Encryption failed")]
133    EncryptionFailure,
134
135    #[error("Compression failed")]
136    CompressionFailure,
137
138    #[error("Decompression failed")]
139    DecompressionFailure,
140
141    #[error("Handshake failed: {0}")]
142    HandshakeError(String),
143
144    #[error("Unexpected message type")]
145    UnexpectedMessage,
146
147    #[error("Timeout occurred")]
148    Timeout,
149
150    #[error("Connection timed out (no activity)")]
151    ConnectionTimeout,
152
153    #[error("Configuration error: {0}")]
154    ConfigError(String),
155
156    #[error("Custom error: {0}")]
157    Custom(String),
158
159    #[error("TLS error: {0}")]
160    TlsError(String),
161}
162
163/// Type alias for Results using ProtocolError
164pub type Result<T> = std::result::Result<T, ProtocolError>;