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)] pub mod dispatch;
48mod err;
49mod method;
50mod obj;
51
52use std::{collections::HashSet, convert::Infallible, sync::Arc};
53
54pub use dispatch::{DispatchTable, InvokeError, UpdateSink};
55pub use err::{RpcError, RpcErrorKind};
56pub use method::{
57 DeserMethod, DynMethod, Method, NoUpdates, RpcMethod, check_method_names, is_method_name,
58 iter_method_names,
59};
60pub use obj::{Object, ObjectArcExt, ObjectId};
61
62#[cfg(feature = "describe-methods")]
63pub use dispatch::description::RpcDispatchInformation;
64
65#[cfg(feature = "describe-methods")]
66#[doc(hidden)]
67pub use dispatch::description::DelegationNote;
68
69#[doc(hidden)]
70pub use obj::cast::CastTable;
71#[doc(hidden)]
72pub use {
73 derive_deftly, dispatch::RpcResult, downcast_rs, erased_serde, futures, inventory,
74 method::MethodInfo_, paste, tor_async_utils, tor_error::internal, typetag,
75};
76
77pub mod templates {
79 pub use crate::method::derive_deftly_template_DynMethod;
80 pub use crate::obj::derive_deftly_template_Object;
81}
82
83#[derive(Debug, Clone, thiserror::Error)]
85#[non_exhaustive]
86pub enum LookupError {
87 #[error("No visible object with ID {0:?}")]
90 NoObject(ObjectId),
91
92 #[error("Unexpected type on object with ID {0:?}")]
95 WrongType(ObjectId),
96}
97
98impl From<LookupError> for RpcError {
99 fn from(err: LookupError) -> Self {
100 use LookupError as E;
101 use RpcErrorKind as EK;
102 let kind = match &err {
103 E::NoObject(_) => EK::ObjectNotFound,
104 E::WrongType(_) => EK::InvalidRequest,
105 };
106 RpcError::new(err.to_string(), kind)
107 }
108}
109
110pub trait Context: Send + Sync {
112 fn lookup_object(&self, id: &ObjectId) -> Result<Arc<dyn Object>, LookupError>;
114
115 fn register_owned(&self, object: Arc<dyn Object>) -> ObjectId;
119
120 fn release_owned(&self, object: &ObjectId) -> Result<(), LookupError>;
127
128 fn dispatch_table(&self) -> &Arc<std::sync::RwLock<DispatchTable>>;
130}
131
132#[derive(Debug, Clone, thiserror::Error)]
144#[non_exhaustive]
145pub enum SendUpdateError {
146 #[error("Unable to send on MPSC connection")]
148 ConnectionClosed,
149}
150
151impl tor_error::HasKind for SendUpdateError {
152 fn kind(&self) -> tor_error::ErrorKind {
153 tor_error::ErrorKind::Internal
154 }
155}
156
157impl From<Infallible> for SendUpdateError {
158 fn from(_: Infallible) -> Self {
159 unreachable!()
160 }
161}
162impl From<futures::channel::mpsc::SendError> for SendUpdateError {
163 fn from(_: futures::channel::mpsc::SendError) -> Self {
164 SendUpdateError::ConnectionClosed
165 }
166}
167
168pub trait ContextExt: Context {
172 fn lookup<T: Object>(&self, id: &ObjectId) -> Result<Arc<T>, LookupError> {
176 self.lookup_object(id)?
177 .downcast_arc()
178 .map_err(|_| LookupError::WrongType(id.clone()))
179 }
180}
181
182impl<T: Context> ContextExt for T {}
183
184pub fn invoke_rpc_method(
192 ctx: Arc<dyn Context>,
193 obj_id: &ObjectId,
194 obj: Arc<dyn Object>,
195 method: Box<dyn DynMethod>,
196 sink: dispatch::BoxedUpdateSink,
197) -> Result<dispatch::RpcResultFuture, InvokeError> {
198 match method.invoke_without_dispatch(Arc::clone(&ctx), obj_id) {
199 Err(InvokeError::NoDispatchBypass) => {
200 }
202 other => return other,
203 }
204
205 let (obj, invocable) = ctx
206 .dispatch_table()
207 .read()
208 .expect("poisoned lock")
209 .resolve_rpc_invoker(obj, method.as_ref())?;
210
211 invocable.invoke(obj, method, ctx, sink)
212}
213
214pub async fn invoke_special_method<M: Method>(
223 ctx: Arc<dyn Context>,
224 obj: Arc<dyn Object>,
225 method: Box<M>,
226) -> Result<Box<M::Output>, InvokeError> {
227 let (obj, invocable) = ctx
228 .dispatch_table()
229 .read()
230 .expect("poisoned lock")
231 .resolve_special_invoker::<M>(obj)?;
232
233 invocable
234 .invoke_special(obj, method, ctx)?
235 .await
236 .downcast()
237 .map_err(|_| InvokeError::Bug(tor_error::internal!("Downcast to wrong type")))
238}
239
240#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, Default)]
244#[non_exhaustive]
245pub struct Nil {}
246pub const NIL: Nil = Nil {};
248
249#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, derive_more::From)]
252pub struct SingleIdResponse {
253 id: ObjectId,
255}
256
257#[derive(Clone, Debug, thiserror::Error)]
259#[non_exhaustive]
260#[cfg_attr(test, derive(Eq, PartialEq))]
261pub enum InvalidRpcIdentifier {
262 #[error("Identifier has no namespace separator")]
264 NoNamespace,
265
266 #[error("Identifier has unrecognized namespace")]
268 UnrecognizedNamespace,
269
270 #[error("Identifier name has unexpected format")]
272 BadIdName,
273}
274
275pub(crate) fn is_valid_rpc_identifier(
282 recognized_namespaces: Option<&HashSet<&str>>,
283 method: &str,
284) -> Result<(), InvalidRpcIdentifier> {
285 fn name_ok(n: &str) -> bool {
287 let mut chars = n.chars();
288 let Some(first) = chars.next() else {
289 return false;
290 };
291 first.is_ascii_lowercase()
292 && chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_')
293 }
294 let (scope, name) = method
295 .split_once(':')
296 .ok_or(InvalidRpcIdentifier::NoNamespace)?;
297
298 if let Some(recognized_namespaces) = recognized_namespaces {
299 if !(scope.starts_with("x-") || recognized_namespaces.contains(scope)) {
300 return Err(InvalidRpcIdentifier::UnrecognizedNamespace);
301 }
302 }
303 if !name_ok(name) {
304 return Err(InvalidRpcIdentifier::BadIdName);
305 }
306
307 Ok(())
308}
309
310#[cfg(test)]
311mod test {
312 #![allow(clippy::bool_assert_comparison)]
314 #![allow(clippy::clone_on_copy)]
315 #![allow(clippy::dbg_macro)]
316 #![allow(clippy::mixed_attributes_style)]
317 #![allow(clippy::print_stderr)]
318 #![allow(clippy::print_stdout)]
319 #![allow(clippy::single_char_pattern)]
320 #![allow(clippy::unwrap_used)]
321 #![allow(clippy::unchecked_time_subtraction)]
322 #![allow(clippy::useless_vec)]
323 #![allow(clippy::needless_pass_by_value)]
324 use futures::SinkExt as _;
327 use futures_await_test::async_test;
328
329 use super::*;
330 use crate::dispatch::test::{Ctx, GetKids, Swan};
331
332 #[async_test]
333 async fn invoke() {
334 let ctx = Arc::new(Ctx::from(DispatchTable::from_inventory()));
335 let discard = || Box::pin(futures::sink::drain().sink_err_into());
336 let r = invoke_rpc_method(
337 ctx.clone(),
338 &ObjectId::from("Odile"),
339 Arc::new(Swan),
340 Box::new(GetKids),
341 discard(),
342 )
343 .unwrap()
344 .await
345 .unwrap();
346 assert_eq!(serde_json::to_string(&r).unwrap(), r#"{"v":"cygnets"}"#);
347
348 let r = invoke_special_method(ctx, Arc::new(Swan), Box::new(GetKids))
349 .await
350 .unwrap()
351 .unwrap();
352 assert_eq!(r.v, "cygnets");
353 }
354
355 #[test]
356 fn valid_method_names() {
357 let namespaces: HashSet<_> = ["arti", "wombat"].into_iter().collect();
358
359 for name in [
360 "arti:clone",
361 "arti:clone7",
362 "arti:clone_now",
363 "wombat:knish",
364 "x-foo:bar",
365 ] {
366 assert!(is_valid_rpc_identifier(Some(&namespaces), name).is_ok());
367 }
368 }
369
370 #[test]
371 fn invalid_method_names() {
372 let namespaces: HashSet<_> = ["arti", "wombat"].into_iter().collect();
373 use InvalidRpcIdentifier as E;
374
375 for (name, expect_err) in [
376 ("arti-foo:clone", E::UnrecognizedNamespace),
377 ("fred", E::NoNamespace),
378 ("arti:", E::BadIdName),
379 ("arti:7clone", E::BadIdName),
380 ("arti:CLONE", E::BadIdName),
381 ("arti:clone-now", E::BadIdName),
382 ] {
383 assert_eq!(
384 is_valid_rpc_identifier(Some(&namespaces), name),
385 Err(expect_err)
386 );
387 }
388 }
389}