-
Notifications
You must be signed in to change notification settings - Fork 14
feat: abstract over stream types on provide and get side #147
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
Open
rklaehn
wants to merge
35
commits into
main
Choose a base branch
from
newtype-it
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
35 commits
Select commit
Hold shift + click to select a range
e5ac6dd
WIP make provider events a proper irpc protocol and allow configuring…
rklaehn d17c6f6
Add transfer_completed and transfer_aborted fn.
rklaehn b23995e
Nicer proto
rklaehn a78c212
Update tests
rklaehn df1e1ef
tests pass
rklaehn a9ac8e5
Everything works
rklaehn 1e4a581
minimize diff and required changes
rklaehn 6449930
clippy
rklaehn b26aefb
Footgun protection
rklaehn 6d86e4f
Add limit example
rklaehn 4b87b6d
Add len to notify_payload_write
rklaehn f992a44
clippy
rklaehn 4bddf77
nicer connection counter
rklaehn 33333a9
Add docs for the limit example.
rklaehn 9a62a58
refactor: make limits example more DRY
Frando 071db5e
Make sure to send a proper reset code when resetting a connection
rklaehn 2d72de0
deny
rklaehn 2dac46c
Use async syntax for implementing ProtocolHandler
rklaehn a67d787
Use irpc::channel::SendError as default sink error.
rklaehn 546f57e
fixup
Frando f399e2b
Remove map_err that isn't needed anymore
rklaehn 3f0a661
Refactor the GetError to be just a list of things that can go wrong.
rklaehn 2f9ebd5
silence some of the tests
rklaehn d764dc0
Genericize provider side a bit
rklaehn 4e8387a
Refactor error and make get and provide side generic
rklaehn 4c4a5e7
Add example how to add compression to the entire blobs protocol.
rklaehn f3d02e7
Working adapters
rklaehn 41284d2
compression example works again
rklaehn 349c36b
Generic receive into store
rklaehn bc159ca
More moving stuff around
rklaehn 1390954
clippy
rklaehn 4ddc137
Merge branch 'main' into newtype-it
rklaehn 3dc6d97
Remove async-compression dep on compile
rklaehn 6ceacfd
PR review: added cancellation safety note and id()
rklaehn 845e01e
PR review: rename the weirdly named ...Specific traits
rklaehn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,229 @@ | ||
/// Example how to use compression with iroh-blobs | ||
/// | ||
/// We create a derived protocol that compresses both requests and responses using lz4 | ||
/// or any other compression algorithm supported by async-compression. | ||
mod common; | ||
use std::{fmt::Debug, path::PathBuf}; | ||
|
||
use anyhow::Result; | ||
use clap::Parser; | ||
use common::setup_logging; | ||
use iroh::protocol::ProtocolHandler; | ||
use iroh_blobs::{ | ||
api::Store, | ||
get::StreamPair, | ||
provider::{ | ||
self, | ||
events::{ClientConnected, EventSender, HasErrorCode}, | ||
handle_stream, | ||
}, | ||
store::mem::MemStore, | ||
ticket::BlobTicket, | ||
}; | ||
use tracing::debug; | ||
|
||
use crate::common::get_or_generate_secret_key; | ||
|
||
#[derive(Debug, Parser)] | ||
#[command(version, about)] | ||
pub enum Args { | ||
/// Limit requests by node id | ||
Provide { | ||
/// Path for files to add. | ||
path: PathBuf, | ||
}, | ||
/// Get a blob. Just for completeness sake. | ||
Get { | ||
/// Ticket for the blob to download | ||
ticket: BlobTicket, | ||
/// Path to save the blob to | ||
#[clap(long)] | ||
target: Option<PathBuf>, | ||
}, | ||
} | ||
|
||
trait Compression: Clone + Send + Sync + Debug + 'static { | ||
const ALPN: &'static [u8]; | ||
fn recv_stream( | ||
&self, | ||
stream: iroh::endpoint::RecvStream, | ||
) -> impl iroh_blobs::util::RecvStream + Sync + 'static; | ||
fn send_stream( | ||
&self, | ||
stream: iroh::endpoint::SendStream, | ||
) -> impl iroh_blobs::util::SendStream + Sync + 'static; | ||
} | ||
|
||
mod lz4 { | ||
use std::io; | ||
|
||
use async_compression::tokio::{bufread::Lz4Decoder, write::Lz4Encoder}; | ||
use iroh::endpoint::VarInt; | ||
use iroh_blobs::util::{ | ||
AsyncReadRecvStream, AsyncReadRecvStreamExtra, AsyncWriteSendStream, | ||
AsyncWriteSendStreamExtra, | ||
}; | ||
use tokio::io::{AsyncRead, AsyncWrite, BufReader}; | ||
|
||
struct SendStream(Lz4Encoder<iroh::endpoint::SendStream>); | ||
|
||
impl SendStream { | ||
pub fn new(inner: iroh::endpoint::SendStream) -> AsyncWriteSendStream<Self> { | ||
AsyncWriteSendStream::new(Self(Lz4Encoder::new(inner))) | ||
} | ||
} | ||
|
||
impl AsyncWriteSendStreamExtra for SendStream { | ||
fn inner(&mut self) -> &mut (impl AsyncWrite + Unpin + Send) { | ||
&mut self.0 | ||
} | ||
|
||
fn reset(&mut self, code: VarInt) -> io::Result<()> { | ||
Ok(self.0.get_mut().reset(code)?) | ||
} | ||
|
||
async fn stopped(&mut self) -> io::Result<Option<VarInt>> { | ||
Ok(self.0.get_mut().stopped().await?) | ||
} | ||
|
||
fn id(&self) -> u64 { | ||
self.0.get_ref().id().index() | ||
} | ||
} | ||
|
||
struct RecvStream(Lz4Decoder<BufReader<iroh::endpoint::RecvStream>>); | ||
|
||
impl RecvStream { | ||
pub fn new(inner: iroh::endpoint::RecvStream) -> AsyncReadRecvStream<Self> { | ||
AsyncReadRecvStream::new(Self(Lz4Decoder::new(BufReader::new(inner)))) | ||
} | ||
} | ||
|
||
impl AsyncReadRecvStreamExtra for RecvStream { | ||
fn inner(&mut self) -> &mut (impl AsyncRead + Unpin + Send) { | ||
&mut self.0 | ||
} | ||
|
||
fn stop(&mut self, code: VarInt) -> io::Result<()> { | ||
Ok(self.0.get_mut().get_mut().stop(code)?) | ||
} | ||
|
||
fn id(&self) -> u64 { | ||
self.0.get_ref().get_ref().id().index() | ||
} | ||
} | ||
|
||
#[derive(Debug, Clone)] | ||
pub struct Compression; | ||
|
||
impl super::Compression for Compression { | ||
const ALPN: &[u8] = concat_const::concat_bytes!(b"lz4/", iroh_blobs::ALPN); | ||
fn recv_stream( | ||
&self, | ||
stream: iroh::endpoint::RecvStream, | ||
) -> impl iroh_blobs::util::RecvStream + Sync + 'static { | ||
RecvStream::new(stream) | ||
} | ||
fn send_stream( | ||
&self, | ||
stream: iroh::endpoint::SendStream, | ||
) -> impl iroh_blobs::util::SendStream + Sync + 'static { | ||
SendStream::new(stream) | ||
} | ||
} | ||
} | ||
|
||
#[derive(Debug, Clone)] | ||
struct CompressedBlobsProtocol<C: Compression> { | ||
store: Store, | ||
events: EventSender, | ||
compression: C, | ||
} | ||
|
||
impl<C: Compression> CompressedBlobsProtocol<C> { | ||
fn new(store: &Store, events: EventSender, compression: C) -> Self { | ||
Self { | ||
store: store.clone(), | ||
events, | ||
compression, | ||
} | ||
} | ||
} | ||
|
||
impl<C: Compression> ProtocolHandler for CompressedBlobsProtocol<C> { | ||
async fn accept( | ||
&self, | ||
connection: iroh::endpoint::Connection, | ||
) -> std::result::Result<(), iroh::protocol::AcceptError> { | ||
let connection_id = connection.stable_id() as u64; | ||
if let Err(cause) = self | ||
.events | ||
.client_connected(|| ClientConnected { | ||
connection_id, | ||
node_id: connection.remote_node_id().ok(), | ||
}) | ||
.await | ||
{ | ||
connection.close(cause.code(), cause.reason()); | ||
debug!("closing connection: {cause}"); | ||
return Ok(()); | ||
} | ||
while let Ok((send, recv)) = connection.accept_bi().await { | ||
let send = self.compression.send_stream(send); | ||
let recv = self.compression.recv_stream(recv); | ||
let store = self.store.clone(); | ||
let pair = provider::StreamPair::new(connection_id, recv, send, self.events.clone()); | ||
tokio::spawn(handle_stream(pair, store)); | ||
} | ||
Ok(()) | ||
} | ||
} | ||
|
||
#[tokio::main] | ||
async fn main() -> Result<()> { | ||
setup_logging(); | ||
let args = Args::parse(); | ||
let secret = get_or_generate_secret_key()?; | ||
let endpoint = iroh::Endpoint::builder() | ||
.secret_key(secret) | ||
.discovery_n0() | ||
.bind() | ||
.await?; | ||
let compression = lz4::Compression; | ||
match args { | ||
Args::Provide { path } => { | ||
let store = MemStore::new(); | ||
let tag = store.add_path(path).await?; | ||
let blobs = CompressedBlobsProtocol::new(&store, EventSender::DEFAULT, compression); | ||
let router = iroh::protocol::Router::builder(endpoint.clone()) | ||
.accept(lz4::Compression::ALPN, blobs) | ||
.spawn(); | ||
let ticket = BlobTicket::new(endpoint.node_id().into(), tag.hash, tag.format); | ||
println!("Serving blob with hash {}", tag.hash); | ||
println!("Ticket: {ticket}"); | ||
println!("Node is running. Press Ctrl-C to exit."); | ||
tokio::signal::ctrl_c().await?; | ||
println!("Shutting down."); | ||
router.shutdown().await?; | ||
} | ||
Args::Get { ticket, target } => { | ||
let store = MemStore::new(); | ||
let conn = endpoint | ||
.connect(ticket.node_addr().clone(), lz4::Compression::ALPN) | ||
.await?; | ||
let connection_id = conn.stable_id() as u64; | ||
let (send, recv) = conn.open_bi().await?; | ||
let send = compression.send_stream(send); | ||
let recv = compression.recv_stream(recv); | ||
let sp = StreamPair::new(connection_id, recv, send); | ||
let _stats = store.remote().fetch(sp, ticket.hash_and_format()).await?; | ||
if let Some(target) = target { | ||
let size = store.export(ticket.hash(), &target).await?; | ||
println!("Wrote {} bytes to {}", size, target.display()); | ||
} else { | ||
println!("Hash: {}", ticket.hash()); | ||
} | ||
} | ||
} | ||
Ok(()) | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
maybe
AsyncWriteSendStreamExt
? forExtension
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hm, ...Ext traits for me are specifically for the "extension method" hack.
trait FooExt { ... }
impl<T: Foo> FooExt for T {}