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
use alloc::{rc::Rc, sync::Arc};
use core::{
    future::Future,
    marker::PhantomData,
    pin::Pin,
    task::{Context, Poll},
};

use futures_core::ready;
use pin_project_lite::pin_project;

use crate::{IntoServiceFactory, Service, ServiceFactory};

/// Apply a [`Transform`] to a [`Service`].
pub fn apply<T, S, I, Req>(t: T, factory: I) -> ApplyTransform<T, S, Req>
where
    I: IntoServiceFactory<S, Req>,
    S: ServiceFactory<Req>,
    T: Transform<S::Service, Req, InitError = S::InitError>,
{
    ApplyTransform::new(t, factory.into_factory())
}

/// Defines the interface of a service factory that wraps inner service during construction.
///
/// Transformers wrap an inner service and runs during inbound and/or outbound processing in the
/// service lifecycle. It may modify request and/or response.
///
/// For example, a timeout service wrapper:
///
/// ```ignore
/// pub struct Timeout<S> {
///     service: S,
///     timeout: Duration,
/// }
///
/// impl<S: Service<Req>, Req> Service<Req> for Timeout<S> {
///     type Response = S::Response;
///     type Error = TimeoutError<S::Error>;
///     type Future = TimeoutServiceResponse<S>;
///
///     actix_service::forward_ready!(service);
///
///     fn call(&self, req: Req) -> Self::Future {
///         TimeoutServiceResponse {
///             fut: self.service.call(req),
///             sleep: Sleep::new(clock::now() + self.timeout),
///         }
///     }
/// }
/// ```
///
/// This wrapper service is decoupled from the underlying service implementation and could be
/// applied to any service.
///
/// The `Transform` trait defines the interface of a service wrapper. `Transform` is often
/// implemented for middleware, defining how to construct a middleware Service. A Service that is
/// constructed by the factory takes the Service that follows it during execution as a parameter,
/// assuming ownership of the next Service.
///
/// A transform for the `Timeout` middleware could look like this:
///
/// ```ignore
/// pub struct TimeoutTransform {
///     timeout: Duration,
/// }
///
/// impl<S: Service<Req>, Req> Transform<S, Req> for TimeoutTransform {
///     type Response = S::Response;
///     type Error = TimeoutError<S::Error>;
///     type InitError = S::Error;
///     type Transform = Timeout<S>;
///     type Future = Ready<Result<Self::Transform, Self::InitError>>;
///
///     fn new_transform(&self, service: S) -> Self::Future {
///         ready(Ok(Timeout {
///             service,
///             timeout: self.timeout,
///         }))
///     }
/// }
/// ```
pub trait Transform<S, Req> {
    /// Responses produced by the service.
    type Response;

    /// Errors produced by the service.
    type Error;

    /// The `TransformService` value created by this factory
    type Transform: Service<Req, Response = Self::Response, Error = Self::Error>;

    /// Errors produced while building a transform service.
    type InitError;

    /// The future response value.
    type Future: Future<Output = Result<Self::Transform, Self::InitError>>;

    /// Creates and returns a new Transform component, asynchronously
    fn new_transform(&self, service: S) -> Self::Future;
}

impl<T, S, Req> Transform<S, Req> for Rc<T>
where
    T: Transform<S, Req>,
{
    type Response = T::Response;
    type Error = T::Error;
    type Transform = T::Transform;
    type InitError = T::InitError;
    type Future = T::Future;

    fn new_transform(&self, service: S) -> T::Future {
        self.as_ref().new_transform(service)
    }
}

impl<T, S, Req> Transform<S, Req> for Arc<T>
where
    T: Transform<S, Req>,
{
    type Response = T::Response;
    type Error = T::Error;
    type Transform = T::Transform;
    type InitError = T::InitError;
    type Future = T::Future;

    fn new_transform(&self, service: S) -> T::Future {
        self.as_ref().new_transform(service)
    }
}

/// Apply a [`Transform`] to a [`Service`].
pub struct ApplyTransform<T, S, Req>(Rc<(T, S)>, PhantomData<Req>);

impl<T, S, Req> ApplyTransform<T, S, Req>
where
    S: ServiceFactory<Req>,
    T: Transform<S::Service, Req, InitError = S::InitError>,
{
    /// Create new `ApplyTransform` new service instance
    fn new(t: T, service: S) -> Self {
        Self(Rc::new((t, service)), PhantomData)
    }
}

impl<T, S, Req> Clone for ApplyTransform<T, S, Req> {
    fn clone(&self) -> Self {
        ApplyTransform(self.0.clone(), PhantomData)
    }
}

impl<T, S, Req> ServiceFactory<Req> for ApplyTransform<T, S, Req>
where
    S: ServiceFactory<Req>,
    T: Transform<S::Service, Req, InitError = S::InitError>,
{
    type Response = T::Response;
    type Error = T::Error;

    type Config = S::Config;
    type Service = T::Transform;
    type InitError = T::InitError;
    type Future = ApplyTransformFuture<T, S, Req>;

    fn new_service(&self, cfg: S::Config) -> Self::Future {
        ApplyTransformFuture {
            store: self.0.clone(),
            state: ApplyTransformFutureState::A {
                fut: self.0.as_ref().1.new_service(cfg),
            },
        }
    }
}

pin_project! {
    pub struct ApplyTransformFuture<T, S, Req>
    where
        S: ServiceFactory<Req>,
        T: Transform<S::Service, Req, InitError = S::InitError>,
    {
        store: Rc<(T, S)>,
        #[pin]
        state: ApplyTransformFutureState<T, S, Req>,
    }
}

pin_project! {
    #[project = ApplyTransformFutureStateProj]
    pub enum ApplyTransformFutureState<T, S, Req>
    where
        S: ServiceFactory<Req>,
        T: Transform<S::Service, Req, InitError = S::InitError>,
    {
        A { #[pin] fut: S::Future },
        B { #[pin] fut: T::Future },
    }
}

impl<T, S, Req> Future for ApplyTransformFuture<T, S, Req>
where
    S: ServiceFactory<Req>,
    T: Transform<S::Service, Req, InitError = S::InitError>,
{
    type Output = Result<T::Transform, T::InitError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut this = self.as_mut().project();

        match this.state.as_mut().project() {
            ApplyTransformFutureStateProj::A { fut } => {
                let srv = ready!(fut.poll(cx))?;
                let fut = this.store.0.new_transform(srv);
                this.state.set(ApplyTransformFutureState::B { fut });
                self.poll(cx)
            }
            ApplyTransformFutureStateProj::B { fut } => fut.poll(cx),
        }
    }
}

#[cfg(test)]
mod tests {
    use core::time::Duration;

    use actix_utils::future::{ready, Ready};

    use super::*;
    use crate::Service;

    // pseudo-doctest for Transform trait
    pub struct TimeoutTransform {
        timeout: Duration,
    }

    // pseudo-doctest for Transform trait
    impl<S: Service<Req>, Req> Transform<S, Req> for TimeoutTransform {
        type Response = S::Response;
        type Error = S::Error;
        type InitError = S::Error;
        type Transform = Timeout<S>;
        type Future = Ready<Result<Self::Transform, Self::InitError>>;

        fn new_transform(&self, service: S) -> Self::Future {
            ready(Ok(Timeout {
                service,
                _timeout: self.timeout,
            }))
        }
    }

    // pseudo-doctest for Transform trait
    pub struct Timeout<S> {
        service: S,
        _timeout: Duration,
    }

    // pseudo-doctest for Transform trait
    impl<S: Service<Req>, Req> Service<Req> for Timeout<S> {
        type Response = S::Response;
        type Error = S::Error;
        type Future = S::Future;

        crate::forward_ready!(service);

        fn call(&self, req: Req) -> Self::Future {
            self.service.call(req)
        }
    }
}