p2panda_store/
transactions.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Trait definitions for atomic write transactions.
4
5/// Store implementation returning an atomic transaction object for fail-safe writes.
6pub trait WritableStore {
7    /// Error type from store.
8    type Error;
9
10    /// Store type for fail-safe transactions.
11    type Transaction<'c>: Transaction;
12
13    /// Returns new transaction object to "begin" a single, atomic write transaction which is
14    /// finally "committed" into the store.
15    fn begin<'c>(&mut self) -> impl Future<Output = Result<Self::Transaction<'c>, Self::Error>>;
16}
17
18/// Writes state changes into a store as part of an atomic transaction.
19///
20/// Developers should implement this trait on types which represent state which needs persisting or
21/// the "delta" which needs changing. On `write` the concrete query (for example a SQL insert or
22/// update) is executed as part of an atomic transaction.
23///
24/// The "written" object can usually be dropped after a successful transaction.
25pub trait WriteToStore<S: WritableStore> {
26    fn write(&self, tx: &mut S::Transaction<'_>) -> impl Future<Output = Result<(), S::Error>>;
27}
28
29/// Organises multiple "writes" to a store into one atomic transaction.
30pub trait Transaction {
31    /// Error type from store which can occur when writing to it or rolling back.
32    type Error;
33
34    /// Finally "commits" all writes to the store as one single "transaction".
35    fn commit(self) -> impl Future<Output = Result<(), Self::Error>>;
36
37    /// Aborts writing to the store and "rolls back" all changes. This should automatically be
38    /// called on `Drop`.
39    fn rollback(self) -> impl Future<Output = Result<(), Self::Error>>;
40}