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
//! Gateway error types and their mapping to the OpenAI error envelope.
use axum::Json;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
/// A request-time failure, rendered to the client as an OpenAI error envelope.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub(crate) enum GatewayError {
/// The bearer key was missing or did not match `server.key`.
#[error("unauthorized")]
Unauthorized,
/// The request named a model with no `[[model]]` entry.
#[non_exhaustive]
#[error("unknown model {0}")]
UnknownModel(String),
/// A tool endpoint was reached but the tool is not configured.
#[non_exhaustive]
#[error("tool not configured: {0}")]
ToolNotConfigured(&'static str),
/// The request body could not be understood.
#[non_exhaustive]
#[error("malformed request: {0}")]
MalformedRequest(String),
/// The upstream backend could not be reached (transport-layer failure).
#[non_exhaustive]
#[error("upstream transport error")]
UpstreamTransport(#[source] Box<dyn std::error::Error + Send + Sync>),
/// The upstream returned a success status but a body that could not be
/// decoded into the expected shape.
///
/// Distinct from [`GatewayError::UpstreamTransport`] so a decode failure
/// (a protocol problem) never masquerades as a transport death and triggers
/// a spurious local `llama-server` respawn (UP-004, UPSTREAM-003). The cause
/// is preserved via `source()`.
#[non_exhaustive]
#[error("upstream protocol error")]
UpstreamProtocol(#[source] Box<dyn std::error::Error + Send + Sync>),
/// The upstream backend returned a non-success status.
#[non_exhaustive]
#[error("upstream returned {status}")]
UpstreamStatus {
/// The status code the backend returned.
status: u16,
/// The (truncated) upstream body, for diagnostics.
body: String,
},
/// The endpoint's waiting queue is full.
#[error("queue full")]
QueueFull,
/// `POST /admin/switch-profile` named a profile that is not on disk.
#[non_exhaustive]
#[error("profile not found: {0}")]
ProfileNotFound(String),
/// Profile reload failed at a named stage; the underlying cause is
/// preserved via `source()` rather than flattened into a string.
#[non_exhaustive]
#[error("switch profile failed at {stage}")]
SwitchFailed {
/// The switch stage that failed (for diagnostics).
stage: &'static str,
/// The underlying cause.
#[source]
source: Box<dyn std::error::Error + Send + Sync>,
},
/// Admin profile routes were reached without a configured profiles directory.
#[error("profiles directory not configured")]
ProfilesUnavailable,
}
impl From<crate::queue::AdmitError> for GatewayError {
fn from(value: crate::queue::AdmitError) -> Self {
match value {
// Both are "cannot admit now" from the client's perspective (503);
// the queue layer keeps them distinct for diagnostics and tests.
crate::queue::AdmitError::QueueFull | crate::queue::AdmitError::Unavailable => {
GatewayError::QueueFull
}
}
}
}
impl GatewayError {
/// Wrap a transport error, hiding its concrete type from the public API.
#[must_use]
pub(crate) fn upstream_transport(source: reqwest::Error) -> GatewayError {
GatewayError::UpstreamTransport(Box::new(source))
}
/// Wrap a body-decode failure as a protocol error (not a transport error),
/// preserving the cause via `source()`.
#[must_use]
pub(crate) fn upstream_protocol(
source: impl std::error::Error + Send + Sync + 'static,
) -> GatewayError {
GatewayError::UpstreamProtocol(Box::new(source))
}
/// Wrap a profile-switch failure at `stage`, preserving the cause.
#[must_use]
pub(crate) fn switch_failed(
stage: &'static str,
source: impl std::error::Error + Send + Sync + 'static,
) -> GatewayError {
GatewayError::SwitchFailed {
stage,
source: Box::new(source),
}
}
/// The `(status, type, code)` triple for the OpenAI error envelope.
fn classify(&self) -> (StatusCode, &'static str, &'static str) {
match self {
GatewayError::Unauthorized => (
StatusCode::UNAUTHORIZED,
"authentication_error",
"unauthorized",
),
GatewayError::UnknownModel(_) => (
StatusCode::NOT_FOUND,
"invalid_request_error",
"model_not_found",
),
GatewayError::ToolNotConfigured(_) => {
(StatusCode::NOT_FOUND, "invalid_request_error", "not_found")
}
GatewayError::MalformedRequest(_) => (
StatusCode::BAD_REQUEST,
"invalid_request_error",
"malformed_request",
),
GatewayError::UpstreamTransport(_) => (
StatusCode::BAD_GATEWAY,
"server_error",
"upstream_transport",
),
GatewayError::UpstreamProtocol(_) => {
(StatusCode::BAD_GATEWAY, "server_error", "upstream_protocol")
}
GatewayError::UpstreamStatus { status, .. } => {
let code = StatusCode::from_u16(*status).unwrap_or(StatusCode::BAD_GATEWAY);
if code.is_client_error() {
(code, "invalid_request_error", "upstream_client_error")
} else {
(StatusCode::BAD_GATEWAY, "server_error", "upstream_error")
}
}
GatewayError::QueueFull => (
StatusCode::SERVICE_UNAVAILABLE,
"server_error",
"queue_full",
),
GatewayError::ProfileNotFound(_) => (
StatusCode::NOT_FOUND,
"invalid_request_error",
"profile_not_found",
),
GatewayError::SwitchFailed { .. } => (
StatusCode::BAD_REQUEST,
"invalid_request_error",
"switch_failed",
),
GatewayError::ProfilesUnavailable => (
StatusCode::BAD_REQUEST,
"invalid_request_error",
"profiles_unavailable",
),
}
}
}
impl IntoResponse for GatewayError {
fn into_response(self) -> Response {
let (status, kind, code) = self.classify();
let body = Json(serde_json::json!({
"error": { "message": self.to_string(), "type": kind, "code": code }
}));
(status, body).into_response()
}
}
/// A configuration load or validation failure.
///
/// Paths are kept as [`PathBuf`](std::path::PathBuf) and the include chain as a
/// `Vec<PathBuf>` (ERR-006); the TOML parse cause is preserved as a private
/// `#[source]` rather than flattened into a string (ERR-002).
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ConfigError {
/// The configuration file could not be read.
#[non_exhaustive]
#[error("read config {}", path.display())]
Read {
/// The path that could not be read.
path: std::path::PathBuf,
/// The underlying I/O error.
#[source]
source: std::io::Error,
},
/// The configuration was not valid TOML.
#[non_exhaustive]
#[error("parse config{}", parse_location(path.as_ref()))]
Parse {
/// The file the parse failure came from, when known.
path: Option<std::path::PathBuf>,
/// The underlying TOML deserialization error (boxed: it is large).
#[source]
source: Box<toml::de::Error>,
},
/// A `${VAR}` referenced an environment variable that was not set.
#[non_exhaustive]
#[error("unresolved environment variable {0}")]
UnresolvedVar(String),
/// A `${...}` interpolation was malformed (for example, unclosed).
#[non_exhaustive]
#[error("interpolation: {0}")]
Interpolation(String),
/// The configuration parsed but failed a semantic check.
#[non_exhaustive]
#[error("invalid config: {0}")]
Validation(String),
/// An `include` chain revisited a file already being resolved.
#[non_exhaustive]
#[error("include cycle at {} (chain: {})", path.display(), render_chain(chain))]
IncludeCycle {
/// The path that closed the cycle.
path: std::path::PathBuf,
/// The include stack when the cycle was detected.
chain: Vec<std::path::PathBuf>,
},
/// An `include` chain exceeded the maximum nesting depth.
#[non_exhaustive]
#[error("include depth exceeded {max} at {}", path.display())]
IncludeDepth {
/// The path that would have been loaded next.
path: std::path::PathBuf,
/// The configured maximum depth.
max: usize,
},
}
/// Renders the optional parse-failure path as a ` (path)` suffix or empty.
fn parse_location(path: Option<&std::path::PathBuf>) -> String {
path.map(|p| format!(" ({})", p.display()))
.unwrap_or_default()
}
/// Renders an include chain as `a -> b -> c`.
fn render_chain(chain: &[std::path::PathBuf]) -> String {
chain
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(" -> ")
}
#[cfg(test)]
mod tests {
use super::*;
use std::error::Error as _;
#[test]
fn gateway_error_classify_is_table_driven() {
let cases: Vec<(GatewayError, (StatusCode, &str, &str))> = vec![
(
GatewayError::Unauthorized,
(
StatusCode::UNAUTHORIZED,
"authentication_error",
"unauthorized",
),
),
(
GatewayError::UnknownModel("m".to_owned()),
(
StatusCode::NOT_FOUND,
"invalid_request_error",
"model_not_found",
),
),
(
GatewayError::QueueFull,
(
StatusCode::SERVICE_UNAVAILABLE,
"server_error",
"queue_full",
),
),
(
GatewayError::switch_failed("build-routing", std::io::Error::other("x")),
(
StatusCode::BAD_REQUEST,
"invalid_request_error",
"switch_failed",
),
),
];
for (error, expected) in cases {
assert_eq!(error.classify(), expected);
}
}
#[test]
fn upstream_protocol_is_502_and_not_a_transport_error() {
let error = GatewayError::upstream_protocol(std::io::Error::other("bad json"));
assert_eq!(
error.classify(),
(StatusCode::BAD_GATEWAY, "server_error", "upstream_protocol")
);
// Must not be a transport error, so a decode failure never triggers a
// local child respawn (UP-004, UPSTREAM-003).
assert!(!matches!(error, GatewayError::UpstreamTransport(_)));
assert!(error.source().is_some());
}
#[test]
fn switch_failed_preserves_its_cause() {
let error = GatewayError::switch_failed("load-profile", std::io::Error::other("disk"));
assert!(error.source().is_some());
assert!(error.to_string().contains("load-profile"));
assert!(!error.to_string().contains("disk"));
}
#[test]
fn admit_error_maps_both_variants_to_queue_full() {
for admit in [
crate::queue::AdmitError::QueueFull,
crate::queue::AdmitError::Unavailable,
] {
assert!(matches!(GatewayError::from(admit), GatewayError::QueueFull));
}
}
}