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: place_orders failed (maybe_placed: {maybe_placed}, {} client_order_ids): {source}",
.client_order_ids.len()
)]
BatchPlace {
client_order_ids: Vec<String>,
maybe_placed: bool,
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),
#[error(
"cexy: [{PAGING_STALLED}] {operation}: still no rows after {retries} retries of the same cursor; page again later"
)]
PagingStalled {
operation: &'static str,
cursor: String,
retries: u32,
#[source]
source: Option<Box<dyn std::error::Error + Send + Sync>>,
},
#[error(
"cexy: [{PAGING_CURSOR_REPEATED}] {operation}: the server repeated a cursor after a page of rows; paging stopped"
)]
PagingCursorRepeated {
operation: &'static str,
cursor: String,
},
}
pub const PAGING_STALLED: &str = "PAGING_STALLED";
pub const PAGING_CURSOR_REPEATED: &str = "PAGING_CURSOR_REPEATED";
impl Error {
pub fn api(&self) -> Option<&ApiError> {
match self {
Error::Api(e) => Some(e),
Error::BatchPlace { source, .. } => source.api(),
_ => None,
}
}
pub fn is(&self, category: ErrorCategory) -> bool {
self.api().is_some_and(|e| e.is(category))
}
pub fn code(&self) -> Option<&str> {
match self {
Error::Api(e) => Some(e.code.as_str()),
Error::BatchPlace { source, .. } => source.code(),
Error::WebSocket(e) => Some(&e.code),
Error::PagingStalled { .. } => Some(PAGING_STALLED),
Error::PagingCursorRepeated { .. } => Some(PAGING_CURSOR_REPEATED),
_ => None,
}
}
pub fn is_retryable(&self) -> bool {
match self {
Error::Connection(_) | Error::PagingStalled { .. } => true,
Error::Api(e) => {
e.retryable_ignoring_wait() && 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>,
header_wait: Option<Duration>,
category: Option<ErrorCategory>,
}
impl ApiError {
pub(crate) fn retryable_ignoring_wait(&self) -> bool {
let concurrent = self.code == ErrorCode::ConcurrentModification;
if (400..500).contains(&self.status)
&& self.status != 429
&& !(self.status == 409 && concurrent)
{
return false;
}
self.retryable || concurrent
}
pub(crate) fn is_futures_busy(&self) -> bool {
self.status == 503
&& self.details.get("reason").and_then(Value::as_str)
== Some("futures_data_unavailable")
}
pub(crate) fn busy_hint(&self) -> Option<Duration> {
self.header_wait
.or_else(|| details_wait(&self.details).and_then(server_secs))
}
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 std::error::Error for ApiError {}
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, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ErrorBody {
pub code: ErrorCode,
pub message: String,
#[serde(default)]
pub retryable: bool,
#[serde(default)]
pub details: BTreeMap<String, Value>,
#[serde(default)]
pub fields: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub request_id: Option<String>,
}
impl ErrorBody {
pub fn detail_str(&self, name: &str) -> Option<&str> {
self.details
.get(name)
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
}
}
#[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)]
#[non_exhaustive]
pub struct WsError {
pub code: String,
pub message: String,
pub from_server: bool,
pub channel: Option<String>,
pub details: BTreeMap<String, Value>,
pub retry_after: Option<Duration>,
}
impl WsError {
pub(crate) fn local(code: &str, message: impl Into<String>) -> WsError {
WsError {
code: code.to_string(),
message: message.into(),
from_server: false,
channel: None,
details: BTreeMap::new(),
retry_after: None,
}
}
pub(crate) fn from_frame(
code: &str,
message: &str,
frame: &serde_json::Map<String, Value>,
) -> WsError {
let details: BTreeMap<String, Value> = frame
.get("details")
.and_then(Value::as_object)
.map(|o| o.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
.unwrap_or_default();
WsError {
code: code.to_string(),
message: message.to_string(),
from_server: true,
channel: frame
.get("channel")
.and_then(Value::as_str)
.map(str::to_string),
retry_after: details
.get("retry_after_seconds")
.and_then(Value::as_f64)
.and_then(server_secs),
details,
}
}
}
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, 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,
header_wait: 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.header_wait = header_wait(headers);
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,
header_wait: 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 = header_wait(headers);
if let Some(d) = details_wait(details).and_then(server_secs)
&& best.is_none_or(|b| d > b)
{
best = Some(d);
}
best
}
fn header_wait(headers: &HeaderMap) -> Option<Duration> {
let v = header(headers, "retry-after")?;
if let Ok(secs) = v.parse::<f64>() {
return server_secs(secs);
}
let at = chrono::DateTime::parse_from_rfc2822(&v).ok()?;
let d = (at.with_timezone(&chrono::Utc) - chrono::Utc::now())
.to_std()
.ok()?;
(!d.is_zero()).then_some(d)
}
fn details_wait(details: &BTreeMap<String, Value>) -> Option<f64> {
match details.get("retry_after_seconds") {
Some(Value::Number(n)) => n.as_f64(),
Some(Value::String(s)) => s.parse::<f64>().ok(),
_ => None,
}
}