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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
# Error Handling Guide

A comprehensive guide to handling errors and implementing retry logic in PresenceForge.


## Table of Contents

- [Overview]#overview
- [Error Types]#error-types
- [Error Categories]#error-categories
- [Common Error Scenarios]#common-error-scenarios
- [Connection Retry & Reconnection]#connection-retry--reconnection
- [Best Practices]#best-practices
- [Recovery Strategies]#recovery-strategies

---

## Overview

PresenceForge uses the `DiscordIpcError` enum for all error cases. All fallible operations return `Result<T, DiscordIpcError>`, which is aliased as `presenceforge::Result<T>` for convenience.

### Basic Error Handling

```rust
use presenceforge::Result;
use presenceforge::sync::DiscordIpcClient;

fn main() -> Result<()> {
    let mut client = DiscordIpcClient::new("your_client_id")?;
    client.connect()?;

    // ... use client

    Ok(())
}
```

---

## Error Types

Below are the most common variants in `DiscordIpcError` and when they occur. See the crate docs for the full enum.

### `ConnectionFailed(std::io::Error)`

When the library fails to open/connect the IPC socket/pipe.

Common causes:

- Discord is not running
- No available IPC pipes/sockets
- Permission denied accessing pipe/socket

```rust
use presenceforge::DiscordIpcError;
use presenceforge::sync::DiscordIpcClient;

match DiscordIpcClient::new("client_id") {
    Ok(mut client) => {
        let _ = client.connect()?; // ignore handshake payload
        println!("Connected!");
    }
    Err(DiscordIpcError::ConnectionFailed(e)) => {
        eprintln!("Connection failed: {}", e);
    }
    Err(e) => eprintln!("Other error: {}", e),
}
```

---

### `SocketDiscoveryFailed { source, attempted_paths }`

Auto-discovery tried multiple standard locations but none were usable. `attempted_paths` helps troubleshooting.

---

### `ConnectionTimeout { timeout_ms, last_error }`

Timed out while retrying connections for the configured duration.

---

### `NoValidSocket`

No Discord IPC sockets were found.

---

### `HandshakeFailed(String)`

Discord responded with an error or an unexpected opcode during the handshake.

```rust
match client.connect() {
    Ok(_) => println!("Handshake successful"),
    Err(DiscordIpcError::HandshakeFailed(msg)) => {
        eprintln!("Handshake failed: {}", msg);
    }
    Err(e) => eprintln!("Other error: {}", e),
}
```

---

### `ProtocolViolation { message, context }` and `InvalidOpcode(u32)`

Indicates malformed data or unexpected protocol values. The `context` includes opcode and payload size when available.

---

### `SerializationFailed(serde_json::Error)` and `DeserializationFailed(serde_json::Error)`

JSON encoding/decoding problems. Often caused by invalid activities or malformed responses.

```rust
if let Err(DiscordIpcError::SerializationFailed(e)) = client.set_activity(&activity) {
    eprintln!("Serialization error: {}", e);
}
```

---

### `InvalidResponse(String)`

Response shape was valid JSON but not what the library expected (e.g., nonce mismatch).

---

### `DiscordError { code, message }`

Discord reported an application-level error (includes error code and message from Discord).

---

### `SocketClosed`

The underlying connection closed while reading/writing.

---

### `InvalidActivity(String)` and `SystemTimeError(String)`

Activity validation failed, or system time issues occurred while computing timestamps.

---

## Error Categories

PresenceForge groups errors into categories for easier handling:

```rust
use presenceforge::error::ErrorCategory;

let category = error.category();
match category {
    ErrorCategory::Connection => {
        println!("Connection problem - check Discord is running");
    }
    ErrorCategory::Protocol => {
        println!("Protocol issue - try updating Discord");
    }
    ErrorCategory::Serialization => {
        println!("Data serialization problem");
    }
    ErrorCategory::Application => {
        println!("Discord application error");
    }
    ErrorCategory::Other => {
        println!("Other error type");
    }
}
```

### Helper Methods

#### `is_connection_error(&self) -> bool`

```rust
if error.is_connection_error() {
    eprintln!(" Tip: Make sure Discord is running!");
    eprintln!(" Try: ps aux | grep -i discord");
}
```

#### `is_recoverable(&self) -> bool`

```rust
if error.is_recoverable() {
    println!(" This error might be recoverable - trying again...");
    retry_logic();
} else {
    eprintln!(" Fatal error - cannot continue");
    std::process::exit(1);
}
```

---

## Common Error Scenarios

### Scenario 1: Discord Not Running

**Problem:** Connection fails because Discord isn't running.

```rust
use presenceforge:: DiscordIpcError;
use presenceforge::sync::DiscordIpcClient;

fn connect_to_discord(client_id: &str) -> Result<DiscordIpcClient, Box<dyn std::error::Error>> {
    match DiscordIpcClient::new(client_id) {
        Ok(mut client) => {
            client.connect()?;
            Ok(client)
        }
        Err(DiscordIpcError::ConnectionFailed(_)) => {
            eprintln!(" Cannot connect to Discord");
            eprintln!(" Make sure Discord is running");
            eprintln!(" Start Discord and try again");
            Err("Discord not running".into())
        }
        Err(e) => Err(e.into()),
    }
}
```

---

### Scenario 2: Lost Connection During Operation

**Problem:** Connection is lost while the application is running.

```rust
use presenceforge::{ActivityBuilder, DiscordIpcError};
use presenceforge::sync::DiscordIpcClient;
use std::thread;
use std::time::Duration;

fn maintain_presence(mut client: DiscordIpcClient) -> Result<(), Box<dyn std::error::Error>> {
    let activity = ActivityBuilder::new()
        .state("Running")
        .start_timestamp_now()?
        .build();

    loop {
        match client.set_activity(&activity) {
            Ok(_) => {
                println!(" Activity updated");
            }
            Err(e) if e.is_connection_error() => {
                eprintln!(" Connection lost. Recreating client and reconnecting...");
                // Recreate the client (sync API has no reconnect method)
                client = DiscordIpcClient::new("your_client_id")?;
                let _ = client.connect()?;
                client.set_activity(&activity)?;
            }
            Err(e) => {
                eprintln!(" Unexpected error: {}", e);
                return Err(e.into());
            }
        }

        thread::sleep(Duration::from_secs(15));
    }
}
```

---

## Connection Retry & Reconnection

PresenceForge provides built-in support for connection retry and reconnection to handle transient network issues and Discord restarts.

### Using the `reconnect()` Method

The `reconnect()` method closes the existing connection and establishes a new one:

```rust
use presenceforge::ActivityBuilder;
use presenceforge::sync::DiscordIpcClient;
use std::time::Duration;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = DiscordIpcClient::new("your_client_id")?;
    client.connect()?;

    let activity = ActivityBuilder::new()
        .state("Playing a game")
        .build();

    // Update activity in a loop
    loop {
        match client.set_activity(&activity) {
            Ok(_) => println!("✓ Activity updated"),
            Err(e) if e.is_connection_error() => {
                println!("⚠ Connection lost, reconnecting...");
                client.reconnect()?;
                client.set_activity(&activity)?;
            }
            Err(e) => return Err(e.into()),
        }

        std::thread::sleep(Duration::from_secs(15));
    }
}
```

### Using Retry Utilities

For initial connection, use the `with_retry` function with automatic exponential backoff:

```rust
use presenceforge::retry::{with_retry, RetryConfig};
use presenceforge::sync::DiscordIpcClient;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Default: 3 attempts, 1s initial delay, exponential backoff
    let config = RetryConfig::default();

    let mut client = with_retry(&config, || {
        println!("Attempting to connect...");
        DiscordIpcClient::new("your_client_id")
    })?;

    client.connect()?;
    println!("✓ Connected successfully!");

    Ok(())
}
```

### Custom Retry Configuration

```rust
use presenceforge::retry::RetryConfig;

// More aggressive retry: 5 attempts, shorter delays
let config = RetryConfig::new(
    5,      // max_attempts
    500,    // initial_delay_ms (0.5s)
    8000,   // max_delay_ms (8s)
    2.0,    // backoff_multiplier (exponential)
);

// Retry delays will be: 500ms, 1s, 2s, 4s, 8s
let mut client = with_retry(&config, || {
    DiscordIpcClient::new("your_client_id")
})?;
```

### Async Retry & Reconnect

#### Tokio

The new reconnectable wrapper provides automatic retry and manual reconnect capabilities:

```rust
use presenceforge::async_io::tokio::{TokioDiscordIpcClient, PipeConfig};
use presenceforge::retry::RetryConfig;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create client with reconnect support
    let mut client = TokioDiscordIpcClient::new(
        "your_client_id",
        PipeConfig::Auto,
        Some(5000)
    );

    // Connect with retry
    let retry_config = RetryConfig::with_max_attempts(5);
    client.connect_with_retry(&retry_config).await?;

    // Later: manual reconnect if connection is lost
    if let Err(e) = client.set_activity(activity).await {
        if e.is_recoverable() {
            client.reconnect().await?;
        }
    }

    Ok(())
}
```

#### async-std

```rust
use presenceforge::async_io::async_std::{AsyncStdDiscordIpcClient, PipeConfig};

#[async_std::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = AsyncStdDiscordIpcClient::new(
        "your_client_id",
        PipeConfig::Auto,
        Some(5000)
    );

    client.connect().await?;

    // Reconnect when needed
    client.reconnect().await?;
    Ok(())
}
```

#### smol

```rust
use presenceforge::async_io::smol::{SmolDiscordIpcClient, PipeConfig};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    smol::block_on(async {
        let mut client = SmolDiscordIpcClient::new(
            "your_client_id",
            PipeConfig::Auto,
            Some(5000)
        );

        client.connect().await?;

        // Reconnect when needed
        client.reconnect().await?;
        Ok(())
    })
}
```

**For complete examples, see:**

- `examples/connection_retry.rs` (sync)
- `examples/async_tokio_reconnect.rs` (async)

---

### Scenario 3: Invalid Configuration

**Problem:** Environment or configuration issues prevent connection.

```rust
use presenceforge::DiscordIpcError;
use presenceforge::sync::DiscordIpcClient;
use std::env;

fn setup_client() -> Result<DiscordIpcClient, Box<dyn std::error::Error>> {
    // Get client ID from environment
    let client_id = env::var("DISCORD_CLIENT_ID").map_err(|_| {
        eprintln!(" DISCORD_CLIENT_ID environment variable not set");
        eprintln!(" Set it with: export DISCORD_CLIENT_ID='your_app_id'");
        eprintln!(" Get your App ID from: https://discord.com/developers/applications");
        "Missing DISCORD_CLIENT_ID"
    })?;

    // Validate client ID format (should be numeric)
    if !client_id.chars().all(|c| c.is_numeric()) {
        eprintln!(" Invalid client ID format: {}", client_id);
        eprintln!(" Client ID should be a numeric string");
        return Err("Invalid client ID format".into());
    }

    // Create client
    let mut client = match DiscordIpcClient::new(&client_id) {
        Ok(c) => c,
        Err(DiscordIpcError::InvalidClientId) => {
            eprintln!(" Discord rejected client ID: {}", client_id);
            eprintln!(" Verify this is the correct Application ID");
            return Err("Invalid client ID".into());
        }
        Err(e) => return Err(e.into()),
    };

    // Connect
    client.connect()?;

    Ok(client)
}
```

---

## Best Practices

### 1. Always Handle Errors Explicitly

**Don't:**

```rust
let client = DiscordIpcClient::new("client_id").unwrap();
```

**Do:**

```rust
let mut client = match DiscordIpcClient::new("client_id") {
    Ok(c) => c,
    Err(e) => {
        eprintln!("Failed to create client: {}", e);
        return Err(e.into());
    }
};
```

---

### 2. Provide Context in Error Messages

**Don't:**

```rust
client.set_activity(&activity)?;
```

**Do:**

```rust
client.set_activity(&activity)
    .map_err(|e| {
        eprintln!("Failed to set activity: {}", e);
        e
    })?;
```

---

### 3. Use Error Categories for Different Handling

```rust
use presenceforge::error::ErrorCategory;

match operation_result {
    Err(e) => {
        match e.category() {
            ErrorCategory::Connection => {
                // Connection errors might be temporary
                retry_with_backoff();
            }
            ErrorCategory::Protocol => {
                // Protocol errors need investigation
                log_for_debugging(&e);
                return Err(e.into());
            }
            ErrorCategory::Serialization => {
                // Serialization errors indicate bugs
                panic!("Bug in activity creation: {}", e);
            }
            _ => return Err(e.into()),
        }
    }
    Ok(_) => { /* success */ }
}
```

---

### 4. Implement Retry Logic for Transient Errors

PresenceForge includes built-in retry utilities with exponential backoff:

```rust
use presenceforge::retry::{with_retry, RetryConfig};

use presenceforge::sync::DiscordIpcClient;

fn connect_with_retry(client_id: &str) -> Result<DiscordIpcClient, Box<dyn std::error::Error>> {
    // Use default retry config (3 attempts, 1s initial delay, exponential backoff)
    let config = RetryConfig::default();

    let mut client = with_retry(&config, || {
        DiscordIpcClient::new(client_id)
    })?;

    client.connect()?;
    Ok(client)
}
```

**Custom retry configuration:**

```rust
use presenceforge::retry::RetryConfig;

// Create custom retry configuration
let config = RetryConfig::new(
    5,      // max_attempts
    500,    // initial_delay_ms
    8000,   // max_delay_ms
    2.0,    // backoff_multiplier
);

let mut client = with_retry(&config, || {
    DiscordIpcClient::new(client_id)
})?;
```

---

### 5. Clean Up on Errors

```rust
use presenceforge::ActivityBuilder;
use presenceforge::sync::DiscordIpcClient;

fn run_presence() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = DiscordIpcClient::new("client_id")?;
    client.connect()?;

    let activity = ActivityBuilder::new()
        .state("Running")
        .build();

    client.set_activity(&activity)?;

    // Ensure cleanup happens even on error
    let result = do_work();

    // Always try to clear activity before exiting
    if let Err(e) = client.clear_activity() {
        eprintln!("Warning: Failed to clear activity: {}", e);
    }

    result
}
```

---

## Recovery Strategies

### Strategy 1: Automatic Reconnection

```rust
struct ResilientClient {
    client_id: String,
    client: Option<DiscordIpcClient>,
}

impl ResilientClient {
    fn new(client_id: String) -> Self {
        Self {
            client_id,
            client: None,
        }
    }

    fn ensure_connected(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        if self.client.is_none() {
            let mut client = DiscordIpcClient::new(&self.client_id)?;
            client.connect()?;
            self.client = Some(client);
        }
        Ok(())
    }

    fn set_activity_resilient(
        &mut self,
        activity: &Activity
    ) -> Result<(), Box<dyn std::error::Error>> {
        self.ensure_connected()?;

        let result = self.client
            .as_mut()
            .unwrap()
            .set_activity(activity);

        if let Err(e) = result {
            if e.is_connection_error() {
                // Connection lost, reset and try once more
                self.client = None;
                self.ensure_connected()?;
                return Ok(self.client.as_mut().unwrap().set_activity(activity)?);
            }
            return Err(e.into());
        }

        Ok(())
    }
}
```

---

### Strategy 2: Graceful Degradation

```rust
fn update_presence_best_effort(
    client: &mut DiscordIpcClient,
    activity: &Activity
) {
    match client.set_activity(activity) {
        Ok(_) => println!(" Presence updated"),
        Err(e) => {
            eprintln!(" Failed to update presence: {}", e);
            eprintln!(" Continuing without Rich Presence");
            // Application continues without Rich Presence
        }
    }
}
```

---

### Strategy 3: User Notification

```rust
fn connect_with_user_feedback(
    client_id: &str
) -> Result<DiscordIpcClient, Box<dyn std::error::Error>> {
    println!(" Connecting to Discord...");

    match DiscordIpcClient::new(client_id) {
        Ok(mut client) => {
            match client.connect() {
                Ok(_) => {
                    println!(" Connected to Discord successfully!");
                    Ok(client)
                }
                Err(e) => {
                    eprintln!(" Handshake failed: {}", e);
                    eprintln!(" Try restarting Discord");
                    Err(e.into())
                }
            }
        }
        Err(e) => {
            eprintln!(" Connection failed: {}", e);
            eprintln!();
            eprintln!(" Troubleshooting checklist:");
            eprintln!("   [ ] Discord is installed");
            eprintln!("   [ ] Discord is running");
            eprintln!("   [ ] Discord is not blocked by firewall");
            eprintln!("   [ ] Your client ID is correct");
            Err(e.into())
        }
    }
}
```

---

## See Also

- [API Reference]API_REFERENCE.md - Error type documentation (WIP)
- [FAQ]FAQ.md - Common issues and solutions
- [Getting Started]GETTING_STARTED.md - Basic setup guide