nagisa_core/
middleware.rs1use crate::ctx::Ctx;
7use crate::router::Router;
8use async_trait::async_trait;
9use std::future::Future;
10use std::pin::Pin;
11use std::sync::Arc;
12
13#[derive(Clone, Copy, PartialEq, Eq, Debug)]
15pub enum Flow {
16 Continue,
17 Stop,
18}
19
20#[async_trait]
22pub trait Middleware: Send + Sync + 'static {
23 async fn handle(&self, ctx: Arc<Ctx>, next: Next<'_>) -> Flow;
24}
25
26pub struct Next<'a> {
28 pub(crate) remaining: &'a [Arc<dyn Middleware>],
29 pub(crate) terminal: &'a Router,
30}
31
32impl<'a> Next<'a> {
33 pub fn run(self, ctx: Arc<Ctx>) -> Pin<Box<dyn Future<Output = Flow> + Send + 'a>> {
35 Box::pin(async move {
36 match self.remaining.split_first() {
37 Some((mw, rest)) => {
38 let next = Next { remaining: rest, terminal: self.terminal };
39 mw.handle(ctx, next).await
40 }
41 None => {
42 self.terminal.run_handlers(ctx).await;
44 Flow::Continue
45 }
46 }
47 })
48 }
49}