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#![allow(clippy::cognitive_complexity)] #![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#![warn(clippy::or_fun_call)]
28#![deny(clippy::print_stderr)]
29#![deny(clippy::print_stdout)]
30#![warn(clippy::rc_buffer)]
31#![deny(clippy::ref_option_ref)]
32#![warn(clippy::semicolon_if_nothing_returned)]
33#![warn(clippy::trait_duplication_in_bounds)]
34#![deny(clippy::unchecked_time_subtraction)]
35#![deny(clippy::unnecessary_wraps)]
36#![warn(clippy::unseparated_literal_suffix)]
37#![deny(clippy::unwrap_used)]
38#![deny(clippy::mod_module_files)]
39#![allow(clippy::let_unit_value)] #![allow(clippy::uninlined_format_args)]
41#![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)]
48#![deny(clippy::string_slice)] #![allow(recursion_depth_exceeding_limit)] #![warn(unnameable_types)]
54
55pub mod dispatch;
56mod err;
57mod method;
58mod obj;
59
60use std::{collections::HashSet, convert::Infallible, sync::Arc};
61
62pub use dispatch::{DispatchTable, InvokeError, UpdateSink};
63pub use err::{RpcError, RpcErrorKind};
64pub use method::{
65 DeserMethod, DynMethod, Method, NoUpdates, RpcMethod, check_method_names, is_method_name,
66 iter_method_names,
67};
68pub use obj::{Object, ObjectArcExt, ObjectId};
69
70#[cfg(feature = "describe-methods")]
71pub use dispatch::description::RpcDispatchInformation;
72
73#[cfg(feature = "describe-methods")]
74#[doc(hidden)]
75pub use dispatch::description::DelegationNote;
76
77#[doc(hidden)]
78pub use obj::cast::CastTable;
79#[doc(hidden)]
80pub use {
81 derive_deftly, dispatch::RpcResult, downcast_rs, erased_serde, futures, inventory,
82 method::MethodInfo_, paste, tor_async_utils, tor_error::internal, typetag,
83};
84
85pub mod templates {
87 pub use crate::method::derive_deftly_template_DynMethod;
88 pub use crate::obj::derive_deftly_template_Object;
89}
90
91#[derive(Debug, Clone, thiserror::Error)]
93#[non_exhaustive]
94pub enum LookupError {
95 #[error("No visible object with ID {0:?}")]
98 NoObject(ObjectId),
99
100 #[error("Unexpected type on object with ID {0:?}")]
103 WrongType(ObjectId),
104
105 #[error("Weak reference {0:?} is no longer present")]
108 Expired(ObjectId),
109}
110
111impl LookupError {
112 fn rpc_error_kind(&self) -> RpcErrorKind {
114 use LookupError as E;
115 use RpcErrorKind as EK;
116
117 match self {
118 E::NoObject(_) => EK::ObjectNotFound,
119 E::WrongType(_) => EK::InvalidRequest,
120 E::Expired(_) => EK::WeakReferenceExpired,
121 }
122 }
123}
124
125impl From<LookupError> for RpcError {
126 fn from(err: LookupError) -> Self {
127 RpcError::new(err.to_string(), err.rpc_error_kind())
128 }
129}
130
131pub trait Context: Send + Sync {
133 fn lookup_object(&self, id: &ObjectId) -> Result<Arc<dyn Object>, LookupError>;
135
136 fn register_owned(&self, object: Arc<dyn Object>) -> ObjectId;
140
141 fn register_weak(&self, object: &Arc<dyn Object>) -> ObjectId;
145
146 fn release(&self, object: &ObjectId) -> Result<(), LookupError>;
150
151 fn dispatch_table(&self) -> &Arc<std::sync::RwLock<DispatchTable>>;
153}
154
155#[derive(Debug, Clone, thiserror::Error)]
167#[non_exhaustive]
168pub enum SendUpdateError {
169 #[error("Unable to send on MPSC connection")]
171 ConnectionClosed,
172}
173
174impl tor_error::HasKind for SendUpdateError {
175 fn kind(&self) -> tor_error::ErrorKind {
176 tor_error::ErrorKind::Internal
177 }
178}
179
180impl From<Infallible> for SendUpdateError {
181 fn from(_: Infallible) -> Self {
182 unreachable!()
183 }
184}
185impl From<futures::channel::mpsc::SendError> for SendUpdateError {
186 fn from(_: futures::channel::mpsc::SendError) -> Self {
187 SendUpdateError::ConnectionClosed
188 }
189}
190
191pub trait ContextExt: Context {
195 fn lookup<T: Object>(&self, id: &ObjectId) -> Result<Arc<T>, LookupError> {
199 self.lookup_object(id)?
200 .downcast_arc()
201 .map_err(|_| LookupError::WrongType(id.clone()))
202 }
203}
204
205impl<T: Context> ContextExt for T {}
206
207pub fn invoke_rpc_method(
215 ctx: Arc<dyn Context>,
216 obj_id: &ObjectId,
217 method: Box<dyn DynMethod>,
218 sink: dispatch::BoxedUpdateSink,
219) -> Result<dispatch::RpcResultFuture, InvokeError> {
220 match method.invoke_without_dispatch(Arc::clone(&ctx), obj_id) {
221 Err(InvokeError::NoDispatchBypass) => {
222 }
224 other => return other,
225 }
226
227 let obj = ctx.lookup_object(obj_id).map_err(InvokeError::NoObject)?;
228
229 let (obj, invocable) = ctx
230 .dispatch_table()
231 .read()
232 .expect("poisoned lock")
233 .resolve_rpc_invoker(obj, method.as_ref())?;
234
235 invocable.invoke(obj, method, ctx, sink)
236}
237
238pub async fn invoke_special_method<M: Method>(
247 ctx: Arc<dyn Context>,
248 obj: Arc<dyn Object>,
249 method: Box<M>,
250) -> Result<Box<M::Output>, InvokeError> {
251 let (obj, invocable) = ctx
252 .dispatch_table()
253 .read()
254 .expect("poisoned lock")
255 .resolve_special_invoker::<M>(obj)?;
256
257 invocable
258 .invoke_special(obj, method, ctx)?
259 .await
260 .downcast()
261 .map_err(|_| InvokeError::Bug(tor_error::internal!("Downcast to wrong type")))
262}
263
264#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, Default)]
268#[non_exhaustive]
269pub struct Nil {}
270pub const NIL: Nil = Nil {};
272
273#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, derive_more::From)]
276pub struct SingleIdResponse {
277 id: ObjectId,
279}
280
281#[derive(Clone, Debug, thiserror::Error)]
283#[non_exhaustive]
284#[cfg_attr(test, derive(Eq, PartialEq))]
285pub enum InvalidRpcIdentifier {
286 #[error("Identifier has no namespace separator")]
288 NoNamespace,
289
290 #[error("Identifier has unrecognized namespace")]
292 UnrecognizedNamespace,
293
294 #[error("Identifier name has unexpected format")]
296 BadIdName,
297}
298
299pub(crate) fn is_valid_rpc_identifier(
306 recognized_namespaces: Option<&HashSet<&str>>,
307 method: &str,
308) -> Result<(), InvalidRpcIdentifier> {
309 fn name_ok(n: &str) -> bool {
311 let mut chars = n.chars();
312 let Some(first) = chars.next() else {
313 return false;
314 };
315 first.is_ascii_lowercase()
316 && chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_')
317 }
318 let (scope, name) = method
319 .split_once(':')
320 .ok_or(InvalidRpcIdentifier::NoNamespace)?;
321
322 if let Some(recognized_namespaces) = recognized_namespaces {
323 if !(scope.starts_with("x-") || recognized_namespaces.contains(scope)) {
324 return Err(InvalidRpcIdentifier::UnrecognizedNamespace);
325 }
326 }
327 if !name_ok(name) {
328 return Err(InvalidRpcIdentifier::BadIdName);
329 }
330
331 Ok(())
332}
333
334#[cfg(test)]
335mod test {
336 #![allow(clippy::bool_assert_comparison)]
338 #![allow(clippy::clone_on_copy)]
339 #![allow(clippy::dbg_macro)]
340 #![allow(clippy::mixed_attributes_style)]
341 #![allow(clippy::print_stderr)]
342 #![allow(clippy::print_stdout)]
343 #![allow(clippy::single_char_pattern)]
344 #![allow(clippy::unwrap_used)]
345 #![allow(clippy::unchecked_time_subtraction)]
346 #![allow(clippy::useless_vec)]
347 #![allow(clippy::needless_pass_by_value)]
348 #![allow(clippy::string_slice)] use futures::SinkExt as _;
352 use futures_await_test::async_test;
353
354 use super::*;
355 use crate::dispatch::test::{Ctx, GetKids, Swan};
356
357 #[async_test]
358 async fn invoke() {
359 let ctx = Arc::new(Ctx::from(DispatchTable::from_inventory()));
360 let discard = || Box::pin(futures::sink::drain().sink_err_into());
361 let id = ctx.register_owned(Arc::new(Swan));
362
363 let r = invoke_rpc_method(ctx.clone(), &id, Box::new(GetKids), discard())
364 .unwrap()
365 .await
366 .unwrap();
367 assert_eq!(serde_json::to_string(&r).unwrap(), r#"{"v":"cygnets"}"#);
368
369 let r = invoke_special_method(ctx, Arc::new(Swan), Box::new(GetKids))
370 .await
371 .unwrap()
372 .unwrap();
373 assert_eq!(r.v, "cygnets");
374 }
375
376 #[test]
377 fn valid_method_names() {
378 let namespaces: HashSet<_> = ["arti", "wombat"].into_iter().collect();
379
380 for name in [
381 "arti:clone",
382 "arti:clone7",
383 "arti:clone_now",
384 "wombat:knish",
385 "x-foo:bar",
386 ] {
387 assert!(is_valid_rpc_identifier(Some(&namespaces), name).is_ok());
388 }
389 }
390
391 #[test]
392 fn invalid_method_names() {
393 let namespaces: HashSet<_> = ["arti", "wombat"].into_iter().collect();
394 use InvalidRpcIdentifier as E;
395
396 for (name, expect_err) in [
397 ("arti-foo:clone", E::UnrecognizedNamespace),
398 ("fred", E::NoNamespace),
399 ("arti:", E::BadIdName),
400 ("arti:7clone", E::BadIdName),
401 ("arti:CLONE", E::BadIdName),
402 ("arti:clone-now", E::BadIdName),
403 ] {
404 assert_eq!(
405 is_valid_rpc_identifier(Some(&namespaces), name),
406 Err(expect_err)
407 );
408 }
409 }
410}