Skip to main content

waratah_api/
error.rs

1//! HTTP-facing API errors.
2
3use axum::http::StatusCode;
4use axum::response::{IntoResponse, Response};
5use thiserror::Error;
6use waratah_compute::ComputeError;
7
8use crate::query_library::QueryLibraryError;
9
10/// Failure translating an RDF4J request into a compute call or wire format.
11#[derive(Debug, Error)]
12pub enum ApiError {
13    /// Repository id is not registered on this server.
14    #[error("unknown repository: {0}")]
15    UnknownRepository(String),
16
17    /// Request is missing a required SPARQL query string.
18    #[error("missing SPARQL query")]
19    MissingQuery,
20
21    /// Request body / content-type is not accepted for SPARQL Protocol.
22    #[error("unsupported SPARQL request content type")]
23    UnsupportedContentType,
24
25    /// The `Accept` header lists only response formats this server cannot
26    /// produce (no wildcard fallback matched).
27    #[error("no supported response format matches Accept: {0}")]
28    NotAcceptable(String),
29
30    /// A request argument could not be decoded or has an unsupported value.
31    #[error("invalid request argument: {0}")]
32    InvalidArgument(String),
33
34    /// Compute rejected or failed the operation.
35    #[error(transparent)]
36    Compute(#[from] ComputeError),
37
38    /// SPARQL Results serialization failed.
39    #[error("failed to serialize SPARQL results: {0}")]
40    Serialize(String),
41
42    /// HTTP ingest is disabled (no `--ingest-dir` / test without a staging dir).
43    #[error("ingest directory is not configured")]
44    IngestNotConfigured,
45
46    /// Named ingest file is missing from the staging directory.
47    #[error("ingest file not found: {0}")]
48    IngestFileNotFound(String),
49
50    /// Filesystem I/O in the ingest directory.
51    #[error(transparent)]
52    Io(#[from] std::io::Error),
53
54    /// This compute has no cluster config (cannot assemble a snapshot).
55    #[error("cluster snapshot is not available on this backend")]
56    ClusterUnavailable,
57
58    /// The query library is disabled in this process (no `--queries-dir`, no
59    /// inline demo queries) — same convention as ingest (`501` = no ingest
60    /// directory) and cluster (`501` = no cluster view).
61    #[error("query library is not configured")]
62    QueryLibraryNotConfigured,
63
64    /// A configured query library failed to resolve for this repository:
65    /// the directory is missing (`404`) or a sidecar / directory read
66    /// failed (`500`).
67    #[error(transparent)]
68    QueryLibrary(#[from] QueryLibraryError),
69}
70
71impl ApiError {
72    pub(crate) fn status(&self) -> StatusCode {
73        match self {
74            Self::UnknownRepository(_) => StatusCode::NOT_FOUND,
75            Self::IngestFileNotFound(_) => StatusCode::NOT_FOUND,
76            Self::IngestNotConfigured | Self::Compute(ComputeError::IngestUnsupported) => {
77                StatusCode::NOT_IMPLEMENTED
78            }
79            Self::ClusterUnavailable => StatusCode::NOT_IMPLEMENTED,
80            Self::QueryLibraryNotConfigured => StatusCode::NOT_IMPLEMENTED,
81            Self::QueryLibrary(QueryLibraryError::Missing(_)) => StatusCode::NOT_FOUND,
82            Self::QueryLibrary(QueryLibraryError::Invalid { .. }) => {
83                StatusCode::INTERNAL_SERVER_ERROR
84            }
85            Self::NotAcceptable(_) => StatusCode::NOT_ACCEPTABLE,
86            Self::MissingQuery | Self::UnsupportedContentType | Self::InvalidArgument(_) => {
87                StatusCode::BAD_REQUEST
88            }
89            Self::Compute(ComputeError::Sparql(_))
90            | Self::Compute(ComputeError::UnsupportedSparql(_))
91            | Self::Compute(ComputeError::UnsupportedRdfFormat { .. })
92            | Self::Compute(ComputeError::RdfParse { .. })
93            | Self::Compute(ComputeError::InvalidBaseIri { .. })
94            | Self::Compute(ComputeError::InvalidGraphIri { .. })
95            | Self::Compute(ComputeError::InvalidQuad(_))
96            | Self::Compute(ComputeError::InvalidLiteral(_)) => StatusCode::BAD_REQUEST,
97            Self::Compute(ComputeError::Cancelled) => StatusCode::SERVICE_UNAVAILABLE,
98            Self::Compute(ComputeError::DeadlineExceeded) => StatusCode::REQUEST_TIMEOUT,
99            Self::Compute(_) | Self::Serialize(_) | Self::Io(_) => {
100                StatusCode::INTERNAL_SERVER_ERROR
101            }
102        }
103    }
104}
105
106impl IntoResponse for ApiError {
107    fn into_response(self) -> Response {
108        (self.status(), self.to_string()).into_response()
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115
116    #[test]
117    fn invalid_literal_is_bad_request() {
118        let error = ApiError::Compute(ComputeError::InvalidLiteral("bad geometry".into()));
119        assert_eq!(error.status(), StatusCode::BAD_REQUEST);
120    }
121
122    #[test]
123    fn cancelled_query_is_unavailable() {
124        let error = ApiError::Compute(ComputeError::Cancelled);
125        assert_eq!(error.status(), StatusCode::SERVICE_UNAVAILABLE);
126    }
127
128    #[test]
129    fn deadline_exceeded_is_request_timeout() {
130        let error = ApiError::Compute(ComputeError::DeadlineExceeded);
131        assert_eq!(error.status(), StatusCode::REQUEST_TIMEOUT);
132    }
133
134    #[test]
135    fn ingest_not_configured_is_not_implemented() {
136        let error = ApiError::IngestNotConfigured;
137        assert_eq!(error.status(), StatusCode::NOT_IMPLEMENTED);
138    }
139
140    #[test]
141    fn unsupported_accept_is_not_acceptable() {
142        let error = ApiError::NotAcceptable("application/x-unknown".into());
143        assert_eq!(error.status(), StatusCode::NOT_ACCEPTABLE);
144    }
145
146    #[test]
147    fn cluster_unavailable_is_not_implemented() {
148        let error = ApiError::ClusterUnavailable;
149        assert_eq!(error.status(), StatusCode::NOT_IMPLEMENTED);
150    }
151
152    #[test]
153    fn query_library_not_configured_is_not_implemented() {
154        let error = ApiError::QueryLibraryNotConfigured;
155        assert_eq!(error.status(), StatusCode::NOT_IMPLEMENTED);
156    }
157
158    #[test]
159    fn unpublished_query_library_is_not_found() {
160        let error = ApiError::QueryLibrary(QueryLibraryError::Missing("main".into()));
161        assert_eq!(error.status(), StatusCode::NOT_FOUND);
162    }
163
164    #[test]
165    fn broken_query_library_is_internal_server_error() {
166        let error = ApiError::QueryLibrary(QueryLibraryError::Invalid {
167            path: "/tmp/broken.toml".into(),
168            message: "invalid query sidecar (boom)".into(),
169        });
170        assert_eq!(error.status(), StatusCode::INTERNAL_SERVER_ERROR);
171    }
172}