mirror of
https://github.com/n0-computer/iroh.git
synced 2026-11-30 00:01:16 +00:00
feat: add iroh-sync and integrate into iroh node (#1333)
## Description This PR adds `iroh-sync`, a document synchronization protocol, to iroh, and integrates with `iroh-net`, `iroh-gossip` and `iroh-bytes`. * At the core is the `iroh-sync` crate, with a set reconciliation algorithm implemented by @dignifiedquire. See [the old iroh-sync repo](https://github.com/n0-computer/iroh-sync/) for the prehistory and #1216 for the initial PR (fully included in this PR, and by now outdated) * Iroh sync is integrated in the iroh node, with iroh-gossip, in the RPC interface, and the CLI. * `LiveSync` is the handle to an actor that integrates sync with [gossip](#1149 ) to broadcast and receive document updates from peers. For each open document a gossip swarm is joined with a `TopicId` derived from the doc namespace. * mod `download` contains the new downloader. It will be improved in #1344 . * mod `client` is the new high-level RPC client. It currently only has methods for dealing with docs and sync, other things should be added once we merged this. CLI commands for sync are in `commands/sync.rs`. Will be much better with #1356 . * `examples/sync.rs` has a REPL to modify and sync docs. It does a full setup without using the iroh console. Also includes code to sync directories, and a hammer command for load testing. * The PR also introduces `iroh::client::Iroh`, a wrapper around the RPC client, and `iroh::client::Doc`, a wrapper around RPC client for a single document ## Notes & open questions #### Should likely happen before merge: * [x] Make `iroh_sync::Store:::list_authors` and `list_replicas` return iterators `iroh-sync` *fixed in #1366 * * [ ] Add `iroh_sync::Store::close_replica` * [x] `ContentStatus` in `on_insert` callback is reported as `Ready` if the content is still `baomap::PartialEntry` (in-process download) *fixed in a8e809367245504787168d354f1714b11305920d* #### Can happen after merge, but before `0.6` release * [ ] Implement `AuthorImport` and `AuthorShare` RPC & CLI commands * [ ] sync store `list_namespaces` and `list_authors` internally collect, return iterator instead * [ ] Fix cross-compiles to arm/android. See https://github.com/cross-rs/cross/issues/1311 * [ ] Ensure that fingerpring calculation is efficient and/or cached for large documents. Currently calculating the initial fingerprint iterates once over all entries in a document. * [ ] Make content downloads be more reliable * [ ] Add some way to download content from peers independent of the first insertion event for a remote entry. The downloader with retries is tracked in #1334 and 1344, but independent of that, we still would currently only ever try to queue a download when the `on_insert` callback triggers, which is only once. There should be a way, even if manual for now, to try to download missing content in a replica from peers. * [ ] during `iroh-sync` sync include info if content is available for each entry * [ ] Add basic peer management and persistence. Currently live sync will stop to do anything after a node restart. * [ ] Persist the addressbook of peers for a document, to reconnect when restarting the node * [ ] Implement `PeerAdd` and `PeerList` RPC & CLI commands. The latter needs changes in `iroh-net` to expose information of currently-connected peers and their peer info. * [ ] Make read-only replicas possible * [ ] Improve reliablity of replica sync. * sync is triggered on each `NeighborUp` event from gossip. check that we don't sync too much. * maybe include peer info in gossip messages, to queue syncs with those (but not all at once) * track and exchange the timestamp of last full sync for peers, to know if you missed gossiped message and react accordingly * add more tests with peers coming and leaving #### Open questions * [ ] `iroh_sync::EntrySignature` should the signatures include a namespace prefix? * [ ] do we want the 1:1 mapping of `NamespaceId`and gossip `TopicId`, or would the topic id as a hash be better? #### Other TODOs collected from the code * [ ] Port `hammer` and `fs` commands from REPL example to iroh cli * [ ] docs/naming: settle terminology about keypairs, private/secret/signing keys, public keys/identifiers and make docs and symbols consistent * [ ] Make `bytes_get` streaming in the RPC interface * [ ] Allow to unset the subscription on a replica * [ ] `iroh-sync` shouldn't depend on `iroh-bytes` only for `Hash` type -> #1354 * [ ] * [ ] Move `sync::live::PeerSource` to iroh-net or even better -> #1354 * [ ] `StoreInstance::put` propagate error and verify timestamp is reasonable. * [ ] `StoreInstance::get_range` implement inverted range * [ ] `iroh_sync`: Remove some items only used in tests (marked with #[cfg(test)]) * [ ] `iroh_sync` fs store: verify get method fetches all keys with this namespace * [ ] `ranger::SimpleStore::get_range`: optimize * [ ] `ranger::Peer` avoid allocs? * [ ] `fs::StoreInstance::get_fingerprint` optimize * [ ] `SyncEngine::doc_subscribe` remove unwrap, handle error ## Change checklist - [x] Self-review. - [x] Documentation updates if relevant. - [ ] Tests if relevant. --------- Co-authored-by: dignifiedquire <me@dignifiedquire.com> Co-authored-by: Asmir Avdicevic <asmir.avdicevic64@gmail.com> Co-authored-by: Kasey <klhuizinga@gmail.com>
This commit is contained in:
co-authored by
dignifiedquire
Asmir Avdicevic
Kasey
parent
5d3ef9167e
commit
3f141be6fd
@@ -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:
|
||||
|
||||
Generated
+302
-56
@@ -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"
|
||||
|
||||
@@ -5,6 +5,7 @@ members = [
|
||||
"iroh-gossip",
|
||||
"iroh-metrics",
|
||||
"iroh-net",
|
||||
"iroh-sync",
|
||||
"iroh-test",
|
||||
]
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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<W: AsyncWrite + Unpin>(writer: &mut W, data: &[u8]) -> Result<()> {
|
||||
pub async fn write_lp<W: AsyncWrite + Unpin>(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<W: AsyncWrite + Unpin>(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<Option<Bytes>> {
|
||||
|
||||
@@ -83,6 +83,18 @@ impl From<[u8; 32]> for Hash {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Hash> 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<std::cmp::Ordering> {
|
||||
Some(self.0.as_bytes().cmp(other.0.as_bytes()))
|
||||
@@ -202,6 +214,12 @@ impl From<anyhow::Error> for RpcError {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::io::Error> 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<T> = result::Result<T, RpcError>;
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
+34
-12
@@ -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<u16>,
|
||||
}
|
||||
|
||||
impl IrohInfo {
|
||||
async fn from_endpoint(endpoint: &MagicEndpoint) -> anyhow::Result<Self> {
|
||||
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::<IrohInfo>(&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:?}");
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
@@ -56,20 +56,20 @@ macro_rules! idbytes_impls {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Into<[u8; 32]>> From<T> for $ty {
|
||||
impl<T: ::std::convert::Into<[u8; 32]>> ::std::convert::From<T> 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<Self, Self::Err> {
|
||||
fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
|
||||
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
|
||||
}
|
||||
|
||||
+28
-2
@@ -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<Self, SignatureError> {
|
||||
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, Self::Error> {
|
||||
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<SigningKey> 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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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"]
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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<R: CryptoRngCore + ?Sized>(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<Self> {
|
||||
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<R: CryptoRngCore + ?Sized>(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<Self> {
|
||||
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<Self, Self::Err> {
|
||||
Ok(Self::from_bytes(&base32::parse_array(s)?))
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for Namespace {
|
||||
type Err = anyhow::Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
Ok(Self::from_bytes(&base32::parse_array(s)?))
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for AuthorId {
|
||||
type Err = anyhow::Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
Self::from_bytes(&base32::parse_array(s)?)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for NamespaceId {
|
||||
type Err = anyhow::Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
Self::from_bytes(&base32::parse_array(s)?)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SigningKey> for Author {
|
||||
fn from(signing_key: SigningKey) -> Self {
|
||||
Self { signing_key }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SigningKey> for Namespace {
|
||||
fn from(signing_key: SigningKey) -> Self {
|
||||
Self { signing_key }
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for NamespaceId {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
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<Ordering> {
|
||||
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<const N: usize>(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"))
|
||||
}
|
||||
}
|
||||
@@ -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::*;
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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<S: store::Store>(
|
||||
endpoint: &MagicEndpoint,
|
||||
doc: &Replica<S::Instance>,
|
||||
peer_id: PublicKey,
|
||||
derp_region: Option<u16>,
|
||||
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::<S, _, _>(&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<S: store::Store>(
|
||||
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(())
|
||||
}
|
||||
@@ -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<Option<Self::Item>, 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<Message> 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<S: store::Store, R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
|
||||
writer: &mut W,
|
||||
reader: &mut R,
|
||||
alice: &Replica<S::Instance>,
|
||||
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<S: store::Store, R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
|
||||
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::<Result<Vec<_>>>()
|
||||
.unwrap()
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
alice_replica_store
|
||||
.get(alice_replica.namespace(), GetFilter::all())
|
||||
.unwrap()
|
||||
.collect::<Result<Vec<_>>>()
|
||||
.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::<store::memory::Store, _, _>(
|
||||
&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::<store::memory::Store, _, _>(
|
||||
&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::<Result<Vec<_>>>()
|
||||
.unwrap()
|
||||
.len(),
|
||||
2
|
||||
);
|
||||
assert_eq!(
|
||||
alice_replica_store
|
||||
.get(alice_replica.namespace(), GetFilter::all())
|
||||
.unwrap()
|
||||
.collect::<Result<Vec<_>>>()
|
||||
.unwrap()
|
||||
.len(),
|
||||
2
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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<RecordIdentifier, SignedEntry> + Send + Sync + 'static + Clone;
|
||||
|
||||
/// Iterator over entries in the store, returned from [`Self::get`]
|
||||
type GetIter<'a>: Iterator<Item = Result<SignedEntry>>
|
||||
where
|
||||
Self: 'a;
|
||||
|
||||
/// Iterator over replica namespaces in the store, returned from [`Self::list_namespaces`]
|
||||
type NamespaceIter<'a>: Iterator<Item = Result<NamespaceId>>
|
||||
where
|
||||
Self: 'a;
|
||||
|
||||
/// Iterator over authors in the store, returned from [`Self::list_authors`]
|
||||
type AuthorsIter<'a>: Iterator<Item = Result<Author>>
|
||||
where
|
||||
Self: 'a;
|
||||
|
||||
/// Create a new replica for `namespace` and persist in this store.
|
||||
fn new_replica(&self, namespace: Namespace) -> Result<Replica<Self::Instance>>;
|
||||
|
||||
/// List all replica namespaces in this store.
|
||||
fn list_namespaces(&self) -> Result<Self::NamespaceIter<'_>>;
|
||||
|
||||
/// 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<Option<Replica<Self::Instance>>>;
|
||||
|
||||
/// Create a new author key and persist it in the store.
|
||||
fn new_author<R: CryptoRngCore + ?Sized>(&self, rng: &mut R) -> Result<Author>;
|
||||
|
||||
/// List all author keys in this store.
|
||||
fn list_authors(&self) -> Result<Self::AuthorsIter<'_>>;
|
||||
|
||||
/// Get an author key from the store.
|
||||
fn get_author(&self, author: &AuthorId) -> Result<Option<Author>>;
|
||||
|
||||
/// Iterate over entries of a replica.
|
||||
///
|
||||
/// The [`GetFilter`] has several methods of filtering the returned entries.
|
||||
fn get(&self, namespace: NamespaceId, filter: GetFilter) -> Result<Self::GetIter<'_>>;
|
||||
|
||||
/// 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<Option<SignedEntry>>;
|
||||
}
|
||||
|
||||
/// Filter a get query onto a namespace
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct GetFilter {
|
||||
latest: bool,
|
||||
author: Option<AuthorId>,
|
||||
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<u8>),
|
||||
/// Filter for exact key match
|
||||
Key(Vec<u8>),
|
||||
}
|
||||
@@ -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<Database>,
|
||||
replicas: Arc<RwLock<HashMap<NamespaceId, Replica<StoreInstance>>>>,
|
||||
}
|
||||
|
||||
// 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<u8>) # (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<RecordsId, RecordsValue> =
|
||||
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<Path>) -> Result<Self> {
|
||||
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<anyhow::Result<SignedEntry>>),
|
||||
}
|
||||
|
||||
impl<'s> Iterator for GetIter<'s> {
|
||||
type Item = anyhow::Result<SignedEntry>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
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<Result<Author>>;
|
||||
type NamespaceIter<'a> = std::vec::IntoIter<Result<NamespaceId>>;
|
||||
|
||||
fn open_replica(&self, namespace_id: &NamespaceId) -> Result<Option<Replica<Self::Instance>>> {
|
||||
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<Self::NamespaceIter<'_>> {
|
||||
// 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<Option<Author>> {
|
||||
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<R: CryptoRngCore + ?Sized>(&self, rng: &mut R) -> Result<Author> {
|
||||
let author = Author::new(rng);
|
||||
self.insert_author(author.clone())?;
|
||||
Ok(author)
|
||||
}
|
||||
|
||||
fn list_authors(&self) -> Result<Self::AuthorsIter<'_>> {
|
||||
// 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<Replica<Self::Instance>> {
|
||||
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<Self::GetIter<'_>> {
|
||||
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<Option<SignedEntry>> {
|
||||
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<RangeLatestIterator<'_>> {
|
||||
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<RangeLatestIterator<'_>> {
|
||||
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<RangeLatestIterator<'_>> {
|
||||
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<RangeAllIterator<'a>> {
|
||||
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<RangeAllIterator<'_>> {
|
||||
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<RangeAllIterator<'_>> {
|
||||
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<RangeAllIterator<'_>> {
|
||||
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<RecordIdentifier, SignedEntry> for StoreInstance {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
/// Get a the first key (or the default if none is available).
|
||||
fn get_first(&self) -> Result<RecordIdentifier> {
|
||||
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<Option<SignedEntry>> {
|
||||
self.store
|
||||
.get_latest_by_key_and_author(id.namespace(), id.author(), id.key())
|
||||
}
|
||||
|
||||
fn len(&self) -> Result<usize> {
|
||||
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<bool> {
|
||||
Ok(self.len()? == 0)
|
||||
}
|
||||
|
||||
fn get_fingerprint(
|
||||
&self,
|
||||
range: &Range<RecordIdentifier>,
|
||||
limit: Option<&Range<RecordIdentifier>>,
|
||||
) -> Result<Fingerprint> {
|
||||
// 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<RecordIdentifier>,
|
||||
limit: Option<Range<RecordIdentifier>>,
|
||||
) -> Result<Self::RangeIterator<'_>> {
|
||||
// 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<Vec<SignedEntry>> {
|
||||
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<Self::AllIterator<'_>> {
|
||||
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<Range<RecordIdentifier>>, 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<Range<RecordIdentifier>>,
|
||||
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::Item> {
|
||||
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<u8>),
|
||||
Key(Vec<u8>),
|
||||
}
|
||||
|
||||
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::Item> {
|
||||
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::<Result<Vec<_>>>()?;
|
||||
assert_eq!(entries.len(), 10);
|
||||
|
||||
// get all prefix
|
||||
let entries = store
|
||||
.get_all_by_prefix(namespace.id(), "hello-")?
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
assert_eq!(entries.len(), 10);
|
||||
|
||||
// get latest
|
||||
let entries = store
|
||||
.get_latest(namespace.id())?
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
assert_eq!(entries.len(), 5);
|
||||
|
||||
// get latest by prefix
|
||||
let entries = store
|
||||
.get_latest_by_prefix(namespace.id(), "hello-")?
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
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::<Result<Vec<_>>>()?;
|
||||
assert_eq!(entries.len(), 0);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -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<RwLock<HashMap<NamespaceId, Replica<ReplicaStoreInstance>>>>,
|
||||
authors: Arc<RwLock<HashMap<AuthorId, Author>>>,
|
||||
/// Stores records by namespace -> identifier + timestamp
|
||||
replica_records: Arc<RwLock<ReplicaRecordsOwned>>,
|
||||
}
|
||||
|
||||
type ReplicaRecordsOwned =
|
||||
HashMap<NamespaceId, BTreeMap<RecordIdentifier, BTreeMap<u64, SignedEntry>>>;
|
||||
|
||||
impl super::Store for Store {
|
||||
type Instance = ReplicaStoreInstance;
|
||||
type GetIter<'a> = GetIter<'a>;
|
||||
type AuthorsIter<'a> = std::vec::IntoIter<Result<Author>>;
|
||||
type NamespaceIter<'a> = std::vec::IntoIter<Result<NamespaceId>>;
|
||||
|
||||
fn open_replica(&self, namespace: &NamespaceId) -> Result<Option<Replica<Self::Instance>>> {
|
||||
let replicas = &*self.replicas.read();
|
||||
Ok(replicas.get(namespace).cloned())
|
||||
}
|
||||
|
||||
fn list_namespaces(&self) -> Result<Self::NamespaceIter<'_>> {
|
||||
// TODO: avoid collect?
|
||||
Ok(self
|
||||
.replicas
|
||||
.read()
|
||||
.keys()
|
||||
.cloned()
|
||||
.map(Ok)
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter())
|
||||
}
|
||||
|
||||
fn get_author(&self, author: &AuthorId) -> Result<Option<Author>> {
|
||||
let authors = &*self.authors.read();
|
||||
Ok(authors.get(author).cloned())
|
||||
}
|
||||
|
||||
fn new_author<R: CryptoRngCore + ?Sized>(&self, rng: &mut R) -> Result<Author> {
|
||||
let author = Author::new(rng);
|
||||
self.authors.write().insert(author.id(), author.clone());
|
||||
Ok(author)
|
||||
}
|
||||
|
||||
fn list_authors(&self) -> Result<Self::AuthorsIter<'_>> {
|
||||
// TODO: avoid collect?
|
||||
Ok(self
|
||||
.authors
|
||||
.read()
|
||||
.values()
|
||||
.cloned()
|
||||
.map(Ok)
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter())
|
||||
}
|
||||
|
||||
fn new_replica(&self, namespace: Namespace) -> Result<Replica<ReplicaStoreInstance>> {
|
||||
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<Self::GetIter<'_>> {
|
||||
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<Option<SignedEntry>> {
|
||||
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<anyhow::Result<SignedEntry>>),
|
||||
}
|
||||
|
||||
impl<'s> Iterator for GetIter<'s> {
|
||||
type Item = anyhow::Result<SignedEntry>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
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<GetLatestIter<'_>> {
|
||||
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<GetLatestIter<'_>> {
|
||||
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<GetLatestIter<'_>> {
|
||||
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<GetAllIter<'a>> {
|
||||
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<GetAllIter<'_>> {
|
||||
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<GetAllIter<'_>> {
|
||||
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<GetAllIter<'_>> {
|
||||
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<u8>,
|
||||
},
|
||||
/// Filter by prefix only.
|
||||
Prefix {
|
||||
namespace: NamespaceId,
|
||||
prefix: Vec<u8>,
|
||||
},
|
||||
}
|
||||
|
||||
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<Self::Item> {
|
||||
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<Self::Item> {
|
||||
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<F, T>(&self, f: F) -> T
|
||||
where
|
||||
F: FnOnce(Option<&BTreeMap<RecordIdentifier, BTreeMap<u64, SignedEntry>>>) -> T,
|
||||
{
|
||||
let guard = self.store.replica_records.read();
|
||||
let value = guard.get(&self.namespace);
|
||||
f(value)
|
||||
}
|
||||
|
||||
fn with_records_mut<F, T>(&self, f: F) -> T
|
||||
where
|
||||
F: FnOnce(Option<&mut BTreeMap<RecordIdentifier, BTreeMap<u64, SignedEntry>>>) -> T,
|
||||
{
|
||||
let mut guard = self.store.replica_records.write();
|
||||
let value = guard.get_mut(&self.namespace);
|
||||
f(value)
|
||||
}
|
||||
|
||||
fn with_records_mut_with_default<F, T>(&self, f: F) -> T
|
||||
where
|
||||
F: FnOnce(&mut BTreeMap<RecordIdentifier, BTreeMap<u64, SignedEntry>>) -> 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<NamespaceId, BTreeMap<RecordIdentifier, BTreeMap<u64, SignedEntry>>>,
|
||||
>;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RecordsIter<'a> {
|
||||
namespace: NamespaceId,
|
||||
replica_records: ReplicaRecords<'a>,
|
||||
i: usize,
|
||||
}
|
||||
|
||||
impl Iterator for RecordsIter<'_> {
|
||||
type Item = (RecordIdentifier, BTreeMap<u64, SignedEntry>);
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
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<RecordIdentifier, SignedEntry> for ReplicaStoreInstance {
|
||||
type Error = Infallible;
|
||||
|
||||
/// Get a the first key (or the default if none is available).
|
||||
fn get_first(&self) -> Result<RecordIdentifier, Self::Error> {
|
||||
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<Option<SignedEntry>, 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<usize, Self::Error> {
|
||||
Ok(self.with_records(|records| records.map(|v| v.len()).unwrap_or_default()))
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.len()? == 0)
|
||||
}
|
||||
|
||||
fn get_fingerprint(
|
||||
&self,
|
||||
range: &Range<RecordIdentifier>,
|
||||
limit: Option<&Range<RecordIdentifier>>,
|
||||
) -> Result<Fingerprint, Self::Error> {
|
||||
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<RecordIdentifier>,
|
||||
limit: Option<Range<RecordIdentifier>>,
|
||||
) -> Result<Self::RangeIterator<'_>, Self::Error> {
|
||||
Ok(RangeIterator {
|
||||
iter: self.records_iter(),
|
||||
range: Some(range),
|
||||
limit,
|
||||
})
|
||||
}
|
||||
|
||||
fn remove(&mut self, key: &RecordIdentifier) -> Result<Vec<SignedEntry>, 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::AllIterator<'_>, 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<Range<RecordIdentifier>>,
|
||||
limit: Option<Range<RecordIdentifier>>,
|
||||
}
|
||||
|
||||
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<Self::Item> {
|
||||
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()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<RecordIdentifier, SignedEntry>;
|
||||
|
||||
/// 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<S: ranger::Store<RecordIdentifier, SignedEntry>> {
|
||||
inner: Arc<RwLock<InnerReplica<S>>>,
|
||||
on_insert_sender: flume::Sender<(InsertOrigin, SignedEntry)>,
|
||||
#[allow(clippy::type_complexity)]
|
||||
on_insert_receiver: Arc<Mutex<Option<flume::Receiver<(InsertOrigin, SignedEntry)>>>>,
|
||||
}
|
||||
|
||||
#[derive(derive_more::Debug)]
|
||||
struct InnerReplica<S: ranger::Store<RecordIdentifier, SignedEntry>> {
|
||||
namespace: Namespace,
|
||||
peer: Peer<RecordIdentifier, SignedEntry, S>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct ReplicaData {
|
||||
entries: Vec<SignedEntry>,
|
||||
namespace: Namespace,
|
||||
}
|
||||
|
||||
impl<S: ranger::Store<RecordIdentifier, SignedEntry>> Replica<S> {
|
||||
/// 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<flume::Receiver<(InsertOrigin, SignedEntry)>> {
|
||||
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<Hash, S::Error> {
|
||||
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<crate::ranger::Message<RecordIdentifier, SignedEntry>, 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<RecordIdentifier, SignedEntry>,
|
||||
from_peer: PeerIdBytes,
|
||||
) -> Result<Option<crate::ranger::Message<RecordIdentifier, SignedEntry>>, 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<u8>) {
|
||||
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<u8> {
|
||||
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<u8>,
|
||||
/// 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<Self>) -> 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<Self> {
|
||||
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<u8>) {
|
||||
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<u8>) {
|
||||
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<S: store::Store>(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::<Result<_>>()?;
|
||||
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::<Result<_>>()?;
|
||||
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::<Result<_>>()?;
|
||||
assert_eq!(entries.len(), 1);
|
||||
|
||||
// Get latest by prefix
|
||||
let entries: Vec<_> = store
|
||||
.get(
|
||||
my_replica.namespace(),
|
||||
GetFilter::latest().with_prefix(b"/cool"),
|
||||
)?
|
||||
.collect::<Result<_>>()?;
|
||||
assert_eq!(entries.len(), 1);
|
||||
|
||||
// Get All
|
||||
let entries: Vec<_> = store
|
||||
.get(my_replica.namespace(), GetFilter::all())?
|
||||
.collect::<Result<_>>()?;
|
||||
assert_eq!(entries.len(), 12);
|
||||
|
||||
// Get All latest
|
||||
let entries: Vec<_> = store
|
||||
.get(my_replica.namespace(), GetFilter::latest())?
|
||||
.collect::<Result<_>>()?;
|
||||
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::<Result<_>>()?;
|
||||
assert_eq!(entries.len(), 2);
|
||||
|
||||
let entries: Vec<_> = store
|
||||
.get(
|
||||
my_replica.namespace(),
|
||||
GetFilter::all()
|
||||
.with_author(bob.id())
|
||||
.with_key("/cool/path"),
|
||||
)?
|
||||
.collect::<Result<_>>()?;
|
||||
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::<Result<_>>()?;
|
||||
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::<Result<_>>()?;
|
||||
assert_eq!(entries.len(), 2);
|
||||
|
||||
// Get latest by prefix
|
||||
let entries: Vec<_> = store
|
||||
.get(
|
||||
my_replica.namespace(),
|
||||
GetFilter::latest().with_prefix(b"/cool"),
|
||||
)?
|
||||
.collect::<Result<_>>()?;
|
||||
assert_eq!(entries.len(), 2);
|
||||
|
||||
// Get all by prefix
|
||||
let entries: Vec<_> = store
|
||||
.get(
|
||||
my_replica.namespace(),
|
||||
GetFilter::all().with_prefix(b"/cool"),
|
||||
)?
|
||||
.collect::<Result<_>>()?;
|
||||
assert_eq!(entries.len(), 3);
|
||||
|
||||
// Get All
|
||||
let entries: Vec<_> = store
|
||||
.get(my_replica.namespace(), GetFilter::all())?
|
||||
.collect::<Result<_>>()?;
|
||||
assert_eq!(entries.len(), 13);
|
||||
|
||||
// Get All latest
|
||||
let entries: Vec<_> = store
|
||||
.get(my_replica.namespace(), GetFilter::latest())?
|
||||
.collect::<Result<_>>()?;
|
||||
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<S: store::Store>(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<S: store::Store>(
|
||||
author: &Author,
|
||||
alice: &Replica<S::Instance>,
|
||||
alice_store: &S,
|
||||
bob: &Replica<S::Instance>,
|
||||
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(())
|
||||
}
|
||||
}
|
||||
+22
-3
@@ -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"]
|
||||
|
||||
@@ -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("<bad key>");
|
||||
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)
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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<C> {
|
||||
rpc: RpcClient<ProviderService, C>,
|
||||
}
|
||||
|
||||
impl<C> Iroh<C>
|
||||
where
|
||||
C: ServiceConnection<ProviderService>,
|
||||
{
|
||||
/// Create a new high-level client to a Iroh node from the low-level RPC client.
|
||||
pub fn new(rpc: RpcClient<ProviderService, C>) -> Self {
|
||||
Self { rpc }
|
||||
}
|
||||
|
||||
/// Create a new document author.
|
||||
pub async fn create_author(&self) -> Result<AuthorId> {
|
||||
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<impl Stream<Item = Result<AuthorId>>> {
|
||||
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<Doc<C>> {
|
||||
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<Doc<C>> {
|
||||
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<impl Stream<Item = Result<NamespaceId>>> {
|
||||
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<Doc<C>> {
|
||||
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<Option<Doc<C>>> {
|
||||
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<Bytes> {
|
||||
let res = self.rpc.rpc(BytesGetRequest { hash }).await??;
|
||||
Ok(res.data)
|
||||
}
|
||||
|
||||
/// Get statistics of the running node.
|
||||
pub async fn stats(&self) -> Result<HashMap<String, CounterStats>> {
|
||||
let res = self.rpc.rpc(StatsGetRequest {}).await??;
|
||||
Ok(res.stats)
|
||||
}
|
||||
}
|
||||
|
||||
/// Document handle
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Doc<C> {
|
||||
id: NamespaceId,
|
||||
rpc: RpcClient<ProviderService, C>,
|
||||
}
|
||||
|
||||
impl<C> Doc<C>
|
||||
where
|
||||
C: ServiceConnection<ProviderService>,
|
||||
{
|
||||
/// 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<u8>,
|
||||
value: Vec<u8>,
|
||||
) -> Result<SignedEntry> {
|
||||
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<Bytes> {
|
||||
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<u8>) -> Result<SignedEntry> {
|
||||
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<impl Stream<Item = Result<SignedEntry>>> {
|
||||
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<DocTicket> {
|
||||
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<PeerSource>) -> 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<impl Stream<Item = anyhow::Result<LiveEvent>>> {
|
||||
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<LiveStatus> {
|
||||
let res = self.rpc.rpc(DocInfoRequest { doc_id: self.id }).await??;
|
||||
Ok(res.status)
|
||||
}
|
||||
}
|
||||
|
||||
fn flatten<T, E1, E2>(
|
||||
s: impl Stream<Item = StdResult<StdResult<T, E1>, E2>>,
|
||||
) -> impl Stream<Item = Result<T>>
|
||||
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()),
|
||||
})
|
||||
}
|
||||
@@ -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<ProviderService, FlumeConnection<ProviderResponse, ProviderRequest>>;
|
||||
|
||||
/// 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<FlumeConnection<ProviderResponse, ProviderRequest>>;
|
||||
|
||||
/// In-memory document client to an iroh node running in the same process.
|
||||
pub type Doc = super::Doc<FlumeConnection<ProviderResponse, ProviderRequest>>;
|
||||
@@ -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<ProviderService, QuinnConnection<ProviderResponse, ProviderRequest>>;
|
||||
|
||||
/// Client to an iroh node running in a seperate process.
|
||||
///
|
||||
/// This is obtained from [`connect`].
|
||||
pub type Iroh = super::Iroh<QuinnConnection<ProviderResponse, ProviderRequest>>;
|
||||
|
||||
/// RPC document client to an iroh node running in a seperate process.
|
||||
pub type Doc = super::Doc<QuinnConnection<ProviderResponse, ProviderRequest>>;
|
||||
|
||||
/// Connect to an iroh node running on the same computer, but in a different process.
|
||||
pub async fn connect(rpc_port: u16) -> anyhow::Result<Iroh> {
|
||||
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<RpcClient> {
|
||||
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<Vec<u8>>,
|
||||
keylog: bool,
|
||||
) -> anyhow::Result<quinn::Endpoint> {
|
||||
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)
|
||||
}
|
||||
+19
-50
@@ -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<RpcClient<ProviderService, QuinnConnection<ProviderResponse, ProviderRequest>>>
|
||||
{
|
||||
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::<ProviderService, _>::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<Vec<u8>>,
|
||||
keylog: bool,
|
||||
) -> Result<quinn::Endpoint> {
|
||||
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<RpcClient> {
|
||||
iroh::client::quic::connect_raw(rpc_port).await
|
||||
}
|
||||
|
||||
#[cfg(feature = "metrics")]
|
||||
pub fn init_metrics_collection(
|
||||
pub fn start_metrics_server(
|
||||
metrics_addr: Option<SocketAddr>,
|
||||
rt: &iroh_bytes::util::runtime::Handle,
|
||||
) -> Option<tokio::task::JoinHandle<()>> {
|
||||
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}");
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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<D: Store>(
|
||||
db: D,
|
||||
async fn provide<B: BaoStore, D: DocStore>(
|
||||
bao_store: B,
|
||||
doc_store: D,
|
||||
rt: &runtime::Handle,
|
||||
key: Option<PathBuf>,
|
||||
opts: ProvideOptions,
|
||||
) -> Result<Node<D>> {
|
||||
) -> Result<Node<B, D>> {
|
||||
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);
|
||||
|
||||
@@ -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<PeerSource>,
|
||||
},
|
||||
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<AuthorId>,
|
||||
/// 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<AuthorId>,
|
||||
/// 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<String>,
|
||||
},
|
||||
}
|
||||
|
||||
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!("<invalid UTF-8>"),
|
||||
},
|
||||
Err(err) => println!("<failed to get content: {err}>"),
|
||||
}
|
||||
} else {
|
||||
println!(
|
||||
"<skipping content with len {}: too large to print>",
|
||||
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("<bad key>");
|
||||
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)
|
||||
}
|
||||
+6
-1
@@ -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");
|
||||
|
||||
@@ -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<BoxFuture<'static, Option<(Hash, u64)>>>;
|
||||
|
||||
/// 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<Mutex<HashMap<Hash, DownloadFuture>>>,
|
||||
to_actor_tx: flume::Sender<DownloadRequest>,
|
||||
}
|
||||
|
||||
impl Downloader {
|
||||
/// Create a new downloader
|
||||
pub fn new<B: BaoStore>(
|
||||
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<PublicKey>) {
|
||||
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<Option<(Hash, u64)>>;
|
||||
type PendingDownloadsFutures =
|
||||
FuturesUnordered<LocalBoxFuture<'static, (PublicKey, Hash, anyhow::Result<Option<u64>>)>>;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct DownloadRequest {
|
||||
hash: Hash,
|
||||
peers: Vec<PublicKey>,
|
||||
reply: DownloadReply,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct DownloadActor<B> {
|
||||
dialer: Dialer,
|
||||
db: B,
|
||||
conns: HashMap<PublicKey, quinn::Connection>,
|
||||
replies: HashMap<Hash, VecDeque<DownloadReply>>,
|
||||
pending_download_futs: PendingDownloadsFutures,
|
||||
queue: DownloadQueue,
|
||||
rx: flume::Receiver<DownloadRequest>,
|
||||
}
|
||||
impl<B: BaoStore> DownloadActor<B> {
|
||||
fn new(endpoint: MagicEndpoint, db: B, rx: flume::Receiver<DownloadRequest>) -> 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<Hash, VecDeque<PublicKey>>,
|
||||
candidates_by_peer: HashMap<PublicKey, VecDeque<Hash>>,
|
||||
running_by_hash: HashMap<Hash, PublicKey>,
|
||||
running_by_peer: HashMap<PublicKey, Hash>,
|
||||
}
|
||||
|
||||
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<Hash> {
|
||||
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<Hash> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
+2
-2
@@ -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;
|
||||
|
||||
|
||||
@@ -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<HashMap<String, CounterStats>> {
|
||||
let mut map = HashMap::new();
|
||||
let core =
|
||||
iroh_metrics::core::Core::get().ok_or_else(|| anyhow::anyhow!("metrics are disabled"))?;
|
||||
collect(
|
||||
core.get_collector::<iroh_sync::metrics::Metrics>(),
|
||||
&mut map,
|
||||
);
|
||||
collect(
|
||||
core.get_collector::<iroh_net::metrics::MagicsockMetrics>(),
|
||||
&mut map,
|
||||
);
|
||||
collect(
|
||||
core.get_collector::<iroh_net::metrics::NetcheckMetrics>(),
|
||||
&mut map,
|
||||
);
|
||||
collect(
|
||||
core.get_collector::<iroh_net::metrics::PortmapMetrics>(),
|
||||
&mut map,
|
||||
);
|
||||
collect(
|
||||
core.get_collector::<iroh_net::metrics::DerpMetrics>(),
|
||||
&mut map,
|
||||
);
|
||||
Ok(map)
|
||||
}
|
||||
|
||||
// TODO: support other things than counters
|
||||
fn collect(metrics: Option<&impl Iterable>, map: &mut HashMap<String, CounterStats>) {
|
||||
let Some(metrics) = metrics else {
|
||||
return;
|
||||
};
|
||||
for (name, counter) in metrics.iter() {
|
||||
if let Some(counter) = counter.downcast_ref::<Counter>() {
|
||||
let value = counter.get();
|
||||
let description = counter.description.to_string();
|
||||
map.insert(name.to_string(), CounterStats { value, description });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+276
-65
@@ -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<D, E = DummyServerEndpoint, C = NoCollectionParser>
|
||||
where
|
||||
pub struct Builder<
|
||||
D,
|
||||
S = iroh_sync::store::memory::Store,
|
||||
E = DummyServerEndpoint,
|
||||
C = NoCollectionParser,
|
||||
> where
|
||||
D: Map,
|
||||
S: DocStore,
|
||||
E: ServiceEndpoint<ProviderService>,
|
||||
C: CollectionParser,
|
||||
{
|
||||
@@ -91,9 +108,10 @@ where
|
||||
derp_map: Option<DerpMap>,
|
||||
collection_parser: C,
|
||||
rt: Option<runtime::Handle>,
|
||||
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<D: Map> Builder<D> {
|
||||
impl<D: Map, S: DocStore> Builder<D, S> {
|
||||
/// 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<D: Map> Builder<D> {
|
||||
auth_handler: Arc::new(NoopRequestAuthorizationHandler),
|
||||
collection_parser: NoCollectionParser,
|
||||
rt: None,
|
||||
docs,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<D, E, C> Builder<D, E, C>
|
||||
impl<D, S, E, C> Builder<D, S, E, C>
|
||||
where
|
||||
D: Store,
|
||||
D: BaoStore,
|
||||
S: DocStore,
|
||||
E: ServiceEndpoint<ProviderService>,
|
||||
C: CollectionParser,
|
||||
{
|
||||
@@ -162,7 +182,7 @@ where
|
||||
pub fn rpc_endpoint<E2: ServiceEndpoint<ProviderService>>(
|
||||
self,
|
||||
value: E2,
|
||||
) -> Builder<D, E2, C> {
|
||||
) -> Builder<D, S, E2, C> {
|
||||
// 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<C2: CollectionParser>(
|
||||
self,
|
||||
collection_parser: C2,
|
||||
) -> Builder<D, E, C2> {
|
||||
) -> Builder<D, S, E, C2> {
|
||||
// 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<Node<D>> {
|
||||
pub async fn spawn(self) -> Result<Node<D, S>> {
|
||||
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<Gossip> = 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<EventCallback>,
|
||||
handler: RpcHandler<D, C>,
|
||||
handler: RpcHandler<D, S, C>,
|
||||
rpc: E,
|
||||
internal_rpc: impl ServiceEndpoint<ProviderService>,
|
||||
custom_get_handler: Arc<dyn CustomGetHandler>,
|
||||
auth_handler: Arc<dyn RequestAuthorizationHandler>,
|
||||
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<String> {
|
||||
let data = connecting.handshake_data().await?;
|
||||
match data.downcast::<quinn::crypto::rustls::HandshakeData>() {
|
||||
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<D: BaoStore, S: DocStore, C: CollectionParser>(
|
||||
connecting: quinn::Connecting,
|
||||
alpn: String,
|
||||
node: Arc<NodeInner<D, S>>,
|
||||
gossip: Gossip,
|
||||
collection_parser: C,
|
||||
custom_get_handler: Arc<dyn CustomGetHandler>,
|
||||
auth_handler: Arc<dyn RequestAuthorizationHandler>,
|
||||
) -> 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<dyn Fn(Event) -> 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<D: Map> {
|
||||
inner: Arc<NodeInner<D>>,
|
||||
pub struct Node<D: Map, S: DocStore> {
|
||||
inner: Arc<NodeInner<D, S>>,
|
||||
task: Shared<BoxFuture<'static, Result<(), Arc<JoinError>>>>,
|
||||
}
|
||||
|
||||
#[derive(derive_more::Debug)]
|
||||
struct NodeInner<D> {
|
||||
struct NodeInner<D, S: DocStore> {
|
||||
db: D,
|
||||
endpoint: MagicEndpoint,
|
||||
secret_key: SecretKey,
|
||||
@@ -503,6 +590,7 @@ struct NodeInner<D> {
|
||||
#[allow(dead_code)]
|
||||
callbacks: Callbacks,
|
||||
rt: runtime::Handle,
|
||||
pub(crate) sync: SyncEngine<S>,
|
||||
}
|
||||
|
||||
/// Events emitted by the [`Node`] informing about the current status.
|
||||
@@ -512,12 +600,12 @@ pub enum Event {
|
||||
ByteProvide(iroh_bytes::provider::Event),
|
||||
}
|
||||
|
||||
impl<D: ReadableStore> Node<D> {
|
||||
impl<D: ReadableStore, S: DocStore> Node<D, S> {
|
||||
/// 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<D> {
|
||||
Builder::with_db(db)
|
||||
pub fn builder(bao_store: D, doc_store: S) -> Builder<D, S> {
|
||||
Builder::with_db_and_store(bao_store, doc_store)
|
||||
}
|
||||
|
||||
/// The address on which the node socket is bound.
|
||||
@@ -557,12 +645,15 @@ impl<D: ReadableStore> Node<D> {
|
||||
}
|
||||
|
||||
/// Returns a handle that can be used to do RPC calls to the node internally.
|
||||
pub fn controller(
|
||||
&self,
|
||||
) -> RpcClient<ProviderService, impl ServiceConnection<ProviderService>> {
|
||||
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<D: ReadableStore> Node<D> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<D: Map> NodeInner<D> {
|
||||
impl<D: Map, S: DocStore> NodeInner<D, S> {
|
||||
async fn local_endpoints(&self) -> Result<Vec<Endpoint>> {
|
||||
self.endpoint.local_endpoints().await
|
||||
}
|
||||
@@ -616,7 +707,7 @@ impl<D: Map> NodeInner<D> {
|
||||
}
|
||||
|
||||
/// The future completes when the spawned tokio task finishes.
|
||||
impl<D: Map> Future for Node<D> {
|
||||
impl<D: Map, S: DocStore> Future for Node<D, S> {
|
||||
type Output = Result<(), Arc<JoinError>>;
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
|
||||
@@ -625,12 +716,12 @@ impl<D: Map> Future for Node<D> {
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct RpcHandler<D, C> {
|
||||
inner: Arc<NodeInner<D>>,
|
||||
struct RpcHandler<D, S: DocStore, C> {
|
||||
inner: Arc<NodeInner<D, S>>,
|
||||
collection_parser: C,
|
||||
}
|
||||
|
||||
impl<D: Store, C: CollectionParser> RpcHandler<D, C> {
|
||||
impl<D: BaoStore, S: DocStore, C: CollectionParser> RpcHandler<D, S, C> {
|
||||
fn rt(&self) -> runtime::Handle {
|
||||
self.inner.rt.clone()
|
||||
}
|
||||
@@ -775,7 +866,6 @@ impl<D: Store, C: CollectionParser> RpcHandler<D, C> {
|
||||
{
|
||||
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<D: Store, C: CollectionParser> RpcHandler<D, C> {
|
||||
anyhow::bail!("collections not supported");
|
||||
}
|
||||
|
||||
async fn stats(self, _req: StatsGetRequest) -> RpcResult<StatsGetResponse> {
|
||||
#[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<D: Store, C: CollectionParser> RpcHandler<D, C> {
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
// TODO: streaming
|
||||
async fn bytes_get(self, req: BytesGetRequest) -> RpcResult<BytesGetResponse> {
|
||||
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<D: Store, E: ServiceEndpoint<ProviderService>, C: CollectionParser>(
|
||||
fn handle_rpc_request<
|
||||
D: BaoStore,
|
||||
S: DocStore,
|
||||
E: ServiceEndpoint<ProviderService>,
|
||||
C: CollectionParser,
|
||||
>(
|
||||
msg: ProviderRequest,
|
||||
chan: RpcChannel<ProviderService, E>,
|
||||
handler: &RpcHandler<D, C>,
|
||||
handler: &RpcHandler<D, S, C>,
|
||||
rt: &runtime::Handle,
|
||||
) {
|
||||
let handler = handler.clone();
|
||||
@@ -1053,10 +1185,87 @@ fn handle_rpc_request<D: Store, E: ServiceEndpoint<ProviderService>, 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()
|
||||
|
||||
+389
-3
@@ -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<ProviderService> for AuthorListRequest {
|
||||
type Pattern = ServerStreaming;
|
||||
}
|
||||
|
||||
impl ServerStreamingMsg<ProviderService> for AuthorListRequest {
|
||||
type Response = RpcResult<AuthorListResponse>;
|
||||
}
|
||||
|
||||
/// 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<ProviderService> for AuthorCreateRequest {
|
||||
type Response = RpcResult<AuthorCreateResponse>;
|
||||
}
|
||||
|
||||
/// 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<ProviderService> for AuthorImportRequest {
|
||||
type Response = RpcResult<AuthorImportResponse>;
|
||||
}
|
||||
|
||||
/// 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<ProviderService> for DocSubscribeRequest {
|
||||
type Pattern = ServerStreaming;
|
||||
}
|
||||
|
||||
impl ServerStreamingMsg<ProviderService> for DocSubscribeRequest {
|
||||
type Response = RpcResult<DocSubscribeResponse>;
|
||||
}
|
||||
|
||||
/// 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<ProviderService> for DocListRequest {
|
||||
type Pattern = ServerStreaming;
|
||||
}
|
||||
|
||||
impl ServerStreamingMsg<ProviderService> for DocListRequest {
|
||||
type Response = RpcResult<DocListResponse>;
|
||||
}
|
||||
|
||||
/// 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<ProviderService> for DocCreateRequest {
|
||||
type Response = RpcResult<DocCreateResponse>;
|
||||
}
|
||||
|
||||
/// 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<PeerSource>,
|
||||
}
|
||||
impl DocTicket {
|
||||
/// Create a new doc ticket
|
||||
pub fn new(key: KeyBytes, peers: Vec<PeerSource>) -> Self {
|
||||
Self { key, peers }
|
||||
}
|
||||
/// Serialize the ticket to a byte array.
|
||||
pub fn to_bytes(&self) -> anyhow::Result<Vec<u8>> {
|
||||
let bytes = postcard::to_stdvec(&self)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
/// Parse ticket from a byte array.
|
||||
pub fn from_bytes(bytes: &[u8]) -> anyhow::Result<Self> {
|
||||
let slf = postcard::from_bytes(bytes)?;
|
||||
Ok(slf)
|
||||
}
|
||||
}
|
||||
impl FromStr for DocTicket {
|
||||
type Err = anyhow::Error;
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
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<ProviderService> for DocImportRequest {
|
||||
type Response = RpcResult<DocImportResponse>;
|
||||
}
|
||||
|
||||
/// 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<ProviderService> for DocShareRequest {
|
||||
type Response = RpcResult<DocShareResponse>;
|
||||
}
|
||||
|
||||
/// 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<ProviderService> for DocInfoRequest {
|
||||
type Response = RpcResult<DocInfoResponse>;
|
||||
}
|
||||
|
||||
/// 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<PeerSource>,
|
||||
}
|
||||
|
||||
impl RpcMsg<ProviderService> for DocStartSyncRequest {
|
||||
type Response = RpcResult<DocStartSyncResponse>;
|
||||
}
|
||||
|
||||
/// 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<ProviderService> for DocStopSyncRequest {
|
||||
type Response = RpcResult<DocStopSyncResponse>;
|
||||
}
|
||||
|
||||
/// 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<u8>,
|
||||
/// Value of this entry.
|
||||
// TODO: Allow to provide the hash directly
|
||||
// TODO: Add a way to provide content as stream
|
||||
pub value: Vec<u8>,
|
||||
}
|
||||
|
||||
impl RpcMsg<ProviderService> for DocSetRequest {
|
||||
type Response = RpcResult<DocSetResponse>;
|
||||
}
|
||||
|
||||
/// 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<ProviderService> for DocGetRequest {
|
||||
type Pattern = ServerStreaming;
|
||||
}
|
||||
|
||||
impl ServerStreamingMsg<ProviderService> for DocGetRequest {
|
||||
type Response = RpcResult<DocGetResponse>;
|
||||
}
|
||||
|
||||
/// 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<ProviderService> for BytesGetRequest {
|
||||
type Response = RpcResult<BytesGetResponse>;
|
||||
}
|
||||
|
||||
/// 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<ProviderService> for StatsGetRequest {
|
||||
type Response = RpcResult<StatsGetResponse>;
|
||||
}
|
||||
|
||||
/// 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<String, CounterStats>,
|
||||
}
|
||||
|
||||
/// 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<AuthorListResponse>),
|
||||
AuthorCreate(RpcResult<AuthorCreateResponse>),
|
||||
AuthorImport(RpcResult<AuthorImportResponse>),
|
||||
|
||||
DocInfo(RpcResult<DocInfoResponse>),
|
||||
DocList(RpcResult<DocListResponse>),
|
||||
DocCreate(RpcResult<DocCreateResponse>),
|
||||
DocImport(RpcResult<DocImportResponse>),
|
||||
DocSet(RpcResult<DocSetResponse>),
|
||||
DocGet(RpcResult<DocGetResponse>),
|
||||
DocShare(RpcResult<DocShareResponse>),
|
||||
DocStartSync(RpcResult<DocStartSyncResponse>),
|
||||
DocStopSync(RpcResult<DocStopSyncResponse>),
|
||||
DocSubscribe(RpcResult<DocSubscribeResponse>),
|
||||
|
||||
BytesGet(RpcResult<BytesGetResponse>),
|
||||
|
||||
Stats(RpcResult<StatsGetResponse>),
|
||||
}
|
||||
|
||||
impl Service for ProviderService {
|
||||
|
||||
@@ -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<S: Store> {
|
||||
pub(crate) rt: Handle,
|
||||
pub(crate) store: S,
|
||||
pub(crate) endpoint: MagicEndpoint,
|
||||
pub(crate) live: LiveSync<S>,
|
||||
active: Arc<RwLock<HashSet<NamespaceId>>>,
|
||||
}
|
||||
|
||||
impl<S: Store> SyncEngine<S> {
|
||||
/// 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<B: BaoStore>(
|
||||
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<PeerSource>,
|
||||
) -> 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<Replica<S::Instance>> {
|
||||
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<Author> {
|
||||
self.store
|
||||
.get_author(id)?
|
||||
.ok_or_else(|| anyhow!("author not found"))
|
||||
}
|
||||
}
|
||||
@@ -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<SocketAddr>,
|
||||
/// Derp region for this peer
|
||||
pub derp_region: Option<u16>,
|
||||
}
|
||||
|
||||
impl PeerSource {
|
||||
/// Deserializes from bytes.
|
||||
fn from_bytes(bytes: &[u8]) -> anyhow::Result<Self> {
|
||||
postcard::from_bytes(bytes).map_err(Into::into)
|
||||
}
|
||||
/// Serializes to bytes.
|
||||
pub fn to_bytes(&self) -> Vec<u8> {
|
||||
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<Self> {
|
||||
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<Self, Self::Err> {
|
||||
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<S: store::Store> {
|
||||
Status {
|
||||
namespace: NamespaceId,
|
||||
s: sync::oneshot::Sender<Option<LiveStatus>>,
|
||||
},
|
||||
StartSync {
|
||||
replica: Replica<S::Instance>,
|
||||
peers: Vec<PeerSource>,
|
||||
},
|
||||
JoinPeers {
|
||||
namespace: NamespaceId,
|
||||
peers: Vec<PeerSource>,
|
||||
},
|
||||
StopSync {
|
||||
namespace: NamespaceId,
|
||||
},
|
||||
Shutdown,
|
||||
Subscribe {
|
||||
namespace: NamespaceId,
|
||||
#[debug("cb")]
|
||||
cb: OnLiveEventCallback,
|
||||
s: sync::oneshot::Sender<Result<RemovalToken>>,
|
||||
},
|
||||
Unsubscribe {
|
||||
namespace: NamespaceId,
|
||||
token: RemovalToken,
|
||||
s: sync::oneshot::Sender<bool>,
|
||||
},
|
||||
}
|
||||
|
||||
/// 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<dyn Fn(LiveEvent) -> 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<EntryStatus> 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<S: store::Store> {
|
||||
to_actor_tx: mpsc::Sender<ToActor<S>>,
|
||||
task: Shared<BoxFuture<'static, Result<(), Arc<JoinError>>>>,
|
||||
}
|
||||
|
||||
impl<S: store::Store> LiveSync<S> {
|
||||
/// Start the live sync.
|
||||
///
|
||||
/// This spawn a background actor to handle gossip events and forward operations over broadcast
|
||||
/// messages.
|
||||
pub fn spawn<B: baomap::Store>(
|
||||
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::<S>::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<S::Instance>,
|
||||
peers: Vec<PeerSource>,
|
||||
) -> Result<()> {
|
||||
self.to_actor_tx
|
||||
.send(ToActor::<S>::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<PeerSource>) -> Result<()> {
|
||||
self.to_actor_tx
|
||||
.send(ToActor::<S>::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::<S>::StopSync { namespace })
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Subscribes `cb` to events on this `namespace`.
|
||||
pub async fn subscribe<F>(&self, namespace: NamespaceId, cb: F) -> Result<RemovalToken>
|
||||
where
|
||||
F: Fn(LiveEvent) -> BoxFuture<'static, KeepCallback> + Send + Sync + 'static,
|
||||
{
|
||||
let (s, r) = sync::oneshot::channel();
|
||||
self.to_actor_tx
|
||||
.send(ToActor::<S>::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<bool> {
|
||||
let (s, r) = sync::oneshot::channel();
|
||||
self.to_actor_tx
|
||||
.send(ToActor::<S>::Unsubscribe {
|
||||
namespace,
|
||||
token,
|
||||
s,
|
||||
})
|
||||
.await?;
|
||||
let token = r.await?;
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
/// Get status for a document
|
||||
pub async fn status(&self, namespace: NamespaceId) -> Result<Option<LiveStatus>> {
|
||||
let (s, r) = sync::oneshot::channel();
|
||||
self.to_actor_tx
|
||||
.send(ToActor::<S>::Status { namespace, s })
|
||||
.await?;
|
||||
let status = r.await?;
|
||||
Ok(status)
|
||||
}
|
||||
}
|
||||
|
||||
// Currently peers might double-sync in both directions.
|
||||
struct Actor<S: store::Store, B: baomap::Store> {
|
||||
endpoint: MagicEndpoint,
|
||||
gossip: Gossip,
|
||||
bao_store: B,
|
||||
downloader: Downloader,
|
||||
|
||||
replicas: HashMap<TopicId, Replica<S::Instance>>,
|
||||
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<ToActor<S>>,
|
||||
|
||||
pending_syncs: FuturesUnordered<BoxFuture<'static, (TopicId, PublicKey, Result<()>)>>,
|
||||
pending_joins: FuturesUnordered<BoxFuture<'static, (TopicId, Result<()>)>>,
|
||||
|
||||
event_subscriptions: HashMap<TopicId, HashMap<u64, OnLiveEventCallback>>,
|
||||
event_removal_id: AtomicU64,
|
||||
|
||||
pending_downloads: FuturesUnordered<BoxFuture<'static, Option<(TopicId, Hash)>>>,
|
||||
}
|
||||
|
||||
/// Token needed to remove inserted callbacks.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct RemovalToken(u64);
|
||||
|
||||
impl<S: store::Store, B: baomap::Store> Actor<S, B> {
|
||||
pub fn new(
|
||||
endpoint: MagicEndpoint,
|
||||
gossip: Gossip,
|
||||
bao_store: B,
|
||||
downloader: Downloader,
|
||||
to_actor_rx: mpsc::Receiver<ToActor<S>>,
|
||||
) -> 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::<S>(&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<LiveStatus> {
|
||||
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<RemovalToken> {
|
||||
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<PeerSource>,
|
||||
) -> anyhow::Result<()> {
|
||||
let topic = TopicId::from_bytes(*namespace.as_bytes());
|
||||
let peer_ids: Vec<PublicKey> = 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<S::Instance>,
|
||||
peers: Vec<PeerSource>,
|
||||
) -> 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<u64, OnLiveEventCallback>, 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<S: Store> SyncEngine<S> {
|
||||
pub fn author_create(&self, _req: AuthorCreateRequest) -> RpcResult<AuthorCreateResponse> {
|
||||
// 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<Item = RpcResult<AuthorListResponse>> {
|
||||
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<DocCreateResponse> {
|
||||
let doc = self.store.new_replica(Namespace::new(&mut OsRng {}))?;
|
||||
Ok(DocCreateResponse {
|
||||
id: doc.namespace(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn doc_list(&self, _req: DocListRequest) -> impl Stream<Item = RpcResult<DocListResponse>> {
|
||||
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<DocInfoResponse> {
|
||||
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<DocShareResponse> {
|
||||
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<Item = RpcResult<DocSubscribeResponse>> {
|
||||
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<DocImportResponse> {
|
||||
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<DocStartSyncResponse> {
|
||||
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<DocStopSyncResponse> {
|
||||
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<B: BaoStore>(
|
||||
&self,
|
||||
bao_store: &B,
|
||||
req: DocSetRequest,
|
||||
) -> RpcResult<DocSetResponse> {
|
||||
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<Item = RpcResult<DocGetResponse>> {
|
||||
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<T>(
|
||||
ite: Result<impl Iterator<Item = Result<T, impl Into<RpcError>>>, impl Into<RpcError>>,
|
||||
) -> impl Iterator<Item = RpcResult<T>> {
|
||||
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()),
|
||||
}
|
||||
}
|
||||
+32
-7
@@ -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<Path>, dst: impl AsRef<Path>) -> io::Result<()> {
|
||||
std::fs::create_dir_all(&dst)?;
|
||||
fn copy_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> 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(())
|
||||
|
||||
@@ -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<D: Store>(
|
||||
db: D,
|
||||
addr: SocketAddr,
|
||||
) -> Builder<D, DummyServerEndpoint, IrohCollectionParser> {
|
||||
Node::builder(db)
|
||||
) -> Builder<D, store::memory::Store, DummyServerEndpoint, IrohCollectionParser> {
|
||||
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)
|
||||
|
||||
@@ -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<Node<iroh::baomap::mem::Store, store::memory::Store>> {
|
||||
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<Vec<Node<iroh::baomap::mem::Store, store::memory::Store>>> {
|
||||
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::<Vec<_>>();
|
||||
|
||||
// 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<Vec<u8>> {
|
||||
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();
|
||||
}
|
||||
Reference in New Issue
Block a user