#![warn(missing_docs)]
use bytes::Bytes;
use rings_core::dht::Did;
use crate::extension::ext::Ctx;
use crate::extension::ext::Interpret;
use crate::extension::ext::Protocol;
use crate::extension::ext::Reject;
use crate::extension::ext::Scope;
use crate::extension::ext::Transition;
use crate::extension::ext::Wire;
pub const NAMESPACE: &str = "echo";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Echoed {
pub from: Did,
pub payload: Bytes,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EchoEffect {
Reply {
to: Did,
payload: Bytes,
},
}
#[derive(Default)]
pub struct Echo;
impl Protocol for Echo {
type State = u64;
type Event = Echoed;
type Effect = EchoEffect;
fn namespace(&self) -> &str {
NAMESPACE
}
fn init(&self) -> u64 {
0
}
fn decode(&self, wire: Wire<'_>) -> Result<Echoed, Reject> {
Ok(Echoed {
from: wire.from,
payload: Bytes::copy_from_slice(wire.payload),
})
}
fn step(&self, ctx: Ctx<'_, u64>, event: Echoed) -> Transition<u64, EchoEffect> {
Transition::with(ctx.state + 1, vec![EchoEffect::Reply {
to: event.from,
payload: event.payload,
}])
}
}
#[derive(Default)]
pub struct EchoShell;
#[cfg_attr(feature = "browser", async_trait::async_trait(?Send))]
#[cfg_attr(not(feature = "browser"), async_trait::async_trait)]
impl Interpret for EchoShell {
type Effect = EchoEffect;
async fn run(&self, scope: &Scope, effect: EchoEffect) -> crate::error::Result<Vec<Bytes>> {
match effect {
EchoEffect::Reply { to, payload } => {
scope.send(to, payload).await?;
Ok(Vec::new())
}
}
}
}