use layered::Execute;
use layered::prelude::*;
#[tokio::main]
async fn main() {
let stack = (
Logging::layer("layer-1"),
Logging::layer("layer-2"),
Execute::new(|input| async move {
println!("executing input: {input}");
input
}),
);
let service = stack.into_service();
let _output = service.execute("Hello, World!".to_string()).await;
}
#[derive(Debug)]
pub struct Logging<S> {
inner: S,
id: &'static str,
}
#[derive(Debug)]
pub struct LoggingLayer {
id: &'static str,
}
impl Logging<()> {
#[must_use]
pub fn layer(id: &'static str) -> LoggingLayer {
LoggingLayer { id }
}
}
impl<S, In: Send, Out> Service<In> for Logging<S>
where
S: Service<In, Out = Out>,
{
type Out = Out;
async fn execute(&self, input: In) -> Self::Out {
println!("{}: executing input...", self.id);
let result = self.inner.execute(input).await;
println!("{}: executing input...done", self.id);
result
}
}
impl<S> Layer<S> for LoggingLayer {
type Service = Logging<S>;
fn layer(&self, inner: S) -> Self::Service {
Logging { inner, id: self.id }
}
}