Skip to content

Instantly share code, notes, and snippets.

@Frando
Forked from dignifiedquire/main-sync.rs
Last active May 16, 2024 15:06
Show Gist options
  • Save Frando/f66909e632be5a4e3443ec6072c8ec98 to your computer and use it in GitHub Desktop.
Save Frando/f66909e632be5a4e3443ec6072c8ec98 to your computer and use it in GitHub Desktop.
quick-start-rust-iroh
use anyhow::Result;
use futures_lite::stream::StreamExt;
use iroh::{
base::node_addr::AddrInfoOptions,
client::docs::{LiveEvent, ShareMode},
docs::{store::Query, DocTicket},
node::MemNode,
};
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let node = iroh::node::Node::memory().spawn().await?;
let node_id = node.node_id();
println!("Started iroh node with id:\n{}", node_id);
let maybe_ticket = std::env::args().nth(1);
if let Some(ticket) = maybe_ticket {
join_document(node, ticket).await?;
} else {
create_document(node).await?;
tokio::signal::ctrl_c().await?;
}
Ok(())
}
async fn create_document(node: MemNode) -> Result<()> {
let doc = node.docs.create().await?;
println!("Created doc {}", doc.id());
let author = node.authors.create().await?;
println!("Created author: {}", author);
doc.set_bytes(author, "hello", "world").await?;
let maybe_entry = doc.get_one(Query::key_exact("hello")).await?;
// unwrap, because we know we have this entry
let entry = maybe_entry.unwrap();
let key = std::str::from_utf8(&entry.key()).unwrap();
let value_bytes = entry.content_bytes(&*node).await?;
let value = std::str::from_utf8(&value_bytes).unwrap();
println!("Stored and retrieved entry: {} => {}", key, value);
let ticket = doc.share(ShareMode::Write, AddrInfoOptions::Id).await?;
println!("Doc ticket:\n{}", ticket);
Ok(())
}
async fn join_document(node: MemNode, ticket: String) -> Result<()> {
let ticket: DocTicket = ticket.parse()?;
let (doc, mut events) = node.docs.import_and_subscribe(ticket).await?;
// Wait until we synced and downloaded all content.
// `PendingContentReady` will only be emitted after `SyncFinished`.
while let Some(event) = events.try_next().await? {
match event {
LiveEvent::SyncFinished(_) => println!("sync finished"),
LiveEvent::PendingContentReady => {
println!("all content downloaded");
break;
}
_ => {}
}
}
let mut entries = doc.get_many(Query::all()).await?;
while let Some(entry) = entries.next().await {
let entry = entry?;
let key = std::str::from_utf8(&entry.key()).unwrap();
let value_bytes = entry.content_bytes(&*node).await?;
let value = std::str::from_utf8(&value_bytes).unwrap();
println!("{} => {}", key, value);
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment