ostrya_remote/error.rs
1//! The error type of this crate and its wire codes.
2
3use ostrya_core::{Checksum, ObjectName};
4
5use crate::proto::{ErrorMessage, RefState};
6
7/// The result type of this crate, with [`Error`] as its error.
8pub type Result<T> = std::result::Result<T, Error>;
9
10/// The error of each fallible operation of this crate.
11///
12/// A variant with a wire code matches one code of an `Error` message, for
13/// example [`Error::Protocol`] for the code `protocol`. [`ErrorCode`] names
14/// the codes. [`code`](Error::code) returns the code of an error and lists the
15/// variants that have no code.
16#[derive(Debug, thiserror::Error)]
17#[non_exhaustive]
18pub enum Error {
19 /// The server does not support the requested protocol version.
20 #[error("version-unsupported: {0}")]
21 VersionUnsupported(String),
22 /// The server repository sets `[core] locking=false`.
23 #[error("locking-disabled: {0}")]
24 LockingDisabled(String),
25 /// A refusal of the credential of an HTTP push session.
26 ///
27 /// The client returns this variant for an `Error` message with the code
28 /// `unauthorized`. An ostrya server sends that message over HTTP alone,
29 /// with the status 401 or 403. A 401 or 403 whose body is not one frame
30 /// is [`Error::Transport`].
31 #[error("unauthorized: {0}")]
32 Unauthorized(String),
33 /// A malformed frame, an unknown kind, or a message out of order.
34 #[error("protocol: {0}")]
35 Protocol(String),
36 /// A frame, a batch, or a metadata object over its limit.
37 #[error("limit-exceeded: {0}")]
38 LimitExceeded(String),
39 /// An object whose bytes do not hash to its name.
40 #[error("checksum-mismatch: {0}")]
41 ChecksumMismatch(String),
42 /// Content that the server refuses to store.
43 ///
44 /// The repository mode cannot store the content, or the content is
45 /// privileged and the policy does not allow it.
46 #[error("mode-refused: {0}")]
47 ModeRefused(String),
48 /// A commit that reaches objects that the server does not hold.
49 ///
50 /// The objects are not in the repository and are not staged in the
51 /// session. `missing` lists them.
52 #[error("missing-objects: {message}")]
53 MissingObjects {
54 /// The message for a human.
55 message: String,
56 /// The objects that are missing.
57 missing: Vec<ObjectName>,
58 },
59 /// A ref that is not in its expected state, or a ref that exists and
60 /// that the update can create and not move.
61 ///
62 /// The second case is an update that writes a commit to a ref that
63 /// exists, with `t` and no `w` on the ref, also when the commit is the
64 /// current commit. `name` and `current` give the current state.
65 /// `current` is `None` if the ref is absent.
66 #[error("ref-mismatch: {message}")]
67 RefMismatch {
68 /// The message for a human.
69 message: String,
70 /// The name of the ref.
71 name: String,
72 /// The current commit of the ref.
73 current: Option<Checksum>,
74 },
75 /// A ref update that is not a fast-forward.
76 ///
77 /// The new commit does not descend from the current tip, and the policy
78 /// does not allow it.
79 #[error("non-fast-forward: {0}")]
80 NonFastForward(String),
81 /// A ref delete that the policy does not allow.
82 #[error("delete-denied: {0}")]
83 DeleteDenied(String),
84 /// A ref name that an ostrya server refuses.
85 #[error("invalid-ref: {0}")]
86 InvalidRef(String),
87 /// A session or a ref update that the policy refuses.
88 ///
89 /// In a push session, these are the causes:
90 ///
91 /// - The client group opens no push session.
92 /// - A ref of `Hello` has no `r`.
93 /// - An update writes a commit to a ref with no `w` and no `t`.
94 /// - An update names a ref that a push does not write: a remote ref, the
95 /// collection anchor ref of a server with a collection id, a ref that
96 /// is an alias, or a ref path that a ref write cannot replace.
97 /// - Two updates write a commit, and the ref of one names a directory of
98 /// the other.
99 ///
100 /// In a one-way stream, the rule that matches the update does not accept
101 /// it, or the update names a remote ref that no rule matches.
102 #[error("ref-denied: {0}")]
103 RefDenied(String),
104 /// A commit with no trusted signature that verifies.
105 ///
106 /// The policy requires a trusted signature.
107 #[error("signature-required: {0}")]
108 SignatureRequired(String),
109 /// A commit whose bindings do not match the session.
110 ///
111 /// The `ostree.ref-binding` of the commit does not name a target ref, or
112 /// its `ostree.collection-binding` does not name the collection id of the
113 /// server.
114 #[error("binding-mismatch: {0}")]
115 BindingMismatch(String),
116 /// A server-side failure, for example an I/O error.
117 #[error("internal: {0}")]
118 Internal(String),
119 /// The client ended the session with `Abort`, or abandoned an object.
120 ///
121 /// The client abandons an object with the abandon marker. No wire code
122 /// carries this variant, because the server sends no `Error` message in
123 /// reply.
124 #[error("the client aborted the session")]
125 Aborted,
126 /// A `Commit` whose outcome is unknown.
127 ///
128 /// The client sent `Commit`, and the session ended with no reply that the
129 /// client can read. The server can have written the refs, and the client
130 /// cannot know if it did. `refs` names the refs of the ref updates.
131 #[error("the outcome of the commit of {refs:?} is unknown: {message}")]
132 CommitOutcomeUnknown {
133 /// The refs of the ref updates.
134 refs: Vec<String>,
135 /// A message for a human that states what ended the session.
136 message: String,
137 },
138 /// A failure of the object source while the session sends its objects.
139 ///
140 /// The session ends with `Abort`.
141 #[error("the object source failed: {0}")]
142 Source(#[source] Box<dyn std::error::Error + Send + Sync>),
143 /// A call of the client that the session refuses.
144 ///
145 /// The session refuses a call with an argument or source data that it
146 /// cannot send. It also refuses a call while another call runs, and a
147 /// call on a broken session.
148 #[error("invalid input: {0}")]
149 InvalidInput(String),
150 /// A failure of the transport under the session.
151 ///
152 /// - Over ssh, the ssh client cannot start, or it exits with a failure
153 /// status while the session fails with an I/O error. The message names
154 /// the program.
155 /// - Over HTTP, the session cannot use the response of the server. The
156 /// message names the URL, and for the first three cases the status:
157 /// - a status that the receive endpoint does not give, a 3xx included
158 /// - a body that is not one frame
159 /// - a frame other than an `Error` message with an error status
160 /// - a `HelloReply` with no session id of 64 lowercase hex digits
161 /// - a frame other than an `Error` message in answer to `DELETE`
162 ///
163 /// No wire code carries this variant.
164 #[error("transport: {0}")]
165 Transport(String),
166 /// A failure of the HTTP client of the session.
167 ///
168 /// The client cannot be built, a request cannot be sent, or a request
169 /// fails after it is sent. No wire code carries this variant.
170 #[error(transparent)]
171 Fetch(ostrya_fetch::Error),
172 /// An I/O error of the underlying stream.
173 ///
174 /// An end of file inside a frame or an object has the kind
175 /// `UnexpectedEof`.
176 #[error(transparent)]
177 Io(#[from] std::io::Error),
178 /// A failure of the walk or of the hash pass of a local tree.
179 ///
180 /// If the send pass cannot open a file of the tree again, it also
181 /// returns this variant. `path` names the entry on the local filesystem,
182 /// the walk root included. `source` keeps the `io::ErrorKind` of the
183 /// failure.
184 /// [`TreeModel::scan`](crate::tree::TreeModel::scan) lists the kinds in
185 /// its `# Errors` section.
186 ///
187 /// No wire code carries this variant. The walk and the hash pass come
188 /// before any session. A session returns a failed open of the send pass
189 /// inside [`Error::Source`].
190 #[error("{}: {source}", .path.display())]
191 Walk {
192 /// The entry on the local filesystem.
193 path: std::path::PathBuf,
194 /// The I/O error, with the `io::ErrorKind` of the failure.
195 #[source]
196 source: std::io::Error,
197 },
198}
199
200/// The wire code of an `Error` message.
201///
202/// A later protocol version can add codes.
203#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
204#[non_exhaustive]
205pub enum ErrorCode {
206 /// `version-unsupported`.
207 VersionUnsupported,
208 /// `locking-disabled`.
209 LockingDisabled,
210 /// `unauthorized`.
211 Unauthorized,
212 /// `protocol`.
213 Protocol,
214 /// `limit-exceeded`.
215 LimitExceeded,
216 /// `checksum-mismatch`.
217 ChecksumMismatch,
218 /// `mode-refused`.
219 ModeRefused,
220 /// `missing-objects`.
221 MissingObjects,
222 /// `ref-mismatch`.
223 RefMismatch,
224 /// `non-fast-forward`.
225 NonFastForward,
226 /// `delete-denied`.
227 DeleteDenied,
228 /// `invalid-ref`.
229 InvalidRef,
230 /// `ref-denied`.
231 RefDenied,
232 /// `signature-required`.
233 SignatureRequired,
234 /// `binding-mismatch`.
235 BindingMismatch,
236 /// `internal`.
237 Internal,
238}
239
240impl ErrorCode {
241 /// All 16 codes, in the order that [`ErrorCode`] declares them.
242 pub const ALL: [ErrorCode; 16] = [
243 ErrorCode::VersionUnsupported,
244 ErrorCode::LockingDisabled,
245 ErrorCode::Unauthorized,
246 ErrorCode::Protocol,
247 ErrorCode::LimitExceeded,
248 ErrorCode::ChecksumMismatch,
249 ErrorCode::ModeRefused,
250 ErrorCode::MissingObjects,
251 ErrorCode::RefMismatch,
252 ErrorCode::NonFastForward,
253 ErrorCode::DeleteDenied,
254 ErrorCode::InvalidRef,
255 ErrorCode::RefDenied,
256 ErrorCode::SignatureRequired,
257 ErrorCode::BindingMismatch,
258 ErrorCode::Internal,
259 ];
260
261 /// Returns the wire name of the code.
262 pub fn as_str(self) -> &'static str {
263 match self {
264 ErrorCode::VersionUnsupported => "version-unsupported",
265 ErrorCode::LockingDisabled => "locking-disabled",
266 ErrorCode::Unauthorized => "unauthorized",
267 ErrorCode::Protocol => "protocol",
268 ErrorCode::LimitExceeded => "limit-exceeded",
269 ErrorCode::ChecksumMismatch => "checksum-mismatch",
270 ErrorCode::ModeRefused => "mode-refused",
271 ErrorCode::MissingObjects => "missing-objects",
272 ErrorCode::RefMismatch => "ref-mismatch",
273 ErrorCode::NonFastForward => "non-fast-forward",
274 ErrorCode::DeleteDenied => "delete-denied",
275 ErrorCode::InvalidRef => "invalid-ref",
276 ErrorCode::RefDenied => "ref-denied",
277 ErrorCode::SignatureRequired => "signature-required",
278 ErrorCode::BindingMismatch => "binding-mismatch",
279 ErrorCode::Internal => "internal",
280 }
281 }
282
283 /// Returns the code of a wire name, or `None` if the name is not a code.
284 pub fn from_name(name: &str) -> Option<ErrorCode> {
285 ErrorCode::ALL.into_iter().find(|c| c.as_str() == name)
286 }
287}
288
289impl Error {
290 /// Returns the wire code of the error, or `None` for a variant with no code.
291 ///
292 /// These variants have no wire code:
293 ///
294 /// - [`Error::Aborted`]
295 /// - [`Error::CommitOutcomeUnknown`]
296 /// - [`Error::Source`]
297 /// - [`Error::InvalidInput`]
298 /// - [`Error::Transport`]
299 /// - [`Error::Fetch`]
300 /// - [`Error::Io`]
301 /// - [`Error::Walk`]
302 pub fn code(&self) -> Option<ErrorCode> {
303 Some(match self {
304 Error::VersionUnsupported(_) => ErrorCode::VersionUnsupported,
305 Error::LockingDisabled(_) => ErrorCode::LockingDisabled,
306 Error::Unauthorized(_) => ErrorCode::Unauthorized,
307 Error::Protocol(_) => ErrorCode::Protocol,
308 Error::LimitExceeded(_) => ErrorCode::LimitExceeded,
309 Error::ChecksumMismatch(_) => ErrorCode::ChecksumMismatch,
310 Error::ModeRefused(_) => ErrorCode::ModeRefused,
311 Error::MissingObjects { .. } => ErrorCode::MissingObjects,
312 Error::RefMismatch { .. } => ErrorCode::RefMismatch,
313 Error::NonFastForward(_) => ErrorCode::NonFastForward,
314 Error::DeleteDenied(_) => ErrorCode::DeleteDenied,
315 Error::InvalidRef(_) => ErrorCode::InvalidRef,
316 Error::RefDenied(_) => ErrorCode::RefDenied,
317 Error::SignatureRequired(_) => ErrorCode::SignatureRequired,
318 Error::BindingMismatch(_) => ErrorCode::BindingMismatch,
319 Error::Internal(_) => ErrorCode::Internal,
320 Error::Aborted
321 | Error::CommitOutcomeUnknown { .. }
322 | Error::Source(_)
323 | Error::InvalidInput(_)
324 | Error::Transport(_)
325 | Error::Fetch(_)
326 | Error::Io(_)
327 | Error::Walk { .. } => return None,
328 })
329 }
330
331 /// Returns the `Error` message that reports this error to the peer.
332 ///
333 /// An error with no wire code reports as the code `internal`, with its
334 /// display text as the message.
335 pub fn to_message(&self) -> ErrorMessage {
336 let (code, message) = match self {
337 Error::MissingObjects { message, missing } => {
338 return ErrorMessage {
339 code: ErrorCode::MissingObjects,
340 message: message.clone(),
341 missing: missing.clone(),
342 current: None,
343 };
344 }
345 Error::RefMismatch {
346 message,
347 name,
348 current,
349 } => {
350 return ErrorMessage {
351 code: ErrorCode::RefMismatch,
352 message: message.clone(),
353 missing: Vec::new(),
354 current: Some(RefState {
355 name: name.clone(),
356 commit: *current,
357 }),
358 };
359 }
360 Error::Aborted
361 | Error::CommitOutcomeUnknown { .. }
362 | Error::Source(_)
363 | Error::InvalidInput(_)
364 | Error::Transport(_)
365 | Error::Fetch(_)
366 | Error::Io(_)
367 | Error::Walk { .. } => (ErrorCode::Internal, self.to_string()),
368 Error::VersionUnsupported(m)
369 | Error::LockingDisabled(m)
370 | Error::Unauthorized(m)
371 | Error::Protocol(m)
372 | Error::LimitExceeded(m)
373 | Error::ChecksumMismatch(m)
374 | Error::ModeRefused(m)
375 | Error::NonFastForward(m)
376 | Error::DeleteDenied(m)
377 | Error::InvalidRef(m)
378 | Error::RefDenied(m)
379 | Error::SignatureRequired(m)
380 | Error::BindingMismatch(m)
381 | Error::Internal(m) => (self.code().expect("not Io"), m.clone()),
382 };
383 ErrorMessage {
384 code,
385 message,
386 missing: Vec::new(),
387 current: None,
388 }
389 }
390}
391
392/// Converts an `Error` message from a server to the [`Error`] variant of its
393/// code.
394///
395/// The conversion drops a `missing` list or a `current` state on a code that
396/// does not carry one. A decoded `ref-mismatch` always carries its `current`
397/// state, so [`Error::to_message`] gives the same message back.
398impl From<ErrorMessage> for Error {
399 fn from(msg: ErrorMessage) -> Error {
400 let m = msg.message;
401 match msg.code {
402 ErrorCode::VersionUnsupported => Error::VersionUnsupported(m),
403 ErrorCode::LockingDisabled => Error::LockingDisabled(m),
404 ErrorCode::Unauthorized => Error::Unauthorized(m),
405 ErrorCode::Protocol => Error::Protocol(m),
406 ErrorCode::LimitExceeded => Error::LimitExceeded(m),
407 ErrorCode::ChecksumMismatch => Error::ChecksumMismatch(m),
408 ErrorCode::ModeRefused => Error::ModeRefused(m),
409 ErrorCode::MissingObjects => Error::MissingObjects {
410 message: m,
411 missing: msg.missing,
412 },
413 ErrorCode::RefMismatch => {
414 let (name, current) = match msg.current {
415 Some(s) => (s.name, s.commit),
416 None => (String::new(), None),
417 };
418 Error::RefMismatch {
419 message: m,
420 name,
421 current,
422 }
423 }
424 ErrorCode::NonFastForward => Error::NonFastForward(m),
425 ErrorCode::DeleteDenied => Error::DeleteDenied(m),
426 ErrorCode::InvalidRef => Error::InvalidRef(m),
427 ErrorCode::RefDenied => Error::RefDenied(m),
428 ErrorCode::SignatureRequired => Error::SignatureRequired(m),
429 ErrorCode::BindingMismatch => Error::BindingMismatch(m),
430 ErrorCode::Internal => Error::Internal(m),
431 }
432 }
433}