1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
use std::sync::Arc;

use futures::future::BoxFuture;
use tokio::sync::{Mutex, RwLock};

type Middleware<V, R> = Box<dyn FnMut(V, Next<V, R>) -> BoxFuture<'static, R> + Send>;
type MiddlewareMutex<V, R> = Mutex<Middleware<V, R>>;
type ListOfMiddlewares<V, R> = Vec<MiddlewareMutex<V, R>>;
type SharableListOfMiddlewares<V, R> = Arc<RwLock<ListOfMiddlewares<V, R>>>;

pub struct Manager<V, R> {
    list: SharableListOfMiddlewares<V, R>,
}

impl<V: 'static, R: 'static> Manager<V, R> {
    /// Create new instance
    pub fn new() -> Self {
        Self {
            list: Arc::default(),
        }
    }

    pub fn last<M: 'static>(last: M) -> Self
    where
        M: FnMut(V, Next<V, R>) -> BoxFuture<'static, R> + Send,
    {
        let s = Self::new();
        s.next(last);

        s
    }

    /// Start processing the value
    pub async fn send(&self, value: V) -> R {
        let total = self.list.read().await.len();

        let qq = Arc::clone(&self.list);
        let next = Next {
            list: Arc::clone(&qq),
            next: total - 1,
        };

        let lock = self.list.read().await;
        let mut callback = lock.last().unwrap().lock().await;
        (callback)(value, next).await
    }

    pub fn next<M: 'static>(&self, m: M) -> &Self
    where
        M: FnMut(V, Next<V, R>) -> BoxFuture<'static, R> + Send,
    {
        let list = Arc::clone(&self.list);
        futures::executor::block_on(async move {
            let mut lock = list.write().await;
            lock.push(Mutex::new(Box::new(m)));
        });

        self
    }
}

pub struct Next<V, R> {
    list: SharableListOfMiddlewares<V, R>,
    next: usize,
}

impl<V, R> Next<V, R> {
    pub async fn call(mut self, value: V) -> R {
        let list = Arc::clone(&self.list);
        let lock = list.read().await;
        self.next -= 1;
        if let Some(next) = lock.get(self.next) {
            let mut callback = next.lock().await;
            return callback(value, self).await;
        }
        panic!("There must be a default")
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[tokio::test]
    pub async fn test_last() {
        let result_str = "This is the end of the row";
        let manager = Manager::last(move |_v, _n| Box::pin(async move { result_str.to_string() }));

        assert_eq!(&manager.send(()).await, result_str);
    }

    #[tokio::test]
    pub async fn test_calling() {
        let manager = Manager {
            list: Arc::default(),
        };

        manager
            .next(|value, _next| Box::pin(async move { value }))
            .next(|value, next| Box::pin(async move { next.call(value * 2).await }))
            .next(|value, next| Box::pin(async move { next.call(value + 2).await }));

        let result: i32 = manager.send(10).await;

        assert_eq!(result, 24);
    }
}