Skip to main content

typed_openrpc/
registry.rs

1use crate::rpc_method::{MethodDoc, RpcMethod};
2
3/// Collects all documented RPC methods.
4#[derive(Clone, Debug, Default)]
5pub struct Registry {
6    methods: Vec<MethodDoc>,
7}
8
9impl Registry {
10    /// Create an empty registry.
11    pub fn new() -> Self {
12        Self::default()
13    }
14
15    /// Return an iterator over registered methods.
16    pub fn methods(&self) -> &[MethodDoc] {
17        &self.methods
18    }
19
20    /// Consume the registry and yield the collected methods.
21    pub fn into_methods(self) -> Vec<MethodDoc> {
22        self.methods
23    }
24
25    /// Add an arbitrary method documentation entry.
26    pub fn register(&mut self, doc: MethodDoc) {
27        self.methods.push(doc);
28    }
29
30    /// Convenience wrapper for registering a `RpcMethod` implementation.
31    pub fn register_method<M: RpcMethod>(&mut self) {
32        self.register(MethodDoc::from::<M>());
33    }
34
35    /// Extend the registry with multiple method docs.
36    pub fn extend<I>(&mut self, docs: I)
37    where
38        I: IntoIterator<Item = MethodDoc>,
39    {
40        self.methods.extend(docs);
41    }
42
43    #[cfg(feature = "inventory")]
44    /// Populate the registry with methods submitted through the `inventory` crate.
45    ///
46    /// Typically this is used alongside the `#[rpc_method]` macro, which registers each method
47    /// when the `inventory` feature is enabled. Calling `collect` (or
48    /// [`registry_from_inventory`](crate::registry_from_inventory)) lets you gather these
49    /// definitions at build or runtime to generate an OpenRPC document.
50    pub fn collect(&mut self) {
51        for entry in inventory::iter::<crate::MethodDocInventoryEntry> {
52            self.register((entry.constructor)());
53        }
54    }
55}
56
57/// Entry submitted via the `inventory` registry.
58#[cfg(feature = "inventory")]
59pub struct MethodDocInventoryEntry {
60    pub constructor: fn() -> MethodDoc,
61}
62
63#[cfg(feature = "inventory")]
64inventory::collect!(MethodDocInventoryEntry);