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