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