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
// Copyright 2022 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.

//! Provides a hook that runs before request execution.

use crate::{context, server::Serve, ServerError};
use futures::prelude::*;

/// A hook that runs before request execution.
#[allow(async_fn_in_trait)]
pub trait BeforeRequest<Req> {
    /// The function that is called before request execution.
    ///
    /// If this function returns an error, the request will not be executed and the error will be
    /// returned instead.
    ///
    /// This function can also modify the request context. This could be used, for example, to
    /// enforce a maximum deadline on all requests.
    async fn before(&mut self, ctx: &mut context::Context, req: &Req) -> Result<(), ServerError>;
}

/// A list of hooks that run in order before request execution.
pub trait BeforeRequestList<Req>: BeforeRequest<Req> {
    /// The hook returned by `BeforeRequestList::then`.
    type Then<Next>: BeforeRequest<Req>
    where
        Next: BeforeRequest<Req>;

    /// Returns a hook that, when run, runs two hooks, first `self` and then `next`.
    fn then<Next: BeforeRequest<Req>>(self, next: Next) -> Self::Then<Next>;

    /// Same as `then`, but helps the compiler with type inference when Next is a closure.
    fn then_fn<
        Next: FnMut(&mut context::Context, &Req) -> Fut,
        Fut: Future<Output = Result<(), ServerError>>,
    >(
        self,
        next: Next,
    ) -> Self::Then<Next>
    where
        Self: Sized,
    {
        self.then(next)
    }

    /// The service fn returned by `BeforeRequestList::serving`.
    type Serve<S: Serve<Req = Req>>: Serve<Req = Req>;

    /// Runs the list of request hooks before execution of the given serve fn.
    /// This is equivalent to `serve.before(before_request_chain)` but may be syntactically nicer.
    fn serving<S: Serve<Req = Req>>(self, serve: S) -> Self::Serve<S>;
}

impl<F, Fut, Req> BeforeRequest<Req> for F
where
    F: FnMut(&mut context::Context, &Req) -> Fut,
    Fut: Future<Output = Result<(), ServerError>>,
{
    async fn before(&mut self, ctx: &mut context::Context, req: &Req) -> Result<(), ServerError> {
        self(ctx, req).await
    }
}

/// A Service function that runs a hook before request execution.
#[derive(Clone)]
pub struct HookThenServe<Serv, Hook> {
    serve: Serv,
    hook: Hook,
}

impl<Serv, Hook> HookThenServe<Serv, Hook> {
    pub(crate) fn new(serve: Serv, hook: Hook) -> Self {
        Self { serve, hook }
    }
}

impl<Serv, Hook> Serve for HookThenServe<Serv, Hook>
where
    Serv: Serve,
    Hook: BeforeRequest<Serv::Req>,
{
    type Req = Serv::Req;
    type Resp = Serv::Resp;

    async fn serve(
        self,
        mut ctx: context::Context,
        req: Self::Req,
    ) -> Result<Serv::Resp, ServerError> {
        let HookThenServe {
            serve, mut hook, ..
        } = self;
        hook.before(&mut ctx, &req).await?;
        serve.serve(ctx, req).await
    }
}

/// Returns a request hook builder that runs a series of hooks before request execution.
///
/// Example
///
/// ```rust
/// use futures::{executor::block_on, future};
/// use tarpc::{context, ServerError, server::{Serve, serve, request_hook::{self,
///             BeforeRequest, BeforeRequestList}}};
/// use std::{cell::Cell, io};
///
/// let i = Cell::new(0);
/// let serve = request_hook::before()
///     .then_fn(|_, _| async {
///         assert!(i.get() == 0);
///         i.set(1);
///         Ok(())
///     })
///     .then_fn(|_, _| async {
///         assert!(i.get() == 1);
///         i.set(2);
///         Ok(())
///     })
///     .serving(serve(|_ctx, i| async move { Ok(i + 1) }));
/// let response = serve.clone().serve(context::current(), 1);
/// assert!(block_on(response).is_ok());
/// assert!(i.get() == 2);
/// ```
pub fn before() -> BeforeRequestNil {
    BeforeRequestNil
}

/// A list of hooks that run in order before a request is executed.
#[derive(Clone, Copy)]
pub struct BeforeRequestCons<First, Rest>(First, Rest);

/// A noop hook that runs before a request is executed.
#[derive(Clone, Copy)]
pub struct BeforeRequestNil;

impl<Req, First: BeforeRequest<Req>, Rest: BeforeRequest<Req>> BeforeRequest<Req>
    for BeforeRequestCons<First, Rest>
{
    async fn before(&mut self, ctx: &mut context::Context, req: &Req) -> Result<(), ServerError> {
        let BeforeRequestCons(first, rest) = self;
        first.before(ctx, req).await?;
        rest.before(ctx, req).await?;
        Ok(())
    }
}

impl<Req> BeforeRequest<Req> for BeforeRequestNil {
    async fn before(&mut self, _: &mut context::Context, _: &Req) -> Result<(), ServerError> {
        Ok(())
    }
}

impl<Req, First: BeforeRequest<Req>, Rest: BeforeRequestList<Req>> BeforeRequestList<Req>
    for BeforeRequestCons<First, Rest>
{
    type Then<Next> = BeforeRequestCons<First, Rest::Then<Next>> where Next: BeforeRequest<Req>;

    fn then<Next: BeforeRequest<Req>>(self, next: Next) -> Self::Then<Next> {
        let BeforeRequestCons(first, rest) = self;
        BeforeRequestCons(first, rest.then(next))
    }

    type Serve<S: Serve<Req = Req>> = HookThenServe<S, Self>;

    fn serving<S: Serve<Req = Req>>(self, serve: S) -> Self::Serve<S> {
        HookThenServe::new(serve, self)
    }
}

impl<Req> BeforeRequestList<Req> for BeforeRequestNil {
    type Then<Next> = BeforeRequestCons<Next, BeforeRequestNil> where Next: BeforeRequest<Req>;

    fn then<Next: BeforeRequest<Req>>(self, next: Next) -> Self::Then<Next> {
        BeforeRequestCons(next, BeforeRequestNil)
    }

    type Serve<S: Serve<Req = Req>> = S;

    fn serving<S: Serve<Req = Req>>(self, serve: S) -> S {
        serve
    }
}

#[test]
fn before_request_list() {
    use crate::server::serve;
    use futures::executor::block_on;
    use std::cell::Cell;

    let i = Cell::new(0);
    let serve = before()
        .then_fn(|_, _| async {
            assert!(i.get() == 0);
            i.set(1);
            Ok(())
        })
        .then_fn(|_, _| async {
            assert!(i.get() == 1);
            i.set(2);
            Ok(())
        })
        .serving(serve(|_ctx, i| async move { Ok(i + 1) }));
    let response = serve.clone().serve(context::current(), 1);
    assert!(block_on(response).is_ok());
    assert!(i.get() == 2);
}