1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
|
use std::{fmt::Display, mem};
use crate::app::App;
use chrono::Utc;
use log::{debug, trace};
use serde::{Serialize, de::DeserializeOwned};
use sqlx::{SqliteConnection, query};
pub(crate) mod barcode;
pub(crate) mod product;
pub(crate) mod product_parent;
pub(crate) mod unit;
pub(crate) mod unit_property;
pub(crate) mod recipe;
pub(crate) trait Transactionable:
Sized + std::fmt::Debug + Serialize + DeserializeOwned
{
type ApplyError: std::error::Error + Display;
type UndoError: std::error::Error + Display;
/// Apply this transaction.
///
/// This should change the db state.
async fn apply(self, txn: &mut SqliteConnection) -> Result<(), Self::ApplyError>;
/// Undo this transaction.
///
/// This should return the db to the state it was in before this transaction.
async fn undo(self, txn: &mut SqliteConnection) -> Result<(), Self::UndoError>;
}
#[derive(Debug)]
pub(crate) struct Operations<O: Transactionable> {
name: &'static str,
ops: Vec<O>,
}
impl<O: Transactionable> Default for Operations<O> {
fn default() -> Self {
Self::new("<default impl>")
}
}
impl<O: Transactionable> Operations<O> {
#[must_use]
pub(crate) fn new(name: &'static str) -> Self {
Self {
name,
ops: Vec::new(),
}
}
pub(crate) async fn apply(mut self, app: &App) -> Result<(), apply::Error<O>> {
let ops = mem::take(&mut self.ops);
if ops.is_empty() {
return Ok(());
}
trace!("Begin commit of {}", self.name);
let mut txn = app.db.begin().await?;
for op in ops {
trace!("Commiting operation: {op:?}");
add_operation_to_txn_log(&op, &mut txn).await?;
op.apply(&mut txn)
.await
.map_err(|err| apply::Error::InnerApply(err))?;
}
txn.commit().await?;
trace!("End commit of {}", self.name);
Ok(())
}
pub(crate) fn push(&mut self, op: O) {
self.ops.push(op);
}
}
pub(crate) mod apply {
use actix_web::{ResponseError, http::header::HeaderValue};
use log::error;
use crate::storage::sql::insert::{Transactionable, add_operations_to_txn_log};
#[derive(thiserror::Error, Debug)]
pub(crate) enum Error<O: Transactionable> {
#[error("Failed to execute sql statments")]
Sql(#[from] sqlx::Error),
#[error("Failed to append operations to the txn log: {0}")]
TxnLogAppend(#[from] add_operations_to_txn_log::Error),
#[error("Failed to apply one of the operations: {0}")]
InnerApply(<O as Transactionable>::ApplyError),
}
impl<O: Transactionable> ResponseError for Error<O> {
fn status_code(&self) -> actix_web::http::StatusCode {
actix_web::http::StatusCode::INTERNAL_SERVER_ERROR
}
fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> {
error!("Emmiting `INTERNAL_SERVER_ERROR`: {self}");
let mut res =
actix_web::HttpResponse::new(self.status_code()).set_body(self.to_string());
let mime = actix_web::mime::TEXT_PLAIN_UTF_8;
res.headers_mut().insert(
actix_web::http::header::CONTENT_TYPE,
HeaderValue::from_str(mime.to_string().as_str()).expect("Hard-coded conversion"),
);
res.set_body(actix_web::body::BoxBody::new(self.to_string()))
}
}
}
impl<O: Transactionable> Drop for Operations<O> {
fn drop(&mut self) {
assert!(
self.ops.is_empty(),
"Trying to drop uncommitted operations (name: {}) ({:#?}). This is a bug.",
self.name,
self.ops
);
}
}
async fn add_operation_to_txn_log<O: Transactionable>(
operation: &O,
txn: &mut SqliteConnection,
) -> Result<(), add_operations_to_txn_log::Error> {
debug!("Adding operation to txn log: {operation:?}");
let now = Utc::now().timestamp();
let operation = serde_json::to_string(&operation).expect("should be serializable");
query!(
r#"
INSERT INTO txn_log (
timestamp,
operation
)
VALUES (?, ?);
"#,
now,
operation,
)
.execute(txn)
.await?;
Ok(())
}
pub(crate) mod add_operations_to_txn_log {
#[derive(thiserror::Error, Debug)]
pub(crate) enum Error {
#[error("Failed to execute sql statments")]
SqlError(#[from] sqlx::Error),
}
}
|