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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
use anyhow::Result;
use async_trait::async_trait;
use futures::future::BoxFuture;

#[async_trait]
pub trait Handle<Request> {
    type Response;
    async fn handle(&mut self, request: Request) -> Result<Self::Response>;
}

pub trait Layer<H> {
    type Handle;
    fn layer(self, handle: H) -> Self::Handle;
}

#[derive(Clone, Debug)]
pub struct BeforeHookLayer<K> {
    hook: K,
}

impl<K> BeforeHookLayer<K> {
    pub fn new(hook: K) -> Self {
        Self { hook }
    }
}

impl<K, H> Layer<H> for BeforeHookLayer<K> {
    type Handle = BeforeHook<H, K>;

    fn layer(self, inner: H) -> Self::Handle {
        BeforeHook {
            hook: self.hook,
            inner,
        }
    }
}

#[derive(Clone, Debug)]
pub struct BeforeHook<H, K> {
    hook: K,
    inner: H,
}

#[async_trait]
impl<Q, H, K> Handle<Q> for BeforeHook<H, K>
where
    Q: Send + 'static,
    H: Handle<K::Output> + Send,
    K: Hook<Q> + Send,
    K::Output: Send,
{
    type Response = H::Response;

    async fn handle(&mut self, request: Q) -> Result<Self::Response> {
        let next_request = self.hook.hook(request).await?;
        self.inner.handle(next_request).await
    }
}

#[async_trait]
pub trait Hook<Input> {
    type Output;
    async fn hook(&mut self, input: Input) -> Result<Self::Output>;
}

#[derive(Clone, Debug)]
pub struct Choice<X, Y> {
    first: X,
    second: Y,
}

#[async_trait]
impl<Q, S, X, Y> Handle<Q> for Choice<X, Y>
where
    Q: Clone + Send + Sync + 'static,
    X: Handle<Q, Response = Option<S>> + Send,
    Y: Handle<Q, Response = Option<S>> + Send,
{
    type Response = Option<S>;

    async fn handle(&mut self, request: Q) -> Result<Self::Response> {
        if let Some(ret) = self.first.handle(request.clone()).await? {
            return Ok(Some(ret));
        }
        self.second.handle(request).await
    }
}

pub trait HandleChoiceExt<Q>: Handle<Q> {
    fn prepend<X>(self, first: X) -> Choice<X, Self>
    where
        Self: Sized,
    {
        Choice {
            first,
            second: self,
        }
    }

    fn append<Y>(self, second: Y) -> Choice<Self, Y>
    where
        Self: Sized,
    {
        Choice {
            first: self,
            second,
        }
    }
}

impl<T: ?Sized, Q> HandleChoiceExt<Q> for T where T: Handle<Q> {}

#[derive(Debug, Clone, Default)]
pub struct Identity;

impl<H> Layer<H> for Identity {
    type Handle = H;

    fn layer(self, inner: H) -> Self::Handle {
        inner
    }
}

#[derive(Clone, Debug)]
pub enum Either<A, B> {
    A(A),
    B(B),
}

impl<A, B, H> Layer<H> for Either<A, B>
where
    A: Layer<H>,
    B: Layer<H>,
{
    type Handle = Either<A::Handle, B::Handle>;

    fn layer(self, inner: H) -> Self::Handle {
        match self {
            Either::A(a) => Either::A(a.layer(inner)),
            Either::B(b) => Either::B(b.layer(inner)),
        }
    }
}

impl<A, B, Q> Handle<Q> for Either<A, B>
where
    A: Handle<Q>,
    B: Handle<Q, Response = A::Response>,
{
    type Response = A::Response;

    fn handle<'a: 's, 's>(&'a mut self, request: Q) -> BoxFuture<'s, Result<Self::Response>>
    where
        Self: 's,
    {
        match self {
            Either::A(a) => a.handle(request),
            Either::B(b) => b.handle(request),
        }
    }
}

#[derive(Clone, Debug)]
pub struct Stack<I, O> {
    inner: I,
    outer: O,
}

impl<I, O> Stack<I, O> {
    pub fn new(inner: I, outer: O) -> Stack<I, O> {
        Self { inner, outer }
    }
}

impl<I, O, H> Layer<H> for Stack<I, O>
where
    I: Layer<H>,
    O: Layer<I::Handle>,
{
    type Handle = O::Handle;

    fn layer(self, handle: H) -> Self::Handle {
        self.outer.layer(self.inner.layer(handle))
    }
}

#[derive(Clone, Debug)]
pub struct Builder<L> {
    layer: L,
}

impl Builder<Identity> {
    pub fn new() -> Self {
        Self { layer: Identity }
    }
}

impl Default for Builder<Identity> {
    fn default() -> Self {
        Self::new()
    }
}

impl<L> Builder<L> {
    pub fn layer<I>(self, layer: I) -> Builder<Stack<I, L>> {
        Builder {
            layer: Stack::new(layer, self.layer),
        }
    }

    pub fn option_layer<I>(self, layer: Option<I>) -> Builder<Stack<Either<I, Identity>, L>> {
        let inner = match layer {
            Some(layer) => Either::A(layer),
            None => Either::B(Identity),
        };
        Builder {
            layer: Stack::new(inner, self.layer),
        }
    }

    pub fn before_hook<K>(self, hook: K) -> Builder<Stack<BeforeHookLayer<K>, L>> {
        let before_hook = BeforeHookLayer::new(hook);
        self.layer(before_hook)
    }

    pub fn build<H>(self, handle: H) -> L::Handle
    where
        L: Layer<H>,
    {
        self.layer.layer(handle)
    }
}