Repository navigation
Expand file tree
/
Copy pathbank.rs
More file actions
267 lines (232 loc) · 8 KB
/
Copy pathbank.rs
File metadata and controls
267 lines (232 loc) · 8 KB
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#![allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
use std::{
io::{Read as _, Write},
path::PathBuf,
sync::Arc,
time::SystemTime,
};
use async_trait::async_trait;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use serde::{Deserialize, Serialize};
use switchy::{
fs::sync::{File, OpenOptions},
unsync::{
inject_yields,
sync::{Mutex, RwLock, RwLockReadGuard},
},
};
pub type TransactionId = i32;
pub type BankAccountBalance = Decimal;
pub type CreateTime = u64;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
IO(#[from] std::io::Error),
#[error(transparent)]
SerdeJson(#[from] serde_json::Error),
}
#[async_trait]
pub trait Bank: Send + Sync {
/// # Errors
///
/// * If the `Bank` implementation fails to list the `Transaction`s
async fn list_transactions(
&self,
) -> Result<switchy::unsync::sync::RwLockReadGuard<Vec<Transaction>>, Error>;
/// # Errors
///
/// * If the `Bank` implementation fails to get the `Transaction`
async fn get_transaction(&self, id: TransactionId) -> Result<Option<Transaction>, Error>;
/// # Errors
///
/// * If the `Bank` implementation fails to create the `Transaction`
async fn create_transaction(&self, amount: Decimal) -> Result<Transaction, Error>;
/// # Errors
///
/// * If the `Bank` implementation fails to void the `Transaction`
async fn void_transaction(&self, id: TransactionId) -> Result<Option<Transaction>, Error>;
/// # Errors
///
/// * If the `Bank` implementation fails to get the balance
async fn get_balance(&self) -> Result<BankAccountBalance, Error>;
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Transaction {
pub id: TransactionId,
pub amount: Decimal,
pub created_at: CreateTime,
}
impl std::fmt::Display for Transaction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"id={} created_at={} amount=${:.2}",
self.id, self.created_at, self.amount
))
}
}
#[derive(Debug, thiserror::Error)]
pub enum TransactionFromStrError {
#[error("Missing id")]
MissingId,
#[error("Missing created_at")]
MissingCreatedAt,
#[error("Missing amount")]
MissingAmount,
#[error(transparent)]
ParseInt(#[from] std::num::ParseIntError),
#[error(transparent)]
FromStrDecimal(#[from] rust_decimal::Error),
}
impl std::str::FromStr for Transaction {
type Err = TransactionFromStrError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut components = s.split(' ');
let id = components
.next()
.ok_or(TransactionFromStrError::MissingId)?;
let id = &id["id=".len()..];
let id = id.parse::<TransactionId>()?;
let created_at = components
.next()
.ok_or(TransactionFromStrError::MissingCreatedAt)?;
let created_at = &created_at["created_at=".len()..];
let created_at = created_at.parse::<CreateTime>()?;
let amount = components
.next()
.ok_or(TransactionFromStrError::MissingCreatedAt)?;
let amount = &amount["amount=$".len()..];
let amount = Decimal::from_str(amount)?;
Ok(Self {
id,
amount,
created_at,
})
}
}
#[derive(Clone)]
pub struct LocalBank {
file: Arc<Mutex<File>>,
transactions: Arc<RwLock<Vec<Transaction>>>,
current_id: Arc<RwLock<TransactionId>>,
balance: Arc<RwLock<BankAccountBalance>>,
}
impl LocalBank {
/// # Errors
///
/// * If there is IO error reading existing transactions from the filesystem
pub fn new() -> Result<Self, std::io::Error> {
let mut file = OpenOptions::new()
.create(true)
.read(true)
.write(true)
.truncate(false)
.open(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("transactions.db"))?;
let mut transactions = String::new();
file.read_to_string(&mut transactions)?;
let transactions = transactions
.split('\n')
.filter(|x| !x.is_empty())
.map(serde_json::from_str)
.collect::<Result<Vec<Transaction>, _>>()?;
Ok(Self {
file: Arc::new(Mutex::new(file)),
current_id: Arc::new(RwLock::new(transactions.last().map_or(1, |x| x.id + 1))),
transactions: Arc::new(RwLock::new(transactions)),
balance: Arc::new(RwLock::new(dec!(0.0))),
})
}
}
#[inject_yields]
#[async_trait]
impl Bank for LocalBank {
async fn list_transactions(&self) -> Result<RwLockReadGuard<Vec<Transaction>>, Error> {
Ok(self.transactions.read().await)
}
async fn get_transaction(&self, id: TransactionId) -> Result<Option<Transaction>, Error> {
log::debug!("get_transaction: id={id}");
Ok(self
.transactions
.read()
.await
.iter()
.find(|x| x.id == id)
.cloned())
}
async fn create_transaction(&self, amount: Decimal) -> Result<Transaction, Error> {
log::debug!("create_transaction: amount={amount}");
let mut binding = self.current_id.write().await;
let id = *binding;
*binding += 1;
let now = switchy::time::now();
let seconds_since_epoch = now
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs();
let transaction = Transaction {
id,
amount,
created_at: seconds_since_epoch as CreateTime,
};
{
let binding = self.transactions.read().await;
if let Some(last_transaction) = binding.last() {
assert!(
transaction.created_at >= last_transaction.created_at,
"expected transaction.created_at={} >= last_transaction.created_at={}",
transaction.created_at,
last_transaction.created_at,
);
assert!(
transaction.id == last_transaction.id + 1,
"expected id to be least transaction.id + 1 last_transaction.id={} to transaction_id={}",
last_transaction.id,
transaction.id,
);
}
drop(binding);
}
assert!(
transaction.created_at > 0,
"created_at={} must be > 0",
transaction.created_at
);
assert!(
seconds_since_epoch >= transaction.created_at as u64,
"Time went backwards {now:?} seconds_since_epoch={seconds_since_epoch} created_at={}",
transaction.created_at,
);
let mut serialized = serde_json::to_string(&transaction)?;
serialized.push('\n');
self.file.lock().await.write_all(serialized.as_bytes())?;
*self.balance.write().await += transaction.amount;
self.transactions.write().await.push(transaction.clone());
drop(binding);
Ok(transaction)
}
async fn void_transaction(&self, id: TransactionId) -> Result<Option<Transaction>, Error> {
log::debug!("void_transaction: id={id}");
let Some(existing) = self
.transactions
.read()
.await
.iter()
.find(|x| x.id == id)
.cloned()
else {
return Ok(None);
};
let originally_created_at = existing.created_at;
let new_transaction = self.create_transaction(-existing.amount).await?;
assert!(
new_transaction.created_at >= originally_created_at,
"Time went backwards new_transaction.created_at={} originally_created_at={originally_created_at}",
new_transaction.created_at
);
Ok(Some(new_transaction))
}
async fn get_balance(&self) -> Result<BankAccountBalance, Error> {
log::debug!("get_balance");
Ok(*self.balance.read().await)
}
}