1mod epoch;
2pub mod records;
3pub mod schema;
4pub mod sql;
5pub mod target;
6
7use std::{borrow::Cow, error::Error as StdError, fmt, io};
8
9use capsid_model::{Category, api::NOT_LEADER};
10
11pub use epoch::AuthorityEpoch;
12
13pub type Result<T, E = StoreError> = std::result::Result<T, E>;
14
15#[derive(Debug, thiserror::Error)]
16pub enum StoreError {
17 #[error("{resource} not found: {name}")]
18 NotFound { resource: Resource, name: String },
19
20 #[error("state filesystem")]
21 Io(#[from] io::Error),
22
23 #[error("controller recovery authority: {0}")]
24 Authority(Cow<'static, str>),
25
26 #[error("invalid controller authority epoch")]
27 Epoch(#[source] uuid::Error),
28
29 #[error("state database")]
30 Sqlite(#[from] rusqlite::Error),
31
32 #[error("controller consensus")]
33 Raft(#[from] capsid_raft::Error),
34
35 #[error("state record")]
36 Json(#[from] serde_json::Error),
37
38 #[error("{0}")]
39 Busy(Cow<'static, str>),
40
41 #[error("{0}")]
42 QuotaExceeded(Cow<'static, str>),
43
44 #[error("{0}")]
45 Conflict(Cow<'static, str>),
46
47 #[error("{0}")]
48 Denied(Cow<'static, str>),
49
50 #[error("{0}")]
51 Invalid(Cow<'static, str>),
52
53 #[error(transparent)]
54 Model(#[from] capsid_model::Error),
55
56 #[error(transparent)]
57 Host(capsid_host::Error),
58
59 #[error("corrupt state record: {0}")]
60 Corrupt(Cow<'static, str>),
61
62 #[error("{NOT_LEADER}")]
63 NotLeader,
64
65 #[error(transparent)]
66 Egress(capsid_egress::Error),
67}
68
69impl From<capsid_egress::Error> for StoreError {
70 fn from(error: capsid_egress::Error) -> Self {
71 match error {
72 capsid_egress::Error::Io(error) => Self::Io(error),
73 capsid_egress::Error::Model(error) => Self::Model(error),
74 capsid_egress::Error::Host(error) => error.into(),
75 error => Self::Egress(error),
76 }
77 }
78}
79
80impl From<capsid_host::Error> for StoreError {
81 fn from(error: capsid_host::Error) -> Self {
82 match error {
83 capsid_host::Error::Io(error) => Self::Io(error),
84 capsid_host::Error::Model(error) => Self::Model(error),
85 error => Self::Host(error),
86 }
87 }
88}
89
90impl From<capsid_protocol::Error> for StoreError {
91 fn from(error: capsid_protocol::Error) -> Self {
92 Self::Model(error.into())
93 }
94}
95
96impl StoreError {
97 pub fn into_io(self) -> io::Error {
98 match self {
99 Self::Io(error) => error,
100 error => io::Error::new(error.category().io_kind(), error),
101 }
102 }
103
104 pub fn not_found(resource: Resource, name: impl Into<String>) -> Self {
105 Self::NotFound {
106 resource,
107 name: name.into(),
108 }
109 }
110
111 pub fn invalid(message: impl Into<Cow<'static, str>>) -> Self {
112 Self::Invalid(message.into())
113 }
114
115 pub fn conflict(message: impl Into<Cow<'static, str>>) -> Self {
116 Self::Conflict(message.into())
117 }
118
119 pub fn busy(message: impl Into<Cow<'static, str>>) -> Self {
120 Self::Busy(message.into())
121 }
122
123 pub fn quota_exceeded(message: impl Into<Cow<'static, str>>) -> Self {
124 Self::QuotaExceeded(message.into())
125 }
126
127 pub fn denied(message: impl Into<Cow<'static, str>>) -> Self {
128 Self::Denied(message.into())
129 }
130
131 pub fn corrupt(message: impl Into<Cow<'static, str>>) -> Self {
132 Self::Corrupt(message.into())
133 }
134
135 pub fn authority(message: impl Into<Cow<'static, str>>) -> Self {
136 Self::Authority(message.into())
137 }
138
139 pub fn is_infrastructure(&self) -> bool {
140 matches!(
141 self,
142 Self::Io(_) | Self::Sqlite(_) | Self::Json(_) | Self::Authority(_)
143 )
144 }
145
146 pub fn category(&self) -> Category {
147 match self {
148 Self::NotFound { .. } => Category::NotFound,
149 Self::Busy(_) | Self::NotLeader => Category::Busy,
150 Self::QuotaExceeded(_) => Category::QuotaExceeded,
151 Self::Conflict(_) => Category::Conflict,
152 Self::Denied(_) => Category::PermissionDenied,
153 Self::Io(error) => io_category(error),
154 Self::Sqlite(error)
155 if error.sqlite_error_code() == Some(rusqlite::ErrorCode::DiskFull) =>
156 {
157 Category::StorageFull
158 }
159 Self::Raft(
160 capsid_raft::Error::NotLeader { .. }
161 | capsid_raft::Error::NoLeader
162 | capsid_raft::Error::NoQuorum
163 | capsid_raft::Error::Io(_),
164 ) => Category::Busy,
165 Self::Invalid(_) => Category::InvalidInput,
166 Self::Model(error) => error.category(),
167 Self::Host(error) => error.category(),
168 Self::Egress(error) => error.category(),
169 Self::Authority(_)
170 | Self::Epoch(_)
171 | Self::Corrupt(_)
172 | Self::Sqlite(_)
173 | Self::Raft(_)
174 | Self::Json(_) => Category::Internal,
175 }
176 }
177}
178
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub enum Resource {
181 Instance,
182
183 Attempt,
184
185 Template,
186
187 Bundle,
188
189 Volume,
190
191 Backup,
192
193 Checkpoint,
194
195 Relocation,
196
197 Workspace,
198
199 Run,
200
201 Workload,
202
203 Ledger,
204
205 Operation,
206
207 Revision,
208
209 JobRun,
210
211 JobGroup,
212
213 Pool,
214
215 PrivateNetwork,
216
217 EgressGrant,
218
219 ManagementIntent,
220
221 Project,
222
223 Token,
224}
225
226impl fmt::Display for Resource {
227 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228 f.write_str(match self {
229 Self::Instance => "instance",
230 Self::Attempt => "attempt",
231 Self::Template => "template",
232 Self::Bundle => "bundle",
233 Self::Volume => "volume",
234 Self::Backup => "volume backup",
235 Self::Checkpoint => "checkpoint",
236 Self::Relocation => "relocation",
237 Self::Workspace => "workspace",
238 Self::Run => "run request",
239 Self::Workload => "workload",
240 Self::Ledger => "ledger",
241 Self::Operation => "operation",
242 Self::Revision => "workload revision",
243 Self::JobRun => "job run",
244 Self::JobGroup => "job group",
245 Self::Pool => "pool or claim",
246 Self::PrivateNetwork => "private network",
247 Self::EgressGrant => "network grant",
248 Self::ManagementIntent => "management intent",
249 Self::Project => "project",
250 Self::Token => "token",
251 })
252 }
253}
254
255const MAX_CHAIN_DEPTH: usize = 16;
256
257fn io_category(error: &io::Error) -> Category {
259 let wrapped = error
260 .get_ref()
261 .map(|inner| inner as &(dyn StdError + 'static));
262 std::iter::successors(wrapped, |&inner| inner.source())
263 .take(MAX_CHAIN_DEPTH)
264 .find_map(|inner| {
265 if let Some(store) = inner.downcast_ref::<StoreError>() {
266 return Some(store.category());
267 }
268
269 if let Some(model) = inner.downcast_ref::<capsid_model::Error>() {
270 return Some(model.category());
271 }
272
273 match inner.downcast_ref::<capsid_host::Error>()? {
274 capsid_host::Error::Io(_) => None,
275 host => Some(host.category()),
276 }
277 })
278 .unwrap_or_else(|| Category::from_io_kind(error.kind()))
279}