Skip to content

Commit 55add0d

Browse files
committed
refactor: less spawning, more selecting
1 parent e927579 commit 55add0d

File tree

1 file changed

+18
-14
lines changed

1 file changed

+18
-14
lines changed

crates/rostra-client/src/client.rs

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ impl Client {
257257
let endpoints = self.db.get_id_endpoints(id).await;
258258

259259
// Try all known endpoints in parallel
260-
let mut connection_attempts = Vec::new();
260+
let mut connection_futures = Vec::new();
261261
for ((_ts, node_id), _stats) in endpoints {
262262
let Ok(node_id) = iroh::NodeId::from_bytes(&node_id.to_bytes()) else {
263263
debug!(target: LOG_TARGET, %id, "Invalid iroh id for rostra id found");
@@ -270,7 +270,7 @@ impl Client {
270270
}
271271

272272
let endpoint = self.endpoint.clone();
273-
connection_attempts.push(tokio::spawn(async move {
273+
connection_futures.push(Box::pin(async move {
274274
let conn = endpoint
275275
.connect(node_id, ROSTRA_P2P_V0_ALPN)
276276
.await
@@ -283,28 +283,32 @@ impl Client {
283283
}));
284284
}
285285

286-
if !connection_attempts.is_empty() {
287-
// Wait for first successful connection or all failures
288-
for attempt in connection_attempts {
289-
match attempt.await {
290-
Ok(Ok(conn)) => return Ok(conn),
291-
Ok(Err(err)) => {
286+
if !connection_futures.is_empty() {
287+
use futures::future::select_all;
288+
289+
// Try all connections in parallel, take first success
290+
while !connection_futures.is_empty() {
291+
let (result, _index, remaining) = select_all(connection_futures).await;
292+
connection_futures = remaining;
293+
294+
match result {
295+
Ok(conn) => return Ok(conn),
296+
Err(err) => {
292297
debug!(
293298
target: LOG_TARGET,
294299
%id,
295300
err = %err.fmt_compact(),
296301
"Failed to connect to endpoint"
297302
);
298303
}
299-
Err(_) => continue,
300304
}
301305
}
306+
debug!(
307+
target: LOG_TARGET,
308+
%id,
309+
"All known endpoints failed, trying pkarr resolution"
310+
);
302311
}
303-
debug!(
304-
target: LOG_TARGET,
305-
%id,
306-
"All known endpoints failed, trying pkarr resolution"
307-
);
308312

309313
// Fall back to pkarr if no known endpoints worked
310314
self.connect_by_pkarr_resolution(id).await

0 commit comments

Comments
 (0)