use std::collections::BTreeMap;
use std::fmt;
use std::time::Duration;
use reqwest::header::HeaderMap;
use serde_json::Value;
use crate::cancel_all::CancelAllSummary;
use crate::models_gen::ErrorCode;
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("{0}")]
Api(Box<ApiError>),
#[error("cexy: {0}")]
Config(String),
#[error("cexy: {message}")]
InvalidAmount {
field: String,
message: String,
},
#[error("{0}")]
Connection(ConnectionError),
#[error(
"cexy: order state unknown for client_order_id {client_order_id}; check order_by_client_id before retrying: {source}"
)]
OrderStateUnknown {
client_order_id: String,
source: Box<Error>,
},
#[error("cexy: cancel-all interrupted after {} round(s): {source}", .summary.rounds)]
CancelAllInterrupted {
source: Box<Error>,
summary: Box<CancelAllSummary>,
},
#[error("{0}")]
WebSocket(WsError),
#[error("cexy: {0}")]
Decode(String),
}
impl Error {
pub fn api(&self) -> Option<&ApiError> {
match self {
Error::Api(e) => Some(e),
_ => None,
}
}
pub fn is(&self, category: ErrorCategory) -> bool {
self.api().is_some_and(|e| e.is(category))
}
pub fn is_retryable(&self) -> bool {
match self {
Error::Connection(_) => true,
Error::Api(e) => {
(e.retryable || e.code == ErrorCode::ConcurrentModification)
&& e.retry_after.is_none_or(|d| d <= MAX_SERVER_WAIT)
}
_ => false,
}
}
pub(crate) fn server_wait_too_long(&self) -> bool {
self.api()
.and_then(|e| e.retry_after)
.is_some_and(|d| d > MAX_SERVER_WAIT)
}
pub(crate) fn is_ambiguous(&self) -> bool {
match self {
Error::Connection(_) => true,
Error::Api(e) => e.status >= 500,
_ => false,
}
}
pub(crate) fn config(msg: impl Into<String>) -> Error {
Error::Config(msg.into())
}
}
impl From<ApiError> for Error {
fn from(e: ApiError) -> Error {
Error::Api(Box::new(e))
}
}
impl From<WsError> for Error {
fn from(e: WsError) -> Error {
Error::WebSocket(e)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorCategory {
Validation,
Authentication,
Forbidden,
JurisdictionBlocked,
NotFound,
Conflict,
Unprocessable,
RateLimited,
Server,
UnexpectedRedirect,
}
#[derive(Clone)]
pub struct ApiError {
pub status: u16,
pub code: ErrorCode,
pub message: String,
pub details: BTreeMap<String, Value>,
pub fields: BTreeMap<String, String>,
pub request_id: Option<String>,
pub retryable: bool,
pub retry_after: Option<Duration>,
category: Option<ErrorCategory>,
}
impl ApiError {
pub fn category(&self) -> Option<ErrorCategory> {
self.category
}
pub fn is(&self, category: ErrorCategory) -> bool {
match self.category {
Some(c) if c == category => true,
Some(ErrorCategory::JurisdictionBlocked) => category == ErrorCategory::Forbidden,
_ => false,
}
}
}
impl fmt::Display for ApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "cexy: [{} {}] {}", self.status, self.code, self.message)?;
if let Some(rid) = &self.request_id {
write!(f, " (request_id {rid})")?;
}
Ok(())
}
}
impl fmt::Debug for ApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ApiError")
.field("status", &self.status)
.field("code", &self.code)
.field("message", &self.message)
.field("details", &self.details)
.field("fields", &self.fields)
.field("request_id", &self.request_id)
.field("retryable", &self.retryable)
.field("retry_after", &self.retry_after)
.finish()
}
}
#[derive(Debug, Clone)]
pub struct ConnectionError {
pub method: String,
pub path: String,
pub timeout: bool,
pub message: String,
}
impl fmt::Display for ConnectionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.timeout {
write!(f, "cexy: {} {} timed out", self.method, self.path)
} else {
write!(
f,
"cexy: {} {} failed: {}",
self.method, self.path, self.message
)
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WsError {
pub code: String,
pub message: String,
pub from_server: bool,
}
impl WsError {
pub(crate) fn local(code: &str, message: impl Into<String>) -> WsError {
WsError {
code: code.to_string(),
message: message.into(),
from_server: false,
}
}
}
impl fmt::Display for WsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "cexy websocket: [{}] {}", self.code, self.message)
}
}
impl std::error::Error for WsError {}
fn default_retryable(status: u16) -> bool {
matches!(status, 408 | 429 | 500 | 502 | 503 | 504)
}
pub(crate) fn error_from_response(
status: u16,
body: &[u8],
headers: &HeaderMap,
redact: &dyn Fn(&str) -> String,
) -> ApiError {
let header_rid = header(headers, "x-request-id");
let mut e = ApiError {
status,
code: ErrorCode::Other(format!("HTTP_{status}")),
message: format!("HTTP {status}"),
details: BTreeMap::new(),
fields: BTreeMap::new(),
request_id: header_rid,
retryable: default_retryable(status),
retry_after: None,
category: None,
};
let env: Option<Value> = serde_json::from_slice(body).ok();
let err_obj = env
.as_ref()
.and_then(|v| v.get("error"))
.and_then(Value::as_object);
let code = err_obj.and_then(|o| o.get("code")).and_then(Value::as_str);
let has_envelope = code.is_some();
if let (Some(o), Some(code)) = (err_obj, code) {
e.code = ErrorCode::from(code);
e.message = o
.get("message")
.and_then(Value::as_str)
.unwrap_or(code)
.to_string();
if let Some(d) = o.get("details").and_then(Value::as_object) {
for (k, v) in d {
e.details.insert(redact(k), redact_json(v, redact));
}
}
if let Some(fl) = o.get("fields").and_then(Value::as_object) {
for (k, v) in fl {
if let Some(s) = v.as_str() {
e.fields.insert(redact(k), redact(s));
}
}
}
if let Some(rid) = o
.get("request_id")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
{
e.request_id = Some(redact(rid));
}
if let Some(r) = o.get("retryable").and_then(Value::as_bool) {
e.retryable = r;
}
}
e.message = redact(&e.message);
e.retry_after = retry_after(headers, &e.details);
e.category = if status == 429 || e.code == ErrorCode::RateLimited {
Some(ErrorCategory::RateLimited)
} else if e.code == ErrorCode::JurisdictionBlocked {
Some(ErrorCategory::JurisdictionBlocked)
} else if has_envelope && !e.code.is_known() {
None
} else if status >= 500 {
Some(ErrorCategory::Server)
} else {
match status {
400 => Some(ErrorCategory::Validation),
401 => Some(ErrorCategory::Authentication),
403 => Some(ErrorCategory::Forbidden),
404 => Some(ErrorCategory::NotFound),
409 => Some(ErrorCategory::Conflict),
422 => Some(ErrorCategory::Unprocessable),
451 => Some(ErrorCategory::JurisdictionBlocked),
_ => None,
}
};
e
}
pub(crate) fn redirect_error(
status: u16,
headers: &HeaderMap,
redact: &dyn Fn(&str) -> String,
) -> ApiError {
let loc = header(headers, "location").map(|l| redact(&l));
let mut message =
format!("unexpected redirect (HTTP {status}); the SDK does not follow redirects");
let mut details = BTreeMap::new();
if let Some(l) = &loc {
message.push_str(&format!(" (Location: {l})"));
details.insert("location".to_string(), Value::String(l.clone()));
}
ApiError {
status,
code: ErrorCode::UnexpectedRedirect,
message,
details,
fields: BTreeMap::new(),
request_id: header(headers, "x-request-id"),
retryable: false,
retry_after: None,
category: Some(ErrorCategory::UnexpectedRedirect),
}
}
fn redact_json(v: &Value, redact: &dyn Fn(&str) -> String) -> Value {
match v {
Value::String(s) => Value::String(redact(s)),
Value::Array(a) => Value::Array(a.iter().map(|x| redact_json(x, redact)).collect()),
Value::Object(o) => Value::Object(
o.iter()
.map(|(k, x)| (redact(k), redact_json(x, redact)))
.collect(),
),
other => other.clone(),
}
}
pub(crate) fn header(headers: &HeaderMap, name: &str) -> Option<String> {
headers
.get(name)
.and_then(|v| v.to_str().ok())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
pub const MAX_SERVER_WAIT: Duration = Duration::from_secs(120);
pub(crate) fn server_secs(secs: f64) -> Option<Duration> {
if !secs.is_finite() || secs <= 0.0 {
return None;
}
Some(Duration::try_from_secs_f64(secs).unwrap_or(Duration::MAX))
}
fn retry_after(headers: &HeaderMap, details: &BTreeMap<String, Value>) -> Option<Duration> {
let mut best: Option<Duration> = None;
if let Some(v) = header(headers, "retry-after") {
if let Ok(secs) = v.parse::<f64>() {
best = server_secs(secs);
} else if let Ok(at) = chrono::DateTime::parse_from_rfc2822(&v) {
let d = at.with_timezone(&chrono::Utc) - chrono::Utc::now();
if let Ok(d) = d.to_std()
&& !d.is_zero()
{
best = Some(d);
}
}
}
let secs = match details.get("retry_after_seconds") {
Some(Value::Number(n)) => n.as_f64(),
Some(Value::String(s)) => s.parse::<f64>().ok(),
_ => None,
};
if let Some(d) = secs.and_then(server_secs)
&& best.is_none_or(|b| d > b)
{
best = Some(d);
}
best
}