use crafty_proto::{CodecError, LogIndex, decode, encode};
use serde::Serialize;
use serde::de::DeserializeOwned;
pub trait Command: Clone + Send + 'static {
fn to_bytes(&self) -> Result<Vec<u8>, CodecError>;
fn from_bytes(bytes: &[u8]) -> Result<Self, CodecError>
where
Self: Sized;
}
impl<T> Command for T
where
T: Clone + Send + 'static + Serialize + DeserializeOwned,
{
fn to_bytes(&self) -> Result<Vec<u8>, CodecError> {
encode(self)
}
fn from_bytes(bytes: &[u8]) -> Result<Self, CodecError> {
decode(bytes)
}
}
pub trait Query: Send + 'static {
fn to_bytes(&self) -> Result<Vec<u8>, CodecError>;
fn from_bytes(bytes: &[u8]) -> Result<Self, CodecError>
where
Self: Sized;
}
impl<T> Query for T
where
T: Send + 'static + Serialize + DeserializeOwned,
{
fn to_bytes(&self) -> Result<Vec<u8>, CodecError> {
encode(self)
}
fn from_bytes(bytes: &[u8]) -> Result<Self, CodecError> {
decode(bytes)
}
}
pub trait StateMachine: Send + 'static {
type Command: Command;
type Query: Query;
type Response: Send + 'static + Serialize + DeserializeOwned;
type Error: std::error::Error + Send + Sync + 'static;
fn apply(
&mut self,
index: LogIndex,
command: &Self::Command,
) -> Result<Self::Response, Self::Error>;
fn query(&self, query: &Self::Query) -> Result<Self::Response, Self::Error>;
fn snapshot(&self) -> Result<Vec<u8>, Self::Error>;
fn restore(&mut self, snapshot: &[u8]) -> Result<(), Self::Error>;
}