persy/recover.rs
1use crate::{
2 error::{GenericError, PE},
3 journal::recover_impl::RecoverImpl,
4 persy::PersyImpl,
5 Persy, TransactionId,
6};
7use std::sync::Arc;
8
9/// Possible state of a transaction in the log
10#[derive(PartialEq, Eq, Debug, Clone)]
11pub enum RecoverStatus {
12 /// Can't find the start of the transaction so already completed
13 Partial,
14 /// Started but not completed
15 Started,
16 /// Successfully prepared
17 PrepareCommit,
18 /// rollback-ed
19 Rollback,
20 /// Successfully committed after prepared
21 Commit,
22 /// Successfully cleaned up resources after commit
23 Cleanup,
24}
25
26/// Intermediate recover status to select witch transactions to commit or rollback and list witch
27/// transactions are in a intermediate state
28///
29/// # Example
30///
31///
32/// ```rust
33/// # use persy::{Persy,Config};
34/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
35/// # Persy::create("./target/recover_example.persy")?;
36/// let mut recover = Persy::recover("./target/recover_example.persy", Config::new())?;
37/// for (tx_id,status) in recover.list_transactions() {
38/// // Check the transaction if can be committed using the tx_id
39/// if true {
40/// // if so commit the tx
41/// recover.commit(tx_id);
42/// } else {
43/// // otherwise roll back it
44/// recover.rollback(tx_id);
45/// }
46/// // finalize all the transaction marked to finalize and get a persy instance.
47/// }
48/// let persy = recover.finalize()?;
49/// # std::fs::remove_file("./target/recover_example.persy")?;
50/// # Ok(())
51/// # }
52/// ```
53pub struct Recover {
54 recover_impl: RecoverImpl,
55 persy_impl: Arc<PersyImpl>,
56}
57
58impl Recover {
59 pub(crate) fn new(recover_impl: RecoverImpl, persy_impl: Arc<PersyImpl>) -> Recover {
60 Recover {
61 recover_impl,
62 persy_impl,
63 }
64 }
65 /// List all the transactions found in the log with the current status
66 pub fn list_transactions(&self) -> Vec<(TransactionId, RecoverStatus)> {
67 self.recover_impl.list_transactions()
68 }
69 /// Mark to commit a transaction in the log with state prepared commit
70 pub fn commit(&mut self, tx_id: TransactionId) {
71 self.recover_impl.commit(tx_id)
72 }
73 /// Mark to rollback a transaction that is not yet committed
74 pub fn rollback(&mut self, tx_id: TransactionId) {
75 self.recover_impl.rollback(tx_id)
76 }
77 /// Read the status of a transaction in the log
78 pub fn status(&self, tx_id: TransactionId) -> Option<RecoverStatus> {
79 self.recover_impl.status(tx_id)
80 }
81 /// Recover all the prepared committed transactions that are not marked to rollback
82 pub fn finalize(self) -> Result<Persy, PE<GenericError>> {
83 self.persy_impl.final_recover(self.recover_impl)?;
84 Ok(Persy {
85 persy_impl: self.persy_impl,
86 })
87 }
88}