lib.rs
1 #![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg))] 2 #![doc = include_str!("../README.md")] 3 // @@ begin lint list maintained by maint/add_warning @@ 4 #![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable) 5 #![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly) 6 #![warn(missing_docs)] 7 #![warn(noop_method_call)] 8 #![warn(unreachable_pub)] 9 #![warn(clippy::all)] 10 #![deny(clippy::await_holding_lock)] 11 #![deny(clippy::cargo_common_metadata)] 12 #![deny(clippy::cast_lossless)] 13 #![deny(clippy::checked_conversions)] 14 #![warn(clippy::cognitive_complexity)] 15 #![deny(clippy::debug_assert_with_mut_call)] 16 #![deny(clippy::exhaustive_enums)] 17 #![deny(clippy::exhaustive_structs)] 18 #![deny(clippy::expl_impl_clone_on_copy)] 19 #![deny(clippy::fallible_impl_from)] 20 #![deny(clippy::implicit_clone)] 21 #![deny(clippy::large_stack_arrays)] 22 #![warn(clippy::manual_ok_or)] 23 #![deny(clippy::missing_docs_in_private_items)] 24 #![warn(clippy::needless_borrow)] 25 #![warn(clippy::needless_pass_by_value)] 26 #![warn(clippy::option_option)] 27 #![deny(clippy::print_stderr)] 28 #![deny(clippy::print_stdout)] 29 #![warn(clippy::rc_buffer)] 30 #![deny(clippy::ref_option_ref)] 31 #![warn(clippy::semicolon_if_nothing_returned)] 32 #![warn(clippy::trait_duplication_in_bounds)] 33 #![deny(clippy::unchecked_duration_subtraction)] 34 #![deny(clippy::unnecessary_wraps)] 35 #![warn(clippy::unseparated_literal_suffix)] 36 #![deny(clippy::unwrap_used)] 37 #![deny(clippy::mod_module_files)] 38 #![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness 39 #![allow(clippy::uninlined_format_args)] 40 #![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945 41 #![allow(clippy::result_large_err)] // temporary workaround for arti#587 42 #![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best 43 #![allow(clippy::needless_lifetimes)] // See arti#1765 44 //! <!-- @@ end lint list maintained by maint/add_warning @@ --> 45 46 pub mod dispatch; 47 mod err; 48 mod method; 49 mod obj; 50 51 use std::{convert::Infallible, sync::Arc}; 52 53 pub use dispatch::{DispatchTable, InvokeError, UpdateSink}; 54 pub use err::{RpcError, RpcErrorKind}; 55 pub use method::{ 56 check_method_names, is_method_name, iter_method_names, DeserMethod, DynMethod, 57 InvalidMethodName, Method, NoUpdates, RpcMethod, 58 }; 59 pub use obj::{Object, ObjectArcExt, ObjectId}; 60 61 #[cfg(feature = "describe-methods")] 62 #[cfg_attr(docsrs, doc(cfg(feature = "describe-methods")))] 63 pub use dispatch::description::RpcDispatchInformation; 64 65 #[cfg(feature = "describe-methods")] 66 #[cfg_attr(docsrs, doc(cfg(feature = "describe-methods")))] 67 #[doc(hidden)] 68 pub use dispatch::description::DelegationNote; 69 70 #[doc(hidden)] 71 pub use obj::cast::CastTable; 72 #[doc(hidden)] 73 pub use { 74 derive_deftly, dispatch::RpcResult, downcast_rs, erased_serde, futures, inventory, 75 method::MethodInfo_, once_cell, paste, tor_async_utils, tor_error::internal, typetag, 76 }; 77 78 /// Templates for use with [`derive_deftly`] 79 pub mod templates { 80 pub use crate::method::derive_deftly_template_DynMethod; 81 pub use crate::obj::derive_deftly_template_Object; 82 } 83 84 /// An error returned from [`ContextExt::lookup`]. 85 #[derive(Debug, Clone, thiserror::Error)] 86 #[non_exhaustive] 87 pub enum LookupError { 88 /// The specified object does not (currently) exist, 89 /// or the user does not have permission to access it. 90 #[error("No visible object with ID {0:?}")] 91 NoObject(ObjectId), 92 93 /// The specified object exists, but does not have the 94 /// expected type. 95 #[error("Unexpected type on object with ID {0:?}")] 96 WrongType(ObjectId), 97 } 98 99 impl From<LookupError> for RpcError { 100 fn from(err: LookupError) -> Self { 101 use LookupError as E; 102 use RpcErrorKind as EK; 103 let kind = match &err { 104 E::NoObject(_) => EK::ObjectNotFound, 105 E::WrongType(_) => EK::InvalidRequest, 106 }; 107 RpcError::new(err.to_string(), kind) 108 } 109 } 110 111 /// A trait describing the context in which an RPC method is executed. 112 pub trait Context: Send + Sync { 113 /// Look up an object by identity within this context. 114 fn lookup_object(&self, id: &ObjectId) -> Result<Arc<dyn Object>, LookupError>; 115 116 /// Create an owning reference to `object` within this context. 117 /// 118 /// Return an ObjectId for this object. 119 /// 120 /// TODO RPC: We may need to change the above semantics and the name of this 121 /// function depending on how we decide to name and specify things. 122 fn register_owned(&self, object: Arc<dyn Object>) -> ObjectId; 123 124 /// Make sure that 125 /// this context contains a non-owning reference to `object`, 126 /// creating one if necessary. 127 /// 128 /// Return an ObjectId for this object. 129 /// 130 /// Note that this takes an Arc, since that's required in order to find a 131 /// working type Id for the target object. 132 /// 133 /// TODO RPC: We may need to change the above semantics and the name of this 134 /// function depending on how we decide to name and specify things. 135 fn register_weak(&self, object: Arc<dyn Object>) -> ObjectId; 136 137 /// Drop an owning reference to the object called `object` within this context. 138 /// 139 /// This will return an error if `object` is not an owning reference. 140 /// 141 /// TODO RPC should this really return a LookupError? 142 fn release_owned(&self, object: &ObjectId) -> Result<(), LookupError>; 143 144 /// Return a dispatch table that can be used to invoke other RPC methods. 145 fn dispatch_table(&self) -> &Arc<std::sync::RwLock<DispatchTable>>; 146 } 147 148 /// An error caused while trying to send an update to a method. 149 /// 150 /// These errors should be impossible in our current implementation, since they 151 /// can only happen if the `mpsc::Receiver` is closed—which can only happen 152 /// when the session loop drops it, which only happens when the session loop has 153 /// stopped polling its `FuturesUnordered` full of RPC request futures. Thus, any 154 /// `send` that would encounter this error should be in a future that is never 155 /// polled under circumstances when the error could happen. 156 /// 157 /// Still, programming errors are real, so we are handling this rather than 158 /// declaring it a panic or something. 159 #[derive(Debug, Clone, thiserror::Error)] 160 #[non_exhaustive] 161 pub enum SendUpdateError { 162 /// The request was cancelled, or the connection was closed. 163 #[error("Unable to send on MPSC connection")] 164 ConnectionClosed, 165 } 166 167 impl tor_error::HasKind for SendUpdateError { 168 fn kind(&self) -> tor_error::ErrorKind { 169 tor_error::ErrorKind::Internal 170 } 171 } 172 173 impl From<Infallible> for SendUpdateError { 174 fn from(_: Infallible) -> Self { 175 unreachable!() 176 } 177 } 178 impl From<futures::channel::mpsc::SendError> for SendUpdateError { 179 fn from(_: futures::channel::mpsc::SendError) -> Self { 180 SendUpdateError::ConnectionClosed 181 } 182 } 183 184 /// Extension trait for [`Context`]. 185 /// 186 /// This is a separate trait so that `Context` can be object-safe. 187 pub trait ContextExt: Context { 188 /// Look up an object of a given type, and downcast it. 189 /// 190 /// Return an error if the object can't be found, or has the wrong type. 191 fn lookup<T: Object>(&self, id: &ObjectId) -> Result<Arc<T>, LookupError> { 192 self.lookup_object(id)? 193 .downcast_arc() 194 .map_err(|_| LookupError::WrongType(id.clone())) 195 } 196 } 197 198 impl<T: Context> ContextExt for T {} 199 200 /// Try to find an appropriate function for calling a given RPC method on a 201 /// given RPC-visible object. 202 /// 203 /// On success, return a Future. 204 /// 205 /// Differs from using `DispatchTable::invoke()` in that it drops its lock 206 /// on the dispatch table before invoking the method. 207 pub fn invoke_rpc_method( 208 ctx: Arc<dyn Context>, 209 obj_id: &ObjectId, 210 obj: Arc<dyn Object>, 211 method: Box<dyn DynMethod>, 212 sink: dispatch::BoxedUpdateSink, 213 ) -> Result<dispatch::RpcResultFuture, InvokeError> { 214 match method.invoke_without_dispatch(Arc::clone(&ctx), obj_id) { 215 Err(InvokeError::NoDispatchBypass) => { 216 // fall through 217 } 218 other => return other, 219 } 220 221 let (obj, invocable) = ctx 222 .dispatch_table() 223 .read() 224 .expect("poisoned lock") 225 .resolve_rpc_invoker(obj, method.as_ref())?; 226 227 invocable.invoke(obj, method, ctx, sink) 228 } 229 230 /// Invoke the given `method` on `obj` within `ctx`, and return its 231 /// actual result type. 232 /// 233 /// Unlike `invoke_rpc_method`, this method does not return a type-erased result, 234 /// and does not require that the result can be serialized as an RPC object. 235 /// 236 /// Differs from using `DispatchTable::invoke_special()` in that it drops its lock 237 /// on the dispatch table before invoking the method. 238 pub async fn invoke_special_method<M: Method>( 239 ctx: Arc<dyn Context>, 240 obj: Arc<dyn Object>, 241 method: Box<M>, 242 ) -> Result<Box<M::Output>, InvokeError> { 243 let (obj, invocable) = ctx 244 .dispatch_table() 245 .read() 246 .expect("poisoned lock") 247 .resolve_special_invoker::<M>(obj)?; 248 249 invocable 250 .invoke_special(obj, method, ctx)? 251 .await 252 .downcast() 253 .map_err(|_| InvokeError::Bug(tor_error::internal!("Downcast to wrong type"))) 254 } 255 256 /// A serializable empty object. 257 /// 258 /// Used when we need to declare that a method returns nothing. 259 #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, Default)] 260 #[non_exhaustive] 261 pub struct Nil {} 262 /// An instance of rpc::Nil. 263 pub const NIL: Nil = Nil {}; 264 265 /// Common return type for RPC methods that return a single object ID 266 /// and nothing else. 267 #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, derive_more::From)] 268 pub struct SingleIdResponse { 269 /// The ID of the object that we're returning. 270 id: ObjectId, 271 } 272 273 #[cfg(test)] 274 mod test { 275 // @@ begin test lint list maintained by maint/add_warning @@ 276 #![allow(clippy::bool_assert_comparison)] 277 #![allow(clippy::clone_on_copy)] 278 #![allow(clippy::dbg_macro)] 279 #![allow(clippy::mixed_attributes_style)] 280 #![allow(clippy::print_stderr)] 281 #![allow(clippy::print_stdout)] 282 #![allow(clippy::single_char_pattern)] 283 #![allow(clippy::unwrap_used)] 284 #![allow(clippy::unchecked_duration_subtraction)] 285 #![allow(clippy::useless_vec)] 286 #![allow(clippy::needless_pass_by_value)] 287 //! <!-- @@ end test lint list maintained by maint/add_warning @@ --> 288 289 use futures::SinkExt as _; 290 use futures_await_test::async_test; 291 292 use super::*; 293 use crate::dispatch::test::{Ctx, GetKids, Swan}; 294 295 #[async_test] 296 async fn invoke() { 297 let ctx = Arc::new(Ctx::from(DispatchTable::from_inventory())); 298 let discard = || Box::pin(futures::sink::drain().sink_err_into()); 299 let r = invoke_rpc_method( 300 ctx.clone(), 301 &ObjectId::from("Odile"), 302 Arc::new(Swan), 303 Box::new(GetKids), 304 discard(), 305 ) 306 .unwrap() 307 .await 308 .unwrap(); 309 assert_eq!(serde_json::to_string(&r).unwrap(), r#"{"v":"cygnets"}"#); 310 311 let r = invoke_special_method(ctx, Arc::new(Swan), Box::new(GetKids)) 312 .await 313 .unwrap() 314 .unwrap(); 315 assert_eq!(r.v, "cygnets"); 316 } 317 }