presenceforge 0.1.0

A library for Discord Rich Presence (IPC) integration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
use std::fmt::{self, Display};
use std::io;
use thiserror::Error;

/// Context information for protocol violations
#[derive(Debug, Clone)]
pub struct ProtocolContext {
    pub expected_opcode: Option<u32>,
    pub received_opcode: Option<u32>,
    pub payload_size: Option<usize>,
}

impl ProtocolContext {
    /// Create a new ProtocolContext with all fields empty
    pub fn new() -> Self {
        Self {
            expected_opcode: None,
            received_opcode: None,
            payload_size: None,
        }
    }

    /// Create a ProtocolContext with expected and received opcodes
    pub fn with_opcodes(expected: u32, received: u32) -> Self {
        Self {
            expected_opcode: Some(expected),
            received_opcode: Some(received),
            payload_size: None,
        }
    }

    /// Create a ProtocolContext with a received opcode and payload size
    pub fn with_payload(received_opcode: u32, payload_size: usize) -> Self {
        Self {
            expected_opcode: None,
            received_opcode: Some(received_opcode),
            payload_size: Some(payload_size),
        }
    }
}

impl Default for ProtocolContext {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorCategory {
    /// Errors related to connecting to Discord
    Connection,
    /// Errors related to the IPC protocol
    Protocol,
    /// Errors related to serialization/deserialization
    Serialization,
    /// Errors related to the Discord application itself
    Application,
    /// Other unspecified errors
    Other,
}

impl Display for ErrorCategory {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Connection => write!(f, "connection"),
            Self::Protocol => write!(f, "protocol"),
            Self::Serialization => write!(f, "serialization"),
            Self::Application => write!(f, "application"),
            Self::Other => write!(f, "other"),
        }
    }
}

/// Errors that can occur during Discord IPC operations
///
/// # Error Handling Examples
///
/// Basic error handling:
/// ```rust,no_run
/// use presenceforge::DiscordIpcError;
/// use presenceforge::sync::DiscordIpcClient;
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let mut client = match DiscordIpcClient::new("your-client-id") {
///         Ok(client) => client,
///         Err(DiscordIpcError::ConnectionFailed(e)) => {
///             eprintln!("Failed to connect to Discord: {}", e);
///             eprintln!("Is Discord running?");
///             return Err(Box::new(e));
///         },
///         Err(e) => return Err(Box::new(e)),
///     };
///     
///     // Use the client...
///     Ok(())
/// }
/// ```
///
/// Using utility functions for recoverable errors:
/// ```rust
/// use presenceforge::{DiscordIpcError, Activity};
/// use presenceforge::sync::DiscordIpcClient;
/// use std::time::Duration;
///
/// fn connect_with_retry(client_id: &str, max_attempts: u32) -> Result<DiscordIpcClient, DiscordIpcError> {
///     let mut attempt = 1;
///     
///     while attempt <= max_attempts {
///         match DiscordIpcClient::new(client_id) {
///             Ok(client) => return Ok(client),
///             Err(e) if e.is_recoverable() && attempt < max_attempts => {
///                 eprintln!("Connection attempt {} failed: {}. Retrying...", attempt, e);
///                 std::thread::sleep(Duration::from_secs(2));
///                 attempt += 1;
///             },
///             Err(e) => return Err(e),
///         }
///     }
///     
///     unreachable!()
/// }
/// ```
///
/// See the `examples/error_handling.rs` file for more comprehensive examples.
#[derive(Error, Debug)]
pub enum DiscordIpcError {
    /// Failed to connect to Discord IPC socket or pipe
    #[error("Failed to connect to Discord IPC socket: {0}")]
    ConnectionFailed(#[source] io::Error),

    /// Failed to discover Discord socket after trying multiple paths
    #[error("Failed to discover Discord socket. Attempted paths: {}", attempted_paths.join(", "))]
    SocketDiscoveryFailed {
        #[source]
        source: io::Error,
        attempted_paths: Vec<String>,
    },

    /// Connection timed out
    #[error("Connection timeout after {timeout_ms}ms")]
    ConnectionTimeout {
        timeout_ms: u64,
        last_error: Option<String>,
    },

    /// Failed to find a valid Discord IPC socket or pipe
    #[error("No Discord IPC socket found. Is Discord running?")]
    NoValidSocket,

    /// Failed to serialize JSON payload
    #[error("Failed to serialize JSON payload: {0}")]
    SerializationFailed(#[source] serde_json::Error),

    /// Failed to deserialize JSON payload from Discord
    #[error("Failed to deserialize response from Discord: {0}")]
    DeserializationFailed(#[source] serde_json::Error),

    /// Received an invalid or unexpected response from Discord
    #[error("Invalid response from Discord: {0}")]
    InvalidResponse(String),

    /// Handshake with Discord failed
    #[error("Handshake failed: {0}")]
    HandshakeFailed(String),

    /// Socket connection was closed unexpectedly
    #[error("Socket connection was closed unexpectedly")]
    SocketClosed,

    /// Received an invalid opcode from Discord
    #[error("Invalid opcode: {0}")]
    InvalidOpcode(u32),

    /// Protocol violation occurred during IPC communication
    #[error("Protocol violation: {message}")]
    ProtocolViolation {
        message: String,
        context: ProtocolContext,
    },

    #[error("Discord error: {code} - {message}")]
    DiscordError {
        /// The error code returned by Discord
        code: i32,
        /// The error message returned by Discord
        message: String,
    },

    #[error("Invalid activity: {0}")]
    InvalidActivity(String),

    /// System time error (e.g., time before UNIX epoch)
    #[error("System time error: {0}")]
    SystemTimeError(String),
}

impl DiscordIpcError {
    pub fn category(&self) -> ErrorCategory {
        match self {
            Self::ConnectionFailed(_)
            | Self::SocketDiscoveryFailed { .. }
            | Self::ConnectionTimeout { .. }
            | Self::NoValidSocket
            | Self::SocketClosed => ErrorCategory::Connection,

            Self::SerializationFailed(_) | Self::DeserializationFailed(_) => {
                ErrorCategory::Serialization
            }

            Self::InvalidResponse(_)
            | Self::HandshakeFailed(_)
            | Self::InvalidOpcode(_)
            | Self::ProtocolViolation { .. } => ErrorCategory::Protocol,

            Self::DiscordError { .. } => ErrorCategory::Application,

            Self::InvalidActivity(_) | Self::SystemTimeError(_) => ErrorCategory::Other,
        }
    }

    pub fn is_connection_error(&self) -> bool {
        matches!(self.category(), ErrorCategory::Connection)
    }

    pub fn is_recoverable(&self) -> bool {
        matches!(
            self,
            Self::ConnectionTimeout { .. }
                | Self::SocketClosed
                | Self::InvalidResponse(_)
                | Self::SocketDiscoveryFailed { .. }
        )
    }

    pub fn discord_error(code: i32, message: impl Into<String>) -> Self {
        Self::DiscordError {
            code,
            message: message.into(),
        }
    }

    /// Create a SocketDiscoveryFailed error with the attempted paths
    pub fn socket_discovery_failed(source: io::Error, attempted_paths: Vec<String>) -> Self {
        Self::SocketDiscoveryFailed {
            source,
            attempted_paths,
        }
    }

    /// Create a ConnectionTimeout error with optional last error
    pub fn connection_timeout(timeout_ms: u64, last_error: Option<String>) -> Self {
        Self::ConnectionTimeout {
            timeout_ms,
            last_error,
        }
    }

    /// Create a ProtocolViolation error with message and context
    pub fn protocol_violation(message: impl Into<String>, context: ProtocolContext) -> Self {
        Self::ProtocolViolation {
            message: message.into(),
            context,
        }
    }
}

impl From<io::Error> for DiscordIpcError {
    fn from(error: io::Error) -> Self {
        Self::ConnectionFailed(error)
    }
}

impl From<serde_json::Error> for DiscordIpcError {
    fn from(error: serde_json::Error) -> Self {
        Self::SerializationFailed(error)
    }
}

/// Result type for Discord IPC operations
pub type Result<T = ()> = std::result::Result<T, DiscordIpcError>;

pub mod utils {
    use super::DiscordIpcError;
    use std::error::Error;
    use std::fmt::{self, Display};

    /// A wrapper error type that can be used to convert DiscordIpcError to application errors
    #[derive(Debug)]
    pub struct AppError {
        source: DiscordIpcError,
        context: Option<String>,
    }

    impl AppError {
        pub fn new(source: DiscordIpcError, context: impl Into<String>) -> Self {
            Self {
                source,
                context: Some(context.into()),
            }
        }

        pub fn from_error(source: DiscordIpcError) -> Self {
            Self {
                source,
                context: None,
            }
        }

        /// Get the underlying Discord IPC error
        pub fn discord_error(&self) -> &DiscordIpcError {
            &self.source
        }

        pub fn context(&self) -> Option<&str> {
            self.context.as_deref()
        }
    }

    impl Display for AppError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            if let Some(context) = &self.context {
                write!(f, "{}: {}", context, self.source)
            } else {
                write!(f, "{}", self.source)
            }
        }
    }

    impl Error for AppError {
        fn source(&self) -> Option<&(dyn Error + 'static)> {
            Some(&self.source)
        }
    }

    /// Extension trait for Result<T, DiscordIpcError> to convert to application errors
    pub trait ResultExt<T> {
        /// Add context to the error
        fn with_context(self, context: impl Into<String>) -> std::result::Result<T, AppError>;

        /// Convert to a different error type
        fn map_err_to<E>(self, f: impl FnOnce(DiscordIpcError) -> E) -> std::result::Result<T, E>;

        /// Handle recoverable errors and attempt to retry the operation
        fn retry_if<F>(
            self,
            is_recoverable: fn(&DiscordIpcError) -> bool,
            retry_op: F,
        ) -> std::result::Result<T, DiscordIpcError>
        where
            F: FnOnce() -> std::result::Result<T, DiscordIpcError>;
    }

    impl<T> ResultExt<T> for std::result::Result<T, DiscordIpcError> {
        fn with_context(self, context: impl Into<String>) -> std::result::Result<T, AppError> {
            self.map_err(|err| AppError::new(err, context))
        }

        fn map_err_to<E>(self, f: impl FnOnce(DiscordIpcError) -> E) -> std::result::Result<T, E> {
            self.map_err(f)
        }

        fn retry_if<F>(
            self,
            is_recoverable: fn(&DiscordIpcError) -> bool,
            retry_op: F,
        ) -> std::result::Result<T, DiscordIpcError>
        where
            F: FnOnce() -> std::result::Result<T, DiscordIpcError>,
        {
            match self {
                Ok(value) => Ok(value),
                Err(err) if is_recoverable(&err) => retry_op(),
                Err(err) => Err(err),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::utils::{AppError, ResultExt};

    #[test]
    fn protocol_context_helpers_populate_fields() {
        let empty = ProtocolContext::new();
        assert!(empty.expected_opcode.is_none());
        assert!(empty.received_opcode.is_none());

        let with_opcodes = ProtocolContext::with_opcodes(1, 2);
        assert_eq!(with_opcodes.expected_opcode, Some(1));
        assert_eq!(with_opcodes.received_opcode, Some(2));

        let with_payload = ProtocolContext::with_payload(3, 42);
        assert_eq!(with_payload.received_opcode, Some(3));
        assert_eq!(with_payload.payload_size, Some(42));
    }

    #[test]
    fn error_category_and_recoverable_detection() {
        let conn_err = DiscordIpcError::SocketClosed;
        assert_eq!(conn_err.category(), ErrorCategory::Connection);
        assert!(conn_err.is_connection_error());
        assert!(conn_err.is_recoverable());

        let proto_err = DiscordIpcError::InvalidResponse("oops".into());
        assert_eq!(proto_err.category(), ErrorCategory::Protocol);
        assert!(proto_err.is_recoverable());

        let app_err = DiscordIpcError::discord_error(4000, "bad");
        assert_eq!(app_err.category(), ErrorCategory::Application);
        assert!(!app_err.is_recoverable());
    }

    #[test]
    fn app_error_preserves_context() {
        let err = DiscordIpcError::SocketClosed;
        let wrapped = AppError::new(err, "while sending message");

        assert!(matches!(
            wrapped.discord_error(),
            DiscordIpcError::SocketClosed
        ));
        assert_eq!(wrapped.context(), Some("while sending message"));
        assert!(format!("{}", wrapped).contains("while sending message"));
    }

    #[test]
    fn result_ext_retry_if_retries_on_recoverable() {
        use std::cell::Cell;

        let attempts = Cell::new(0);
        let initial: Result<()> = Err(DiscordIpcError::SocketClosed);

        let outcome = initial.retry_if(DiscordIpcError::is_recoverable, || {
            attempts.set(attempts.get() + 1);
            Ok(())
        });

        assert!(outcome.is_ok());
        assert_eq!(attempts.get(), 1);
    }

    #[test]
    fn result_ext_with_context_maps_error() {
        let result: Result<()> = Err(DiscordIpcError::SocketClosed);
        let app_result = result.with_context("connecting");

        let err = app_result.unwrap_err();
        assert_eq!(err.context(), Some("connecting"));
    }
}