|
| 1 | +//! This example demonstrates using irpc-iroh with a cloneable state struct |
| 2 | +//! on the server side instead of with an actor loop. |
| 3 | +
|
| 4 | +use anyhow::Result; |
| 5 | +use iroh::{protocol::Router, Endpoint}; |
| 6 | + |
| 7 | +use self::storage::{StorageClient, StorageServer}; |
| 8 | + |
| 9 | +#[tokio::main] |
| 10 | +async fn main() -> Result<()> { |
| 11 | + tracing_subscriber::fmt::init(); |
| 12 | + |
| 13 | + // Start the server. |
| 14 | + let (server_router, server_addr) = { |
| 15 | + let endpoint = Endpoint::bind().await?; |
| 16 | + let storage = StorageServer::default(); |
| 17 | + let router = Router::builder(endpoint) |
| 18 | + .accept(storage::ALPN, storage) |
| 19 | + .spawn(); |
| 20 | + let addr = router.endpoint().addr(); |
| 21 | + (router, addr) |
| 22 | + }; |
| 23 | + |
| 24 | + // Connect by passing an endpoint, which allows automatic reconnection. |
| 25 | + let client_endpoint = Endpoint::bind().await?; |
| 26 | + let api = StorageClient::connect(client_endpoint, server_addr.clone()); |
| 27 | + api.set("hello", "world").await?; |
| 28 | + api.set("goodbye", "see you soon").await?; |
| 29 | + let value = api.get("hello").await?; |
| 30 | + println!("hello = {value:?}"); |
| 31 | + let mut list = api.list().await?; |
| 32 | + while let Some(value) = list.recv().await? { |
| 33 | + println!("list: {value:?}"); |
| 34 | + } |
| 35 | + |
| 36 | + // Or create a client from a connection directly. |
| 37 | + let client2 = Endpoint::bind().await?; |
| 38 | + let conn = client2.connect(server_addr, storage::ALPN).await?; |
| 39 | + let api = StorageClient::from_connection(conn); |
| 40 | + let value = api.get("goodbye").await?; |
| 41 | + println!("goodbye = {value:?}"); |
| 42 | + |
| 43 | + drop(server_router); |
| 44 | + Ok(()) |
| 45 | +} |
| 46 | + |
| 47 | +mod storage { |
| 48 | + //! Implementation of our storage service. |
| 49 | +
|
| 50 | + use std::{ |
| 51 | + collections::BTreeMap, |
| 52 | + sync::{Arc, Mutex, MutexGuard}, |
| 53 | + }; |
| 54 | + |
| 55 | + use anyhow::Result; |
| 56 | + use iroh::{ |
| 57 | + endpoint::Connection, |
| 58 | + protocol::{AcceptError, ProtocolHandler}, |
| 59 | + Endpoint, |
| 60 | + }; |
| 61 | + use irpc::{ |
| 62 | + channel::{mpsc, oneshot}, |
| 63 | + rpc_requests, Client, WithChannels, |
| 64 | + }; |
| 65 | + // Import the macro |
| 66 | + use irpc_iroh::{read_request, IrohLazyRemoteConnection, IrohRemoteConnection}; |
| 67 | + use serde::{Deserialize, Serialize}; |
| 68 | + use tracing::info; |
| 69 | + |
| 70 | + pub const ALPN: &[u8] = b"irpc/example-storage/0"; |
| 71 | + |
| 72 | + #[derive(Debug, Serialize, Deserialize)] |
| 73 | + struct Get { |
| 74 | + key: String, |
| 75 | + } |
| 76 | + |
| 77 | + #[derive(Debug, Serialize, Deserialize)] |
| 78 | + struct List; |
| 79 | + |
| 80 | + #[derive(Debug, Serialize, Deserialize)] |
| 81 | + struct Set { |
| 82 | + key: String, |
| 83 | + value: String, |
| 84 | + } |
| 85 | + |
| 86 | + #[derive(Debug, Serialize, Deserialize)] |
| 87 | + struct SetMany; |
| 88 | + |
| 89 | + // Use the macro to generate both the StorageProtocol and StorageMessage enums |
| 90 | + // plus implement Channels for each type |
| 91 | + #[rpc_requests(message = StorageMessage)] |
| 92 | + #[derive(Serialize, Deserialize, Debug)] |
| 93 | + enum StorageProtocol { |
| 94 | + #[rpc(tx=oneshot::Sender<Option<String>>)] |
| 95 | + Get(Get), |
| 96 | + #[rpc(tx=oneshot::Sender<()>)] |
| 97 | + Set(Set), |
| 98 | + #[rpc(tx=oneshot::Sender<u64>, rx=mpsc::Receiver<(String, String)>)] |
| 99 | + SetMany(SetMany), |
| 100 | + #[rpc(tx=mpsc::Sender<String>)] |
| 101 | + List(List), |
| 102 | + } |
| 103 | + |
| 104 | + #[derive(Debug, Clone, Default)] |
| 105 | + pub struct StorageServer { |
| 106 | + state: Arc<Mutex<BTreeMap<String, String>>>, |
| 107 | + } |
| 108 | + |
| 109 | + impl ProtocolHandler for StorageServer { |
| 110 | + async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { |
| 111 | + while let Some(msg) = read_request::<StorageProtocol>(&conn).await? { |
| 112 | + self.handle_message(msg).await; |
| 113 | + } |
| 114 | + conn.closed().await; |
| 115 | + Ok(()) |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + impl StorageServer { |
| 120 | + async fn handle_message(&self, msg: StorageMessage) { |
| 121 | + info!("handle message {:?}", msg); |
| 122 | + match msg { |
| 123 | + StorageMessage::Get(msg) => { |
| 124 | + let WithChannels { tx, inner, .. } = msg; |
| 125 | + let value = self.state().get(&inner.key).cloned(); |
| 126 | + tx.send(value).await.ok(); |
| 127 | + } |
| 128 | + StorageMessage::Set(msg) => { |
| 129 | + let WithChannels { tx, inner, .. } = msg; |
| 130 | + self.state().insert(inner.key, inner.value); |
| 131 | + tx.send(()).await.ok(); |
| 132 | + } |
| 133 | + StorageMessage::SetMany(msg) => { |
| 134 | + let WithChannels { tx, mut rx, .. } = msg; |
| 135 | + let mut i = 0; |
| 136 | + while let Ok(Some((key, value))) = rx.recv().await { |
| 137 | + self.state().insert(key, value); |
| 138 | + i += 1; |
| 139 | + } |
| 140 | + tx.send(i).await.ok(); |
| 141 | + } |
| 142 | + StorageMessage::List(msg) => { |
| 143 | + let WithChannels { tx, .. } = msg; |
| 144 | + let values = { |
| 145 | + let state = self.state(); |
| 146 | + // We clone the values so that we don't keep the lock open for the lifetime of the request. |
| 147 | + // If we wouldn't want to clone here because there can be many entries, |
| 148 | + // we have to redesign the storage to support a notion of snapshots, or use an async lock |
| 149 | + // but that would mean that no other requests can be processed while the stream here is sent out. |
| 150 | + let values: Vec<_> = state |
| 151 | + .iter() |
| 152 | + .map(|(key, value)| format!("{key}={value}")) |
| 153 | + .collect(); |
| 154 | + values |
| 155 | + }; |
| 156 | + for value in values { |
| 157 | + if tx.send(value).await.is_err() { |
| 158 | + break; |
| 159 | + } |
| 160 | + } |
| 161 | + } |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + fn state(&self) -> MutexGuard<'_, BTreeMap<String, String>> { |
| 166 | + self.state.lock().expect("poisoned") |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + pub struct StorageClient { |
| 171 | + inner: Client<StorageProtocol>, |
| 172 | + } |
| 173 | + |
| 174 | + impl StorageClient { |
| 175 | + /// Connect via an [`Endpoint`]. |
| 176 | + /// |
| 177 | + /// This will create a client that automatically reconnects if the connection closes. |
| 178 | + pub fn connect(endpoint: Endpoint, addr: impl Into<iroh::EndpointAddr>) -> StorageClient { |
| 179 | + let conn = IrohLazyRemoteConnection::new(endpoint, addr.into(), ALPN.to_vec()); |
| 180 | + StorageClient { |
| 181 | + inner: Client::boxed(conn), |
| 182 | + } |
| 183 | + } |
| 184 | + |
| 185 | + /// Create a client from a [`Connection`]. |
| 186 | + /// |
| 187 | + /// This creates a client from a single [`Connection`]. If the connection closes, the client will |
| 188 | + /// not reconnect and all calls will return errors. |
| 189 | + pub fn from_connection(conn: Connection) -> StorageClient { |
| 190 | + StorageClient { |
| 191 | + inner: Client::boxed(IrohRemoteConnection::new(conn)), |
| 192 | + } |
| 193 | + } |
| 194 | + |
| 195 | + pub async fn get(&self, key: impl ToString) -> Result<Option<String>, irpc::Error> { |
| 196 | + self.inner |
| 197 | + .rpc(Get { |
| 198 | + key: key.to_string(), |
| 199 | + }) |
| 200 | + .await |
| 201 | + } |
| 202 | + |
| 203 | + pub async fn list(&self) -> Result<mpsc::Receiver<String>, irpc::Error> { |
| 204 | + self.inner.server_streaming(List, 10).await |
| 205 | + } |
| 206 | + |
| 207 | + pub async fn set( |
| 208 | + &self, |
| 209 | + key: impl ToString, |
| 210 | + value: impl ToString, |
| 211 | + ) -> Result<(), irpc::Error> { |
| 212 | + let msg = Set { |
| 213 | + key: key.to_string(), |
| 214 | + value: value.to_string(), |
| 215 | + }; |
| 216 | + self.inner.rpc(msg).await |
| 217 | + } |
| 218 | + } |
| 219 | +} |
0 commit comments