-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
306 lines (272 loc) · 9.43 KB
/
Copy pathlib.rs
File metadata and controls
306 lines (272 loc) · 9.43 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
#![cfg_attr(feature = "fail-on-warnings", deny(warnings))]
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
#![allow(clippy::multiple_crate_versions)]
use std::{
str::{self, FromStr as _},
string::FromUtf8Error,
sync::LazyLock,
};
use bank::{Bank, LocalBank, TransactionId};
use rust_decimal::Decimal;
use strum::{AsRefStr, EnumString, ParseError};
use switchy::{
tcp::{GenericTcpListener, GenericTcpStream, TcpListener},
unsync::{
inject_yields,
io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
task,
util::CancellationToken,
},
};
pub mod bank;
pub static SERVER_CANCELLATION_TOKEN: LazyLock<CancellationToken> =
LazyLock::new(CancellationToken::new);
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
Async(#[from] switchy::unsync::Error),
#[error(transparent)]
IO(#[from] std::io::Error),
#[error(transparent)]
FromUtf8(#[from] FromUtf8Error),
#[error(transparent)]
Parse(#[from] ParseError),
#[error(transparent)]
Tcp(#[from] switchy::tcp::Error),
#[error(transparent)]
Decimal(#[from] rust_decimal::Error),
#[error(transparent)]
Bank(#[from] bank::Error),
#[error(transparent)]
ParseInt(#[from] std::num::ParseIntError),
}
#[derive(Debug, EnumString, AsRefStr)]
#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
pub enum ServerAction {
Health,
ListTransactions,
GetTransaction,
CreateTransaction,
VoidTransaction,
GetBalance,
Close,
Exit,
}
impl std::fmt::Display for ServerAction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_ref())
}
}
/// # Errors
///
/// * If the `TcpListener` fails to bind
/// * If the server TCP loop produces an error
#[inject_yields]
pub async fn run(addr: impl Into<String>) -> Result<(), Error> {
let addr = addr.into();
let listener = TcpListener::bind(&addr).await?;
log::info!("Server listening on {addr}");
let bank = LocalBank::new()?;
SERVER_CANCELLATION_TOKEN
.run_until_cancelled(async move {
while let Ok((stream, addr)) = listener.accept().await {
log::debug!("client connected");
let (mut read, mut write) = stream.into_split();
let mut message = String::new();
let bank = bank.clone();
task::spawn(async move {
while let Ok(Some(action)) = read_message(&mut message, &mut read).await {
log::debug!("[{addr}] parsing action={action}");
let Ok(action) = ServerAction::from_str(&action).inspect_err(|_| {
log::error!("[{addr}] Invalid action '{action}'");
}) else {
continue;
};
log::info!("[{addr}] received {action} action");
let resp = match action {
ServerAction::Health => health(&mut write).await,
ServerAction::ListTransactions => {
list_transactions(&bank, &mut write).await
}
ServerAction::GetTransaction => {
get_transaction(&bank, &mut message, &mut write, &mut read).await
}
ServerAction::CreateTransaction => {
create_transaction(&bank, &mut message, &mut write, &mut read).await
}
ServerAction::VoidTransaction => {
void_transaction(&bank, &mut message, &mut write, &mut read).await
}
ServerAction::GetBalance => get_balance(&bank, &mut write).await,
ServerAction::Close => {
return;
}
ServerAction::Exit => {
SERVER_CANCELLATION_TOKEN.cancel();
return;
}
};
if let Err(e) = resp {
log::error!("[{addr}] Failed to handle action={action}: {e:?}");
}
}
log::debug!("[{addr}] client connection connection dropped");
});
}
log::debug!("server finished");
Ok::<_, Error>(())
})
.await
.transpose()?;
log::debug!("run finished");
Ok(())
}
#[inject_yields]
async fn read_message(
message: &mut String,
reader: &mut (impl AsyncRead + Unpin),
) -> Result<Option<String>, Error> {
if let Some(index) = message.chars().position(|x| x == 0 as char) {
let mut remaining = message.split_off(index);
let value = message.clone();
remaining.remove(0);
*message = remaining;
return Ok(Some(value));
}
let mut buf = [0_u8; 1024];
Ok(loop {
let count = match reader.read(&mut buf).await {
Ok(count) => count,
Err(e) => {
log::error!("read_message: failed to read from stream: {e:?}");
break None;
}
};
if count == 0 {
log::debug!("read_message: received empty response");
break None;
}
log::trace!("read count={count}");
let value = String::from_utf8(buf[..count].to_vec())?;
message.push_str(&value);
if let Some(index) = value.chars().position(|x| x == 0 as char) {
let mut remaining = message.split_off(message.len() - value.len() + index);
let value = message.clone();
remaining.remove(0);
*message = remaining;
break Some(value);
}
})
}
#[inject_yields]
async fn write_message(
message: impl Into<String>,
stream: &mut (impl AsyncWrite + Unpin),
) -> Result<(), Error> {
let message = message.into();
log::debug!("write_message: writing message={message}");
let mut bytes = message.into_bytes();
bytes.push(0_u8);
Ok(stream.write_all(&bytes).await?)
}
#[inject_yields]
async fn list_transactions(
bank: &impl Bank,
writer: &mut (impl AsyncWrite + Unpin),
) -> Result<(), Error> {
let message = {
let transactions = bank.list_transactions().await?;
if transactions.is_empty() {
log::debug!("list_transactions: no transactions");
}
transactions
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join("\n")
};
write_message(message, writer).await?;
Ok(())
}
#[inject_yields]
async fn get_transaction(
bank: &impl Bank,
message: &mut String,
writer: &mut (impl AsyncWrite + Unpin),
reader: &mut (impl AsyncRead + Unpin),
) -> Result<(), Error> {
write_message("Enter the transaction ID:", writer).await?;
let Some(message) = read_message(message, reader).await? else {
use std::io::{Error, ErrorKind};
return Err(Error::new(
ErrorKind::NotFound,
"get_transaction: No message received from TCP client",
)
.into());
};
let id = message.parse::<TransactionId>()?;
if let Some(transaction) = bank.get_transaction(id).await? {
write_message(transaction.to_string(), writer).await?;
} else {
write_message("Transaction not found", writer).await?;
}
Ok(())
}
#[inject_yields]
async fn create_transaction(
bank: &impl Bank,
message: &mut String,
writer: &mut (impl AsyncWrite + Unpin),
reader: &mut (impl AsyncRead + Unpin),
) -> Result<(), Error> {
write_message("Enter the transaction amount:", writer).await?;
let Some(message) = read_message(message, reader).await? else {
use std::io::{Error, ErrorKind};
return Err(Error::new(
ErrorKind::NotFound,
"create_transaction: No message received from TCP client",
)
.into());
};
let transaction = bank
.create_transaction(Decimal::from_str(&message)?)
.await?;
write_message(transaction.to_string(), writer).await?;
Ok(())
}
#[inject_yields]
async fn void_transaction(
bank: &impl Bank,
message: &mut String,
writer: &mut (impl AsyncWrite + Unpin),
reader: &mut (impl AsyncRead + Unpin),
) -> Result<(), Error> {
write_message("Enter the transaction ID:", writer).await?;
let Some(message) = read_message(message, reader).await? else {
use std::io::{Error, ErrorKind};
return Err(Error::new(
ErrorKind::NotFound,
"void_transaction: No message received from TCP client",
)
.into());
};
let id = message.parse::<TransactionId>()?;
if let Some(transaction) = bank.void_transaction(id).await? {
write_message(transaction.to_string(), writer).await?;
} else {
write_message("Transaction not found", writer).await?;
}
Ok(())
}
#[inject_yields]
async fn health(stream: &mut (impl AsyncWrite + Unpin)) -> Result<(), Error> {
write_message("healthy", stream).await
}
#[inject_yields]
async fn get_balance(
bank: &impl Bank,
stream: &mut (impl AsyncWrite + Unpin),
) -> Result<(), Error> {
let balance = bank.get_balance().await?;
write_message(format!("${balance}"), stream).await
}