1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3#![allow(renamed_and_removed_lints)] #![allow(unknown_lints)] #![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_time_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)] #![allow(clippy::uninlined_format_args)]
40#![allow(clippy::significant_drop_in_scrutinee)] #![allow(clippy::result_large_err)] #![allow(clippy::needless_raw_string_hashes)] #![allow(clippy::needless_lifetimes)] #![allow(mismatched_lifetime_syntaxes)] #![allow(clippy::collapsible_if)] #![deny(clippy::unused_async)]
47#![deny(clippy::string_slice)] pub mod dispatch;
51mod err;
52mod method;
53mod obj;
54
55use std::{collections::HashSet, convert::Infallible, sync::Arc};
56
57pub use dispatch::{DispatchTable, InvokeError, UpdateSink};
58pub use err::{RpcError, RpcErrorKind};
59pub use method::{
60 DeserMethod, DynMethod, Method, NoUpdates, RpcMethod, check_method_names, is_method_name,
61 iter_method_names,
62};
63pub use obj::{Object, ObjectArcExt, ObjectId};
64
65#[cfg(feature = "describe-methods")]
66pub use dispatch::description::RpcDispatchInformation;
67
68#[cfg(feature = "describe-methods")]
69#[doc(hidden)]
70pub use dispatch::description::DelegationNote;
71
72#[doc(hidden)]
73pub use obj::cast::CastTable;
74#[doc(hidden)]
75pub use {
76 derive_deftly, dispatch::RpcResult, downcast_rs, erased_serde, futures, inventory,
77 method::MethodInfo_, paste, tor_async_utils, tor_error::internal, typetag,
78};
79
80pub mod templates {
82 pub use crate::method::derive_deftly_template_DynMethod;
83 pub use crate::obj::derive_deftly_template_Object;
84}
85
86#[derive(Debug, Clone, thiserror::Error)]
88#[non_exhaustive]
89pub enum LookupError {
90 #[error("No visible object with ID {0:?}")]
93 NoObject(ObjectId),
94
95 #[error("Unexpected type on object with ID {0:?}")]
98 WrongType(ObjectId),
99
100 #[error("Weak reference {0:?} is no longer present")]
103 Expired(ObjectId),
104}
105
106impl LookupError {
107 fn rpc_error_kind(&self) -> RpcErrorKind {
109 use LookupError as E;
110 use RpcErrorKind as EK;
111
112 match self {
113 E::NoObject(_) => EK::ObjectNotFound,
114 E::WrongType(_) => EK::InvalidRequest,
115 E::Expired(_) => EK::WeakReferenceExpired,
116 }
117 }
118}
119
120impl From<LookupError> for RpcError {
121 fn from(err: LookupError) -> Self {
122 RpcError::new(err.to_string(), err.rpc_error_kind())
123 }
124}
125
126pub trait Context: Send + Sync {
128 fn lookup_object(&self, id: &ObjectId) -> Result<Arc<dyn Object>, LookupError>;
130
131 fn register_owned(&self, object: Arc<dyn Object>) -> ObjectId;
135
136 fn register_weak(&self, object: &Arc<dyn Object>) -> ObjectId;
140
141 fn release(&self, object: &ObjectId) -> Result<(), LookupError>;
145
146 fn dispatch_table(&self) -> &Arc<std::sync::RwLock<DispatchTable>>;
148}
149
150#[derive(Debug, Clone, thiserror::Error)]
162#[non_exhaustive]
163pub enum SendUpdateError {
164 #[error("Unable to send on MPSC connection")]
166 ConnectionClosed,
167}
168
169impl tor_error::HasKind for SendUpdateError {
170 fn kind(&self) -> tor_error::ErrorKind {
171 tor_error::ErrorKind::Internal
172 }
173}
174
175impl From<Infallible> for SendUpdateError {
176 fn from(_: Infallible) -> Self {
177 unreachable!()
178 }
179}
180impl From<futures::channel::mpsc::SendError> for SendUpdateError {
181 fn from(_: futures::channel::mpsc::SendError) -> Self {
182 SendUpdateError::ConnectionClosed
183 }
184}
185
186pub trait ContextExt: Context {
190 fn lookup<T: Object>(&self, id: &ObjectId) -> Result<Arc<T>, LookupError> {
194 self.lookup_object(id)?
195 .downcast_arc()
196 .map_err(|_| LookupError::WrongType(id.clone()))
197 }
198}
199
200impl<T: Context> ContextExt for T {}
201
202pub fn invoke_rpc_method(
210 ctx: Arc<dyn Context>,
211 obj_id: &ObjectId,
212 method: Box<dyn DynMethod>,
213 sink: dispatch::BoxedUpdateSink,
214) -> Result<dispatch::RpcResultFuture, InvokeError> {
215 match method.invoke_without_dispatch(Arc::clone(&ctx), obj_id) {
216 Err(InvokeError::NoDispatchBypass) => {
217 }
219 other => return other,
220 }
221
222 let obj = ctx.lookup_object(obj_id).map_err(InvokeError::NoObject)?;
223
224 let (obj, invocable) = ctx
225 .dispatch_table()
226 .read()
227 .expect("poisoned lock")
228 .resolve_rpc_invoker(obj, method.as_ref())?;
229
230 invocable.invoke(obj, method, ctx, sink)
231}
232
233pub async fn invoke_special_method<M: Method>(
242 ctx: Arc<dyn Context>,
243 obj: Arc<dyn Object>,
244 method: Box<M>,
245) -> Result<Box<M::Output>, InvokeError> {
246 let (obj, invocable) = ctx
247 .dispatch_table()
248 .read()
249 .expect("poisoned lock")
250 .resolve_special_invoker::<M>(obj)?;
251
252 invocable
253 .invoke_special(obj, method, ctx)?
254 .await
255 .downcast()
256 .map_err(|_| InvokeError::Bug(tor_error::internal!("Downcast to wrong type")))
257}
258
259#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, Default)]
263#[non_exhaustive]
264pub struct Nil {}
265pub const NIL: Nil = Nil {};
267
268#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, derive_more::From)]
271pub struct SingleIdResponse {
272 id: ObjectId,
274}
275
276#[derive(Clone, Debug, thiserror::Error)]
278#[non_exhaustive]
279#[cfg_attr(test, derive(Eq, PartialEq))]
280pub enum InvalidRpcIdentifier {
281 #[error("Identifier has no namespace separator")]
283 NoNamespace,
284
285 #[error("Identifier has unrecognized namespace")]
287 UnrecognizedNamespace,
288
289 #[error("Identifier name has unexpected format")]
291 BadIdName,
292}
293
294pub(crate) fn is_valid_rpc_identifier(
301 recognized_namespaces: Option<&HashSet<&str>>,
302 method: &str,
303) -> Result<(), InvalidRpcIdentifier> {
304 fn name_ok(n: &str) -> bool {
306 let mut chars = n.chars();
307 let Some(first) = chars.next() else {
308 return false;
309 };
310 first.is_ascii_lowercase()
311 && chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_')
312 }
313 let (scope, name) = method
314 .split_once(':')
315 .ok_or(InvalidRpcIdentifier::NoNamespace)?;
316
317 if let Some(recognized_namespaces) = recognized_namespaces {
318 if !(scope.starts_with("x-") || recognized_namespaces.contains(scope)) {
319 return Err(InvalidRpcIdentifier::UnrecognizedNamespace);
320 }
321 }
322 if !name_ok(name) {
323 return Err(InvalidRpcIdentifier::BadIdName);
324 }
325
326 Ok(())
327}
328
329#[cfg(test)]
330mod test {
331 #![allow(clippy::bool_assert_comparison)]
333 #![allow(clippy::clone_on_copy)]
334 #![allow(clippy::dbg_macro)]
335 #![allow(clippy::mixed_attributes_style)]
336 #![allow(clippy::print_stderr)]
337 #![allow(clippy::print_stdout)]
338 #![allow(clippy::single_char_pattern)]
339 #![allow(clippy::unwrap_used)]
340 #![allow(clippy::unchecked_time_subtraction)]
341 #![allow(clippy::useless_vec)]
342 #![allow(clippy::needless_pass_by_value)]
343 #![allow(clippy::string_slice)] use futures::SinkExt as _;
347 use futures_await_test::async_test;
348
349 use super::*;
350 use crate::dispatch::test::{Ctx, GetKids, Swan};
351
352 #[async_test]
353 async fn invoke() {
354 let ctx = Arc::new(Ctx::from(DispatchTable::from_inventory()));
355 let discard = || Box::pin(futures::sink::drain().sink_err_into());
356 let id = ctx.register_owned(Arc::new(Swan));
357
358 let r = invoke_rpc_method(ctx.clone(), &id, Box::new(GetKids), discard())
359 .unwrap()
360 .await
361 .unwrap();
362 assert_eq!(serde_json::to_string(&r).unwrap(), r#"{"v":"cygnets"}"#);
363
364 let r = invoke_special_method(ctx, Arc::new(Swan), Box::new(GetKids))
365 .await
366 .unwrap()
367 .unwrap();
368 assert_eq!(r.v, "cygnets");
369 }
370
371 #[test]
372 fn valid_method_names() {
373 let namespaces: HashSet<_> = ["arti", "wombat"].into_iter().collect();
374
375 for name in [
376 "arti:clone",
377 "arti:clone7",
378 "arti:clone_now",
379 "wombat:knish",
380 "x-foo:bar",
381 ] {
382 assert!(is_valid_rpc_identifier(Some(&namespaces), name).is_ok());
383 }
384 }
385
386 #[test]
387 fn invalid_method_names() {
388 let namespaces: HashSet<_> = ["arti", "wombat"].into_iter().collect();
389 use InvalidRpcIdentifier as E;
390
391 for (name, expect_err) in [
392 ("arti-foo:clone", E::UnrecognizedNamespace),
393 ("fred", E::NoNamespace),
394 ("arti:", E::BadIdName),
395 ("arti:7clone", E::BadIdName),
396 ("arti:CLONE", E::BadIdName),
397 ("arti:clone-now", E::BadIdName),
398 ] {
399 assert_eq!(
400 is_valid_rpc_identifier(Some(&namespaces), name),
401 Err(expect_err)
402 );
403 }
404 }
405}