nautilus_kalshi/http/error.rs
1// -------------------------------------------------------------------------------------------------
2// Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3// https://nautechsystems.io
4//
5// Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6// You may not use this file except in compliance with the License.
7// You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! HTTP error taxonomy for Kalshi REST responses.
17
18use 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/// Errors emitted by the Kalshi HTTP client.
28#[derive(Debug, Error)]
29pub enum KalshiHttpError {
30 /// Missing credentials, invalid signing input, or signature-generation failure.
31 #[error("authentication failed: {0}")]
32 Authentication(#[from] ConfigError),
33 /// Non-success response without potentially sensitive body content.
34 #[error("HTTP {0}")]
35 Status(u16),
36 /// Network-level failure.
37 #[error("network error: {0}")]
38 Network(String),
39 /// HTTP failure retaining a redacted raw body and selected response headers.
40 #[error("HTTP {status}")]
41 Http {
42 status: u16,
43 evidence: Box<ResponseEvidence>,
44 },
45 /// Structured venue failure with its original HTTP status and raw evidence.
46 #[error("Kalshi venue failure, HTTP {status}")]
47 Venue {
48 status: u16,
49 evidence: Box<ResponseEvidence>,
50 },
51 /// Failed to encode a request before transmission.
52 #[error("request encoding failed")]
53 Encoding,
54 /// Invalid request rejected before transmission.
55 #[error("invalid request: {0}")]
56 Validation(&'static str),
57 /// Transport failure whose request may have reached the venue.
58 #[error("HTTP transport failed")]
59 Transport(#[source] HttpClientError),
60 /// Request cancellation; dispatch may already have begun when `dispatched` is true.
61 #[error("request canceled, dispatch started: {dispatched}")]
62 Canceled { dispatched: bool },
63 /// Malformed success payload; the status and raw acknowledgement remain available.
64 #[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 /// A response whose item count or identities do not match the request.
72 ///
73 /// The operation may have succeeded; callers reconcile using the retained response evidence.
74 #[error("unexpected response, HTTP {status}: {reason}")]
75 Response {
76 status: u16,
77 reason: &'static str,
78 evidence: Box<ResponseEvidence>,
79 },
80 /// A pagination source failed or did not make progress.
81 #[error("pagination failed: {0}")]
82 Pagination(&'static str),
83 /// A later local failure retains possible transmission from an earlier attempt.
84 #[error("earlier attempt may have reached Kalshi: {0}")]
85 AfterSend(Box<Self>),
86 /// Discovery failed before the requested operation could be transmitted.
87 #[error("quota discovery failed: {0}")]
88 Discovery(Box<Self>),
89 /// Local token admission failed before transmission.
90 #[error("quota admission failed: {0}")]
91 Quota(&'static str),
92 /// Retry termination retaining monotonic possible-transmission evidence.
93 #[error("retry terminated: {reason}, dispatch started: {dispatched}")]
94 Retry {
95 reason: RetryError,
96 dispatched: bool,
97 },
98 /// Failed domain parsing after a successful wire decode.
99 #[error("parse error: {0}")]
100 Parse(String),
101}
102
103/// Response evidence with redacted diagnostics and explicit access to private data.
104pub struct ResponseEvidence {
105 /// Raw response body, potentially containing private data and redacted in debug output.
106 pub body: SecretString,
107 /// Structured venue error decoded from the response body, when available.
108 pub venue: Option<VenueError>,
109 /// Value of the `Retry-After` response header, when present.
110 pub retry_after: Option<String>,
111 /// Value of the `X-Request-ID` response header, when present.
112 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 /// Classifies transient failures independently of operation safety and command outcomes.
124 #[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 /// Returns whether local evidence proves no attempt reached the send operation.
168 ///
169 /// Execution callers can map true to `CommandFailure::NotSent`. False preserves an unknown
170 /// outcome, including duplicate identities, malformed successes, and transport failures.
171 #[must_use]
172 pub fn is_definitely_not_sent(&self) -> bool {
173 matches!(
174 self,
175 Self::Discovery(_)
176 | Self::Authentication(_)
177 | Self::Encoding
178 | Self::Validation(_)
179 | Self::Quota(_)
180 | Self::Canceled { dispatched: false }
181 | Self::Retry {
182 dispatched: false,
183 ..
184 }
185 )
186 }
187}