Skip to content

example: simplify transfer example #53

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Feb 24, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 85 additions & 51 deletions examples/transfer.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use std::{path::PathBuf, str::FromStr};
use std::path::PathBuf;

use anyhow::Result;
use anyhow::{bail, Result};
use iroh::{protocol::Router, Endpoint};
use iroh_blobs::{
net_protocol::Blobs,
rpc::client::blobs::{ReadAtLen, WrapOption},
rpc::client::blobs::{self, WrapOption},
store::ExportMode,
ticket::BlobTicket,
util::SetTagOption,
};
Expand All @@ -19,70 +20,103 @@ async fn main() -> Result<()> {

// Now we build a router that accepts blobs connections & routes them
// to the blobs protocol.
let node = Router::builder(endpoint)
let router = Router::builder(endpoint)
.accept(iroh_blobs::ALPN, blobs.clone())
.spawn()
.await?;

let blobs = blobs.client();

let args = std::env::args().collect::<Vec<_>>();
match &args.iter().map(String::as_str).collect::<Vec<_>>()[..] {
[_cmd, "send", path] => {
let abs_path = PathBuf::from_str(path)?.canonicalize()?;
// Grab all passed in arguments, the first one is the binary itself, so we skip it.
let args: Vec<_> = std::env::args().skip(1).collect();
if args.len() < 2 {
print_usage();
bail!("too few arguments");
}

println!("Analyzing file.");
match &*args[0] {
"send" => {
send(&router, blobs.client(), &args).await?;

let blob = blobs
.add_from_path(abs_path, true, SetTagOption::Auto, WrapOption::NoWrap)
.await?
.finish()
.await?;
tokio::signal::ctrl_c().await?;
}
"receive" => {
receive(blobs.client(), &args).await?;
}
cmd => {
print_usage();
bail!("unknown command {}", cmd);
}
}

let node_id = node.endpoint().node_id();
let ticket = BlobTicket::new(node_id.into(), blob.hash, blob.format)?;
// Gracefully shut down the node
println!("Shutting down.");
router.shutdown().await?;

println!("File analyzed. Fetch this file by running:");
println!("cargo run --example transfer -- receive {ticket} {path}");
Ok(())
}

tokio::signal::ctrl_c().await?;
}
[_cmd, "receive", ticket, path] => {
let path_buf = PathBuf::from_str(path)?;
let ticket = BlobTicket::from_str(ticket)?;
async fn send(router: &Router, blobs: &blobs::MemClient, args: &[String]) -> Result<()> {
let path: PathBuf = args[1].parse()?;
let abs_path = path.canonicalize()?;

println!("Starting download.");
println!("Analyzing file.");

blobs
.download(ticket.hash(), ticket.node_addr().clone())
.await?
.finish()
.await?;
// keep the file in place, and link it
let in_place = true;
let blob = blobs
.add_from_path(abs_path, in_place, SetTagOption::Auto, WrapOption::NoWrap)
.await?
.await?;

println!("Finished download.");
println!("Copying to destination.");
let node_id = router.endpoint().node_id();
let ticket = BlobTicket::new(node_id.into(), blob.hash, blob.format)?;

let mut file = tokio::fs::File::create(path_buf).await?;
let mut reader = blobs.read_at(ticket.hash(), 0, ReadAtLen::All).await?;
tokio::io::copy(&mut reader, &mut file).await?;
println!("File analyzed. Fetch this file by running:");
println!(
"cargo run --example transfer -- receive {ticket} {}",
path.display()
);
Ok(())
}

println!("Finished copying.");
}
_ => {
println!("Couldn't parse command line arguments.");
println!("Usage:");
println!(" # to send:");
println!(" cargo run --example transfer -- send [FILE]");
println!(" # this will print a ticket.");
println!();
println!(" # to receive:");
println!(" cargo run --example transfer -- receive [TICKET] [FILE]");
}
async fn receive(blobs: &blobs::MemClient, args: &[String]) -> Result<()> {
if args.len() < 3 {
print_usage();
bail!("too few arguments");
}
let path_buf: PathBuf = args[1].parse()?;
let ticket: BlobTicket = args[2].parse()?;

// Gracefully shut down the node
println!("Shutting down.");
node.shutdown().await?;
println!("Starting download.");

blobs
.download(ticket.hash(), ticket.node_addr().clone())
.await?
.await?;

println!("Finished download.");
println!("Copying to destination.");

blobs
.export(
ticket.hash(),
path_buf,
ticket.format().into(),
ExportMode::Copy,
)
.await?;

println!("Finished copying.");

Ok(())
}

fn print_usage() {
println!("Couldn't parse command line arguments.");
println!("Usage:");
println!(" # to send:");
println!(" cargo run --example transfer -- send [FILE]");
println!(" # this will print a ticket.");
println!();
println!(" # to receive:");
println!(" cargo run --example transfer -- receive [TICKET] [FILE]");
}
11 changes: 11 additions & 0 deletions src/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ use std::{borrow::Borrow, fmt, str::FromStr};
use postcard::experimental::max_size::MaxSize;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};

use crate::store::ExportFormat;

/// Hash type used throughout.
#[derive(PartialEq, Eq, Copy, Clone, Hash)]
pub struct Hash(blake3::Hash);
Expand Down Expand Up @@ -242,6 +244,15 @@ impl BlobFormat {
}
}

impl From<BlobFormat> for ExportFormat {
fn from(value: BlobFormat) -> Self {
match value {
BlobFormat::Raw => ExportFormat::Blob,
BlobFormat::HashSeq => ExportFormat::Collection,
}
}
}

/// A hash and format pair
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, MaxSize, Hash)]
pub struct HashAndFormat {
Expand Down
Loading