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
#![deny(missing_docs)]

//! Define the [`Request`] and [`ExcService`] traits, and provide some useful helper traits.

use futures::{future::BoxFuture, FutureExt};
use std::marker::PhantomData;
use tower::{Layer, Service, ServiceExt};
use traits::IntoService;

/// Exchange Error.
pub mod error;

/// Layer.
pub mod layer;

/// Traits.
pub mod traits;

/// The adapt layer.
pub mod adapt;

#[cfg(feature = "retry")]
/// Retry utils.
pub mod retry;

pub use layer::ExcLayer;
pub use {
    adapt::Adaptor,
    traits::{BoxCloneExcService, BoxExcService, ExcService, ExcServiceExt, IntoExc, Request},
};

use self::adapt::{Adapt, AdaptLayer, AdaptService};
pub use self::error::ExchangeError;

#[cfg(feature = "send")]
pub use self::traits::send::SendExcService;

/// The core service wrapper of this crate, which implements
/// [`ExcService<T>`] *if* the request type of the underlying
/// service implements [`Adaptor<T>`].
///
/// With the help of [`Exc`], we can use a single type to represent
/// all the services that an exchange can provide.
///
/// For example, let `Exchange` be an api endpoint implementation of a exchange,
/// which implements [`Service<R>`], where `R` is the request type of the api endpoint.
/// Then `Exc<Exchange, R>` will implement `Service<SubscribeTickers>` and
/// `Service<PlaceOrder>`, as long as `R` implements both `Adaptor<SubscribeTickers>`
/// and `Adaptor<PlaceOrder>`.
#[derive(Debug)]
pub struct Exc<C, Req> {
    channel: C,
    _req: PhantomData<fn() -> Req>,
}

impl<C, Req> Clone for Exc<C, Req>
where
    C: Clone,
{
    fn clone(&self) -> Self {
        Self {
            channel: self.channel.clone(),
            _req: PhantomData,
        }
    }
}

impl<C, Req> Exc<C, Req> {
    /// Into the inner channel.
    #[inline]
    pub fn into_inner(self) -> C {
        self.channel
    }
}

impl<C, Req> Exc<C, Req>
where
    Req: Request,
    C: ExcService<Req>,
{
    /// Create from the given [`ExcService`].
    pub fn new(service: C) -> Self {
        Self {
            channel: service,
            _req: PhantomData,
        }
    }

    /// Make a request using the underlying channel directly.
    pub async fn request(&mut self, request: Req) -> Result<Req::Response, ExchangeError> {
        ServiceExt::<Req>::oneshot(self.channel.as_service(), request).await
    }

    /// Apply rate-limit layer to the channel.
    #[cfg(feature = "limit")]
    pub fn into_rate_limited(
        self,
        num: u64,
        per: std::time::Duration,
    ) -> Exc<tower::limit::RateLimit<IntoService<C, Req>>, Req> {
        use tower::limit::RateLimitLayer;
        self.into_layered(&RateLimitLayer::new(num, per))
    }

    #[cfg(feature = "retry")]
    /// Apply retry layer to the channel.
    pub fn into_retry(
        self,
        max_duration: std::time::Duration,
    ) -> Exc<tower::retry::Retry<crate::retry::Always, IntoService<C, Req>>, Req>
    where
        Req: Clone,
        C: Clone,
    {
        use crate::retry::Always;
        use tower::retry::RetryLayer;

        self.into_layered(&RetryLayer::new(Always::with_max_duration(max_duration)))
    }

    /// Adapt the request type of the underlying channel to the target type `R`.
    pub fn into_adapted<R>(self) -> Exc<Adapt<IntoService<C, Req>, Req, R>, R>
    where
        R: Request,
        IntoService<C, Req>: AdaptService<Req, R>,
    {
        self.into_layered(&AdaptLayer::default())
    }

    /// Apply a layer to the underlying channel.
    pub fn into_layered<T, R>(self, layer: &T) -> Exc<T::Service, R>
    where
        T: Layer<IntoService<C, Req>>,
        R: Request,
        T::Service: ExcService<R>,
    {
        Exc {
            channel: layer.layer(self.channel.into_service()),
            _req: PhantomData,
        }
    }
}

impl<C, Req, R> Service<R> for Exc<C, Req>
where
    R: Request,
    R::Response: Send + 'static,
    Req: Adaptor<R>,
    C: ExcService<Req>,
    C::Future: Send + 'static,
{
    type Response = R::Response;
    type Error = ExchangeError;
    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;

    fn poll_ready(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        self.channel.poll_ready(cx)
    }

    fn call(&mut self, req: R) -> Self::Future {
        let request = Req::from_request(req);
        match request {
            Ok(req) => {
                let res = self.channel.call(req);
                async move {
                    let resp = res.await?;
                    let resp = Req::into_response(resp)?;
                    Ok(resp)
                }
                .left_future()
            }
            Err(err) => futures::future::ready(Err(err)).right_future(),
        }
        .boxed()
    }
}