diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eb4c3e8155..eb5a9ff801 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -245,6 +245,9 @@ jobs: run: cross check --all --target ${{ matrix.target }} - name: test + # cross tests are currently broken vor armv7 and aarch64 + # see https://github.com/cross-rs/cross/issues/1311 + if: matrix.target == 'i686-unknown-linux-gnu' run: cross test --all --target ${{ matrix.target }} -- --test-threads=12 check_fmt_and_docs: diff --git a/Cargo.lock b/Cargo.lock index 2c485a3acf..76e01e052c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -48,6 +48,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "aliasable" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "250f629c0161ad8107cf89319e990051fae62832fd343083bea452d93e2205fd" + [[package]] name = "android-tzdata" version = "0.1.1" @@ -189,15 +195,6 @@ dependencies = [ "syn 2.0.29", ] -[[package]] -name = "atomic-polyfill" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3ff7eb3f316534d83a8a2c3d1674ace8a5a71198eba31e2e2b597833f699b28" -dependencies = [ - "critical-section", -] - [[package]] name = "atomic-waker" version = "1.1.1" @@ -337,20 +334,6 @@ version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635" -[[package]] -name = "blake3" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "199c42ab6972d92c9f8995f086273d25c42fc0f7b2a1fcefba465c1352d25ba5" -dependencies = [ - "arrayref", - "arrayvec", - "cc", - "cfg-if", - "constant_time_eq", - "digest", -] - [[package]] name = "block-buffer" version = "0.10.4" @@ -542,6 +525,17 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2da6da31387c7e4ef160ffab6d5e7f00c42626fe39aea70a7b0f1773f7dd6c1b" +[[package]] +name = "clipboard-win" +version = "4.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7191c27c2357d9b7ef96baac1773290d4ca63b24205b82a3fd8a0637afcf0362" +dependencies = [ + "error-code", + "str-buf", + "winapi", +] + [[package]] name = "cobs" version = "0.2.3" @@ -668,7 +662,7 @@ dependencies = [ "clap", "criterion-plot", "is-terminal", - "itertools", + "itertools 0.10.5", "num-traits", "once_cell", "oorandom", @@ -689,14 +683,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1" dependencies = [ "cast", - "itertools", + "itertools 0.10.5", ] [[package]] -name = "critical-section" -version = "1.1.2" +name = "crossbeam" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7059fff8937831a9ae6f0fe4d658ffabf58f2ca96aa9dec1c889f936f705f216" +checksum = "2801af0d36612ae591caa9568261fddce32ce6e08a7275ea334a06a4ad021a2c" +dependencies = [ + "cfg-if", + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-epoch", + "crossbeam-queue", + "crossbeam-utils", +] [[package]] name = "crossbeam-channel" @@ -732,6 +734,16 @@ dependencies = [ "scopeguard", ] +[[package]] +name = "crossbeam-queue" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1cfb3ea8a53f37c40dea2c7bedcbd88bdfae54f5e2175d6ecaff1c988353add" +dependencies = [ + "cfg-if", + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.16" @@ -999,6 +1011,15 @@ dependencies = [ "subtle", ] +[[package]] +name = "dirs" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" +dependencies = [ + "dirs-sys", +] + [[package]] name = "dirs-next" version = "2.0.0" @@ -1009,6 +1030,18 @@ dependencies = [ "dirs-sys-next", ] +[[package]] +name = "dirs-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.48.0", +] + [[package]] name = "dirs-sys-next" version = "0.1.2" @@ -1151,6 +1184,12 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "endian-type" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34f04666d835ff5d62e058c3995147c06f42fe86ff053337632bca83e42702d" + [[package]] name = "enum-as-inner" version = "0.5.1" @@ -1218,6 +1257,16 @@ dependencies = [ "libc", ] +[[package]] +name = "error-code" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64f18991e7bf11e7ffee451b5318b5c1a73c52d0d0ada6e5a3017c8c1ced6a21" +dependencies = [ + "libc", + "str-buf", +] + [[package]] name = "fallible-iterator" version = "0.2.0" @@ -1230,6 +1279,17 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6999dc1837253364c2ebb0704ba97994bd874e8f195d665c50b7548f6ea92764" +[[package]] +name = "fd-lock" +version = "3.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef033ed5e9bad94e55838ca0ca906db0e043f517adda0c8b79c7a8c66c93c1b5" +dependencies = [ + "cfg-if", + "rustix", + "windows-sys 0.48.0", +] + [[package]] name = "ff" version = "0.13.0" @@ -1393,7 +1453,7 @@ version = "0.99.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "784f84eebc366e15251c4a8c3acee82a6a6f427949776ecb88377362a9621738" dependencies = [ - "proc-macro-error", + "proc-macro-error 0.4.12", "proc-macro-hack", "proc-macro2", "quote", @@ -1490,15 +1550,6 @@ version = "1.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" -[[package]] -name = "hash32" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67" -dependencies = [ - "byteorder", -] - [[package]] name = "hashbrown" version = "0.12.3" @@ -1514,20 +1565,6 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a" -[[package]] -name = "heapless" -version = "0.7.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db04bc24a18b9ea980628ecf00e6c0264f3c1426dac36c00cb49b6fbad8b0743" -dependencies = [ - "atomic-polyfill", - "hash32", - "rustc_version", - "serde", - "spin 0.9.8", - "stable_deref_trait", -] - [[package]] name = "heck" version = "0.4.1" @@ -1570,6 +1607,15 @@ version = "1.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3688e69b38018fec1557254f64c8dc2cc8ec502890182f395dbb0aa997aa5735" +[[package]] +name = "home" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5444c27eef6923071f7ebcc33e3444508466a76f7a2b93da00ed6e19f30c1ddb" +dependencies = [ + "windows-sys 0.48.0", +] + [[package]] name = "hostname" version = "0.3.1" @@ -1828,21 +1874,30 @@ dependencies = [ "hex", "indicatif", "iroh-bytes", + "iroh-gossip", "iroh-io", "iroh-metrics", "iroh-net", + "iroh-sync", "iroh-test", + "itertools 0.11.0", "multibase", "nix", "num_cpus", + "once_cell", + "parking_lot", "portable-atomic", "postcard", "proptest", "quic-rpc", "quinn", "rand", + "range-collections", "regex", + "rustyline", "serde", + "shell-words", + "shellexpand", "tempfile", "testdir", "thiserror", @@ -1904,10 +1959,9 @@ dependencies = [ [[package]] name = "iroh-gossip" -version = "0.4.1" +version = "0.5.1" dependencies = [ "anyhow", - "blake3", "bytes", "clap", "data-encoding", @@ -1916,6 +1970,7 @@ dependencies = [ "futures", "genawaiter", "indexmap 2.0.0", + "iroh-blake3", "iroh-metrics", "iroh-net", "iroh-test", @@ -2036,6 +2091,40 @@ dependencies = [ "zeroize", ] +[[package]] +name = "iroh-sync" +version = "0.5.1" +dependencies = [ + "anyhow", + "bytes", + "crossbeam", + "data-encoding", + "derive_more", + "ed25519-dalek", + "flume", + "futures", + "hex", + "iroh-blake3", + "iroh-bytes", + "iroh-metrics", + "iroh-net", + "once_cell", + "ouroboros", + "parking_lot", + "postcard", + "quinn", + "rand", + "rand_core", + "redb", + "serde", + "tempfile", + "tokio", + "tokio-stream", + "tokio-util", + "tracing", + "url", +] + [[package]] name = "iroh-test" version = "0.5.1" @@ -2065,6 +2154,15 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.9" @@ -2321,6 +2419,15 @@ dependencies = [ "tokio", ] +[[package]] +name = "nibble_vec" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77a5d83df9f36fe23f0c3648c6bbb8b0298bb5f1939c8f2704431371f4b84d43" +dependencies = [ + "smallvec", +] + [[package]] name = "nix" version = "0.26.2" @@ -2553,6 +2660,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + [[package]] name = "os_info" version = "3.7.0" @@ -2574,6 +2687,30 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "ouroboros" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2ba07320d39dfea882faa70554b4bd342a5f273ed59ba7c1c6b4c840492c954" +dependencies = [ + "aliasable", + "ouroboros_macro", + "static_assertions", +] + +[[package]] +name = "ouroboros_macro" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4c6225c69b4ca778c0aea097321a64c421cf4577b331c61b229267edabb6f8" +dependencies = [ + "heck", + "proc-macro-error 1.0.4", + "proc-macro2", + "quote", + "syn 2.0.29", +] + [[package]] name = "overload" version = "0.1.1" @@ -2872,7 +3009,6 @@ checksum = "c9ee729232311d3cd113749948b689627618133b1c5012b77342c1950b25eaeb" dependencies = [ "cobs", "const_format", - "heapless", "postcard-derive", "serde", ] @@ -2963,7 +3099,20 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "18f33027081eba0a6d8aba6d1b1c3a3be58cbb12106341c2d5759fcd9b5277e7" dependencies = [ - "proc-macro-error-attr", + "proc-macro-error-attr 0.4.12", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr 1.0.4", "proc-macro2", "quote", "syn 1.0.109", @@ -2983,6 +3132,17 @@ dependencies = [ "version_check", ] +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + [[package]] name = "proc-macro-hack" version = "0.5.20+deprecated" @@ -3041,6 +3201,16 @@ dependencies = [ "unarray", ] +[[package]] +name = "pyo3-build-config" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "076c73d0bc438f7a4ef6fdd0c3bb4732149136abd952b110ac93e4edb13a6ba5" +dependencies = [ + "once_cell", + "target-lexicon", +] + [[package]] name = "quanta" version = "0.11.1" @@ -3149,6 +3319,16 @@ dependencies = [ "pest_derive", ] +[[package]] +name = "radix_trie" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c069c179fcdc6a2fe24d8d18305cf085fdbd4f922c041943e203685d6a1c58fd" +dependencies = [ + "endian-type", + "nibble_vec", +] + [[package]] name = "rand" version = "0.8.5" @@ -3243,6 +3423,16 @@ dependencies = [ "yasna", ] +[[package]] +name = "redb" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97d37f4ea12036ad04bd2a02ce385bf28e56f97344223952dccaacbf8704823e" +dependencies = [ + "libc", + "pyo3-build-config", +] + [[package]] name = "redox_syscall" version = "0.2.16" @@ -3561,6 +3751,29 @@ dependencies = [ "wait-timeout", ] +[[package]] +name = "rustyline" +version = "12.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "994eca4bca05c87e86e15d90fc7a91d1be64b4482b38cb2d27474568fe7c9db9" +dependencies = [ + "bitflags 2.4.0", + "cfg-if", + "clipboard-win", + "fd-lock", + "home", + "libc", + "log", + "memchr", + "nix", + "radix_trie", + "scopeguard", + "unicode-segmentation", + "unicode-width", + "utf8parse", + "winapi", +] + [[package]] name = "ryu" version = "1.0.15" @@ -3799,6 +4012,21 @@ dependencies = [ "winapi", ] +[[package]] +name = "shell-words" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24188a676b6ae68c3b2cb3a01be17fbf7240ce009799bb56d5b1409051e78fde" + +[[package]] +name = "shellexpand" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da03fa3b94cc19e3ebfc88c4229c49d8f08cdbd1228870a45f0ffdf84988e14b" +dependencies = [ + "dirs", +] + [[package]] name = "signal-hook-registry" version = "1.4.1" @@ -3934,6 +4162,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "str-buf" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e08d8363704e6c71fc928674353e6b7c23dcea9d82d7012c8faf2a3a025f8d0" + [[package]] name = "strsim" version = "0.10.0" @@ -4093,6 +4327,12 @@ dependencies = [ "libc", ] +[[package]] +name = "target-lexicon" +version = "0.12.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d0e916b1148c8e263850e1ebcbd046f333e0683c724876bb0da63ea4373dc8a" + [[package]] name = "tempfile" version = "3.8.0" @@ -4544,6 +4784,12 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "unicode-segmentation" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36" + [[package]] name = "unicode-width" version = "0.1.10" diff --git a/Cargo.toml b/Cargo.toml index e352b2a09b..01a63e1be4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,7 @@ members = [ "iroh-gossip", "iroh-metrics", "iroh-net", + "iroh-sync", "iroh-test", ] diff --git a/deny.toml b/deny.toml index 1380340df9..f65fd56cb2 100644 --- a/deny.toml +++ b/deny.toml @@ -4,8 +4,10 @@ multiple-versions = "allow" [licenses] allow = [ "Apache-2.0", + "Apache-2.0 WITH LLVM-exception", "BSD-2-Clause", "BSD-3-Clause", + "BSL-1.0", # BOSL license "ISC", "MIT", "OpenSSL", diff --git a/iroh-bytes/src/protocol.rs b/iroh-bytes/src/protocol.rs index dbe6fc5cc7..063c19fd23 100644 --- a/iroh-bytes/src/protocol.rs +++ b/iroh-bytes/src/protocol.rs @@ -518,7 +518,7 @@ impl GetRequest { } /// Write the given data to the provider sink, with a unsigned varint length prefix. -pub(crate) async fn write_lp(writer: &mut W, data: &[u8]) -> Result<()> { +pub async fn write_lp(writer: &mut W, data: &[u8]) -> Result<()> { ensure!( data.len() < MAX_MESSAGE_SIZE, "sending message is too large" @@ -539,7 +539,7 @@ pub(crate) async fn write_lp(writer: &mut W, data: &[u8]) /// /// The message as raw bytes. If the end of the stream is reached and there is no partial /// message, returns `None`. -pub(crate) async fn read_lp( +pub async fn read_lp( mut reader: impl AsyncRead + Unpin, buffer: &mut BytesMut, ) -> Result> { diff --git a/iroh-bytes/src/util.rs b/iroh-bytes/src/util.rs index 490c9e5a3b..432ba03fb3 100644 --- a/iroh-bytes/src/util.rs +++ b/iroh-bytes/src/util.rs @@ -83,6 +83,18 @@ impl From<[u8; 32]> for Hash { } } +impl From for [u8; 32] { + fn from(value: Hash) -> Self { + *value.as_bytes() + } +} + +impl From<&[u8; 32]> for Hash { + fn from(value: &[u8; 32]) -> Self { + Hash(blake3::Hash::from(*value)) + } +} + impl PartialOrd for Hash { fn partial_cmp(&self, other: &Self) -> Option { Some(self.0.as_bytes().cmp(other.0.as_bytes())) @@ -202,6 +214,12 @@ impl From for RpcError { } } +impl From for RpcError { + fn from(e: std::io::Error) -> Self { + RpcError(serde_error::Error::new(&e)) + } +} + /// A serializable result type for use in RPC responses. #[allow(dead_code)] pub type RpcResult = result::Result; diff --git a/iroh-gossip/Cargo.toml b/iroh-gossip/Cargo.toml index 3276848c10..b046b9603c 100644 --- a/iroh-gossip/Cargo.toml +++ b/iroh-gossip/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "iroh-gossip" -version = "0.4.1" +version = "0.5.1" edition = "2021" readme = "README.md" description = "gossip messages over broadcast trees" @@ -14,7 +14,7 @@ rust-version = "1.67" [dependencies] # proto dependencies (required) anyhow = { version = "1", features = ["backtrace"] } -blake3 = "1.3.3" +blake3 = { package = "iroh-blake3", version = "1.4.3"} bytes = { version = "1.4.0", features = ["serde"] } data-encoding = "2.4.0" derive_more = { version = "1.0.0-beta.1", features = ["add", "debug", "display", "from", "try_into"] } diff --git a/iroh-gossip/src/net.rs b/iroh-gossip/src/net.rs index a7d6473608..4953e602cd 100644 --- a/iroh-gossip/src/net.rs +++ b/iroh-gossip/src/net.rs @@ -17,7 +17,7 @@ use tokio::{ sync::{broadcast, mpsc, oneshot, watch}, task::JoinHandle, }; -use tracing::{debug, warn}; +use tracing::{debug, trace, warn}; use self::util::{read_message, write_message, Dialer, Timers}; use crate::proto::{self, TopicId}; @@ -25,7 +25,7 @@ use crate::proto::{self, TopicId}; pub mod util; /// ALPN protocol name -pub const GOSSIP_ALPN: &[u8] = b"n0/iroh-gossip/0"; +pub const GOSSIP_ALPN: &[u8] = b"/iroh-gossip/0"; /// Maximum message size is limited to 1024 bytes. pub const MAX_MESSAGE_SIZE: usize = 1024; @@ -265,6 +265,20 @@ struct IrohInfo { derp_region: Option, } +impl IrohInfo { + async fn from_endpoint(endpoint: &MagicEndpoint) -> anyhow::Result { + Ok(Self { + addrs: endpoint + .local_endpoints() + .await? + .iter() + .map(|ep| ep.addr) + .collect(), + derp_region: endpoint.my_derp().await, + }) + } +} + /// Whether a connection is initiated by us (Dial) or by the remote peer (Accept) #[derive(Debug)] enum ConnOrigin { @@ -356,11 +370,7 @@ impl Actor { } }, _ = self.on_endpoints_rx.changed() => { - let endpoints = self.on_endpoints_rx.borrow().clone(); - let info = IrohInfo { - addrs: endpoints.iter().map(|ep| ep.addr).collect(), - derp_region: self.endpoint.my_derp().await - }; + let info = IrohInfo::from_endpoint(&self.endpoint).await?; let peer_data = postcard::to_stdvec(&info)?; self.handle_in_event(InEvent::UpdatePeerData(peer_data.into()), Instant::now()).await?; } @@ -469,13 +479,21 @@ impl Actor { async fn handle_in_event(&mut self, event: InEvent, now: Instant) -> anyhow::Result<()> { let me = *self.state.me(); - debug!(?me, "handle in_event {event:?}"); + if matches!(event, InEvent::TimerExpired(_)) { + trace!(?me, "handle in_event {event:?}"); + } else { + debug!(?me, "handle in_event {event:?}"); + }; if let InEvent::PeerDisconnected(peer) = &event { self.conn_send_tx.remove(peer); } let out = self.state.handle(event, now); for event in out { - debug!(?me, "handle out_event {event:?}"); + if matches!(event, OutEvent::ScheduleTimer(_, _)) { + trace!(?me, "handle out_event {event:?}"); + } else { + debug!(?me, "handle out_event {event:?}"); + }; match event { OutEvent::SendMessage(peer_id, message) => { if let Some(send) = self.conn_send_tx.get(&peer_id) { @@ -518,10 +536,14 @@ impl Actor { OutEvent::PeerData(peer, data) => match postcard::from_bytes::(&data) { Err(err) => warn!("Failed to decode PeerData from {peer}: {err}"), Ok(info) => { - debug!("add known addrs for {peer}: {info:?}..."); - self.endpoint + debug!(me = ?self.endpoint.peer_id(), peer = ?peer, "add known addrs: {info:?}"); + if let Err(err) = self + .endpoint .add_known_addrs(peer, info.derp_region, &info.addrs) - .await?; + .await + { + debug!(me = ?self.endpoint.peer_id(), peer = ?peer, "add known failed: {err:?}"); + } } }, } diff --git a/iroh-gossip/src/proto/util.rs b/iroh-gossip/src/proto/util.rs index 64c7a92c9a..a93f15d12a 100644 --- a/iroh-gossip/src/proto/util.rs +++ b/iroh-gossip/src/proto/util.rs @@ -56,20 +56,20 @@ macro_rules! idbytes_impls { } } - impl> From for $ty { + impl> ::std::convert::From for $ty { fn from(value: T) -> Self { Self::from_bytes(value.into()) } } - impl std::fmt::Display for $ty { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + impl ::std::fmt::Display for $ty { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "{}", $crate::proto::util::base32::fmt(&self.0)) } } - impl std::fmt::Debug for $ty { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + impl ::std::fmt::Debug for $ty { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!( f, "{}({})", @@ -79,22 +79,22 @@ macro_rules! idbytes_impls { } } - impl std::str::FromStr for $ty { + impl ::std::str::FromStr for $ty { type Err = ::anyhow::Error; - fn from_str(s: &str) -> Result { + fn from_str(s: &str) -> ::std::result::Result { Ok(Self::from_bytes($crate::proto::util::base32::parse_array( s, )?)) } } - impl AsRef<[u8]> for $ty { + impl ::std::convert::AsRef<[u8]> for $ty { fn as_ref(&self) -> &[u8] { &self.0 } } - impl AsRef<[u8; 32]> for $ty { + impl ::std::convert::AsRef<[u8; 32]> for $ty { fn as_ref(&self) -> &[u8; 32] { &self.0 } diff --git a/iroh-net/src/key.rs b/iroh-net/src/key.rs index 4d06aa97fe..aa4fe870f1 100644 --- a/iroh-net/src/key.rs +++ b/iroh-net/src/key.rs @@ -57,6 +57,18 @@ impl PublicKey { self.public.as_bytes() } + /// Construct a `PublicKey` from a slice of bytes. + /// + /// # Warning + /// + /// This will return a [`SignatureError`] if the bytes passed into this method do not represent + /// a valid `ed25519_dalek` curve point. Will never fail for bytes return from [`Self::as_bytes`]. + /// See [`VerifyingKey::from_bytes`] for details. + pub fn from_bytes(bytes: &[u8; 32]) -> Result { + let public = VerifyingKey::from_bytes(bytes)?; + Ok(public.into()) + } + fn public_crypto_box(&self) -> crypto_box::PublicKey { crypto_box::PublicKey::from_bytes(self.public_crypto_box) } @@ -81,6 +93,15 @@ impl TryFrom<&[u8]> for PublicKey { } } +impl TryFrom<&[u8; 32]> for PublicKey { + type Error = SignatureError; + + #[inline] + fn try_from(bytes: &[u8; 32]) -> Result { + Self::from_bytes(bytes) + } +} + impl AsRef<[u8]> for PublicKey { fn as_ref(&self) -> &[u8] { self.as_bytes() @@ -240,6 +261,12 @@ impl SecretKey { self.secret.to_bytes() } + /// Create a secret key from its byte representation. + pub fn from_bytes(bytes: &[u8; 32]) -> Self { + let secret = SigningKey::from_bytes(bytes); + secret.into() + } + fn secret_crypto_box(&self) -> &crypto_box::SecretKey { self.secret_crypto_box .get_or_init(|| secret_ed_box(&self.secret)) @@ -257,8 +284,7 @@ impl From for SecretKey { impl From<[u8; 32]> for SecretKey { fn from(value: [u8; 32]) -> Self { - let secret = SigningKey::from(value); - secret.into() + Self::from_bytes(&value) } } diff --git a/iroh-sync/Cargo.toml b/iroh-sync/Cargo.toml new file mode 100644 index 0000000000..1335064ec6 --- /dev/null +++ b/iroh-sync/Cargo.toml @@ -0,0 +1,55 @@ +[package] +name = "iroh-sync" +version = "0.5.1" +edition = "2021" +readme = "README.md" +description = "Iroh sync" +license = "MIT/Apache-2.0" +authors = ["n0 team"] +repository = "https://github.com/n0-computer/iroh" + +# Sadly this also needs to be updated in .github/workflows/ci.yml +rust-version = "1.67" + +[dependencies] +anyhow = "1" +blake3 = { package = "iroh-blake3", version = "1.4.3"} +crossbeam = "0.8.2" +data-encoding = "2.4.0" +derive_more = { version = "1.0.0-beta.1", features = ["debug", "display", "from", "try_into"] } +ed25519-dalek = { version = "2.0.0", features = ["serde", "rand_core"] } +flume = "0.10" +iroh-bytes = { version = "0.5.0", path = "../iroh-bytes" } +iroh-metrics = { version = "0.5.0", path = "../iroh-metrics", optional = true } +once_cell = "1.18.0" +postcard = { version = "1", default-features = false, features = ["alloc", "use-std", "experimental-derive"] } +rand = "0.8.5" +rand_core = "0.6.4" +serde = { version = "1.0.164", features = ["derive"] } +url = "2.4" +bytes = "1" +parking_lot = "0.12.1" +hex = "0.4" +tracing = "0.1" + +# fs-store +redb = { version = "1.0.5", optional = true } +ouroboros = { version = "0.17", optional = true } + +# net +iroh-net = { version = "0.5.1", optional = true, path = "../iroh-net" } +tokio = { version = "1", optional = true, features = ["io-util", "sync"] } +tokio-util = { version = "0.7", optional = true, features = ["codec", "io-util", "io"] } +tokio-stream = { version = "0.1", optional = true, features = ["sync"]} +quinn = { version = "0.10", optional = true } +futures = { version = "0.3", optional = true } + +[dev-dependencies] +tokio = { version = "1", features = ["sync", "macros"] } +tempfile = "3.4" + +[features] +default = ["net", "fs-store", "metrics"] +net = ["iroh-net", "tokio", "tokio-stream", "tokio-util", "quinn", "futures"] +fs-store = ["redb", "ouroboros"] +metrics = ["iroh-metrics"] diff --git a/iroh-sync/LICENSE-APACHE b/iroh-sync/LICENSE-APACHE new file mode 100644 index 0000000000..16fe87b06e --- /dev/null +++ b/iroh-sync/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/iroh-sync/LICENSE-MIT b/iroh-sync/LICENSE-MIT new file mode 100644 index 0000000000..dfd85baf84 --- /dev/null +++ b/iroh-sync/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2023 + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/iroh-sync/README.md b/iroh-sync/README.md new file mode 100644 index 0000000000..27484946f0 --- /dev/null +++ b/iroh-sync/README.md @@ -0,0 +1,48 @@ +# iroh-sync + +Multi-dimensional key-value documents with an efficient synchronization protocol. + +The crate operates on *Replicas*. A replica contains an unlimited number of +*Entrys*. Each entry is identified by a key, its author, and the replica's +namespace. Its value is the 32-byte BLAKE3 hash of the entry's content data, +the size of this content data, and a timestamp. +The content data itself is not stored or transfered through a replica. + +All entries in a replica are signed with two keypairs: + +* The *Namespace* key, as a token of write capability. The public key is the *NamespaceId*, which + also serves as the unique identifier for a replica. +* The *Author* key, as a proof of authorship. Any number of authors may be created, and + their semantic meaning is application-specific. The public key of an author is the [AuthorId]. + +Replicas can be synchronized between peers by exchanging messages. The synchronization algorithm +is based on a technique called *range-based set reconciliation*, based on [this paper][paper] by +Aljoscha Meyer: + +> Range-based set reconciliation is a simple approach to efficiently compute the union of two +sets over a network, based on recursively partitioning the sets and comparing fingerprints of +the partitions to probabilistically detect whether a partition requires further work. + +The crate exposes a generic storage interface with in-memory and persistent, file-based +implementations. The latter makes use of [`redb`], an embedded key-value store, and persists +the whole store with all replicas to a single file. + +[paper]: https://arxiv.org/abs/2212.13567 + + +# License + +This project is licensed under either of + + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or + http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in this project by you, as defined in the Apache-2.0 license, +shall be dual licensed as above, without any additional terms or conditions. diff --git a/iroh-sync/src/keys.rs b/iroh-sync/src/keys.rs new file mode 100644 index 0000000000..830e17be3e --- /dev/null +++ b/iroh-sync/src/keys.rs @@ -0,0 +1,283 @@ +//! Keys used in iroh-sync + +use std::{cmp::Ordering, fmt, str::FromStr}; + +use ed25519_dalek::{Signature, SignatureError, Signer, SigningKey, VerifyingKey}; +use rand_core::CryptoRngCore; +use serde::{Deserialize, Serialize}; + +/// Author key to insert entries in a [`crate::Replica`] +/// +/// Internally, an author is a [`SigningKey`] which is used to sign entries. +#[derive(Clone, Serialize, Deserialize)] +pub struct Author { + signing_key: SigningKey, +} +impl Author { + /// Create a new [`Author`] with a random key. + pub fn new(rng: &mut R) -> Self { + let signing_key = SigningKey::generate(rng); + Author { signing_key } + } + + /// Create an [`Author`] from a byte array. + pub fn from_bytes(bytes: &[u8; 32]) -> Self { + SigningKey::from_bytes(bytes).into() + } + + /// Returns the [`Author`] byte representation. + pub fn to_bytes(&self) -> [u8; 32] { + self.signing_key.to_bytes() + } + + /// Get the [`AuthorId`] for this author. + pub fn id(&self) -> AuthorId { + AuthorId(self.signing_key.verifying_key()) + } + + /// Sign a message with this [`Author`] key. + pub fn sign(&self, msg: &[u8]) -> Signature { + self.signing_key.sign(msg) + } + + /// Strictly verify a signature on a message with this [`Author`]'s public key. + pub fn verify(&self, msg: &[u8], signature: &Signature) -> Result<(), SignatureError> { + self.signing_key.verify_strict(msg, signature) + } +} + +/// Identifier for an [`Author`] +/// +/// This is the corresponding [`VerifyingKey`] for an author. It is used as an identifier, and can +/// be used to verify [`Signature`]s. +#[derive(Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Hash)] +pub struct AuthorId(VerifyingKey); + +impl AuthorId { + /// Verify that a signature matches the `msg` bytes and was created with the [`Author`] + /// that corresponds to this [`AuthorId`]. + pub fn verify(&self, msg: &[u8], signature: &Signature) -> Result<(), SignatureError> { + self.0.verify_strict(msg, signature) + } + + /// Get the byte representation of this [`AuthorId`]. + pub fn as_bytes(&self) -> &[u8; 32] { + self.0.as_bytes() + } + + /// Create from a slice of bytes. + /// + /// Will return an error if the input bytes do not represent a valid [`ed25519_dalek`] + /// curve point. Will never fail for a byte array returned from [`Self::as_bytes`]. + /// See [`VerifyingKey::from_bytes`] for details. + pub fn from_bytes(bytes: &[u8; 32]) -> anyhow::Result { + Ok(AuthorId(VerifyingKey::from_bytes(bytes)?)) + } +} + +/// Namespace key of a [`crate::Replica`]. +/// +/// Holders of this key can insert new entries into a [`crate::Replica`]. +/// Internally, a [`Namespace`] is a [`SigningKey`] which is used to sign entries. +#[derive(Clone, Serialize, Deserialize)] +pub struct Namespace { + signing_key: SigningKey, +} + +impl Namespace { + /// Create a new [`Namespace`] with a random key. + pub fn new(rng: &mut R) -> Self { + let signing_key = SigningKey::generate(rng); + + Namespace { signing_key } + } + + /// Create a [`Namespace`] from a byte array. + pub fn from_bytes(bytes: &[u8; 32]) -> Self { + SigningKey::from_bytes(bytes).into() + } + + /// Returns the [`Namespace`] byte representation. + pub fn to_bytes(&self) -> [u8; 32] { + self.signing_key.to_bytes() + } + + /// Get the [`NamespaceId`] for this namespace. + pub fn id(&self) -> NamespaceId { + NamespaceId(self.signing_key.verifying_key()) + } + + /// Sign a message with this [`Namespace`] key. + pub fn sign(&self, msg: &[u8]) -> Signature { + self.signing_key.sign(msg) + } + + /// Strictly verify a signature on a message with this [`Namespace`]'s public key. + pub fn verify(&self, msg: &[u8], signature: &Signature) -> Result<(), SignatureError> { + self.signing_key.verify_strict(msg, signature) + } +} + +/// Identifier for a [`Namespace`] +/// +/// This is the corresponding [`VerifyingKey`] for a [`Namespace`]. It is used as an identifier, and can +/// be used to verify [`Signature`]s. +#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)] +pub struct NamespaceId(VerifyingKey); + +impl NamespaceId { + /// Verify that a signature matches the `msg` bytes and was created with the [`Namespace`] + /// that corresponds to this [`NamespaceId`]. + pub fn verify(&self, msg: &[u8], signature: &Signature) -> Result<(), SignatureError> { + self.0.verify_strict(msg, signature) + } + + /// Get the byte representation of this [`NamespaceId`]. + pub fn as_bytes(&self) -> &[u8; 32] { + self.0.as_bytes() + } + + /// Create from a slice of bytes. + /// + /// Will return an error if the input bytes do not represent a valid [`ed25519_dalek`] + /// curve point. Will never fail for a byte array returned from [`Self::as_bytes`]. + /// See [`VerifyingKey::from_bytes`] for details. + pub fn from_bytes(bytes: &[u8; 32]) -> anyhow::Result { + Ok(NamespaceId(VerifyingKey::from_bytes(bytes)?)) + } +} + +impl fmt::Display for Author { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", base32::fmt(self.to_bytes())) + } +} + +impl fmt::Display for Namespace { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", base32::fmt(self.to_bytes())) + } +} + +impl fmt::Display for AuthorId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", base32::fmt(self.as_bytes())) + } +} + +impl fmt::Display for NamespaceId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", base32::fmt(self.as_bytes())) + } +} + +impl fmt::Debug for Namespace { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Namespace({})", self) + } +} + +impl fmt::Debug for Author { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Author({})", self) + } +} + +impl fmt::Debug for NamespaceId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "NamespaceId({})", self) + } +} + +impl fmt::Debug for AuthorId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "AuthorId({})", self) + } +} + +impl FromStr for Author { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + Ok(Self::from_bytes(&base32::parse_array(s)?)) + } +} + +impl FromStr for Namespace { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + Ok(Self::from_bytes(&base32::parse_array(s)?)) + } +} + +impl FromStr for AuthorId { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + Self::from_bytes(&base32::parse_array(s)?) + } +} + +impl FromStr for NamespaceId { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + Self::from_bytes(&base32::parse_array(s)?) + } +} + +impl From for Author { + fn from(signing_key: SigningKey) -> Self { + Self { signing_key } + } +} + +impl From for Namespace { + fn from(signing_key: SigningKey) -> Self { + Self { signing_key } + } +} + +impl PartialOrd for NamespaceId { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for NamespaceId { + fn cmp(&self, other: &Self) -> Ordering { + self.0.as_bytes().cmp(other.0.as_bytes()) + } +} + +impl PartialOrd for AuthorId { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for AuthorId { + fn cmp(&self, other: &Self) -> Ordering { + self.0.as_bytes().cmp(other.0.as_bytes()) + } +} + +/// Utilities for working with byte array identifiers +// TODO: copy-pasted from iroh-gossip/src/proto/util.rs +// Unify into iroh-common crate or similar +mod base32 { + /// Convert to a base32 string + pub fn fmt(bytes: impl AsRef<[u8]>) -> String { + let mut text = data_encoding::BASE32_NOPAD.encode(bytes.as_ref()); + text.make_ascii_lowercase(); + text + } + /// Parse from a base32 string into a byte array + pub fn parse_array(input: &str) -> anyhow::Result<[u8; N]> { + data_encoding::BASE32_NOPAD + .decode(input.to_ascii_uppercase().as_bytes())? + .try_into() + .map_err(|_| ::anyhow::anyhow!("Failed to parse: invalid byte length")) + } +} diff --git a/iroh-sync/src/lib.rs b/iroh-sync/src/lib.rs new file mode 100644 index 0000000000..391b6b09b7 --- /dev/null +++ b/iroh-sync/src/lib.rs @@ -0,0 +1,42 @@ +//! Multi-dimensional key-value documents with an efficient synchronization protocol +//! +//! The crate operates on [Replicas](Replica). A replica contains an unlimited number of +//! [Entrys][Entry]. Each entry is identified by a key, its author, and the replica's +//! namespace. Its value is the [32-byte BLAKE3 hash](iroh_bytes::Hash) +//! of the entry's content data, the size of this content data, and a timestamp. +//! The content data itself is not stored or transfered through a replica. +//! +//! All entries in a replica are signed with two keypairs: +//! +//! * The [Namespace] key, as a token of write capability. The public key is the [NamespaceId], which +//! also serves as the unique identifier for a replica. +//! * The [Author] key, as a proof of authorship. Any number of authors may be created, and +//! their semantic meaning is application-specific. The public key of an author is the [AuthorId]. +//! +//! Replicas can be synchronized between peers by exchanging messages. The synchronization algorithm +//! is based on a technique called *range-based set reconciliation*, based on [this paper][paper] by +//! Aljoscha Meyer: +//! +//! > Range-based set reconciliation is a simple approach to efficiently compute the union of two +//! sets over a network, based on recursively partitioning the sets and comparing fingerprints of +//! the partitions to probabilistically detect whether a partition requires further work. +//! +//! The crate exposes a [generic storage interface](store::Store) with +//! [in-memory](store::memory::Store) and [persistent, file-based](store::fs::Store) +//! implementations. The latter makes use of [`redb`], an embedded key-value store, and persists +//! the whole store with all replicas to a single file. +//! +//! [paper]: https://arxiv.org/abs/2212.13567 +#![deny(missing_docs, rustdoc::broken_intra_doc_links)] + +mod keys; +#[cfg(feature = "metrics")] +pub mod metrics; +#[cfg(feature = "net")] +pub mod net; +mod ranger; +pub mod store; +pub mod sync; + +pub use keys::*; +pub use sync::*; diff --git a/iroh-sync/src/metrics.rs b/iroh-sync/src/metrics.rs new file mode 100644 index 0000000000..91af686c97 --- /dev/null +++ b/iroh-sync/src/metrics.rs @@ -0,0 +1,37 @@ +//! Metrics for iroh-sync + +use iroh_metrics::{ + core::{Counter, Metric}, + struct_iterable::Iterable, +}; + +/// Metrics for iroh-sync +#[allow(missing_docs)] +#[derive(Debug, Clone, Iterable)] +pub struct Metrics { + pub new_entries_local: Counter, + pub new_entries_remote: Counter, + pub new_entries_local_size: Counter, + pub new_entries_remote_size: Counter, + pub initial_sync_success: Counter, + pub initial_sync_failed: Counter, +} + +impl Default for Metrics { + fn default() -> Self { + Self { + new_entries_local: Counter::new("Number of document entries added locally"), + new_entries_remote: Counter::new("Number of document entries added by peers"), + new_entries_local_size: Counter::new("Total size of entry contents added locally"), + new_entries_remote_size: Counter::new("Total size of entry contents added by peers"), + initial_sync_success: Counter::new("Number of successfull initial syncs "), + initial_sync_failed: Counter::new("Number of failed initial syncs"), + } + } +} + +impl Metric for Metrics { + fn name() -> &'static str { + "iroh-sync" + } +} diff --git a/iroh-sync/src/net.rs b/iroh-sync/src/net.rs new file mode 100644 index 0000000000..25534ae8ed --- /dev/null +++ b/iroh-sync/src/net.rs @@ -0,0 +1,77 @@ +//! Network implementation of the iroh-sync protocol + +use std::net::SocketAddr; + +use anyhow::{Context, Result}; +use iroh_net::{key::PublicKey, magic_endpoint::get_peer_id, MagicEndpoint}; +use tracing::debug; + +use crate::{ + net::codec::{run_alice, run_bob}, + store, + sync::Replica, +}; + +#[cfg(feature = "metrics")] +use crate::metrics::Metrics; +#[cfg(feature = "metrics")] +use iroh_metrics::inc; + +/// The ALPN identifier for the iroh-sync protocol +pub const SYNC_ALPN: &[u8] = b"/iroh-sync/1"; + +mod codec; + +/// Connect to a peer and sync a replica +pub async fn connect_and_sync( + endpoint: &MagicEndpoint, + doc: &Replica, + peer_id: PublicKey, + derp_region: Option, + addrs: &[SocketAddr], +) -> anyhow::Result<()> { + debug!("sync with peer {}: start", peer_id); + let connection = endpoint + .connect(peer_id, SYNC_ALPN, derp_region, addrs) + .await + .context("dial_and_sync")?; + let (mut send_stream, mut recv_stream) = connection.open_bi().await?; + let res = run_alice::(&mut send_stream, &mut recv_stream, doc, peer_id).await; + + #[cfg(feature = "metrics")] + if res.is_ok() { + inc!(Metrics, initial_sync_success); + } else { + inc!(Metrics, initial_sync_failed); + } + + debug!("sync with peer {}: finish {:?}", peer_id, res); + res +} + +/// Handle an iroh-sync connection and sync all shared documents in the replica store. +pub async fn handle_connection( + connecting: quinn::Connecting, + replica_store: S, +) -> Result<()> { + let connection = connecting.await?; + let peer_id = get_peer_id(&connection).await?; + let (mut send_stream, mut recv_stream) = connection.accept_bi().await?; + debug!(peer = ?peer_id, "incoming sync: start"); + + let res = run_bob(&mut send_stream, &mut recv_stream, replica_store, peer_id).await; + + #[cfg(feature = "metrics")] + if res.is_ok() { + inc!(Metrics, initial_sync_success); + } else { + inc!(Metrics, initial_sync_failed); + } + + res?; + send_stream.finish().await?; + + debug!(peer = ?peer_id, "incoming sync: done"); + + Ok(()) +} diff --git a/iroh-sync/src/net/codec.rs b/iroh-sync/src/net/codec.rs new file mode 100644 index 0000000000..fef102a378 --- /dev/null +++ b/iroh-sync/src/net/codec.rs @@ -0,0 +1,289 @@ +use anyhow::{bail, ensure, Result}; +use bytes::{Buf, BufMut, BytesMut}; +use futures::SinkExt; +use iroh_net::key::PublicKey; +use serde::{Deserialize, Serialize}; +use tokio::io::{AsyncRead, AsyncWrite}; +use tokio_stream::StreamExt; +use tokio_util::codec::{Decoder, Encoder, FramedRead, FramedWrite}; +use tracing::debug; + +use crate::{store, NamespaceId, Replica}; + +#[derive(Debug, Default)] +struct SyncCodec; + +const MAX_MESSAGE_SIZE: usize = 1024 * 1024 * 1024; // This is likely too large, but lets have some restrictions + +impl Decoder for SyncCodec { + type Item = Message; + type Error = anyhow::Error; + fn decode( + &mut self, + src: &mut BytesMut, + ) -> std::result::Result, Self::Error> { + if src.len() < 4 { + return Ok(None); + } + let bytes: [u8; 4] = src[..4].try_into().unwrap(); + let frame_len = u32::from_be_bytes(bytes) as usize; + ensure!( + frame_len <= MAX_MESSAGE_SIZE, + "received message that is too large: {}", + frame_len + ); + if src.len() < 4 + frame_len { + return Ok(None); + } + + let message: Message = postcard::from_bytes(&src[4..4 + frame_len])?; + src.advance(4 + frame_len); + Ok(Some(message)) + } +} + +impl Encoder for SyncCodec { + type Error = anyhow::Error; + + fn encode( + &mut self, + item: Message, + dst: &mut BytesMut, + ) -> std::result::Result<(), Self::Error> { + let len = + postcard::serialize_with_flavor(&item, postcard::ser_flavors::Size::default()).unwrap(); + ensure!( + len <= MAX_MESSAGE_SIZE, + "attempting to send message that is too large {}", + len + ); + + dst.put_u32(u32::try_from(len).expect("already checked")); + if dst.len() < 4 + len { + dst.resize(4 + len, 0u8); + } + postcard::to_slice(&item, &mut dst[4..])?; + + Ok(()) + } +} + +/// Sync Protocol +/// +/// - Init message: signals which namespace is being synced +/// - N Sync messages +/// +/// On any error and on success the substream is closed. +#[derive(Debug, Clone, Serialize, Deserialize)] +enum Message { + Init { + /// Namespace to sync + namespace: NamespaceId, + /// Initial message + message: crate::sync::ProtocolMessage, + }, + Sync(crate::sync::ProtocolMessage), +} + +/// Runs the initiator side of the sync protocol. +pub(super) async fn run_alice( + writer: &mut W, + reader: &mut R, + alice: &Replica, + other_peer_id: PublicKey, +) -> Result<()> { + let other_peer_id = *other_peer_id.as_bytes(); + let mut reader = FramedRead::new(reader, SyncCodec); + let mut writer = FramedWrite::new(writer, SyncCodec); + + // Init message + + let init_message = Message::Init { + namespace: alice.namespace(), + message: alice.sync_initial_message().map_err(Into::into)?, + }; + writer.send(init_message).await?; + + // Sync message loop + + while let Some(msg) = reader.next().await { + match msg? { + Message::Init { .. } => { + bail!("unexpected message: init"); + } + Message::Sync(msg) => { + if let Some(msg) = alice + .sync_process_message(msg, other_peer_id) + .map_err(Into::into)? + { + writer.send(Message::Sync(msg)).await?; + } else { + break; + } + } + } + } + + Ok(()) +} + +/// Runs the receiver side of the sync protocol. +pub(super) async fn run_bob( + writer: &mut W, + reader: &mut R, + replica_store: S, + other_peer_id: PublicKey, +) -> Result<()> { + let other_peer_id = *other_peer_id.as_bytes(); + let mut reader = FramedRead::new(reader, SyncCodec); + let mut writer = FramedWrite::new(writer, SyncCodec); + + let mut replica = None; + + while let Some(msg) = reader.next().await { + match msg? { + Message::Init { namespace, message } => { + ensure!(replica.is_none(), "double init message"); + + match replica_store.open_replica(&namespace)? { + Some(r) => { + debug!("starting sync for {}", namespace); + if let Some(msg) = r + .sync_process_message(message, other_peer_id) + .map_err(Into::into)? + { + writer.send(Message::Sync(msg)).await?; + } else { + break; + } + replica = Some(r); + } + None => { + bail!("unable to synchronize unknown namespace: {}", namespace); + } + } + } + Message::Sync(msg) => match replica { + Some(ref replica) => { + if let Some(msg) = replica + .sync_process_message(msg, other_peer_id) + .map_err(Into::into)? + { + writer.send(Message::Sync(msg)).await?; + } else { + break; + } + } + None => { + bail!("unexpected sync message without init"); + } + }, + } + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use crate::{ + store::{GetFilter, Store as _}, + sync::Namespace, + }; + use iroh_net::key::SecretKey; + + use super::*; + + #[tokio::test] + async fn test_sync_simple() -> Result<()> { + let mut rng = rand::thread_rng(); + let alice_peer_id = SecretKey::from_bytes(&[1u8; 32]).public(); + let bob_peer_id = SecretKey::from_bytes(&[2u8; 32]).public(); + + let alice_replica_store = store::memory::Store::default(); + // For now uses same author on both sides. + let author = alice_replica_store.new_author(&mut rng).unwrap(); + + let namespace = Namespace::new(&mut rng); + + let alice_replica = alice_replica_store.new_replica(namespace.clone()).unwrap(); + alice_replica + .hash_and_insert("hello bob", &author, "from alice") + .unwrap(); + + let bob_replica_store = store::memory::Store::default(); + let bob_replica = bob_replica_store.new_replica(namespace.clone()).unwrap(); + bob_replica + .hash_and_insert("hello alice", &author, "from bob") + .unwrap(); + + assert_eq!( + bob_replica_store + .get(bob_replica.namespace(), GetFilter::all()) + .unwrap() + .collect::>>() + .unwrap() + .len(), + 1 + ); + assert_eq!( + alice_replica_store + .get(alice_replica.namespace(), GetFilter::all()) + .unwrap() + .collect::>>() + .unwrap() + .len(), + 1 + ); + + let (alice, bob) = tokio::io::duplex(64); + + let (mut alice_reader, mut alice_writer) = tokio::io::split(alice); + let replica = alice_replica.clone(); + let alice_task = tokio::task::spawn(async move { + run_alice::( + &mut alice_writer, + &mut alice_reader, + &replica, + bob_peer_id, + ) + .await + }); + + let (mut bob_reader, mut bob_writer) = tokio::io::split(bob); + let bob_replica_store_task = bob_replica_store.clone(); + let bob_task = tokio::task::spawn(async move { + run_bob::( + &mut bob_writer, + &mut bob_reader, + bob_replica_store_task, + alice_peer_id, + ) + .await + }); + + alice_task.await??; + bob_task.await??; + + assert_eq!( + bob_replica_store + .get(bob_replica.namespace(), GetFilter::all()) + .unwrap() + .collect::>>() + .unwrap() + .len(), + 2 + ); + assert_eq!( + alice_replica_store + .get(alice_replica.namespace(), GetFilter::all()) + .unwrap() + .collect::>>() + .unwrap() + .len(), + 2 + ); + + Ok(()) + } +} diff --git a/iroh-sync/src/ranger.rs b/iroh-sync/src/ranger.rs new file mode 100644 index 0000000000..cbec0c359b --- /dev/null +++ b/iroh-sync/src/ranger.rs @@ -0,0 +1,1322 @@ +//! Implementation of Set Reconcilliation based on +//! "Range-Based Set Reconciliation" by Aljoscha Meyer. +//! + +use std::collections::BTreeMap; +use std::fmt::Debug; +use std::marker::PhantomData; +use std::{cmp::Ordering, convert::Infallible}; + +use serde::{Deserialize, Serialize}; + +/// Stores a range. +/// +/// There are three possibilities +/// - x, x: All elements in a set, denoted with +/// - [x, y): x < y: Includes x, but not y +/// - S \ [y, x) y < x: Includes x, but not y. +/// This means that ranges are "wrap around" conceptually. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)] +pub struct Range { + x: K, + y: K, +} + +impl Range { + pub fn x(&self) -> &K { + &self.x + } + + pub fn y(&self) -> &K { + &self.y + } + + pub fn new(x: K, y: K) -> Self { + Range { x, y } + } + + pub fn map(self, f: impl FnOnce(K, K) -> (X, X)) -> Range { + let (x, y) = f(self.x, self.y); + Range { x, y } + } +} + +impl From<(K, K)> for Range { + fn from((x, y): (K, K)) -> Self { + Range { x, y } + } +} + +pub trait RangeKey: Sized + Ord + Debug { + /// Is this key inside the range? + fn contains(&self, range: &Range) -> bool { + contains(self, range) + } +} + +/// Default implementation of `contains` for `Ord` types. +pub fn contains(t: &T, range: &Range) -> bool { + match range.x().cmp(range.y()) { + Ordering::Equal => true, + Ordering::Less => range.x() <= t && t < range.y(), + Ordering::Greater => range.x() <= t || t < range.y(), + } +} + +impl RangeKey for &str {} +impl RangeKey for &[u8] {} + +#[derive(Copy, Clone, PartialEq, Serialize, Deserialize)] +pub struct Fingerprint(pub [u8; 32]); + +impl Debug for Fingerprint { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Fp({})", blake3::Hash::from(self.0).to_hex()) + } +} + +impl Fingerprint { + /// The fingerprint of the empty set + pub fn empty() -> Self { + Fingerprint::new(&[][..]) + } + + pub fn new(val: T) -> Self { + val.as_fingerprint() + } +} + +pub trait AsFingerprint { + fn as_fingerprint(&self) -> Fingerprint; +} + +impl> AsFingerprint for T { + fn as_fingerprint(&self) -> Fingerprint { + Fingerprint(blake3::hash(self.as_ref()).into()) + } +} + +impl std::ops::BitXorAssign for Fingerprint { + fn bitxor_assign(&mut self, rhs: Self) { + for (a, b) in self.0.iter_mut().zip(rhs.0.iter()) { + *a ^= b; + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct RangeFingerprint { + #[serde(bound( + serialize = "Range: Serialize", + deserialize = "Range: Deserialize<'de>" + ))] + pub range: Range, + /// The fingerprint of `range`. + pub fingerprint: Fingerprint, +} + +/// Transfers items inside a range to the other participant. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct RangeItem { + /// The range out of which the elements are. + #[serde(bound( + serialize = "Range: Serialize", + deserialize = "Range: Deserialize<'de>" + ))] + pub range: Range, + #[serde(bound( + serialize = "K: Serialize, V: Serialize", + deserialize = "K: Deserialize<'de>, V: Deserialize<'de>" + ))] + pub values: Vec<(K, V)>, + /// If false, requests to send local items in the range. + /// Otherwise not. + pub have_local: bool, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub enum MessagePart { + #[serde(bound( + serialize = "RangeFingerprint: Serialize", + deserialize = "RangeFingerprint: Deserialize<'de>" + ))] + RangeFingerprint(RangeFingerprint), + #[serde(bound( + serialize = "RangeItem: Serialize", + deserialize = "RangeItem: Deserialize<'de>" + ))] + RangeItem(RangeItem), +} + +impl MessagePart { + pub fn is_range_fingerprint(&self) -> bool { + matches!(self, MessagePart::RangeFingerprint(_)) + } + + pub fn is_range_item(&self) -> bool { + matches!(self, MessagePart::RangeItem(_)) + } + + pub fn values(&self) -> Option<&[(K, V)]> { + match self { + MessagePart::RangeFingerprint(_) => None, + MessagePart::RangeItem(RangeItem { values, .. }) => Some(values), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Message { + #[serde(bound( + serialize = "MessagePart: Serialize", + deserialize = "MessagePart: Deserialize<'de>" + ))] + parts: Vec>, +} + +impl Message +where + K: RangeKey + Clone + Default + AsFingerprint, +{ + /// Construct the initial message. + fn init>(store: &S, limit: Option<&Range>) -> Result { + let x = store.get_first()?; + let range = Range::new(x.clone(), x); + let fingerprint = store.get_fingerprint(&range, limit)?; + let part = MessagePart::RangeFingerprint(RangeFingerprint { range, fingerprint }); + Ok(Message { parts: vec![part] }) + } + + pub fn parts(&self) -> &[MessagePart] { + &self.parts + } +} + +pub trait Store: Sized +where + K: RangeKey + Clone + Default + AsFingerprint, +{ + type Error: Debug + Send + Sync + Into; + + /// Get a the first key (or the default if none is available). + fn get_first(&self) -> Result; + fn get(&self, key: &K) -> Result, Self::Error>; + fn len(&self) -> Result; + fn is_empty(&self) -> Result; + /// Calculate the fingerprint of the given range. + fn get_fingerprint( + &self, + range: &Range, + limit: Option<&Range>, + ) -> Result; + + /// Insert the given key value pair. + fn put(&mut self, k: K, v: V) -> Result<(), Self::Error>; + + type RangeIterator<'a>: Iterator> + where + Self: 'a, + K: 'a, + V: 'a; + + /// Returns all items in the given range + fn get_range( + &self, + range: Range, + limit: Option>, + ) -> Result, Self::Error>; + fn remove(&mut self, key: &K) -> Result, Self::Error>; + + type AllIterator<'a>: Iterator> + where + Self: 'a, + K: 'a, + V: 'a; + fn all(&self) -> Result, Self::Error>; +} + +#[derive(Debug)] +pub struct SimpleStore { + data: BTreeMap, +} + +impl Default for SimpleStore { + fn default() -> Self { + SimpleStore { + data: BTreeMap::default(), + } + } +} + +impl Store for SimpleStore +where + K: RangeKey + Clone + Default + AsFingerprint, + V: Clone, +{ + type Error = Infallible; + + fn get_first(&self) -> Result { + if let Some((k, _)) = self.data.first_key_value() { + Ok(k.clone()) + } else { + Ok(Default::default()) + } + } + + fn get(&self, key: &K) -> Result, Self::Error> { + Ok(self.data.get(key).cloned()) + } + + fn len(&self) -> Result { + Ok(self.data.len()) + } + + fn is_empty(&self) -> Result { + Ok(self.data.is_empty()) + } + + /// Calculate the fingerprint of the given range. + fn get_fingerprint( + &self, + range: &Range, + limit: Option<&Range>, + ) -> Result { + let elements = self.get_range(range.clone(), limit.cloned())?; + let mut fp = Fingerprint::empty(); + for el in elements { + let el = el?; + fp ^= el.0.as_fingerprint(); + } + + Ok(fp) + } + + /// Insert the given key value pair. + fn put(&mut self, k: K, v: V) -> Result<(), Self::Error> { + self.data.insert(k, v); + Ok(()) + } + + type RangeIterator<'a> = SimpleRangeIterator<'a, K, V> + where K: 'a, V: 'a; + /// Returns all items in the given range + fn get_range( + &self, + range: Range, + limit: Option>, + ) -> Result, Self::Error> { + // TODO: this is not very efficient, optimize depending on data structure + let iter = self.data.iter(); + + Ok(SimpleRangeIterator { + iter, + range: Some(range), + limit, + }) + } + + fn remove(&mut self, key: &K) -> Result, Self::Error> { + // No versions stored + + let res = self.data.remove(key).into_iter().collect(); + Ok(res) + } + + type AllIterator<'a> = SimpleRangeIterator<'a, K, V> + where K: 'a, + V: 'a; + + fn all(&self) -> Result, Self::Error> { + let iter = self.data.iter(); + + Ok(SimpleRangeIterator { + iter, + range: None, + limit: None, + }) + } +} + +#[derive(Debug)] +pub struct SimpleRangeIterator<'a, K: 'a, V: 'a> { + iter: std::collections::btree_map::Iter<'a, K, V>, + range: Option>, + limit: Option>, +} + +impl<'a, K, V> Iterator for SimpleRangeIterator<'a, K, V> +where + K: RangeKey + Clone, + V: Clone, +{ + type Item = Result<(K, V), Infallible>; + + fn next(&mut self) -> Option { + let mut next = self.iter.next()?; + + let filter = |x: &K| match (&self.range, &self.limit) { + (None, None) => true, + (Some(ref range), Some(ref limit)) => x.contains(range) && x.contains(limit), + (Some(ref range), None) => x.contains(range), + (None, Some(ref limit)) => x.contains(limit), + }; + + loop { + if filter(next.0) { + return Some(Ok((next.0.clone(), next.1.clone()))); + } + + next = self.iter.next()?; + } + } +} + +#[derive(Debug)] +pub struct Peer = SimpleStore> +where + K: RangeKey + Clone + Default + AsFingerprint, +{ + store: S, + /// Up to how many values to send immediately, before sending only a fingerprint. + max_set_size: usize, + /// `k` in the protocol, how many splits to generate. at least 2 + split_factor: usize, + limit: Option>, + + _phantom: PhantomData, // why??? +} + +impl Default for Peer +where + K: RangeKey + Clone + Default + AsFingerprint, + S: Store + Default, +{ + fn default() -> Self { + Peer { + store: S::default(), + max_set_size: 1, + split_factor: 2, + limit: None, + _phantom: Default::default(), + } + } +} + +// currently unused outside of tests +#[cfg(test)] +impl Peer +where + K: PartialEq + RangeKey + Clone + Default + Debug + AsFingerprint, + V: Clone + Debug, + S: Store + Default, +{ + fn with_limit(limit: Range) -> Self { + Peer { + store: S::default(), + max_set_size: 1, + split_factor: 2, + limit: Some(limit), + _phantom: Default::default(), + } + } +} + +impl Peer +where + K: PartialEq + RangeKey + Clone + Default + Debug + AsFingerprint, + V: Clone + Debug, + S: Store, +{ + pub fn from_store(store: S) -> Self { + Peer { + store, + max_set_size: 1, + split_factor: 2, + limit: None, + _phantom: Default::default(), + } + } + + /// Generates the initial message. + pub fn initial_message(&self) -> Result, S::Error> { + Message::init(&self.store, self.limit.as_ref()) + } + + /// Processes an incoming message and produces a response. + /// If terminated, returns `None` + pub fn process_message( + &mut self, + message: Message, + cb: F, + ) -> Result>, S::Error> + where + F: Fn(K, V), + { + let mut out = Vec::new(); + + // TODO: can these allocs be avoided? + let mut items = Vec::new(); + let mut fingerprints = Vec::new(); + for part in message.parts { + match part { + MessagePart::RangeItem(item) => { + items.push(item); + } + MessagePart::RangeFingerprint(fp) => { + fingerprints.push(fp); + } + } + } + + // Process item messages + for RangeItem { + range, + values, + have_local, + } in items + { + let diff: Option> = if have_local { + None + } else { + Some( + self.store + .get_range(range.clone(), self.limit.clone())? + .filter_map(|el| match el { + Ok((k, v)) => { + if !values.iter().any(|(vk, _)| vk == &k) { + Some(Ok((k, v))) + } else { + None + } + } + Err(err) => Some(Err(err)), + }) + .collect::>()?, + ) + }; + + // Store incoming values + for (k, v) in values { + cb(k.clone(), v.clone()); + self.store.put(k, v)?; + } + + if let Some(diff) = diff { + if !diff.is_empty() { + out.push(MessagePart::RangeItem(RangeItem { + range, + values: diff, + have_local: true, + })); + } + } + } + + // Process fingerprint messages + for RangeFingerprint { range, fingerprint } in fingerprints { + let local_fingerprint = self.store.get_fingerprint(&range, self.limit.as_ref())?; + + // Case1 Match, nothing to do + if local_fingerprint == fingerprint { + continue; + } + + // Case2 Recursion Anchor + let local_values: Vec<_> = self + .store + .get_range(range.clone(), self.limit.clone())? + .collect::>()?; + if local_values.len() <= 1 || fingerprint == Fingerprint::empty() { + let values = local_values.into_iter().map(|(k, v)| (k, v)).collect(); + out.push(MessagePart::RangeItem(RangeItem { + range, + values, + have_local: false, + })); + } else { + // Case3 Recurse + // Create partition + // m0 = x < m1 < .. < mk = y, with k>= 2 + // such that [ml, ml+1) is nonempty + let mut ranges = Vec::with_capacity(self.split_factor); + let chunk_len = div_ceil(local_values.len(), self.split_factor); + + // Select the first index, for which the key is larger than the x of the range. + let mut start_index = local_values + .iter() + .position(|(k, _)| range.x() <= k) + .unwrap_or(0); + let max_len = local_values.len(); + for i in 0..self.split_factor { + let s_index = start_index; + let start = (s_index * chunk_len) % max_len; + let e_index = s_index + 1; + let end = (e_index * chunk_len) % max_len; + + let (x, y) = if i == 0 { + // first + (range.x(), &local_values[end].0) + } else if i == self.split_factor - 1 { + // last + (&local_values[start].0, range.y()) + } else { + // regular + (&local_values[start].0, &local_values[end].0) + }; + let range = Range::new(x.clone(), y.clone()); + ranges.push(range); + start_index += 1; + } + + for range in ranges.into_iter() { + let chunk: Vec<_> = self + .store + .get_range(range.clone(), self.limit.clone())? + .collect(); + // Add either the fingerprint or the item set + let fingerprint = self.store.get_fingerprint(&range, self.limit.as_ref())?; + if chunk.len() > self.max_set_size { + out.push(MessagePart::RangeFingerprint(RangeFingerprint { + range, + fingerprint, + })); + } else { + let values = chunk + .into_iter() + .map(|el| match el { + Ok((k, v)) => { + let k: K = k; + let v: V = v; + Ok((k, v)) + } + Err(err) => Err(err), + }) + .collect::>()?; + out.push(MessagePart::RangeItem(RangeItem { + range, + values, + have_local: false, + })); + } + } + } + } + + // If we have any parts, return a message + if !out.is_empty() { + Ok(Some(Message { parts: out })) + } else { + Ok(None) + } + } + + /// Insert a key value pair. + pub fn put(&mut self, k: K, v: V) -> Result<(), S::Error> { + self.store.put(k, v) + } + + /// List all existing key value pairs. + // currently unused outside of tests + #[cfg(test)] + pub fn all(&self) -> Result> + '_, S::Error> { + self.store.all() + } + + // /// Get the entry for the given key. + // pub fn get(&self, k: &K) -> Result, S::Error> { + // self.store.get(k) + // } + // /// Remove the given key. + // pub fn remove(&mut self, k: &K) -> Result, S::Error> { + // self.store.remove(k) + // } + // + // /// Returns a refernce to the underlying store. + // pub fn store(&self) -> &S { + // &self.store + // } +} + +/// Sadly is still unstable.. +fn div_ceil(a: usize, b: usize) -> usize { + debug_assert!(a != 0); + debug_assert!(b != 0); + + a / b + (a % b != 0) as usize +} + +#[cfg(test)] +mod tests { + use std::fmt::Debug; + + use super::*; + + #[test] + fn test_paper_1() { + let alice_set = [("ape", 1), ("eel", 1), ("fox", 1), ("gnu", 1)]; + let bob_set = [ + ("bee", 1), + ("cat", 1), + ("doe", 1), + ("eel", 1), + ("fox", 1), + ("hog", 1), + ]; + + let res = sync(None, &alice_set, &bob_set); + assert_eq!(res.alice_to_bob.len(), 2, "A -> B message count"); + assert_eq!(res.bob_to_alice.len(), 2, "B -> A message count"); + + // Initial message + assert_eq!(res.alice_to_bob[0].parts.len(), 1); + assert!(res.alice_to_bob[0].parts[0].is_range_fingerprint()); + + // Response from Bob - recurse once + assert_eq!(res.bob_to_alice[0].parts.len(), 2); + assert!(res.bob_to_alice[0].parts[0].is_range_fingerprint()); + assert!(res.bob_to_alice[0].parts[1].is_range_fingerprint()); + + // Last response from Alice + assert_eq!(res.alice_to_bob[1].parts.len(), 3); + assert!(res.alice_to_bob[1].parts[0].is_range_item()); + assert!(res.alice_to_bob[1].parts[1].is_range_fingerprint()); + assert!(res.alice_to_bob[1].parts[2].is_range_item()); + + // Last response from Bob + assert_eq!(res.bob_to_alice[1].parts.len(), 2); + assert!(res.bob_to_alice[1].parts[0].is_range_item()); + assert!(res.bob_to_alice[1].parts[1].is_range_item()); + } + + #[test] + fn test_paper_2() { + let alice_set = [ + ("ape", 1), + ("bee", 1), + ("cat", 1), + ("doe", 1), + ("eel", 1), + ("fox", 1), // the only value being sent + ("gnu", 1), + ("hog", 1), + ]; + let bob_set = [ + ("ape", 1), + ("bee", 1), + ("cat", 1), + ("doe", 1), + ("eel", 1), + ("gnu", 1), + ("hog", 1), + ]; + + let res = sync(None, &alice_set, &bob_set); + assert_eq!(res.alice_to_bob.len(), 3, "A -> B message count"); + assert_eq!(res.bob_to_alice.len(), 2, "B -> A message count"); + } + + #[test] + fn test_paper_3() { + let alice_set = [ + ("ape", 1), + ("bee", 1), + ("cat", 1), + ("doe", 1), + ("eel", 1), + ("fox", 1), + ("gnu", 1), + ("hog", 1), + ]; + let bob_set = [("ape", 1), ("cat", 1), ("eel", 1), ("gnu", 1)]; + + let res = sync(None, &alice_set, &bob_set); + assert_eq!(res.alice_to_bob.len(), 3, "A -> B message count"); + assert_eq!(res.bob_to_alice.len(), 2, "B -> A message count"); + } + + #[test] + fn test_limits() { + let alice_set = [("ape", 1), ("bee", 1), ("cat", 1)]; + let bob_set = [("ape", 1), ("cat", 1), ("doe", 1)]; + + // No Limit + let res = sync(None, &alice_set, &bob_set); + assert_eq!(res.alice_to_bob.len(), 3, "A -> B message count"); + assert_eq!(res.bob_to_alice.len(), 2, "B -> A message count"); + + // With Limit: just ape + let limit = ("ape", "bee").into(); + let res = sync(Some(limit), &alice_set, &bob_set); + assert_eq!(res.alice_to_bob.len(), 1, "A -> B message count"); + assert_eq!(res.bob_to_alice.len(), 0, "B -> A message count"); + + // With Limit: just bee, cat + let limit = ("bee", "doe").into(); + let res = sync(Some(limit), &alice_set, &bob_set); + assert_eq!(res.alice_to_bob.len(), 2, "A -> B message count"); + assert_eq!(res.bob_to_alice.len(), 1, "B -> A message count"); + } + + #[test] + fn test_prefixes_simple() { + let alice_set = [("/foo/bar", 1), ("/foo/baz", 1), ("/foo/cat", 1)]; + let bob_set = [("/foo/bar", 1), ("/alice/bar", 1), ("/alice/baz", 1)]; + + // No Limit + let res = sync(None, &alice_set, &bob_set); + assert_eq!(res.alice_to_bob.len(), 2, "A -> B message count"); + assert_eq!(res.bob_to_alice.len(), 2, "B -> A message count"); + + // With Limit: just /alice + let limit = ("/alice", "/b").into(); + let res = sync(Some(limit), &alice_set, &bob_set); + assert_eq!(res.alice_to_bob.len(), 1, "A -> B message count"); + assert_eq!(res.bob_to_alice.len(), 1, "B -> A message count"); + } + + #[test] + fn test_prefixes_empty_alice() { + let alice_set = []; + let bob_set = [("/foo/bar", 1), ("/alice/bar", 1), ("/alice/baz", 1)]; + + // No Limit + let res = sync(None, &alice_set, &bob_set); + assert_eq!(res.alice_to_bob.len(), 1, "A -> B message count"); + assert_eq!(res.bob_to_alice.len(), 1, "B -> A message count"); + + // With Limit: just /alice + let limit = ("/alice", "/b").into(); + let res = sync(Some(limit), &alice_set, &bob_set); + assert_eq!(res.alice_to_bob.len(), 1, "A -> B message count"); + assert_eq!(res.bob_to_alice.len(), 1, "B -> A message count"); + } + + #[test] + fn test_prefixes_empty_bob() { + let alice_set = [("/foo/bar", 1), ("/foo/baz", 1), ("/foo/cat", 1)]; + let bob_set = []; + + // No Limit + let res = sync(None, &alice_set, &bob_set); + assert_eq!(res.alice_to_bob.len(), 2, "A -> B message count"); + assert_eq!(res.bob_to_alice.len(), 1, "B -> A message count"); + + // With Limit: just /alice + let limit = ("/alice", "/b").into(); + let res = sync(Some(limit), &alice_set, &bob_set); + assert_eq!(res.alice_to_bob.len(), 1, "A -> B message count"); + assert_eq!(res.bob_to_alice.len(), 0, "B -> A message count"); + } + + #[test] + fn test_multikey() { + #[derive(Default, Clone, PartialEq, Eq, PartialOrd, Ord)] + struct Multikey { + author: [u8; 4], + key: Vec, + } + + impl RangeKey for Multikey { + fn contains(&self, range: &Range) -> bool { + let author = range.x().author.cmp(&range.y().author); + let key = range.x().key.cmp(&range.y().key); + + match (author, key) { + (Ordering::Equal, Ordering::Equal) => { + // All + true + } + (Ordering::Equal, Ordering::Less) => { + // Regular, based on key + range.x().key <= self.key && self.key < range.y().key + } + (Ordering::Equal, Ordering::Greater) => { + // Reverse, based on key + range.x().key <= self.key || self.key < range.y().key + } + (Ordering::Less, Ordering::Equal) => { + // Regular, based on author + range.x().author <= self.author && self.author < range.y().author + } + (Ordering::Greater, Ordering::Equal) => { + // Reverse, based on key + range.x().author <= self.author || self.author < range.y().author + } + (Ordering::Less, Ordering::Less) => { + // Regular, key and author + range.x().key <= self.key + && self.key < range.y().key + && range.x().author <= self.author + && self.author < range.y().author + } + (Ordering::Greater, Ordering::Greater) => { + // Reverse, key and author + (range.x().key <= self.key || self.key < range.y().key) + && (range.x().author <= self.author || self.author < range.y().author) + } + (Ordering::Less, Ordering::Greater) => { + // Regular author, Reverse key + (range.x().key <= self.key || self.key < range.y().key) + && (range.x().author <= self.author && self.author < range.y().author) + } + (Ordering::Greater, Ordering::Less) => { + // Regular key, Reverse author + (range.x().key <= self.key && self.key < range.y().key) + && (range.x().author <= self.author || self.author < range.y().author) + } + } + } + } + + impl Debug for Multikey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let key = if let Ok(key) = std::str::from_utf8(&self.key) { + key.to_string() + } else { + hex::encode(&self.key) + }; + f.debug_struct("Multikey") + .field("author", &hex::encode(self.author)) + .field("key", &key) + .finish() + } + } + impl AsFingerprint for Multikey { + fn as_fingerprint(&self) -> Fingerprint { + let mut hasher = blake3::Hasher::new(); + hasher.update(&self.author); + hasher.update(&self.key); + Fingerprint(hasher.finalize().into()) + } + } + + impl Multikey { + fn new(author: [u8; 4], key: impl AsRef<[u8]>) -> Self { + Multikey { + author, + key: key.as_ref().to_vec(), + } + } + } + let author_a = [1u8; 4]; + let author_b = [2u8; 4]; + let alice_set = [ + (Multikey::new(author_a, "ape"), 1), + (Multikey::new(author_a, "bee"), 1), + (Multikey::new(author_b, "bee"), 1), + (Multikey::new(author_a, "doe"), 1), + ]; + let bob_set = [ + (Multikey::new(author_a, "ape"), 1), + (Multikey::new(author_a, "bee"), 1), + (Multikey::new(author_a, "cat"), 1), + (Multikey::new(author_b, "cat"), 1), + ]; + + // No limit + let res = sync(None, &alice_set, &bob_set); + assert_eq!(res.alice_to_bob.len(), 2, "A -> B message count"); + assert_eq!(res.bob_to_alice.len(), 2, "B -> A message count"); + res.assert_alice_set( + "no limit", + &[ + (Multikey::new(author_a, "ape"), 1), + (Multikey::new(author_a, "bee"), 1), + (Multikey::new(author_b, "bee"), 1), + (Multikey::new(author_a, "doe"), 1), + (Multikey::new(author_a, "cat"), 1), + (Multikey::new(author_b, "cat"), 1), + ], + ); + + res.assert_bob_set( + "no limit", + &[ + (Multikey::new(author_a, "ape"), 1), + (Multikey::new(author_a, "bee"), 1), + (Multikey::new(author_b, "bee"), 1), + (Multikey::new(author_a, "doe"), 1), + (Multikey::new(author_a, "cat"), 1), + (Multikey::new(author_b, "cat"), 1), + ], + ); + + // Only author_a + let limit = Range::new(Multikey::new(author_a, ""), Multikey::new(author_b, "")); + let res = sync(Some(limit), &alice_set, &bob_set); + assert_eq!(res.alice_to_bob.len(), 2, "A -> B message count"); + assert_eq!(res.bob_to_alice.len(), 1, "B -> A message count"); + res.assert_alice_set( + "only author_a", + &[ + (Multikey::new(author_a, "ape"), 1), + (Multikey::new(author_a, "bee"), 1), + (Multikey::new(author_b, "bee"), 1), + (Multikey::new(author_a, "doe"), 1), + (Multikey::new(author_a, "cat"), 1), + ], + ); + + res.assert_bob_set( + "only author_a", + &[ + (Multikey::new(author_a, "ape"), 1), + (Multikey::new(author_a, "bee"), 1), + (Multikey::new(author_a, "cat"), 1), + (Multikey::new(author_b, "cat"), 1), + (Multikey::new(author_a, "doe"), 1), + ], + ); + + // All authors, but only cat + let limit = Range::new( + Multikey::new(author_a, "cat"), + Multikey::new(author_a, "doe"), + ); + let res = sync(Some(limit), &alice_set, &bob_set); + assert_eq!(res.alice_to_bob.len(), 1, "A -> B message count"); + assert_eq!(res.bob_to_alice.len(), 1, "B -> A message count"); + + res.assert_alice_set( + "only cat", + &[ + (Multikey::new(author_a, "ape"), 1), + (Multikey::new(author_a, "bee"), 1), + (Multikey::new(author_b, "bee"), 1), + (Multikey::new(author_a, "doe"), 1), + (Multikey::new(author_a, "cat"), 1), + (Multikey::new(author_b, "cat"), 1), + ], + ); + + res.assert_bob_set( + "only cat", + &[ + (Multikey::new(author_a, "ape"), 1), + (Multikey::new(author_a, "bee"), 1), + (Multikey::new(author_a, "cat"), 1), + (Multikey::new(author_b, "cat"), 1), + ], + ); + } + + struct SyncResult + where + K: RangeKey + Clone + Default + AsFingerprint, + V: Clone, + { + alice: Peer, + bob: Peer, + alice_to_bob: Vec>, + bob_to_alice: Vec>, + } + + impl SyncResult + where + K: RangeKey + Clone + Default + AsFingerprint + Debug, + V: Clone + Debug, + { + fn print_messages(&self) { + let len = std::cmp::max(self.alice_to_bob.len(), self.bob_to_alice.len()); + for i in 0..len { + if let Some(msg) = self.alice_to_bob.get(i) { + println!("A -> B:"); + print_message(msg); + } + if let Some(msg) = self.bob_to_alice.get(i) { + println!("B -> A:"); + print_message(msg); + } + } + } + } + + impl SyncResult + where + K: Debug + RangeKey + Clone + Default + AsFingerprint, + V: Debug + Clone + PartialEq, + { + fn assert_alice_set(&self, ctx: &str, expected: &[(K, V)]) { + dbg!(self.alice.all().unwrap().collect::>()); + for (k, v) in expected { + assert_eq!( + self.alice.store.get(k).unwrap().as_ref(), + Some(v), + "{}: (alice) missing key {:?}", + ctx, + k + ); + } + assert_eq!( + expected.len(), + self.alice.store.len().unwrap(), + "{}: (alice)", + ctx + ); + } + + fn assert_bob_set(&self, ctx: &str, expected: &[(K, V)]) { + dbg!(self.bob.all().unwrap().collect::>()); + + for (k, v) in expected { + assert_eq!( + self.bob.store.get(k).unwrap().as_ref(), + Some(v), + "{}: (bob) missing key {:?}", + ctx, + k + ); + } + assert_eq!( + expected.len(), + self.bob.store.len().unwrap(), + "{}: (bob)", + ctx + ); + } + } + + fn print_message(msg: &Message) + where + K: Debug, + V: Debug, + { + for part in &msg.parts { + match part { + MessagePart::RangeFingerprint(RangeFingerprint { range, fingerprint }) => { + println!( + " RangeFingerprint({:?}, {:?}, {:?})", + range.x(), + range.y(), + fingerprint + ); + } + MessagePart::RangeItem(RangeItem { + range, + values, + have_local, + }) => { + println!( + " RangeItem({:?} | {:?}) (local?: {})\n {:?}", + range.x(), + range.y(), + have_local, + values, + ); + } + } + } + } + + fn sync( + limit: Option>, + alice_set: &[(K, V)], + bob_set: &[(K, V)], + ) -> SyncResult + where + K: PartialEq + RangeKey + Clone + Default + Debug + AsFingerprint, + V: Clone + Debug + PartialEq, + { + println!("Using Limit: {:?}", limit); + let mut expected_set_alice = BTreeMap::new(); + let mut expected_set_bob = BTreeMap::new(); + + let mut alice = if let Some(limit) = limit.clone() { + Peer::::with_limit(limit) + } else { + Peer::::default() + }; + for (k, v) in alice_set { + alice.put(k.clone(), v.clone()).unwrap(); + + let include = if let Some(ref limit) = limit { + k.contains(limit) + } else { + true + }; + if include { + expected_set_bob.insert(k.clone(), v.clone()); + } + // alices things are always in alices store + expected_set_alice.insert(k.clone(), v.clone()); + } + + let mut bob = if let Some(limit) = limit.clone() { + Peer::::with_limit(limit) + } else { + Peer::::default() + }; + for (k, v) in bob_set { + bob.put(k.clone(), v.clone()).unwrap(); + let include = if let Some(ref limit) = limit { + k.contains(limit) + } else { + true + }; + if include { + expected_set_alice.insert(k.clone(), v.clone()); + } + // bobs things are always in bobs store + expected_set_bob.insert(k.clone(), v.clone()); + } + + let mut alice_to_bob = Vec::new(); + let mut bob_to_alice = Vec::new(); + let initial_message = alice.initial_message().unwrap(); + + let mut next_to_bob = Some(initial_message); + let mut rounds = 0; + while let Some(msg) = next_to_bob.take() { + assert!(rounds < 100, "too many rounds"); + rounds += 1; + alice_to_bob.push(msg.clone()); + + if let Some(msg) = bob.process_message(msg, |_, _| {}).unwrap() { + bob_to_alice.push(msg.clone()); + next_to_bob = alice.process_message(msg, |_, _| {}).unwrap(); + } + } + let res = SyncResult { + alice, + bob, + alice_to_bob, + bob_to_alice, + }; + res.print_messages(); + + let alice_now: Vec<_> = res.alice.all().unwrap().collect::>().unwrap(); + assert_eq!( + expected_set_alice.into_iter().collect::>(), + alice_now, + "alice" + ); + + let bob_now: Vec<_> = res.bob.all().unwrap().collect::>().unwrap(); + assert_eq!( + expected_set_bob.into_iter().collect::>(), + bob_now, + "bob" + ); + + // Check that values were never sent twice + let mut alice_sent = BTreeMap::new(); + for msg in &res.alice_to_bob { + for part in &msg.parts { + if let Some(values) = part.values() { + for (key, value) in values { + assert!( + alice_sent.insert(key.clone(), value.clone()).is_none(), + "alice: duplicate {:?} - {:?}", + key, + value + ); + } + } + } + } + + let mut bob_sent = BTreeMap::new(); + for msg in &res.bob_to_alice { + for part in &msg.parts { + if let Some(values) = part.values() { + for (key, value) in values { + assert!( + bob_sent.insert(key.clone(), value.clone()).is_none(), + "bob: duplicate {:?} - {:?}", + key, + value + ); + } + } + } + } + + res + } + + #[test] + fn store_get_range() { + let mut store = SimpleStore::<&'static str, usize>::default(); + let set = [ + ("bee", 1), + ("cat", 1), + ("doe", 1), + ("eel", 1), + ("fox", 1), + ("hog", 1), + ]; + for (k, v) in &set { + store.put(*k, *v).unwrap(); + } + + let all: Vec<_> = store + .get_range(Range::new("", ""), None) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!(&all, &set[..]); + + let regular: Vec<_> = store + .get_range(("bee", "eel").into(), None) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!(®ular, &set[..3]); + + // empty start + let regular: Vec<_> = store + .get_range(("", "eel").into(), None) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!(®ular, &set[..3]); + + let regular: Vec<_> = store + .get_range(("cat", "hog").into(), None) + .unwrap() + .collect::>() + .unwrap(); + + assert_eq!(®ular, &set[1..5]); + + let excluded: Vec<_> = store + .get_range(("fox", "bee").into(), None) + .unwrap() + .collect::>() + .unwrap(); + + assert_eq!(excluded[0].0, "fox"); + assert_eq!(excluded[1].0, "hog"); + assert_eq!(excluded.len(), 2); + + let excluded: Vec<_> = store + .get_range(("fox", "doe").into(), None) + .unwrap() + .collect::>() + .unwrap(); + + assert_eq!(excluded.len(), 4); + assert_eq!(excluded[0].0, "bee"); + assert_eq!(excluded[1].0, "cat"); + assert_eq!(excluded[2].0, "fox"); + assert_eq!(excluded[3].0, "hog"); + + // Limit + let all: Vec<_> = store + .get_range(("", "").into(), Some(("bee", "doe").into())) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!(&all, &set[..2]); + } + + #[test] + fn test_div_ceil() { + assert_eq!(div_ceil(1, 1), 1); + assert_eq!(div_ceil(2, 1), 2); + assert_eq!(div_ceil(4, 2), 4 / 2); + + assert_eq!(div_ceil(3, 2), 2); + assert_eq!(div_ceil(5, 3), 2); + } +} diff --git a/iroh-sync/src/store.rs b/iroh-sync/src/store.rs new file mode 100644 index 0000000000..888a8574b0 --- /dev/null +++ b/iroh-sync/src/store.rs @@ -0,0 +1,150 @@ +//! Storage trait and implementation for iroh-sync documents + +use anyhow::Result; +use rand_core::CryptoRngCore; +use serde::{Deserialize, Serialize}; + +use crate::{ + ranger, + sync::{Author, AuthorId, Namespace, NamespaceId, RecordIdentifier, Replica, SignedEntry}, +}; + +#[cfg(feature = "fs-store")] +pub mod fs; +pub mod memory; + +/// Abstraction over the different available storage solutions. +pub trait Store: std::fmt::Debug + Clone + Send + Sync + 'static { + /// The specialized instance scoped to a `Namespace`. + type Instance: ranger::Store + Send + Sync + 'static + Clone; + + /// Iterator over entries in the store, returned from [`Self::get`] + type GetIter<'a>: Iterator> + where + Self: 'a; + + /// Iterator over replica namespaces in the store, returned from [`Self::list_namespaces`] + type NamespaceIter<'a>: Iterator> + where + Self: 'a; + + /// Iterator over authors in the store, returned from [`Self::list_authors`] + type AuthorsIter<'a>: Iterator> + where + Self: 'a; + + /// Create a new replica for `namespace` and persist in this store. + fn new_replica(&self, namespace: Namespace) -> Result>; + + /// List all replica namespaces in this store. + fn list_namespaces(&self) -> Result>; + + /// Open a replica from this store. + /// + /// Store implementers must ensure that only a single instance of [`Replica`] is created per + /// namespace. On subsequent calls, a clone of that singleton instance must be returned. + /// + // TODO: Add close_replica + fn open_replica(&self, namespace: &NamespaceId) -> Result>>; + + /// Create a new author key and persist it in the store. + fn new_author(&self, rng: &mut R) -> Result; + + /// List all author keys in this store. + fn list_authors(&self) -> Result>; + + /// Get an author key from the store. + fn get_author(&self, author: &AuthorId) -> Result>; + + /// Iterate over entries of a replica. + /// + /// The [`GetFilter`] has several methods of filtering the returned entries. + fn get(&self, namespace: NamespaceId, filter: GetFilter) -> Result>; + + /// Gets the single latest entry for the specified key and author. + fn get_latest_by_key_and_author( + &self, + namespace: NamespaceId, + author: AuthorId, + key: impl AsRef<[u8]>, + ) -> Result>; +} + +/// Filter a get query onto a namespace +#[derive(Debug, Serialize, Deserialize)] +pub struct GetFilter { + latest: bool, + author: Option, + key: KeyFilter, +} + +impl Default for GetFilter { + fn default() -> Self { + Self::latest() + } +} + +impl GetFilter { + /// Create a new get filter. + /// + /// When `latest` is `true`, it will iterate over the latest entries, otherwise it will + /// iterate over all entires. + pub fn new(latest: bool) -> Self { + GetFilter { + latest, + author: None, + key: KeyFilter::All, + } + } + + /// No filter, iterate over all entries. + pub fn all() -> Self { + Self::new(false) + } + + /// Only include the latest entries. + pub fn latest() -> Self { + Self::new(true) + } + + /// Set the key filter. + pub fn with_key_filter(mut self, key_filter: KeyFilter) -> Self { + self.key = key_filter; + self + } + + /// Filter by exact key match. + pub fn with_key(mut self, key: impl AsRef<[u8]>) -> Self { + self.key = KeyFilter::Key(key.as_ref().to_vec()); + self + } + + /// Filter by prefix key match. + pub fn with_prefix(mut self, prefix: impl AsRef<[u8]>) -> Self { + self.key = KeyFilter::Prefix(prefix.as_ref().to_vec()); + self + } + + /// Filter by author. + pub fn with_author(mut self, author: AuthorId) -> Self { + self.author = Some(author); + self + } + + /// Include not only latest entries but also all historical entries. + pub fn with_history(mut self) -> Self { + self.latest = false; + self + } +} + +/// Filter the keys in a namespace +#[derive(Debug, Serialize, Deserialize)] +pub enum KeyFilter { + /// No filter, list all entries + All, + /// Filter for entries starting with a prefix + Prefix(Vec), + /// Filter for exact key match + Key(Vec), +} diff --git a/iroh-sync/src/store/fs.rs b/iroh-sync/src/store/fs.rs new file mode 100644 index 0000000000..0e9e68c407 --- /dev/null +++ b/iroh-sync/src/store/fs.rs @@ -0,0 +1,857 @@ +//! On disk storage for replicas. + +use std::{collections::HashMap, path::Path, sync::Arc}; + +use anyhow::{bail, Result}; +use ouroboros::self_referencing; +use parking_lot::RwLock; +use rand_core::CryptoRngCore; +use redb::{ + AccessGuard, Database, MultimapRange, MultimapTableDefinition, MultimapValue, + ReadOnlyMultimapTable, ReadTransaction, ReadableMultimapTable, ReadableTable, TableDefinition, +}; + +use crate::{ + ranger::{AsFingerprint, Fingerprint, Range, RangeKey}, + store::Store as _, + sync::{ + Author, AuthorId, Entry, EntrySignature, Namespace, NamespaceId, Record, RecordIdentifier, + Replica, SignedEntry, + }, +}; + +use self::ouroboros_impl_range_all_iterator::BorrowedMutFields; + +/// Manages the replicas and authors for an instance. +#[derive(Debug, Clone)] +pub struct Store { + db: Arc, + replicas: Arc>>>, +} + +// Table Definitions + +// Authors +// Table +// Key: [u8; 32] # AuthorId +// Value: #[u8; 32] # Author +const AUTHORS_TABLE: TableDefinition<&[u8; 32], &[u8; 32]> = TableDefinition::new("authors-1"); + +// Namespaces +// Table +// Key: [u8; 32] # NamespaceId +// Value: #[u8; 32] # Namespace +const NAMESPACES_TABLE: TableDefinition<&[u8; 32], &[u8; 32]> = + TableDefinition::new("namespaces-1"); + +// Records +// Multimap +// Key: ([u8; 32], [u8; 32], Vec) # (NamespaceId, AuthorId, Key) +// Values: +// (u64, [u8; 32], [u8; 32], u64, [u8; 32]) +// # (timestamp, signature_namespace, signature_author, len, hash) + +type RecordsId<'a> = (&'a [u8; 32], &'a [u8; 32], &'a [u8]); +type RecordsValue<'a> = (u64, &'a [u8; 64], &'a [u8; 64], u64, &'a [u8; 32]); + +const RECORDS_TABLE: MultimapTableDefinition = + MultimapTableDefinition::new("records-1"); + +impl Store { + /// Create or open a store from a `path` to a database file. + /// + /// The file will be created if it does not exist, otherwise it will be opened. + pub fn new(path: impl AsRef) -> Result { + let db = Database::create(path)?; + + // Setup all tables + let write_tx = db.begin_write()?; + { + let _table = write_tx.open_multimap_table(RECORDS_TABLE)?; + let _table = write_tx.open_table(NAMESPACES_TABLE)?; + let _table = write_tx.open_table(AUTHORS_TABLE)?; + } + write_tx.commit()?; + + Ok(Store { + db: Arc::new(db), + replicas: Default::default(), + }) + } + + /// Stores a new namespace + fn insert_namespace(&self, namespace: Namespace) -> Result<()> { + let write_tx = self.db.begin_write()?; + { + let mut namespace_table = write_tx.open_table(NAMESPACES_TABLE)?; + namespace_table.insert(namespace.id().as_bytes(), &namespace.to_bytes())?; + } + write_tx.commit()?; + + Ok(()) + } + + fn insert_author(&self, author: Author) -> Result<()> { + let write_tx = self.db.begin_write()?; + { + let mut author_table = write_tx.open_table(AUTHORS_TABLE)?; + author_table.insert(author.id().as_bytes(), &author.to_bytes())?; + } + write_tx.commit()?; + + Ok(()) + } +} + +/// Iterator for entries in [`Store`] +// We use a struct with an inner enum to exclude the enum variants from the public API. +#[derive(Debug)] +pub struct GetIter<'s> { + inner: GetIterInner<'s>, +} + +#[derive(Debug)] +enum GetIterInner<'s> { + All(RangeAllIterator<'s>), + Latest(RangeLatestIterator<'s>), + Single(std::option::IntoIter>), +} + +impl<'s> Iterator for GetIter<'s> { + type Item = anyhow::Result; + + fn next(&mut self) -> Option { + match &mut self.inner { + GetIterInner::All(iter) => iter.next().map(|x| x.map(|(_id, entry)| entry)), + GetIterInner::Latest(iter) => iter.next().map(|x| x.map(|(_id, entry)| entry)), + GetIterInner::Single(iter) => iter.next(), + } + } +} + +impl super::Store for Store { + type Instance = StoreInstance; + type GetIter<'a> = GetIter<'a>; + type AuthorsIter<'a> = std::vec::IntoIter>; + type NamespaceIter<'a> = std::vec::IntoIter>; + + fn open_replica(&self, namespace_id: &NamespaceId) -> Result>> { + if let Some(replica) = self.replicas.read().get(namespace_id) { + return Ok(Some(replica.clone())); + } + + let read_tx = self.db.begin_read()?; + let namespace_table = read_tx.open_table(NAMESPACES_TABLE)?; + let Some(namespace) = namespace_table.get(namespace_id.as_bytes())? else { + return Ok(None); + }; + let namespace = Namespace::from_bytes(namespace.value()); + let replica = Replica::new(namespace, StoreInstance::new(*namespace_id, self.clone())); + self.replicas.write().insert(*namespace_id, replica.clone()); + Ok(Some(replica)) + } + + fn list_namespaces(&self) -> Result> { + // TODO: avoid collect + let read_tx = self.db.begin_read()?; + let namespace_table = read_tx.open_table(NAMESPACES_TABLE)?; + let namespaces: Vec<_> = namespace_table + .iter()? + .map(|res| match res { + Ok((_key, value)) => Ok(Namespace::from_bytes(value.value()).id()), + Err(err) => Err(err.into()), + }) + .collect(); + Ok(namespaces.into_iter()) + } + + fn get_author(&self, author_id: &AuthorId) -> Result> { + let read_tx = self.db.begin_read()?; + let author_table = read_tx.open_table(AUTHORS_TABLE)?; + let Some(author) = author_table.get(author_id.as_bytes())? else { + return Ok(None); + }; + + let author = Author::from_bytes(author.value()); + Ok(Some(author)) + } + + fn new_author(&self, rng: &mut R) -> Result { + let author = Author::new(rng); + self.insert_author(author.clone())?; + Ok(author) + } + + fn list_authors(&self) -> Result> { + // TODO: avoid collect + let read_tx = self.db.begin_read()?; + let authors_table = read_tx.open_table(AUTHORS_TABLE)?; + let authors: Vec<_> = authors_table + .iter()? + .map(|res| match res { + Ok((_key, value)) => Ok(Author::from_bytes(value.value())), + Err(err) => Err(err.into()), + }) + .collect(); + + Ok(authors.into_iter()) + } + + fn new_replica(&self, namespace: Namespace) -> Result> { + let id = namespace.id(); + self.insert_namespace(namespace.clone())?; + + let replica = Replica::new(namespace, StoreInstance::new(id, self.clone())); + + self.replicas.write().insert(id, replica.clone()); + Ok(replica) + } + + fn get(&self, namespace: NamespaceId, filter: super::GetFilter) -> Result> { + use super::KeyFilter::*; + let inner = match filter.latest { + false => match (filter.key, filter.author) { + (All, None) => GetIterInner::All(self.get_all(namespace)?), + (Prefix(prefix), None) => { + GetIterInner::All(self.get_all_by_prefix(namespace, &prefix)?) + } + (Key(key), None) => GetIterInner::All(self.get_all_by_key(namespace, key)?), + (Key(key), Some(author)) => { + GetIterInner::All(self.get_all_by_key_and_author(namespace, author, key)?) + } + (All, Some(_)) | (Prefix(_), Some(_)) => { + bail!("This filter combination is not yet supported") + } + }, + true => match (filter.key, filter.author) { + (All, None) => GetIterInner::Latest(self.get_latest(namespace)?), + (Prefix(prefix), None) => { + GetIterInner::Latest(self.get_latest_by_prefix(namespace, &prefix)?) + } + (Key(key), None) => GetIterInner::Latest(self.get_latest_by_key(namespace, key)?), + (Key(key), Some(author)) => GetIterInner::Single( + self.get_latest_by_key_and_author(namespace, author, key)? + .map(Ok) + .into_iter(), + ), + (All, Some(_)) | (Prefix(_), Some(_)) => { + bail!("This filter combination is not yet supported") + } + }, + }; + Ok(GetIter { inner }) + } + + fn get_latest_by_key_and_author( + &self, + namespace: NamespaceId, + author: AuthorId, + key: impl AsRef<[u8]>, + ) -> Result> { + let read_tx = self.db.begin_read()?; + let record_table = read_tx.open_multimap_table(RECORDS_TABLE)?; + + let db_key = (namespace.as_bytes(), author.as_bytes(), key.as_ref()); + let records = record_table.get(db_key)?; + let Some(record) = records.last() else { + return Ok(None); + }; + let record = record?; + let (timestamp, namespace_sig, author_sig, len, hash) = record.value(); + let record = Record::new(timestamp, len, hash.into()); + let id = RecordIdentifier::new(key, namespace, author); + let entry = Entry::new(id, record); + let entry_signature = EntrySignature::from_parts(namespace_sig, author_sig); + let signed_entry = SignedEntry::new(entry_signature, entry); + + Ok(Some(signed_entry)) + } +} + +impl Store { + fn get_latest_by_key( + &self, + namespace: NamespaceId, + key: impl AsRef<[u8]>, + ) -> Result> { + let start = (namespace.as_bytes(), &[0u8; 32], &[][..]); + let end = (namespace.as_bytes(), &[255u8; 32], &[][..]); + let iter = RangeLatestIterator::try_new( + self.db.begin_read()?, + |read_tx| { + read_tx + .open_multimap_table(RECORDS_TABLE) + .map_err(anyhow::Error::from) + }, + |record_table| record_table.range(start..=end).map_err(anyhow::Error::from), + None, + RangeFilter::Key(key.as_ref().to_vec()), + )?; + + Ok(iter) + } + + fn get_latest_by_prefix( + &self, + namespace: NamespaceId, + prefix: impl AsRef<[u8]>, + ) -> Result> { + let start = (namespace.as_bytes(), &[0u8; 32], &[][..]); + let end = (namespace.as_bytes(), &[255u8; 32], &[][..]); + let iter = RangeLatestIterator::try_new( + self.db.begin_read()?, + |read_tx| { + read_tx + .open_multimap_table(RECORDS_TABLE) + .map_err(anyhow::Error::from) + }, + |record_table| record_table.range(start..=end).map_err(anyhow::Error::from), + None, + RangeFilter::Prefix(prefix.as_ref().to_vec()), + )?; + + Ok(iter) + } + + fn get_latest(&self, namespace: NamespaceId) -> Result> { + let start = (namespace.as_bytes(), &[0u8; 32], &[][..]); + let end = (namespace.as_bytes(), &[255u8; 32], &[][..]); + let iter = RangeLatestIterator::try_new( + self.db.begin_read()?, + |read_tx| { + read_tx + .open_multimap_table(RECORDS_TABLE) + .map_err(anyhow::Error::from) + }, + |record_table| record_table.range(start..=end).map_err(anyhow::Error::from), + None, + RangeFilter::None, + )?; + + Ok(iter) + } + + fn get_all_by_key_and_author<'a, 'b: 'a>( + &'a self, + namespace: NamespaceId, + author: AuthorId, + key: impl AsRef<[u8]> + 'b, + ) -> Result> { + let start = (namespace.as_bytes(), author.as_bytes(), key.as_ref()); + let end = (namespace.as_bytes(), author.as_bytes(), key.as_ref()); + let iter = RangeAllIterator::try_new( + self.db.begin_read()?, + |read_tx| { + read_tx + .open_multimap_table(RECORDS_TABLE) + .map_err(anyhow::Error::from) + }, + |record_table| { + record_table + .range(start..=end) + .map_err(anyhow::Error::from) + .map(|v| (v, None)) + }, + RangeFilter::None, + )?; + + Ok(iter) + } + + fn get_all_by_key( + &self, + namespace: NamespaceId, + key: impl AsRef<[u8]>, + ) -> Result> { + let start = (namespace.as_bytes(), &[0u8; 32], &[][..]); + let end = (namespace.as_bytes(), &[255u8; 32], &[][..]); + let iter = RangeAllIterator::try_new( + self.db.begin_read()?, + |read_tx| { + read_tx + .open_multimap_table(RECORDS_TABLE) + .map_err(anyhow::Error::from) + }, + |record_table| { + record_table + .range(start..=end) + .map_err(anyhow::Error::from) + .map(|v| (v, None)) + }, + RangeFilter::Key(key.as_ref().to_vec()), + )?; + + Ok(iter) + } + + fn get_all_by_prefix( + &self, + namespace: NamespaceId, + prefix: impl AsRef<[u8]>, + ) -> Result> { + let start = (namespace.as_bytes(), &[0u8; 32], &[][..]); + let end = (namespace.as_bytes(), &[255u8; 32], &[][..]); + let iter = RangeAllIterator::try_new( + self.db.begin_read()?, + |read_tx| { + read_tx + .open_multimap_table(RECORDS_TABLE) + .map_err(anyhow::Error::from) + }, + |record_table| { + record_table + .range(start..=end) + .map_err(anyhow::Error::from) + .map(|v| (v, None)) + }, + RangeFilter::Prefix(prefix.as_ref().to_vec()), + )?; + + Ok(iter) + } + + fn get_all(&self, namespace: NamespaceId) -> Result> { + let start = (namespace.as_bytes(), &[0u8; 32], &[][..]); + let end = (namespace.as_bytes(), &[255u8; 32], &[][..]); + let iter = RangeAllIterator::try_new( + self.db.begin_read()?, + |read_tx| { + read_tx + .open_multimap_table(RECORDS_TABLE) + .map_err(anyhow::Error::from) + }, + |record_table| { + record_table + .range(start..=end) + .map_err(anyhow::Error::from) + .map(|v| (v, None)) + }, + RangeFilter::None, + )?; + + Ok(iter) + } +} + +/// [`Namespace`] specific wrapper around the [`Store`]. +#[derive(Debug, Clone)] +pub struct StoreInstance { + namespace: NamespaceId, + store: Store, +} + +impl StoreInstance { + fn new(namespace: NamespaceId, store: Store) -> Self { + StoreInstance { namespace, store } + } +} + +impl crate::ranger::Store for StoreInstance { + type Error = anyhow::Error; + + /// Get a the first key (or the default if none is available). + fn get_first(&self) -> Result { + let read_tx = self.store.db.begin_read()?; + let record_table = read_tx.open_multimap_table(RECORDS_TABLE)?; + + // TODO: verify this fetches all keys with this namespace + let start = (self.namespace.as_bytes(), &[0u8; 32], &[][..]); + let end = (self.namespace.as_bytes(), &[255u8; 32], &[][..]); + let mut records = record_table.range(start..=end)?; + + let Some(record) = records.next() else { + return Ok(RecordIdentifier::default()); + }; + let (compound_key, _) = record?; + let (namespace_id, author_id, key) = compound_key.value(); + + let id = RecordIdentifier::from_parts(key, namespace_id, author_id)?; + Ok(id) + } + + fn get(&self, id: &RecordIdentifier) -> Result> { + self.store + .get_latest_by_key_and_author(id.namespace(), id.author(), id.key()) + } + + fn len(&self) -> Result { + let read_tx = self.store.db.begin_read()?; + let record_table = read_tx.open_multimap_table(RECORDS_TABLE)?; + + // TODO: verify this fetches all keys with this namespace + let start = (self.namespace.as_bytes(), &[0u8; 32], &[][..]); + let end = (self.namespace.as_bytes(), &[255u8; 32], &[][..]); + let records = record_table.range(start..=end)?; + Ok(records.count()) + } + + fn is_empty(&self) -> Result { + Ok(self.len()? == 0) + } + + fn get_fingerprint( + &self, + range: &Range, + limit: Option<&Range>, + ) -> Result { + // TODO: optimize? + + let elements = self.get_range(range.clone(), limit.cloned())?; + let mut fp = Fingerprint::empty(); + for el in elements { + let el = el?; + fp ^= el.0.as_fingerprint(); + } + + Ok(fp) + } + + fn put(&mut self, k: RecordIdentifier, v: SignedEntry) -> Result<()> { + // TODO: propagate error/not insertion? + if v.verify().is_ok() { + let timestamp = v.entry().record().timestamp(); + // TODO: verify timestamp is "reasonable" + + let write_tx = self.store.db.begin_write()?; + { + let mut record_table = write_tx.open_multimap_table(RECORDS_TABLE)?; + let key = (k.namespace_bytes(), k.author_bytes(), k.key()); + let record = v.entry().record(); + let value = ( + timestamp, + &v.signature().namespace_signature().to_bytes(), + &v.signature().author_signature().to_bytes(), + record.content_len(), + record.content_hash().as_bytes(), + ); + record_table.insert(key, value)?; + } + write_tx.commit()?; + } + Ok(()) + } + + type RangeIterator<'a> = RangeLatestIterator<'a>; + fn get_range( + &self, + range: Range, + limit: Option>, + ) -> Result> { + // TODO: implement inverted range + let range_start = range.x(); + let range_end = range.y(); + + let start = ( + range_start.namespace_bytes(), + range_start.author_bytes(), + range_start.key(), + ); + let end = ( + range_end.namespace_bytes(), + range_end.author_bytes(), + range_end.key(), + ); + let iter = RangeLatestIterator::try_new( + self.store.db.begin_read()?, + |read_tx| { + read_tx + .open_multimap_table(RECORDS_TABLE) + .map_err(anyhow::Error::from) + }, + |record_table| record_table.range(start..=end).map_err(anyhow::Error::from), + limit, + RangeFilter::None, + )?; + + Ok(iter) + } + + fn remove(&mut self, k: &RecordIdentifier) -> Result> { + let write_tx = self.store.db.begin_write()?; + let res = { + let mut records_table = write_tx.open_multimap_table(RECORDS_TABLE)?; + let key = (k.namespace_bytes(), k.author_bytes(), k.key()); + let records = records_table.remove_all(key)?; + let mut res = Vec::new(); + for record in records.into_iter() { + let record = record?; + let (timestamp, namespace_sig, author_sig, len, hash) = record.value(); + let record = Record::new(timestamp, len, hash.into()); + let entry = Entry::new(k.clone(), record); + let entry_signature = EntrySignature::from_parts(namespace_sig, author_sig); + let signed_entry = SignedEntry::new(entry_signature, entry); + res.push(signed_entry); + } + res + }; + write_tx.commit()?; + Ok(res) + } + + type AllIterator<'a> = RangeLatestIterator<'a>; + + fn all(&self) -> Result> { + let start = (self.namespace.as_bytes(), &[0u8; 32], &[][..]); + let end = (self.namespace.as_bytes(), &[255u8; 32], &[][..]); + let iter = RangeLatestIterator::try_new( + self.store.db.begin_read()?, + |read_tx| { + read_tx + .open_multimap_table(RECORDS_TABLE) + .map_err(anyhow::Error::from) + }, + |record_table| record_table.range(start..=end).map_err(anyhow::Error::from), + None, + RangeFilter::None, + )?; + + Ok(iter) + } +} + +fn matches(limit: &Option>, x: &RecordIdentifier) -> bool { + limit.as_ref().map(|r| x.contains(r)).unwrap_or(true) +} + +#[self_referencing] +pub struct RangeLatestIterator<'a> { + read_tx: ReadTransaction<'a>, + #[borrows(read_tx)] + #[covariant] + record_table: ReadOnlyMultimapTable<'this, RecordsId<'static>, RecordsValue<'static>>, + #[covariant] + #[borrows(record_table)] + records: MultimapRange<'this, RecordsId<'static>, RecordsValue<'static>>, + limit: Option>, + filter: RangeFilter, +} + +impl std::fmt::Debug for RangeLatestIterator<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RangeLatestIterator") + .finish_non_exhaustive() + } +} + +impl Iterator for RangeLatestIterator<'_> { + type Item = Result<(RecordIdentifier, SignedEntry)>; + + fn next(&mut self) -> Option { + self.with_mut(|fields| { + for next in fields.records.by_ref() { + let next = match next { + Ok(next) => next, + Err(err) => return Some(Err(err.into())), + }; + + let (namespace, author, key) = next.0.value(); + let id = match RecordIdentifier::from_parts(key, namespace, author) { + Ok(id) => id, + Err(err) => return Some(Err(err)), + }; + if fields.filter.matches(&id) && matches(fields.limit, &id) { + let last = next.1.last(); + let value = match last? { + Ok(value) => value, + Err(err) => return Some(Err(err.into())), + }; + let (timestamp, namespace_sig, author_sig, len, hash) = value.value(); + let record = Record::new(timestamp, len, hash.into()); + let entry = Entry::new(id.clone(), record); + let entry_signature = EntrySignature::from_parts(namespace_sig, author_sig); + let signed_entry = SignedEntry::new(entry_signature, entry); + + return Some(Ok((id, signed_entry))); + } + } + None + }) + } +} + +#[self_referencing] +pub struct RangeAllIterator<'a> { + read_tx: ReadTransaction<'a>, + #[borrows(read_tx)] + #[covariant] + record_table: ReadOnlyMultimapTable<'this, RecordsId<'static>, RecordsValue<'static>>, + #[covariant] + #[borrows(record_table)] + records: ( + MultimapRange<'this, RecordsId<'static>, RecordsValue<'static>>, + Option<( + AccessGuard<'this, RecordsId<'static>>, + MultimapValue<'this, RecordsValue<'static>>, + RecordIdentifier, + )>, + ), + filter: RangeFilter, +} + +#[derive(Debug)] +enum RangeFilter { + None, + Prefix(Vec), + Key(Vec), +} + +impl RangeFilter { + fn matches(&self, id: &RecordIdentifier) -> bool { + match self { + RangeFilter::None => true, + RangeFilter::Prefix(ref prefix) => id.key().starts_with(prefix), + RangeFilter::Key(ref key) => id.key() == key, + } + } +} + +impl std::fmt::Debug for RangeAllIterator<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RangeAllIterator").finish_non_exhaustive() + } +} + +/// Advance the internal iterator to the next set of multimap values +fn next_iter(fields: &mut BorrowedMutFields) -> Result<()> { + for next_iter in fields.records.0.by_ref() { + let (id_guard, values_guard) = next_iter?; + let (namespace, author, key) = id_guard.value(); + let id = RecordIdentifier::from_parts(key, namespace, author)?; + if fields.filter.matches(&id) { + fields.records.1 = Some((id_guard, values_guard, id)); + return Ok(()); + } + } + Ok(()) +} + +impl Iterator for RangeAllIterator<'_> { + type Item = Result<(RecordIdentifier, SignedEntry)>; + + fn next(&mut self) -> Option { + self.with_mut(|mut fields| { + loop { + if fields.records.1.is_none() { + if let Err(err) = next_iter(&mut fields) { + return Some(Err(err)); + } + } + // If this is None, nothing is available anymore + let (_id_guard, values_guard, id) = fields.records.1.as_mut()?; + + match values_guard.next() { + Some(Ok(value)) => { + let (timestamp, namespace_sig, author_sig, len, hash) = value.value(); + let record = Record::new(timestamp, len, hash.into()); + let entry = Entry::new(id.clone(), record); + let entry_signature = EntrySignature::from_parts(namespace_sig, author_sig); + let signed_entry = SignedEntry::new(entry_signature, entry); + return Some(Ok((id.clone(), signed_entry))); + } + Some(Err(err)) => return Some(Err(err.into())), + None => { + // clear the current + fields.records.1 = None; + } + } + } + }) + } +} + +#[cfg(test)] +mod tests { + use crate::ranger::Store as _; + use crate::store::Store as _; + + use super::*; + + #[test] + fn test_basics() -> Result<()> { + let dbfile = tempfile::NamedTempFile::new()?; + let store = Store::new(dbfile.path())?; + + let author = store.new_author(&mut rand::thread_rng())?; + let namespace = Namespace::new(&mut rand::thread_rng()); + let replica = store.new_replica(namespace.clone())?; + + let replica_back = store.open_replica(&namespace.id())?.unwrap(); + assert_eq!( + replica.namespace().as_bytes(), + replica_back.namespace().as_bytes() + ); + + let author_back = store.get_author(&author.id())?.unwrap(); + assert_eq!(author.to_bytes(), author_back.to_bytes(),); + + let mut wrapper = StoreInstance::new(namespace.id(), store.clone()); + for i in 0..5 { + let id = RecordIdentifier::new(format!("hello-{i}"), namespace.id(), author.id()); + let entry = Entry::new( + id.clone(), + Record::from_data(format!("world-{i}"), namespace.id()), + ); + let entry = SignedEntry::from_entry(entry, &namespace, &author); + wrapper.put(id, entry)?; + } + + // all + let all: Vec<_> = wrapper.all()?.collect(); + assert_eq!(all.len(), 5); + + // add a second version + for i in 0..5 { + let id = RecordIdentifier::new(format!("hello-{i}"), namespace.id(), author.id()); + let entry = Entry::new( + id.clone(), + Record::from_data(format!("world-{i}-2"), namespace.id()), + ); + let entry = SignedEntry::from_entry(entry, &namespace, &author); + wrapper.put(id, entry)?; + } + + // get all + let entries = store.get_all(namespace.id())?.collect::>>()?; + assert_eq!(entries.len(), 10); + + // get all prefix + let entries = store + .get_all_by_prefix(namespace.id(), "hello-")? + .collect::>>()?; + assert_eq!(entries.len(), 10); + + // get latest + let entries = store + .get_latest(namespace.id())? + .collect::>>()?; + assert_eq!(entries.len(), 5); + + // get latest by prefix + let entries = store + .get_latest_by_prefix(namespace.id(), "hello-")? + .collect::>>()?; + assert_eq!(entries.len(), 5); + + // delete and get + for i in 0..5 { + let id = RecordIdentifier::new(format!("hello-{i}"), namespace.id(), author.id()); + let res = wrapper.get(&id)?; + assert!(res.is_some()); + let out = wrapper.remove(&id)?; + assert_eq!(out.len(), 2); + for val in out { + assert_eq!(val.entry().id(), &id); + } + let res = wrapper.get(&id)?; + assert!(res.is_none()); + } + + // get latest + let entries = store + .get_latest(namespace.id())? + .collect::>>()?; + assert_eq!(entries.len(), 0); + + Ok(()) + } +} diff --git a/iroh-sync/src/store/memory.rs b/iroh-sync/src/store/memory.rs new file mode 100644 index 0000000000..b909555151 --- /dev/null +++ b/iroh-sync/src/store/memory.rs @@ -0,0 +1,594 @@ +//! In memory storage for replicas. + +use std::{ + collections::{BTreeMap, HashMap}, + convert::Infallible, + sync::Arc, +}; + +use anyhow::{bail, Result}; +use parking_lot::{RwLock, RwLockReadGuard}; +use rand_core::CryptoRngCore; + +use crate::{ + ranger::{AsFingerprint, Fingerprint, Range, RangeKey}, + sync::{Author, AuthorId, Namespace, NamespaceId, RecordIdentifier, Replica, SignedEntry}, +}; + +/// Manages the replicas and authors for an instance. +#[derive(Debug, Clone, Default)] +pub struct Store { + replicas: Arc>>>, + authors: Arc>>, + /// Stores records by namespace -> identifier + timestamp + replica_records: Arc>, +} + +type ReplicaRecordsOwned = + HashMap>>; + +impl super::Store for Store { + type Instance = ReplicaStoreInstance; + type GetIter<'a> = GetIter<'a>; + type AuthorsIter<'a> = std::vec::IntoIter>; + type NamespaceIter<'a> = std::vec::IntoIter>; + + fn open_replica(&self, namespace: &NamespaceId) -> Result>> { + let replicas = &*self.replicas.read(); + Ok(replicas.get(namespace).cloned()) + } + + fn list_namespaces(&self) -> Result> { + // TODO: avoid collect? + Ok(self + .replicas + .read() + .keys() + .cloned() + .map(Ok) + .collect::>() + .into_iter()) + } + + fn get_author(&self, author: &AuthorId) -> Result> { + let authors = &*self.authors.read(); + Ok(authors.get(author).cloned()) + } + + fn new_author(&self, rng: &mut R) -> Result { + let author = Author::new(rng); + self.authors.write().insert(author.id(), author.clone()); + Ok(author) + } + + fn list_authors(&self) -> Result> { + // TODO: avoid collect? + Ok(self + .authors + .read() + .values() + .cloned() + .map(Ok) + .collect::>() + .into_iter()) + } + + fn new_replica(&self, namespace: Namespace) -> Result> { + let id = namespace.id(); + let replica = Replica::new(namespace, ReplicaStoreInstance::new(id, self.clone())); + self.replicas + .write() + .insert(replica.namespace(), replica.clone()); + Ok(replica) + } + + fn get(&self, namespace: NamespaceId, filter: super::GetFilter) -> Result> { + use super::KeyFilter::*; + let inner = match filter.latest { + false => match (filter.key, filter.author) { + (All, None) => GetIterInner::All(self.get_all(namespace)?), + (Prefix(prefix), None) => { + GetIterInner::All(self.get_all_by_prefix(namespace, &prefix)?) + } + (Key(key), None) => GetIterInner::All(self.get_all_by_key(namespace, key)?), + (Key(key), Some(author)) => { + GetIterInner::All(self.get_all_by_key_and_author(namespace, author, key)?) + } + (All, Some(_)) | (Prefix(_), Some(_)) => { + bail!("This filter combination is not yet supported") + } + }, + true => match (filter.key, filter.author) { + (All, None) => GetIterInner::Latest(self.get_latest(namespace)?), + (Prefix(prefix), None) => { + GetIterInner::Latest(self.get_latest_by_prefix(namespace, &prefix)?) + } + (Key(key), None) => GetIterInner::Latest(self.get_latest_by_key(namespace, key)?), + (Key(key), Some(author)) => GetIterInner::Single( + self.get_latest_by_key_and_author(namespace, author, key)? + .map(Ok) + .into_iter(), + ), + (All, Some(_)) | (Prefix(_), Some(_)) => { + bail!("This filter combination is not yet supported") + } + }, + }; + Ok(GetIter { inner }) + } + + fn get_latest_by_key_and_author( + &self, + namespace: NamespaceId, + author: AuthorId, + key: impl AsRef<[u8]>, + ) -> Result> { + let inner = self.replica_records.read(); + + let value = inner + .get(&namespace) + .and_then(|records| records.get(&RecordIdentifier::new(key, namespace, author))) + .and_then(|values| values.last_key_value()); + + Ok(value.map(|(_, v)| v.clone())) + } +} + +/// Iterator for entries in [`Store`] +// We use a struct with an inner enum to exclude the enum variants from the public API. +#[derive(Debug)] +pub struct GetIter<'s> { + inner: GetIterInner<'s>, +} + +#[derive(Debug)] +enum GetIterInner<'s> { + All(GetAllIter<'s>), + Latest(GetLatestIter<'s>), + Single(std::option::IntoIter>), +} + +impl<'s> Iterator for GetIter<'s> { + type Item = anyhow::Result; + + fn next(&mut self) -> Option { + match &mut self.inner { + GetIterInner::All(iter) => iter.next().map(|x| x.map(|(_id, entry)| entry)), + GetIterInner::Latest(iter) => iter.next().map(|x| x.map(|(_id, entry)| entry)), + GetIterInner::Single(iter) => iter.next(), + } + } +} + +impl Store { + fn get_latest_by_key( + &self, + namespace: NamespaceId, + key: impl AsRef<[u8]>, + ) -> Result> { + let records = self.replica_records.read(); + let key = key.as_ref().to_vec(); + let filter = GetFilter::Key { namespace, key }; + + Ok(GetLatestIter { + records, + filter, + index: 0, + }) + } + + fn get_latest_by_prefix( + &self, + namespace: NamespaceId, + prefix: impl AsRef<[u8]>, + ) -> Result> { + let records = self.replica_records.read(); + let prefix = prefix.as_ref().to_vec(); + let filter = GetFilter::Prefix { namespace, prefix }; + + Ok(GetLatestIter { + records, + filter, + index: 0, + }) + } + + fn get_latest(&self, namespace: NamespaceId) -> Result> { + let records = self.replica_records.read(); + let filter = GetFilter::All { namespace }; + + Ok(GetLatestIter { + records, + filter, + index: 0, + }) + } + + fn get_all_by_key_and_author<'a, 'b: 'a>( + &'a self, + namespace: NamespaceId, + author: AuthorId, + key: impl AsRef<[u8]> + 'b, + ) -> Result> { + let records = self.replica_records.read(); + let record_id = RecordIdentifier::new(key, namespace, author); + let filter = GetFilter::KeyAuthor(record_id); + + Ok(GetAllIter { + records, + filter, + index: 0, + }) + } + + fn get_all_by_key( + &self, + namespace: NamespaceId, + key: impl AsRef<[u8]>, + ) -> Result> { + let records = self.replica_records.read(); + let key = key.as_ref().to_vec(); + let filter = GetFilter::Key { namespace, key }; + + Ok(GetAllIter { + records, + filter, + index: 0, + }) + } + + fn get_all_by_prefix( + &self, + namespace: NamespaceId, + prefix: impl AsRef<[u8]>, + ) -> Result> { + let records = self.replica_records.read(); + let prefix = prefix.as_ref().to_vec(); + let filter = GetFilter::Prefix { namespace, prefix }; + + Ok(GetAllIter { + records, + filter, + index: 0, + }) + } + + fn get_all(&self, namespace: NamespaceId) -> Result> { + let records = self.replica_records.read(); + let filter = GetFilter::All { namespace }; + + Ok(GetAllIter { + records, + filter, + index: 0, + }) + } +} + +#[derive(Debug)] +enum GetFilter { + /// All entries. + All { namespace: NamespaceId }, + /// Filter by key and author. + KeyAuthor(RecordIdentifier), + /// Filter by key only. + Key { + namespace: NamespaceId, + key: Vec, + }, + /// Filter by prefix only. + Prefix { + namespace: NamespaceId, + prefix: Vec, + }, +} + +impl GetFilter { + fn namespace(&self) -> NamespaceId { + match self { + GetFilter::All { namespace } => *namespace, + GetFilter::KeyAuthor(ref r) => r.namespace(), + GetFilter::Key { namespace, .. } => *namespace, + GetFilter::Prefix { namespace, .. } => *namespace, + } + } +} + +#[derive(Debug)] +struct GetLatestIter<'a> { + records: ReplicaRecords<'a>, + filter: GetFilter, + /// Current iteration index. + index: usize, +} + +impl<'a> Iterator for GetLatestIter<'a> { + type Item = Result<(RecordIdentifier, SignedEntry)>; + + fn next(&mut self) -> Option { + let records = self.records.get(&self.filter.namespace())?; + let res = match self.filter { + GetFilter::All { namespace } => records + .iter() + .filter(|(k, _)| k.namespace() == namespace) + .filter_map(|(key, value)| { + value + .last_key_value() + .map(|(_, v)| (key.clone(), v.clone())) + }) + .nth(self.index)?, + GetFilter::KeyAuthor(ref record_id) => { + let values = records.get(record_id)?; + let (_, res) = values.iter().nth(self.index)?; + (record_id.clone(), res.clone()) + } + GetFilter::Key { namespace, ref key } => records + .iter() + .filter(|(k, _)| k.key() == key && k.namespace() == namespace) + .filter_map(|(key, value)| { + value + .last_key_value() + .map(|(_, v)| (key.clone(), v.clone())) + }) + .nth(self.index)?, + GetFilter::Prefix { + namespace, + ref prefix, + } => records + .iter() + .filter(|(k, _)| k.key().starts_with(prefix) && k.namespace() == namespace) + .filter_map(|(key, value)| { + value + .last_key_value() + .map(|(_, v)| (key.clone(), v.clone())) + }) + .nth(self.index)?, + }; + self.index += 1; + Some(Ok(res)) + } +} + +#[derive(Debug)] +struct GetAllIter<'a> { + records: ReplicaRecords<'a>, + filter: GetFilter, + /// Current iteration index. + index: usize, +} + +impl<'a> Iterator for GetAllIter<'a> { + type Item = Result<(RecordIdentifier, SignedEntry)>; + + fn next(&mut self) -> Option { + let records = self.records.get(&self.filter.namespace())?; + let res = match self.filter { + GetFilter::All { namespace } => records + .iter() + .filter(|(k, _)| k.namespace() == namespace) + .flat_map(|(key, value)| { + value.iter().map(|(_, value)| (key.clone(), value.clone())) + }) + .nth(self.index)?, + GetFilter::KeyAuthor(ref record_id) => { + let values = records.get(record_id)?; + let (_, value) = values.iter().nth(self.index)?; + (record_id.clone(), value.clone()) + } + GetFilter::Key { namespace, ref key } => records + .iter() + .filter(|(k, _)| k.key() == key && k.namespace() == namespace) + .flat_map(|(key, value)| { + value.iter().map(|(_, value)| (key.clone(), value.clone())) + }) + .nth(self.index)?, + GetFilter::Prefix { + namespace, + ref prefix, + } => records + .iter() + .filter(|(k, _)| k.key().starts_with(prefix) && k.namespace() == namespace) + .flat_map(|(key, value)| { + value.iter().map(|(_, value)| (key.clone(), value.clone())) + }) + .nth(self.index)?, + }; + self.index += 1; + Some(Ok(res)) + } +} + +/// Instance of a [`Store`] +#[derive(Debug, Clone)] +pub struct ReplicaStoreInstance { + namespace: NamespaceId, + store: Store, +} + +impl ReplicaStoreInstance { + fn new(namespace: NamespaceId, store: Store) -> Self { + ReplicaStoreInstance { namespace, store } + } + + fn with_records(&self, f: F) -> T + where + F: FnOnce(Option<&BTreeMap>>) -> T, + { + let guard = self.store.replica_records.read(); + let value = guard.get(&self.namespace); + f(value) + } + + fn with_records_mut(&self, f: F) -> T + where + F: FnOnce(Option<&mut BTreeMap>>) -> T, + { + let mut guard = self.store.replica_records.write(); + let value = guard.get_mut(&self.namespace); + f(value) + } + + fn with_records_mut_with_default(&self, f: F) -> T + where + F: FnOnce(&mut BTreeMap>) -> T, + { + let mut guard = self.store.replica_records.write(); + let value = guard.entry(self.namespace).or_default(); + f(value) + } + + fn records_iter(&self) -> RecordsIter<'_> { + RecordsIter { + namespace: self.namespace, + replica_records: self.store.replica_records.read(), + i: 0, + } + } +} + +type ReplicaRecords<'a> = RwLockReadGuard< + 'a, + HashMap>>, +>; + +#[derive(Debug)] +struct RecordsIter<'a> { + namespace: NamespaceId, + replica_records: ReplicaRecords<'a>, + i: usize, +} + +impl Iterator for RecordsIter<'_> { + type Item = (RecordIdentifier, BTreeMap); + + fn next(&mut self) -> Option { + let records = self.replica_records.get(&self.namespace)?; + let (key, value) = records.iter().nth(self.i)?; + self.i += 1; + Some((key.clone(), value.clone())) + } +} + +impl crate::ranger::Store for ReplicaStoreInstance { + type Error = Infallible; + + /// Get a the first key (or the default if none is available). + fn get_first(&self) -> Result { + Ok(self.with_records(|records| { + records + .and_then(|r| r.first_key_value().map(|(k, _)| k.clone())) + .unwrap_or_default() + })) + } + + fn get(&self, key: &RecordIdentifier) -> Result, Self::Error> { + Ok(self.with_records(|records| { + records + .and_then(|r| r.get(key)) + .and_then(|values| values.last_key_value()) + .map(|(_, v)| v.clone()) + })) + } + + fn len(&self) -> Result { + Ok(self.with_records(|records| records.map(|v| v.len()).unwrap_or_default())) + } + + fn is_empty(&self) -> Result { + Ok(self.len()? == 0) + } + + fn get_fingerprint( + &self, + range: &Range, + limit: Option<&Range>, + ) -> Result { + let elements = self.get_range(range.clone(), limit.cloned())?; + let mut fp = Fingerprint::empty(); + for el in elements { + let el = el?; + fp ^= el.0.as_fingerprint(); + } + + Ok(fp) + } + + fn put(&mut self, k: RecordIdentifier, v: SignedEntry) -> Result<(), Self::Error> { + // TODO: propagate error/not insertion? + if v.verify().is_ok() { + let timestamp = v.entry().record().timestamp(); + // TODO: verify timestamp is "reasonable" + + self.with_records_mut_with_default(|records| { + records.entry(k).or_default().insert(timestamp, v); + }); + } + Ok(()) + } + + type RangeIterator<'a> = RangeIterator<'a>; + + fn get_range( + &self, + range: Range, + limit: Option>, + ) -> Result, Self::Error> { + Ok(RangeIterator { + iter: self.records_iter(), + range: Some(range), + limit, + }) + } + + fn remove(&mut self, key: &RecordIdentifier) -> Result, Self::Error> { + let res = self.with_records_mut(|records| { + records + .and_then(|records| records.remove(key).map(|v| v.into_values().collect())) + .unwrap_or_default() + }); + Ok(res) + } + + type AllIterator<'a> = RangeIterator<'a>; + + fn all(&self) -> Result, Self::Error> { + Ok(RangeIterator { + iter: self.records_iter(), + range: None, + limit: None, + }) + } +} + +/// Range iterator for a [`ReplicaStoreInstance`] +#[derive(Debug)] +pub struct RangeIterator<'a> { + iter: RecordsIter<'a>, + range: Option>, + limit: Option>, +} + +impl RangeIterator<'_> { + fn matches(&self, x: &RecordIdentifier) -> bool { + let range = self.range.as_ref().map(|r| x.contains(r)).unwrap_or(true); + let limit = self.limit.as_ref().map(|r| x.contains(r)).unwrap_or(true); + range && limit + } +} + +impl Iterator for RangeIterator<'_> { + type Item = Result<(RecordIdentifier, SignedEntry), Infallible>; + + fn next(&mut self) -> Option { + let mut next = self.iter.next()?; + loop { + if self.matches(&next.0) { + let (k, mut values) = next; + let (_, v) = values.pop_last()?; + return Some(Ok((k, v))); + } + + next = self.iter.next()?; + } + } +} diff --git a/iroh-sync/src/sync.rs b/iroh-sync/src/sync.rs new file mode 100644 index 0000000000..2b1e28a6e5 --- /dev/null +++ b/iroh-sync/src/sync.rs @@ -0,0 +1,881 @@ +//! API for iroh-sync replicas + +// Names and concepts are roughly based on Willows design at the moment: +// +// https://hackmd.io/DTtck8QOQm6tZaQBBtTf7w +// +// This is going to change! + +use std::{fmt::Debug, sync::Arc, time::SystemTime}; + +#[cfg(feature = "metrics")] +use crate::metrics::Metrics; +#[cfg(feature = "metrics")] +use iroh_metrics::{inc, inc_by}; + +use parking_lot::{Mutex, RwLock}; + +use ed25519_dalek::{Signature, SignatureError}; +use iroh_bytes::Hash; +use serde::{Deserialize, Serialize}; + +use crate::ranger::{self, AsFingerprint, Fingerprint, Peer, RangeKey}; + +pub use crate::keys::*; + +/// Protocol message for the set reconciliation protocol. +/// +/// Can be serialized to bytes with [serde] to transfer between peers. +pub type ProtocolMessage = crate::ranger::Message; + +/// Byte represenation of a `PeerId` from `iroh-net`. +// TODO: PeerId is in iroh-net which iroh-sync doesn't depend on. Add iroh-common crate with `PeerId`. +pub type PeerIdBytes = [u8; 32]; + +/// Whether an entry was inserted locally or by a remote peer. +#[derive(Debug, Clone)] +pub enum InsertOrigin { + /// The entry was inserted locally. + Local, + /// The entry was received from the remote peer identified by [`PeerIdBytes`]. + Sync(PeerIdBytes), +} + +/// Local representation of a mutable, synchronizable key-value store. +#[derive(derive_more::Debug, Clone)] +pub struct Replica> { + inner: Arc>>, + on_insert_sender: flume::Sender<(InsertOrigin, SignedEntry)>, + #[allow(clippy::type_complexity)] + on_insert_receiver: Arc>>>, +} + +#[derive(derive_more::Debug)] +struct InnerReplica> { + namespace: Namespace, + peer: Peer, +} + +#[derive(Debug, Serialize, Deserialize)] +struct ReplicaData { + entries: Vec, + namespace: Namespace, +} + +impl> Replica { + /// Create a new replica. + // TODO: make read only replicas possible + pub fn new(namespace: Namespace, store: S) -> Self { + let (s, r) = flume::bounded(16); // TODO: should this be configurable? + Replica { + inner: Arc::new(RwLock::new(InnerReplica { + namespace, + peer: Peer::from_store(store), + })), + on_insert_sender: s, + on_insert_receiver: Arc::new(Mutex::new(Some(r))), + } + } + + /// Subscribe to insert events. + /// + /// Only one subscription can be active at a time. If a previous subscription was created, this + /// will return `None`. + // TODO: Allow to clear a previous subscription? + pub fn subscribe(&self) -> Option> { + self.on_insert_receiver.lock().take() + } + + /// Insert a new record at the given key. + /// + /// The entry will by signed by the provided `author`. + /// The `len` must be the byte length of the data identified by `hash`. + pub fn insert( + &self, + key: impl AsRef<[u8]>, + author: &Author, + hash: Hash, + len: u64, + ) -> Result<(), S::Error> { + let mut inner = self.inner.write(); + + let id = RecordIdentifier::new(key, inner.namespace.id(), author.id()); + let record = Record::from_hash(hash, len); + + // Store signed entries + let entry = Entry::new(id.clone(), record); + let signed_entry = entry.sign(&inner.namespace, author); + inner.peer.put(id, signed_entry.clone())?; + drop(inner); + + self.on_insert_sender + .send((InsertOrigin::Local, signed_entry)) + .ok(); + + #[cfg(feature = "metrics")] + { + inc!(Metrics, new_entries_local); + inc_by!(Metrics, new_entries_local_size, len); + } + + Ok(()) + } + + /// Hashes the given data and inserts it. + /// + /// This does not store the content, just the record of it. + /// Returns the calculated hash. + pub fn hash_and_insert( + &self, + key: impl AsRef<[u8]>, + author: &Author, + data: impl AsRef<[u8]>, + ) -> Result { + let len = data.as_ref().len() as u64; + let hash = Hash::new(data); + self.insert(key, author, hash, len)?; + Ok(hash) + } + + /// Get the identifier for an entry in this replica. + pub fn id(&self, key: impl AsRef<[u8]>, author: &Author) -> RecordIdentifier { + let inner = self.inner.read(); + RecordIdentifier::new(key, inner.namespace.id(), author.id()) + } + + /// Insert an entry into this replica which was received from a remote peer. + /// + /// This will verify both the namespace and author signatures of the entry, emit an `on_insert` + /// event, and insert the entry into the replica store. + pub fn insert_remote_entry( + &self, + entry: SignedEntry, + received_from: PeerIdBytes, + ) -> anyhow::Result<()> { + entry.verify()?; + let mut inner = self.inner.write(); + let id = entry.entry.id.clone(); + inner.peer.put(id, entry.clone()).map_err(Into::into)?; + drop(inner); + self.on_insert_sender + .send((InsertOrigin::Sync(received_from), entry.clone())) + .ok(); + + #[cfg(feature = "metrics")] + { + inc!(Metrics, new_entries_remote); + inc_by!(Metrics, new_entries_remote_size, entry.content_len()); + } + + Ok(()) + } + + /// Create the initial message for the set reconciliation flow with a remote peer. + pub fn sync_initial_message( + &self, + ) -> Result, S::Error> { + self.inner.read().peer.initial_message() + } + + /// Process a set reconciliation message from a remote peer. + /// + /// Returns the next message to be sent to the peer, if any. + pub fn sync_process_message( + &self, + message: crate::ranger::Message, + from_peer: PeerIdBytes, + ) -> Result>, S::Error> { + let reply = self + .inner + .write() + .peer + .process_message(message, |_key, entry| { + self.on_insert_sender + .send((InsertOrigin::Sync(from_peer), entry)) + .ok(); + })?; + + Ok(reply) + } + + /// Get the namespace identifier for this [`Replica`]. + pub fn namespace(&self) -> NamespaceId { + self.inner.read().namespace.id() + } + + /// Get the byte represenation of the [`Namespace`] key for this replica. + // TODO: Why return [u8; 32] and not `Namespace` here? + pub fn secret_key(&self) -> [u8; 32] { + self.inner.read().namespace.to_bytes() + } +} + +/// A signed entry. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SignedEntry { + signature: EntrySignature, + entry: Entry, +} + +impl SignedEntry { + pub(crate) fn new(signature: EntrySignature, entry: Entry) -> Self { + SignedEntry { signature, entry } + } + + /// Create a new signed entry by signing an entry with the `namespace` and `author`. + pub fn from_entry(entry: Entry, namespace: &Namespace, author: &Author) -> Self { + let signature = EntrySignature::from_entry(&entry, namespace, author); + SignedEntry { signature, entry } + } + + /// Verify the signatures on this entry. + pub fn verify(&self) -> Result<(), SignatureError> { + self.signature + .verify(&self.entry, &self.entry.id.namespace, &self.entry.id.author) + } + + /// Get the signature. + pub fn signature(&self) -> &EntrySignature { + &self.signature + } + + /// Get the [`Entry`]. + pub fn entry(&self) -> &Entry { + &self.entry + } + + /// Get the content [`struct@Hash`] of the entry. + pub fn content_hash(&self) -> &Hash { + self.entry().record().content_hash() + } + + /// Get the content length of the entry. + pub fn content_len(&self) -> u64 { + self.entry().record().content_len() + } + + /// Get the [`AuthorId`] of the entry. + pub fn author(&self) -> AuthorId { + self.entry().id().author() + } + + /// Get the key of the entry. + pub fn key(&self) -> &[u8] { + self.entry().id().key() + } +} + +/// Signature over an entry. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct EntrySignature { + author_signature: Signature, + namespace_signature: Signature, +} + +impl EntrySignature { + /// Create a new signature by signing an entry with the `namespace` and `author`. + pub fn from_entry(entry: &Entry, namespace: &Namespace, author: &Author) -> Self { + // TODO: this should probably include a namespace prefix + // namespace in the cryptographic sense. + let bytes = entry.to_vec(); + let namespace_signature = namespace.sign(&bytes); + let author_signature = author.sign(&bytes); + + EntrySignature { + author_signature, + namespace_signature, + } + } + + /// Verify that this signature was created by signing the `entry` with the + /// secret keys of the specified `author` and `namespace`. + pub fn verify( + &self, + entry: &Entry, + namespace: &NamespaceId, + author: &AuthorId, + ) -> Result<(), SignatureError> { + let bytes = entry.to_vec(); + namespace.verify(&bytes, &self.namespace_signature)?; + author.verify(&bytes, &self.author_signature)?; + + Ok(()) + } + + pub(crate) fn from_parts(namespace_sig: &[u8; 64], author_sig: &[u8; 64]) -> Self { + let namespace_signature = Signature::from_bytes(namespace_sig); + let author_signature = Signature::from_bytes(author_sig); + + EntrySignature { + author_signature, + namespace_signature, + } + } + + pub(crate) fn author_signature(&self) -> &Signature { + &self.author_signature + } + + pub(crate) fn namespace_signature(&self) -> &Signature { + &self.namespace_signature + } +} + +/// A single entry in a [`Replica`] +/// +/// An entry is identified by a key, its [`Author`], and the [`Replica`]'s +/// [`Namespace`]. Its value is the [32-byte BLAKE3 hash](iroh_bytes::Hash) +/// of the entry's content data, the size of this content data, and a timestamp. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Entry { + id: RecordIdentifier, + record: Record, +} + +impl Entry { + /// Create a new entry + pub fn new(id: RecordIdentifier, record: Record) -> Self { + Entry { id, record } + } + + /// Get the [`RecordIdentifier`] for this entry. + pub fn id(&self) -> &RecordIdentifier { + &self.id + } + + /// Get the [`NamespaceId`] of this entry. + pub fn namespace(&self) -> NamespaceId { + self.id.namespace() + } + + /// Get the [`Record`] contained in this entry. + pub fn record(&self) -> &Record { + &self.record + } + + /// Serialize this entry into its canonical byte representation used for signing. + pub fn into_vec(&self, out: &mut Vec) { + self.id.as_bytes(out); + self.record.as_bytes(out); + } + + /// Serialize this entry into a new vector with its canonical byte representation. + pub fn to_vec(&self) -> Vec { + let mut out = Vec::new(); + self.into_vec(&mut out); + out + } + + /// Sign this entry with a [`Namespace`] and [`Author`]. + pub fn sign(self, namespace: &Namespace, author: &Author) -> SignedEntry { + SignedEntry::from_entry(self, namespace, author) + } +} + +/// The indentifier of a record. +#[derive(Default, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct RecordIdentifier { + /// The key of the record. + key: Vec, + /// The [`NamespaceId`] of the namespace this record belongs to. + namespace: NamespaceId, + /// The [`AuthorId`] of the author that wrote this record. + author: AuthorId, +} + +impl AsFingerprint for RecordIdentifier { + fn as_fingerprint(&self) -> crate::ranger::Fingerprint { + let mut hasher = blake3::Hasher::new(); + hasher.update(self.namespace.as_bytes()); + hasher.update(self.author.as_bytes()); + hasher.update(&self.key); + Fingerprint(hasher.finalize().into()) + } +} + +impl RangeKey for RecordIdentifier { + fn contains(&self, range: &crate::ranger::Range) -> bool { + use crate::ranger::contains; + + let key_range = range.clone().map(|x, y| (x.key, y.key)); + let namespace_range = range.clone().map(|x, y| (x.namespace, y.namespace)); + let author_range = range.clone().map(|x, y| (x.author, y.author)); + + contains(&self.key, &key_range) + && contains(&self.namespace, &namespace_range) + && contains(&self.author, &author_range) + } +} + +impl RecordIdentifier { + /// Create a new [`RecordIdentifier`]. + pub fn new(key: impl AsRef<[u8]>, namespace: NamespaceId, author: AuthorId) -> Self { + RecordIdentifier { + key: key.as_ref().to_vec(), + namespace, + author, + } + } + + pub(crate) fn from_parts( + key: &[u8], + namespace: &[u8; 32], + author: &[u8; 32], + ) -> anyhow::Result { + Ok(RecordIdentifier { + key: key.to_vec(), + namespace: NamespaceId::from_bytes(namespace)?, + author: AuthorId::from_bytes(author)?, + }) + } + + /// Serialize this [`RecordIdentifier`] into a mutable byte array. + pub(crate) fn as_bytes(&self, out: &mut Vec) { + out.extend_from_slice(self.namespace.as_bytes()); + out.extend_from_slice(self.author.as_bytes()); + out.extend_from_slice(&self.key); + } + + /// Get the key of this record. + pub fn key(&self) -> &[u8] { + &self.key + } + + /// Get the [`NamespaceId`] of this record. + pub fn namespace(&self) -> NamespaceId { + self.namespace + } + + pub(crate) fn namespace_bytes(&self) -> &[u8; 32] { + self.namespace.as_bytes() + } + + /// Get the [`AuthorId`] of this record. + pub fn author(&self) -> AuthorId { + self.author + } + + pub(crate) fn author_bytes(&self) -> &[u8; 32] { + self.author.as_bytes() + } +} + +/// The data part of an entry in a [`Replica`]. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Record { + /// Record creation timestamp. Counted as micros since the Unix epoch. + timestamp: u64, + /// Length of the data referenced by `hash`. + len: u64, + /// Hash of the content data. + hash: Hash, +} + +impl Record { + /// Create a new record. + pub fn new(timestamp: u64, len: u64, hash: Hash) -> Self { + Record { + timestamp, + len, + hash, + } + } + + /// Get the timestamp of this record. + pub fn timestamp(&self) -> u64 { + self.timestamp + } + + /// Get the length of the data addressed by this record's content hash. + pub fn content_len(&self) -> u64 { + self.len + } + + /// Get the [`struct@Hash`] of the content data of this record. + pub fn content_hash(&self) -> &Hash { + &self.hash + } + + /// Create a new record with a timestamp of the current system date. + pub fn from_hash(hash: Hash, len: u64) -> Self { + let timestamp = SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .expect("time drift") + .as_micros() as u64; + Self::new(timestamp, len, hash) + } + + // TODO: remove + #[cfg(test)] + pub(crate) fn from_data(data: impl AsRef<[u8]>, namespace: NamespaceId) -> Self { + // Salted hash + // TODO: do we actually want this? + // TODO: this should probably use a namespace prefix if used + let mut hasher = blake3::Hasher::new(); + hasher.update(namespace.as_bytes()); + hasher.update(data.as_ref()); + let hash = hasher.finalize(); + Self::from_hash(hash.into(), data.as_ref().len() as u64) + } + + /// Serialize this record into a mutable byte array. + pub(crate) fn as_bytes(&self, out: &mut Vec) { + out.extend_from_slice(&self.timestamp.to_be_bytes()); + out.extend_from_slice(&self.len.to_be_bytes()); + out.extend_from_slice(self.hash.as_ref()); + } +} + +#[cfg(test)] +mod tests { + use anyhow::Result; + + use crate::{ + ranger::Range, + store::{self, GetFilter}, + }; + + use super::*; + + #[test] + fn test_basics_memory() -> Result<()> { + let store = store::memory::Store::default(); + test_basics(store)?; + + Ok(()) + } + + #[cfg(feature = "fs-store")] + #[test] + fn test_basics_fs() -> Result<()> { + let dbfile = tempfile::NamedTempFile::new()?; + let store = store::fs::Store::new(dbfile.path())?; + test_basics(store)?; + Ok(()) + } + + fn test_basics(store: S) -> Result<()> { + let mut rng = rand::thread_rng(); + let alice = Author::new(&mut rng); + let bob = Author::new(&mut rng); + let myspace = Namespace::new(&mut rng); + + let record_id = RecordIdentifier::new("/my/key", myspace.id(), alice.id()); + let record = Record::from_data(b"this is my cool data", myspace.id()); + let entry = Entry::new(record_id, record); + let signed_entry = entry.sign(&myspace, &alice); + signed_entry.verify().expect("failed to verify"); + + let my_replica = store.new_replica(myspace)?; + for i in 0..10 { + my_replica + .hash_and_insert(format!("/{i}"), &alice, format!("{i}: hello from alice")) + .map_err(Into::into)?; + } + + for i in 0..10 { + let res = store + .get_latest_by_key_and_author(my_replica.namespace(), alice.id(), format!("/{i}"))? + .unwrap(); + let len = format!("{i}: hello from alice").as_bytes().len() as u64; + assert_eq!(res.entry().record().content_len(), len); + res.verify()?; + } + + // Test multiple records for the same key + my_replica + .hash_and_insert("/cool/path", &alice, "round 1") + .map_err(Into::into)?; + let _entry = store + .get_latest_by_key_and_author(my_replica.namespace(), alice.id(), "/cool/path")? + .unwrap(); + // Second + my_replica + .hash_and_insert("/cool/path", &alice, "round 2") + .map_err(Into::into)?; + let _entry = store + .get_latest_by_key_and_author(my_replica.namespace(), alice.id(), "/cool/path")? + .unwrap(); + + // Get All by author + let entries: Vec<_> = store + .get( + my_replica.namespace(), + GetFilter::all() + .with_author(alice.id()) + .with_key("/cool/path"), + )? + .collect::>()?; + assert_eq!(entries.len(), 2); + + // Get All by key + let entries: Vec<_> = store + .get( + my_replica.namespace(), + GetFilter::all().with_key(b"/cool/path"), + )? + .collect::>()?; + assert_eq!(entries.len(), 2); + + // Get latest by key + let entries: Vec<_> = store + .get( + my_replica.namespace(), + GetFilter::latest().with_key(b"/cool/path"), + )? + .collect::>()?; + assert_eq!(entries.len(), 1); + + // Get latest by prefix + let entries: Vec<_> = store + .get( + my_replica.namespace(), + GetFilter::latest().with_prefix(b"/cool"), + )? + .collect::>()?; + assert_eq!(entries.len(), 1); + + // Get All + let entries: Vec<_> = store + .get(my_replica.namespace(), GetFilter::all())? + .collect::>()?; + assert_eq!(entries.len(), 12); + + // Get All latest + let entries: Vec<_> = store + .get(my_replica.namespace(), GetFilter::latest())? + .collect::>()?; + assert_eq!(entries.len(), 11); + + // insert record from different author + let _entry = my_replica + .hash_and_insert("/cool/path", &bob, "bob round 1") + .map_err(Into::into)?; + + // Get All by author + let entries: Vec<_> = store + .get( + my_replica.namespace(), + GetFilter::all() + .with_author(alice.id()) + .with_key("/cool/path"), + )? + .collect::>()?; + assert_eq!(entries.len(), 2); + + let entries: Vec<_> = store + .get( + my_replica.namespace(), + GetFilter::all() + .with_author(bob.id()) + .with_key("/cool/path"), + )? + .collect::>()?; + assert_eq!(entries.len(), 1); + + // Get All by key + let entries: Vec<_> = store + .get( + my_replica.namespace(), + GetFilter::all().with_key(b"/cool/path"), + )? + .collect::>()?; + assert_eq!(entries.len(), 3); + + // Get latest by key + let entries: Vec<_> = store + .get( + my_replica.namespace(), + GetFilter::latest().with_key(b"/cool/path"), + )? + .collect::>()?; + assert_eq!(entries.len(), 2); + + // Get latest by prefix + let entries: Vec<_> = store + .get( + my_replica.namespace(), + GetFilter::latest().with_prefix(b"/cool"), + )? + .collect::>()?; + assert_eq!(entries.len(), 2); + + // Get all by prefix + let entries: Vec<_> = store + .get( + my_replica.namespace(), + GetFilter::all().with_prefix(b"/cool"), + )? + .collect::>()?; + assert_eq!(entries.len(), 3); + + // Get All + let entries: Vec<_> = store + .get(my_replica.namespace(), GetFilter::all())? + .collect::>()?; + assert_eq!(entries.len(), 13); + + // Get All latest + let entries: Vec<_> = store + .get(my_replica.namespace(), GetFilter::latest())? + .collect::>()?; + assert_eq!(entries.len(), 12); + + Ok(()) + } + + #[test] + fn test_multikey() { + let mut rng = rand::thread_rng(); + + let k = ["a", "c", "z"]; + + let mut n: Vec<_> = (0..3).map(|_| Namespace::new(&mut rng)).collect(); + n.sort_by_key(|n| n.id()); + + let mut a: Vec<_> = (0..3).map(|_| Author::new(&mut rng)).collect(); + a.sort_by_key(|a| a.id()); + + // Just key + { + let ri0 = RecordIdentifier::new(k[0], n[0].id(), a[0].id()); + let ri1 = RecordIdentifier::new(k[1], n[0].id(), a[0].id()); + let ri2 = RecordIdentifier::new(k[2], n[0].id(), a[0].id()); + + let range = Range::new(ri0.clone(), ri2.clone()); + assert!(ri0.contains(&range), "start"); + assert!(ri1.contains(&range), "inside"); + assert!(!ri2.contains(&range), "end"); + } + + // Just namespace + { + let ri0 = RecordIdentifier::new(k[0], n[0].id(), a[0].id()); + let ri1 = RecordIdentifier::new(k[0], n[1].id(), a[0].id()); + let ri2 = RecordIdentifier::new(k[0], n[2].id(), a[0].id()); + + let range = Range::new(ri0.clone(), ri2.clone()); + assert!(ri0.contains(&range), "start"); + assert!(ri1.contains(&range), "inside"); + assert!(!ri2.contains(&range), "end"); + } + + // Just author + { + let ri0 = RecordIdentifier::new(k[0], n[0].id(), a[0].id()); + let ri1 = RecordIdentifier::new(k[0], n[0].id(), a[1].id()); + let ri2 = RecordIdentifier::new(k[0], n[0].id(), a[2].id()); + + let range = Range::new(ri0.clone(), ri2.clone()); + assert!(ri0.contains(&range), "start"); + assert!(ri1.contains(&range), "inside"); + assert!(!ri2.contains(&range), "end"); + } + + // Just key and namespace + { + let ri0 = RecordIdentifier::new(k[0], n[0].id(), a[0].id()); + let ri1 = RecordIdentifier::new(k[1], n[1].id(), a[0].id()); + let ri2 = RecordIdentifier::new(k[2], n[2].id(), a[0].id()); + + let range = Range::new(ri0.clone(), ri2.clone()); + assert!(ri0.contains(&range), "start"); + assert!(ri1.contains(&range), "inside"); + assert!(!ri2.contains(&range), "end"); + } + } + + #[test] + fn test_replica_sync_memory() -> Result<()> { + let alice_store = store::memory::Store::default(); + let bob_store = store::memory::Store::default(); + + test_replica_sync(alice_store, bob_store)?; + Ok(()) + } + + #[cfg(feature = "fs-store")] + #[test] + fn test_replica_sync_fs() -> Result<()> { + let alice_dbfile = tempfile::NamedTempFile::new()?; + let alice_store = store::fs::Store::new(alice_dbfile.path())?; + let bob_dbfile = tempfile::NamedTempFile::new()?; + let bob_store = store::fs::Store::new(bob_dbfile.path())?; + test_replica_sync(alice_store, bob_store)?; + + Ok(()) + } + + fn test_replica_sync(alice_store: S, bob_store: S) -> Result<()> { + let alice_set = ["ape", "eel", "fox", "gnu"]; + let bob_set = ["bee", "cat", "doe", "eel", "fox", "hog"]; + + let mut rng = rand::thread_rng(); + let author = Author::new(&mut rng); + let myspace = Namespace::new(&mut rng); + let alice = alice_store.new_replica(myspace.clone())?; + for el in &alice_set { + alice + .hash_and_insert(el, &author, el.as_bytes()) + .map_err(Into::into)?; + } + + let bob = bob_store.new_replica(myspace)?; + for el in &bob_set { + bob.hash_and_insert(el, &author, el.as_bytes()) + .map_err(Into::into)?; + } + + sync( + &author, + &alice, + &alice_store, + &bob, + &bob_store, + &alice_set, + &bob_set, + )?; + Ok(()) + } + + fn sync( + author: &Author, + alice: &Replica, + alice_store: &S, + bob: &Replica, + bob_store: &S, + alice_set: &[&str], + bob_set: &[&str], + ) -> Result<()> { + let alice_peer_id = [1u8; 32]; + let bob_peer_id = [2u8; 32]; + // Sync alice - bob + let mut next_to_bob = Some(alice.sync_initial_message().map_err(Into::into)?); + let mut rounds = 0; + while let Some(msg) = next_to_bob.take() { + assert!(rounds < 100, "too many rounds"); + rounds += 1; + println!("round {}", rounds); + if let Some(msg) = bob + .sync_process_message(msg, alice_peer_id) + .map_err(Into::into)? + { + next_to_bob = alice + .sync_process_message(msg, bob_peer_id) + .map_err(Into::into)?; + } + } + + // Check result + for el in alice_set { + alice_store.get_latest_by_key_and_author(alice.namespace(), author.id(), el)?; + bob_store.get_latest_by_key_and_author(bob.namespace(), author.id(), el)?; + } + + for el in bob_set { + alice_store.get_latest_by_key_and_author(alice.namespace(), author.id(), el)?; + bob_store.get_latest_by_key_and_author(bob.namespace(), author.id(), el)?; + } + Ok(()) + } +} diff --git a/iroh/Cargo.toml b/iroh/Cargo.toml index b3c7aefb46..e531004945 100644 --- a/iroh/Cargo.toml +++ b/iroh/Cargo.toml @@ -19,6 +19,7 @@ bytes = "1" derive_more = { version = "1.0.0-beta.1", features = ["debug", "display", "from", "try_into"] } flume = "0.10.14" futures = "0.3.25" +genawaiter = { version = "0.99", default-features = false, features = ["futures03"] } hex = { version = "0.4.3" } iroh-bytes = { version = "0.5.0", path = "../iroh-bytes" } iroh-io = { version = "0.2.2" } @@ -26,15 +27,20 @@ iroh-metrics = { version = "0.5.0", path = "../iroh-metrics", optional = true } iroh-net = { version = "0.5.1", path = "../iroh-net" } num_cpus = { version = "1.15.0" } portable-atomic = "1" +iroh-sync = { version = "0.5.1", path = "../iroh-sync" } +iroh-gossip = { version = "0.5.1", path = "../iroh-gossip" } +once_cell = "1.18.0" +parking_lot = "0.12.1" postcard = { version = "1", default-features = false, features = ["alloc", "use-std", "experimental-derive"] } quic-rpc = { version = "0.6", default-features = false, features = ["flume-transport"] } quinn = "0.10" +range-collections = { version = "0.4.0" } rand = "0.8" serde = { version = "1", features = ["derive"] } thiserror = "1" tokio = { version = "1", features = ["io-util", "rt"] } tokio-stream = "0.1" -tokio-util = { version = "0.7", features = ["io-util", "io"] } +tokio-util = { version = "0.7", features = ["codec", "io-util", "io"] } tracing = "0.1" walkdir = "2" @@ -50,6 +56,12 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"], optional = tr data-encoding = "2.4.0" url = { version = "2.4", features = ["serde"] } +# Examples +shell-words = { version = "1.1.0", optional = true } +shellexpand = { version = "3.1.0", optional = true } +rustyline = { version = "12.0.0", optional = true } +itertools = "0.11.0" + [features] default = ["cli", "metrics"] cli = ["clap", "config", "console", "dirs-next", "indicatif", "multibase", "quic-rpc/quinn-transport", "tempfile", "tokio/rt-multi-thread", "tracing-subscriber", "flat-db", "mem-db", "iroh-collection"] @@ -58,6 +70,7 @@ mem-db = [] flat-db = [] iroh-collection = [] test = [] +example-sync = ["cli", "shell-words", "shellexpand", "rustyline"] [dev-dependencies] anyhow = { version = "1", features = ["backtrace"] } @@ -66,9 +79,7 @@ duct = "0.13.6" genawaiter = { version = "0.99", features = ["futures03"] } iroh-test = { version = "0.5.1", path = "../iroh-test" } nix = "0.26.2" -postcard = "1" proptest = "1.2.0" -rand = "0.8" regex = { version = "1.7.1", features = ["std"] } tempfile = "3.4" testdir = "0.8" @@ -83,6 +94,14 @@ required-features = ["cli"] name = "collection" required-features = ["mem-db", "iroh-collection"] +[[example]] +name = "dump-blob-stream" +required-features = ["mem-db", "iroh-collection"] + [[example]] name = "hello-world" required-features = ["mem-db"] + +[[example]] +name = "sync" +required-features = ["example-sync"] diff --git a/iroh/examples/client.rs b/iroh/examples/client.rs new file mode 100644 index 0000000000..e72a67bfcf --- /dev/null +++ b/iroh/examples/client.rs @@ -0,0 +1,46 @@ +use indicatif::HumanBytes; +use iroh::node::Node; +use iroh_bytes::util::runtime; +use iroh_sync::{store::GetFilter, sync::SignedEntry}; +use tokio_stream::StreamExt; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + let rt = runtime::Handle::from_currrent(1)?; + let db = iroh::baomap::mem::Store::new(rt.clone()); + let store = iroh_sync::store::memory::Store::default(); + let node = Node::builder(db.clone(), store) + .runtime(&rt) + .spawn() + .await?; + let client = node.client(); + let doc = client.create_doc().await?; + let author = client.create_author().await?; + let key = b"hello".to_vec(); + let value = b"world".to_vec(); + doc.set_bytes(author, key.clone(), value).await?; + let mut stream = doc.get(GetFilter::latest()).await?; + while let Some(entry) = stream.try_next().await? { + println!("entry {}", fmt_entry(&entry)); + let content = doc.get_content_bytes(&entry).await?; + println!(" content {}", String::from_utf8(content.to_vec())?) + } + + Ok(()) +} + +fn fmt_entry(entry: &SignedEntry) -> String { + let id = entry.entry().id(); + let key = std::str::from_utf8(id.key()).unwrap_or(""); + let author = fmt_hash(id.author().as_bytes()); + let hash = entry.entry().record().content_hash(); + let hash = fmt_hash(hash.as_bytes()); + let len = HumanBytes(entry.entry().record().content_len()); + format!("@{author}: {key} = {hash} ({len})",) +} + +fn fmt_hash(hash: impl AsRef<[u8]>) -> String { + let mut text = data_encoding::BASE32_NOPAD.encode(&hash.as_ref()[..5]); + text.make_ascii_lowercase(); + format!("{}…", &text) +} diff --git a/iroh/examples/collection.rs b/iroh/examples/collection.rs index 51df19fcbf..353bab8904 100644 --- a/iroh/examples/collection.rs +++ b/iroh/examples/collection.rs @@ -41,9 +41,12 @@ async fn main() -> anyhow::Result<()> { // create a new iroh runtime with 1 worker thread, reusing the existing tokio runtime let rt = runtime::Handle::from_currrent(1)?; + // create an in-memory doc store for iroh sync (not used here) + let doc_store = iroh_sync::store::memory::Store::default(); + // create a new node // we must configure the iroh collection parser so the node understands iroh collections - let node = iroh::node::Node::builder(db) + let node = iroh::node::Node::builder(db, doc_store) .collection_parser(IrohCollectionParser) .runtime(&rt) .spawn() diff --git a/iroh/examples/hello-world.rs b/iroh/examples/hello-world.rs index 93ed838260..508569c643 100644 --- a/iroh/examples/hello-world.rs +++ b/iroh/examples/hello-world.rs @@ -22,12 +22,17 @@ async fn main() -> anyhow::Result<()> { setup_logging(); // create a new, empty in memory database let mut db = iroh::baomap::readonly_mem::Store::default(); + // create an in-memory doc store (not used in the example) + let doc_store = iroh_sync::store::memory::Store::default(); // create a new iroh runtime with 1 worker thread, reusing the existing tokio runtime let rt = runtime::Handle::from_currrent(1)?; // add some data and remember the hash let hash = db.insert(b"Hello, world!"); // create a new node - let node = iroh::node::Node::builder(db).runtime(&rt).spawn().await?; + let node = iroh::node::Node::builder(db, doc_store) + .runtime(&rt) + .spawn() + .await?; // create a ticket let ticket = node.ticket(hash).await?.with_recursive(false); // print some info about the node diff --git a/iroh/examples/rpc.rs b/iroh/examples/rpc.rs index 3c8f4dccd4..1f8a2ca80b 100644 --- a/iroh/examples/rpc.rs +++ b/iroh/examples/rpc.rs @@ -47,7 +47,8 @@ async fn run(db: impl Store) -> anyhow::Result<()> { // create a new node // we must configure the iroh collection parser so the node understands iroh collections - let node = iroh::node::Node::builder(db) + let doc_store = iroh_sync::store::memory::Store::default(); + let node = iroh::node::Node::builder(db, doc_store) .secret_key(secret_key) .collection_parser(IrohCollectionParser) .runtime(&rt) diff --git a/iroh/examples/sync.rs b/iroh/examples/sync.rs new file mode 100644 index 0000000000..7e073b5271 --- /dev/null +++ b/iroh/examples/sync.rs @@ -0,0 +1,1043 @@ +//! Live edit a p2p document +//! +//! By default a new peer id is created when starting the example. To reuse your identity, +//! set the `--secret-key` CLI flag with the secret key printed on a previous invocation. +//! +//! You can use this with a local DERP server. To do so, run +//! `cargo run --bin derper -- --dev` +//! and then set the `-d http://localhost:3340` flag on this example. + +use std::{ + collections::HashSet, fmt, net::SocketAddr, path::PathBuf, str::FromStr, sync::Arc, + time::Instant, +}; + +use anyhow::{anyhow, bail}; +use bytes::Bytes; +use clap::{CommandFactory, FromArgMatches, Parser}; +use indicatif::HumanBytes; +use iroh::{ + download::Downloader, + sync_engine::{PeerSource, SyncEngine, SYNC_ALPN}, +}; +use iroh_bytes::util::runtime; +use iroh_bytes::{ + baomap::{ImportMode, Map, MapEntry, Store as BaoStore}, + util::progress::IgnoreProgressSender, +}; +use iroh_gossip::{ + net::{Gossip, GOSSIP_ALPN}, + proto::TopicId, +}; +use iroh_io::AsyncSliceReaderExt; +use iroh_net::{ + defaults::default_derp_map, derp::DerpMap, key::SecretKey, magic_endpoint::get_alpn, + MagicEndpoint, +}; +use iroh_sync::{ + store::{self, GetFilter, Store as _}, + sync::{Author, Entry, Namespace, Replica, SignedEntry}, +}; +use once_cell::sync::OnceCell; +use serde::{Deserialize, Serialize}; +use tokio::{ + io::AsyncWriteExt, + sync::{mpsc, oneshot}, + task::JoinHandle, +}; +use tracing::warn; +use tracing_subscriber::{EnvFilter, Registry}; +use url::Url; + +use iroh_bytes_handlers::IrohBytesHandlers; + +const MAX_DISPLAY_CONTENT_LEN: u64 = 1024 * 1024; + +type Doc = Replica<::Instance>; + +#[derive(Parser, Debug)] +struct Args { + /// Secret key for this node + #[clap(long)] + secret_key: Option, + /// Path to a data directory where blobs will be persisted + #[clap(short, long)] + storage_path: Option, + /// Set a custom DERP server. By default, the DERP server hosted by n0 will be used. + #[clap(short, long)] + derp: Option, + /// Disable DERP completeley + #[clap(long)] + no_derp: bool, + /// Set your nickname + #[clap(short, long)] + name: Option, + /// Set the bind port for our socket. By default, a random port will be used. + #[clap(short, long, default_value = "0")] + bind_port: u16, + /// Bind address on which to serve Prometheus metrics + #[clap(long)] + metrics_addr: Option, + #[clap(subcommand)] + command: Command, +} + +#[derive(Parser, Debug)] +enum Command { + Open { doc_name: String }, + Join { ticket: String }, +} + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + let args = Args::parse(); + run(args).await +} + +pub fn init_metrics_collection( + metrics_addr: Option, +) -> Option> { + iroh::metrics::try_init_metrics_collection().ok(); + // doesn't start the server if the address is None + if let Some(metrics_addr) = metrics_addr { + return Some(tokio::spawn(async move { + if let Err(e) = iroh_metrics::metrics::start_metrics_server(metrics_addr).await { + eprintln!("Failed to start metrics server: {e}"); + } + })); + } + tracing::info!("Metrics server not started, no address provided"); + None +} + +async fn run(args: Args) -> anyhow::Result<()> { + // setup logging + let log_filter = init_logging(); + + let metrics_fut = init_metrics_collection(args.metrics_addr); + + // parse or generate our secret_key + let secret_key = match args.secret_key { + None => SecretKey::generate(), + Some(key) => SecretKey::from_str(&key)?, + }; + println!("> our secret key: {}", secret_key); + + // configure our derp map + let derp_map = match (args.no_derp, args.derp) { + (false, None) => Some(default_derp_map()), + (false, Some(url)) => Some(DerpMap::from_url(url, 0)), + (true, None) => None, + (true, Some(_)) => bail!("You cannot set --no-derp and --derp at the same time"), + }; + println!("> using DERP servers: {}", fmt_derp_map(&derp_map)); + + // build our magic endpoint and the gossip protocol + let (endpoint, gossip, initial_endpoints) = { + // init a cell that will hold our gossip handle to be used in endpoint callbacks + let gossip_cell: OnceCell = OnceCell::new(); + // init a channel that will emit once the initial endpoints of our local node are discovered + let (initial_endpoints_tx, mut initial_endpoints_rx) = mpsc::channel(1); + // build the magic endpoint + let endpoint = MagicEndpoint::builder() + .secret_key(secret_key.clone()) + .alpns(vec![ + GOSSIP_ALPN.to_vec(), + SYNC_ALPN.to_vec(), + iroh_bytes::protocol::ALPN.to_vec(), + ]) + .derp_map(derp_map) + .on_endpoints({ + let gossip_cell = gossip_cell.clone(); + Box::new(move |endpoints| { + // send our updated endpoints to the gossip protocol to be sent as PeerData to peers + if let Some(gossip) = gossip_cell.get() { + gossip.update_endpoints(endpoints).ok(); + } + // trigger oneshot on the first endpoint update + initial_endpoints_tx.try_send(endpoints.to_vec()).ok(); + }) + }) + .bind(args.bind_port) + .await?; + + // initialize the gossip protocol + let gossip = Gossip::from_endpoint(endpoint.clone(), Default::default()); + // insert into the gossip cell to be used in the endpoint callbacks above + gossip_cell.set(gossip.clone()).unwrap(); + + // wait for a first endpoint update so that we know about at least one of our addrs + let initial_endpoints = initial_endpoints_rx.recv().await.unwrap(); + // pass our initial endpoints to the gossip protocol so that they can be announced to peers + gossip.update_endpoints(&initial_endpoints)?; + (endpoint, gossip, initial_endpoints) + }; + println!("> our peer id: {}", endpoint.peer_id()); + + let (topic, peers) = match &args.command { + Command::Open { doc_name } => { + let topic: TopicId = iroh_bytes::Hash::new(doc_name.as_bytes()).into(); + println!( + "> opening document {doc_name} as namespace {} and waiting for peers to join us...", + fmt_hash(topic.as_bytes()) + ); + (topic, vec![]) + } + Command::Join { ticket } => { + let Ticket { topic, peers } = Ticket::from_str(ticket)?; + println!("> joining topic {topic} and connecting to {peers:?}",); + (topic, peers) + } + }; + + let our_ticket = { + // add our local endpoints to the ticket and print it for others to join + let addrs = initial_endpoints.iter().map(|ep| ep.addr).collect(); + let mut peers = peers.clone(); + peers.push(PeerSource { + peer_id: endpoint.peer_id(), + addrs, + derp_region: endpoint.my_derp().await, + }); + Ticket { peers, topic } + }; + println!("> ticket to join us: {our_ticket}"); + + // unwrap our storage path or default to temp + let storage_path = args.storage_path.unwrap_or_else(|| { + let name = format!("iroh-sync-{}", endpoint.peer_id()); + let dir = std::env::temp_dir().join(name); + if !dir.exists() { + std::fs::create_dir_all(&dir).expect("failed to create temp dir"); + } + dir + }); + println!("> storage directory: {storage_path:?}"); + + // create a runtime that can spawn tasks on a local-thread executors (to support !Send futures) + let rt = iroh_bytes::util::runtime::Handle::from_currrent(num_cpus::get())?; + + // create a doc store for the iroh-sync docs + let author = Author::from_bytes(&secret_key.to_bytes()); + let docs_path = storage_path.join("docs.db"); + let docs = iroh_sync::store::fs::Store::new(&docs_path)?; + + // create a bao store for the iroh-bytes blobs + let blob_path = storage_path.join("blobs"); + std::fs::create_dir_all(&blob_path)?; + let db = iroh::baomap::flat::Store::load(&blob_path, &blob_path, &rt).await?; + + // create the live syncer + let downloader = Downloader::new(rt.clone(), endpoint.clone(), db.clone()); + let live_sync = SyncEngine::spawn( + rt.clone(), + endpoint.clone(), + gossip.clone(), + docs.clone(), + db.clone(), + downloader, + ); + + // construct the state that is passed to the endpoint loop and from there cloned + // into to the connection handler task for incoming connections. + let state = Arc::new(State { + gossip: gossip.clone(), + docs: docs.clone(), + bytes: IrohBytesHandlers::new(rt.clone(), db.clone()), + }); + + // spawn our endpoint loop that forwards incoming connections + rt.main().spawn(endpoint_loop(endpoint.clone(), state)); + + // open our document and add to the live syncer + let namespace = Namespace::from_bytes(topic.as_bytes()); + println!("> opening doc {}", fmt_hash(namespace.id().as_bytes())); + let doc = match docs.open_replica(&namespace.id()) { + Ok(Some(doc)) => doc, + Err(_) | Ok(None) => docs.new_replica(namespace)?, + }; + live_sync.start_sync(doc.namespace(), peers.clone()).await?; + + // spawn an repl thread that reads stdin and parses each line as a `Cmd` command + let (cmd_tx, mut cmd_rx) = mpsc::channel(1); + std::thread::spawn(move || repl_loop(cmd_tx).expect("input loop crashed")); + // process commands in a loop + println!("> ready to accept commands"); + println!("> type `help` for a list of commands"); + + let current_watch: Arc>> = + Arc::new(tokio::sync::Mutex::new(None)); + + let watch = current_watch.clone(); + let doc_events = doc.subscribe().expect("already subscribed"); + rt.main().spawn(async move { + while let Ok((_origin, entry)) = doc_events.recv_async().await { + let entry = entry.entry(); + let matcher = watch.lock().await; + if let Some(matcher) = &*matcher { + let key = entry.id().key(); + if key.starts_with(matcher.as_bytes()) { + println!("change: {}", fmt_entry(entry)); + } + } + } + }); + + let repl_state = ReplState { + rt, + store: docs, + author, + doc, + db, + ticket: our_ticket, + log_filter, + current_watch, + }; + + loop { + // wait for a command from the input repl thread + let Some((cmd, to_repl_tx)) = cmd_rx.recv().await else { + break; + }; + // exit command: break early + if let Cmd::Exit = cmd { + to_repl_tx.send(ToRepl::Exit).ok(); + break; + } + + // handle the command, but select against Ctrl-C signal so that commands can be aborted + tokio::select! { + biased; + _ = tokio::signal::ctrl_c() => { + println!("> aborted"); + } + res = repl_state.handle_command(cmd) => if let Err(err) = res { + println!("> error: {err}"); + }, + }; + // notify to the repl that we want to get the next command + to_repl_tx.send(ToRepl::Continue).ok(); + } + + // exit: cancel the sync and store blob database and document + if let Err(err) = live_sync.shutdown().await { + println!("> syncer closed with error: {err:?}"); + } + if let Some(metrics_fut) = metrics_fut { + metrics_fut.abort(); + drop(metrics_fut); + } + + Ok(()) +} + +struct ReplState { + rt: runtime::Handle, + store: store::fs::Store, + author: Author, + doc: Doc, + db: iroh::baomap::flat::Store, + ticket: Ticket, + log_filter: LogLevelReload, + current_watch: Arc>>, +} + +impl ReplState { + async fn handle_command(&self, cmd: Cmd) -> anyhow::Result<()> { + match cmd { + Cmd::Set { key, value } => { + let value = value.into_bytes(); + let len = value.len(); + let hash = self.db.import_bytes(value.into()).await?; + self.doc.insert(key, &self.author, hash, len as u64)?; + } + Cmd::Get { + key, + print_content, + prefix, + } => { + let entries = if prefix { + self.store + .get(self.doc.namespace(), GetFilter::all().with_prefix(key))? + } else { + self.store + .get(self.doc.namespace(), GetFilter::all().with_key(key))? + }; + for entry in entries { + let entry = entry?; + println!("{}", fmt_entry(entry.entry())); + if print_content { + println!("{}", fmt_content(&self.db, &entry).await); + } + } + } + Cmd::Watch { key } => { + println!("watching key: '{key}'"); + self.current_watch.lock().await.replace(key); + } + Cmd::WatchCancel => match self.current_watch.lock().await.take() { + Some(key) => { + println!("canceled watching key: '{key}'"); + } + None => { + println!("no watch active"); + } + }, + Cmd::Ls { prefix } => { + let entries = match prefix { + None => self.store.get(self.doc.namespace(), GetFilter::all())?, + Some(prefix) => self + .store + .get(self.doc.namespace(), GetFilter::all().with_prefix(prefix))?, + }; + let mut count = 0; + for entry in entries { + let entry = entry?; + count += 1; + println!("{}", fmt_entry(entry.entry()),); + } + println!("> {} entries", count); + } + Cmd::Ticket => { + println!("Ticket: {}", self.ticket); + } + Cmd::Log { directive } => { + let next_filter = EnvFilter::from_str(&directive)?; + self.log_filter.modify(|layer| *layer = next_filter)?; + } + Cmd::Stats => get_stats(), + Cmd::Fs(cmd) => self.handle_fs_command(cmd).await?, + Cmd::Hammer { + prefix, + threads, + count, + size, + mode, + } => { + println!( + "> Hammering with prefix \"{prefix}\" for {threads} x {count} messages of size {size} bytes in {mode} mode", + mode = format!("{mode:?}").to_lowercase() + ); + let start = Instant::now(); + let mut handles: Vec>> = Vec::new(); + match mode { + HammerMode::Set => { + let mut bytes = vec![0; size]; + // TODO: Add a flag to fill content differently per entry to be able to + // test downloading too + bytes.fill(97); + for t in 0..threads { + let prefix = prefix.clone(); + let doc = self.doc.clone(); + let bytes = bytes.clone(); + let db = self.db.clone(); + let author = self.author.clone(); + let handle = self.rt.main().spawn(async move { + for i in 0..count { + let value = + String::from_utf8(bytes.clone()).unwrap().into_bytes(); + let len = value.len(); + let key = format!("{}/{}/{}", prefix, t, i); + let hash = db.import_bytes(value.into()).await?; + doc.insert(key, &author, hash, len as u64)?; + } + Ok(count) + }); + handles.push(handle); + } + } + HammerMode::Get => { + for t in 0..threads { + let prefix = prefix.clone(); + let doc = self.doc.clone(); + let store = self.store.clone(); + let handle = self.rt.main().spawn(async move { + let mut read = 0; + for i in 0..count { + let key = format!("{}/{}/{}", prefix, t, i); + let entries = store + .get(doc.namespace(), GetFilter::all().with_key(key))?; + for entry in entries { + let entry = entry?; + let _content = fmt_content_simple(&doc, &entry); + read += 1; + } + } + Ok(read) + }); + handles.push(handle); + } + } + } + + let mut total_count = 0; + for result in futures::future::join_all(handles).await { + // Check that no errors ocurred and count rows inserted/read + total_count += result??; + } + + let diff = start.elapsed().as_secs_f64(); + println!( + "> Hammering done in {diff:.2}s for {total_count} messages with total of {size}", + size = HumanBytes(total_count as u64 * size as u64), + ); + } + Cmd::Exit => {} + } + Ok(()) + } + + async fn handle_fs_command(&self, cmd: FsCmd) -> anyhow::Result<()> { + match cmd { + FsCmd::ImportFile { file_path, key } => { + let file_path = canonicalize_path(&file_path)?.canonicalize()?; + let (hash, len) = self + .db + .import( + file_path.clone(), + ImportMode::Copy, + IgnoreProgressSender::default(), + ) + .await?; + self.doc.insert(key, &self.author, hash, len)?; + println!( + "> imported {file_path:?}: {} ({})", + fmt_hash(hash), + HumanBytes(len) + ); + } + FsCmd::ImportDir { + dir_path, + mut key_prefix, + } => { + if key_prefix.ends_with('/') { + key_prefix.pop(); + } + let root = canonicalize_path(&dir_path)?.canonicalize()?; + let files = walkdir::WalkDir::new(&root).into_iter(); + // TODO: parallelize + for file in files { + let file = file?; + if file.file_type().is_file() { + let relative = file.path().strip_prefix(&root)?.to_string_lossy(); + if relative.is_empty() { + warn!("invalid file path: {:?}", file.path()); + continue; + } + let key = format!("{key_prefix}/{relative}"); + let (hash, len) = self + .db + .import( + file.path().into(), + ImportMode::Copy, + IgnoreProgressSender::default(), + ) + .await?; + self.doc.insert(key, &self.author, hash, len)?; + println!( + "> imported {relative}: {} ({})", + fmt_hash(hash), + HumanBytes(len) + ); + } + } + } + FsCmd::ExportDir { + mut key_prefix, + dir_path, + } => { + if !key_prefix.ends_with('/') { + key_prefix.push('/'); + } + let root = canonicalize_path(&dir_path)?; + println!("> exporting {key_prefix} to {root:?}"); + let entries = self.store.get( + self.doc.namespace(), + GetFilter::latest().with_prefix(&key_prefix), + )?; + let mut checked_dirs = HashSet::new(); + for entry in entries { + let entry = entry?; + let key = entry.entry().id().key(); + let relative = String::from_utf8(key[key_prefix.len()..].to_vec())?; + let len = entry.entry().record().content_len(); + let blob = self.db.get(entry.content_hash()); + if let Some(blob) = blob { + let mut reader = blob.data_reader().await?; + let path = root.join(&relative); + let parent = path.parent().unwrap(); + if !checked_dirs.contains(parent) { + tokio::fs::create_dir_all(&parent).await?; + checked_dirs.insert(parent.to_owned()); + } + let mut file = tokio::fs::File::create(&path).await?; + copy(&mut reader, &mut file).await?; + println!( + "> exported {} to {path:?} ({})", + fmt_hash(entry.content_hash()), + HumanBytes(len) + ); + } + } + } + FsCmd::ExportFile { key, file_path } => { + let path = canonicalize_path(&file_path)?; + // TODO: Fix + let entry = self + .store + .get(self.doc.namespace(), GetFilter::latest().with_key(&key))? + .next(); + if let Some(entry) = entry { + let entry = entry?; + println!("> exporting {key} to {path:?}"); + let parent = path.parent().ok_or_else(|| anyhow!("Invalid path"))?; + tokio::fs::create_dir_all(&parent).await?; + let mut file = tokio::fs::File::create(&path).await?; + let blob = self + .db + .get(entry.content_hash()) + .ok_or_else(|| anyhow!(format!("content for {key} is not available")))?; + let mut reader = blob.data_reader().await?; + copy(&mut reader, &mut file).await?; + } else { + println!("> key not found, abort"); + } + } + } + + Ok(()) + } +} + +#[derive(Parser, Debug)] +pub enum Cmd { + /// Set an entry + Set { + /// Key to the entry (parsed as UTF-8 string). + key: String, + /// Content to store for this entry (parsed as UTF-8 string) + value: String, + }, + /// Get entries by key + /// + /// Shows the author, content hash and content length for all entries for this key. + Get { + /// Key to the entry (parsed as UTF-8 string). + key: String, + /// Print the value (but only if it is valid UTF-8 and smaller than 1MB) + #[clap(short = 'c', long)] + print_content: bool, + /// Match the key as prefix, not an exact match. + #[clap(short = 'p', long)] + prefix: bool, + }, + /// List entries. + Ls { + /// Optionally list only entries whose key starts with PREFIX. + prefix: Option, + }, + + /// Import from and export to the local file system. + #[clap(subcommand)] + Fs(FsCmd), + + /// Print the ticket with which other peers can join our document. + Ticket, + /// Change the log level + Log { + /// The log level or log filtering directive + /// + /// Valid log levels are: "trace", "debug", "info", "warn", "error" + /// + /// You can also set one or more filtering directives to enable more fine-grained log + /// filtering. The supported filtering directives and their semantics are documented here: + /// https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives + /// + /// To disable logging completely, set to the empty string (via empty double quotes: ""). + #[clap(verbatim_doc_comment)] + directive: String, + }, + /// Watch for changes. + Watch { + /// The key to watch. + key: String, + }, + /// Cancels any running watch command. + WatchCancel, + /// Show stats about the current session + Stats, + /// Hammer time - stress test with the hammer + Hammer { + /// The hammer mode + #[clap(value_enum)] + mode: HammerMode, + /// The key prefix + prefix: String, + /// The number of threads to use (each thread will create it's own replica) + #[clap(long, short, default_value = "2")] + threads: usize, + /// The number of entries to create + #[clap(long, short, default_value = "1000")] + count: usize, + /// The size of each entry in Bytes + #[clap(long, short, default_value = "1024")] + size: usize, + }, + /// Quit + Exit, +} + +#[derive(Clone, Debug, clap::ValueEnum)] +pub enum HammerMode { + /// Create entries + Set, + /// Read entries + Get, +} + +#[derive(Parser, Debug)] +pub enum FsCmd { + /// Import a file system directory into the document. + ImportDir { + /// The file system path to import recursively + dir_path: String, + /// The key prefix to apply to the document keys + key_prefix: String, + }, + /// Import a file into the document. + ImportFile { + /// The path to the file + file_path: String, + /// The key in the document + key: String, + }, + /// Export a part of the document into a file system directory + ExportDir { + /// The key prefix to filter on + key_prefix: String, + /// The file system path to export to + dir_path: String, + }, + /// Import a file into the document. + ExportFile { + /// The key in the document + key: String, + /// The path to the file + file_path: String, + }, +} + +impl FromStr for Cmd { + type Err = anyhow::Error; + fn from_str(s: &str) -> Result { + let args = shell_words::split(s)?; + let matches = Cmd::command() + .multicall(true) + .subcommand_required(true) + .try_get_matches_from(args)?; + let cmd = Cmd::from_arg_matches(&matches)?; + Ok(cmd) + } +} + +#[derive(Debug)] +struct State { + gossip: Gossip, + docs: iroh_sync::store::fs::Store, + bytes: IrohBytesHandlers, +} + +async fn endpoint_loop(endpoint: MagicEndpoint, state: Arc) -> anyhow::Result<()> { + while let Some(conn) = endpoint.accept().await { + let state = state.clone(); + tokio::spawn(async move { + if let Err(err) = handle_connection(conn, state).await { + println!("> connection closed, reason: {err}"); + } + }); + } + Ok(()) +} + +async fn handle_connection(mut conn: quinn::Connecting, state: Arc) -> anyhow::Result<()> { + let alpn = get_alpn(&mut conn).await?; + println!("> incoming connection with alpn {alpn}"); + match alpn.as_bytes() { + GOSSIP_ALPN => state.gossip.handle_connection(conn.await?).await, + SYNC_ALPN => iroh_sync::net::handle_connection(conn, state.docs.clone()).await, + alpn if alpn == iroh_bytes::protocol::ALPN => state.bytes.handle_connection(conn).await, + _ => bail!("ignoring connection: unsupported ALPN protocol"), + } +} + +#[derive(Debug)] +enum ToRepl { + Continue, + Exit, +} + +fn repl_loop(cmd_tx: mpsc::Sender<(Cmd, oneshot::Sender)>) -> anyhow::Result<()> { + use rustyline::{error::ReadlineError, Config, DefaultEditor}; + let mut rl = DefaultEditor::with_config(Config::builder().check_cursor_position(true).build())?; + loop { + // prepare a channel to receive a signal from the main thread when a command completed + let (to_repl_tx, to_repl_rx) = oneshot::channel(); + let readline = rl.readline(">> "); + match readline { + Ok(line) if line.is_empty() => continue, + Ok(line) => { + rl.add_history_entry(line.as_str())?; + match Cmd::from_str(&line) { + Ok(cmd) => cmd_tx.blocking_send((cmd, to_repl_tx))?, + Err(err) => { + println!("{err}"); + continue; + } + }; + } + Err(ReadlineError::Interrupted | ReadlineError::Eof) => { + cmd_tx.blocking_send((Cmd::Exit, to_repl_tx))?; + } + Err(ReadlineError::WindowResized) => continue, + Err(err) => return Err(err.into()), + } + // wait for reply from main thread + match to_repl_rx.blocking_recv()? { + ToRepl::Continue => continue, + ToRepl::Exit => break, + } + } + Ok(()) +} + +fn get_stats() { + let Ok(stats) = iroh::metrics::get_metrics() else { + println!("metrics collection is disabled"); + return; + }; + for (name, details) in stats.iter() { + println!( + "{:23} : {:>6} ({})", + name, details.value, details.description + ); + } +} + +#[derive(Debug, Serialize, Deserialize)] +struct Ticket { + topic: TopicId, + peers: Vec, +} +impl Ticket { + /// Deserializes from bytes. + fn from_bytes(bytes: &[u8]) -> anyhow::Result { + postcard::from_bytes(bytes).map_err(Into::into) + } + /// Serializes to bytes. + pub fn to_bytes(&self) -> Vec { + postcard::to_stdvec(self).expect("postcard::to_stdvec is infallible") + } +} + +/// Serializes to base32. +impl fmt::Display for Ticket { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let encoded = self.to_bytes(); + let mut text = data_encoding::BASE32_NOPAD.encode(&encoded); + text.make_ascii_lowercase(); + write!(f, "{text}") + } +} + +/// Deserializes from base32. +impl FromStr for Ticket { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + let bytes = data_encoding::BASE32_NOPAD.decode(s.to_ascii_uppercase().as_bytes())?; + let slf = Self::from_bytes(&bytes)?; + Ok(slf) + } +} + +type LogLevelReload = tracing_subscriber::reload::Handle; +fn init_logging() -> LogLevelReload { + use tracing_subscriber::{filter, fmt, prelude::*, reload}; + let filter = filter::EnvFilter::from_default_env(); + let (filter, reload_handle) = reload::Layer::new(filter); + tracing_subscriber::registry() + .with(filter) + .with(fmt::Layer::default()) + .init(); + reload_handle +} + +// helpers + +fn fmt_entry(entry: &Entry) -> String { + let id = entry.id(); + let key = std::str::from_utf8(id.key()).unwrap_or(""); + let author = fmt_hash(id.author().as_bytes()); + let hash = entry.record().content_hash(); + let hash = fmt_hash(hash.as_bytes()); + let len = HumanBytes(entry.record().content_len()); + format!("@{author}: {key} = {hash} ({len})",) +} + +async fn fmt_content_simple(_doc: &Doc, entry: &SignedEntry) -> String { + let len = entry.entry().record().content_len(); + format!("<{}>", HumanBytes(len)) +} + +async fn fmt_content(db: &B, entry: &SignedEntry) -> String { + let len = entry.entry().record().content_len(); + if len > MAX_DISPLAY_CONTENT_LEN { + format!("<{}>", HumanBytes(len)) + } else { + match read_content(db, entry).await { + Err(err) => format!(""), + Ok(content) => match String::from_utf8(content.into()) { + Ok(str) => str, + Err(_err) => format!("", HumanBytes(len)), + }, + } + } +} + +async fn read_content(db: &B, entry: &SignedEntry) -> anyhow::Result { + let data = db + .get(entry.content_hash()) + .ok_or_else(|| anyhow!("not found"))? + .data_reader() + .await? + .read_to_end() + .await?; + Ok(data) +} +fn fmt_hash(hash: impl AsRef<[u8]>) -> String { + let mut text = data_encoding::BASE32_NOPAD.encode(hash.as_ref()); + text.make_ascii_lowercase(); + format!("{}…{}", &text[..5], &text[(text.len() - 2)..]) +} +fn fmt_derp_map(derp_map: &Option) -> String { + match derp_map { + None => "None".to_string(), + Some(map) => map + .regions() + .flat_map(|region| region.nodes.iter().map(|node| node.url.to_string())) + .collect::>() + .join(", "), + } +} +fn canonicalize_path(path: &str) -> anyhow::Result { + let path = PathBuf::from(shellexpand::tilde(&path).to_string()); + Ok(path) +} + +/// Copy from a [`iroh_io::AsyncSliceReader`] into a [`tokio::io::AsyncWrite`] +/// +/// TODO: move to iroh-io or iroh-bytes +async fn copy( + mut reader: impl iroh_io::AsyncSliceReader, + mut writer: impl tokio::io::AsyncWrite + Unpin, +) -> anyhow::Result<()> { + // this is the max chunk size. + // will only allocate this much if the resource behind the reader is at least this big. + let chunk_size = 1024 * 16; + let mut pos = 0u64; + loop { + let chunk = reader.read_at(pos, chunk_size).await?; + if chunk.is_empty() { + break; + } + writer.write_all(&chunk).await?; + pos += chunk.len() as u64; + } + Ok(()) +} + +/// handlers for iroh_bytes connections +mod iroh_bytes_handlers { + use std::sync::Arc; + + use bytes::Bytes; + use futures::{future::BoxFuture, FutureExt}; + use iroh_bytes::{ + protocol::{GetRequest, RequestToken}, + provider::{CustomGetHandler, EventSender, RequestAuthorizationHandler}, + }; + + use iroh::collection::IrohCollectionParser; + + #[derive(Debug, Clone)] + pub struct IrohBytesHandlers { + db: iroh::baomap::flat::Store, + rt: iroh_bytes::util::runtime::Handle, + event_sender: NoopEventSender, + get_handler: Arc, + auth_handler: Arc, + } + impl IrohBytesHandlers { + pub fn new(rt: iroh_bytes::util::runtime::Handle, db: iroh::baomap::flat::Store) -> Self { + Self { + db, + rt, + event_sender: NoopEventSender, + get_handler: Arc::new(NoopCustomGetHandler), + auth_handler: Arc::new(NoopRequestAuthorizationHandler), + } + } + pub async fn handle_connection(&self, conn: quinn::Connecting) -> anyhow::Result<()> { + iroh_bytes::provider::handle_connection( + conn, + self.db.clone(), + self.event_sender.clone(), + IrohCollectionParser, + self.get_handler.clone(), + self.auth_handler.clone(), + self.rt.clone(), + ) + .await; + Ok(()) + } + } + + #[derive(Debug, Clone)] + struct NoopEventSender; + impl EventSender for NoopEventSender { + fn send(&self, _event: iroh_bytes::provider::Event) -> BoxFuture<()> { + async {}.boxed() + } + } + #[derive(Debug)] + struct NoopCustomGetHandler; + impl CustomGetHandler for NoopCustomGetHandler { + fn handle( + &self, + _token: Option, + _request: Bytes, + ) -> BoxFuture<'static, anyhow::Result> { + async move { Err(anyhow::anyhow!("no custom get handler defined")) }.boxed() + } + } + #[derive(Debug)] + struct NoopRequestAuthorizationHandler; + impl RequestAuthorizationHandler for NoopRequestAuthorizationHandler { + fn authorize( + &self, + token: Option, + _request: &iroh_bytes::protocol::Request, + ) -> BoxFuture<'static, anyhow::Result<()>> { + async move { + if let Some(token) = token { + anyhow::bail!( + "no authorization handler defined, but token was provided: {:?}", + token + ); + } + Ok(()) + } + .boxed() + } + } +} diff --git a/iroh/src/client.rs b/iroh/src/client.rs new file mode 100644 index 0000000000..8cf1b10ff4 --- /dev/null +++ b/iroh/src/client.rs @@ -0,0 +1,244 @@ +//! Client to an iroh node. Is generic over the connection (in-memory or RPC). +//! +//! TODO: Contains only iroh sync related methods. Add other methods. + +use std::collections::HashMap; +use std::result::Result as StdResult; + +use anyhow::{anyhow, Result}; +use bytes::Bytes; +use futures::{Stream, StreamExt, TryStreamExt}; +use iroh_bytes::Hash; +use iroh_sync::store::GetFilter; +use iroh_sync::sync::{AuthorId, NamespaceId, SignedEntry}; +use quic_rpc::{RpcClient, ServiceConnection}; + +use crate::rpc_protocol::{ + AuthorCreateRequest, AuthorListRequest, BytesGetRequest, CounterStats, DocCreateRequest, + DocGetRequest, DocImportRequest, DocInfoRequest, DocListRequest, DocSetRequest, + DocShareRequest, DocStartSyncRequest, DocStopSyncRequest, DocSubscribeRequest, DocTicket, + ProviderService, ShareMode, StatsGetRequest, +}; +use crate::sync_engine::{LiveEvent, LiveStatus, PeerSource}; + +pub mod mem; +#[cfg(feature = "cli")] +pub mod quic; + +/// Iroh client +#[derive(Debug, Clone)] +pub struct Iroh { + rpc: RpcClient, +} + +impl Iroh +where + C: ServiceConnection, +{ + /// Create a new high-level client to a Iroh node from the low-level RPC client. + pub fn new(rpc: RpcClient) -> Self { + Self { rpc } + } + + /// Create a new document author. + pub async fn create_author(&self) -> Result { + let res = self.rpc.rpc(AuthorCreateRequest).await??; + Ok(res.author_id) + } + + /// List document authors for which we have a secret key. + pub async fn list_authors(&self) -> Result>> { + let stream = self.rpc.server_streaming(AuthorListRequest {}).await?; + Ok(flatten(stream).map_ok(|res| res.author_id)) + } + + /// Create a new document. + pub async fn create_doc(&self) -> Result> { + let res = self.rpc.rpc(DocCreateRequest {}).await??; + let doc = Doc { + id: res.id, + rpc: self.rpc.clone(), + }; + Ok(doc) + } + + /// Import a document from a ticket and join all peers in the ticket. + pub async fn import_doc(&self, ticket: DocTicket) -> Result> { + let res = self.rpc.rpc(DocImportRequest(ticket)).await??; + let doc = Doc { + id: res.doc_id, + rpc: self.rpc.clone(), + }; + Ok(doc) + } + + /// List all documents. + pub async fn list_docs(&self) -> Result>> { + let stream = self.rpc.server_streaming(DocListRequest {}).await?; + Ok(flatten(stream).map_ok(|res| res.id)) + } + + /// Get a [`Doc`] client for a single document. Return an error if the document cannot be found. + pub async fn get_doc(&self, id: NamespaceId) -> Result> { + match self.try_get_doc(id).await? { + Some(doc) => Ok(doc), + None => Err(anyhow!("Document not found")), + } + } + + /// Get a [`Doc`] client for a single document. Return None if the document cannot be found. + pub async fn try_get_doc(&self, id: NamespaceId) -> Result>> { + if let Err(_err) = self.rpc.rpc(DocInfoRequest { doc_id: id }).await? { + return Ok(None); + } + let doc = Doc { + id, + rpc: self.rpc.clone(), + }; + Ok(Some(doc)) + } + + /// Get the bytes for a hash. + /// + /// Note: This reads the full blob into memory. + // TODO: add get_reader for streaming gets + pub async fn get_bytes(&self, hash: Hash) -> Result { + let res = self.rpc.rpc(BytesGetRequest { hash }).await??; + Ok(res.data) + } + + /// Get statistics of the running node. + pub async fn stats(&self) -> Result> { + let res = self.rpc.rpc(StatsGetRequest {}).await??; + Ok(res.stats) + } +} + +/// Document handle +#[derive(Debug, Clone)] +pub struct Doc { + id: NamespaceId, + rpc: RpcClient, +} + +impl Doc +where + C: ServiceConnection, +{ + /// Get the document id of this doc. + pub fn id(&self) -> NamespaceId { + self.id + } + + /// Set the content of a key to a byte array. + pub async fn set_bytes( + &self, + author_id: AuthorId, + key: Vec, + value: Vec, + ) -> Result { + let res = self + .rpc + .rpc(DocSetRequest { + doc_id: self.id, + author_id, + key, + value, + }) + .await??; + Ok(res.entry) + } + + /// Get the contents of an entry as a byte array. + // TODO: add get_content_reader + pub async fn get_content_bytes(&self, entry: &SignedEntry) -> Result { + let hash = *entry.content_hash(); + let bytes = self.rpc.rpc(BytesGetRequest { hash }).await??; + Ok(bytes.data) + } + + /// Get the latest entry for a key and author. + pub async fn get_latest(&self, author_id: AuthorId, key: Vec) -> Result { + let filter = GetFilter::latest().with_key(key).with_author(author_id); + let mut stream = self.get(filter).await?; + let entry = stream + .next() + .await + .unwrap_or_else(|| Err(anyhow!("not found")))?; + Ok(entry) + } + + /// Get entries. + pub async fn get(&self, filter: GetFilter) -> Result>> { + let stream = self + .rpc + .server_streaming(DocGetRequest { + doc_id: self.id, + filter, + }) + .await?; + Ok(flatten(stream).map_ok(|res| res.entry)) + } + + /// Share this document with peers over a ticket. + pub async fn share(&self, mode: ShareMode) -> anyhow::Result { + let res = self + .rpc + .rpc(DocShareRequest { + doc_id: self.id, + mode, + }) + .await??; + Ok(res.0) + } + + /// Start to sync this document with a list of peers. + pub async fn start_sync(&self, peers: Vec) -> Result<()> { + let _res = self + .rpc + .rpc(DocStartSyncRequest { + doc_id: self.id, + peers, + }) + .await??; + Ok(()) + } + + /// Stop the live sync for this document. + pub async fn stop_sync(&self) -> Result<()> { + let _res = self + .rpc + .rpc(DocStopSyncRequest { doc_id: self.id }) + .await??; + Ok(()) + } + + /// Subscribe to events for this document. + pub async fn subscribe(&self) -> anyhow::Result>> { + let stream = self + .rpc + .server_streaming(DocSubscribeRequest { doc_id: self.id }) + .await?; + Ok(flatten(stream).map_ok(|res| res.event).map_err(Into::into)) + } + + /// Get status info for this document + pub async fn status(&self) -> anyhow::Result { + let res = self.rpc.rpc(DocInfoRequest { doc_id: self.id }).await??; + Ok(res.status) + } +} + +fn flatten( + s: impl Stream, E2>>, +) -> impl Stream> +where + E1: std::error::Error + Send + Sync + 'static, + E2: std::error::Error + Send + Sync + 'static, +{ + s.map(|res| match res { + Ok(Ok(res)) => Ok(res), + Ok(Err(err)) => Err(err.into()), + Err(err) => Err(err.into()), + }) +} diff --git a/iroh/src/client/mem.rs b/iroh/src/client/mem.rs new file mode 100644 index 0000000000..1d72f7368a --- /dev/null +++ b/iroh/src/client/mem.rs @@ -0,0 +1,20 @@ +//! Type declarations for an in-memory client to an iroh node running in the same process. +//! +//! The in-memory client is obtained directly from a running node through +//! [`crate::node::Node::client`] + +use quic_rpc::transport::flume::FlumeConnection; + +use crate::rpc_protocol::{ProviderRequest, ProviderResponse, ProviderService}; + +/// RPC client to an iroh node running in the same process. +pub type RpcClient = + quic_rpc::RpcClient>; + +/// In-memory client to an iroh node running in the same process. +/// +/// This is obtained from [`crate::node::Node::client`]. +pub type Iroh = super::Iroh>; + +/// In-memory document client to an iroh node running in the same process. +pub type Doc = super::Doc>; diff --git a/iroh/src/client/quic.rs b/iroh/src/client/quic.rs new file mode 100644 index 0000000000..c4e683957a --- /dev/null +++ b/iroh/src/client/quic.rs @@ -0,0 +1,65 @@ +//! Type declarations and utility functions for an RPC client to an iroh node running in a seperate process. + +use std::{ + net::{Ipv4Addr, SocketAddr, SocketAddrV4}, + sync::Arc, + time::Duration, +}; + +use quic_rpc::transport::quinn::QuinnConnection; + +use crate::rpc_protocol::{ProviderRequest, ProviderResponse, ProviderService, VersionRequest}; + +/// TODO: Change to "/iroh-rpc/1" +pub const RPC_ALPN: [u8; 17] = *b"n0/provider-rpc/1"; + +/// RPC client to an iroh node running in a seperate process. +pub type RpcClient = + quic_rpc::RpcClient>; + +/// Client to an iroh node running in a seperate process. +/// +/// This is obtained from [`connect`]. +pub type Iroh = super::Iroh>; + +/// RPC document client to an iroh node running in a seperate process. +pub type Doc = super::Doc>; + +/// Connect to an iroh node running on the same computer, but in a different process. +pub async fn connect(rpc_port: u16) -> anyhow::Result { + let client = connect_raw(rpc_port).await?; + Ok(Iroh::new(client)) +} + +/// Create a raw RPC client to an iroh node running on the same computer, but in a different +/// process. +pub async fn connect_raw(rpc_port: u16) -> anyhow::Result { + use anyhow::Context; + let bind_addr = SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0).into(); + let endpoint = create_quinn_client(bind_addr, vec![RPC_ALPN.to_vec()], false)?; + let addr = SocketAddr::new(Ipv4Addr::LOCALHOST.into(), rpc_port); + let server_name = "localhost".to_string(); + let connection = QuinnConnection::new(endpoint, addr, server_name); + let client = RpcClient::new(connection); + // Do a version request to check if the server is running. + let _version = tokio::time::timeout(Duration::from_secs(1), client.rpc(VersionRequest)) + .await + .context("iroh server is not running")??; + Ok(client) +} +fn create_quinn_client( + bind_addr: SocketAddr, + alpn_protocols: Vec>, + keylog: bool, +) -> anyhow::Result { + let secret_key = iroh_net::key::SecretKey::generate(); + let tls_client_config = + iroh_net::tls::make_client_config(&secret_key, None, alpn_protocols, keylog)?; + let mut client_config = quinn::ClientConfig::new(Arc::new(tls_client_config)); + let mut endpoint = quinn::Endpoint::client(bind_addr)?; + let mut transport_config = quinn::TransportConfig::default(); + transport_config.keep_alive_interval(Some(Duration::from_secs(1))); + client_config.transport_config(Arc::new(transport_config)); + endpoint.set_default_client_config(client_config); + Ok(endpoint) +} diff --git a/iroh/src/commands.rs b/iroh/src/commands.rs index 528e8376b2..6a08d66a34 100644 --- a/iroh/src/commands.rs +++ b/iroh/src/commands.rs @@ -1,25 +1,20 @@ -use std::net::{Ipv4Addr, SocketAddrV4}; use std::str::FromStr; -use std::sync::Arc; -use std::time::Duration; use std::{net::SocketAddr, path::PathBuf}; -use anyhow::{Context, Result}; +use anyhow::Result; use clap::{Parser, Subcommand}; use futures::StreamExt; +use iroh::client::quic::RpcClient; use iroh::dial::Ticket; use iroh::rpc_protocol::*; use iroh_bytes::{protocol::RequestToken, util::runtime, Hash}; use iroh_net::key::{PublicKey, SecretKey}; -use quic_rpc::transport::quinn::QuinnConnection; -use quic_rpc::RpcClient; use crate::config::Config; use self::provide::{ProvideOptions, ProviderRpcPort}; const DEFAULT_RPC_PORT: u16 = 0x1337; -const RPC_ALPN: [u8; 17] = *b"n0/provider-rpc/1"; const MAX_RPC_CONNECTIONS: u32 = 16; const MAX_RPC_STREAMS: u64 = 1024; @@ -28,6 +23,7 @@ pub mod doctor; pub mod get; pub mod list; pub mod provide; +pub mod sync; pub mod validate; /// Send data. @@ -216,6 +212,10 @@ impl Cli { Ok(()) } Commands::Doctor { command } => self::doctor::run(command, config).await, + Commands::Sync { command, rpc_port } => { + let client = make_rpc_client(rpc_port).await?; + command.run(client).await + } } } } @@ -390,59 +390,28 @@ pub enum Commands { #[clap(long, default_value_t = DEFAULT_RPC_PORT)] rpc_port: u16, }, + Sync { + /// RPC port + #[clap(long, default_value_t = DEFAULT_RPC_PORT)] + rpc_port: u16, + #[clap(subcommand)] + command: sync::Commands, + }, } -async fn make_rpc_client( - rpc_port: u16, -) -> anyhow::Result>> -{ - let bind_addr = SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0).into(); - let endpoint = create_quinn_client(bind_addr, vec![RPC_ALPN.to_vec()], false)?; - let addr = SocketAddr::new(Ipv4Addr::LOCALHOST.into(), rpc_port); - let server_name = "localhost".to_string(); - let connection = QuinnConnection::new(endpoint, addr, server_name); - let client = RpcClient::::new(connection); - // Do a version request to check if the server is running. - let _version = tokio::time::timeout(Duration::from_secs(1), client.rpc(VersionRequest)) - .await - .context("iroh server is not running")??; - Ok(client) -} - -pub fn create_quinn_client( - bind_addr: SocketAddr, - alpn_protocols: Vec>, - keylog: bool, -) -> Result { - let secret_key = iroh_net::key::SecretKey::generate(); - let tls_client_config = - iroh_net::tls::make_client_config(&secret_key, None, alpn_protocols, keylog)?; - let mut client_config = quinn::ClientConfig::new(Arc::new(tls_client_config)); - let mut endpoint = quinn::Endpoint::client(bind_addr)?; - let mut transport_config = quinn::TransportConfig::default(); - transport_config.keep_alive_interval(Some(Duration::from_secs(1))); - client_config.transport_config(Arc::new(transport_config)); - endpoint.set_default_client_config(client_config); - Ok(endpoint) +pub async fn make_rpc_client(rpc_port: u16) -> anyhow::Result { + iroh::client::quic::connect_raw(rpc_port).await } #[cfg(feature = "metrics")] -pub fn init_metrics_collection( +pub fn start_metrics_server( metrics_addr: Option, rt: &iroh_bytes::util::runtime::Handle, ) -> Option> { - use iroh_metrics::core::Metric; - // doesn't start the server if the address is None if let Some(metrics_addr) = metrics_addr { - iroh_metrics::core::Core::init(|reg, metrics| { - metrics.insert(iroh::metrics::Metrics::new(reg)); - metrics.insert(iroh_net::metrics::MagicsockMetrics::new(reg)); - metrics.insert(iroh_net::metrics::NetcheckMetrics::new(reg)); - metrics.insert(iroh_net::metrics::PortmapMetrics::new(reg)); - metrics.insert(iroh_net::metrics::DerpMetrics::new(reg)); - }); - + // metrics are initilaized in iroh::node::Node::spawn + // here we only start the server return Some(rt.main().spawn(async move { if let Err(e) = iroh_metrics::metrics::start_metrics_server(metrics_addr).await { eprintln!("Failed to start metrics server: {e}"); diff --git a/iroh/src/commands/get.rs b/iroh/src/commands/get.rs index e0a90b339e..9a45c95897 100644 --- a/iroh/src/commands/get.rs +++ b/iroh/src/commands/get.rs @@ -69,8 +69,11 @@ impl GetInteractive { tokio::fs::create_dir_all(&temp_dir).await?; let db: iroh::baomap::flat::Store = iroh::baomap::flat::Store::load(temp_dir.clone(), temp_dir.clone(), &self.rt).await?; + // TODO: we don't need sync here, maybe disable completely? + let doc_store = iroh_sync::store::memory::Store::default(); // spin up temp node and ask it to download the data for us - let mut provider = iroh::node::Node::builder(db).collection_parser(IrohCollectionParser); + let mut provider = + iroh::node::Node::builder(db, doc_store).collection_parser(IrohCollectionParser); if let Some(ref dm) = self.opts.derp_map { provider = provider.derp_map(dm.clone()); } diff --git a/iroh/src/commands/provide.rs b/iroh/src/commands/provide.rs index 41e63cf7bd..78b7666458 100644 --- a/iroh/src/commands/provide.rs +++ b/iroh/src/commands/provide.rs @@ -9,12 +9,14 @@ use std::{ use anyhow::{anyhow, ensure, Context, Result}; use iroh::{ baomap::flat, + client::quic::RPC_ALPN, collection::IrohCollectionParser, node::{Node, StaticTokenAuthHandler}, rpc_protocol::{ProvideRequest, ProviderRequest, ProviderResponse, ProviderService}, }; -use iroh_bytes::{baomap::Store, protocol::RequestToken, util::runtime}; +use iroh_bytes::{baomap::Store as BaoStore, protocol::RequestToken, util::runtime}; use iroh_net::{derp::DerpMap, key::SecretKey}; +use iroh_sync::store::Store as DocStore; use quic_rpc::{transport::quinn::QuinnServerEndpoint, ServiceEndpoint}; use tokio::io::AsyncWriteExt; use tracing::{info_span, Instrument}; @@ -23,7 +25,7 @@ use crate::config::IrohPaths; use super::{ add::{aggregate_add_response, print_add_response}, - MAX_RPC_CONNECTIONS, MAX_RPC_STREAMS, RPC_ALPN, + MAX_RPC_CONNECTIONS, MAX_RPC_STREAMS, }; #[derive(Debug)] @@ -57,8 +59,9 @@ pub async fn run( .await .with_context(|| format!("Failed to load iroh database from {}", blob_dir.display()))?; let key = Some(IrohPaths::SecretKey.with_env()?); + let store = iroh_sync::store::fs::Store::new(IrohPaths::DocsDatabase.with_env()?)?; let token = opts.request_token.clone(); - let provider = provide(db.clone(), rt, key, opts).await?; + let provider = provide(db.clone(), store, rt, key, opts).await?; let controller = provider.controller(); if let Some(t) = token.as_ref() { println!("Request token: {}", t); @@ -125,15 +128,16 @@ pub async fn run( Ok(()) } -async fn provide( - db: D, +async fn provide( + bao_store: B, + doc_store: D, rt: &runtime::Handle, key: Option, opts: ProvideOptions, -) -> Result> { +) -> Result> { let secret_key = get_secret_key(key).await?; - let mut builder = Node::builder(db) + let mut builder = Node::builder(bao_store, doc_store) .collection_parser(IrohCollectionParser) .custom_auth_handler(Arc::new(StaticTokenAuthHandler::new(opts.request_token))) .keylog(opts.keylog); diff --git a/iroh/src/commands/sync.rs b/iroh/src/commands/sync.rs new file mode 100644 index 0000000000..46cb5af9dd --- /dev/null +++ b/iroh/src/commands/sync.rs @@ -0,0 +1,251 @@ +use clap::Parser; +use futures::TryStreamExt; +use indicatif::HumanBytes; +use iroh::{ + client::quic::Iroh, + rpc_protocol::{DocTicket, ShareMode}, + sync_engine::PeerSource, +}; +use iroh_sync::{ + store::GetFilter, + sync::{AuthorId, NamespaceId, SignedEntry}, +}; + +use super::RpcClient; + +const MAX_DISPLAY_CONTENT_LEN: u64 = 1024 * 1024; + +#[allow(clippy::large_enum_variant)] +#[derive(Debug, Clone, Parser)] +pub enum Commands { + Author { + #[clap(subcommand)] + command: Author, + }, + Docs { + #[clap(subcommand)] + command: Docs, + }, + Doc { + id: NamespaceId, + #[clap(subcommand)] + command: Doc, + }, +} + +impl Commands { + pub async fn run(self, client: RpcClient) -> anyhow::Result<()> { + let iroh = Iroh::new(client); + match self { + Commands::Author { command } => command.run(iroh).await, + Commands::Docs { command } => command.run(iroh).await, + Commands::Doc { command, id } => command.run(iroh, id).await, + } + } +} + +#[derive(Debug, Clone, Parser)] +pub enum Author { + List, + Create, +} + +impl Author { + pub async fn run(self, iroh: Iroh) -> anyhow::Result<()> { + match self { + Author::List => { + let mut stream = iroh.list_authors().await?; + while let Some(author_id) = stream.try_next().await? { + println!("{}", author_id); + } + } + Author::Create => { + let author_id = iroh.create_author().await?; + println!("{}", author_id); + } + } + Ok(()) + } +} + +#[derive(Debug, Clone, Parser)] +pub enum Docs { + List, + Create, + Import { ticket: DocTicket }, +} + +impl Docs { + pub async fn run(self, iroh: Iroh) -> anyhow::Result<()> { + match self { + Docs::Create => { + let doc = iroh.create_doc().await?; + println!("created {}", doc.id()); + } + Docs::Import { ticket } => { + let doc = iroh.import_doc(ticket).await?; + println!("imported {}", doc.id()); + } + Docs::List => { + let mut stream = iroh.list_docs().await?; + while let Some(id) = stream.try_next().await? { + println!("{}", id) + } + } + } + Ok(()) + } +} + +#[derive(Debug, Clone, Parser)] +pub enum Doc { + StartSync { + peers: Vec, + }, + Share { + mode: ShareMode, + }, + /// Set an entry + Set { + /// Author of this entry. + #[clap(short, long)] + author: AuthorId, + /// Key to the entry (parsed as UTF-8 string). + key: String, + /// Content to store for this entry (parsed as UTF-8 string) + value: String, + }, + /// Get entries by key + /// + /// Shows the author, content hash and content length for all entries for this key. + Get { + /// Key to the entry (parsed as UTF-8 string). + key: String, + /// If true, get all entries that start with KEY. + #[clap(short, long)] + prefix: bool, + /// Filter by author. + #[clap(short, long)] + author: Option, + /// If true, old entries will be included. By default only the latest value for each key is + /// shown. + #[clap(short, long)] + old: bool, + + /// Also print the content for each entry (but only if smaller than 1MB and valid UTf-8) + #[clap(short, long)] + content: bool, + }, + List { + /// Filter by author. + #[clap(short, long)] + author: Option, + /// If true, old entries will be included. By default only the latest value for each key is + /// shown. + #[clap(short, long)] + old: bool, + /// Optional key prefix (parsed as UTF-8 string) + prefix: Option, + }, +} + +impl Doc { + pub async fn run(self, iroh: Iroh, doc_id: NamespaceId) -> anyhow::Result<()> { + let doc = iroh.get_doc(doc_id).await?; + match self { + Doc::StartSync { peers } => { + doc.start_sync(peers).await?; + println!("ok"); + } + Doc::Share { mode } => { + let ticket = doc.share(mode).await?; + println!("ticket: {}", ticket); + } + Doc::Set { author, key, value } => { + let key = key.as_bytes().to_vec(); + let value = value.as_bytes().to_vec(); + let entry = doc.set_bytes(author, key, value).await?; + println!("{}", fmt_entry(&entry)); + } + Doc::Get { + key, + prefix, + author, + old, + content, + } => { + let mut filter = match old { + true => GetFilter::all(), + false => GetFilter::latest(), + }; + if let Some(author) = author { + filter = filter.with_author(author); + }; + let filter = match prefix { + true => filter.with_prefix(key), + false => filter.with_key(key), + }; + + let mut stream = doc.get(filter).await?; + while let Some(entry) = stream.try_next().await? { + println!("{}", fmt_entry(&entry)); + if content { + if entry.content_len() < MAX_DISPLAY_CONTENT_LEN { + match doc.get_content_bytes(&entry).await { + Ok(content) => match String::from_utf8(content.into()) { + Ok(s) => println!("{s}"), + Err(_err) => println!(""), + }, + Err(err) => println!(""), + } + } else { + println!( + "", + HumanBytes(entry.content_len()) + ) + } + } + println!(); + } + } + Doc::List { + old, + prefix, + author, + } => { + let filter = match old { + true => GetFilter::all(), + false => GetFilter::latest(), + }; + let mut filter = match prefix { + Some(prefix) => filter.with_prefix(prefix), + None => filter, + }; + if let Some(author) = author { + filter = filter.with_author(author); + }; + let mut stream = doc.get(filter).await?; + while let Some(entry) = stream.try_next().await? { + println!("{}", fmt_entry(&entry)); + } + } + } + Ok(()) + } +} + +fn fmt_entry(entry: &SignedEntry) -> String { + let id = entry.entry().id(); + let key = std::str::from_utf8(id.key()).unwrap_or(""); + let author = fmt_hash(id.author().as_bytes()); + let hash = entry.entry().record().content_hash(); + let hash = fmt_hash(hash.as_bytes()); + let len = HumanBytes(entry.entry().record().content_len()); + format!("@{author}: {key} = {hash} ({len})",) +} + +fn fmt_hash(hash: impl AsRef<[u8]>) -> String { + let mut text = data_encoding::BASE32_NOPAD.encode(&hash.as_ref()[..5]); + text.make_ascii_lowercase(); + format!("{}…", &text) +} diff --git a/iroh/src/config.rs b/iroh/src/config.rs index 149715534c..dc41ec999c 100644 --- a/iroh/src/config.rs +++ b/iroh/src/config.rs @@ -32,6 +32,8 @@ pub enum IrohPaths { BaoFlatStoreComplete, /// Path to the node's [flat-file store](iroh::baomap::flat) for partial blobs. BaoFlatStorePartial, + /// Path to the [iroh-sync document database](iroh_sync::store::fs::Store) + DocsDatabase, } impl From<&IrohPaths> for &'static str { fn from(value: &IrohPaths) -> Self { @@ -39,6 +41,7 @@ impl From<&IrohPaths> for &'static str { IrohPaths::SecretKey => "keypair", IrohPaths::BaoFlatStoreComplete => "blobs.v0", IrohPaths::BaoFlatStorePartial => "blobs-partial.v0", + IrohPaths::DocsDatabase => "docs.redb", } } } @@ -49,6 +52,7 @@ impl FromStr for IrohPaths { "keypair" => Self::SecretKey, "blobs.v0" => Self::BaoFlatStoreComplete, "blobs-partial.v0" => Self::BaoFlatStorePartial, + "docs.redb" => Self::DocsDatabase, _ => bail!("unknown file or directory"), }) } @@ -259,9 +263,10 @@ mod tests { #[test] fn test_iroh_paths_parse_roundtrip() { let kinds = [ + IrohPaths::SecretKey, IrohPaths::BaoFlatStoreComplete, IrohPaths::BaoFlatStorePartial, - IrohPaths::SecretKey, + IrohPaths::DocsDatabase, ]; for iroh_path in &kinds { let root = PathBuf::from("/tmp"); diff --git a/iroh/src/download.rs b/iroh/src/download.rs new file mode 100644 index 0000000000..d7acb134b1 --- /dev/null +++ b/iroh/src/download.rs @@ -0,0 +1,386 @@ +//! Download queue + +#[cfg(feature = "metrics")] +use std::time::Instant; +use std::{ + collections::{HashMap, VecDeque}, + sync::Arc, +}; + +use anyhow::anyhow; +use futures::{ + future::{BoxFuture, LocalBoxFuture, Shared}, + stream::FuturesUnordered, + FutureExt, +}; +use iroh_bytes::{ + baomap::{MapEntry, Store as BaoStore}, + util::{progress::IgnoreProgressSender, Hash}, +}; +use iroh_gossip::net::util::Dialer; +#[cfg(feature = "metrics")] +use iroh_metrics::{inc, inc_by}; +use iroh_net::{key::PublicKey, MagicEndpoint}; +use tokio::sync::{oneshot, Mutex}; +use tokio_stream::StreamExt; +use tracing::{debug, error, warn}; + +#[cfg(feature = "metrics")] +use crate::metrics::Metrics; + +/// Future for the completion of a download request +pub type DownloadFuture = Shared>>; + +/// A download queue for iroh-bytes +/// +/// Spawns a background task that handles connecting to peers and performing get requests. +/// +/// TODO: Support retries and backoff - become a proper queue... +/// TODO: Support collections, likely become generic over C: CollectionParser +#[derive(Debug, Clone)] +pub struct Downloader { + pending_downloads: Arc>>, + to_actor_tx: flume::Sender, +} + +impl Downloader { + /// Create a new downloader + pub fn new( + rt: iroh_bytes::util::runtime::Handle, + endpoint: MagicEndpoint, + db: B, + ) -> Self { + let (tx, rx) = flume::bounded(64); + // spawn the actor on a local pool + // the local pool is required because WritableFileDatabase::download_single + // returns a future that is !Send + rt.local_pool().spawn_pinned(move || async move { + let mut actor = DownloadActor::new(endpoint, db, rx); + if let Err(err) = actor.run().await { + error!("download actor failed with error {err:?}"); + } + }); + Self { + pending_downloads: Arc::new(Mutex::new(HashMap::new())), + to_actor_tx: tx, + } + } + + /// Add a new download request to the download queue. + /// + /// Note: This method takes only [`PublicKey`]s and will attempt to connect to those peers. For + /// this to succeed, you need to add addresses for these peers to the magic endpoint's + /// addressbook yourself. See [`MagicEndpoint::add_known_addrs`]. + pub async fn push(&self, hash: Hash, peers: Vec) { + let (reply, reply_rx) = oneshot::channel(); + let req = DownloadRequest { hash, peers, reply }; + + if let Err(err) = self.to_actor_tx.send_async(req).await { + warn!("download actor dropped: {err}"); + } + + if self.pending_downloads.lock().await.get(&hash).is_none() { + let pending_downloads = self.pending_downloads.clone(); + let fut = async move { + let res = reply_rx.await; + pending_downloads.lock().await.remove(&hash); + res.ok().flatten() + }; + self.pending_downloads + .lock() + .await + .insert(hash, fut.boxed().shared()); + } + } + + /// Returns a future that completes once the blob for `hash` has been downloaded, or all queued + /// requests for that blob have failed. + /// + /// NOTE: This does not start the download itself. Use [`Self::push`] for that. + pub async fn finished(&self, hash: &Hash) -> DownloadFuture { + match self.pending_downloads.lock().await.get(hash) { + Some(fut) => fut.clone(), + None => futures::future::ready(None).boxed().shared(), + } + } +} + +type DownloadReply = oneshot::Sender>; +type PendingDownloadsFutures = + FuturesUnordered>)>>; + +#[derive(Debug)] +struct DownloadRequest { + hash: Hash, + peers: Vec, + reply: DownloadReply, +} + +#[derive(Debug)] +struct DownloadActor { + dialer: Dialer, + db: B, + conns: HashMap, + replies: HashMap>, + pending_download_futs: PendingDownloadsFutures, + queue: DownloadQueue, + rx: flume::Receiver, +} +impl DownloadActor { + fn new(endpoint: MagicEndpoint, db: B, rx: flume::Receiver) -> Self { + Self { + rx, + db, + dialer: Dialer::new(endpoint), + replies: Default::default(), + conns: Default::default(), + pending_download_futs: Default::default(), + queue: Default::default(), + } + } + pub async fn run(&mut self) -> anyhow::Result<()> { + loop { + tokio::select! { + req = self.rx.recv_async() => match req { + Err(_) => return Ok(()), + Ok(req) => self.on_download_request(req).await + }, + (peer, conn) = self.dialer.next() => match conn { + Ok(conn) => { + debug!(peer = ?peer, "connection established"); + self.conns.insert(peer, conn); + self.on_peer_ready(peer); + }, + Err(err) => self.on_peer_fail(&peer, err), + }, + Some((peer, hash, res)) = self.pending_download_futs.next() => match res { + Ok(Some(size)) => { + self.queue.on_success(hash, peer); + self.reply(hash, Some((hash, size))); + self.on_peer_ready(peer); + } + Ok(None) => { + // TODO: This case is currently never reached, because iroh::get::get_blob + // doesn't return an option but only a result, with no way (AFAICS) to discern + // between connection error and not found. + // self.on_not_found(&peer, hash); + // self.on_peer_ready(peer); + unreachable!() + } + Err(_err) => { + self.on_not_found(&peer, hash); + self.on_peer_ready(peer); + // TODO: In case of connection errors or similar we want to call + // on_peer_fail to not continue downloading from this peer. + // Currently however a "not found" is also an error, thus calling + // on_peer_fail would stop trying to get other hashes from this peer. + // This likely needs fixing in iroh::get::get to have a meaningful error to + // see if the connection failed or if it's just a "not found". + // self.on_peer_fail(&peer, err), + } + } + } + } + } + + fn reply(&mut self, hash: Hash, res: Option<(Hash, u64)>) { + for reply in self.replies.remove(&hash).into_iter().flatten() { + reply.send(res).ok(); + } + } + + fn on_peer_fail(&mut self, peer: &PublicKey, err: anyhow::Error) { + warn!("download from {peer} failed: {err:?}"); + for hash in self.queue.on_peer_fail(peer) { + self.reply(hash, None); + } + self.conns.remove(peer); + } + + fn on_not_found(&mut self, peer: &PublicKey, hash: Hash) { + self.queue.on_not_found(hash, *peer); + if self.queue.has_no_candidates(&hash) { + self.reply(hash, None); + } + } + + fn on_peer_ready(&mut self, peer: PublicKey) { + if let Some(hash) = self.queue.try_next_for_peer(peer) { + debug!(peer = ?peer, hash = ?hash, "on_peer_ready: get next"); + self.start_download_unchecked(peer, hash); + } else { + debug!(peer = ?peer, "on_peer_ready: nothing left, disconnect"); + self.conns.remove(&peer); + } + } + + fn start_download_unchecked(&mut self, peer: PublicKey, hash: Hash) { + let conn = self.conns.get(&peer).unwrap().clone(); + let db = self.db.clone(); + let progress_sender = IgnoreProgressSender::default(); + + let fut = async move { + debug!(peer = ?peer, hash = ?hash, "start download"); + + #[cfg(feature = "metrics")] + let start = Instant::now(); + + // TODO: None for not found instead of error + let res = crate::get::get_blob(&db, conn, &hash, progress_sender).await; + let res = res.and_then(|_stats| { + db.get(&hash) + .ok_or_else(|| anyhow!("downloaded blob not found in store")) + .map(|entry| Some(entry.size())) + }); + debug!(peer = ?peer, hash = ?hash, "finish download: {res:?}"); + + // record metrics + #[cfg(feature = "metrics")] + { + let elapsed = start.elapsed().as_millis(); + match &res { + Ok(Some(len)) => { + inc!(Metrics, downloads_success); + inc_by!(Metrics, download_bytes_total, *len); + inc_by!(Metrics, download_time_total, elapsed as u64); + } + Ok(None) => inc!(Metrics, downloads_notfound), + Err(_) => inc!(Metrics, downloads_error), + } + } + + (peer, hash, res) + }; + self.pending_download_futs.push(fut.boxed_local()); + } + + async fn on_download_request(&mut self, req: DownloadRequest) { + let DownloadRequest { peers, hash, reply } = req; + if let Some(entry) = self.db.get(&hash) { + let size = entry.size(); + reply.send(Some((hash, size))).ok(); + return; + } + self.replies.entry(hash).or_default().push_back(reply); + for peer in peers { + debug!(peer = ?peer, hash = ?hash, "queue download"); + self.queue.push_candidate(hash, peer); + // TODO: Don't dial all peers instantly. + if self.conns.get(&peer).is_none() && !self.dialer.is_pending(&peer) { + self.dialer.queue_dial(peer, &iroh_bytes::protocol::ALPN); + } + } + } +} + +#[derive(Debug, Default)] +struct DownloadQueue { + candidates_by_hash: HashMap>, + candidates_by_peer: HashMap>, + running_by_hash: HashMap, + running_by_peer: HashMap, +} + +impl DownloadQueue { + pub fn push_candidate(&mut self, hash: Hash, peer: PublicKey) { + self.candidates_by_hash + .entry(hash) + .or_default() + .push_back(peer); + self.candidates_by_peer + .entry(peer) + .or_default() + .push_back(hash); + } + + pub fn try_next_for_peer(&mut self, peer: PublicKey) -> Option { + let mut next = None; + for (idx, hash) in self.candidates_by_peer.get(&peer)?.iter().enumerate() { + if !self.running_by_hash.contains_key(hash) { + next = Some((idx, *hash)); + break; + } + } + if let Some((idx, hash)) = next { + self.running_by_hash.insert(hash, peer); + self.running_by_peer.insert(peer, hash); + self.candidates_by_peer.get_mut(&peer).unwrap().remove(idx); + if let Some(peers) = self.candidates_by_hash.get_mut(&hash) { + peers.retain(|p| p != &peer); + } + self.ensure_no_empty(hash, peer); + Some(hash) + } else { + None + } + } + + pub fn has_no_candidates(&self, hash: &Hash) -> bool { + self.candidates_by_hash.get(hash).is_none() && self.running_by_hash.get(hash).is_none() + } + + /// Mark a download as successfull. + pub fn on_success(&mut self, hash: Hash, peer: PublicKey) { + let peer2 = self.running_by_hash.remove(&hash); + debug_assert_eq!(peer2, Some(peer)); + self.running_by_peer.remove(&peer); + self.candidates_by_hash.remove(&hash); + for hashes in self.candidates_by_peer.values_mut() { + hashes.retain(|h| h != &hash); + } + self.ensure_no_empty(hash, peer); + } + + /// To be called when a peer failed (i.e. disconnected). + /// + /// Returns a list of hashes that have no other peers queue. Those hashes should thus be + /// considered failed. + pub fn on_peer_fail(&mut self, peer: &PublicKey) -> Vec { + let mut failed = vec![]; + for hash in self + .candidates_by_peer + .remove(peer) + .map(|hashes| hashes.into_iter()) + .into_iter() + .flatten() + { + if let Some(peers) = self.candidates_by_hash.get_mut(&hash) { + peers.retain(|p| p != peer); + if peers.is_empty() && self.running_by_hash.get(&hash).is_none() { + failed.push(hash); + } + } + } + if let Some(hash) = self.running_by_peer.remove(peer) { + self.running_by_hash.remove(&hash); + if self.candidates_by_hash.get(&hash).is_none() { + failed.push(hash); + } + } + failed + } + + pub fn on_not_found(&mut self, hash: Hash, peer: PublicKey) { + let peer2 = self.running_by_hash.remove(&hash); + debug_assert_eq!(peer2, Some(peer)); + self.running_by_peer.remove(&peer); + self.ensure_no_empty(hash, peer); + } + + fn ensure_no_empty(&mut self, hash: Hash, peer: PublicKey) { + if self + .candidates_by_peer + .get(&peer) + .map_or(false, |hashes| hashes.is_empty()) + { + self.candidates_by_peer.remove(&peer); + } + if self + .candidates_by_hash + .get(&hash) + .map_or(false, |peers| peers.is_empty()) + { + self.candidates_by_hash.remove(&hash); + } + } +} diff --git a/iroh/src/lib.rs b/iroh/src/lib.rs index b8a363921c..9f12a9fecf 100644 --- a/iroh/src/lib.rs +++ b/iroh/src/lib.rs @@ -3,14 +3,18 @@ pub use iroh_bytes as bytes; pub use iroh_net as net; +pub use iroh_sync as sync; pub mod baomap; +pub mod client; #[cfg(feature = "iroh-collection")] pub mod collection; pub mod dial; +pub mod download; pub mod get; pub mod node; pub mod rpc_protocol; +pub mod sync_engine; pub mod util; /// Expose metrics module diff --git a/iroh/src/main.rs b/iroh/src/main.rs index ce986cde08..441e3df973 100644 --- a/iroh/src/main.rs +++ b/iroh/src/main.rs @@ -8,7 +8,7 @@ mod commands; mod config; use crate::{ - commands::{init_metrics_collection, Cli}, + commands::{start_metrics_server, Cli}, config::{iroh_config_path, Config, CONFIG_FILE_NAME, ENV_PREFIX}, }; @@ -50,7 +50,7 @@ async fn main_impl() -> Result<()> { )?; #[cfg(feature = "metrics")] - let metrics_fut = init_metrics_collection(cli.metrics_addr, &rt); + let metrics_fut = start_metrics_server(cli.metrics_addr, &rt); let r = cli.run(&rt, &config).await; diff --git a/iroh/src/metrics.rs b/iroh/src/metrics.rs index 3b3b7f46ef..4dd559ba37 100644 --- a/iroh/src/metrics.rs +++ b/iroh/src/metrics.rs @@ -1,8 +1,12 @@ +use std::collections::HashMap; + use iroh_metrics::{ core::{Counter, Metric}, struct_iterable::Iterable, }; +use crate::rpc_protocol::CounterStats; + /// Enum of metrics for the module #[allow(missing_docs)] #[derive(Debug, Clone, Iterable)] @@ -10,6 +14,11 @@ pub struct Metrics { pub requests_total: Counter, pub bytes_sent: Counter, pub bytes_received: Counter, + pub download_bytes_total: Counter, + pub download_time_total: Counter, + pub downloads_success: Counter, + pub downloads_error: Counter, + pub downloads_notfound: Counter, } impl Default for Metrics { @@ -18,6 +27,11 @@ impl Default for Metrics { requests_total: Counter::new("Total number of requests received"), bytes_sent: Counter::new("Number of bytes streamed"), bytes_received: Counter::new("Number of bytes received"), + download_bytes_total: Counter::new("Total number of content bytes downloaded"), + download_time_total: Counter::new("Total time in ms spent downloading content bytes"), + downloads_success: Counter::new("Total number of successfull downloads"), + downloads_error: Counter::new("Total number of downloads failed with error"), + downloads_notfound: Counter::new("Total number of downloads failed with not found"), } } } @@ -27,3 +41,61 @@ impl Metric for Metrics { "Iroh" } } + +/// Initialize the global metrics collection. +/// +/// Will return an error if the global metrics collection was already initialized. +pub fn try_init_metrics_collection() -> std::io::Result<()> { + iroh_metrics::core::Core::try_init(|reg, metrics| { + metrics.insert(crate::metrics::Metrics::new(reg)); + metrics.insert(iroh_sync::metrics::Metrics::new(reg)); + metrics.insert(iroh_net::metrics::MagicsockMetrics::new(reg)); + metrics.insert(iroh_net::metrics::NetcheckMetrics::new(reg)); + metrics.insert(iroh_net::metrics::PortmapMetrics::new(reg)); + metrics.insert(iroh_net::metrics::DerpMetrics::new(reg)); + }) +} + +/// Collect the current metrics into a hash map. +/// +/// TODO: Only counters are supported for now, other metrics will be skipped without error. +pub fn get_metrics() -> anyhow::Result> { + let mut map = HashMap::new(); + let core = + iroh_metrics::core::Core::get().ok_or_else(|| anyhow::anyhow!("metrics are disabled"))?; + collect( + core.get_collector::(), + &mut map, + ); + collect( + core.get_collector::(), + &mut map, + ); + collect( + core.get_collector::(), + &mut map, + ); + collect( + core.get_collector::(), + &mut map, + ); + collect( + core.get_collector::(), + &mut map, + ); + Ok(map) +} + +// TODO: support other things than counters +fn collect(metrics: Option<&impl Iterable>, map: &mut HashMap) { + let Some(metrics) = metrics else { + return; + }; + for (name, counter) in metrics.iter() { + if let Some(counter) = counter.downcast_ref::() { + let value = counter.get(); + let description = counter.description.to_string(); + map.insert(name.to_string(), CounterStats { value, description }); + } + } +} diff --git a/iroh/src/node.rs b/iroh/src/node.rs index 337e1b880b..73c22f08ab 100644 --- a/iroh/src/node.rs +++ b/iroh/src/node.rs @@ -15,44 +15,56 @@ use std::sync::Arc; use std::task::Poll; use std::time::Duration; -use crate::dial::Ticket; -use crate::rpc_protocol::{ - AddrsRequest, AddrsResponse, IdRequest, IdResponse, ListBlobsRequest, ListBlobsResponse, - ListCollectionsRequest, ListCollectionsResponse, ListIncompleteBlobsRequest, - ListIncompleteBlobsResponse, ProvideRequest, ProviderRequest, ProviderResponse, - ProviderService, ShareRequest, ShutdownRequest, ValidateRequest, VersionRequest, - VersionResponse, WatchRequest, WatchResponse, -}; -use anyhow::{Context, Result}; +use anyhow::{anyhow, bail, Context, Result}; use bytes::Bytes; use futures::future::{BoxFuture, Shared}; use futures::{FutureExt, Stream, StreamExt, TryFutureExt}; -use iroh_bytes::baomap::{ExportMode, Map, MapEntry, ReadableStore, Store, ValidateProgress}; +use iroh_bytes::baomap::{ + ExportMode, Map, MapEntry, ReadableStore, Store as BaoStore, ValidateProgress, +}; use iroh_bytes::collection::{CollectionParser, NoCollectionParser}; use iroh_bytes::get::Stats; use iroh_bytes::protocol::GetRequest; use iroh_bytes::provider::ShareProgress; use iroh_bytes::util::progress::{FlumeProgressSender, IdGenerator, ProgressSender}; +use iroh_bytes::util::{RpcError, RpcResult}; use iroh_bytes::{ protocol::{Closed, Request, RequestToken}, provider::{CustomGetHandler, ProvideProgress, RequestAuthorizationHandler}, util::runtime, util::Hash, }; +use iroh_gossip::net::{Gossip, GOSSIP_ALPN}; +use iroh_io::AsyncSliceReaderExt; +use iroh_net::magic_endpoint::get_alpn; use iroh_net::{ config::Endpoint, derp::DerpMap, key::{PublicKey, SecretKey}, tls, MagicEndpoint, }; +use iroh_sync::store::Store as DocStore; +use once_cell::sync::OnceCell; use quic_rpc::server::RpcChannel; use quic_rpc::transport::flume::FlumeConnection; use quic_rpc::transport::misc::DummyServerEndpoint; -use quic_rpc::{RpcClient, RpcServer, ServiceConnection, ServiceEndpoint}; +use quic_rpc::{RpcClient, RpcServer, ServiceEndpoint}; use tokio::sync::{mpsc, RwLock}; use tokio::task::JoinError; use tokio_util::sync::CancellationToken; -use tracing::{debug, trace}; +use tracing::{debug, trace, warn}; + +use crate::dial::Ticket; +use crate::download::Downloader; +use crate::rpc_protocol::{ + AddrsRequest, AddrsResponse, BytesGetRequest, BytesGetResponse, IdRequest, IdResponse, + ListBlobsRequest, ListBlobsResponse, ListCollectionsRequest, ListCollectionsResponse, + ListIncompleteBlobsRequest, ListIncompleteBlobsResponse, ProvideRequest, ProviderRequest, + ProviderResponse, ProviderService, ShareRequest, ShutdownRequest, StatsGetRequest, + StatsGetResponse, ValidateRequest, VersionRequest, VersionResponse, WatchRequest, + WatchResponse, +}; +use crate::sync_engine::{SyncEngine, SYNC_ALPN}; const MAX_CONNECTIONS: u32 = 1024; const MAX_STREAMS: u64 = 10; @@ -75,9 +87,14 @@ const ENDPOINT_WAIT: Duration = Duration::from_secs(5); /// The returned [`Node`] is awaitable to know when it finishes. It can be terminated /// using [`Node::shutdown`]. #[derive(Debug)] -pub struct Builder -where +pub struct Builder< + D, + S = iroh_sync::store::memory::Store, + E = DummyServerEndpoint, + C = NoCollectionParser, +> where D: Map, + S: DocStore, E: ServiceEndpoint, C: CollectionParser, { @@ -91,9 +108,10 @@ where derp_map: Option, collection_parser: C, rt: Option, + docs: S, } -const PROTOCOLS: [&[u8]; 1] = [&iroh_bytes::protocol::ALPN]; +const PROTOCOLS: [&[u8]; 3] = [&iroh_bytes::protocol::ALPN, GOSSIP_ALPN, SYNC_ALPN]; /// A noop authorization handler that does not do any authorization. /// @@ -134,9 +152,9 @@ impl CustomGetHandler for NoopCustomGetHandler { } } -impl Builder { +impl Builder { /// Creates a new builder for [`Node`] using the given database. - fn with_db(db: D) -> Self { + fn with_db_and_store(db: D, docs: S) -> Self { Self { bind_addr: DEFAULT_BIND_ADDR.into(), secret_key: SecretKey::generate(), @@ -148,13 +166,15 @@ impl Builder { auth_handler: Arc::new(NoopRequestAuthorizationHandler), collection_parser: NoCollectionParser, rt: None, + docs, } } } -impl Builder +impl Builder where - D: Store, + D: BaoStore, + S: DocStore, E: ServiceEndpoint, C: CollectionParser, { @@ -162,7 +182,7 @@ where pub fn rpc_endpoint>( self, value: E2, - ) -> Builder { + ) -> Builder { // we can't use ..self here because the return type is different Builder { bind_addr: self.bind_addr, @@ -175,6 +195,7 @@ where derp_map: self.derp_map, collection_parser: self.collection_parser, rt: self.rt, + docs: self.docs, } } @@ -182,7 +203,7 @@ where pub fn collection_parser( self, collection_parser: C2, - ) -> Builder { + ) -> Builder { // we can't use ..self here because the return type is different Builder { collection_parser, @@ -195,6 +216,7 @@ where rpc_endpoint: self.rpc_endpoint, derp_map: self.derp_map, rt: self.rt, + docs: self.docs, } } @@ -257,16 +279,29 @@ where /// This will create the underlying network server and spawn a tokio task accepting /// connections. The returned [`Node`] can be used to control the task as well as /// get information about it. - pub async fn spawn(self) -> Result> { + pub async fn spawn(self) -> Result> { trace!("spawning node"); let rt = self.rt.context("runtime not set")?; + // Initialize the metrics collection. + // + // The metrics are global per process. Subsequent calls do not change the metrics + // collection and will return an error. We ignore this error. This means that if you'd + // spawn multiple Iroh nodes in the same process, the metrics would be shared between the + // nodes. + #[cfg(feature = "metrics")] + crate::metrics::try_init_metrics_collection().ok(); + let (endpoints_update_s, endpoints_update_r) = flume::bounded(1); let mut transport_config = quinn::TransportConfig::default(); transport_config .max_concurrent_bidi_streams(MAX_STREAMS.try_into()?) .max_concurrent_uni_streams(0u32.into()); + // init a cell that will hold our gossip handle to be used in endpoint callbacks + let gossip_cell: OnceCell = OnceCell::new(); + let gossip_cell2 = gossip_cell.clone(); + let endpoint = MagicEndpoint::builder() .secret_key(self.secret_key.clone()) .alpns(PROTOCOLS.iter().map(|p| p.to_vec()).collect()) @@ -275,7 +310,14 @@ where .transport_config(transport_config) .concurrent_connections(MAX_CONNECTIONS) .on_endpoints(Box::new(move |eps| { - if !endpoints_update_s.is_disconnected() && !eps.is_empty() { + if eps.is_empty() { + return; + } + // send our updated endpoints to the gossip protocol to be sent as PeerData to peers + if let Some(gossip) = gossip_cell2.get() { + gossip.update_endpoints(eps).ok(); + } + if !endpoints_update_s.is_disconnected() { endpoints_update_s.send(()).ok(); } })) @@ -287,6 +329,23 @@ where let cancel_token = CancellationToken::new(); debug!("rpc listening on: {:?}", self.rpc_endpoint.local_addr()); + + // initialize the gossip protocol + let gossip = Gossip::from_endpoint(endpoint.clone(), Default::default()); + // insert into the gossip cell to be used in the endpoint callbacks above + gossip_cell.set(gossip.clone()).unwrap(); + + // spawn the sync engine + let downloader = Downloader::new(rt.clone(), endpoint.clone(), self.db.clone()); + let sync = SyncEngine::spawn( + rt.clone(), + endpoint.clone(), + gossip.clone(), + self.docs, + self.db.clone(), + downloader, + ); + let (internal_rpc, controller) = quic_rpc::transport::flume::connection(1); let rt2 = rt.clone(); let rt3 = rt.clone(); @@ -300,6 +359,7 @@ where callbacks: callbacks.clone(), cb_sender, rt, + sync, }); let task = { let handler = RpcHandler { @@ -318,6 +378,7 @@ where self.auth_handler, self.collection_parser, rt3, + gossip, ) .await }) @@ -343,13 +404,14 @@ where server: MagicEndpoint, callbacks: Callbacks, mut cb_receiver: mpsc::Receiver, - handler: RpcHandler, + handler: RpcHandler, rpc: E, internal_rpc: impl ServiceEndpoint, custom_get_handler: Arc, auth_handler: Arc, collection_parser: C, rt: runtime::Handle, + gossip: Gossip, ) { let rpc = RpcServer::new(rpc); let internal_rpc = RpcServer::new(internal_rpc); @@ -362,6 +424,16 @@ where } let cancel_token = handler.inner.cancel_token.clone(); + // forward our initial endpoints to the gossip protocol + // it may happen the the first endpoint update callback is missed because the gossip cell + // is only initialized once the endpoint is fully bound + if let Ok(local_endpoints) = server.local_endpoints().await { + if !local_endpoints.is_empty() { + debug!(me = ?server.peer_id(), "gossip initial update: {local_endpoints:?}"); + gossip.update_endpoints(&local_endpoints).ok(); + } + } + loop { tokio::select! { biased; @@ -392,7 +464,6 @@ where }, // handle incoming p2p connections Some(mut connecting) = server.accept() => { - let alpn = match get_alpn(&mut connecting).await { Ok(alpn) => alpn, Err(err) => { @@ -400,19 +471,17 @@ where continue; } }; - if alpn.as_bytes() == iroh_bytes::protocol::ALPN.as_ref() { - let db = handler.inner.db.clone(); - let custom_get_handler = custom_get_handler.clone(); - let auth_handler = auth_handler.clone(); - let collection_parser = collection_parser.clone(); - let rt2 = rt.clone(); - let callbacks = callbacks.clone(); - rt.main().spawn(iroh_bytes::provider::handle_connection(connecting, db, callbacks, collection_parser, custom_get_handler, auth_handler, rt2)); - } else { - tracing::error!("unknown protocol: {}", alpn); - continue; - } - } + let gossip = gossip.clone(); + let inner = handler.inner.clone(); + let collection_parser = collection_parser.clone(); + let custom_get_handler = custom_get_handler.clone(); + let auth_handler = auth_handler.clone(); + rt.main().spawn(async move { + if let Err(err) = handle_connection(connecting, alpn, inner, gossip, collection_parser, custom_get_handler, auth_handler).await { + warn!("Handling incoming connection ended with error: {err}"); + } + }); + }, // Handle new callbacks Some(cb) = cb_receiver.recv() => { callbacks.push(cb).await; @@ -433,15 +502,33 @@ where } } -async fn get_alpn(connecting: &mut quinn::Connecting) -> Result { - let data = connecting.handshake_data().await?; - match data.downcast::() { - Ok(data) => match data.protocol { - Some(protocol) => std::string::String::from_utf8(protocol).map_err(Into::into), - None => anyhow::bail!("no ALPN protocol available"), - }, - Err(_) => anyhow::bail!("unknown handshake type"), +async fn handle_connection( + connecting: quinn::Connecting, + alpn: String, + node: Arc>, + gossip: Gossip, + collection_parser: C, + custom_get_handler: Arc, + auth_handler: Arc, +) -> Result<()> { + match alpn.as_bytes() { + GOSSIP_ALPN => gossip.handle_connection(connecting.await?).await?, + SYNC_ALPN => iroh_sync::net::handle_connection(connecting, node.sync.store.clone()).await?, + alpn if alpn == iroh_bytes::protocol::ALPN => { + iroh_bytes::provider::handle_connection( + connecting, + node.db.clone(), + node.callbacks.clone(), + collection_parser, + custom_get_handler, + auth_handler, + node.rt.clone(), + ) + .await + } + _ => bail!("ignoring connection: unsupported ALPN protocol"), } + Ok(()) } type EventCallback = Box BoxFuture<'static, ()> + 'static + Sync + Send>; @@ -486,13 +573,13 @@ impl iroh_bytes::provider::EventSender for Callbacks { /// await the [`Node`] struct directly, it will complete when the task completes. If /// this is dropped the node task is not stopped but keeps running. #[derive(Debug, Clone)] -pub struct Node { - inner: Arc>, +pub struct Node { + inner: Arc>, task: Shared>>>, } #[derive(derive_more::Debug)] -struct NodeInner { +struct NodeInner { db: D, endpoint: MagicEndpoint, secret_key: SecretKey, @@ -503,6 +590,7 @@ struct NodeInner { #[allow(dead_code)] callbacks: Callbacks, rt: runtime::Handle, + pub(crate) sync: SyncEngine, } /// Events emitted by the [`Node`] informing about the current status. @@ -512,12 +600,12 @@ pub enum Event { ByteProvide(iroh_bytes::provider::Event), } -impl Node { +impl Node { /// Returns a new builder for the [`Node`]. /// /// Once the done with the builder call [`Builder::spawn`] to create the node. - pub fn builder(db: D) -> Builder { - Builder::with_db(db) + pub fn builder(bao_store: D, doc_store: S) -> Builder { + Builder::with_db_and_store(bao_store, doc_store) } /// The address on which the node socket is bound. @@ -557,12 +645,15 @@ impl Node { } /// Returns a handle that can be used to do RPC calls to the node internally. - pub fn controller( - &self, - ) -> RpcClient> { + pub fn controller(&self) -> crate::client::mem::RpcClient { RpcClient::new(self.inner.controller.clone()) } + /// Return a client to control this node over an in-memory channel. + pub fn client(&self) -> crate::client::mem::Iroh { + crate::client::Iroh::new(self.controller()) + } + /// Return a single token containing everything needed to get a hash. /// /// See [`Ticket`] for more details of how it can be used. @@ -595,7 +686,7 @@ impl Node { } } -impl NodeInner { +impl NodeInner { async fn local_endpoints(&self) -> Result> { self.endpoint.local_endpoints().await } @@ -616,7 +707,7 @@ impl NodeInner { } /// The future completes when the spawned tokio task finishes. -impl Future for Node { +impl Future for Node { type Output = Result<(), Arc>; fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll { @@ -625,12 +716,12 @@ impl Future for Node { } #[derive(Debug, Clone)] -struct RpcHandler { - inner: Arc>, +struct RpcHandler { + inner: Arc>, collection_parser: C, } -impl RpcHandler { +impl RpcHandler { fn rt(&self) -> runtime::Handle { self.inner.rt.clone() } @@ -775,7 +866,6 @@ impl RpcHandler { { use crate::collection::{Blob, Collection}; use crate::util::io::pathbuf_from_name; - use iroh_io::AsyncSliceReaderExt; tracing::trace!("exporting collection {} to {}", hash, path.display()); tokio::fs::create_dir_all(&path).await?; let collection = db.get(&hash).context("collection not there")?; @@ -968,6 +1058,18 @@ impl RpcHandler { anyhow::bail!("collections not supported"); } + async fn stats(self, _req: StatsGetRequest) -> RpcResult { + #[cfg(feature = "metrics")] + let res = Ok(StatsGetResponse { + stats: crate::metrics::get_metrics()?, + }); + + #[cfg(not(feature = "metrics"))] + let res = Err(anyhow::anyhow!("metrics are disabled").into()); + + res + } + async fn version(self, _: VersionRequest) -> VersionResponse { VersionResponse { version: env!("CARGO_PKG_VERSION").to_string(), @@ -1014,12 +1116,42 @@ impl RpcHandler { )) }) } + + // TODO: streaming + async fn bytes_get(self, req: BytesGetRequest) -> RpcResult { + let entry = self + .inner + .db + .get(&req.hash) + .ok_or_else(|| RpcError::from(anyhow!("not found")))?; + // TODO: size limit + // TODO: streaming + let data = self.inner.rt.local_pool().spawn_pinned(|| async move { + let data = entry + .data_reader() + .await + .map_err(anyhow::Error::from)? + .read_to_end() + .await + .map_err(anyhow::Error::from)?; + Result::<_, anyhow::Error>::Ok(data) + }); + let data = data + .await + .map_err(|_err| anyhow::anyhow!("task failed to complete"))??; + Ok(BytesGetResponse { data }) + } } -fn handle_rpc_request, C: CollectionParser>( +fn handle_rpc_request< + D: BaoStore, + S: DocStore, + E: ServiceEndpoint, + C: CollectionParser, +>( msg: ProviderRequest, chan: RpcChannel, - handler: &RpcHandler, + handler: &RpcHandler, rt: &runtime::Handle, ) { let handler = handler.clone(); @@ -1053,10 +1185,87 @@ fn handle_rpc_request, C: Collecti Id(msg) => chan.rpc(msg, handler, RpcHandler::id).await, Addrs(msg) => chan.rpc(msg, handler, RpcHandler::addrs).await, Shutdown(msg) => chan.rpc(msg, handler, RpcHandler::shutdown).await, + Stats(msg) => chan.rpc(msg, handler, RpcHandler::stats).await, Validate(msg) => { chan.server_streaming(msg, handler, RpcHandler::validate) .await } + AuthorList(msg) => { + chan.server_streaming(msg, handler, |handler, req| { + handler.inner.sync.author_list(req) + }) + .await + } + AuthorCreate(msg) => { + chan.rpc(msg, handler, |handler, req| async move { + handler.inner.sync.author_create(req) + }) + .await + } + AuthorImport(_msg) => { + todo!() + } + DocInfo(msg) => { + chan.rpc(msg, handler, |handler, req| async move { + handler.inner.sync.doc_info(req).await + }) + .await + } + DocList(msg) => { + chan.server_streaming(msg, handler, |handler, req| { + handler.inner.sync.doc_list(req) + }) + .await + } + DocCreate(msg) => { + chan.rpc(msg, handler, |handler, req| async move { + handler.inner.sync.doc_create(req) + }) + .await + } + DocImport(msg) => { + chan.rpc(msg, handler, |handler, req| async move { + handler.inner.sync.doc_import(req).await + }) + .await + } + DocSet(msg) => { + let bao_store = handler.inner.db.clone(); + chan.rpc(msg, handler, |handler, req| async move { + handler.inner.sync.doc_set(&bao_store, req).await + }) + .await + } + DocGet(msg) => { + chan.server_streaming(msg, handler, |handler, req| handler.inner.sync.doc_get(req)) + .await + } + DocStartSync(msg) => { + chan.rpc(msg, handler, |handler, req| async move { + handler.inner.sync.doc_start_sync(req).await + }) + .await + } + DocStopSync(msg) => { + chan.rpc(msg, handler, |handler, req| async move { + handler.inner.sync.doc_stop_sync(req).await + }) + .await + } + DocShare(msg) => { + chan.rpc(msg, handler, |handler, req| async move { + handler.inner.sync.doc_share(req).await + }) + .await + } + DocSubscribe(msg) => { + chan.server_streaming(msg, handler, |handler, req| { + async move { handler.inner.sync.doc_subscribe(req).await }.flatten_stream() + }) + .await + } + // TODO: make streaming + BytesGet(msg) => chan.rpc(msg, handler, RpcHandler::bytes_get).await, } }); } @@ -1153,8 +1362,9 @@ mod tests { async fn test_ticket_multiple_addrs() { let rt = test_runtime(); let (db, hashes) = crate::baomap::readonly_mem::Store::new([("test", b"hello")]); + let doc_store = iroh_sync::store::memory::Store::default(); let hash = hashes["test"].into(); - let node = Node::builder(db) + let node = Node::builder(db, doc_store) .bind_addr((Ipv4Addr::UNSPECIFIED, 0).into()) .runtime(&rt) .spawn() @@ -1171,7 +1381,8 @@ mod tests { async fn test_node_add_collection_event() -> Result<()> { let rt = runtime::Handle::from_currrent(1)?; let db = crate::baomap::mem::Store::new(rt); - let node = Node::builder(db) + let doc_store = iroh_sync::store::memory::Store::default(); + let node = Node::builder(db, doc_store) .bind_addr((Ipv4Addr::UNSPECIFIED, 0).into()) .runtime(&test_runtime()) .spawn() diff --git a/iroh/src/rpc_protocol.rs b/iroh/src/rpc_protocol.rs index 275e405ebe..d5ca45fb41 100644 --- a/iroh/src/rpc_protocol.rs +++ b/iroh/src/rpc_protocol.rs @@ -7,19 +7,30 @@ //! response, while others like provide have a stream of responses. //! //! Note that this is subject to change. The RPC protocol is not yet stable. -use std::{net::SocketAddr, path::PathBuf}; +use std::{collections::HashMap, fmt, net::SocketAddr, path::PathBuf, str::FromStr}; +use bytes::Bytes; use derive_more::{From, TryInto}; use iroh_bytes::{protocol::RequestToken, provider::ShareProgress, Hash}; +use iroh_gossip::proto::util::base32; use iroh_net::key::PublicKey; +use iroh_sync::{ + store::GetFilter, + sync::{AuthorId, NamespaceId, SignedEntry}, +}; use quic_rpc::{ message::{Msg, RpcMsg, ServerStreaming, ServerStreamingMsg}, Service, }; use serde::{Deserialize, Serialize}; -pub use iroh_bytes::{baomap::ValidateProgress, provider::ProvideProgress}; +pub use iroh_bytes::{baomap::ValidateProgress, provider::ProvideProgress, util::RpcResult}; + +use crate::sync_engine::{LiveEvent, LiveStatus, PeerSource}; + +/// A 32-byte key or token +pub type KeyBytes = [u8; 32]; /// A request to the node to provide the data at the given path /// @@ -256,6 +267,341 @@ pub struct VersionResponse { pub version: String, } +// author + +/// List document authors for which we have a secret key. +#[derive(Serialize, Deserialize, Debug)] +pub struct AuthorListRequest {} + +impl Msg for AuthorListRequest { + type Pattern = ServerStreaming; +} + +impl ServerStreamingMsg for AuthorListRequest { + type Response = RpcResult; +} + +/// Response for [`AuthorListRequest`] +#[derive(Serialize, Deserialize, Debug)] +pub struct AuthorListResponse { + /// The author id + pub author_id: AuthorId, +} + +/// Create a new document author. +#[derive(Serialize, Deserialize, Debug)] +pub struct AuthorCreateRequest; + +impl RpcMsg for AuthorCreateRequest { + type Response = RpcResult; +} + +/// Response for [`AuthorCreateRequest`] +#[derive(Serialize, Deserialize, Debug)] +pub struct AuthorCreateResponse { + /// The id of the created author + pub author_id: AuthorId, +} + +/// Import author from secret key +#[derive(Serialize, Deserialize, Debug)] +pub struct AuthorImportRequest { + /// The secret key for the author + pub key: KeyBytes, +} + +impl RpcMsg for AuthorImportRequest { + type Response = RpcResult; +} + +/// Response to [`AuthorImportRequest`] +#[derive(Serialize, Deserialize, Debug)] +pub struct AuthorImportResponse { + /// The author id of the imported author + pub author_id: AuthorId, +} + +/// Intended capability for document share tickets +#[derive(Serialize, Deserialize, Debug, Clone)] +#[cfg_attr(feature = "cli", derive(clap::ValueEnum))] +pub enum ShareMode { + /// Read-only access + Read, + /// Write access + Write, +} + +/// Subscribe to events for a document. +#[derive(Serialize, Deserialize, Debug)] +pub struct DocSubscribeRequest { + /// The document id + pub doc_id: NamespaceId, +} + +impl Msg for DocSubscribeRequest { + type Pattern = ServerStreaming; +} + +impl ServerStreamingMsg for DocSubscribeRequest { + type Response = RpcResult; +} + +/// Response to [`DocSubscribeRequest`] +#[derive(Serialize, Deserialize, Debug)] +pub struct DocSubscribeResponse { + /// The event that occured on the document + pub event: LiveEvent, +} + +/// List all documents +#[derive(Serialize, Deserialize, Debug)] +pub struct DocListRequest {} + +impl Msg for DocListRequest { + type Pattern = ServerStreaming; +} + +impl ServerStreamingMsg for DocListRequest { + type Response = RpcResult; +} + +/// Response to [`DocListRequest`] +#[derive(Serialize, Deserialize, Debug)] +pub struct DocListResponse { + /// The document id + pub id: NamespaceId, +} + +/// Create a new document +#[derive(Serialize, Deserialize, Debug)] +pub struct DocCreateRequest {} + +impl RpcMsg for DocCreateRequest { + type Response = RpcResult; +} + +/// Response to [`DocCreateRequest`] +#[derive(Serialize, Deserialize, Debug)] +pub struct DocCreateResponse { + /// The document id + pub id: NamespaceId, +} + +/// Contains both a key (either secret or public) to a document, and a list of peers to join. +#[derive(Serialize, Deserialize, Clone, Debug)] +pub struct DocTicket { + /// either a public or private key + pub key: KeyBytes, + /// a list of peers + pub peers: Vec, +} +impl DocTicket { + /// Create a new doc ticket + pub fn new(key: KeyBytes, peers: Vec) -> Self { + Self { key, peers } + } + /// Serialize the ticket to a byte array. + pub fn to_bytes(&self) -> anyhow::Result> { + let bytes = postcard::to_stdvec(&self)?; + Ok(bytes) + } + /// Parse ticket from a byte array. + pub fn from_bytes(bytes: &[u8]) -> anyhow::Result { + let slf = postcard::from_bytes(bytes)?; + Ok(slf) + } +} +impl FromStr for DocTicket { + type Err = anyhow::Error; + fn from_str(s: &str) -> Result { + Self::from_bytes(&base32::parse_vec(s)?) + } +} +impl fmt::Display for DocTicket { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{}", + base32::fmt(self.to_bytes().expect("failed to serialize")) + ) + } +} + +/// Import a document from a ticket. +#[derive(Serialize, Deserialize, Debug)] +pub struct DocImportRequest(pub DocTicket); + +impl RpcMsg for DocImportRequest { + type Response = RpcResult; +} + +/// Response to [`DocImportRequest`] +#[derive(Serialize, Deserialize, Debug)] +pub struct DocImportResponse { + /// the document id + pub doc_id: NamespaceId, +} + +/// Share a document with peers over a ticket. +#[derive(Serialize, Deserialize, Debug)] +pub struct DocShareRequest { + /// The document id + pub doc_id: NamespaceId, + /// Whether to share read or write access to the document + pub mode: ShareMode, +} + +impl RpcMsg for DocShareRequest { + type Response = RpcResult; +} + +/// The response to [`DocShareRequest`] +#[derive(Serialize, Deserialize, Debug)] +pub struct DocShareResponse(pub DocTicket); + +/// Get info on a document +#[derive(Serialize, Deserialize, Debug)] +pub struct DocInfoRequest { + /// The document id + pub doc_id: NamespaceId, +} + +impl RpcMsg for DocInfoRequest { + type Response = RpcResult; +} + +/// Response to [`DocInfoRequest`] +// TODO: actually provide info +#[derive(Serialize, Deserialize, Debug)] +pub struct DocInfoResponse { + /// Live sync status + pub status: LiveStatus, +} + +/// Start to sync a doc with peers. +#[derive(Serialize, Deserialize, Debug)] +pub struct DocStartSyncRequest { + /// The document id + pub doc_id: NamespaceId, + /// List of peers to join + pub peers: Vec, +} + +impl RpcMsg for DocStartSyncRequest { + type Response = RpcResult; +} + +/// Response to [`DocStartSyncRequest`] +#[derive(Serialize, Deserialize, Debug)] +pub struct DocStartSyncResponse {} + +/// Stop the live sync for a doc. +#[derive(Serialize, Deserialize, Debug)] +pub struct DocStopSyncRequest { + /// The document id + pub doc_id: NamespaceId, +} + +impl RpcMsg for DocStopSyncRequest { + type Response = RpcResult; +} + +/// Response to [`DocStopSyncRequest`] +#[derive(Serialize, Deserialize, Debug)] +pub struct DocStopSyncResponse {} + +/// Set an entry in a document +#[derive(Serialize, Deserialize, Debug)] +pub struct DocSetRequest { + /// The document id + pub doc_id: NamespaceId, + /// Author of this entry. + pub author_id: AuthorId, + /// Key of this entry. + pub key: Vec, + /// Value of this entry. + // TODO: Allow to provide the hash directly + // TODO: Add a way to provide content as stream + pub value: Vec, +} + +impl RpcMsg for DocSetRequest { + type Response = RpcResult; +} + +/// Response to [`DocSetRequest`] +#[derive(Serialize, Deserialize, Debug)] +pub struct DocSetResponse { + /// The newly-created entry. + pub entry: SignedEntry, +} + +/// Get entries from a document +#[derive(Serialize, Deserialize, Debug)] +pub struct DocGetRequest { + /// The document id + pub doc_id: NamespaceId, + /// Filter entries by this [`GetFilter`] + pub filter: GetFilter, +} + +impl Msg for DocGetRequest { + type Pattern = ServerStreaming; +} + +impl ServerStreamingMsg for DocGetRequest { + type Response = RpcResult; +} + +/// Response to [`DocGetRequest`] +#[derive(Serialize, Deserialize, Debug)] +pub struct DocGetResponse { + /// The document entry + pub entry: SignedEntry, +} + +/// Get the bytes for a hash +#[derive(Serialize, Deserialize, Debug)] +pub struct BytesGetRequest { + /// Hash to get bytes for + pub hash: Hash, +} + +impl RpcMsg for BytesGetRequest { + type Response = RpcResult; +} + +/// Response to [`BytesGetRequest`] +#[derive(Serialize, Deserialize, Debug)] +pub struct BytesGetResponse { + /// The blob data + pub data: Bytes, +} + +/// Get stats for the running Iroh node +#[derive(Serialize, Deserialize, Debug)] +pub struct StatsGetRequest {} + +impl RpcMsg for StatsGetRequest { + type Response = RpcResult; +} + +/// Counter stats +#[derive(Serialize, Deserialize, Debug)] +pub struct CounterStats { + /// The counter value + pub value: u64, + /// The counter description + pub description: String, +} + +/// Response to [`StatsGetRequest`] +#[derive(Serialize, Deserialize, Debug)] +pub struct StatsGetResponse { + /// Map of statistics + pub stats: HashMap, +} + /// The RPC service for the iroh provider process. #[derive(Debug, Clone)] pub struct ProviderService; @@ -275,10 +621,31 @@ pub enum ProviderRequest { Addrs(AddrsRequest), Shutdown(ShutdownRequest), Validate(ValidateRequest), + + // TODO: I see I changed naming convention here but at least to me it becomes easier to parse + // with the subject in front if there's many commands + AuthorList(AuthorListRequest), + AuthorCreate(AuthorCreateRequest), + AuthorImport(AuthorImportRequest), + + DocInfo(DocInfoRequest), + DocList(DocListRequest), + DocCreate(DocCreateRequest), + DocImport(DocImportRequest), + DocSet(DocSetRequest), + DocGet(DocGetRequest), + DocStartSync(DocStartSyncRequest), + DocStopSync(DocStopSyncRequest), + DocShare(DocShareRequest), + DocSubscribe(DocSubscribeRequest), + + BytesGet(BytesGetRequest), + + Stats(StatsGetRequest), } /// The response enum, listing all possible responses. -#[allow(missing_docs)] +#[allow(missing_docs, clippy::large_enum_variant)] #[derive(Debug, Serialize, Deserialize, From, TryInto)] pub enum ProviderResponse { Watch(WatchResponse), @@ -292,6 +659,25 @@ pub enum ProviderResponse { Addrs(AddrsResponse), Validate(ValidateProgress), Shutdown(()), + + AuthorList(RpcResult), + AuthorCreate(RpcResult), + AuthorImport(RpcResult), + + DocInfo(RpcResult), + DocList(RpcResult), + DocCreate(RpcResult), + DocImport(RpcResult), + DocSet(RpcResult), + DocGet(RpcResult), + DocShare(RpcResult), + DocStartSync(RpcResult), + DocStopSync(RpcResult), + DocSubscribe(RpcResult), + + BytesGet(RpcResult), + + Stats(RpcResult), } impl Service for ProviderService { diff --git a/iroh/src/sync_engine.rs b/iroh/src/sync_engine.rs new file mode 100644 index 0000000000..8646ce6f82 --- /dev/null +++ b/iroh/src/sync_engine.rs @@ -0,0 +1,111 @@ +//! Handlers and actors to for live syncing [`iroh_sync`] replicas. +//! +//! [`iroh_sync::Replica`] is also called documents here. + +use std::{collections::HashSet, sync::Arc}; + +use anyhow::anyhow; +use iroh_bytes::{baomap::Store as BaoStore, util::runtime::Handle}; +use iroh_gossip::net::Gossip; +use iroh_net::MagicEndpoint; +use iroh_sync::{ + store::Store, + sync::{Author, AuthorId, NamespaceId, Replica}, +}; +use parking_lot::RwLock; + +use crate::download::Downloader; + +mod live; +pub mod rpc; + +pub use iroh_sync::net::SYNC_ALPN; +pub use live::*; + +/// The SyncEngine contains the [`LiveSync`] handle, and keeps a copy of the store and endpoint. +/// +/// The RPC methods dealing with documents and sync operate on the `SyncEngine`, with method +/// implementations in [rpc]. +#[derive(Debug, Clone)] +pub struct SyncEngine { + pub(crate) rt: Handle, + pub(crate) store: S, + pub(crate) endpoint: MagicEndpoint, + pub(crate) live: LiveSync, + active: Arc>>, +} + +impl SyncEngine { + /// Start the sync engine. + /// + /// This will spawn a background task for the [`LiveSync`]. When documents are added to the + /// engine with [`Self::start_sync`], then new entries inserted locally will be sent to peers + /// through iroh-gossip. + /// + /// The engine will also register for [`Replica::subscribe`] events to download content for new + /// entries from peers. + pub fn spawn( + rt: Handle, + endpoint: MagicEndpoint, + gossip: Gossip, + store: S, + bao_store: B, + downloader: Downloader, + ) -> Self { + let live = LiveSync::spawn(rt.clone(), endpoint.clone(), gossip, bao_store, downloader); + Self { + live, + store, + rt, + endpoint, + active: Default::default(), + } + } + + /// Start to sync a document. + /// + /// If `peers` is non-empty, it will both do an initial set-reconciliation sync with each peer, + /// and join an iroh-gossip swarm with these peers to receive and broadcast document updates. + pub async fn start_sync( + &self, + namespace: NamespaceId, + peers: Vec, + ) -> anyhow::Result<()> { + if !self.active.read().contains(&namespace) { + let replica = self.get_replica(&namespace)?; + self.live.start_sync(replica, peers).await?; + self.active.write().insert(namespace); + } else if !peers.is_empty() { + self.live.join_peers(namespace, peers).await?; + } + Ok(()) + } + + /// Stop syncing a document. + pub async fn stop_sync(&self, namespace: NamespaceId) -> anyhow::Result<()> { + let replica = self.get_replica(&namespace)?; + self.active.write().remove(&replica.namespace()); + self.live.stop_sync(namespace).await?; + Ok(()) + } + + /// Shutdown the sync engine. + pub async fn shutdown(&self) -> anyhow::Result<()> { + self.live.shutdown().await?; + Ok(()) + } + + /// Get a [`Replica`] from the store, returning an error if the replica does not exist. + pub fn get_replica(&self, id: &NamespaceId) -> anyhow::Result> { + self.store + .open_replica(id)? + .ok_or_else(|| anyhow!("doc not found")) + } + + /// Get an [`Author`] from the store, returning an error if the replica does not exist. + pub fn get_author(&self, id: &AuthorId) -> anyhow::Result { + self.store + .get_author(id)? + .ok_or_else(|| anyhow!("author not found")) + } +} diff --git a/iroh/src/sync_engine/live.rs b/iroh/src/sync_engine/live.rs new file mode 100644 index 0000000000..e7dda80110 --- /dev/null +++ b/iroh/src/sync_engine/live.rs @@ -0,0 +1,711 @@ +use std::{ + collections::HashMap, + fmt, + net::SocketAddr, + str::FromStr, + sync::{atomic::AtomicU64, Arc}, +}; + +use crate::download::Downloader; +use anyhow::{anyhow, bail, Result}; +use futures::{ + future::{BoxFuture, Shared}, + stream::{BoxStream, FuturesUnordered, StreamExt}, + FutureExt, TryFutureExt, +}; +use iroh_bytes::{ + baomap::{self, EntryStatus}, + util::runtime::Handle, + Hash, +}; +use iroh_gossip::{ + net::{Event, Gossip}, + proto::TopicId, +}; +use iroh_net::{key::PublicKey, MagicEndpoint}; +use iroh_sync::{ + net::connect_and_sync, + store, + sync::{Entry, InsertOrigin, NamespaceId, Replica, SignedEntry}, +}; +use serde::{Deserialize, Serialize}; +use tokio::{ + sync::{self, mpsc}, + task::JoinError, +}; +use tracing::{debug, error, info, warn}; + +const CHANNEL_CAP: usize = 8; + +/// The address to connect to a peer +// TODO: Move into iroh-net +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct PeerSource { + /// The peer id (required) + pub peer_id: PublicKey, + /// Socket addresses for this peer (may be empty) + pub addrs: Vec, + /// Derp region for this peer + pub derp_region: Option, +} + +impl PeerSource { + /// Deserializes from bytes. + fn from_bytes(bytes: &[u8]) -> anyhow::Result { + postcard::from_bytes(bytes).map_err(Into::into) + } + /// Serializes to bytes. + pub fn to_bytes(&self) -> Vec { + postcard::to_stdvec(self).expect("postcard::to_stdvec is infallible") + } + /// Create with information gathered from a [`MagicEndpoint`] + pub async fn from_endpoint(endpoint: &MagicEndpoint) -> anyhow::Result { + Ok(Self { + peer_id: endpoint.peer_id(), + derp_region: endpoint.my_derp().await, + addrs: endpoint + .local_endpoints() + .await? + .into_iter() + .map(|ep| ep.addr) + .collect(), + }) + } +} + +/// Serializes to base32. +impl fmt::Display for PeerSource { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let encoded = self.to_bytes(); + let mut text = data_encoding::BASE32_NOPAD.encode(&encoded); + text.make_ascii_lowercase(); + write!(f, "{text}") + } +} + +/// Deserializes from base32. +impl FromStr for PeerSource { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + let bytes = data_encoding::BASE32_NOPAD.decode(s.to_ascii_uppercase().as_bytes())?; + let slf = Self::from_bytes(&bytes)?; + Ok(slf) + } +} + +/// An iroh-sync operation +/// +/// This is the message that is broadcast over iroh-gossip. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum Op { + /// A new entry was inserted into the document. + Put(SignedEntry), +} + +#[derive(Debug)] +enum SyncState { + Running, + Finished, + Failed(anyhow::Error), +} + +/// Sync status for a document +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct LiveStatus { + /// Whether this document is in the live sync + pub active: bool, + /// Number of event listeners registered + pub subscriptions: usize, +} + +#[derive(derive_more::Debug)] +enum ToActor { + Status { + namespace: NamespaceId, + s: sync::oneshot::Sender>, + }, + StartSync { + replica: Replica, + peers: Vec, + }, + JoinPeers { + namespace: NamespaceId, + peers: Vec, + }, + StopSync { + namespace: NamespaceId, + }, + Shutdown, + Subscribe { + namespace: NamespaceId, + #[debug("cb")] + cb: OnLiveEventCallback, + s: sync::oneshot::Sender>, + }, + Unsubscribe { + namespace: NamespaceId, + token: RemovalToken, + s: sync::oneshot::Sender, + }, +} + +/// Whether to keep a live event callback active. +#[derive(Debug)] +pub enum KeepCallback { + /// Keep active + Keep, + /// Drop this callback + Drop, +} + +/// Callback used for tracking [`LiveEvent`]s. +pub type OnLiveEventCallback = + Box BoxFuture<'static, KeepCallback> + Send + Sync + 'static>; + +/// Events informing about actions of the live sync progres. +#[derive(Serialize, Deserialize, Debug, Clone)] +#[allow(clippy::large_enum_variant)] +pub enum LiveEvent { + /// A local insertion. + InsertLocal { + /// The inserted entry. + entry: Entry, + }, + /// Received a remote insert. + InsertRemote { + /// The peer that sent us the entry. + from: PublicKey, + /// The inserted entry. + entry: Entry, + /// If the content is available at the local node + content_status: ContentStatus, + }, + /// The content of an entry was downloaded and is now available at the local node + ContentReady { + /// The content hash of the newly available entry content + hash: Hash, + }, +} + +/// Availability status of an entry's content bytes +// TODO: Add IsDownloading +#[derive(Serialize, Deserialize, Debug, Clone)] +pub enum ContentStatus { + /// Fully available on the local node. + Complete, + /// Partially available on the local node. + Incomplete, + /// Not available on the local node. + /// + /// This currently means either that the content is about to be downloaded, failed to be + /// downloaded, or was never requested. + Missing, +} + +impl From for ContentStatus { + fn from(value: EntryStatus) -> Self { + match value { + EntryStatus::Complete => ContentStatus::Complete, + EntryStatus::Partial => ContentStatus::Incomplete, + EntryStatus::NotFound => ContentStatus::Missing, + } + } +} + +/// Handle to a running live sync actor +#[derive(Debug, Clone)] +pub struct LiveSync { + to_actor_tx: mpsc::Sender>, + task: Shared>>>, +} + +impl LiveSync { + /// Start the live sync. + /// + /// This spawn a background actor to handle gossip events and forward operations over broadcast + /// messages. + pub fn spawn( + rt: Handle, + endpoint: MagicEndpoint, + gossip: Gossip, + bao_store: B, + downloader: Downloader, + ) -> Self { + let (to_actor_tx, to_actor_rx) = mpsc::channel(CHANNEL_CAP); + let mut actor = Actor::new(endpoint, gossip, bao_store, downloader, to_actor_rx); + let task = rt.main().spawn(async move { + if let Err(err) = actor.run().await { + error!("live sync failed: {err:?}"); + } + }); + let handle = LiveSync { + to_actor_tx, + task: task.map_err(Arc::new).boxed().shared(), + }; + handle + } + + /// Cancel the live sync. + pub async fn shutdown(&self) -> Result<()> { + self.to_actor_tx.send(ToActor::::Shutdown).await?; + self.task.clone().await?; + Ok(()) + } + + /// Start to sync a document with a set of peers, also joining the gossip swarm for that + /// document. + pub async fn start_sync( + &self, + replica: Replica, + peers: Vec, + ) -> Result<()> { + self.to_actor_tx + .send(ToActor::::StartSync { replica, peers }) + .await?; + Ok(()) + } + + /// Join and sync with a set of peers for a document that is already syncing. + pub async fn join_peers(&self, namespace: NamespaceId, peers: Vec) -> Result<()> { + self.to_actor_tx + .send(ToActor::::JoinPeers { namespace, peers }) + .await?; + Ok(()) + } + + /// Stop the live sync for a document. + /// + /// This will leave the gossip swarm for this document. + pub async fn stop_sync(&self, namespace: NamespaceId) -> Result<()> { + self.to_actor_tx + .send(ToActor::::StopSync { namespace }) + .await?; + Ok(()) + } + + /// Subscribes `cb` to events on this `namespace`. + pub async fn subscribe(&self, namespace: NamespaceId, cb: F) -> Result + where + F: Fn(LiveEvent) -> BoxFuture<'static, KeepCallback> + Send + Sync + 'static, + { + let (s, r) = sync::oneshot::channel(); + self.to_actor_tx + .send(ToActor::::Subscribe { + namespace, + cb: Box::new(cb), + s, + }) + .await?; + let token = r.await??; + Ok(token) + } + + /// Unsubscribes `token` to events on this `namespace`. + /// Returns `true` if a callback was found + pub async fn unsubscribe(&self, namespace: NamespaceId, token: RemovalToken) -> Result { + let (s, r) = sync::oneshot::channel(); + self.to_actor_tx + .send(ToActor::::Unsubscribe { + namespace, + token, + s, + }) + .await?; + let token = r.await?; + Ok(token) + } + + /// Get status for a document + pub async fn status(&self, namespace: NamespaceId) -> Result> { + let (s, r) = sync::oneshot::channel(); + self.to_actor_tx + .send(ToActor::::Status { namespace, s }) + .await?; + let status = r.await?; + Ok(status) + } +} + +// Currently peers might double-sync in both directions. +struct Actor { + endpoint: MagicEndpoint, + gossip: Gossip, + bao_store: B, + downloader: Downloader, + + replicas: HashMap>, + replicas_subscription: futures::stream::SelectAll< + flume::r#async::RecvStream<'static, (InsertOrigin, SignedEntry)>, + >, + subscription: BoxStream<'static, Result<(TopicId, Event)>>, + sync_state: HashMap<(TopicId, PublicKey), SyncState>, + + to_actor_rx: mpsc::Receiver>, + + pending_syncs: FuturesUnordered)>>, + pending_joins: FuturesUnordered)>>, + + event_subscriptions: HashMap>, + event_removal_id: AtomicU64, + + pending_downloads: FuturesUnordered>>, +} + +/// Token needed to remove inserted callbacks. +#[derive(Debug, Clone, Copy)] +pub struct RemovalToken(u64); + +impl Actor { + pub fn new( + endpoint: MagicEndpoint, + gossip: Gossip, + bao_store: B, + downloader: Downloader, + to_actor_rx: mpsc::Receiver>, + ) -> Self { + let sub = gossip.clone().subscribe_all().boxed(); + + Self { + gossip, + endpoint, + bao_store, + downloader, + to_actor_rx, + sync_state: Default::default(), + pending_syncs: Default::default(), + pending_joins: Default::default(), + replicas: Default::default(), + replicas_subscription: Default::default(), + subscription: sub, + event_subscriptions: Default::default(), + event_removal_id: Default::default(), + pending_downloads: Default::default(), + } + } + + async fn run(&mut self) -> Result<()> { + loop { + tokio::select! { + biased; + msg = self.to_actor_rx.recv() => { + match msg { + // received shutdown signal, or livesync handle was dropped: + // break loop and exit + Some(ToActor::Shutdown) | None => { + self.shutdown().await?; + break; + } + Some(ToActor::StartSync { replica, peers }) => self.start_sync(replica, peers).await?, + Some(ToActor::StopSync { namespace }) => self.stop_sync(&namespace).await?, + Some(ToActor::JoinPeers { namespace, peers }) => self.join_gossip_and_start_initial_sync(&namespace, peers).await?, + Some(ToActor::Subscribe { namespace, cb, s }) => { + let result = self.subscribe(&namespace, cb).await; + s.send(result).ok(); + }, + Some(ToActor::Unsubscribe { namespace, token, s }) => { + let result = self.unsubscribe(&namespace, token).await; + s.send(result).ok(); + }, + Some(ToActor::Status { namespace , s }) => { + let result = self.status(&namespace).await; + s.send(result).ok(); + }, + } + } + // new gossip message + Some(event) = self.subscription.next() => { + let (topic, event) = event?; + if let Err(err) = self.on_gossip_event(topic, event) { + error!("Failed to process gossip event: {err:?}"); + } + }, + Some((origin, entry)) = self.replicas_subscription.next() => { + if let Err(err) = self.on_replica_event(origin, entry).await { + error!("Failed to process replica event: {err:?}"); + } + } + Some((topic, peer, res)) = self.pending_syncs.next() => { + self.on_sync_finished(topic, peer, res); + + } + Some((topic, res)) = self.pending_joins.next() => { + if let Err(err) = res { + error!("failed to join {topic:?}: {err:?}"); + } else { + info!("joined sync topic {topic:?}"); + } + // TODO: maintain some join state + } + Some(res) = self.pending_downloads.next() => { + if let Some((topic, hash)) = res { + if let Some(subs) = self.event_subscriptions.get_mut(&topic) { + let event = LiveEvent::ContentReady { hash }; + notify_all(subs, event).await; + } + } + + } + } + } + Ok(()) + } + + fn sync_with_peer(&mut self, topic: TopicId, peer: PublicKey) { + let Some(replica) = self.replicas.get(&topic) else { + return; + }; + // Check if we synced and only start sync if not yet synced + // sync_with_peer is triggered on NeighborUp events, so might trigger repeatedly for the + // same peers. + // TODO: Track finished time and potentially re-run sync + if let Some(_state) = self.sync_state.get(&(topic, peer)) { + return; + }; + self.sync_state.insert((topic, peer), SyncState::Running); + let task = { + let endpoint = self.endpoint.clone(); + let replica = replica.clone(); + async move { + debug!("init sync with {peer}"); + // TODO: Make sure that the peer is dialable. + let res = connect_and_sync::(&endpoint, &replica, peer, None, &[]).await; + debug!("synced with {peer}: {res:?}"); + (topic, peer, res) + } + .boxed() + }; + self.pending_syncs.push(task); + } + + async fn shutdown(&mut self) -> anyhow::Result<()> { + for (topic, _replica) in self.replicas.drain() { + self.event_subscriptions.remove(&topic); + self.gossip.quit(topic).await?; + } + + Ok(()) + } + + async fn status(&mut self, namespace: &NamespaceId) -> Option { + let topic = TopicId::from_bytes(*namespace.as_bytes()); + if self.replicas.contains_key(&topic) { + let subscriptions = self + .event_subscriptions + .get(&topic) + .map(|map| map.len()) + .unwrap_or_default(); + Some(LiveStatus { + active: true, + subscriptions, + }) + } else { + None + } + } + + async fn subscribe( + &mut self, + namespace: &NamespaceId, + cb: OnLiveEventCallback, + ) -> anyhow::Result { + let topic = TopicId::from_bytes(*namespace.as_bytes()); + if self.replicas.contains_key(&topic) { + let subs = self.event_subscriptions.entry(topic).or_default(); + let removal_id = self + .event_removal_id + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + subs.insert(removal_id, cb); + let token = RemovalToken(removal_id); + Ok(token) + } else { + bail!("cannot subscribe to unknown replica: {}", namespace); + } + } + + /// Returns `true` if a callback was found and removed + async fn unsubscribe(&mut self, namespace: &NamespaceId, token: RemovalToken) -> bool { + let topic = TopicId::from_bytes(*namespace.as_bytes()); + if let Some(subs) = self.event_subscriptions.get_mut(&topic) { + let res = subs.remove(&token.0).is_some(); + return res; + } + + false + } + + async fn stop_sync(&mut self, namespace: &NamespaceId) -> anyhow::Result<()> { + let topic = TopicId::from_bytes(*namespace.as_bytes()); + if let Some(_replica) = self.replicas.remove(&topic) { + self.event_subscriptions.remove(&topic); + self.gossip.quit(topic).await?; + } + Ok(()) + } + + async fn join_gossip_and_start_initial_sync( + &mut self, + namespace: &NamespaceId, + peers: Vec, + ) -> anyhow::Result<()> { + let topic = TopicId::from_bytes(*namespace.as_bytes()); + let peer_ids: Vec = peers.iter().map(|p| p.peer_id).collect(); + + // add addresses of initial peers to our endpoint address book + for peer in &peers { + if let Err(err) = self + .endpoint + .add_known_addrs(peer.peer_id, peer.derp_region, &peer.addrs) + .await + { + warn!(peer = ?peer.peer_id, "failed to add known addrs: {err:?}"); + } + } + + // join gossip for the topic to receive and send message + self.pending_joins.push({ + let peer_ids = peer_ids.clone(); + let gossip = self.gossip.clone(); + async move { + match gossip.join(topic, peer_ids).await { + Err(err) => (topic, Err(err)), + Ok(fut) => (topic, fut.await), + } + } + .boxed() + }); + + // trigger initial sync with initial peers + for peer in peer_ids { + self.sync_with_peer(topic, peer); + } + Ok(()) + } + + async fn start_sync( + &mut self, + replica: Replica, + peers: Vec, + ) -> Result<()> { + let namespace = replica.namespace(); + let topic = TopicId::from_bytes(*namespace.as_bytes()); + if let std::collections::hash_map::Entry::Vacant(e) = self.replicas.entry(topic) { + // setup replica insert notifications. + let events = replica + .subscribe() + .ok_or_else(|| anyhow::anyhow!("trying to subscribe twice to the same replica"))?; + self.replicas_subscription.push(events.into_stream()); + e.insert(replica); + } + + self.join_gossip_and_start_initial_sync(&namespace, peers) + .await?; + + Ok(()) + } + + fn on_sync_finished(&mut self, topic: TopicId, peer: PublicKey, res: Result<()>) { + let state = match res { + Ok(_) => SyncState::Finished, + Err(err) => SyncState::Failed(err), + }; + self.sync_state.insert((topic, peer), state); + } + + fn on_gossip_event(&mut self, topic: TopicId, event: Event) -> Result<()> { + let Some(replica) = self.replicas.get(&topic) else { + return Err(anyhow!("Missing doc for {topic:?}")); + }; + match event { + // We received a gossip message. Try to insert it into our replica. + Event::Received(data, prev_peer) => { + let op: Op = postcard::from_bytes(&data)?; + match op { + Op::Put(entry) => { + debug!(peer = ?prev_peer, topic = ?topic, "received entry via gossip"); + replica.insert_remote_entry(entry, *prev_peer.as_bytes())? + } + } + } + // A new neighbor appeared in the gossip swarm. Try to sync with it directly. + // [Self::sync_with_peer] will check to not resync with peers synced previously in the + // same session. TODO: Maybe this is too broad and leads to too many sync requests. + Event::NeighborUp(peer) => { + debug!(peer = ?peer, "new neighbor, init sync"); + self.sync_with_peer(topic, peer); + } + _ => {} + } + Ok(()) + } + + async fn on_replica_event( + &mut self, + origin: InsertOrigin, + signed_entry: SignedEntry, + ) -> Result<()> { + let topic = TopicId::from_bytes(*signed_entry.entry().namespace().as_bytes()); + let subs = self.event_subscriptions.get_mut(&topic); + match origin { + InsertOrigin::Local => { + let entry = signed_entry.entry().clone(); + + // A new entry was inserted locally. Broadcast a gossip message. + let op = Op::Put(signed_entry); + let message = postcard::to_stdvec(&op)?.into(); + debug!(topic = ?topic, "broadcast new entry"); + self.gossip.broadcast(topic, message).await?; + + // Notify subscribers about the event + if let Some(subs) = subs { + let event = LiveEvent::InsertLocal { + entry: entry.clone(), + }; + notify_all(subs, event).await; + } + } + InsertOrigin::Sync(peer_id) => { + let from = PublicKey::from_bytes(&peer_id)?; + let entry = signed_entry.entry(); + let hash = *entry.record().content_hash(); + + // A new entry was inserted from initial sync or gossip. Queue downloading the + // content. + let entry_status = self.bao_store.contains(&hash); + if matches!(entry_status, EntryStatus::NotFound) { + self.downloader.push(hash, vec![from]).await; + let fut = self.downloader.finished(&hash).await; + let fut = fut + .map(move |res| res.map(move |(hash, _len)| (topic, hash))) + .boxed(); + self.pending_downloads.push(fut); + } + + // Notify subscribers about the event + if let Some(subs) = subs { + let event = LiveEvent::InsertRemote { + from, + entry: entry.clone(), + content_status: entry_status.into(), + }; + notify_all(subs, event).await; + } + } + } + + Ok(()) + } +} + +async fn notify_all(subs: &mut HashMap, event: LiveEvent) { + let res = futures::future::join_all( + subs.iter() + .map(|(idx, sub)| sub(event.clone()).map(|res| (*idx, res))), + ) + .await; + for (idx, res) in res { + if matches!(res, KeepCallback::Drop) { + subs.remove(&idx); + } + } +} diff --git a/iroh/src/sync_engine/rpc.rs b/iroh/src/sync_engine/rpc.rs new file mode 100644 index 0000000000..04fc86e0cd --- /dev/null +++ b/iroh/src/sync_engine/rpc.rs @@ -0,0 +1,213 @@ +//! This module contains an impl block on [`SyncEngine`] with handlers for RPC requests + +use anyhow::anyhow; +use futures::{FutureExt, Stream}; +use iroh_bytes::{baomap::Store as BaoStore, util::RpcError}; +use iroh_sync::{store::Store, sync::Namespace}; +use itertools::Itertools; +use rand::rngs::OsRng; + +use crate::{ + rpc_protocol::{ + AuthorCreateRequest, AuthorCreateResponse, AuthorListRequest, AuthorListResponse, + DocCreateRequest, DocCreateResponse, DocGetRequest, DocGetResponse, DocImportRequest, + DocImportResponse, DocInfoRequest, DocInfoResponse, DocListRequest, DocListResponse, + DocSetRequest, DocSetResponse, DocShareRequest, DocShareResponse, DocStartSyncRequest, + DocStartSyncResponse, DocStopSyncRequest, DocStopSyncResponse, DocSubscribeRequest, + DocSubscribeResponse, DocTicket, RpcResult, ShareMode, + }, + sync_engine::{KeepCallback, LiveStatus, PeerSource, SyncEngine}, +}; + +/// Capacity for the flume channels to forward sync store iterators to async RPC streams. +const ITER_CHANNEL_CAP: usize = 64; + +#[allow(missing_docs)] +impl SyncEngine { + pub fn author_create(&self, _req: AuthorCreateRequest) -> RpcResult { + // TODO: pass rng + let author = self.store.new_author(&mut rand::rngs::OsRng {})?; + Ok(AuthorCreateResponse { + author_id: author.id(), + }) + } + + pub fn author_list( + &self, + _req: AuthorListRequest, + ) -> impl Stream> { + let (tx, rx) = flume::bounded(ITER_CHANNEL_CAP); + let store = self.store.clone(); + self.rt.main().spawn_blocking(move || { + let ite = store.list_authors(); + let ite = inline_result(ite).map_ok(|author| AuthorListResponse { + author_id: author.id(), + }); + for entry in ite { + if let Err(_err) = tx.send(entry) { + break; + } + } + }); + rx.into_stream() + } + + pub fn doc_create(&self, _req: DocCreateRequest) -> RpcResult { + let doc = self.store.new_replica(Namespace::new(&mut OsRng {}))?; + Ok(DocCreateResponse { + id: doc.namespace(), + }) + } + + pub fn doc_list(&self, _req: DocListRequest) -> impl Stream> { + let (tx, rx) = flume::bounded(ITER_CHANNEL_CAP); + let store = self.store.clone(); + self.rt.main().spawn_blocking(move || { + let ite = store.list_namespaces(); + let ite = inline_result(ite).map_ok(|id| DocListResponse { id }); + for entry in ite { + if let Err(_err) = tx.send(entry) { + break; + } + } + }); + rx.into_stream() + } + + pub async fn doc_info(&self, req: DocInfoRequest) -> RpcResult { + let _replica = self.get_replica(&req.doc_id)?; + let status = self.live.status(req.doc_id).await?; + let status = status.unwrap_or(LiveStatus { + active: false, + subscriptions: 0, + }); + Ok(DocInfoResponse { status }) + } + + pub async fn doc_share(&self, req: DocShareRequest) -> RpcResult { + let replica = self.get_replica(&req.doc_id)?; + let key = match req.mode { + ShareMode::Read => { + // TODO: support readonly docs + // *replica.namespace().as_bytes() + return Err(anyhow!("creating read-only shares is not yet supported").into()); + } + ShareMode::Write => replica.secret_key(), + }; + let me = PeerSource::from_endpoint(&self.endpoint).await?; + self.start_sync(replica.namespace(), vec![]).await?; + Ok(DocShareResponse(DocTicket { + key, + peers: vec![me], + })) + } + + pub async fn doc_subscribe( + &self, + req: DocSubscribeRequest, + ) -> impl Stream> { + let (s, r) = flume::bounded(64); + let res = self + .live + .subscribe(req.doc_id, { + let s = s.clone(); + move |event| { + let s = s.clone(); + async move { + // Send event over the channel, unsubscribe if the channel is closed. + match s.send_async(Ok(DocSubscribeResponse { event })).await { + Err(_err) => KeepCallback::Drop, + Ok(()) => KeepCallback::Keep, + } + } + .boxed() + } + }) + .await; + match res { + Err(err) => { + s.send_async(Err(err.into())).await.ok(); + } + Ok(_token) => {} + }; + r.into_stream() + } + + pub async fn doc_import(&self, req: DocImportRequest) -> RpcResult { + let DocImportRequest(DocTicket { key, peers }) = req; + // TODO: support read-only docs + // if let Ok(namespace) = match NamespaceId::from_bytes(&key) {}; + let namespace = Namespace::from_bytes(&key); + let id = namespace.id(); + let replica = self.store.new_replica(namespace)?; + self.start_sync(replica.namespace(), peers).await?; + Ok(DocImportResponse { doc_id: id }) + } + + pub async fn doc_start_sync( + &self, + req: DocStartSyncRequest, + ) -> RpcResult { + let DocStartSyncRequest { doc_id, peers } = req; + let replica = self.get_replica(&doc_id)?; + self.start_sync(replica.namespace(), peers).await?; + Ok(DocStartSyncResponse {}) + } + + pub async fn doc_stop_sync(&self, req: DocStopSyncRequest) -> RpcResult { + let DocStopSyncRequest { doc_id } = req; + let replica = self.get_replica(&doc_id)?; + self.stop_sync(replica.namespace()).await?; + Ok(DocStopSyncResponse {}) + } + + pub async fn doc_set( + &self, + bao_store: &B, + req: DocSetRequest, + ) -> RpcResult { + let DocSetRequest { + doc_id, + author_id, + key, + value, + } = req; + let replica = self.get_replica(&doc_id)?; + let author = self.get_author(&author_id)?; + let len = value.len(); + let hash = bao_store.import_bytes(value.into()).await?; + replica + .insert(&key, &author, hash, len as u64) + .map_err(Into::into)?; + let entry = self + .store + .get_latest_by_key_and_author(replica.namespace(), author.id(), &key)? + .ok_or_else(|| anyhow!("failed to get entry after insertion"))?; + Ok(DocSetResponse { entry }) + } + + pub fn doc_get(&self, req: DocGetRequest) -> impl Stream> { + let DocGetRequest { doc_id, filter } = req; + let (tx, rx) = flume::bounded(ITER_CHANNEL_CAP); + let store = self.store.clone(); + self.rt.main().spawn_blocking(move || { + let ite = store.get(doc_id, filter); + let ite = inline_result(ite).map_ok(|entry| DocGetResponse { entry }); + for entry in ite { + if let Err(_err) = tx.send(entry) { + break; + } + } + }); + rx.into_stream() + } +} + +fn inline_result( + ite: Result>>, impl Into>, +) -> impl Iterator> { + match ite { + Ok(ite) => itertools::Either::Left(ite.map(|item| item.map_err(|err| err.into()))), + Err(err) => itertools::Either::Right(Some(Err(err.into())).into_iter()), + } +} diff --git a/iroh/tests/cli.rs b/iroh/tests/cli.rs index af5dc864ae..6cf51b7f94 100644 --- a/iroh/tests/cli.rs +++ b/iroh/tests/cli.rs @@ -90,16 +90,41 @@ fn cli_provide_tree() -> Result<()> { test_provide_get_loop(&dir, Input::Path, Output::Path) } -fn copy_dir_all(src: impl AsRef, dst: impl AsRef) -> io::Result<()> { - std::fs::create_dir_all(&dst)?; +fn copy_dir_all(src: impl AsRef, dst: impl AsRef) -> anyhow::Result<()> { + let src = src.as_ref(); + let dst = dst.as_ref(); + std::fs::create_dir_all(dst)?; for entry in std::fs::read_dir(src)? { - let entry = entry?; - let ty = entry.file_type()?; + let entry = entry.with_context(|| { + format!( + "failed to read directory entry in `{}`", + src.to_string_lossy() + ) + })?; + let ty = entry.file_type().with_context(|| { + format!( + "failed to get file type for file `{}`", + entry.path().to_string_lossy() + ) + })?; + let src = entry.path(); + let dst = dst.join(entry.file_name()); if ty.is_dir() { - copy_dir_all(entry.path(), dst.as_ref().join(entry.file_name()))?; + copy_dir_all(&src, &dst).with_context(|| { + format!( + "failed to copy directory `{}` to `{}`", + src.to_string_lossy(), + dst.to_string_lossy() + ) + })?; } else { - let to = dst.as_ref().join(entry.file_name()); - std::fs::copy(entry.path(), to)?; + std::fs::copy(&src, &dst).with_context(|| { + format!( + "failed to copy file `{}` to `{}`", + src.to_string_lossy(), + dst.to_string_lossy() + ) + })?; } } Ok(()) diff --git a/iroh/tests/provide.rs b/iroh/tests/provide.rs index b90fb8f3fb..905d0247a4 100644 --- a/iroh/tests/provide.rs +++ b/iroh/tests/provide.rs @@ -36,6 +36,7 @@ use iroh_bytes::{ util::runtime, Hash, }; +use iroh_sync::store; /// Pick up the tokio runtime from the thread local and add a /// thread per core runtime. @@ -46,8 +47,9 @@ fn test_runtime() -> runtime::Handle { fn test_node( db: D, addr: SocketAddr, -) -> Builder { - Node::builder(db) +) -> Builder { + let store = iroh_sync::store::memory::Store::default(); + Node::builder(db, store) .collection_parser(IrohCollectionParser) .bind_addr(addr) } @@ -622,7 +624,8 @@ async fn test_custom_collection_parser() { let collection_bytes = postcard::to_allocvec(&collection).unwrap(); let collection_hash = db.insert(collection_bytes.clone()); let addr = "127.0.0.1:0".parse().unwrap(); - let node = Node::builder(db) + let doc_store = iroh_sync::store::memory::Store::default(); + let node = Node::builder(db, doc_store) .collection_parser(CollectionsAreJustLinks) .bind_addr(addr) .runtime(&rt) diff --git a/iroh/tests/sync.rs b/iroh/tests/sync.rs new file mode 100644 index 0000000000..62c289c991 --- /dev/null +++ b/iroh/tests/sync.rs @@ -0,0 +1,201 @@ +#![cfg(feature = "mem-db")] + +use std::net::SocketAddr; + +use anyhow::{anyhow, Result}; +use futures::{StreamExt, TryStreamExt}; +use iroh::{ + client::mem::Doc, + collection::IrohCollectionParser, + node::{Builder, Node}, + rpc_protocol::ShareMode, + sync_engine::LiveEvent, +}; +use quic_rpc::transport::misc::DummyServerEndpoint; +use tracing_subscriber::{prelude::*, EnvFilter}; + +use iroh_bytes::util::runtime; +use iroh_sync::store::{self, GetFilter}; + +/// Pick up the tokio runtime from the thread local and add a +/// thread per core runtime. +fn test_runtime() -> runtime::Handle { + runtime::Handle::from_currrent(1).unwrap() +} + +fn test_node( + rt: runtime::Handle, + addr: SocketAddr, +) -> Builder< + iroh::baomap::mem::Store, + store::memory::Store, + DummyServerEndpoint, + IrohCollectionParser, +> { + let db = iroh::baomap::mem::Store::new(rt.clone()); + let store = iroh_sync::store::memory::Store::default(); + Node::builder(db, store) + .collection_parser(IrohCollectionParser) + .runtime(&rt) + .bind_addr(addr) +} + +async fn spawn_node( + rt: runtime::Handle, +) -> anyhow::Result> { + let node = test_node(rt, "127.0.0.1:0".parse()?); + let node = node.spawn().await?; + Ok(node) +} + +async fn spawn_nodes( + rt: runtime::Handle, + n: usize, +) -> anyhow::Result>> { + let mut nodes = vec![]; + for _i in 0..n { + let node = spawn_node(rt.clone()).await?; + nodes.push(node); + } + Ok(nodes) +} + +#[tokio::test] +async fn sync_full_basic() -> Result<()> { + setup_logging(); + let rt = test_runtime(); + let nodes = spawn_nodes(rt, 3).await?; + let clients = nodes.iter().map(|node| node.client()).collect::>(); + + // node1: create doc and ticket + let (ticket, doc1) = { + let iroh = &clients[0]; + let author = iroh.create_author().await?; + let doc = iroh.create_doc().await?; + let key = b"k1"; + let value = b"v1"; + doc.set_bytes(author, key.to_vec(), value.to_vec()).await?; + assert_latest(&doc, key, value).await; + let ticket = doc.share(ShareMode::Write).await?; + (ticket, doc) + }; + + // node2: join in + let _doc2 = { + let iroh = &clients[1]; + let author = iroh.create_author().await?; + let doc = iroh.import_doc(ticket.clone()).await?; + + // wait for remote insert on doc2 + let mut events = doc.subscribe().await?; + let event = events.try_next().await?.unwrap(); + assert!(matches!(event, LiveEvent::InsertRemote { .. })); + let event = events.try_next().await?.unwrap(); + assert!(matches!(event, LiveEvent::ContentReady { .. })); + + assert_latest(&doc, b"k1", b"v1").await; + + // setup event channel on on doc1 + let mut events = doc1.subscribe().await?; + + let key = b"k2"; + let value = b"v2"; + doc.set_bytes(author, key.to_vec(), value.to_vec()).await?; + assert_latest(&doc, key, value).await; + + // wait for remote insert on doc1 + let event = events.try_next().await?.unwrap(); + assert!(matches!(event, LiveEvent::InsertRemote { .. })); + let event = events.try_next().await?.unwrap(); + assert!(matches!(event, LiveEvent::ContentReady { .. })); + + assert_latest(&doc1, key, value).await; + doc + }; + + // node 3 joins & imports the doc from peer 1 + let _doc3 = { + let iroh = &clients[2]; + let doc = iroh.import_doc(ticket).await?; + + // wait for 2 remote inserts + let mut events = doc.subscribe().await?; + let event = events.try_next().await?.unwrap(); + assert!(matches!(event, LiveEvent::InsertRemote { .. })); + let event = events.try_next().await?.unwrap(); + assert!(matches!(event, LiveEvent::InsertRemote { .. })); + let event = events.try_next().await?.unwrap(); + assert!(matches!(event, LiveEvent::ContentReady { .. })); + let event = events.try_next().await?.unwrap(); + assert!(matches!(event, LiveEvent::ContentReady { .. })); + + assert_latest(&doc, b"k1", b"v1").await; + assert_latest(&doc, b"k2", b"v2").await; + doc + }; + + // TODO: + // - gossiping between multiple peers + // - better test utils + // - ... + + for node in nodes { + node.shutdown(); + } + + Ok(()) +} + +#[tokio::test] +async fn sync_subscribe_stop() -> Result<()> { + setup_logging(); + let rt = test_runtime(); + let node = spawn_node(rt).await?; + let client = node.client(); + + let doc = client.create_doc().await?; + let author = client.create_author().await?; + doc.start_sync(vec![]).await?; + + let status = doc.status().await?; + assert!(status.active); + assert_eq!(status.subscriptions, 0); + + let sub = doc.subscribe().await?; + let status = doc.status().await?; + assert_eq!(status.subscriptions, 1); + drop(sub); + + doc.set_bytes(author, b"x".to_vec(), b"x".to_vec()).await?; + let status = doc.status().await?; + assert_eq!(status.subscriptions, 0); + + node.shutdown(); + + Ok(()) +} + +async fn assert_latest(doc: &Doc, key: &[u8], value: &[u8]) { + let content = get_latest(doc, key).await.unwrap(); + assert_eq!(content, value.to_vec()); +} + +async fn get_latest(doc: &Doc, key: &[u8]) -> anyhow::Result> { + let filter = GetFilter::latest().with_key(key); + let entry = doc + .get(filter) + .await? + .next() + .await + .ok_or_else(|| anyhow!("entry not found"))??; + let content = doc.get_content_bytes(&entry).await?; + Ok(content.to_vec()) +} + +fn setup_logging() { + tracing_subscriber::registry() + .with(tracing_subscriber::fmt::layer().with_writer(std::io::stderr)) + .with(EnvFilter::from_default_env()) + .try_init() + .ok(); +}