Skip to content

Commit 617fa50

Browse files
authored
refactor: Use n0-future in favor of futures-* libraries and tokio::{spawn,task,time} (#3156)
## Description - replaces all imports of `futures_lite`, `futures_util`, `futures_sink` and `futures_buffered` with re-exports from `n0_future`. - replaces all imports of `std::time` with `n0_future::time` - replaces all occurrences of `tokio::{spawn,task,time}` with `n0_future::{spawn,task,time}` - **does not affect tests**: we use a bunch of special things there, like `tokio::time::advance` that we don't have n0-future yet. It's also not strictly necessary for shipping e.g. browser stuff. The goal of this PR is - to get us closer to browser compatibility (I've verified that I've replaced enough of all task spawning, etc. such that mostly cfg-ing out and other unrelated changes remain browser support) - to make the diffs of the browser-support PRs easier to follow Essentially this is work extracted out of the browser PRs. ## Breaking Changes I don't think there are any breaking changes from this. It's possible that `JoinSet` or `JoinHandle` types leak from the interfaces somewhere, but they're identical to the old ones (just re-exports) outside of `wasm*-*-unknown` targets. ## Notes & open questions I've tried setting up semgrep, but (1) IIUC, setting it up for CI requires that you have an account with them, only running locally is free and (2) I haven't found a way to ignore e.g. `std::time` imports when you're inside a `*::tests` module, which means we'd either need to convert all our tests to `n0-future` or ignore warnings and I think both of these options might suck. ## Change checklist - [x] Self-review. - [x] All breaking changes documented.
1 parent 03e3e3c commit 617fa50

39 files changed

+220
-229
lines changed

Cargo.lock

Lines changed: 7 additions & 9 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

iroh-dns-server/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,13 @@ derive_more = { version = "1.0.0", features = [
2424
"from",
2525
] }
2626
dirs-next = "2.0.0"
27-
futures-lite = "2.5"
2827
governor = "0.6.3" #needs new release of tower_governor for 0.7.0
2928
hickory-server = { version = "=0.25.0-alpha.4", features = ["dns-over-rustls", "dns-over-https-rustls"] }
3029
http = "1.0.0"
3130
humantime-serde = "1.1.1"
3231
iroh-metrics = { version = "0.31.0" }
3332
lru = "0.12.3"
33+
n0-future = "0.1.2"
3434
pkarr = { version = "2.3.1", features = [ "async", "relay", "dht"], default-features = false }
3535
rcgen = "0.13"
3636
redb = "2.0.0"

iroh-dns-server/src/http/tls.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use axum_server::{
1010
accept::Accept,
1111
tls_rustls::{RustlsAcceptor, RustlsConfig},
1212
};
13-
use futures_lite::{future::Boxed as BoxFuture, FutureExt};
13+
use n0_future::{future::Boxed as BoxFuture, FutureExt};
1414
use serde::{Deserialize, Serialize};
1515
use tokio::io::{AsyncRead, AsyncWrite};
1616
use tokio_rustls_acme::{axum::AxumAcceptor, caches::DirCache, AcmeConfig};

iroh-net-report/Cargo.toml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,11 @@ workspace = true
1919
anyhow = "1"
2020
bytes = "1.7"
2121
derive_more = { version = "1.0.0", features = ["display"] }
22-
futures-buffered = "0.2.8"
23-
futures-lite = "2.3"
2422
hickory-resolver = "=0.25.0-alpha.4"
2523
iroh-base = { version = "0.31.0", path = "../iroh-base", default-features = false, features = ["relay"] }
2624
iroh-metrics = { version = "0.31", default-features = false }
2725
iroh-relay = { version = "0.31", path = "../iroh-relay" }
26+
n0-future = "0.1.2"
2827
netwatch = { version = "0.3" }
2928
portmapper = { version = "0.3", default-features = false }
3029
quinn = { package = "iroh-quinn", version = "0.13.0" }

iroh-net-report/src/defaults.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
33
/// Contains all timeouts that we use in `iroh-net-report`.
44
pub(crate) mod timeouts {
5-
use std::time::Duration;
5+
use n0_future::time::Duration;
66

77
// Timeouts for net_report
88

iroh-net-report/src/dns.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
use std::{fmt::Write, net::IpAddr};
22

33
use anyhow::Result;
4-
use futures_lite::{Future, StreamExt};
54
use hickory_resolver::{IntoName, TokioResolver};
5+
use n0_future::{time, Future, StreamExt};
66

77
use crate::defaults::timeouts::DNS_TIMEOUT;
88

@@ -66,12 +66,12 @@ pub(crate) trait ResolverExt {
6666

6767
impl ResolverExt for TokioResolver {
6868
async fn lookup_ipv4<N: IntoName>(&self, host: N) -> Result<impl Iterator<Item = IpAddr>> {
69-
let addrs = tokio::time::timeout(DNS_TIMEOUT, self.ipv4_lookup(host)).await??;
69+
let addrs = time::timeout(DNS_TIMEOUT, self.ipv4_lookup(host)).await??;
7070
Ok(addrs.into_iter().map(|ip| IpAddr::V4(ip.0)))
7171
}
7272

7373
async fn lookup_ipv6<N: IntoName>(&self, host: N) -> Result<impl Iterator<Item = IpAddr>> {
74-
let addrs = tokio::time::timeout(DNS_TIMEOUT, self.ipv6_lookup(host)).await??;
74+
let addrs = time::timeout(DNS_TIMEOUT, self.ipv6_lookup(host)).await??;
7575
Ok(addrs.into_iter().map(|ip| IpAddr::V6(ip.0)))
7676
}
7777

@@ -150,14 +150,14 @@ async fn stagger_call<T, F: Fn() -> Fut, Fut: Future<Output = Result<T>>>(
150150
f: F,
151151
delays_ms: &[u64],
152152
) -> Result<T> {
153-
let mut calls = futures_buffered::FuturesUnorderedBounded::new(delays_ms.len() + 1);
153+
let mut calls = n0_future::FuturesUnorderedBounded::new(delays_ms.len() + 1);
154154
// NOTE: we add the 0 delay here to have a uniform set of futures. This is more performant than
155155
// using alternatives that allow futures of different types.
156156
for delay in std::iter::once(&0u64).chain(delays_ms) {
157-
let delay = std::time::Duration::from_millis(*delay);
157+
let delay = time::Duration::from_millis(*delay);
158158
let fut = f();
159159
let staggered_fut = async move {
160-
tokio::time::sleep(delay).await;
160+
time::sleep(delay).await;
161161
fut.await
162162
};
163163
calls.push(staggered_fut)

iroh-net-report/src/lib.rs

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,12 @@ use iroh_base::RelayUrl;
2323
#[cfg(feature = "metrics")]
2424
use iroh_metrics::inc;
2525
use iroh_relay::{protos::stun, RelayMap};
26-
use netwatch::UdpSocket;
27-
use tokio::{
28-
sync::{self, mpsc, oneshot},
26+
use n0_future::{
27+
task::{self, AbortOnDropHandle},
2928
time::{Duration, Instant},
3029
};
31-
use tokio_util::task::AbortOnDropHandle;
30+
use netwatch::UdpSocket;
31+
use tokio::sync::{self, mpsc, oneshot};
3232
use tracing::{debug, error, info_span, trace, warn, Instrument};
3333

3434
mod defaults;
@@ -351,7 +351,7 @@ impl Client {
351351
pub fn new(port_mapper: Option<portmapper::Client>, dns_resolver: DnsResolver) -> Result<Self> {
352352
let mut actor = Actor::new(port_mapper, dns_resolver)?;
353353
let addr = actor.addr();
354-
let task = tokio::spawn(
354+
let task = task::spawn(
355355
async move { actor.run().await }.instrument(info_span!("net_report.actor")),
356356
);
357357
let drop_guard = AbortOnDropHandle::new(task);
@@ -899,7 +899,7 @@ pub(crate) mod stun_utils {
899899
);
900900
{
901901
let sock = sock.clone();
902-
tokio::spawn(
902+
task::spawn(
903903
async move {
904904
debug!("udp stun socket listener started");
905905
// TODO: Can we do better for buffers here? Probably doesn't matter much.
@@ -988,7 +988,6 @@ mod tests {
988988

989989
use bytes::BytesMut;
990990
use netwatch::IpFamily;
991-
use tokio::time;
992991
use tokio_util::sync::CancellationToken;
993992
use tracing::info;
994993

@@ -1388,7 +1387,7 @@ mod tests {
13881387
let mut actor = Actor::new(None, resolver.clone()).unwrap();
13891388
for s in &mut tt.steps {
13901389
// trigger the timer
1391-
time::advance(Duration::from_secs(s.after)).await;
1390+
tokio::time::advance(Duration::from_secs(s.after)).await;
13921391
let r = Arc::try_unwrap(s.r.take().unwrap()).unwrap();
13931392
s.r = Some(actor.add_report_history_and_set_preferred_relay(r));
13941393
}

iroh-net-report/src/reportgen.rs

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ use std::{
2323
pin::Pin,
2424
sync::Arc,
2525
task::{Context, Poll},
26-
time::Duration,
2726
};
2827

2928
use anyhow::{anyhow, bail, Context as _, Result};
@@ -37,14 +36,13 @@ use iroh_relay::{
3736
protos::stun,
3837
RelayMap, RelayNode,
3938
};
39+
use n0_future::{
40+
task::{self, AbortOnDropHandle, JoinSet},
41+
time::{self, Duration, Instant},
42+
};
4043
use netwatch::{interfaces, UdpSocket};
4144
use rand::seq::IteratorRandom;
42-
use tokio::{
43-
sync::{mpsc, oneshot},
44-
task::JoinSet,
45-
time::{self, Instant},
46-
};
47-
use tokio_util::task::AbortOnDropHandle;
45+
use tokio::sync::{mpsc, oneshot};
4846
use tracing::{debug, debug_span, error, info_span, trace, warn, Instrument, Span};
4947
use url::Host;
5048

@@ -115,9 +113,8 @@ impl Client {
115113
dns_resolver,
116114
protocols,
117115
};
118-
let task = tokio::spawn(
119-
async move { actor.run().await }.instrument(info_span!("reportgen.actor")),
120-
);
116+
let task =
117+
task::spawn(async move { actor.run().await }.instrument(info_span!("reportgen.actor")));
121118
Self {
122119
_drop_guard: AbortOnDropHandle::new(task),
123120
}
@@ -245,9 +242,9 @@ impl Actor {
245242
let mut captive_task = self.prepare_captive_portal_task();
246243
let mut probes = self.spawn_probes_task().await?;
247244

248-
let total_timer = tokio::time::sleep(OVERALL_REPORT_TIMEOUT);
245+
let total_timer = time::sleep(OVERALL_REPORT_TIMEOUT);
249246
tokio::pin!(total_timer);
250-
let probe_timer = tokio::time::sleep(PROBES_TIMEOUT);
247+
let probe_timer = time::sleep(PROBES_TIMEOUT);
251248
tokio::pin!(probe_timer);
252249

253250
loop {
@@ -385,7 +382,7 @@ impl Actor {
385382
delay=?timeout,
386383
"Have enough probe reports, aborting further probes soon",
387384
);
388-
tokio::spawn(
385+
task::spawn(
389386
async move {
390387
time::sleep(timeout).await;
391388
// Because we do this after a timeout it is entirely normal that the
@@ -488,9 +485,9 @@ impl Actor {
488485
self.outstanding_tasks.captive_task = true;
489486
MaybeFuture {
490487
inner: Some(Box::pin(async move {
491-
tokio::time::sleep(CAPTIVE_PORTAL_DELAY).await;
488+
time::sleep(CAPTIVE_PORTAL_DELAY).await;
492489
debug!("Captive portal check started after {CAPTIVE_PORTAL_DELAY:?}");
493-
let captive_portal_check = tokio::time::timeout(
490+
let captive_portal_check = time::timeout(
494491
CAPTIVE_PORTAL_TIMEOUT,
495492
check_captive_portal(&dns_resolver, &dm, preferred_relay)
496493
.instrument(debug_span!("captive-portal")),
@@ -719,7 +716,7 @@ async fn run_probe(
719716
) -> Result<ProbeReport, ProbeError> {
720717
if !probe.delay().is_zero() {
721718
trace!("delaying probe");
722-
tokio::time::sleep(probe.delay()).await;
719+
time::sleep(probe.delay()).await;
723720
}
724721
debug!("starting probe");
725722

iroh-net-report/src/reportgen/hairpin.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,12 @@ use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
1616

1717
use anyhow::{bail, Context, Result};
1818
use iroh_relay::protos::stun;
19+
use n0_future::{
20+
task::{self, AbortOnDropHandle},
21+
time::{self, Instant},
22+
};
1923
use netwatch::UdpSocket;
20-
use tokio::{sync::oneshot, time::Instant};
21-
use tokio_util::task::AbortOnDropHandle;
24+
use tokio::sync::oneshot;
2225
use tracing::{debug, error, info_span, trace, warn, Instrument};
2326

2427
use crate::{self as net_report, defaults::timeouts::HAIRPIN_CHECK_TIMEOUT, reportgen, Inflight};
@@ -43,7 +46,7 @@ impl Client {
4346
};
4447

4548
let task =
46-
tokio::spawn(async move { actor.run().await }.instrument(info_span!("hairpin.actor")));
49+
task::spawn(async move { actor.run().await }.instrument(info_span!("hairpin.actor")));
4750
Self {
4851
addr: Some(addr),
4952
_drop_guard: AbortOnDropHandle::new(task),
@@ -127,7 +130,7 @@ impl Actor {
127130
}
128131

129132
let now = Instant::now();
130-
let hairpinning_works = match tokio::time::timeout(HAIRPIN_CHECK_TIMEOUT, stun_rx).await {
133+
let hairpinning_works = match time::timeout(HAIRPIN_CHECK_TIMEOUT, stun_rx).await {
131134
Ok(Ok(_)) => true,
132135
Ok(Err(_)) => bail!("net_report actor dropped stun response channel"),
133136
Err(_) => false, // Elapsed

iroh-net-report/src/reportgen/probes.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ use std::{collections::BTreeSet, fmt, sync::Arc};
99
use anyhow::{ensure, Result};
1010
use iroh_base::RelayUrl;
1111
use iroh_relay::{RelayMap, RelayNode};
12+
use n0_future::time::Duration;
1213
use netwatch::interfaces;
13-
use tokio::time::Duration;
1414

1515
use crate::Report;
1616

iroh-relay/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ hyper = { version = "1", features = ["server", "client", "http1"] }
2929
hyper-util = "0.1.1"
3030
iroh-base = { version = "0.31.0", path = "../iroh-base", default-features = false, features = ["key", "relay"] }
3131
iroh-metrics = { version = "0.31", default-features = false }
32-
n0-future = { version = "0.0.1" }
32+
n0-future = "0.1.2"
3333
num_enum = "0.7"
3434
pin-project = "1"
3535
postcard = { version = "1", default-features = false, features = [

iroh-relay/src/client/conn.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,12 @@ use std::{
66
io,
77
pin::Pin,
88
task::{Context, Poll},
9-
time::Duration,
109
};
1110

1211
use anyhow::{bail, Result};
1312
use bytes::Bytes;
1413
use iroh_base::{NodeId, SecretKey};
15-
use n0_future::{Sink, Stream};
14+
use n0_future::{time::Duration, Sink, Stream};
1615
use tokio_tungstenite_wasm::WebSocketStream;
1716
#[cfg(not(wasm_browser))]
1817
use tokio_util::codec::Framed;

0 commit comments

Comments
 (0)