Sfoglia il codice sorgente

[bin/darkfid2] async retry receive with timeout

ertosns 2 anni fa
parent
commit
00d00ae6bd
3 ha cambiato i file con 23 aggiunte e 7 eliminazioni
  1. 1 0
      bin/darkfid2/Cargo.toml
  2. 1 1
      bin/darkfid2/src/task/mod.rs
  3. 21 6
      bin/darkfid2/src/task/sync.rs

+ 1 - 0
bin/darkfid2/Cargo.toml

@@ -24,6 +24,7 @@ log = "0.4.20"
 num-bigint = "0.4.4"
 sled = "0.34.7"
 rand = "0.8.5"
+async-std = "1.12.0"
 
 # JSON-RPC
 async-trait = "0.1.74"

+ 1 - 1
bin/darkfid2/src/task/mod.rs

@@ -19,7 +19,7 @@
 // TODO: Handle ? with matches in these files. They should be robust.
 
 pub mod sync;
-pub use sync::{sync_task};
+pub use sync::sync_task;
 
 pub mod miner;
 pub use miner::miner_task;

+ 21 - 6
bin/darkfid2/src/task/sync.rs

@@ -20,6 +20,8 @@ use darkfi::{system::sleep, util::encoding::base64};
 use darkfi_serial::serialize;
 use log::{debug, info, warn, error};
 use tinyjson::JsonValue;
+use std::time::Duration;
+use async_std::future;
 
 use crate::{
     proto::{SyncRequest, SyncResponse},
@@ -74,21 +76,34 @@ pub async fn sync_task(node: &Darkfid) {
         if let Err(why) = channel.send(&request).await {
             error!(target: "darkfid::task::sync_task", "request send failure: {:}", why);
             sleep(10).await;
+            // try to resend
             continue;
         }
 
-        // TODO: add a timeout here to retry
+
+        let mut counter = 0;
+        let mut response_result;
         // Node waits for response
-        let response = match block_response_sub.receive().await {
-            Err(why) => {
-                panic!("darkfid::task::sync_task block_response_sub receive error at recv_queue recv: {:?}", why)
-            },
-            Ok(value) => value
+        loop {
+            let timeout_response_result = future::timeout(Duration::from_millis(10), block_response_sub.receive()).await;
+            response_result = timeout_response_result.unwrap();
+            if response_result.is_ok() {
+                break
+            } else {
+                sleep(10).await;
+                counter +=1;
+            }
+            if counter == 10 {
+                panic!("darkfid::task::sync_task block_response_sub receive error at recv_queue recv")
+            }
         };
+        // safe to unwrap at this point, if returned error after retries it should had  paniced.
+        let response = response_result.unwrap();
 
         // Verify and store retrieved blocks
         debug!(target: "darkfid::task::sync_task", "Processing received blocks");
         if let Err(why) = node.validator.write().await.add_blocks(&response.blocks).await {
+            // nothing to do if the requested block verification fails.
             panic!("darkfid::task::sync_task block validation failed: {:?}", why)
         };