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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
use crate::{async_trait, Conn, Info, Status, Upgrade};
use std::{borrow::Cow, future::Future, sync::Arc};

/**
# The building block for Trillium applications.

## Concept

Many other frameworks have a notion of `middleware` and `endpoints`,
in which the model is that a request passes through a router and then
any number of middlewares, then a single endpoint that returns a
response, and then passes a response back through the middleware
stack.

Because a Trillium Conn represents both a request and response, there
is no distinction between middleware and endpoints, as all of these
can be modeled as `Fn(Conn) -> Future<Output = Conn>`.

## Implementing Handler

The simplest handler is an async closure or
async fn that receives a Conn and returns a Conn, and Handler has a
blanket implementation for any such Fn.

```
// as a closure
let handler = |conn: trillium::Conn| async move { conn.ok("trillium!") };

use trillium_testing::prelude::*;
assert_ok!(get("/").on(&handler), "trillium!");
```

```
// as an async function
async fn handler(conn: trillium::Conn) -> trillium::Conn {
    conn.ok("trillium!")
}
use trillium_testing::prelude::*;
assert_ok!(get("/").on(&handler), "trillium!");
```

The simplest implementation of Handler for a named type looks like this:
```
pub struct MyHandler;
#[trillium::async_trait]
impl trillium::Handler for MyHandler {
    async fn run(&self, conn: trillium::Conn) -> trillium::Conn {
        conn
    }
}

use trillium_testing::prelude::*;
assert_not_handled!(get("/").on(&MyHandler)); // we did not halt or set a body status
```

**Temporary Note:** Until rust has true async traits, implementing
handler requires the use of the async_trait macro, which is reexported
as [`trillium::async_trait`](crate::async_trait).

## Full trait specification

Unfortunately, the async_trait macro results in the difficult-to-read
documentation at the top of the page, so here is how the trait is
actually defined in trillium code:

```
# use trillium::{Conn, Upgrade, Info};
# use std::borrow::Cow;
#[trillium::async_trait]
pub trait Handler: Send + Sync + 'static {
    async fn run(&self, conn: Conn) -> Conn;
    async fn init(&mut self, info: &mut Info); // optional
    async fn before_send(&self, conn: Conn); // optional
    fn has_upgrade(&self, _upgrade: &Upgrade) -> bool; // optional
    async fn upgrade(&self, _upgrade: Upgrade); // mandatory only if has_upgrade returns true
    fn name(&self) -> Cow<'static, str>; // optional
}
```
See each of the function definitions below for advanced implementation.

For most application code and even trillium-packaged framework code,
`run` is the only trait function that needs to be implemented.

*/

#[async_trait]
pub trait Handler: Send + Sync + 'static {
    /// Executes this handler, performing any modifications to the
    /// Conn that are desired.
    async fn run(&self, conn: Conn) -> Conn;

    /**
    Performs one-time async set up on a mutable borrow of the
    Handler before the server starts accepting requests. This
    allows a Handler to be defined in synchronous code but perform
    async setup such as establishing a database connection or
    fetching some state from an external source. This is optional,
    and chances are high that you do not need this.

    It also receives a mutable borrow of the [`Info`] that represents
    the current connection.

    **stability note:** This may go away at some point. Please open an
    **issue if you have a use case which requires it.
    */
    async fn init(&mut self, _info: &mut Info) {}

    /**
    Performs any final modifications to this conn after all handlers
    have been run. Although this is a slight deviation from the simple
    conn->conn->conn chain represented by most Handlers, it provides
    an easy way for libraries to effectively inject a second handler
    into a response chain. This is useful for loggers that need to
    record information both before and after other handlers have run,
    as well as database transaction handlers and similar library code.

    **❗IMPORTANT NOTE FOR LIBRARY AUTHORS:** Please note that this
    will run __whether or not the conn has was halted before
    [`Handler::run`] was called on a given conn__. This means that if
    you want to make your `before_send` callback conditional on
    whether `run` was called, you need to put a unit type into the
    conn's state and check for that.

    stability note: I don't love this for the exact reason that it
    breaks the simplicity of the conn->conn->model, but it is
    currently the best compromise between that simplicity and
    convenience for the application author, who should not have to add
    two Handlers to achieve an "around" effect.
    */
    async fn before_send(&self, conn: Conn) -> Conn {
        conn
    }

    /**
    predicate function answering the question of whether this Handler
    would like to take ownership of the negotiated Upgrade. If this
    returns true, you must implement [`Handler::upgrade`]. The first
    handler that responds true to this will receive ownership of the
    [`trillium::Upgrade`][crate::Upgrade] in a subsequent call to [`Handler::upgrade`]
    */
    fn has_upgrade(&self, _upgrade: &Upgrade) -> bool {
        false
    }

    /**
    This will only be called if the handler reponds true to
    [`Handler::has_upgrade`] and will only be called once for this
    upgrade. There is no return value, and this function takes
    exclusive ownership of the underlying transport once this is
    called. You can downcast the transport to whatever the source
    transport type is and perform any non-http protocol communication
    that has been negotiated. You probably don't want this unless
    you're implementing something like websockets. Please note that
    for many transports such as TcpStreams, dropping the transport
    (and therefore the Upgrade) will hang up / disconnect.
    */
    async fn upgrade(&self, _upgrade: Upgrade) {
        unimplemented!("if has_upgrade returns true, you must also implement upgrade")
    }

    /**
    Customize the name of your handler. This is used in Debug
    implementations. The default is the type name of this handler.
    */
    fn name(&self) -> Cow<'static, str> {
        std::any::type_name::<Self>().into()
    }
}

#[async_trait]
impl Handler for Box<dyn Handler> {
    async fn run(&self, conn: Conn) -> Conn {
        self.as_ref().run(conn).await
    }

    async fn init(&mut self, info: &mut Info) {
        self.as_mut().init(info).await;
    }

    async fn before_send(&self, conn: Conn) -> Conn {
        self.as_ref().before_send(conn).await
    }

    fn name(&self) -> Cow<'static, str> {
        self.as_ref().name()
    }

    fn has_upgrade(&self, upgrade: &Upgrade) -> bool {
        self.as_ref().has_upgrade(upgrade)
    }

    async fn upgrade(&self, upgrade: Upgrade) {
        self.as_ref().upgrade(upgrade).await;
    }
}

#[async_trait]
impl Handler for Status {
    async fn run(&self, conn: Conn) -> Conn {
        conn.with_status(*self)
    }
}

impl std::fmt::Debug for Box<dyn Handler> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.name().as_ref())
    }
}

#[async_trait]
impl<H: Handler> Handler for Arc<H> {
    async fn run(&self, conn: Conn) -> Conn {
        self.as_ref().run(conn).await
    }

    async fn init(&mut self, info: &mut Info) {
        Self::get_mut(self)
            .expect("cannot call init when there are already clones of an Arc<Handler>")
            .init(info)
            .await;
    }

    async fn before_send(&self, conn: Conn) -> Conn {
        self.as_ref().before_send(conn).await
    }

    fn name(&self) -> Cow<'static, str> {
        self.as_ref().name()
    }

    fn has_upgrade(&self, upgrade: &Upgrade) -> bool {
        self.as_ref().has_upgrade(upgrade)
    }

    async fn upgrade(&self, upgrade: Upgrade) {
        self.as_ref().upgrade(upgrade).await;
    }
}

#[async_trait]
impl<H: Handler> Handler for Vec<H> {
    async fn run(&self, mut conn: Conn) -> Conn {
        for handler in self {
            log::debug!("running {}", handler.name());
            conn = handler.run(conn).await;
            if conn.is_halted() {
                break;
            }
        }
        conn
    }

    async fn init(&mut self, info: &mut Info) {
        for handler in self {
            handler.init(info).await;
        }
    }

    async fn before_send(&self, mut conn: Conn) -> Conn {
        for handler in self.iter().rev() {
            conn = handler.before_send(conn).await;
        }
        conn
    }

    fn name(&self) -> Cow<'static, str> {
        self.iter()
            .map(Handler::name)
            .collect::<Vec<_>>()
            .join(",")
            .into()
    }

    fn has_upgrade(&self, upgrade: &Upgrade) -> bool {
        self.iter().any(|g| g.has_upgrade(upgrade))
    }

    async fn upgrade(&self, upgrade: Upgrade) {
        if let Some(handler) = self.iter().find(|g| g.has_upgrade(&upgrade)) {
            handler.upgrade(upgrade).await;
        }
    }
}

#[async_trait]
impl<Fun, Fut> Handler for Fun
where
    Fun: Fn(Conn) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Conn> + Send + 'static,
{
    async fn run(&self, conn: Conn) -> Conn {
        (self)(conn).await
    }
}

#[async_trait]
impl Handler for &'static str {
    async fn run(&self, conn: Conn) -> Conn {
        conn.ok(*self)
    }

    fn name(&self) -> Cow<'static, str> {
        format!("conn.ok({:?})", &self).into()
    }
}

#[async_trait]
impl Handler for () {
    async fn run(&self, conn: Conn) -> Conn {
        conn
    }
}

#[async_trait]
impl<H: Handler> Handler for Option<H> {
    async fn run(&self, conn: Conn) -> Conn {
        let handler = crate::conn_unwrap!(self, conn);
        handler.run(conn).await
    }

    async fn init(&mut self, info: &mut Info) {
        if let Some(handler) = self {
            handler.init(info).await;
        }
    }

    async fn before_send(&self, conn: Conn) -> Conn {
        let handler = crate::conn_unwrap!(self, conn);
        handler.before_send(conn).await
    }

    fn name(&self) -> Cow<'static, str> {
        match self {
            Some(h) => h.name(),
            None => "-".into(),
        }
    }

    fn has_upgrade(&self, upgrade: &Upgrade) -> bool {
        match self {
            Some(h) => h.has_upgrade(upgrade),
            None => false,
        }
    }

    async fn upgrade(&self, upgrade: Upgrade) {
        if let Some(handler) = self {
            handler.upgrade(upgrade).await;
        }
    }
}

macro_rules! reverse_before_send {
    ($conn:ident, $name:ident) => (
        let $conn = ($name).before_send($conn).await;
    );

    ($conn:ident, $name:ident $($other_names:ident)+) => (
        reverse_before_send!($conn, $($other_names)*);
        reverse_before_send!($conn, $name);
    );
}

macro_rules! impl_handler_tuple {
        ($($name:ident)+) => (
            #[async_trait]
            impl<$($name),*> Handler for ($($name,)*) where $($name: Handler),* {
                #[allow(non_snake_case)]
                async fn run(&self, conn: Conn) -> Conn {
                    let ($(ref $name,)*) = *self;
                    $(
                        log::debug!("running {}", ($name).name());
                        let conn = ($name).run(conn).await;
                        if conn.is_halted() { return conn }
                    )*
                    conn
                }

                #[allow(non_snake_case)]
                async fn init(&mut self, info: &mut Info) {
                    let ($(ref mut $name,)*) = *self;
                    $(
                        log::trace!("initializing {}", ($name).name());
                        ($name).init(info).await;
                    )*
                }

                #[allow(non_snake_case)]
                async fn before_send(&self, conn: Conn) -> Conn {
                    let ($(ref $name,)*) = *self;
                    reverse_before_send!(conn, $($name)+);
                    conn
                }

                #[allow(non_snake_case)]
                fn has_upgrade(&self, upgrade: &Upgrade) -> bool {
                    let ($(ref $name,)*) = *self;
                    $(if ($name).has_upgrade(upgrade) { return true })*
                    false
                }

                #[allow(non_snake_case)]
                async fn upgrade(&self, upgrade: Upgrade) {
                    let ($(ref $name,)*) = *self;
                    $(if ($name).has_upgrade(&upgrade) {
                        return ($name).upgrade(upgrade).await;
                    })*
                }

                #[allow(non_snake_case)]
                fn name(&self) -> Cow<'static, str> {
                    let ($(ref $name,)*) = *self;
                    format!(concat!("(\n", $(
                        concat!("  {",stringify!($name) ,":},\n")
                    ),*, ")"), $($name = ($name).name()),*).into()
                }
            }
        );
    }

impl_handler_tuple! { A B }
impl_handler_tuple! { A B C }
impl_handler_tuple! { A B C D }
impl_handler_tuple! { A B C D E }
impl_handler_tuple! { A B C D E F }
impl_handler_tuple! { A B C D E F G }
impl_handler_tuple! { A B C D E F G H }
impl_handler_tuple! { A B C D E F G H I }
impl_handler_tuple! { A B C D E F G H I J }
impl_handler_tuple! { A B C D E F G H I J K }
impl_handler_tuple! { A B C D E F G H I J K L }
impl_handler_tuple! { A B C D E F G H I J K L M }
impl_handler_tuple! { A B C D E F G H I J K L M N }
impl_handler_tuple! { A B C D E F G H I J K L M N O }