cexy 0.1.0-dev.16

Official Rust SDK for the CEXY.io exchange API (REST + WebSocket)
Documentation
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
//! HTTP transport: rate limiter, credentials, per-attempt timeout, error mapping and retries.

use std::sync::Arc;
use std::time::Duration;

use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use serde::de::DeserializeOwned;
use url::Url;

use crate::auth::{AuthRequest, Authenticator};
use crate::clock::Clock;
use crate::error::{
    ApiError, ConnectionError, Error, ErrorCategory, MAX_SERVER_WAIT, Result, error_from_response,
    redirect_error,
};
use crate::limiter::{PlacementHold, RateLimiter};
use crate::operations_gen::OperationId;
use crate::signing::{encode_bytes, encode_query};

const BACKOFF_BASE: Duration = Duration::from_millis(500);
const BACKOFF_MAX: Duration = Duration::from_secs(10);
const MAX_RESPONSE_BODY: usize = 64 << 20;
/// `details.limit` on a 429 that refused order actions (a market maker's per-second budget). It
/// holds only placements, never reads or cancels.
pub(crate) const ORDER_ACTIONS_LIMIT: &str = "order_actions";

/// Passed to `ClientOptions::on_retry` before the SDK waits and retries. It never holds
/// credentials.
#[derive(Debug)]
pub struct RetryInfo<'a> {
    /// The operation.
    pub operation: OperationId,
    /// HTTP method.
    pub method: &'static str,
    /// Path template.
    pub path: &'static str,
    /// 1 for the first retry.
    pub attempt: u32,
    /// How long the SDK waits before retrying.
    pub delay: Duration,
    /// The failure being retried.
    pub error: &'a Error,
    /// The Idempotency-Key reused on every attempt, if one is sent.
    pub idempotency_key: Option<&'a str>,
}

pub(crate) type RetryHook = Arc<dyn Fn(&RetryInfo<'_>) + Send + Sync>;
pub(crate) type Random = Arc<dyn Fn() -> f64 + Send + Sync>;

pub(crate) struct Call {
    pub(crate) op: OperationId,
    pub(crate) path: Vec<(&'static str, String)>,
    pub(crate) query: Vec<(&'static str, String)>,
    pub(crate) body: Option<Vec<u8>>,
    pub(crate) text: bool,
    pub(crate) idempotency_key: Option<String>,
    /// The endpoint does not honour Idempotency-Key, so none is sent.
    pub(crate) no_idempotency_key: bool,
    /// Request tokens this call takes from the client limiter on each attempt (a batch of N
    /// takes N).
    pub(crate) cost: u32,
    /// Placements in this call (0 for anything else): they wait out an `order_actions` hold and
    /// the optional order-actions budget.
    pub(crate) order_actions: u32,
    /// A 503 `futures_data_unavailable` is not retried by the request retries (the futures
    /// history helpers handle it as a busy answer with their own budget).
    pub(crate) busy_not_retried: bool,
}

/// How a failed attempt ended, as the batch calls need to know it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Attempt {
    /// The server may have acted: a connection error or timeout, any HTTP 5xx except 501 and
    /// 503 (Cloudflare's 520 and 524 included), or a 2xx that is not JSON.
    Ambiguous,
    /// It did not: a 429, a 501, a 503 or any other 4xx.
    Refused,
}

impl Attempt {
    pub(crate) fn of(e: &Error) -> Attempt {
        match e {
            Error::Connection(_) | Error::Decode(_) => Attempt::Ambiguous,
            Error::Api(a) if a.status >= 500 && !matches!(a.status, 501 | 503) => {
                Attempt::Ambiguous
            }
            _ => Attempt::Refused,
        }
    }
}

impl Call {
    pub(crate) fn new(op: OperationId) -> Call {
        Call {
            op,
            path: vec![],
            query: vec![],
            body: None,
            text: false,
            idempotency_key: None,
            no_idempotency_key: false,
            cost: 1,
            order_actions: 0,
            busy_not_retried: false,
        }
    }
    pub(crate) fn busy_not_retried(mut self) -> Call {
        self.busy_not_retried = true;
        self
    }
    pub(crate) fn cost(mut self, tokens: u32) -> Call {
        self.cost = tokens;
        self
    }
    pub(crate) fn order_actions(mut self, n: u32) -> Call {
        self.order_actions = n;
        self
    }
    pub(crate) fn path(mut self, name: &'static str, value: &str) -> Call {
        self.path.push((name, value.to_string()));
        self
    }
    pub(crate) fn query(mut self, q: Vec<(&'static str, String)>) -> Call {
        self.query = q;
        self
    }
    pub(crate) fn json<T: serde::Serialize>(mut self, body: &T) -> Result<Call> {
        let bytes = serde_json::to_vec(body).map_err(|e| {
            Error::config(format!(
                "{}: cannot encode the request body: {e}",
                self.op.as_str()
            ))
        })?;
        self.body = Some(bytes);
        Ok(self)
    }
}

/// Resolved per-call options.
#[derive(Clone)]
pub(crate) struct Resolved {
    pub(crate) timeout: Duration,
    pub(crate) max_retries: u32,
    pub(crate) idempotency_key: Option<String>,
}

pub(crate) struct Raw {
    pub(crate) body: Vec<u8>,
}

pub(crate) struct Transport {
    pub(crate) base_url: String,
    pub(crate) origin: String,
    pub(crate) http: reqwest::Client,
    pub(crate) auth: Option<Arc<dyn Authenticator>>,
    pub(crate) limiter: Option<RateLimiter>,
    /// Set with the limiter: an `order_actions` 429 holds placements here instead.
    pub(crate) placement_hold: Option<PlacementHold>,
    /// The optional order-actions budget (`ClientOptions::order_actions_per_second`).
    pub(crate) order_limiter: Option<RateLimiter>,
    pub(crate) user_agent: String,
    pub(crate) timeout: Duration,
    pub(crate) max_retries: u32,
    pub(crate) clock: Arc<dyn Clock>,
    pub(crate) random: Random,
    pub(crate) on_retry: Option<RetryHook>,
    pub(crate) allow_insecure: bool,
}

impl Transport {
    /// Sends `c` with the standard retry policy: retryable errors and connection failures are
    /// retried. A mutation carries an Idempotency-Key reused on every attempt; the server honours
    /// it on pool join and exit. A mutation is retried only when it is repeat-safe (see
    /// [`repeat_safe`]); any other is sent once. `place_order` and `cancel_order` use `attempt`
    /// with their own policies.
    pub(crate) async fn request(&self, c: Call, o: &Resolved) -> Result<Raw> {
        self.request_noting(c, o, &mut Vec::new()).await
    }

    /// [`Transport::request`], appending to `attempts` how each failed attempt ended. The batch
    /// calls read it to tell a lost answer from a definite refusal.
    pub(crate) async fn request_noting(
        &self,
        mut c: Call,
        o: &Resolved,
        attempts: &mut Vec<Attempt>,
    ) -> Result<Raw> {
        let info = c.op.info();
        if info.method != "GET" && c.idempotency_key.is_none() && !c.no_idempotency_key {
            c.idempotency_key = Some(o.idempotency_key.clone().unwrap_or_else(new_id));
        }
        let max_retries = if repeat_safe(&c) { o.max_retries } else { 0 };
        let mut attempt = 0;
        loop {
            match self.attempt(&c, o).await {
                Ok(raw) => return Ok(raw),
                Err(e) => {
                    attempts.push(Attempt::of(&e));
                    if attempt >= max_retries
                        || !e.is_retryable()
                        || (c.busy_not_retried && e.api().is_some_and(ApiError::is_futures_busy))
                    {
                        return Err(e);
                    }
                    self.backoff(c.op, attempt, &e, c.idempotency_key.as_deref())
                        .await;
                    attempt += 1;
                }
            }
        }
    }

    /// Waits before retry number `attempt + 1`, honouring server hints.
    pub(crate) async fn backoff(
        &self,
        op: OperationId,
        attempt: u32,
        cause: &Error,
        idem: Option<&str>,
    ) {
        let d = self.retry_delay(attempt, cause);
        self.wait(op, attempt, cause, idem, d).await;
    }

    /// Waits exactly `d` before retry number `attempt + 1`, telling the retry hook.
    pub(crate) async fn wait(
        &self,
        op: OperationId,
        attempt: u32,
        cause: &Error,
        idem: Option<&str>,
        d: Duration,
    ) {
        if let Some(hook) = &self.on_retry {
            let info = op.info();
            hook(&RetryInfo {
                operation: op,
                method: info.method,
                path: info.path,
                attempt: attempt + 1,
                delay: d,
                error: cause,
                idempotency_key: idem,
            });
        }
        self.clock.sleep(d).await;
    }

    /// The server's hint plus up to 250 ms of jitter, or full-jitter exponential backoff
    /// (500 ms doubling, capped at 10 s). A hint is never taken beyond [`MAX_SERVER_WAIT`]
    /// (callers stop before that: such errors are not retryable).
    pub(crate) fn retry_delay(&self, attempt: u32, cause: &Error) -> Duration {
        if let Some(ra) = cause.api().and_then(|e| e.retry_after) {
            let jitter = Duration::from_millis(((self.random)() * 250.0) as u64);
            return ra.min(MAX_SERVER_WAIT).saturating_add(jitter);
        }
        let capped = BACKOFF_BASE
            .saturating_mul(2u32.saturating_pow(attempt.min(20)))
            .min(BACKOFF_MAX);
        Duration::from_nanos(((self.random)() * capped.as_nanos() as f64).ceil() as u64)
    }

    /// One try (plus, with request signing, one re-signed resend after `SIGNATURE_EXPIRED` once
    /// the clock is corrected; it is outside the retry budget). `KEY_NOT_SIGNABLE` names the fix;
    /// there is no fallback to another scheme.
    pub(crate) async fn attempt(&self, c: &Call, o: &Resolved) -> Result<Raw> {
        let mut e = match self.attempt_once(c, o).await {
            Err(Error::Api(e)) => e,
            other => return other,
        };
        if e.code.as_str() == "SIGNATURE_REQUIRED" {
            e.message = "this API key must sign its requests: use AuthScheme::Hmac (the default) \
                         instead of AuthScheme::Headers"
                .into();
            e.retryable = false;
            return Err(Error::Api(e));
        }
        if e.code.as_str() == "KEY_NOT_SIGNABLE" {
            e.message =
                "create a new API key; keys issued before request signing can't sign".into();
            e.retryable = false;
            return Err(Error::Api(e));
        }
        if e.code.as_str() != "SIGNATURE_EXPIRED" {
            return Err(Error::Api(e));
        }
        let server_ms = e
            .details
            .get("server_time_ms")
            .and_then(|v| v.as_i64().or_else(|| v.as_f64().map(|f| f as i64)));
        let adjusted = match (&self.auth, server_ms) {
            (Some(auth), Some(ms)) => auth.adjust_clock(ms),
            _ => None,
        };
        match adjusted {
            // Signed again with the corrected clock, once.
            Some(true) => self.attempt_once(c, o).await,
            Some(false) => {
                e.message = "the local clock is more than 1 hour away from the server's: fix the system clock".into();
                e.retryable = false;
                Err(Error::Api(e))
            }
            None => Err(Error::Api(e)), // not a signing scheme
        }
    }

    /// One try: rate limiter, credentials, timeout, error mapping. No retries.
    async fn attempt_once(&self, c: &Call, o: &Resolved) -> Result<Raw> {
        let info = c.op.info();
        let url = self.build_url(c)?;
        if info.auth == "api_key" && self.auth.is_none() {
            return Err(Error::config(format!(
                "{} {} needs an API key: create the client with api_key and api_secret",
                info.method, info.path
            )));
        }
        if let Some(l) = &self.limiter {
            l.acquire(c.cost).await;
        }
        if c.order_actions > 0 {
            if let Some(h) = &self.placement_hold {
                h.wait().await;
            }
            if let Some(l) = &self.order_limiter {
                l.acquire(c.order_actions).await;
            }
        }

        let mut headers = HeaderMap::new();
        let accept = if c.text {
            "text/csv, application/json"
        } else {
            "application/json"
        };
        headers.insert("accept", HeaderValue::from_static(accept));
        headers.insert(
            "user-agent",
            HeaderValue::from_str(&self.user_agent)
                .map_err(|_| Error::config("invalid User-Agent"))?,
        );
        if c.body.is_some() {
            headers.insert("content-type", HeaderValue::from_static("application/json"));
        }
        if info.method != "GET"
            && let Some(k) = &c.idempotency_key
        {
            headers.insert(
                "idempotency-key",
                HeaderValue::from_str(k).map_err(|_| Error::config("invalid Idempotency-Key"))?,
            );
        }
        if info.auth == "api_key" {
            // Defence in depth: requests are always built from base_url, so this only fails on a bug.
            if origin(&url) != self.origin {
                return Err(Error::config(format!(
                    "{} {}: refusing to send credentials to {}",
                    info.method,
                    info.path,
                    origin(&url)
                )));
            }
            let auth = self.auth.as_ref().expect("checked above");
            let mut req = AuthRequest {
                method: info.method,
                url: &url,
                body: c.body.as_deref(),
                headers: vec![],
            };
            auth.authenticate(&mut req)?;
            for (k, v) in req.headers {
                let name = HeaderName::from_bytes(k.as_bytes())
                    .map_err(|_| Error::config("invalid header name"))?;
                let mut value = HeaderValue::from_str(&v)
                    .map_err(|_| Error::config("invalid credential header value"))?;
                value.set_sensitive(true);
                headers.insert(name, value);
            }
        }

        let method = reqwest::Method::from_bytes(info.method.as_bytes()).expect("valid method");
        let mut rb = self
            .http
            .request(method, url)
            .headers(headers)
            .timeout(o.timeout);
        if let Some(b) = &c.body {
            rb = rb.body(b.clone());
        }
        let conn_err = |e: reqwest::Error| {
            Error::Connection(ConnectionError {
                method: info.method.to_string(),
                path: info.path.to_string(),
                timeout: e.is_timeout(),
                message: self.redact(&e.to_string()),
            })
        };
        let mut resp = rb.send().await.map_err(conn_err)?;
        let status = resp.status().as_u16();
        let resp_headers = resp.headers().clone();
        let mut body = Vec::new();
        while let Some(chunk) = resp.chunk().await.map_err(conn_err)? {
            if body.len() + chunk.len() > MAX_RESPONSE_BODY {
                return Err(Error::Decode(format!(
                    "{} {}: response larger than 64 MiB",
                    info.method, info.path
                )));
            }
            body.extend_from_slice(&chunk);
        }

        if let Some(l) = &self.limiter {
            l.update(&resp_headers);
        }
        let redact = |s: &str| self.redact(s);
        if (300..=399).contains(&status) {
            // Redirects are never followed (the client is built with Policy::none()): not
            // retryable, not ambiguous.
            return Err(redirect_error(status, &resp_headers, &redact).into());
        }
        if !(200..=299).contains(&status) {
            let e = error_from_response(status, &body, &resp_headers, &redact);
            if e.is(ErrorCategory::RateLimited)
                && let (Some(ra), Some(l)) = (e.retry_after, &self.limiter)
            {
                let order_actions = e.details.get("limit").and_then(serde_json::Value::as_str)
                    == Some(ORDER_ACTIONS_LIMIT);
                match &self.placement_hold {
                    Some(h) if order_actions => h.hold_for(ra),
                    _ => l.block_for(ra),
                }
            }
            return Err(e.into());
        }
        if !c.text
            && !body.is_empty()
            && serde_json::from_slice::<serde::de::IgnoredAny>(&body).is_err()
        {
            let ct = resp_headers
                .get("content-type")
                .and_then(|v| v.to_str().ok())
                .unwrap_or("unknown content");
            return Err(Error::Decode(format!(
                "{} {}: expected JSON, got {ct:?}",
                info.method, info.path
            )));
        }
        Ok(Raw { body })
    }

    pub(crate) fn build_url(&self, c: &Call) -> Result<Url> {
        let info = c.op.info();
        let mut path = String::new();
        let mut rest = info.path;
        while let Some(start) = rest.find('{') {
            let end = rest[start..]
                .find('}')
                .map(|e| start + e)
                .expect("well-formed path template");
            path.push_str(&rest[..start]);
            let name = &rest[start + 1..end];
            let value = c
                .path
                .iter()
                .find(|(n, _)| *n == name)
                .map(|(_, v)| v.as_str())
                .unwrap_or("");
            if value.is_empty() || value.contains(['\r', '\n']) {
                return Err(Error::config(format!(
                    "{} {}: {name} is required",
                    info.method, info.path
                )));
            }
            // "." and ".." would be dot segments: the url crate resolves them (even as %2E),
            // so the request would silently go to a different route.
            if value == "." || value == ".." {
                return Err(Error::config(format!(
                    "{} {}: {name} must not be \".\" or \"..\"",
                    info.method, info.path
                )));
            }
            path.push_str(&encode_segment(value));
            rest = &rest[end + 1..];
        }
        path.push_str(rest);
        let mut url = Url::parse(&format!("{}{}", self.base_url, path)).map_err(|e| {
            Error::config(format!("{} {}: invalid URL: {e}", info.method, info.path))
        })?;
        // RFC 3986 (%20 for a space), not form encoding (+ for a space): the query that is
        // signed is exactly the query that is sent.
        if !c.query.is_empty() {
            url.set_query(Some(&encode_query(&c.query)));
        }
        Ok(url)
    }

    pub(crate) fn redact(&self, s: &str) -> String {
        match &self.auth {
            Some(a) => a.redact(s),
            None => s.to_string(),
        }
    }
}

/// Whether `request` may retry `c`: reads, and the mutations that are safe to repeat: pool join
/// and exit with their Idempotency-Key (the server honours it there), cancel-all, cancel-all-after,
/// cancel by client order id and cancel-batch (naturally repeatable), and place-batch (every
/// order carries a `client_order_id`, so the server refuses a repeat as `ALREADY_EXISTS`). The
/// server ignores Idempotency-Key elsewhere, so no other mutation is retried.
fn repeat_safe(c: &Call) -> bool {
    c.op.info().method == "GET"
        || matches!(
            c.op,
            OperationId::CancelAll
                | OperationId::CancelAllAfter
                | OperationId::PlaceBatch
                | OperationId::CancelBatch
                | OperationId::CancelOrderByClientId
        )
        || (matches!(c.op, OperationId::JoinPool | OperationId::ExitPool)
            && c.idempotency_key.is_some())
}

/// Percent-encodes one path segment per RFC 3986 with uppercase hex (`/` becomes `%2F`): what
/// is sent is what is signed.
fn encode_segment(v: &str) -> String {
    encode_bytes(v.as_bytes())
}

/// The scheme and host (and port) of `u`, lower case: `"https://api.cexy.io"`.
pub(crate) fn origin(u: &Url) -> String {
    let mut s = format!(
        "{}://{}",
        u.scheme().to_lowercase(),
        u.host_str().unwrap_or("").to_lowercase()
    );
    if let Some(p) = u.port() {
        s.push_str(&format!(":{p}"));
    }
    s
}

#[derive(serde::Deserialize)]
struct Envelope<T> {
    data: T,
}

/// Decodes the `{"data": T}` envelope.
pub(crate) fn decode_data<T: DeserializeOwned>(op: OperationId, raw: &Raw) -> Result<T> {
    serde_json::from_slice::<Envelope<T>>(&raw.body)
        .map(|e| e.data)
        .map_err(|e| Error::Decode(format!("{}: cannot decode the response: {e}", op.as_str())))
}

/// Decodes a bare JSON body (a page).
pub(crate) fn decode<T: DeserializeOwned>(op: OperationId, raw: &Raw) -> Result<T> {
    serde_json::from_slice::<T>(&raw.body)
        .map_err(|e| Error::Decode(format!("{}: cannot decode the response: {e}", op.as_str())))
}

/// A random UUID v4.
pub(crate) fn new_id() -> String {
    uuid::Uuid::new_v4().to_string()
}