1#[cfg(feature = "axum")]
2use axum::response::{IntoResponse, Response};
3#[cfg(feature = "axum")]
4use serde_json::json;
5
6pub type Result<T> = std::result::Result<T, Error>;
7
8#[derive(thiserror::Error, Debug)]
9pub enum Error {
10 #[error("cache io error: {0}")]
11 Io(#[from] std::io::Error),
12
13 #[error("cache config parse error: {0}")]
14 Yaml(#[from] serde_yaml::Error),
15
16 #[cfg(feature = "redis")]
17 #[error("cache redis error: {0}")]
18 Redis(#[from] redis::RedisError),
19
20 #[error("cache file storage error: {0}")]
21 Storage(#[from] cacache::Error),
22
23 #[error("cache missing: {0}")]
24 Missing(String),
25
26 #[error("cache rejected: {0}")]
27 Rejected(String),
28
29 #[error("cache store '{store}' (driver '{driver}') does not support tags")]
33 TagsUnsupported { store: Box<str>, driver: Box<str> },
34
35 #[error("too many cache tags: {count} > {max}")]
39 TooManyTags { count: usize, max: usize },
40
41 #[error("a cache tag invalidation must name at least one tag")]
43 TagsEmpty,
44
45 #[error("cache other: {0}")]
46 Other(String),
47}
48
49impl Error {
50 pub fn other(err: impl std::fmt::Display) -> Self {
51 Self::Other(err.to_string())
52 }
53
54 pub fn wrap(
55 msg: impl std::fmt::Display,
56 err: impl std::fmt::Display,
57 ) -> Self {
58 Self::Other(format!("{msg}: {err}"))
59 }
60}
61
62impl From<String> for Error {
63 fn from(value: String) -> Self {
64 Self::Other(value)
65 }
66}
67
68impl From<&str> for Error {
69 fn from(value: &str) -> Self {
70 Self::Other(value.to_string())
71 }
72}
73
74#[cfg(feature = "orbit")]
75impl From<claviron_orbit::cache::Error> for Error {
76 fn from(value: claviron_orbit::cache::Error) -> Self {
77 use claviron_orbit::cache::Error as Orbit;
78 match value {
79 Orbit::TooManyTags { count, max } => {
80 Self::TooManyTags { count, max }
81 }
82 Orbit::TagsEmpty => Self::TagsEmpty,
83 Orbit::TagsUnsupported { store, .. } => {
84 Self::TagsUnsupported { store, driver: "orbit".into() }
85 }
86 other => Self::wrap("Orbit cache operation failed", other),
87 }
88 }
89}
90
91impl From<crate::ValueError> for Error {
92 fn from(value: crate::ValueError) -> Self {
93 Self::wrap("cache value operation failed", value)
94 }
95}
96
97#[cfg(feature = "axum")]
98impl IntoResponse for Error {
99 fn into_response(self) -> Response {
100 let (status, body) = match self {
101 Error::Missing(message) => {
102 (axum::http::StatusCode::NOT_FOUND, json!({ "error": message }))
103 }
104 Error::Rejected(message) => (
105 axum::http::StatusCode::NOT_IMPLEMENTED,
106 json!({ "error": message }),
107 ),
108 error @ Error::TagsUnsupported { .. } => (
109 axum::http::StatusCode::NOT_IMPLEMENTED,
110 json!({ "error": error.to_string() }),
111 ),
112 other => (
113 axum::http::StatusCode::INTERNAL_SERVER_ERROR,
114 json!({ "error": other.to_string() }),
115 ),
116 };
117
118 (status, body.to_string()).into_response()
119 }
120}