1use std::fmt::Debug;
19
20use nautilus_common::config::ConfigError;
21use nautilus_core::string::secret::SecretString;
22use nautilus_network::{http::HttpClientError, retry::RetryError};
23use thiserror::Error;
24
25use super::models::{Field, VenueError};
26
27#[derive(Debug, Error)]
29pub enum KalshiHttpError {
30 #[error("authentication failed: {0}")]
32 Authentication(#[from] ConfigError),
33 #[error("HTTP {0}")]
35 Status(u16),
36 #[error("network error: {0}")]
38 Network(String),
39 #[error("HTTP {status}")]
41 Http {
42 status: u16,
43 evidence: Box<ResponseEvidence>,
44 },
45 #[error("Kalshi venue failure, HTTP {status}")]
47 Venue {
48 status: u16,
49 evidence: Box<ResponseEvidence>,
50 },
51 #[error("request encoding failed")]
53 Encoding,
54 #[error("invalid request: {0}")]
56 Validation(&'static str),
57 #[error("HTTP transport failed")]
59 Transport(#[source] HttpClientError),
60 #[error("request canceled, dispatch started: {dispatched}")]
62 Canceled { dispatched: bool },
63 #[error("response decoding failed, HTTP {status}, line {line}, column {column}")]
65 Decode {
66 status: u16,
67 line: usize,
68 column: usize,
69 evidence: Box<ResponseEvidence>,
70 },
71 #[error("unexpected response, HTTP {status}: {reason}")]
75 Response {
76 status: u16,
77 reason: &'static str,
78 evidence: Box<ResponseEvidence>,
79 },
80 #[error("pagination failed: {0}")]
82 Pagination(&'static str),
83 #[error("earlier attempt may have reached Kalshi: {0}")]
85 AfterSend(Box<Self>),
86 #[error("quota discovery failed: {0}")]
88 Discovery(Box<Self>),
89 #[error("quota admission failed: {0}")]
91 Quota(&'static str),
92 #[error("retry terminated: {reason}, dispatch started: {dispatched}")]
94 Retry {
95 reason: RetryError,
96 dispatched: bool,
97 },
98 #[error("parse error: {0}")]
100 Parse(String),
101}
102
103pub struct ResponseEvidence {
105 pub body: SecretString,
107 pub venue: Option<VenueError>,
109 pub retry_after: Option<String>,
111 pub request_id: Option<String>,
113}
114
115impl Debug for ResponseEvidence {
116 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117 f.debug_struct(stringify!(ResponseEvidence))
118 .finish_non_exhaustive()
119 }
120}
121
122impl KalshiHttpError {
123 #[must_use]
125 pub fn is_retryable(&self) -> bool {
126 match self {
127 Self::AfterSend(source) => source.is_retryable(),
128 Self::Status(500 | 502..=504) => true,
129 Self::Transport(
130 HttpClientError::TransportError(_) | HttpClientError::TimeoutError(_),
131 ) => true,
132 Self::Http {
133 status: 500 | 502..=504,
134 ..
135 }
136 | Self::Venue {
137 status: 500 | 502..=504,
138 ..
139 } => true,
140 Self::Http {
141 status: 429,
142 evidence,
143 }
144 | Self::Venue {
145 status: 429,
146 evidence,
147 } => {
148 evidence.venue.as_ref().is_some_and(
149 |e| matches!(&e.code, Field::Value(code) if code == "too_many_requests"),
150 ) || serde_json::from_str::<serde_json::Value>(evidence.body.expose_secret())
151 .ok()
152 .and_then(|body| {
153 body.get("error")
154 .and_then(serde_json::Value::as_str)
155 .map(|message| message == "too many requests")
156 })
157 .unwrap_or(false)
158 }
159 Self::Retry {
160 reason: RetryError::OperationTimeout { .. },
161 ..
162 } => true,
163 _ => false,
164 }
165 }
166
167 pub(super) fn is_subaccount_restricted(&self) -> bool {
168 const MESSAGE: &str =
169 "this API key is restricted to a single sub-account and cannot access this endpoint";
170
171 let evidence = match self {
172 Self::Http {
173 status: 403,
174 evidence,
175 }
176 | Self::Venue {
177 status: 403,
178 evidence,
179 } => evidence,
180 _ => return false,
181 };
182
183 if evidence
184 .venue
185 .as_ref()
186 .is_some_and(|e| matches!(&e.message, Field::Value(message) if message == MESSAGE))
187 {
188 return true;
189 }
190
191 let body = evidence.body.expose_secret().trim();
192 body == MESSAGE
193 || serde_json::from_str::<serde_json::Value>(body).is_ok_and(|value| {
194 value.get("error").and_then(serde_json::Value::as_str) == Some(MESSAGE)
195 })
196 }
197
198 #[must_use]
203 pub fn is_definitely_not_sent(&self) -> bool {
204 matches!(
205 self,
206 Self::Discovery(_)
207 | Self::Authentication(_)
208 | Self::Encoding
209 | Self::Validation(_)
210 | Self::Quota(_)
211 | Self::Canceled { dispatched: false }
212 | Self::Retry {
213 dispatched: false,
214 ..
215 }
216 )
217 }
218}
219
220#[cfg(test)]
221mod tests {
222 use rstest::rstest;
223
224 use super::*;
225
226 #[rstest]
227 #[case(403, true)]
228 #[case(401, false)]
229 #[case(500, false)]
230 fn restricted_denial_requires_exact_status_and_message(
231 #[case] status: u16,
232 #[case] expected: bool,
233 ) {
234 let fixtures: serde_json::Value =
235 serde_json::from_str(include_str!("../../test_data/quota_responses.json")).unwrap();
236 let body = serde_json::to_string(&fixtures["subaccount_restricted"]).unwrap();
237
238 let error = KalshiHttpError::Http {
239 status,
240 evidence: Box::new(ResponseEvidence {
241 body: body.into(),
242 venue: None,
243 retry_after: None,
244 request_id: None,
245 }),
246 };
247
248 assert_eq!(error.is_subaccount_restricted(), expected);
249
250 let unrelated = KalshiHttpError::Http {
251 status,
252 evidence: Box::new(ResponseEvidence {
253 body: serde_json::to_string(&fixtures["malformed_success"])
254 .unwrap()
255 .into(),
256 venue: None,
257 retry_after: None,
258 request_id: None,
259 }),
260 };
261
262 assert!(!unrelated.is_subaccount_restricted());
263 }
264}