mirror of
https://github.com/n0-computer/iroh.git
synced 2026-12-04 16:02:04 +00:00
feat: add STDIN and STDOUT support (#39)
* feat: add STDIN and STDOUT support also avoid keeping files data in memory, after calculating the outboard data * Update src/server.rs Co-authored-by: Floris Bruynooghe <flub@devork.be> * Update src/server.rs Co-authored-by: Floris Bruynooghe <flub@devork.be> Co-authored-by: Floris Bruynooghe <flub@devork.be>
This commit is contained in:
1 parent
03e1f9377d
commit
c121094de2
6 files changed
+168
-72
No files matched your search
Generated
+42
@@ -496,6 +496,15 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "1.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7a407cfaa3385c4ae6b23e84623d48c2798d06e3e6a1878f7f59f17b3f86499"
|
||||
dependencies = [
|
||||
"instant",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
@@ -684,6 +693,15 @@ dependencies = [
|
||||
"unicode-width",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "instant"
|
||||
version = "0.1.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "intrusive-collections"
|
||||
version = "0.9.4"
|
||||
@@ -1210,6 +1228,15 @@ version = "0.6.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "456c603be3e8d448b072f410900c09faf164fbce2d480456f50eea6e25f9c848"
|
||||
|
||||
[[package]]
|
||||
name = "remove_dir_all"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7"
|
||||
dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.16.20"
|
||||
@@ -1448,6 +1475,7 @@ dependencies = [
|
||||
"rustls",
|
||||
"s2n-quic",
|
||||
"serde",
|
||||
"tempfile",
|
||||
"testdir",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
@@ -1613,6 +1641,20 @@ dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"fastrand",
|
||||
"libc",
|
||||
"redox_syscall",
|
||||
"remove_dir_all",
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "termcolor"
|
||||
version = "1.1.3"
|
||||
|
||||
@@ -27,6 +27,7 @@ ring = "0.16.20"
|
||||
rustls = { version = "0.20.8", default-features = false, features = ["dangerous_configuration"] }
|
||||
s2n-quic = { version = "1.14.0", default-features = false, features = [ "provider-tls-rustls", "provider-address-token-default" ] }
|
||||
serde = { version = "1.0.152", features = ["derive"] }
|
||||
tempfile = "3.3.0"
|
||||
thiserror = "1.0.38"
|
||||
tokio = { version = "1.24.1", features = ["full"] }
|
||||
tokio-util = { version = "0.7", features = ["io-util", "io"] }
|
||||
|
||||
@@ -145,6 +145,7 @@ pub fn run(hash: bao::Hash, opts: Options) -> impl Stream<Item = Result<Event>>
|
||||
}
|
||||
let (a, mut b) = tokio::io::duplex(1024);
|
||||
|
||||
// TODO: avoid copy
|
||||
let outboard = outboard.to_vec();
|
||||
let t = tokio::task::spawn(async move {
|
||||
let mut decoder = bao::decode::Decoder::new_outboard(
|
||||
@@ -164,6 +165,7 @@ pub fn run(hash: bao::Hash, opts: Options) -> impl Stream<Item = Result<Event>>
|
||||
b.write_all(&buf[..read]).await?;
|
||||
}
|
||||
b.flush().await?;
|
||||
debug!("finished writing");
|
||||
Ok::<(), anyhow::Error>(())
|
||||
});
|
||||
|
||||
|
||||
+3
-3
@@ -25,7 +25,7 @@ mod tests {
|
||||
let dir: PathBuf = testdir!();
|
||||
let path = dir.join("hello_world");
|
||||
tokio::fs::write(&path, "hello world!").await?;
|
||||
let db = server::create_db(vec![&path]).await?;
|
||||
let db = server::create_db(vec![server::DataSource::File(path.clone())]).await?;
|
||||
let hash = *db.iter().next().unwrap().0;
|
||||
let addr = "127.0.0.1:4443".parse().unwrap();
|
||||
let mut server = server::Server::new(db);
|
||||
@@ -84,7 +84,7 @@ mod tests {
|
||||
|
||||
tokio::fs::write(&path, &content).await?;
|
||||
|
||||
let db = server::create_db(vec![&path]).await?;
|
||||
let db = server::create_db(vec![server::DataSource::File(path)]).await?;
|
||||
let hash = *db.iter().next().unwrap().0;
|
||||
let mut server = server::Server::new(db);
|
||||
let peer_id = server.peer_id();
|
||||
@@ -128,7 +128,7 @@ mod tests {
|
||||
let addr = "127.0.0.1:4444".parse().unwrap();
|
||||
|
||||
tokio::fs::write(&path, content).await?;
|
||||
let db = server::create_db(vec![&path]).await?;
|
||||
let db = server::create_db(vec![server::DataSource::File(path)]).await?;
|
||||
let hash = *db.iter().next().unwrap().0;
|
||||
let mut server = server::Server::new(db);
|
||||
let peer_id = server.peer_id();
|
||||
|
||||
+35
-16
@@ -20,10 +20,10 @@ struct Cli {
|
||||
#[derive(Subcommand, Debug, Clone)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
enum Commands {
|
||||
/// Serve the data from the given path
|
||||
/// Serve the data from the given path. If none is specified reads from STDIN.
|
||||
#[clap(about = "Serve the data from the given path")]
|
||||
Server {
|
||||
paths: Vec<PathBuf>,
|
||||
path: Option<PathBuf>,
|
||||
#[clap(long, short)]
|
||||
/// Optional port, defaults to 127.0.01:4433.
|
||||
addr: Option<SocketAddr>,
|
||||
@@ -36,10 +36,9 @@ enum Commands {
|
||||
/// PeerId of the server.
|
||||
peer_id: PeerId,
|
||||
#[clap(long, short)]
|
||||
/// Option address of the server, defaults to 127.0.0.1:4433.
|
||||
/// Optional address of the server, defaults to 127.0.0.1:4433.
|
||||
addr: Option<SocketAddr>,
|
||||
#[clap(long, short)]
|
||||
/// Option path to save the file, defaults to using the hash as the name.
|
||||
/// Optional path to save the file. If none is specified writes the data to STDOUT.
|
||||
out: Option<PathBuf>,
|
||||
},
|
||||
}
|
||||
@@ -69,9 +68,6 @@ async fn main() -> Result<()> {
|
||||
opts.addr = addr;
|
||||
}
|
||||
|
||||
// Write file out
|
||||
let outpath = out.unwrap_or_else(|| hash.to_string().into());
|
||||
|
||||
println!("{} Connecting ...", style("[1/3]").bold().dim());
|
||||
let pb = ProgressBar::hidden();
|
||||
let stream = client::run(hash, opts);
|
||||
@@ -97,11 +93,17 @@ async fn main() -> Result<()> {
|
||||
mut reader,
|
||||
} => {
|
||||
ensure!(hash == new_hash, "invalid hash received");
|
||||
let file = tokio::fs::File::create(&outpath).await?;
|
||||
let out = tokio::io::BufWriter::new(file);
|
||||
// wrap for progress bar
|
||||
let mut wrapped_out = pb.wrap_async_write(out);
|
||||
tokio::io::copy(&mut reader, &mut wrapped_out).await?;
|
||||
if let Some(ref out) = out {
|
||||
let file = tokio::fs::File::create(out).await?;
|
||||
let file = tokio::io::BufWriter::new(file);
|
||||
// wrap for progress bar
|
||||
let mut file = pb.wrap_async_write(file);
|
||||
tokio::io::copy(&mut reader, &mut file).await?;
|
||||
} else {
|
||||
// Write to STDOUT
|
||||
let mut stdout = tokio::io::stdout();
|
||||
tokio::io::copy(&mut reader, &mut stdout).await?;
|
||||
}
|
||||
}
|
||||
client::Event::Done(stats) => {
|
||||
pb.finish_and_clear();
|
||||
@@ -111,8 +113,22 @@ async fn main() -> Result<()> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Commands::Server { paths, addr } => {
|
||||
let db = server::create_db(paths.iter().map(|p| p.as_path()).collect()).await?;
|
||||
Commands::Server { path, addr } => {
|
||||
let mut tmp_path = None;
|
||||
|
||||
let sources = if let Some(path) = path {
|
||||
vec![server::DataSource::File(path)]
|
||||
} else {
|
||||
// Store STDIN content into a temporary file
|
||||
let (file, path) = tempfile::NamedTempFile::new()?.into_parts();
|
||||
let mut file = tokio::fs::File::from_std(file);
|
||||
let path_buf = path.to_path_buf();
|
||||
tmp_path = Some(path);
|
||||
tokio::io::copy(&mut tokio::io::stdin(), &mut file).await?;
|
||||
vec![server::DataSource::File(path_buf)]
|
||||
};
|
||||
|
||||
let db = server::create_db(sources).await?;
|
||||
let mut opts = server::Options::default();
|
||||
if let Some(addr) = addr {
|
||||
opts.addr = addr;
|
||||
@@ -120,7 +136,10 @@ async fn main() -> Result<()> {
|
||||
let mut server = server::Server::new(db);
|
||||
|
||||
println!("Serving from {}", server.peer_id());
|
||||
server.run(opts).await?
|
||||
server.run(opts).await?;
|
||||
|
||||
// Drop tempath to signal it can be destroyed
|
||||
drop(tmp_path);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+85
-53
@@ -1,12 +1,13 @@
|
||||
use std::net::SocketAddr;
|
||||
use std::{collections::HashMap, path::Path, sync::Arc};
|
||||
use std::path::PathBuf;
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use anyhow::{anyhow, bail, ensure, Result};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use s2n_quic::stream::BidirectionalStream;
|
||||
use s2n_quic::Server as QuicServer;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tracing::{debug, error};
|
||||
use tokio::io::AsyncWrite;
|
||||
use tracing::{debug, warn};
|
||||
|
||||
use crate::protocol::{read_lp, write_lp, Handshake, Request, Res, Response, VERSION};
|
||||
use crate::tls::{self, Keypair, PeerId};
|
||||
@@ -71,7 +72,7 @@ impl Server {
|
||||
let db = db.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = handle_stream(db, stream).await {
|
||||
error!("error: {:#?}", err);
|
||||
warn!("error: {:#?}", err);
|
||||
}
|
||||
debug!("disconnected");
|
||||
});
|
||||
@@ -114,40 +115,37 @@ async fn handle_stream(
|
||||
let name = bao::Hash::from(request.name);
|
||||
debug!("got request({}): {}", request.id, name.to_hex());
|
||||
|
||||
let (data, piece) = if let Some(data) = db.get(&name) {
|
||||
debug!("found {}", name.to_hex());
|
||||
(
|
||||
Res::Found {
|
||||
size: data.data.len(),
|
||||
outboard: &data.outboard,
|
||||
},
|
||||
Some(data.clone()),
|
||||
)
|
||||
} else {
|
||||
debug!("not found {}", name.to_hex());
|
||||
(Res::NotFound, None)
|
||||
};
|
||||
match db.get(&name) {
|
||||
Some(Data {
|
||||
outboard,
|
||||
path,
|
||||
size,
|
||||
}) => {
|
||||
debug!("found {}", name.to_hex());
|
||||
write_response(
|
||||
&mut writer,
|
||||
&mut out_buffer,
|
||||
request.id,
|
||||
Res::Found {
|
||||
size: *size,
|
||||
outboard,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
let response = Response {
|
||||
id: request.id,
|
||||
data,
|
||||
};
|
||||
|
||||
if out_buffer.len() < 20 + response.data.len() {
|
||||
out_buffer.resize(20 + response.data.len(), 0u8);
|
||||
debug!("writing data");
|
||||
let file = tokio::fs::File::open(&path).await?;
|
||||
let mut reader = tokio::io::BufReader::new(file);
|
||||
tokio::io::copy(&mut reader, &mut writer).await?;
|
||||
}
|
||||
None => {
|
||||
debug!("not found {}", name.to_hex());
|
||||
write_response(&mut writer, &mut out_buffer, request.id, Res::NotFound)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
let used = postcard::to_slice(&response, &mut out_buffer)?;
|
||||
|
||||
write_lp(&mut writer, used).await?;
|
||||
|
||||
debug!("written response of length {}", used.len());
|
||||
|
||||
if let Some(piece) = piece {
|
||||
debug!("writing data {}", piece.data.len());
|
||||
// if we found the data, write it out now
|
||||
writer.write_all(&piece.data).await?;
|
||||
debug!("done writing data");
|
||||
}
|
||||
debug!("finished response");
|
||||
}
|
||||
None => {
|
||||
break;
|
||||
@@ -159,33 +157,67 @@ async fn handle_stream(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Data {
|
||||
/// outboard data from bo
|
||||
/// Outboard data from bao.
|
||||
outboard: Bytes,
|
||||
/// actual data
|
||||
data: Bytes,
|
||||
/// Path to the original data, which must not change while in use.
|
||||
path: PathBuf,
|
||||
/// Size of the original data.
|
||||
size: usize,
|
||||
}
|
||||
|
||||
pub async fn create_db(paths: Vec<&Path>) -> Result<Arc<HashMap<bao::Hash, Data>>> {
|
||||
#[derive(Debug)]
|
||||
pub enum DataSource {
|
||||
File(PathBuf),
|
||||
}
|
||||
|
||||
pub async fn create_db(data_sources: Vec<DataSource>) -> Result<Arc<HashMap<bao::Hash, Data>>> {
|
||||
println!("Available Data:");
|
||||
|
||||
let mut db = HashMap::new();
|
||||
for path in paths {
|
||||
ensure!(path.is_file(), "can only transfer blob data");
|
||||
let data = tokio::fs::read(path).await?;
|
||||
let num = data.len();
|
||||
let (outboard, hash) = bao::encode::outboard(&data);
|
||||
for data in data_sources {
|
||||
match data {
|
||||
DataSource::File(path) => {
|
||||
ensure!(
|
||||
path.is_file(),
|
||||
"can only transfer blob data: {}",
|
||||
path.display()
|
||||
);
|
||||
let data = tokio::fs::read(&path).await?;
|
||||
let (outboard, hash) = bao::encode::outboard(&data);
|
||||
|
||||
println!("- {}: {}bytes", hash.to_hex(), num);
|
||||
db.insert(
|
||||
hash,
|
||||
Data {
|
||||
outboard: Bytes::from(outboard),
|
||||
data: Bytes::from(data),
|
||||
},
|
||||
);
|
||||
println!("- {}: {}bytes", hash.to_hex(), data.len());
|
||||
db.insert(
|
||||
hash,
|
||||
Data {
|
||||
outboard: Bytes::from(outboard),
|
||||
path,
|
||||
size: data.len(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Arc::new(db))
|
||||
}
|
||||
|
||||
async fn write_response<W: AsyncWrite + Unpin>(
|
||||
mut writer: W,
|
||||
buffer: &mut BytesMut,
|
||||
id: u64,
|
||||
res: Res<'_>,
|
||||
) -> Result<()> {
|
||||
let response = Response { id, data: res };
|
||||
|
||||
if buffer.len() < 20 + response.data.len() {
|
||||
buffer.resize(20 + response.data.len(), 0u8);
|
||||
}
|
||||
let used = postcard::to_slice(&response, buffer)?;
|
||||
|
||||
write_lp(&mut writer, used).await?;
|
||||
|
||||
debug!("written response of length {}", used.len());
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user