1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
#![allow(clippy::tabs_in_doc_comments)] //because "cargo fmt" keeps replacing comment spaces with tabs, despite "format_code_in_doc_comments=false" /*! Hakuban is a data-object sharing library. Check out the [README](https://gitlab.com/yunta/hakuban/-/blob/main/README.md) file if you haven't been there yet. Hakuban is a simple mechanism which allows exposing data-objects in some processes, and observing them in other processes. Hakuban takes care of all the boring details of data transmission, synchronization, object lifetime management, load balancing etc. At a high level the API can be divided into 5 parts: * Network management ([LocalNode], [tokio::WebsocketListener], [tokio::WebsocketConnector]) * Object and tag contract management, and object state access ([ObjectObserve], [ObjectExpose], [TagObserve], [TagExpose], [ObjectDescriptor], [TagDescriptor]) * Event handling ([events] module) * FFI ([ffi] module) * Other modules and structures, exposed to enable tests and custom transports implementation ([message], [node::RemoteNode]) # Concepts An __object__ is a basic unit of share-able data. Objects can be [observed](ObjectObserve) and/or [exposed](ObjectExpose) by processes. Every object is uniquely identified by a set of __tags__ and a single json object[^1]. Such unique identifier is represented by the [ObjectDescriptor] struct. There is no API to access objects directly. Instead, object state can be retrieved and asserted through [ObjectObserve] and [ObjectExpose] contracts. A __tag__ represents a set of __objects__. Process [observing](TagObserve) a tag declares interest in observing all existing objects tagged with that tag. Likewise, process [exposing](TagExpose) a tag declares capability to expose any and all existing objects tagged with that tag. Every tag is uniquely identified by a json object[^1]. Represented by the [TagDescriptor] struct. Tags are not meant to represent data model level collections. They are merely wildcards for declaring observe/expose contracts for objects of yet-unknown [descriptors](ObjectDescriptor). `TODO: explain with example` To exchange object versions processes can connect to each other in a tree topology. Processes (nodes) at the leaf-end of the tree will only receive data relevant to them. [LocalNode] struct represents local hakuban node's state. It is the main access point to the hakuban network. It allows building contracts and access to node-wide events. (There is [node::RemoteNode] struct too, but it should not be needed outside of custom network transport implementations. Look at tokio.rs if you want to do that.) `TODO: explain how single exposer is picked and assigned for each object` [^1]: any valid json really, string, array, number, etc. # Example ```rust # fn main() -> Result<(),hakuban::DefaultSerializerError> { let hakuban = hakuban::LocalNode::builder().build(); let observe = hakuban.object((["some-tag"],"xxx")).observe::<String>(); std::thread::spawn(move || { let expose = hakuban.object((["some-tag"],"xxx")).expose(); expose.set_object_data(&"aaaaaa"); }); for _event in observe.changes() { if let Some(data) = observe.object_data()? { println!("{}", data); break; } } # Ok(()) # } ``` # Connecting somewhere Start the `hakuban-router` (binary built by this lib), and following 2 processes. Order doesn't matter. The A and B processes will communicate through the `hakuban-router` instance. You can also make them communicate directly, by making one of them create [tokio::WebsocketListener] instead of [tokio::WebsocketConnector]. At this moment you should not have more than one WebsocketConnector running at the same time in a single process, to keep the network tree-shaped[^2], other graphs are not supported. [^2]: unless you make sure there is no overlap in object and tag descriptors visible on the other side of both connections Process A: ```rust # use hakuban::{LocalNode, ObjectObserve, tokio::WebsocketConnector}; # async fn infinite_example() -> Result<(),Box<dyn std::error::Error>> { let hakuban = LocalNode::builder().build(); let _upstream = WebsocketConnector::new("ws://127.0.0.1:3001")?.start(hakuban.clone()); let observe = hakuban.object((["some-tag"],"xxx")).observe::<String>(); for _event in observe.changes() { if let Some(data) = observe.object_data()? { println!("{}", data); break; } } # Ok(()) # } ``` Process B: ```rust # use hakuban::{LocalNode, ObjectObserve, tokio::WebsocketConnector}; # async fn infinite_example() -> Result<(),Box<dyn std::error::Error>> { let hakuban = LocalNode::builder().build(); let _upstream = WebsocketConnector::new("ws://127.0.0.1:3001")?.start(hakuban.clone()); let expose = hakuban.object((["some-tag"],"xxx")).expose(); for _event in expose.changes() { if expose.assigned() { expose.set_object_data(&"aaaaaa"); break; } } # Ok(()) # } ``` # Event handling ## Async - with futures::Stream ``` # use hakuban::{LocalNode, ObjectObserve, events::EventStream}; # async fn infinite_example() { # let hakuban = LocalNode::builder().build(); # let observe = hakuban.object((["some-tag"],"xxx")).observe::<String>(); use futures_util::StreamExt; let mut events: EventStream<_> = observe.changes().into(); while let Some(event) = events.next().await { println!("{:?}", event); } # } ``` ## Sync - with an Iterator ```rust # use hakuban::{LocalNode, ObjectObserve}; # fn infinite_example() { # let hakuban = LocalNode::builder().build(); # let observe = hakuban.object((["some-tag"],"xxx")).observe::<String>(); for event in observe.changes() { println!("{:?}", event); } # } ``` ## Sync - with a callback This method is discouraged and very limited. Callbacks get called synchronously while events are being processed in Hakuban core. So, calling any hakuban code from inside an event callback may result in a deadlock. It's still useful for FFI etc. Just don't do anything serious inside. ```rust # use hakuban::{LocalNode, ObjectObserve}; # let hakuban = LocalNode::builder().build(); # let observe = hakuban.object((["some-tag"],"xxx")).observe::<String>(); use hakuban::events::CallbackRegistry; observe.changes().register(Box::new(|event| println!("{:?}", event) )).forever(); ``` ## Buffering events, Annotating events, Merging multiple event sources into one buffer (Stream/Iterator) Look at [events] module documentation. # Cargo feature flags * `default`: `["tokio-runtime"]` * `async`: makes EventStream implement futures::Stream * `tokio-runtime`: enables compilation of tokio.rs, the only runtime&network transport implemented so far. You'll need it if you want to communicate with other processes. # FFI / so Check out documentation of the [ffi] module. # Included binaries There is one binary built by this crate - the `hakuban-router`. It's basically a WebsocketListener surrounded by "main". It accepts connections and will naturally route hakuban communication, like every other hakuban process with WebsocketListener would. */ /* # TO-DO * features * everything listed in README/roadmap * Events should have Emitter and Receiver, and Emitter should auto-unsubscribe on destroy. + Blanket implementation of Callback Registry. * some logging - with levels, tags, env vars (RUST_LOG, output?) https://rust-lang-nursery.github.io/rust-cookbook/development_tools/debugging/config_log.html * clean-up * destroy functions are horrible * de arc-ify selfs where possible * split events.rb into multiple files * merge *contract.rs into a single file * custom test harness https://www.fluvio.io/blog/2021/04/rust-custom-test-harness/ * return proper errors instead of Result<_, String> * ensure all structs hashable by pointers are Pin * remove superfluous fields from test yamls * C-NEWTYPE: use struct ObjectVersion(Vec<i64>); instead of type =, etc. * C-DEBUG: implement debug on all public types * consider * rename ObjectObserve -> ObjectObserveContract in pub api * can expose contract and observe contract be structs instead of traits? * maybe get rid of million hashbrown monomorphizations * all "cores" could be wrappers with Pin<Arc<*Internal>> inside, to ensure id() method stability * batch-lock * split "links" into multiple locks * rate limiting * periodic rebalance * drop multiple-tags-per-object support in favour of exactly-one-tag-per-object (groups, possibly tree-structured) * change msgpack to something faster: [bench](https://github.com/only-cliches/NoProto#benchmarks) [bincode](https://crates.io/crates/bincode) * bindings * js client for browser (wasm) * find out how to structure the project * implement basic object access * js client for nodejs */ mod contract; mod descriptor; mod diff; mod expose_contract; mod observe_contract; pub mod events; pub mod ffi; pub mod message; pub mod node; pub mod object; pub mod tag; #[cfg(feature = "tokio-runtime")] pub mod tokio; pub use descriptor::*; pub use node::local::LocalNode; pub use object::{builder::DefaultSerializerError, core::{ObjectRawData, ObjectType, ObjectVersion}, expose::ObjectExpose, observe::ObjectObserve}; pub use tag::{expose::TagExpose, observe::TagObserve};