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
use exc_core::retry::RetryPolicy;
use exc_core::transport::http::channel::HttpsChannel;
use exc_core::{ExchangeError, Request};
use futures::future::{ready, BoxFuture};
use futures::{FutureExt, TryFutureExt};
use tower::buffer::Buffer;
use tower::ready_cache::ReadyCache;
use tower::retry::Retry;
use tower::util::Either;
use tower::Service;

use crate::http::layer::OkxHttpApi;
use crate::http::types::{request::HttpRequest, response::HttpResponse};
use crate::websocket::transport::channel::Channel as WsChannel;
use crate::websocket::{Request as WsRequest, Response as WsResponse};

use self::endpoint::Endpoint;

/// Endpoint.
pub mod endpoint;

mod adaptation;

/// Okx request.
pub enum OkxRequest {
    /// Request of HTTP API.
    Http(HttpRequest),
    /// Request of WS API.
    Ws(WsRequest),
}

impl OkxRequest {
    /// Subscribe to orders channel.
    pub fn subscribe_orders(inst: &str) -> Self {
        Self::Ws(WsRequest::subscribe_orders(inst))
    }
}

/// Okx response.
pub enum OkxResponse {
    /// Response from HTTP API.
    Http(HttpResponse),
    /// Response from WS API.
    Ws(WsResponse),
}

impl OkxResponse {
    /// Convert into http response.
    pub fn http(self) -> Result<HttpResponse, ExchangeError> {
        if let Self::Http(res) = self {
            Ok(res)
        } else {
            Err(ExchangeError::Other(anyhow::anyhow!(
                "unexpected response type `ws`"
            )))
        }
    }

    /// Convert into websocket response.
    pub fn ws(self) -> Result<WsResponse, ExchangeError> {
        if let Self::Ws(res) = self {
            Ok(res)
        } else {
            Err(ExchangeError::Other(anyhow::anyhow!(
                "unexpected response type `http`"
            )))
        }
    }
}

impl Request for OkxRequest {
    type Response = OkxResponse;
}

type HttpInner = OkxHttpApi<HttpsChannel>;
type Http = Retry<RetryPolicy<HttpRequest, HttpResponse, fn(&ExchangeError) -> bool>, HttpInner>;
type Ws = WsChannel;

impl Service<OkxRequest> for Http {
    type Response = OkxResponse;

    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>> {
        Service::<HttpRequest>::poll_ready(self, cx)
    }

    fn call(&mut self, req: OkxRequest) -> Self::Future {
        if let OkxRequest::Http(req) = req {
            Service::call(self, req).map_ok(OkxResponse::Http).boxed()
        } else {
            ready(Err(ExchangeError::Other(anyhow::anyhow!(
                "Invalid request type"
            ))))
            .boxed()
        }
    }
}

impl Service<OkxRequest> for Ws {
    type Response = OkxResponse;

    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>> {
        Service::<WsRequest>::poll_ready(self, cx)
    }

    fn call(&mut self, req: OkxRequest) -> Self::Future {
        if let OkxRequest::Ws(req) = req {
            Service::call(self, req).map_ok(OkxResponse::Ws).boxed()
        } else {
            ready(Err(ExchangeError::Other(anyhow::anyhow!(
                "Invalid request type"
            ))))
            .boxed()
        }
    }
}

struct Inner {
    svcs: ReadyCache<&'static str, Either<Http, Ws>, OkxRequest>,
}

const HTTP_KEY: &str = "http";
const WS_KEY: &str = "ws";

impl Inner {
    fn new(ws: Ws, http: Http) -> Self {
        let mut svcs = ReadyCache::default();
        svcs.push(WS_KEY, Either::B(ws));
        svcs.push(HTTP_KEY, Either::A(http));
        Inner { svcs }
    }
}

impl Service<OkxRequest> for Inner {
    type Response = OkxResponse;
    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.svcs
            .poll_pending(cx)
            .map_err(|err| ExchangeError::Unavailable(err.into()))
    }

    fn call(&mut self, req: OkxRequest) -> Self::Future {
        let key = match &req {
            OkxRequest::Http(_) => HTTP_KEY,
            OkxRequest::Ws(_) => WS_KEY,
        };
        self.svcs
            .call_ready(&key, req)
            .map_err(ExchangeError::layer)
            .boxed()
    }
}

/// Okx API.
#[derive(Clone)]
pub struct Okx {
    inner: Buffer<Inner, OkxRequest>,
}

impl Okx {
    fn new(ws: Ws, http: Http, cap: usize) -> Self {
        Self {
            inner: Buffer::new(Inner::new(ws, http), cap),
        }
    }

    /// Create a default endpoint (the [`Okx`] builder).
    pub fn endpoint() -> Endpoint {
        Endpoint::default()
    }
}

impl Service<OkxRequest> for Okx {
    type Response = OkxResponse;

    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.inner.poll_ready(cx).map_err(ExchangeError::layer)
    }

    fn call(&mut self, req: OkxRequest) -> Self::Future {
        self.inner.call(req).map_err(ExchangeError::layer).boxed()
    }
}