1
//! Why one DB-transaction attempt of a lock-protocol writer did not commit,
2
//! and the bound on how often it runs again.
3

            
4
use crate::db::DBError;
5
use crate::error::ServerError;
6
use crate::tag::lock::{ATTEMPTS, KeyChanged};
7

            
8
pub(crate) enum Attempt<E> {
9
    Retry,
10
    Failed(E),
11
}
12

            
13
impl<E> Attempt<E> {
14
    /// A tag-lock outcome as an attempt: a changed key and a `retryable`
15
    /// failure run again, any other failure is `fail`ed.
16
346374
    pub(crate) fn of<T, X>(
17
346374
        outcome: Result<Result<T, KeyChanged>, X>,
18
346374
        retryable: fn(&X) -> bool,
19
346374
        fail: fn(X) -> E,
20
346374
    ) -> Result<T, Self> {
21
346374
        match outcome {
22
343259
            Ok(Ok(done)) => Ok(done),
23
78
            Ok(Err(KeyChanged)) => Err(Self::Retry),
24
3037
            Err(err) if retryable(&err) => Err(Self::Retry),
25
3034
            Err(err) => Err(Self::Failed(fail(err))),
26
        }
27
346374
    }
28
}
29

            
30
/// The attempts a writer may still make.
31
pub(crate) struct Tries(usize);
32

            
33
impl Default for Tries {
34
400902
    fn default() -> Self {
35
400902
        Self(ATTEMPTS)
36
400902
    }
37
}
38

            
39
impl Tries {
40
    /// `Some` once the attempt committed, `None` to try again.
41
380689
    pub(crate) fn step<T, E: From<ServerError>>(
42
380689
        &mut self,
43
380689
        outcome: Result<T, Attempt<E>>,
44
380689
    ) -> Result<Option<T>, E> {
45
380689
        self.0 = self.0.saturating_sub(1);
46
380689
        match (outcome, self.0) {
47
372545
            (Ok(done), _) => Ok(Some(done)),
48
8050
            (Err(Attempt::Failed(err)), _) => Err(err),
49
14
            (Err(Attempt::Retry), 0) => Err(ServerError::DB(DBError::WriteConflict).into()),
50
80
            (Err(Attempt::Retry), _) => Ok(None),
51
        }
52
380689
    }
53
}
54

            
55
#[cfg(test)]
56
#[path = "attempt_tests.rs"]
57
mod tests;