rama_http/layer/set_header/response/
header.rs

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
435
436
437
438
439
440
441
442
443
use crate::{HeaderName, HeaderValue, Request, Response};
use rama_core::Context;
use std::{
    future::{ready, Future},
    marker::PhantomData,
};

/// Trait for preparing a maker ([`MakeHeaderValue`]) that will be used
/// to actually create the [`HeaderValue`] when desired.
///
/// The reason why this is split in two parts for responses is because
/// the context is consumed by the inner service producting the response
/// to which the header (maybe) will be attached to. In order to not
/// clone the entire `Context` and its `State` it is therefore better
/// to let the implementer decide what state is to be cloned and which not.
///
/// E.g. for a static Header value one might not need any state or context at all,
/// which would make it pretty wastefull if we would for such cases clone
/// these stateful datastructures anyhow.
///
/// Most users will however not have to worry about this Trait or why it is there,
/// as the trait is implemented already for functions, closures and HeaderValues.
pub trait MakeHeaderValueFactory<S, ReqBody, ResBody>: Send + Sync + 'static {
    /// Maker that _can_ be produced by this Factory.
    type Maker: MakeHeaderValue<ResBody>;

    /// Try to create a header value from the request or response.
    fn make_header_value_maker(
        &self,
        ctx: Context<S>,
        request: Request<ReqBody>,
    ) -> impl Future<Output = (Context<S>, Request<ReqBody>, Self::Maker)> + Send + '_;
}

/// Trait for producing header values, created by a `MakeHeaderValueFactory`.
///
/// Used by [`SetRequestHeader`] and [`SetResponseHeader`].
///
/// This trait is implemented for closures with the correct type signature. Typically users will
/// not have to implement this trait for their own types.
///
/// It is also implemented directly for [`HeaderValue`]. When a fixed header value should be added
/// to all responses, it can be supplied directly to the middleware.
pub trait MakeHeaderValue<B>: Send + Sync + 'static {
    /// Try to create a header value from the request or response.
    fn make_header_value(
        self,
        response: Response<B>,
    ) -> impl Future<Output = (Response<B>, Option<HeaderValue>)> + Send;
}

impl<B, M> MakeHeaderValue<B> for Option<M>
where
    M: MakeHeaderValue<B> + Clone,
    B: Send + 'static,
{
    async fn make_header_value(self, response: Response<B>) -> (Response<B>, Option<HeaderValue>) {
        match self {
            Some(m) => m.make_header_value(response).await,
            None => (response, None),
        }
    }
}

impl<B> MakeHeaderValue<B> for HeaderValue
where
    B: Send + 'static,
{
    fn make_header_value(
        self,
        response: Response<B>,
    ) -> impl Future<Output = (Response<B>, Option<HeaderValue>)> + Send {
        ready((response, Some(self)))
    }
}

impl<S, ReqBody, ResBody> MakeHeaderValueFactory<S, ReqBody, ResBody> for HeaderValue
where
    S: Clone + Send + Sync + 'static,
    ReqBody: Send + 'static,
    ResBody: Send + 'static,
{
    type Maker = Self;

    fn make_header_value_maker(
        &self,
        ctx: Context<S>,
        req: Request<ReqBody>,
    ) -> impl Future<Output = (Context<S>, Request<ReqBody>, Self::Maker)> + Send + '_ {
        ready((ctx, req, self.clone()))
    }
}

impl<S, ReqBody, ResBody> MakeHeaderValueFactory<S, ReqBody, ResBody> for Option<HeaderValue>
where
    S: Clone + Send + Sync + 'static,
    ReqBody: Send + 'static,
    ResBody: Send + 'static,
{
    type Maker = Self;

    fn make_header_value_maker(
        &self,
        ctx: Context<S>,
        req: Request<ReqBody>,
    ) -> impl Future<Output = (Context<S>, Request<ReqBody>, Self::Maker)> + Send + '_ {
        ready((ctx, req, self.clone()))
    }
}

/// Functional version of [`MakeHeaderValue`].
pub trait MakeHeaderValueFactoryFn<S, ReqBody, ResBody, A>: Send + Sync + 'static {
    type Maker: MakeHeaderValue<ResBody>;

    /// Try to create a header value from the request or response.
    fn call(
        &self,
        ctx: Context<S>,
        request: Request<ReqBody>,
    ) -> impl Future<Output = (Context<S>, Request<ReqBody>, Self::Maker)> + Send + '_;
}

impl<F, Fut, S, ReqBody, ResBody, M> MakeHeaderValueFactoryFn<S, ReqBody, ResBody, ()> for F
where
    S: Clone + Send + Sync + 'static,
    ReqBody: Send + 'static,
    ResBody: Send + 'static,
    M: MakeHeaderValue<ResBody>,
    F: Fn() -> Fut + Send + Sync + 'static,
    Fut: Future<Output = M> + Send + 'static,
    M: MakeHeaderValue<ResBody>,
{
    type Maker = M;

    async fn call(
        &self,
        ctx: Context<S>,
        request: Request<ReqBody>,
    ) -> (Context<S>, Request<ReqBody>, M) {
        let maker = self().await;
        (ctx, request, maker)
    }
}

impl<F, Fut, S, ReqBody, ResBody, M>
    MakeHeaderValueFactoryFn<S, ReqBody, ResBody, ((), Request<ReqBody>)> for F
where
    S: Clone + Send + Sync + 'static,
    ReqBody: Send + 'static,
    ResBody: Send + 'static,
    M: MakeHeaderValue<ResBody>,
    F: Fn(Request<ReqBody>) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = (Request<ReqBody>, M)> + Send + 'static,
    M: MakeHeaderValue<ResBody>,
{
    type Maker = M;

    async fn call(
        &self,
        ctx: Context<S>,
        request: Request<ReqBody>,
    ) -> (Context<S>, Request<ReqBody>, M) {
        let (request, maker) = self(request).await;
        (ctx, request, maker)
    }
}

impl<F, Fut, S, ReqBody, ResBody, M> MakeHeaderValueFactoryFn<S, ReqBody, ResBody, (Context<S>,)>
    for F
where
    S: Clone + Send + Sync + 'static,
    ReqBody: Send + 'static,
    ResBody: Send + 'static,
    M: MakeHeaderValue<ResBody>,
    F: Fn(Context<S>) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = (Context<S>, M)> + Send + 'static,
    M: MakeHeaderValue<ResBody>,
{
    type Maker = M;

    async fn call(
        &self,
        ctx: Context<S>,
        request: Request<ReqBody>,
    ) -> (Context<S>, Request<ReqBody>, M) {
        let (ctx, maker) = self(ctx).await;
        (ctx, request, maker)
    }
}

impl<F, Fut, S, ReqBody, ResBody, M> MakeHeaderValueFactoryFn<S, ReqBody, ResBody, (Context<S>, M)>
    for F
where
    S: Clone + Send + Sync + 'static,
    ReqBody: Send + 'static,
    ResBody: Send + 'static,
    M: MakeHeaderValue<ResBody>,
    F: Fn(Context<S>, Request<ReqBody>) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = (Context<S>, Request<ReqBody>, M)> + Send + 'static,
    M: MakeHeaderValue<ResBody>,
{
    type Maker = M;

    fn call(
        &self,
        ctx: Context<S>,
        request: Request<ReqBody>,
    ) -> impl Future<Output = (Context<S>, Request<ReqBody>, M)> + Send + '_ {
        self(ctx, request)
    }
}

/// The public wrapper type for [`MakeHeaderValueFactoryFn`].
pub struct BoxMakeHeaderValueFactoryFn<F, A> {
    f: F,
    _marker: PhantomData<fn(A) -> ()>,
}

impl<F, A> BoxMakeHeaderValueFactoryFn<F, A> {
    /// Create a new [`BoxMakeHeaderValueFactoryFn`].
    pub const fn new(f: F) -> Self {
        Self {
            f,
            _marker: PhantomData,
        }
    }
}

impl<F, A> Clone for BoxMakeHeaderValueFactoryFn<F, A>
where
    F: Clone,
{
    fn clone(&self) -> Self {
        Self {
            f: self.f.clone(),
            _marker: PhantomData,
        }
    }
}

impl<F, A> std::fmt::Debug for BoxMakeHeaderValueFactoryFn<F, A>
where
    F: std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BoxMakeHeaderValueFn")
            .field("f", &self.f)
            .finish()
    }
}

impl<S, ReqBody, ResBody, A, F> MakeHeaderValueFactory<S, ReqBody, ResBody>
    for BoxMakeHeaderValueFactoryFn<F, A>
where
    A: Send + 'static,
    F: MakeHeaderValueFactoryFn<S, ReqBody, ResBody, A>,
{
    type Maker = F::Maker;

    fn make_header_value_maker(
        &self,
        ctx: Context<S>,
        request: Request<ReqBody>,
    ) -> impl Future<Output = (Context<S>, Request<ReqBody>, Self::Maker)> + Send + '_ {
        self.f.call(ctx, request)
    }
}

/// Functional version of [`MakeHeaderValue`],
/// to make it easier to create a (response) header maker
/// directly from a response.
pub trait MakeHeaderValueFn<B, A>: Send + Sync + 'static {
    /// Try to create a header value from the request or response.
    fn call(
        self,
        response: Response<B>,
    ) -> impl Future<Output = (Response<B>, Option<HeaderValue>)> + Send;
}

impl<F, Fut, B> MakeHeaderValueFn<B, ()> for F
where
    B: Send + 'static,
    F: FnOnce() -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Option<HeaderValue>> + Send + 'static,
{
    async fn call(self, response: Response<B>) -> (Response<B>, Option<HeaderValue>) {
        let maybe_value = self().await;
        (response, maybe_value)
    }
}

impl<F, Fut, B> MakeHeaderValueFn<B, Response<B>> for F
where
    B: Send + 'static,
    F: FnOnce(Response<B>) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = (Response<B>, Option<HeaderValue>)> + Send + 'static,
{
    async fn call(self, response: Response<B>) -> (Response<B>, Option<HeaderValue>) {
        let (response, maybe_value) = self(response).await;
        (response, maybe_value)
    }
}

/// The public wrapper type for [`MakeHeaderValueFn`].
pub struct BoxMakeHeaderValueFn<F, A> {
    f: F,
    _marker: PhantomData<fn(A) -> ()>,
}

impl<F, A> BoxMakeHeaderValueFn<F, A> {
    /// Create a new [`BoxMakeHeaderValueFn`].
    pub const fn new(f: F) -> Self {
        Self {
            f,
            _marker: PhantomData,
        }
    }
}

impl<F, A> Clone for BoxMakeHeaderValueFn<F, A>
where
    F: Clone,
{
    fn clone(&self) -> Self {
        Self {
            f: self.f.clone(),
            _marker: PhantomData,
        }
    }
}

impl<F, A> std::fmt::Debug for BoxMakeHeaderValueFn<F, A>
where
    F: std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BoxMakeHeaderValueFn")
            .field("f", &self.f)
            .finish()
    }
}

impl<B, A, F> MakeHeaderValue<B> for BoxMakeHeaderValueFn<F, A>
where
    A: Send + 'static,
    F: MakeHeaderValueFn<B, A>,
{
    fn make_header_value(
        self,
        response: Response<B>,
    ) -> impl Future<Output = (Response<B>, Option<HeaderValue>)> + Send {
        self.f.call(response)
    }
}

impl<F, Fut, S, ReqBody, ResBody> MakeHeaderValueFactoryFn<S, ReqBody, ResBody, ((), (), ())> for F
where
    S: Clone + Send + Sync + 'static,
    ReqBody: Send + 'static,
    ResBody: Send + 'static,
    F: FnOnce() -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = Option<HeaderValue>> + Send + 'static,
{
    type Maker = BoxMakeHeaderValueFn<F, ()>;

    async fn call(
        &self,
        ctx: Context<S>,
        request: Request<ReqBody>,
    ) -> (Context<S>, Request<ReqBody>, Self::Maker) {
        let maker = self.clone();
        (ctx, request, BoxMakeHeaderValueFn::new(maker))
    }
}

impl<F, Fut, S, ReqBody, ResBody>
    MakeHeaderValueFactoryFn<S, ReqBody, ResBody, ((), (), Response<ResBody>)> for F
where
    S: Clone + Send + Sync + 'static,
    ReqBody: Send + 'static,
    ResBody: Send + 'static,
    F: FnOnce(Response<ResBody>) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = (Response<ResBody>, Option<HeaderValue>)> + Send + 'static,
{
    type Maker = BoxMakeHeaderValueFn<F, Response<ResBody>>;

    async fn call(
        &self,
        ctx: Context<S>,
        request: Request<ReqBody>,
    ) -> (Context<S>, Request<ReqBody>, Self::Maker) {
        let maker = self.clone();
        (ctx, request, BoxMakeHeaderValueFn::new(maker))
    }
}

#[derive(Debug, Clone, Copy)]
pub(super) enum InsertHeaderMode {
    Override,
    Append,
    IfNotPresent,
}

impl InsertHeaderMode {
    pub(super) async fn apply<B, M>(
        self,
        header_name: &HeaderName,
        response: Response<B>,
        make: M,
    ) -> Response<B>
    where
        B: Send + 'static,
        M: MakeHeaderValue<B>,
    {
        match self {
            InsertHeaderMode::Override => {
                let (mut response, maybe_value) = make.make_header_value(response).await;
                if let Some(value) = maybe_value {
                    response.headers_mut().insert(header_name.clone(), value);
                }
                response
            }
            InsertHeaderMode::IfNotPresent => {
                if !response.headers().contains_key(header_name) {
                    let (mut response, maybe_value) = make.make_header_value(response).await;
                    if let Some(value) = maybe_value {
                        response.headers_mut().insert(header_name.clone(), value);
                    }
                    response
                } else {
                    response
                }
            }
            InsertHeaderMode::Append => {
                let (mut response, maybe_value) = make.make_header_value(response).await;
                if let Some(value) = maybe_value {
                    response.headers_mut().append(header_name.clone(), value);
                }
                response
            }
        }
    }
}