about summary refs log tree commit diff
path: root/src/error.rs
blob: b84cf9b971b6e1a21eae7acfee125dd208439392 (plain)
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
//! Shared error response shape for all endpoints, modeled on RFC 7807
//! (Problem Details for HTTP APIs) plus a few extra fields: a machine
//! readable `code`, the OpenAPI `operation_id` that failed, a `spec_url`
//! pointing back at /openapi.json, the request's `request_id` (see the
//! SetRequestIdLayer/PropagateRequestIdLayer in lib.rs), `took_ms`
//! (server time spent before the error, the same measure as a success
//! response's `meta.took_ms`), and `next`, a hint at a related endpoint
//! the caller might try instead. RFC 7807 allows extension members
//! like these next to the standard ones.
//!
//! `type`/`spec_url` are relative paths, not absolute URLs, since this
//! service has no fixed public domain; RFC 7807 explicitly allows `type`
//! to be a relative URI reference.

use axum::Json;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use serde::Serialize;

use crate::response::RequestInfo;

#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct ApiError {
    pub r#type: String,
    pub title: String,
    pub status: u16,
    pub code: String,
    pub detail: String,
    /// The blessed typed error body for the 422 `invalid_query` contract
    /// (owner-approved 2026-10-06, AMENDMENT E): `type`, `message`,
    /// `param` and a `detail` object carrying the backend's own error
    /// classification. `None` for every other error shape, so the
    /// envelope's existing fields stay the whole body there.
    pub error: Option<TypedErrorDetail>,
    pub operation_id: String,
    pub spec_url: String,
    pub request_id: Option<String>,
    /// Milliseconds the server spent on the request before this error.
    pub took_ms: Option<u64>,
    pub next: Option<String>,
}

/// The typed 422 `invalid_query` body (the 2026-10-06 contract,
/// `{"error": {"type", "message", "param", "detail"}}`), riding inside
/// the shared `ApiError` envelope under `error` so the existing fields
/// (`code`, `detail`, ...) keep their meaning for every caller.
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct TypedErrorDetail {
    /// The machine-readable error class (`invalid_query`).
    pub r#type: String,
    /// The human-readable rejection diagnostic (the backend's parser
    /// message).
    pub message: String,
    /// The offending request parameter. The search grammar rides on the
    /// `query` parameter (the contract keeps gn3's parameter name).
    pub param: String,
    /// Structured classification: the xapian exception class behind the
    /// rejection, when the backend reported one.
    pub detail: serde_json::Value,
}

impl ApiError {
    pub fn new(
        status: StatusCode,
        code: &str,
        title: &str,
        detail: String,
        operation_id: &str,
    ) -> Self {
        ApiError {
            r#type: format!("/errors/{code}"),
            title: title.to_string(),
            status: status.as_u16(),
            code: code.to_string(),
            detail,
            error: None,
            operation_id: operation_id.to_string(),
            spec_url: "/openapi.json".to_string(),
            request_id: None,
            took_ms: None,
            next: None,
        }
    }

    /// Attach the blessed typed 422 shape (the `error` object of the
    /// 2026-10-06 contract) to an `invalid_query` error. `detail`
    /// carries the backend's xapian error classification, when it
    /// reported one.
    pub fn with_typed_invalid_query(
        mut self,
        message: String,
        xapian_error_type: Option<String>,
    ) -> Self {
        self.error = Some(TypedErrorDetail {
            r#type: "invalid_query".to_string(),
            message,
            param: "query".to_string(),
            detail: serde_json::json!({ "xapian_error_type": xapian_error_type }),
        });
        self
    }

    /// Stamps the error with the request's id and the time taken so far.
    pub fn with_request_id(mut self, request: RequestInfo) -> Self {
        self.request_id = request.id();
        self.took_ms = Some(request.took_ms());
        self
    }

    pub fn with_next(mut self, next: &str) -> Self {
        self.next = Some(next.to_string());
        self
    }

    /// Map a database failure onto the shared error contract. An
    /// unreachable/unconfigured database (minted at `db::pool()`) is a
    /// typed 503 `db_unavailable` -- the database itself is down, not
    /// this request; a query failure on an established pool keeps the
    /// existing 500 `database_error`. Every DB-touching route maps
    /// through this one place, so all four `From`-adapter shapes and
    /// the inline `map_err` sites agree.
    pub fn from_db(error: crate::db::DbError, operation_id: &str) -> ApiError {
        match error {
            crate::db::DbError::Unavailable(detail) => {
                crate::db::record_failure(crate::db::FailureKind::Unavailable, detail.clone());
                ApiError::new(
                    StatusCode::SERVICE_UNAVAILABLE,
                    "db_unavailable",
                    "Database unavailable",
                    detail,
                    operation_id,
                )
            }
            crate::db::DbError::Query(error) => {
                // A connection that died under the query is not the
                // query's fault. Forget the pool so the next request
                // cannot draw the same dead sockets -- this is the one
                // place every database error passes through, so the
                // recovery does not depend on each caller remembering it.
                let detail = error.to_string();
                let lost = crate::db::is_connection_loss_detail(&detail);
                crate::db::record_failure(
                    if lost {
                        crate::db::FailureKind::ConnectionLost
                    } else {
                        crate::db::FailureKind::Query
                    },
                    detail.clone(),
                );
                let api_error = ApiError::new(
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "database_error",
                    "Database error",
                    detail,
                    operation_id,
                );
                if lost {
                    crate::db::forget_pool();
                }
                api_error
            }
        }
    }
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let status = StatusCode::from_u16(self.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
        // Server-side failures get one line on stderr each, as JSON, so a
        // caller's report ("500 at 12:31, request id ...") can be matched to
        // what actually happened. 4xx are not logged: they are the caller's
        // business (and a busy 401/422 stream would drown this out), but a
        // 5xx is ours, and until this existed the service kept no record of
        // one at all.
        if status.is_server_error() {
            eprintln!(
                "{}",
                serde_json::json!({
                    "event": "error",
                    "status": status.as_u16(),
                    "code": self.code,
                    "operation_id": self.operation_id,
                    "request_id": self.request_id,
                    "took_ms": self.took_ms,
                    "detail": truncate(&self.detail, 500),
                })
            );
        }
        (status, Json(self)).into_response()
    }
}

/// `text` cut to `limit` characters (not bytes), for one log line.
fn truncate(text: &str, limit: usize) -> String {
    if text.chars().count() <= limit {
        return text.to_string();
    }
    text.chars().take(limit).collect::<String>() + "…"
}

/// The 401 every token-gated endpoint can return, as one shared
/// `IntoResponses` type (an `ApiError` body under the hood) instead of
/// writing out `(status = 401, description = "...", body = ApiError)`
/// by hand on each `#[utoipa::path(...)]` -- reference it bare inside
/// `responses(...)`, e.g. `responses(Unauthorized, (status = 200, ...))`.
/// Which endpoints actually need it (i.e. take `AuthToken`) is still a
/// per-handler decision; this only removes the repetition in
/// documenting the one response shape that decision implies.
#[derive(utoipa::IntoResponses)]
#[response(status = 401, description = "Missing or invalid token")]
#[allow(dead_code)] // only ever used for its OpenAPI schema, never constructed
pub struct Unauthorized(#[to_schema] ApiError);