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 5 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
58 changes: 39 additions & 19 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 iroh::{protocol::Router, Endpoint};
use iroh_blobs::{
net_protocol::Blobs,
rpc::client::blobs::{ReadAtLen, WrapOption},
rpc::client::blobs::WrapOption,
store::{ExportFormat, ExportMode},
ticket::BlobTicket,
util::SetTagOption,
};
Expand All @@ -19,41 +20,52 @@ 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();
// Grab all passed in arguments, the first one is the binary itself, so we skip it.
let args: Vec<String> = std::env::args().skip(1).collect();
// Convert to &str, so we can pattern-match easily:
let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();

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()?;
match arg_refs.as_slice() {
["send", filename] => {
let filename: PathBuf = filename.parse()?;
let abs_path = std::path::absolute(&filename)?;

println!("Analyzing file.");

// keep the file in place and link it, instead of copying it into the in-memory blobs database
let in_place = true;
let blob = blobs
.add_from_path(abs_path, true, SetTagOption::Auto, WrapOption::NoWrap)
.client()
.add_from_path(abs_path, in_place, SetTagOption::Auto, WrapOption::NoWrap)
.await?
.finish()
.await?;

let node_id = node.endpoint().node_id();
let node_id = router.endpoint().node_id();
let ticket = BlobTicket::new(node_id.into(), blob.hash, blob.format)?;

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

tokio::signal::ctrl_c().await?;
}
[_cmd, "receive", ticket, path] => {
let path_buf = PathBuf::from_str(path)?;
let ticket = BlobTicket::from_str(ticket)?;
["receive", ticket, filename] => {
let filename: PathBuf = filename.parse()?;
let abs_path = std::path::absolute(filename)?;
let ticket: BlobTicket = ticket.parse()?;

println!("Starting download.");

blobs
.client()
.download(ticket.hash(), ticket.node_addr().clone())
.await?
.finish()
Expand All @@ -62,14 +74,22 @@ async fn main() -> Result<()> {
println!("Finished download.");
println!("Copying to destination.");

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?;
blobs
.client()
.export(
ticket.hash(),
abs_path,
ExportFormat::Blob,
ExportMode::Copy,
)
.await?
.finish()
.await?;

println!("Finished copying.");
}
_ => {
println!("Couldn't parse command line arguments.");
println!("Couldn't parse command line arguments: {args:?}");
println!("Usage:");
println!(" # to send:");
println!(" cargo run --example transfer -- send [FILE]");
Expand All @@ -82,7 +102,7 @@ async fn main() -> Result<()> {

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

Ok(())
}
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