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