1
//! Folding the failures of a lock-protocol command into an [`Attempt`].
2

            
3
use super::CmdError;
4
use crate::attempt;
5
use crate::tag::lock::{KeyChanged, is_retryable};
6

            
7
/// An attempt of a command.
8
pub(super) type Attempt = attempt::Attempt<CmdError>;
9

            
10
impl From<sqlx::Error> for Attempt {
11
    fn from(err: sqlx::Error) -> Self {
12
        match is_retryable(&err) {
13
            true => Self::Retry,
14
            false => Self::Failed(err.into()),
15
        }
16
    }
17
}
18

            
19
impl From<CmdError> for Attempt {
20
3441
    fn from(err: CmdError) -> Self {
21
3441
        Self::Failed(err)
22
3441
    }
23
}
24

            
25
/// A tag-lock outcome as an attempt; a missing owner row is `gone`.
26
12370
pub(super) fn settled(
27
12370
    outcome: sqlx::Result<Result<(), KeyChanged>>,
28
12370
    gone: fn() -> CmdError,
29
12370
) -> Result<(), Attempt> {
30
12370
    match outcome {
31
10923
        Ok(Ok(())) => Ok(()),
32
4
        Ok(Err(KeyChanged)) => Err(Attempt::Retry),
33
1443
        Err(err) => Err(missing(err, gone)),
34
    }
35
12370
}
36

            
37
/// A missing row is `gone`; any other failure as in [`Attempt`].
38
1443
pub(super) fn missing(err: sqlx::Error, gone: fn() -> CmdError) -> Attempt {
39
1443
    match err {
40
1443
        sqlx::Error::RowNotFound => gone().into(),
41
        other => other.into(),
42
    }
43
1443
}
44

            
45
3936
pub(super) fn found<T>(row: Option<T>, gone: fn() -> CmdError) -> Result<T, Attempt> {
46
3936
    row.ok_or_else(|| gone().into())
47
3936
}