diff --git a/Cargo.lock b/Cargo.lock index b9b549b13e..f7c22ac45b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1964,6 +1964,7 @@ dependencies = [ "bytes", "cfg_aliases", "clap", + "console", "console_error_panic_hook", "data-encoding", "derive_more", diff --git a/iroh-base/src/key.rs b/iroh-base/src/key.rs index 9cb7b01bdd..c002baa52c 100644 --- a/iroh-base/src/key.rs +++ b/iroh-base/src/key.rs @@ -132,7 +132,7 @@ impl PublicKey { /// Convert to a hex string limited to the first 5 bytes for a friendly string /// representation of the key. - pub fn fmt_short(&self) -> impl Display + 'static { + pub fn fmt_short(&self) -> impl Display + Copy + 'static { PublicKeyShort( self.0.as_bytes()[0..5] .try_into() @@ -153,6 +153,7 @@ impl PublicKey { } } +#[derive(Copy, Clone)] struct PublicKeyShort([u8; 5]); impl Display for PublicKeyShort { diff --git a/iroh/Cargo.toml b/iroh/Cargo.toml index d939b4fc1f..d5fc843963 100644 --- a/iroh/Cargo.toml +++ b/iroh/Cargo.toml @@ -135,6 +135,7 @@ tracing-subscriber = { version = "0.3", features = [ indicatif = { version = "0.18", features = ["tokio"] } parse-size = { version = "1.1.0", features = ['std'] } iroh-base = { version = "0.95.1", default-features = false, features = ["key", "relay"], path = "../iroh-base" } +console = { version = "0.16" } # wasm-in-browser test/dev dependencies [target.'cfg(all(target_family = "wasm", target_os = "unknown"))'.dev-dependencies] diff --git a/iroh/examples/transfer.rs b/iroh/examples/transfer.rs index ae4f211058..431763de69 100644 --- a/iroh/examples/transfer.rs +++ b/iroh/examples/transfer.rs @@ -1,13 +1,39 @@ +//! Transfer data between two endpoints and print various stats and metrics. +//! +//! This example implements a transfer protocol to upload or download data between two iroh endpoints +//! with a time or size limit. After the transfer finishes, statistics about the transfer and the used +//! network paths are printed. +//! +//! It is not the typical "simple" example, yet it may be interesting to read because it uses most of +//! iroh's endpoint builder options. We use it for manual testing before release, and it also runs as +//! part of our CI infrastructure. +//! +//! You can use this example to easily test iroh connectivity between devices. Usage is straightforward: +//! +//! ```sh +//! # Run in release mode and with all features and print available commands and options: +//! cargo run --example transfer --release --all-features -- help +//! +//! # Run a provider endpoint on a device +//! cargo run --example transfer --release --all-features -- provide +//! +//! # And connect to the provider endpoint from another device +//! cargo run --example transfer --release --all-features -- fetch PROVIDER_ENDPOINT_ID +//! ``` + use std::{ collections::BTreeMap, + fmt, net::{SocketAddr, SocketAddrV4, SocketAddrV6}, str::FromStr, time::{Duration, Instant}, }; use bytes::Bytes; -use clap::{Parser, Subcommand}; +use clap::{Parser, Subcommand, ValueEnum}; +use console::Style; use data_encoding::HEXLOWER; +use derive_more::{Display, From}; use indicatif::HumanBytes; use iroh::{ Endpoint, EndpointAddr, EndpointId, RelayMap, RelayMode, RelayUrl, SecretKey, TransportAddr, @@ -17,24 +43,34 @@ use iroh::{ pkarr::{N0_DNS_PKARR_RELAY_PROD, N0_DNS_PKARR_RELAY_STAGING, PkarrPublisher}, }, dns::{DnsResolver, N0_DNS_ENDPOINT_ORIGIN_PROD, N0_DNS_ENDPOINT_ORIGIN_STAGING}, - endpoint::{BindOpts, ConnectionError, PathInfo, PathInfoList}, + endpoint::{ + BindOpts, Connection, ConnectionError, PathInfoList, RecvStream, SendStream, VarInt, + WriteError, + }, }; -use n0_error::{Result, StackResultExt, StdResultExt}; -use n0_future::task::AbortOnDropHandle; +use n0_error::{Result, StackResultExt, StdResultExt, anyerr, ensure_any}; +use n0_future::{stream::StreamExt, task::AbortOnDropHandle}; use netdev::ipnet::{Ipv4Net, Ipv6Net}; -use quinn::PathStats; -use tokio_stream::StreamExt; -use tracing::{info, warn}; +use postcard::experimental::max_size::MaxSize; +use serde::{Deserialize, Serialize, Serializer}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + time::timeout, +}; +use tracing::{Instrument, debug, instrument, warn}; use url::Url; -// Transfer ALPN that we are using to communicate over the `Endpoint` -const TRANSFER_ALPN: &[u8] = b"n0/iroh/transfer/example/0"; +/// ALPN of our transport protocol. +const TRANSFER_ALPN: &[u8] = b"n0/iroh/transfer/example/1"; const DEV_RELAY_URL: &str = "http://localhost:3340"; const DEV_PKARR_RELAY_URL: &str = "http://localhost:8080/pkarr"; const DEV_DNS_ORIGIN_DOMAIN: &str = "irohdns.example"; const DEV_DNS_SERVER: &str = "127.0.0.1:5300"; +/// Connection error code for a gracefully closed connection. +const GRACEFUL_CLOSE: VarInt = VarInt::from_u32(1); + /// Transfer data between iroh endpoints. /// /// This is a useful example to test connection establishment and transfer speed. @@ -56,11 +92,14 @@ const DEV_DNS_SERVER: &str = "127.0.0.1:5300"; #[derive(Parser, Debug)] #[command(name = "transfer")] struct Cli { + /// Output format. + #[clap(global = true, long, value_enum, default_value_t)] + output: OutputMode, #[command(subcommand)] command: Commands, } -#[derive(Clone, Copy, Default, Debug, Eq, PartialEq, clap::ValueEnum)] +#[derive(Clone, Copy, Default, Debug, Eq, PartialEq, clap::ValueEnum, Serialize)] enum Env { /// Use the production servers hosted by number0. Prod, @@ -105,7 +144,71 @@ impl Env { } } -#[derive(Debug, clap::Parser)] +#[derive(Serialize, Deserialize, ValueEnum, Default, Debug, Clone, Copy)] +enum Mode { + /// We send data to the remote, measuring our upload speed. + Upload, + /// We receive data from the remote, measuring our download speed. + #[default] + Download, + /// We send and receive data in parallel. + Bidi, +} + +#[derive(Serialize, Deserialize, MaxSize, derive_more::Debug, Clone, Copy)] +enum Length { + #[debug("Size({})", HumanBytes(*_0))] + Size(u64), + #[debug("Duration({_0:?})")] + Duration(#[serde(with = "duration_micros")] Duration), +} + +impl Length { + fn remaining(&self, start: Instant, size: usize) -> (Duration, usize) { + match self { + Length::Duration(limit) => (limit.saturating_sub(start.elapsed()), usize::MAX), + Length::Size(limit) => (Duration::MAX, (*limit as usize).saturating_sub(size)), + } + } +} + +#[derive(Debug, Serialize, Clone, Copy)] +enum RequestKind { + Upload, + Download, +} + +#[derive(Serialize, Deserialize, MaxSize, Debug, Clone)] +enum Request { + Download(Length), + Upload, +} + +impl Request { + async fn read(recv: &mut RecvStream) -> Result { + let header_len = recv.read_u32().await.anyerr()? as usize; + ensure_any!( + header_len <= Self::POSTCARD_MAX_SIZE, + "received invalid header length" + ); + let mut buf = vec![0u8; header_len]; + recv.read_exact(&mut buf).await.anyerr()?; + let request = postcard::from_bytes(&buf).std_context("failed to decode request")?; + debug!("received request {request:?}"); + Ok(request) + } + + async fn write(&self, send: &mut SendStream) -> Result<()> { + debug!("sending request {self:?}"); + let buf = postcard::to_stdvec(&self).unwrap(); + send.write_u32(buf.len() as u32).await.anyerr()?; + send.write_all(&buf).await.anyerr()?; + Ok(()) + } +} + +#[derive(Debug, clap::Parser, Serialize)] +#[serde(tag = "kind")] struct EndpointArgs { /// Set the environment for relay, pkarr, and DNS servers. /// @@ -169,8 +272,6 @@ struct EndpointArgs { enum Commands { /// Provide data. Provide { - #[clap(long, default_value = "100M", value_parser = parse_byte_size)] - size: u64, #[clap(flatten)] endpoint_args: EndpointArgs, }, @@ -178,6 +279,17 @@ enum Commands { Fetch { /// Endpoint id of the remote to connect to. remote_id: EndpointId, + /// Transfer mode. + #[clap(long, value_enum, default_value_t)] + mode: Mode, + /// Limit the transferred data size. + #[clap(long, value_parser = parse_byte_size, conflicts_with = "duration")] + size: Option, + /// Limit the duration of the transfer, in seconds. + /// + /// [default: 10] + #[clap(long, conflicts_with = "size")] + duration: Option, /// Optionally set a relay URL for the remote. #[clap(long)] remote_relay_url: Option, @@ -194,31 +306,37 @@ const SHUTDOWN_TIME: Duration = Duration::from_secs(4); #[tokio::main] async fn main() -> Result<()> { - tracing_subscriber::fmt() - .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) - .init(); - let cli = Cli::parse(); - match cli.command { - Commands::Provide { - size, - endpoint_args, - } => { - let endpoint = endpoint_args.bind_endpoint().await?; - provide(endpoint, size).await? + tracing_subscriber::fmt::init(); + let Cli { command, output } = Cli::parse(); + match command { + Commands::Provide { endpoint_args } => { + output.emit_if_json(&endpoint_args); + let endpoint = endpoint_args.bind_endpoint(output).await?; + provide(endpoint, output).await? } Commands::Fetch { remote_id, remote_relay_url, remote_direct_address, endpoint_args, + mode, + size, + duration, } => { - let endpoint = endpoint_args.bind_endpoint().await?; + output.emit_if_json(&endpoint_args); + let length = match (size, duration) { + (Some(size), None) => Length::Size(size), + (None, Some(duration)) => Length::Duration(Duration::from_secs(duration)), + (None, None) => Length::Duration(Duration::from_secs(10)), + (Some(_), Some(_)) => unreachable!("--size and --duration args are conflicting"), + }; + let endpoint = endpoint_args.bind_endpoint(output).await?; let addrs = remote_relay_url .into_iter() .map(TransportAddr::Relay) .chain(remote_direct_address.into_iter().map(TransportAddr::Ip)); let remote_addr = EndpointAddr::from_parts(remote_id, addrs); - fetch(endpoint, remote_addr).await? + fetch(endpoint, remote_addr, length, mode, output).await? } } @@ -226,7 +344,7 @@ async fn main() -> Result<()> { } impl EndpointArgs { - async fn bind_endpoint(self) -> Result { + async fn bind_endpoint(self, output: OutputMode) -> Result { let relay_mode = if self.no_relay { RelayMode::Disabled } else if !self.relay_url.is_empty() { @@ -241,8 +359,9 @@ impl EndpointArgs { .context("Failed to parse IROH_SECRET environment variable as iroh secret key")?, Err(_) => { let s = SecretKey::generate(&mut rand::rng()); - println!("Generated a new endpoint secret. To reuse, set"); - println!("\tIROH_SECRET={}", HEXLOWER.encode(&s.to_bytes())); + output.emit(SecretGenerated { + secret_key: HEXLOWER.encode(&s.to_bytes()), + }); s } }; @@ -337,48 +456,33 @@ impl EndpointArgs { } } - let endpoint_id = endpoint.id(); - println!("Our endpoint id:\n\t{endpoint_id}"); - if self.relay_only { endpoint.online().await; } else if !self.no_relay { - tokio::time::timeout(Duration::from_secs(3), endpoint.online()) + timeout(Duration::from_secs(3), endpoint.online()) .await .ok(); } let endpoint_addr = endpoint.addr(); + output.emit(EndpointBound { + endpoint_id: endpoint.id(), + direct_addresses: endpoint_addr.ip_addrs().copied().collect(), + relay_url: endpoint_addr.relay_urls().next().cloned(), + }); - println!("Our direct addresses:"); - for addr in endpoint_addr.ip_addrs() { - println!("\t{addr}"); - } - - if let Some(url) = endpoint_addr.relay_urls().next() { - println!("Our home relay server:\t{url}"); - } else { - println!("No home relay server found"); - } - - println!(); Ok(endpoint) } } -async fn provide(endpoint: Endpoint, size: u64) -> Result<()> { - let endpoint_id = endpoint.id(); - let endpoint_addr = endpoint.addr(); - - println!("Endpoint id:\n{endpoint_id}"); - println!("Direct addresses:"); - for addr in endpoint_addr.ip_addrs() { - println!("\t{addr}"); - } - println!(); - - // accept incoming connections, returns a normal QUIC connection - while let Some(incoming) = endpoint.accept().await { +async fn provide(endpoint: Endpoint, output: OutputMode) -> Result<()> { + loop { + // Accept incoming connections until Ctrl-C is pressed. + let incoming = tokio::select! { + Some(incoming) = endpoint.accept() => incoming, + _ = tokio::signal::ctrl_c() => break, + else => break + }; let accepting = match incoming.accept() { Ok(accepting) => accepting, Err(err) => { @@ -388,229 +492,307 @@ async fn provide(endpoint: Endpoint, size: u64) -> Result<()> { continue; } }; - // spawn a task to handle reading and writing off of the connection + // Spawn a task for each connection. tokio::spawn(async move { - let conn = accepting.await.anyerr()?; - let endpoint_id = conn.remote_id(); - info!( - "new connection from {endpoint_id} with ALPN {}", - String::from_utf8_lossy(TRANSFER_ALPN), - ); - - let remote = endpoint_id.fmt_short(); - println!("[{remote}] Connected"); - - // Spawn a background task that prints connection type changes. Will be aborted on drop. - let _guard = watch_conn_type(conn.remote_id(), conn.paths()); - let stats_task = watch_path_stats(conn.clone()); - - // accept a bi-directional QUIC connection - // use the `quinn` APIs to send and recv content - let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; - tracing::debug!("accepted bi stream, waiting for data..."); - let message = recv.read_to_end(100).await.anyerr()?; - let message = String::from_utf8(message).anyerr()?; - println!("[{remote}] Received: \"{message}\""); - - let start = Instant::now(); - send_data_on_stream(&mut send, size).await?; - - // We sent the last message, so wait for the client to close the connection once - // it received this message. - let res = tokio::time::timeout(SHUTDOWN_TIME, async { - let closed = conn.closed().await; - let remote = endpoint_id.fmt_short(); - if !matches!(closed, ConnectionError::ApplicationClosed(_)) { - println!("[{remote}] Endpoint disconnected with an error: {closed:#}"); - } - }) - .await; - let duration = start.elapsed(); - - println!( - "[{remote}] Transferred {} in {:.4}s, {}/s", - HumanBytes(size), - duration.as_secs_f64(), - HumanBytes((size as f64 / duration.as_secs_f64()) as u64) - ); - if res.is_err() { - println!("[{remote}] Error: Did not disconnect within {SHUTDOWN_TIME:?}",); - } else { - println!("[{remote}] Disconnected"); + match accepting.await { + Ok(conn) => handle_connection(conn, output).await, + Err(err) => warn!("incoming connection failed during handshake: {err:#}"), } - let stats = stats_task - .await - .std_context("fetching stats task panicked")?; - println!("[{remote}] Path stats:"); - for (remote_addr, (_, stats)) in stats { - println!( - " {remote_addr:?}: RTT {:?}, tx={}, rx={}", - stats.rtt, stats.udp_tx.bytes, stats.udp_rx.bytes, - ); - } - n0_error::Ok(()) }); } - // stop with SIGINT (ctrl-c) + close_endpoint_with_timeout(&endpoint, output).await; + Ok(()) } -async fn fetch(endpoint: Endpoint, remote_addr: EndpointAddr) -> Result<()> { - let me = endpoint.id().fmt_short(); +#[instrument("conn", skip_all, fields(remote=%conn.remote_id().fmt_short()))] +async fn handle_connection(conn: Connection, output: OutputMode) { let start = Instant::now(); - let remote_id = remote_addr.id; - - // Attempt to connect, over the given ALPN. - // Returns a Quinn connection. - let conn = endpoint.connect(remote_addr, TRANSFER_ALPN).await?; - println!("Connected to {}", remote_id); - // Spawn a background task that prints connection type changes. Will be aborted on drop. - let _guard = watch_conn_type(conn.remote_id(), conn.paths()); + let remote_id = conn.remote_id(); + output.emit_with_remote(remote_id, ConnectionAccepted {}); + let _guard = watch_conn_type(conn.paths(), Some(remote_id), output); let stats_task = watch_path_stats(conn.clone()); - // Use the Quinn API to send and recv content. - let (mut send, recv) = conn.open_bi().await.anyerr()?; - - let message = format!("{me} is saying hello!"); - send.write_all(message.as_bytes()).await.anyerr()?; - // Call `finish` to signal no more data will be sent on this stream. - send.finish().anyerr()?; - println!("Sent: \"{message}\""); - - let (len, time_to_first_byte, chnk) = drain_stream(recv, false).await?; - - conn.close(0u32.into(), b"done"); - - let transfer_time = start.elapsed(); - - // We received the last message: close all connections and allow for the close - // message to be sent. - let shutdown_start = Instant::now(); - let shutdown = if let Err(_err) = tokio::time::timeout(SHUTDOWN_TIME, endpoint.close()).await { - warn!(timeout = ?SHUTDOWN_TIME, "Endpoint closing timed out"); - "Shutdown timed out".to_string() - } else { - format!( - "Shutdown took {:.4}s", - shutdown_start.elapsed().as_secs_f32() - ) - }; - drop(endpoint); - println!( - "Received {} in {:.4}s ({}/s, time to first byte {}s, {} chunks) ({shutdown})", - HumanBytes(len as u64), - transfer_time.as_secs_f64(), - HumanBytes((len as f64 / transfer_time.as_secs_f64()) as u64), - time_to_first_byte.as_secs_f64(), - chnk, - ); - let stats = stats_task - .await - .std_context("fetching stats task panicked")?; - println!("Path stats:"); - for (remote_addr, (_, stats)) in stats { - println!( - " {remote_addr:?}: RTT {:?}, tx={}, rx={}", - stats.rtt, stats.udp_tx.bytes, stats.udp_rx.bytes, + // Accept incoming streams in a loop until the connection is closed by the remote. + let close_reason = loop { + let (send, recv) = match conn.accept_bi().await { + Ok(streams) => streams, + Err(err) => break err, + }; + let conn = conn.clone(); + tokio::spawn( + async move { + if let Err(err) = handle_request(&conn, send, recv, output).await { + warn!("[{}] Request failed: {err:#}", remote_id.fmt_short()); + } + } + .instrument(tracing::Span::current()), ); - } + }; - Ok(()) + let is_graceful = matches!( + &close_reason, + ConnectionError::ApplicationClosed(f) if f.error_code == GRACEFUL_CLOSE + ); + let error = (!is_graceful).then(|| format!("{close_reason:#}")); + output.emit_with_remote( + remote_id, + ConnectionClosed { + error, + duration: start.elapsed(), + }, + ); + let path_stats = stats_task.await.expect("path stats task panicked"); + output.emit_with_remote(remote_id, path_stats); } -async fn drain_stream( - mut stream: iroh::endpoint::RecvStream, - read_unordered: bool, -) -> Result<(usize, Duration, u64)> { - let mut read = 0; - - let download_start = Instant::now(); - let mut first_byte = true; - let mut time_to_first_byte = download_start.elapsed(); - - let mut num_chunks: u64 = 0; - - if read_unordered { - let mut stream = stream.into_unordered(); - while let Some(chunk) = stream.read_chunk(usize::MAX).await.anyerr()? { - if first_byte { - time_to_first_byte = download_start.elapsed(); - first_byte = false; - } - read += chunk.bytes.len(); - num_chunks += 1; - } - } else { - // These are 32 buffers, for reading approximately 32kB at once - #[rustfmt::skip] - let mut bufs = [ - Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), - Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), - Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), - Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), - Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), - Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), - Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), - Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(), - ]; - - while let Some(n) = stream.read_chunks(&mut bufs[..]).await.anyerr()? { - if first_byte { - time_to_first_byte = download_start.elapsed(); - first_byte = false; - } - read += bufs.iter().take(n).map(|buf| buf.len()).sum::(); - num_chunks += 1; - } - } - - Ok((read, time_to_first_byte, num_chunks)) -} - -async fn send_data_on_stream( - stream: &mut iroh::endpoint::SendStream, - stream_size: u64, +#[instrument("handle", skip_all, fields(id=send.id().index()))] +async fn handle_request( + conn: &Connection, + send: SendStream, + mut recv: RecvStream, + output: OutputMode, ) -> Result<()> { - const DATA: &[u8] = &[0xAB; 1024 * 1024]; - let bytes_data = Bytes::from_static(DATA); - - let full_chunks = stream_size / (DATA.len() as u64); - let remaining = (stream_size % (DATA.len() as u64)) as usize; - - for _ in 0..full_chunks { - stream - .write_chunk(bytes_data.clone()) - .await - .std_context("failed sending data")?; - } - - if remaining != 0 { - stream - .write_chunk(bytes_data.slice(0..remaining)) - .await - .std_context("failed sending data")?; - } - - stream.finish().std_context("failed finishing stream")?; - stream - .stopped() + let request = Request::read(&mut recv) .await - .std_context("failed to wait for stream to be stopped")?; - + .context("failed to read request")?; + output.emit_with_remote(conn.remote_id(), HandleRequest { request: &request }); + match request { + Request::Download(length) => { + let stats = send_data(send, recv, length).await?; + output.emit_with_remote(conn.remote_id(), UploadComplete { stats }); + } + Request::Upload => { + let stats = drain_stream(recv, send, None).await?; + output.emit_with_remote(conn.remote_id(), DownloadComplete { stats }); + } + } Ok(()) } +async fn fetch( + endpoint: Endpoint, + remote_addr: EndpointAddr, + length: Length, + mode: Mode, + output: OutputMode, +) -> Result<()> { + // Attempt to connect, over the given ALPN. Returns a connection. + let start = Instant::now(); + let conn = endpoint.connect(remote_addr, TRANSFER_ALPN).await?; + let remote_id = conn.remote_id(); + output.emit(Connected { + remote_id, + duration: start.elapsed(), + }); + // Spawn a background task that prints connection type changes. Will be aborted on drop. + let _guard = watch_conn_type(conn.paths(), None, output); + let stats_task = watch_path_stats(conn.clone()); + + output.emit(StartRequest { mode, length }); + // Perform requests depending on the request mode. + let request_fut = async { + match mode { + Mode::Upload => { + perform_request(&conn, RequestKind::Upload, length, start, output).await? + } + Mode::Download => { + perform_request(&conn, RequestKind::Download, length, start, output).await? + } + Mode::Bidi => { + tokio::try_join!( + perform_request(&conn, RequestKind::Download, length, start, output), + perform_request(&conn, RequestKind::Upload, length, start, output), + )?; + } + } + // We finished our requests. Close the connection with our graceful error code. + conn.close(GRACEFUL_CLOSE, b"done"); + n0_error::Ok(()) + }; + + // Wait for the request to complete, or for the user to interrupt it with Ctrl-C + let res = tokio::select! { + res = request_fut => res, + _ = tokio::signal::ctrl_c() => Err(anyerr!("Cancelled")) + }; + + let error = conn + .close_reason() + .filter(|reason| !matches!(reason, ConnectionError::LocallyClosed)) + .map(|reason| format!("{reason:#}")); + output.emit(ConnectionClosed { + error, + duration: start.elapsed(), + }); + + close_endpoint_with_timeout(&endpoint, output).await; + let path_stats = stats_task.await.expect("path stats task panicked"); + output.emit(path_stats); + + res +} + +/// Close the endpoint, with a timeout, and emit emit once done. +async fn close_endpoint_with_timeout(endpoint: &Endpoint, output: OutputMode) { + let shutdown_start = Instant::now(); + let timed_out = timeout(SHUTDOWN_TIME, endpoint.close()).await.is_err(); + + output.emit(EndpointClosed { + duration: shutdown_start.elapsed(), + timed_out, + }); +} + +#[instrument("request", skip_all, fields(id = tracing::field::Empty))] +async fn perform_request( + conn: &Connection, + request_kind: RequestKind, + length: Length, + conn_start: Instant, + output: OutputMode, +) -> Result<()> { + let (mut send, recv) = conn.open_bi().await.anyerr()?; + tracing::Span::current().record("id", send.id().index()); + match request_kind { + RequestKind::Download => { + Request::Download(length).write(&mut send).await?; + let stats = drain_stream(recv, send, Some(conn_start)).await?; + output.emit(DownloadComplete { stats }); + } + RequestKind::Upload => { + Request::Upload.write(&mut send).await?; + let stats = send_data(send, recv, length).await?; + output.emit(UploadComplete { stats }); + } + } + Ok(()) +} + +/// Drain `recv`, and once done finish `send`. +#[instrument("drain_stream", skip_all)] +async fn drain_stream( + mut recv: RecvStream, + mut send: SendStream, + started_at: Option, +) -> Result { + debug!("start"); + let start = Instant::now(); + let mut read = 0; + let mut num_chunks: u64 = 0; + let mut time_to_first_byte = None; + + // These are 32 buffers, for reading approximately 32kB at once + let mut bufs: [Bytes; 32] = std::array::from_fn(|_| Bytes::new()); + + while let Some(n) = recv.read_chunks(&mut bufs[..]).await.anyerr()? { + // Update time to first byte if still empty and started_at is set. + if let (None, Some(started_at)) = (time_to_first_byte, started_at) { + time_to_first_byte = Some(started_at.elapsed()); + } + read += bufs.iter().take(n).map(Bytes::len).sum::(); + num_chunks += 1; + } + + send.finish().anyerr()?; + + let stats = DownloadStats { + size: read as u64, + time_to_first_byte, + num_chunks, + duration: start.elapsed(), + }; + debug!(?stats, "done"); + Ok(stats) +} + +/// Send data on `send` for `length`, afterwards wait for `recv` to be closed. +#[instrument("send_data", skip_all)] +async fn send_data( + mut send: SendStream, + mut recv: RecvStream, + length: Length, +) -> Result { + debug!(?length, "start"); + const DATA: &[u8] = &[0xAB; 1024 * 1024]; + let data = Bytes::from_static(DATA); + + let start = Instant::now(); + let mut total = 0; + loop { + let (remaining_time, remaining_size) = length.remaining(start, total); + let chunk = if remaining_size == 0 || remaining_time == Duration::ZERO { + break; + } else if remaining_size < data.len() { + data.slice(..remaining_size) + } else { + data.clone() + }; + total += write_chunk_timeout(&mut send, chunk, remaining_time) + .await + .std_context("failed to send data")?; + } + + send.finish().std_context("failed to finish stream")?; + + debug!("sending finished, wait for confirmation"); + recv.read_to_end(0).await.anyerr()?; + + let stats = UploadStats { + size: total as u64, + duration: start.elapsed(), + }; + debug!(?stats, "done"); + Ok(stats) +} + +/// Writes as much of [`Bytes`] to a [`SendStream`] as possible within `timeout`. +/// +/// Completes once `chunk` is fully written or after `timeout` elapses, whatever comes first. +/// +/// Returns the number of bytes written. +async fn write_chunk_timeout( + send: &mut SendStream, + chunk: Bytes, + timeout: Duration, +) -> Result { + // This follows the pattern of [`SendStream::write_all_chunks`] but with a timeout applied. + let timeout = tokio::time::sleep(timeout); + tokio::pin!(timeout); + let mut bufs = &mut [chunk][..]; + let mut total = 0; + while !bufs.is_empty() { + tokio::select! { + _ = &mut timeout => break, + res = send.write_chunks(bufs) => { + let written = res?; + total += written.bytes; + bufs = &mut bufs[written.chunks..] + } + } + } + Ok(total) +} + fn parse_byte_size(s: &str) -> std::result::Result { let cfg = parse_size::Config::new().with_binary(); cfg.parse_size(s) } fn watch_conn_type( - endpoint_id: EndpointId, paths_watcher: impl Watcher + Send + Unpin + 'static, + remote_id: Option, + output: OutputMode, ) -> AbortOnDropHandle<()> { - let id = endpoint_id.fmt_short(); + let print = move |path: SelectedPath| { + let event = ConnectionTypeChanged { path }; + if let Some(remote_id) = remote_id { + output.emit_with_remote(remote_id, event) + } else { + output.emit(event) + } + }; let task = tokio::task::spawn(async move { let mut stream = paths_watcher.stream(); let mut previous = None; @@ -620,20 +802,16 @@ fn watch_conn_type( if Some(path) == previous.as_ref() { continue; } - println!( - "[{id}] Connection type changed to: {:?} (RTT: {:?})", - path.remote_addr(), - path.rtt() - ); + print(SelectedPath::Selected { + addr: path.remote_addr().clone(), + rtt: path.rtt(), + }); previous = Some(path.clone()); } else if !paths.is_empty() { - println!( - "[{id}] Connection type changed to: mixed ({} paths)", - paths.len() - ); + print(SelectedPath::Mixed { count: paths.len() }); previous = None; } else { - println!("[{id}] Connection type changed to none (no active transmission paths)",); + output.emit(SelectedPath::None); previous = None; } } @@ -641,9 +819,7 @@ fn watch_conn_type( AbortOnDropHandle::new(task) } -fn watch_path_stats( - conn: iroh::endpoint::Connection, -) -> AbortOnDropHandle> { +fn watch_path_stats(conn: iroh::endpoint::Connection) -> AbortOnDropHandle { let task = tokio::spawn(async move { let mut watcher = conn.paths(); let mut latest_stats_by_path = BTreeMap::new(); @@ -667,7 +843,16 @@ fn watch_path_stats( *stats = path.stats(); } } - latest_stats_by_path + let list = latest_stats_by_path + .into_iter() + .map(|(addr, (_info, stats))| PathData { + remote_addr: addr, + rtt: stats.rtt, + bytes_sent: stats.udp_tx.bytes, + bytes_recv: stats.udp_tx.bytes, + }) + .collect(); + PathStats { paths: list } }); AbortOnDropHandle::new(task) } @@ -686,3 +871,301 @@ fn parse_ipv6_net(s: &str) -> Result<(SocketAddrV6, u8)> { let port: u16 = port.parse().std_context("invalid port")?; Ok((SocketAddrV6::new(net.addr(), port, 0, 0), net.prefix_len())) } + +#[derive(ValueEnum, Default, Debug, Clone, Copy)] +enum OutputMode { + /// Print human-readable text. + #[default] + Text, + /// Print newline-delimited JSON. + Json, +} + +impl OutputMode { + fn emit(&self, event: impl Serialize + fmt::Display) { + match self { + OutputMode::Text => println!("{event}"), + OutputMode::Json => println!("{}", serde_json::to_string(&event).unwrap()), + } + } + + fn emit_with_remote(&self, remote: EndpointId, event: impl Serialize + fmt::Display) { + match self { + OutputMode::Text => println!( + "{} {event}", + Style::new() + .dim() + .apply_to(format!("[{}]", remote.fmt_short())) + ), + OutputMode::Json => println!( + "{}", + serde_json::to_string(&RemoteEvent::new(remote, event)).unwrap() + ), + } + } + + fn emit_if_json(&self, event: &impl Serialize) { + if matches!(self, OutputMode::Json) { + println!("{}", serde_json::to_string(&event).unwrap()) + } + } +} + +#[derive(Serialize, Debug, Clone, Display)] +#[display("Generated a new endpoint secret. To reuse, set\n\tIROH_SECRET={secret_key}")] +#[serde(tag = "kind")] +struct SecretGenerated { + secret_key: String, +} + +#[derive(Serialize, Debug, Clone)] +#[serde(tag = "kind")] +struct EndpointBound { + endpoint_id: EndpointId, + direct_addresses: Vec, + relay_url: Option, +} + +impl fmt::Display for EndpointBound { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + writeln!(f, "Our endpoint id:\n\t{}", self.endpoint_id)?; + writeln!(f, "Our direct addresses:")?; + for addr in &self.direct_addresses { + writeln!(f, "\t{addr}")?; + } + match &self.relay_url { + Some(url) => write!(f, "Our home relay server:\t{url}")?, + None => write!(f, "No home relay server found")?, + } + writeln!(f) + } +} + +#[derive(Serialize, Debug, Clone, Display)] +#[serde(tag = "kind")] +#[display("Connection type changed to {path}")] +struct ConnectionTypeChanged { + #[serde(flatten)] + path: SelectedPath, +} + +#[derive(Serialize, Debug, Clone)] +#[serde(tag = "status")] +enum SelectedPath { + Mixed { + count: usize, + }, + Selected { + addr: TransportAddr, + #[serde(with = "duration_micros")] + rtt: Duration, + }, + None, +} + +impl fmt::Display for SelectedPath { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self { + Self::Mixed { count } => { + write!(f, "mixed ({count} paths)") + } + Self::Selected { addr, rtt } => { + write!(f, "{addr:?} (RTT: {}ms)", rtt.as_millis()) + } + Self::None => { + write!(f, "none") + } + } + } +} + +#[derive(Serialize, Debug, Clone, Display)] +#[serde(tag = "kind")] +#[display("Connected to {remote_id} in {}ms", duration.as_millis())] +struct Connected { + remote_id: EndpointId, + #[serde(with = "duration_micros")] + duration: Duration, +} + +#[derive(Serialize, Debug, Clone, Display)] +#[serde(tag = "kind")] +#[display("Starting {mode:?} request with {length:?}")] +struct StartRequest { + mode: Mode, + length: Length, +} + +#[derive(Serialize, Debug, Clone)] +#[serde(tag = "kind")] +struct EndpointClosed { + #[serde(with = "duration_micros")] + duration: Duration, + timed_out: bool, +} + +impl fmt::Display for EndpointClosed { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.timed_out { + false => write!(f, "Shutdown took {:.4}s", self.duration.as_secs_f32()), + true => write!( + f, + "Shutdown timed out after {}s", + self.duration.as_secs_f32() + ), + } + } +} + +#[derive(Serialize, Debug, Clone)] +struct PathData { + remote_addr: TransportAddr, + #[serde(with = "duration_micros")] + rtt: Duration, + bytes_sent: u64, + bytes_recv: u64, +} + +#[derive(Serialize, Debug, Clone)] +#[serde(tag = "kind")] +struct PathStats { + paths: Vec, +} + +impl fmt::Display for PathStats { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + writeln!(f, "Path stats:")?; + for path in &self.paths { + writeln!( + f, + " {:?}: RTT {}ms, tx={}, rx={}", + path.remote_addr, + path.rtt.as_millis(), + path.bytes_sent, + path.bytes_recv, + )?; + } + Ok(()) + } +} + +#[derive(Serialize, Debug, Clone, Display)] +#[serde(tag = "kind")] +#[display("{stats}")] +struct DownloadComplete { + #[serde(flatten)] + stats: DownloadStats, +} + +#[derive(Serialize, Debug, Clone, Display)] +#[serde(tag = "kind")] +#[display("{stats}")] +struct UploadComplete { + #[serde(flatten)] + stats: UploadStats, +} + +#[derive(Serialize, Debug, Clone, Copy, Display)] +#[display("Accepted connection")] +#[serde(tag = "kind")] +struct ConnectionAccepted {} + +#[derive(Serialize, Debug, Clone, Display)] +#[serde(tag = "kind")] +#[display("Handling {request:?} request")] +struct HandleRequest<'a> { + request: &'a Request, +} + +#[derive(Serialize, Debug, Clone)] +#[serde(tag = "kind")] +struct ConnectionClosed { + #[serde(with = "duration_micros")] + duration: Duration, + error: Option, +} + +impl fmt::Display for ConnectionClosed { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let time = format!("(total time: {:.2}s)", self.duration.as_secs_f32()); + match &self.error { + Some(err) => write!(f, "Connection closed with error: {err} {time}"), + None => write!(f, "Connection closed {time}",), + } + } +} + +#[derive(Serialize, Debug, Clone, Display)] +#[display( + "Downloaded: {:>10} in {:.2}s, {:>10}/s ({}{} chunks)", + HumanBytes(self.size).to_string(), + self.duration.as_secs_f64(), + HumanBytes((self.size as f64 / self.duration.as_secs_f64()) as u64), + self.time_to_first_byte + .map(|t| format!("time to first byte {}ms, ", t.as_millis())) + .unwrap_or_default(), + self.num_chunks +)] +struct DownloadStats { + size: u64, + #[serde( + serialize_with = "duration_micros_opt", + skip_serializing_if = "Option::is_none" + )] + time_to_first_byte: Option, + num_chunks: u64, + #[serde(with = "duration_micros")] + duration: Duration, +} + +#[derive(Serialize, Debug, Clone, Display)] +#[display( + "Uploaded: {:>10} in {:.2}s, {:>10}/s", + HumanBytes(self.size).to_string(), + self.duration.as_secs_f64(), + HumanBytes((self.size as f64 / self.duration.as_secs_f64()) as u64) +)] +struct UploadStats { + size: u64, + #[serde(with = "duration_micros")] + duration: Duration, +} + +#[derive(Serialize, Debug, Clone, From, Display)] +#[display("[{}] {inner}", remote_id.fmt_short())] +struct RemoteEvent { + #[serde(flatten)] + inner: T, + remote_id: EndpointId, +} + +impl RemoteEvent { + fn new(remote_id: EndpointId, inner: T) -> Self { + Self { remote_id, inner } + } +} + +fn duration_micros_opt( + value: &Option, + serializer: S, +) -> Result { + match value { + Some(d) => serializer.serialize_u64(d.as_micros() as u64), + None => serializer.serialize_none(), + } +} + +mod duration_micros { + use std::time::Duration; + + use serde::{Deserialize, Deserializer, Serializer}; + + pub fn serialize(duration: &Duration, serializer: S) -> Result { + serializer.serialize_u64(duration.as_micros() as u64) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + let millis = u64::deserialize(deserializer)?; + Ok(Duration::from_micros(millis)) + } +}