p2p_chat/sync/engine/outbox/direct.rs
1//! This module contains logic for directly retrying messages in the outbox
2//! for a specific peer.
3use anyhow::Result;
4use libp2p::PeerId;
5use tracing::{debug, info};
6
7use super::super::SyncEngine;
8
9impl SyncEngine {
10 /// Retries sending pending messages from the outbox to a specific peer.
11 ///
12 /// This function fetches all pending messages and attempts to send those
13 /// destined for `target_peer`. Successfully sent messages are removed
14 /// from the outbox.
15 ///
16 /// # Arguments
17 ///
18 /// * `target_peer` - The `PeerId` of the peer to retry sending messages to.
19 ///
20 /// # Errors
21 ///
22 /// This function will return an error if there are issues accessing the
23 /// outbox or sending messages via the network.
24 pub async fn retry_outbox_for_peer(&self, target_peer: &PeerId) -> Result<()> {
25 let pending_messages = self.outbox.get_pending().await?;
26
27 if pending_messages.is_empty() {
28 return Ok(());
29 }
30
31 let Some(network) = &self.network else {
32 debug!("No network handle available for outbox retry");
33 return Ok(());
34 };
35
36 debug!(
37 "Retrying {} pending messages for peer {}",
38 pending_messages.len(),
39 target_peer
40 );
41
42 for message in pending_messages {
43 if message.recipient != *target_peer {
44 continue;
45 }
46
47 match network
48 .send_message(message.recipient, message.clone())
49 .await
50 {
51 Ok(()) => {
52 self.outbox.remove_pending(&message.id).await?;
53 info!(
54 "Successfully delivered message {} to {}",
55 message.id, message.recipient
56 );
57 }
58 Err(e) => {
59 debug!(
60 "Failed to deliver message {} to {}: {}",
61 message.id, message.recipient, e
62 );
63 }
64 }
65 }
66
67 Ok(())
68 }
69}