From 49871d27e5f5f984f73ff971de3d9c3af1a40a3e Mon Sep 17 00:00:00 2001
From: Ishaan Goel <ishaangoel.99@gmail.com>
Date: Fri, 10 Jan 2025 11:07:48 +0530
Subject: [PATCH] request retry

---
 src/main.rs                                  |  2 +-
 zung_torrent/src/lib.rs                      |  4 +---
 zung_torrent/src/sources/mod.rs              | 14 ++++++++++++--
 zung_torrent/src/sources/trackers/mod.rs     |  6 ++----
 zung_torrent/src/sources/trackers/request.rs |  7 ++++---
 5 files changed, 20 insertions(+), 13 deletions(-)

diff --git a/src/main.rs b/src/main.rs
index 973e472..8f3d064 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -28,7 +28,7 @@ async fn main() -> anyhow::Result<()> {
     tracing_subscriber::fmt()
         // all spans/events with a level higher than TRACE (e.g, info, warn, etc.)
         // will be written to stdout.
-        .with_env_filter("zung=trace")
+        .with_env_filter("zung=info")
         .without_time()
         .compact()
         // display source code file paths
diff --git a/zung_torrent/src/lib.rs b/zung_torrent/src/lib.rs
index 691352e..5dc2fb7 100644
--- a/zung_torrent/src/lib.rs
+++ b/zung_torrent/src/lib.rs
@@ -95,9 +95,7 @@ impl TorrentArgs {
 
                 if let Some(list) = torrent.sources().tracker_list() {
                     for t in list {
-                        if t.is_connected() {
-                            println!("{} -> {}", t.url().cyan(), t.trys())
-                        }
+                        println!("{} -> {}", t.trys(), t.url().cyan());
                     }
                 }
             }
diff --git a/zung_torrent/src/sources/mod.rs b/zung_torrent/src/sources/mod.rs
index 7f4ad32..ed0db8c 100644
--- a/zung_torrent/src/sources/mod.rs
+++ b/zung_torrent/src/sources/mod.rs
@@ -217,12 +217,12 @@ impl DownloadSources {
     }
 
     pub async fn retry_connect_all(&self, info_hash: InfoHashEncoded, peer_id: PeerID) {
-        println!("hi");
         if let Some(list) = self.tracker_list() {
+            let mut handles = Vec::new();
             for tracker in list {
                 if !tracker.is_connected() {
                     let tracker = tracker.clone();
-                    tokio::spawn(async move {
+                    let handle = tokio::spawn(async move {
                         let mut i = 0;
                         loop {
                             i += 1;
@@ -238,13 +238,23 @@ impl DownloadSources {
                                 Err(_) => {
                                     if i < 10 {
                                         continue;
+                                    } else {
+                                        break;
                                     }
                                 }
                             }
                         }
                     });
+
+                    handles.push(handle);
                 }
             }
+
+            tokio::spawn(async {
+                futures::future::join_all(handles).await;
+            })
+            .await
+            .unwrap();
         }
     }
 
diff --git a/zung_torrent/src/sources/trackers/mod.rs b/zung_torrent/src/sources/trackers/mod.rs
index 3d7cafd..6f428d2 100644
--- a/zung_torrent/src/sources/trackers/mod.rs
+++ b/zung_torrent/src/sources/trackers/mod.rs
@@ -70,9 +70,8 @@ impl Tracker {
         info_hash: InfoHashEncoded,
         peer_id: PeerID,
     ) -> Result<()> {
-        // Generate Tracker request.
-        // - Http => Generates a url.
-        // - UDP => Sends a UDP connect request
+        self.inner.trys.fetch_add(1, Ordering::SeqCst);
+
         let request = self
             .url
             .generate_request(socket, info_hash, peer_id)
@@ -82,7 +81,6 @@ impl Tracker {
         let response = request.make_request().await?;
 
         self.inner.connected.store(true, Ordering::Relaxed);
-        self.inner.trys.fetch_add(1, Ordering::SeqCst);
 
         self.set_request(request)?;
         self.set_response(response)?;
diff --git a/zung_torrent/src/sources/trackers/request.rs b/zung_torrent/src/sources/trackers/request.rs
index 07f0ba6..1b8de1b 100644
--- a/zung_torrent/src/sources/trackers/request.rs
+++ b/zung_torrent/src/sources/trackers/request.rs
@@ -6,7 +6,7 @@ use serde::Serialize;
 
 use tokio::net::UdpSocket;
 use tokio::time::timeout;
-use tracing::{instrument, trace, warn};
+use tracing::{instrument, trace};
 use zung_parsers::bencode;
 
 use crate::meta_info::InfoHashEncoded;
@@ -88,9 +88,10 @@ impl TrackerRequest {
 
     #[instrument(skip_all, name = "Tracker Request")]
     pub async fn make_request(&self) -> Result<bencode::Value> {
+        let url = self.to_url()?;
+
         match self {
             TrackerRequest::Http { .. } => {
-                let url = self.to_url()?;
                 let request = timeout(REQUEST_TIMEOUT_DURATION, reqwest::get(&url))
                     .await
                     .with_context(|| format!("Connection Timed Out: {url}"))?
@@ -106,7 +107,7 @@ impl TrackerRequest {
                 Ok(response)
             }
             TrackerRequest::Udp { .. } => {
-                warn!(url = self.to_url()?, "UDP connection is to be implemented");
+                // warn!(url = self.to_url()?, "UDP connection is to be implemented");
                 Err(anyhow!(""))
             }
             TrackerRequest::Empty => Err(anyhow!("Making Request on empty string")),