use async_trait::async_trait;
use crate::shutdown::{ExitReason, ShutdownToken};
use crate::tasks::TaskRegistry;
pub type PeerId = [u8; 32];
#[derive(Debug, Clone)]
pub struct PeerInfo {
pub peer_id: PeerId,
pub remote_addr: String,
pub node_type: String,
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub enum DisconnectReason {
Graceful,
LocalClose,
Transport(String),
ProtocolViolation(String),
}
#[derive(Debug, Clone)]
pub struct InboundMessage {
pub opcode: u8,
pub payload: Vec<u8>,
}
pub struct StartContext<'a> {
pub name: &'static str,
pub shutdown: ShutdownToken,
pub tasks: &'a TaskRegistry,
}
pub struct RunContext {
pub shutdown: ShutdownToken,
pub tasks: TaskRegistry,
}
pub struct StopContext<'a> {
pub shutdown: ShutdownToken,
pub tasks: &'a TaskRegistry,
pub exit_reason: ExitReason,
}
#[async_trait]
pub trait NodeLifecycle: Send + Sync + 'static {
const NAME: Option<&'static str> = None;
async fn pre_start(&self, ctx: &StartContext<'_>) -> anyhow::Result<()>;
async fn on_start(&self, ctx: &StartContext<'_>) -> anyhow::Result<()>;
async fn run(&self, ctx: RunContext) -> anyhow::Result<()>;
async fn on_stop(&self, ctx: &StopContext<'_>) -> anyhow::Result<()>;
async fn post_stop(&self, ctx: &StopContext<'_>) -> anyhow::Result<()>;
}
#[async_trait]
pub trait PeerApi: Send + Sync + 'static {
async fn on_message(&self, _peer: PeerId, _msg: InboundMessage) -> anyhow::Result<()> {
Ok(())
}
async fn on_peer_connected(&self, _peer: PeerId, _info: PeerInfo) {}
async fn on_peer_disconnected(&self, _peer: PeerId, _reason: DisconnectReason) {}
}
#[async_trait]
impl PeerApi for () {}
#[async_trait]
pub trait RpcApi: Send + Sync + 'static {
async fn dispatch(
&self,
method: &str,
params: serde_json::Value,
) -> std::result::Result<serde_json::Value, dig_rpc_types::envelope::JsonRpcError>;
async fn healthz(&self) -> std::result::Result<(), dig_rpc_types::envelope::JsonRpcError> {
Ok(())
}
}
#[async_trait]
impl RpcApi for () {
async fn dispatch(
&self,
method: &str,
_params: serde_json::Value,
) -> std::result::Result<serde_json::Value, dig_rpc_types::envelope::JsonRpcError> {
Err(dig_rpc_types::envelope::JsonRpcError {
code: dig_rpc_types::errors::ErrorCode::MethodNotFound,
message: format!("RpcApi not configured; method {method:?} rejected"),
data: None,
})
}
}