Skip to main content

saorsa_core/
error.rs

1// Copyright (c) 2025 Saorsa Labs Limited
2
3// This software is dual-licensed under:
4// - GNU Affero General Public License v3.0 or later (AGPL-3.0-or-later)
5// - Commercial License
6//
7// For AGPL-3.0 license, see LICENSE-AGPL-3.0
8// For commercial licensing, contact: david@saorsalabs.com
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under these licenses is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
14// This program is distributed in the hope that it will be useful,
15// but WITHOUT ANY WARRANTY; without even the implied warranty of
16// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17// GNU Affero General Public License for more details.
18
19// You should have received a copy of the GNU Affero General Public License
20// along with this program. If not, see <https://www.gnu.org/licenses/>.
21
22//! Comprehensive error handling framework for P2P Foundation
23//!
24//! This module provides a zero-panic error handling system designed to replace 568 unwrap() calls
25//! throughout the codebase with proper error propagation and context.
26//!
27//! # Features
28//!
29//! - **Type-safe error hierarchy**: Custom error types for all subsystems
30//! - **Zero-cost abstractions**: Optimized for performance with Cow<'static, str>
31//! - **Context propagation**: Rich error context without heap allocations
32//! - **Structured logging**: JSON-based error reporting for production monitoring
33//! - **Anyhow integration**: Seamless integration for application-level errors
34//! - **Recovery patterns**: Built-in retry and circuit breaker support
35//!
36//! # Usage Examples
37//!
38//! ## Basic Error Handling
39//!
40//! ```rust,ignore
41//! use saorsa_core::error::{P2PError, P2pResult};
42//! use std::net::SocketAddr;
43//!
44//! fn connect_to_peer(addr: SocketAddr) -> P2pResult<()> {
45//!     // Use proper error propagation instead of unwrap()
46//!     // socket.connect(addr).map_err(|e| P2PError::Network(...))?;
47//!     Ok(())
48//! }
49//! ```
50//!
51//! ## Adding Context
52//!
53//! ```rust,ignore
54//! use saorsa_core::error::{P2PError, P2pResult};
55//! use saorsa_core::error::ErrorContext;
56//!
57//! fn load_config(path: &str) -> P2pResult<String> {
58//!     std::fs::read_to_string(path)
59//!         .context("Failed to read config file")
60//! }
61//! ```
62//!
63//! ## Structured Error Logging
64//!
65//! ```rust,ignore
66//! use saorsa_core::error::P2PError;
67//!
68//! fn handle_error(err: P2PError) {
69//!     // Log with tracing
70//!     tracing::error!("Error occurred: {}", err);
71//! }
72//! ```
73//!
74//! ## Migration from unwrap()
75//!
76//! ```rust,ignore
77//! use saorsa_core::error::P2PError;
78//!
79//! // Before:
80//! // let value = some_operation().unwrap();
81//!
82//! // After - use ? operator with proper error types:
83//! // let value = some_operation()?;
84//!
85//! // For Option types:
86//! // let value = some_option.ok_or_else(|| P2PError::Internal("Missing value".into()))?;
87//! ```
88
89use serde::{Deserialize, Serialize};
90use smallvec::SmallVec;
91use std::borrow::Cow;
92use std::collections::HashMap;
93use std::io;
94use std::net::SocketAddr;
95use std::time::Duration;
96use thiserror::Error;
97
98// Metrics imports would go here when implemented
99// #[cfg(feature = "metrics")]
100// use prometheus::{IntCounterVec, register_int_counter_vec};
101
102/// Core error type for the P2P Foundation library
103#[derive(Debug, Error)]
104pub enum P2PError {
105    // Network errors
106    #[error("Network error: {0}")]
107    Network(#[from] NetworkError),
108
109    // DHT errors
110    #[error("DHT error: {0}")]
111    Dht(#[from] DhtError),
112
113    // Identity errors
114    #[error("Identity error: {0}")]
115    Identity(#[from] IdentityError),
116
117    // Cryptography errors
118    #[error("Cryptography error: {0}")]
119    Crypto(#[from] CryptoError),
120
121    // Storage errors
122    #[error("Storage error: {0}")]
123    Storage(#[from] StorageError),
124
125    // Transport errors
126    #[error("Transport error: {0}")]
127    Transport(#[from] TransportError),
128
129    // Configuration errors
130    #[error("Configuration error: {0}")]
131    Config(#[from] ConfigError),
132
133    // Security errors
134    #[error("Security error: {0}")]
135    Security(#[from] SecurityError),
136
137    // Bootstrap errors
138    #[error("Bootstrap error: {0}")]
139    Bootstrap(#[from] BootstrapError),
140
141    // Generic IO error
142    #[error("IO error: {0}")]
143    Io(#[from] io::Error),
144
145    // Serialization/Deserialization errors
146    #[error("Serialization error: {0}")]
147    Serialization(Cow<'static, str>),
148
149    // Validation errors
150    #[error("Validation error: {0}")]
151    Validation(Cow<'static, str>),
152
153    // Timeout errors
154    #[error("Operation timed out after {0:?}")]
155    Timeout(Duration),
156
157    // Resource exhaustion
158    #[error("Resource exhausted: {0}")]
159    ResourceExhausted(Cow<'static, str>),
160
161    // Generic internal error
162    #[error("Internal error: {0}")]
163    Internal(Cow<'static, str>),
164
165    // Encoding errors
166    #[error("Encoding error: {0}")]
167    Encoding(Cow<'static, str>),
168
169    // Record too large errors
170    #[error("Record too large: {0} bytes (max 512)")]
171    RecordTooLarge(usize),
172
173    // Time-related error
174    #[error("Time error")]
175    TimeError,
176
177    // Invalid input parameter
178    #[error("Invalid input: {0}")]
179    InvalidInput(String),
180
181    // WebRTC bridge errors
182    #[error("WebRTC error: {0}")]
183    WebRtcError(String),
184
185    // Trust system errors
186    #[error("Trust error: {0}")]
187    Trust(Cow<'static, str>),
188}
189
190/// Network-related errors
191#[derive(Debug, Error)]
192pub enum NetworkError {
193    #[error("Connection failed to {addr}: {reason}")]
194    ConnectionFailed {
195        addr: SocketAddr,
196        reason: Cow<'static, str>,
197    },
198
199    #[error("Connection closed unexpectedly for peer: {peer_id}")]
200    ConnectionClosed { peer_id: Cow<'static, str> },
201
202    #[error("Invalid network address: {0}")]
203    InvalidAddress(Cow<'static, str>),
204
205    #[error("Peer not found: {0}")]
206    PeerNotFound(Cow<'static, str>),
207
208    #[error("Peer disconnected - peer: {peer}, reason: {reason}")]
209    PeerDisconnected { peer: String, reason: String },
210
211    #[error("Network timeout")]
212    Timeout,
213
214    #[error("Too many connections")]
215    TooManyConnections,
216
217    #[error("Protocol error: {0}")]
218    ProtocolError(Cow<'static, str>),
219
220    #[error("Bind error: {0}")]
221    BindError(Cow<'static, str>),
222}
223
224/// DHT-related errors
225#[derive(Debug, Error)]
226pub enum DhtError {
227    #[error("Key not found: {0}")]
228    KeyNotFound(Cow<'static, str>),
229
230    #[error("Store operation failed: {0}")]
231    StoreFailed(Cow<'static, str>),
232
233    #[error("Invalid key format: {0}")]
234    InvalidKey(Cow<'static, str>),
235
236    #[error("Routing table full")]
237    RoutingTableFull,
238
239    #[error("No suitable peers found")]
240    NoPeersFound,
241
242    #[error("Replication failed: {0}")]
243    ReplicationFailed(Cow<'static, str>),
244
245    #[error("Query timeout")]
246    QueryTimeout,
247
248    #[error("Routing error: {0}")]
249    RoutingError(Cow<'static, str>),
250
251    #[error("Storage failed: {0}")]
252    StorageFailed(Cow<'static, str>),
253
254    #[error("Insufficient replicas: {0}")]
255    InsufficientReplicas(Cow<'static, str>),
256}
257
258/// Identity-related errors
259#[derive(Debug, Error)]
260pub enum IdentityError {
261    #[error("Invalid three-word address: {0}")]
262    InvalidThreeWordAddress(Cow<'static, str>),
263
264    #[error("Invalid four-word address: {0}")]
265    InvalidFourWordAddress(Cow<'static, str>),
266
267    #[error("Identity not found: {0}")]
268    IdentityNotFound(Cow<'static, str>),
269
270    #[error("Identity already exists: {0}")]
271    IdentityExists(Cow<'static, str>),
272
273    #[error("Invalid signature")]
274    InvalidSignature,
275
276    #[error("Invalid canonical bytes")]
277    InvalidCanonicalBytes,
278
279    #[error("Membership conflict")]
280    MembershipConflict,
281
282    #[error("Missing group key")]
283    MissingGroupKey,
284
285    #[error("Website root update refused")]
286    WebsiteRootUpdateRefused,
287
288    #[error("Key derivation failed: {0}")]
289    KeyDerivationFailed(Cow<'static, str>),
290
291    #[error("Permission denied")]
292    PermissionDenied,
293
294    #[error("Invalid peer ID: {0}")]
295    InvalidPeerId(Cow<'static, str>),
296
297    #[error("Invalid format: {0}")]
298    InvalidFormat(Cow<'static, str>),
299
300    #[error("System time error: {0}")]
301    SystemTime(Cow<'static, str>),
302
303    #[error("Not found: {0}")]
304    NotFound(Cow<'static, str>),
305
306    #[error("Verification failed: {0}")]
307    VerificationFailed(Cow<'static, str>),
308
309    #[error("Insufficient entropy")]
310    InsufficientEntropy,
311
312    #[error("Access denied: {0}")]
313    AccessDenied(Cow<'static, str>),
314}
315
316/// Cryptography-related errors
317#[derive(Debug, Error)]
318pub enum CryptoError {
319    #[error("Encryption failed: {0}")]
320    EncryptionFailed(Cow<'static, str>),
321
322    #[error("Decryption failed: {0}")]
323    DecryptionFailed(Cow<'static, str>),
324
325    #[error("Invalid key length: expected {expected}, got {actual}")]
326    InvalidKeyLength { expected: usize, actual: usize },
327
328    #[error("Signature verification failed")]
329    SignatureVerificationFailed,
330
331    #[error("Key generation failed: {0}")]
332    KeyGenerationFailed(Cow<'static, str>),
333
334    #[error("Invalid public key")]
335    InvalidPublicKey,
336
337    #[error("Invalid private key")]
338    InvalidPrivateKey,
339
340    #[error("HKDF expansion failed: {0}")]
341    HkdfError(Cow<'static, str>),
342}
343
344/// Storage-related errors
345#[derive(Debug, Error)]
346pub enum StorageError {
347    #[error("Database error: {0}")]
348    Database(Cow<'static, str>),
349
350    #[error("Disk full")]
351    DiskFull,
352
353    #[error("Corrupt data: {0}")]
354    CorruptData(Cow<'static, str>),
355
356    #[error("Storage path not found: {0}")]
357    PathNotFound(Cow<'static, str>),
358
359    #[error("Permission denied: {0}")]
360    PermissionDenied(Cow<'static, str>),
361
362    #[error("Lock acquisition failed")]
363    LockFailed,
364
365    #[error("Lock poisoned: {0}")]
366    LockPoisoned(Cow<'static, str>),
367
368    #[error("File not found: {0}")]
369    FileNotFound(Cow<'static, str>),
370
371    #[error("Corruption detected: {0}")]
372    CorruptionDetected(Cow<'static, str>),
373}
374
375/// Transport-related errors
376#[derive(Debug, Error)]
377pub enum TransportError {
378    #[error("QUIC error: {0}")]
379    Quic(Cow<'static, str>),
380
381    #[error("TCP error: {0}")]
382    Tcp(Cow<'static, str>),
383
384    #[error("Invalid transport configuration: {0}")]
385    InvalidConfig(Cow<'static, str>),
386
387    #[error("Transport not supported: {0}")]
388    NotSupported(Cow<'static, str>),
389
390    #[error("Stream error: {0}")]
391    StreamError(Cow<'static, str>),
392
393    #[error("Certificate error: {0}")]
394    CertificateError(Cow<'static, str>),
395
396    #[error("Setup failed: {0}")]
397    SetupFailed(Cow<'static, str>),
398
399    #[error("Connection failed to {addr}: {reason}")]
400    ConnectionFailed {
401        addr: SocketAddr,
402        reason: Cow<'static, str>,
403    },
404
405    #[error("Bind error: {0}")]
406    BindError(Cow<'static, str>),
407
408    #[error("Accept failed: {0}")]
409    AcceptFailed(Cow<'static, str>),
410
411    #[error("Not listening")]
412    NotListening,
413
414    #[error("Not initialized")]
415    NotInitialized,
416}
417
418/// Configuration-related errors
419#[derive(Debug, Error)]
420pub enum ConfigError {
421    #[error("Missing required field: {0}")]
422    MissingField(Cow<'static, str>),
423
424    #[error("Invalid value for {field}: {reason}")]
425    InvalidValue {
426        field: Cow<'static, str>,
427        reason: Cow<'static, str>,
428    },
429
430    #[error("Configuration file not found: {0}")]
431    FileNotFound(Cow<'static, str>),
432
433    #[error("Parse error: {0}")]
434    ParseError(Cow<'static, str>),
435
436    #[error("Validation failed: {0}")]
437    ValidationFailed(Cow<'static, str>),
438
439    #[error("IO error for {path}: {source}")]
440    IoError {
441        path: Cow<'static, str>,
442        #[source]
443        source: std::io::Error,
444    },
445}
446
447/// Security-related errors
448#[derive(Debug, Error)]
449pub enum SecurityError {
450    #[error("Authentication failed")]
451    AuthenticationFailed,
452
453    #[error("Authorization denied")]
454    AuthorizationDenied,
455
456    #[error("Invalid credentials")]
457    InvalidCredentials,
458
459    #[error("Certificate error: {0}")]
460    CertificateError(Cow<'static, str>),
461
462    #[error("Encryption failed: {0}")]
463    EncryptionFailed(Cow<'static, str>),
464
465    #[error("Decryption failed: {0}")]
466    DecryptionFailed(Cow<'static, str>),
467
468    #[error("Invalid key: {0}")]
469    InvalidKey(Cow<'static, str>),
470
471    #[error("Signature verification failed: {0}")]
472    SignatureVerificationFailed(Cow<'static, str>),
473
474    #[error("Key generation failed: {0}")]
475    KeyGenerationFailed(Cow<'static, str>),
476
477    #[error("Authorization failed: {0}")]
478    AuthorizationFailed(Cow<'static, str>),
479}
480
481/// Bootstrap-related errors
482#[derive(Debug, Error)]
483pub enum BootstrapError {
484    #[error("No bootstrap nodes available")]
485    NoBootstrapNodes,
486
487    #[error("Bootstrap failed: {0}")]
488    BootstrapFailed(Cow<'static, str>),
489
490    #[error("Invalid bootstrap node: {0}")]
491    InvalidBootstrapNode(Cow<'static, str>),
492
493    #[error("Bootstrap timeout")]
494    BootstrapTimeout,
495
496    #[error("Cache error: {0}")]
497    CacheError(Cow<'static, str>),
498
499    #[error("Invalid data: {0}")]
500    InvalidData(Cow<'static, str>),
501
502    #[error("Rate limited: {0}")]
503    RateLimited(Cow<'static, str>),
504}
505
506/// Geographic validation errors for connection rejection
507#[derive(Debug, Error, Clone)]
508pub enum GeoRejectionError {
509    #[error("Peer from blocked region: {0}")]
510    BlockedRegion(String),
511
512    #[error("Geographic diversity violation in region {region} (ratio: {current_ratio:.1}%)")]
513    DiversityViolation { region: String, current_ratio: f64 },
514
515    #[error("Region lookup failed: {0}")]
516    LookupFailed(String),
517}
518
519/// Geographic enforcement mode
520#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
521pub enum GeoEnforcementMode {
522    /// Audit mode - log violations but allow connections
523    LogOnly,
524    /// Strict mode - reject connections that violate rules
525    #[default]
526    Strict,
527}
528
529/// Configuration for geographic diversity enforcement
530#[derive(Debug, Clone)]
531pub struct GeographicConfig {
532    /// Minimum number of regions required (default: 3)
533    pub min_regions: usize,
534    /// Maximum ratio of peers from a single region (default: 0.4 = 40%)
535    pub max_single_region_ratio: f64,
536    /// Regions to outright block
537    pub blocked_regions: Vec<String>,
538    /// Enforcement mode (LogOnly or Strict)
539    pub enforcement_mode: GeoEnforcementMode,
540}
541
542impl Default for GeographicConfig {
543    fn default() -> Self {
544        Self {
545            min_regions: 3,
546            max_single_region_ratio: 0.4,
547            blocked_regions: Vec::new(),
548            enforcement_mode: GeoEnforcementMode::Strict,
549        }
550    }
551}
552
553impl GeographicConfig {
554    /// Create a new config with strict enforcement (default)
555    pub fn strict() -> Self {
556        Self::default()
557    }
558
559    /// Create a config for logging only (no rejection)
560    pub fn log_only() -> Self {
561        Self {
562            enforcement_mode: GeoEnforcementMode::LogOnly,
563            ..Default::default()
564        }
565    }
566
567    /// Add a blocked region
568    pub fn with_blocked_region(mut self, region: impl Into<String>) -> Self {
569        self.blocked_regions.push(region.into());
570        self
571    }
572
573    /// Set maximum single region ratio
574    pub fn with_max_ratio(mut self, ratio: f64) -> Self {
575        self.max_single_region_ratio = ratio;
576        self
577    }
578}
579
580/// Result type alias for P2P operations
581pub type P2pResult<T> = Result<T, P2PError>;
582
583// ===== Recovery patterns =====
584
585/// Trait for errors that can be recovered from with retry
586pub trait Recoverable {
587    /// Check if this error is transient and can be retried
588    fn is_transient(&self) -> bool;
589
590    /// Suggested delay before retry
591    fn suggested_retry_after(&self) -> Option<Duration>;
592
593    /// Maximum number of retries recommended
594    fn max_retries(&self) -> usize;
595}
596
597impl Recoverable for P2PError {
598    fn is_transient(&self) -> bool {
599        match self {
600            P2PError::Network(NetworkError::ConnectionFailed { .. }) => true,
601            P2PError::Network(NetworkError::Timeout) => true,
602            P2PError::Transport(TransportError::ConnectionFailed { .. }) => true,
603            P2PError::Dht(DhtError::QueryTimeout) => true,
604            P2PError::Timeout(_) => true,
605            P2PError::ResourceExhausted(_) => true,
606            P2PError::Io(err) => matches!(
607                err.kind(),
608                io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut | io::ErrorKind::Interrupted
609            ),
610            _ => false,
611        }
612    }
613
614    fn suggested_retry_after(&self) -> Option<Duration> {
615        match self {
616            P2PError::Network(NetworkError::Timeout) => Some(Duration::from_secs(5)),
617            P2PError::Timeout(duration) => Some(*duration * 2),
618            P2PError::ResourceExhausted(_) => Some(Duration::from_secs(30)),
619            P2PError::Transport(TransportError::ConnectionFailed { .. }) => {
620                Some(Duration::from_secs(1))
621            }
622            _ => None,
623        }
624    }
625
626    fn max_retries(&self) -> usize {
627        match self {
628            P2PError::Network(NetworkError::ConnectionFailed { .. }) => 3,
629            P2PError::Transport(TransportError::ConnectionFailed { .. }) => 3,
630            P2PError::Timeout(_) => 2,
631            P2PError::ResourceExhausted(_) => 1,
632            _ => 0,
633        }
634    }
635}
636
637/// Extension trait for adding context to errors
638pub trait ErrorContext<T> {
639    /// Add context to an error
640    fn context(self, msg: &str) -> Result<T, P2PError>;
641
642    /// Add context with a closure
643    fn with_context<F>(self, f: F) -> Result<T, P2PError>
644    where
645        F: FnOnce() -> String;
646}
647
648impl<T, E> ErrorContext<T> for Result<T, E>
649where
650    E: Into<P2PError>,
651{
652    fn context(self, msg: &str) -> Result<T, P2PError> {
653        self.map_err(|e| {
654            let base_error = e.into();
655            P2PError::Internal(format!("{}: {}", msg, base_error).into())
656        })
657    }
658
659    fn with_context<F>(self, f: F) -> Result<T, P2PError>
660    where
661        F: FnOnce() -> String,
662    {
663        self.map_err(|e| {
664            let base_error = e.into();
665            P2PError::Internal(format!("{}: {}", f(), base_error).into())
666        })
667    }
668}
669
670/// Helper functions for error creation
671impl P2PError {
672    /// Create a network connection error
673    pub fn connection_failed(addr: SocketAddr, reason: impl Into<String>) -> Self {
674        P2PError::Network(NetworkError::ConnectionFailed {
675            addr,
676            reason: reason.into().into(),
677        })
678    }
679
680    /// Create a timeout error
681    pub fn timeout(duration: Duration) -> Self {
682        P2PError::Timeout(duration)
683    }
684
685    /// Create a validation error
686    pub fn validation(msg: impl Into<Cow<'static, str>>) -> Self {
687        P2PError::Validation(msg.into())
688    }
689
690    /// Create an internal error
691    pub fn internal(msg: impl Into<Cow<'static, str>>) -> Self {
692        P2PError::Internal(msg.into())
693    }
694}
695
696/// Logging integration for errors
697impl P2PError {
698    /// Log error with appropriate level
699    pub fn log(&self) {
700        use tracing::{error, warn};
701
702        match self {
703            P2PError::Network(NetworkError::Timeout) | P2PError::Timeout(_) => warn!("{}", self),
704
705            P2PError::Validation(_) | P2PError::Config(_) => warn!("{}", self),
706
707            _ => error!("{}", self),
708        }
709    }
710
711    /// Log error with context
712    pub fn log_with_context(&self, context: &str) {
713        use tracing::error;
714        error!("{}: {}", context, self);
715    }
716}
717
718// ===== Conversion implementations =====
719
720impl From<serde_json::Error> for P2PError {
721    fn from(err: serde_json::Error) -> Self {
722        P2PError::Serialization(err.to_string().into())
723    }
724}
725
726impl From<postcard::Error> for P2PError {
727    fn from(err: postcard::Error) -> Self {
728        P2PError::Serialization(err.to_string().into())
729    }
730}
731
732impl From<std::net::AddrParseError> for P2PError {
733    fn from(err: std::net::AddrParseError) -> Self {
734        P2PError::Network(NetworkError::InvalidAddress(err.to_string().into()))
735    }
736}
737
738impl From<tokio::time::error::Elapsed> for P2PError {
739    fn from(_: tokio::time::error::Elapsed) -> Self {
740        P2PError::Network(NetworkError::Timeout)
741    }
742}
743
744#[cfg(feature = "adaptive-ml")]
745impl From<crate::adaptive::AdaptiveNetworkError> for P2PError {
746    fn from(err: crate::adaptive::AdaptiveNetworkError) -> Self {
747        use crate::adaptive::AdaptiveNetworkError;
748        match err {
749            AdaptiveNetworkError::Network(io_err) => P2PError::Io(io_err),
750            AdaptiveNetworkError::Serialization(ser_err) => {
751                P2PError::Serialization(ser_err.to_string().into())
752            }
753            AdaptiveNetworkError::Routing(msg) => {
754                P2PError::Internal(format!("Routing error: {msg}").into())
755            }
756            AdaptiveNetworkError::Trust(msg) => {
757                P2PError::Internal(format!("Trust error: {msg}").into())
758            }
759            AdaptiveNetworkError::Learning(msg) => {
760                P2PError::Internal(format!("Learning error: {msg}").into())
761            }
762            AdaptiveNetworkError::Gossip(msg) => {
763                P2PError::Internal(format!("Gossip error: {msg}").into())
764            }
765            AdaptiveNetworkError::Other(msg) => P2PError::Internal(msg.into()),
766        }
767    }
768}
769
770// ===== Structured logging =====
771
772/// Value types for error context
773#[derive(Debug, Clone, Serialize, Deserialize)]
774pub enum ErrorValue {
775    String(Cow<'static, str>),
776    Number(i64),
777    Bool(bool),
778    Duration(Duration),
779    Address(SocketAddr),
780}
781
782/// Structured error log entry optimized for performance
783#[derive(Debug, Serialize, Deserialize)]
784pub struct ErrorLog {
785    pub timestamp: i64, // Unix timestamp for efficiency
786    pub error_type: &'static str,
787    pub message: Cow<'static, str>,
788    pub context: SmallVec<[(&'static str, ErrorValue); 4]>, // Stack-allocated for common cases
789    pub stack_trace: Option<Cow<'static, str>>,
790}
791
792impl ErrorLog {
793    /// Creates an error log entry from a P2PError
794    pub fn from_error(error: &P2PError) -> Self {
795        let mut context = SmallVec::new();
796
797        // Add error-specific context
798        match error {
799            P2PError::Network(NetworkError::ConnectionFailed { addr, reason }) => {
800                context.push(("address", ErrorValue::Address(*addr)));
801                context.push(("reason", ErrorValue::String(reason.clone())));
802            }
803            P2PError::Timeout(duration) => {
804                context.push(("timeout", ErrorValue::Duration(*duration)));
805            }
806            P2PError::Crypto(CryptoError::InvalidKeyLength { expected, actual }) => {
807                context.push(("expected_length", ErrorValue::Number(*expected as i64)));
808                context.push(("actual_length", ErrorValue::Number(*actual as i64)));
809            }
810            _ => {}
811        }
812
813        ErrorLog {
814            timestamp: chrono::Utc::now().timestamp(),
815            error_type: error_type_name(error),
816            message: error.to_string().into(),
817            context,
818            stack_trace: None,
819        }
820    }
821
822    pub fn with_context(mut self, key: &'static str, value: ErrorValue) -> Self {
823        self.context.push((key, value));
824        self
825    }
826
827    pub fn log(&self) {
828        use log::{error, warn};
829
830        let json = serde_json::to_string(self).unwrap_or_else(|_| self.message.to_string());
831
832        match self.error_type {
833            "Validation" | "Config" => warn!("{}", json),
834            _ => error!("{}", json),
835        }
836    }
837}
838
839fn error_type_name(error: &P2PError) -> &'static str {
840    match error {
841        P2PError::Network(_) => "Network",
842        P2PError::Dht(_) => "DHT",
843        P2PError::Identity(_) => "Identity",
844        P2PError::Crypto(_) => "Crypto",
845        P2PError::Storage(_) => "Storage",
846        P2PError::Transport(_) => "Transport",
847        P2PError::Config(_) => "Config",
848        P2PError::Io(_) => "IO",
849        P2PError::Serialization(_) => "Serialization",
850        P2PError::Validation(_) => "Validation",
851        P2PError::Timeout(_) => "Timeout",
852        P2PError::ResourceExhausted(_) => "ResourceExhausted",
853        P2PError::Internal(_) => "Internal",
854        P2PError::Security(_) => "Security",
855        P2PError::Bootstrap(_) => "Bootstrap",
856        P2PError::Encoding(_) => "Encoding",
857        P2PError::RecordTooLarge(_) => "RecordTooLarge",
858        P2PError::TimeError => "TimeError",
859        P2PError::InvalidInput(_) => "InvalidInput",
860        P2PError::WebRtcError(_) => "WebRTC",
861        P2PError::Trust(_) => "Trust",
862    }
863}
864
865/// Error reporting trait for structured logging
866pub trait ErrorReporting {
867    fn report(&self) -> ErrorLog;
868    fn report_with_context(&self, context: HashMap<String, serde_json::Value>) -> ErrorLog;
869}
870
871impl ErrorReporting for P2PError {
872    fn report(&self) -> ErrorLog {
873        ErrorLog::from_error(self)
874    }
875
876    fn report_with_context(&self, context: HashMap<String, serde_json::Value>) -> ErrorLog {
877        let log = ErrorLog::from_error(self);
878        // Convert HashMap entries to ErrorValue entries
879        for (_key, _value) in context {
880            // We need to leak the key to get a &'static str, or use a different approach
881            // For now, we'll skip this functionality as it requires a redesign
882            // log.context.push((key.leak(), ErrorValue::String(value.to_string().into())));
883        }
884        log
885    }
886}
887
888// ===== Anyhow integration =====
889
890/// Conversion helpers for anyhow integration
891pub trait IntoAnyhow<T> {
892    fn into_anyhow(self) -> anyhow::Result<T>;
893}
894
895impl<T> IntoAnyhow<T> for P2pResult<T> {
896    fn into_anyhow(self) -> anyhow::Result<T> {
897        self.map_err(|e| anyhow::anyhow!(e))
898    }
899}
900
901pub trait FromAnyhowExt<T> {
902    fn into_p2p_result(self) -> P2pResult<T>;
903}
904
905impl<T> FromAnyhowExt<T> for anyhow::Result<T> {
906    fn into_p2p_result(self) -> P2pResult<T> {
907        self.map_err(|e| P2PError::Internal(e.to_string().into()))
908    }
909}
910
911/// Re-export for convenience
912pub use anyhow::{Context as AnyhowContext, Result as AnyhowResult};
913
914#[cfg(test)]
915mod tests {
916    use super::*;
917
918    #[test]
919    fn test_error_display() {
920        let err =
921            P2PError::connection_failed("127.0.0.1:8080".parse().unwrap(), "Connection refused");
922        assert_eq!(
923            err.to_string(),
924            "Network error: Connection failed to 127.0.0.1:8080: Connection refused"
925        );
926    }
927
928    #[test]
929    fn test_error_context() {
930        let result: Result<(), io::Error> =
931            Err(io::Error::new(io::ErrorKind::NotFound, "file not found"));
932
933        let with_context = crate::error::ErrorContext::context(result, "Failed to load config");
934        assert!(with_context.is_err());
935        assert!(
936            with_context
937                .unwrap_err()
938                .to_string()
939                .contains("Failed to load config")
940        );
941    }
942
943    #[test]
944    fn test_timeout_error() {
945        let err = P2PError::timeout(Duration::from_secs(30));
946        assert_eq!(err.to_string(), "Operation timed out after 30s");
947    }
948
949    #[test]
950    fn test_crypto_error() {
951        let err = P2PError::Crypto(CryptoError::InvalidKeyLength {
952            expected: 32,
953            actual: 16,
954        });
955        assert_eq!(
956            err.to_string(),
957            "Cryptography error: Invalid key length: expected 32, got 16"
958        );
959    }
960
961    #[test]
962    fn test_error_log_serialization() {
963        let error = P2PError::Network(NetworkError::ConnectionFailed {
964            addr: "127.0.0.1:8080".parse().unwrap(),
965            reason: "Connection refused".into(),
966        });
967
968        let log = error
969            .report()
970            .with_context("peer_id", ErrorValue::String("peer123".into()))
971            .with_context("retry_count", ErrorValue::Number(3));
972
973        let json = serde_json::to_string_pretty(&log).unwrap();
974        assert!(json.contains("Network"));
975        assert!(json.contains("127.0.0.1:8080"));
976        assert!(json.contains("peer123"));
977    }
978
979    #[test]
980    fn test_anyhow_conversion() {
981        let p2p_result: P2pResult<()> = Err(P2PError::validation("Invalid input"));
982        let anyhow_result = p2p_result.into_anyhow();
983        assert!(anyhow_result.is_err());
984
985        let anyhow_err = anyhow::anyhow!("Test error");
986        let anyhow_result: anyhow::Result<()> = Err(anyhow_err);
987        let p2p_result = crate::error::FromAnyhowExt::into_p2p_result(anyhow_result);
988        assert!(p2p_result.is_err());
989        match p2p_result.unwrap_err() {
990            P2PError::Internal(msg) => assert!(msg.contains("Test error")),
991            _ => panic!("Expected Internal error"),
992        }
993    }
994}