use crate::{components::FullNodeComponents, node::FullNode}; use std::fmt; /// Container for all the configurable hook functions. pub(crate) struct NodeHooks { pub(crate) on_component_initialized: Box>, pub(crate) on_node_started: Box>, pub(crate) _marker: std::marker::PhantomData, } impl NodeHooks { /// Creates a new, empty [NodeHooks] instance for the given node type. pub(crate) fn new() -> Self { Self { on_component_initialized: Box::<()>::default(), on_node_started: Box::<()>::default(), _marker: Default::default(), } } /// Sets the hook that is run once the node's components are initialized. pub(crate) fn set_on_component_initialized(&mut self, hook: F) -> &mut Self where F: OnComponentInitializedHook + 'static, { self.on_component_initialized = Box::new(hook); self } /// Sets the hook that is run once the node's components are initialized. #[allow(unused)] pub(crate) fn on_component_initialized(mut self, hook: F) -> Self where F: OnComponentInitializedHook + 'static, { self.set_on_component_initialized(hook); self } /// Sets the hook that is run once the node has started. pub(crate) fn set_on_node_started(&mut self, hook: F) -> &mut Self where F: OnNodeStartedHook + 'static, { self.on_node_started = Box::new(hook); self } /// Sets the hook that is run once the node has started. #[allow(unused)] pub(crate) fn on_node_started(mut self, hook: F) -> Self where F: OnNodeStartedHook + 'static, { self.set_on_node_started(hook); self } } impl Default for NodeHooks { fn default() -> Self { Self::new() } } impl fmt::Debug for NodeHooks { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("NodeHooks") .field("on_component_initialized", &"...") .field("on_node_started", &"...") .finish() } } /// A helper trait for the event hook that is run once the node is initialized. pub trait OnComponentInitializedHook: Send { /// Consumes the event hook and runs it. /// /// If this returns an error, the node launch will be aborted. fn on_event(&self, node: Node) -> eyre::Result<()>; } impl OnComponentInitializedHook for F where F: Fn(Node) -> eyre::Result<()> + Send, { fn on_event(&self, node: Node) -> eyre::Result<()> { self(node) } } /// A helper trait that is run once the node is started. pub trait OnNodeStartedHook: Send { /// Consumes the event hook and runs it. /// /// If this returns an error, the node launch will be aborted. fn on_event(&self, node: FullNode) -> eyre::Result<()>; } impl OnNodeStartedHook for F where Node: FullNodeComponents, F: Fn(FullNode) -> eyre::Result<()> + Send, { fn on_event(&self, node: FullNode) -> eyre::Result<()> { self(node) } } impl OnComponentInitializedHook for () { fn on_event(&self, _node: Node) -> eyre::Result<()> { Ok(()) } } impl OnNodeStartedHook for () { fn on_event(&self, _node: FullNode) -> eyre::Result<()> { Ok(()) } }