2021-02-03 17:40:06 -08:00
|
|
|
use crate::operations::ServerOperation;
|
2021-02-08 09:33:24 -08:00
|
|
|
use anyhow::{bail, Result};
|
2021-02-03 17:40:06 -08:00
|
|
|
use bytes::BytesMut;
|
2021-02-08 09:33:24 -08:00
|
|
|
use log::{debug, error, info};
|
|
|
|
use operations::{MarketOperation, QueryOperation, UserOperation};
|
|
|
|
use sqlx::PgPool;
|
|
|
|
use state::AppState;
|
|
|
|
use std::env;
|
|
|
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
2021-02-03 17:40:06 -08:00
|
|
|
use tokio::net::{TcpListener, TcpStream};
|
|
|
|
use tokio_stream::{wrappers::TcpListenerStream, StreamExt};
|
|
|
|
|
2021-02-08 09:33:24 -08:00
|
|
|
mod market;
|
2021-02-03 17:40:06 -08:00
|
|
|
mod operations;
|
2021-02-08 09:33:24 -08:00
|
|
|
mod state;
|
|
|
|
mod user;
|
2021-02-03 17:40:06 -08:00
|
|
|
|
|
|
|
#[tokio::main]
|
|
|
|
async fn main() -> Result<()> {
|
2021-02-08 09:33:24 -08:00
|
|
|
dotenv::dotenv().ok();
|
|
|
|
// If we can't successfully initialize our crypto library, fail immediately.
|
|
|
|
sodiumoxide::init().unwrap();
|
2021-02-03 17:40:06 -08:00
|
|
|
simple_logger::SimpleLogger::default().init()?;
|
|
|
|
|
2021-02-08 09:33:24 -08:00
|
|
|
let mut listener_stream = TcpListener::bind(&env::var("BIND_ADDRESS")?)
|
2021-02-03 17:40:06 -08:00
|
|
|
.await
|
|
|
|
.map(TcpListenerStream::new)?;
|
|
|
|
|
2021-02-08 09:33:24 -08:00
|
|
|
info!("Successfully bound to port.");
|
|
|
|
|
|
|
|
let db_pool = PgPool::connect(&env::var("DATABASE_URL")?).await?;
|
|
|
|
|
|
|
|
info!("Successfully established connection to database.");
|
2021-02-03 17:40:06 -08:00
|
|
|
|
|
|
|
while let Some(Ok(stream)) = listener_stream.next().await {
|
2021-02-08 09:33:24 -08:00
|
|
|
// clone simply clones the arc reference, so this is cheap.
|
|
|
|
let db_pool = db_pool.clone();
|
2021-02-03 17:40:06 -08:00
|
|
|
tokio::task::spawn(async {
|
2021-02-08 09:33:24 -08:00
|
|
|
match handle_stream(stream, db_pool).await {
|
2021-02-03 17:40:06 -08:00
|
|
|
Ok(_) => (),
|
2021-02-08 09:33:24 -08:00
|
|
|
Err(e) => {
|
|
|
|
// stream.write_all(e);
|
|
|
|
error!("{}", e);
|
|
|
|
}
|
2021-02-03 17:40:06 -08:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
info!("Cleanly shut down. Goodbye!");
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2021-02-08 09:33:24 -08:00
|
|
|
async fn handle_stream(mut socket: TcpStream, pool: PgPool) -> Result<()> {
|
2021-02-03 17:40:06 -08:00
|
|
|
// only accept data that can fit in 256 bytes
|
2021-02-08 09:33:24 -08:00
|
|
|
// the assumption is that a single request should always be within n bytes,
|
|
|
|
// otherwise there's a good chance that it's mal{formed,icious}.
|
2021-02-03 17:40:06 -08:00
|
|
|
let mut buffer = BytesMut::with_capacity(256);
|
2021-02-08 09:33:24 -08:00
|
|
|
let mut state = AppState::new();
|
2021-02-03 17:40:06 -08:00
|
|
|
loop {
|
|
|
|
let bytes_read = socket.read_buf(&mut buffer).await?;
|
2021-02-08 09:33:24 -08:00
|
|
|
if bytes_read == 0 {
|
|
|
|
bail!("Failed to read bytes, assuming socket is closed.")
|
2021-02-03 17:40:06 -08:00
|
|
|
}
|
2021-02-08 09:33:24 -08:00
|
|
|
let data = buffer.split_to(bytes_read); // O(1)
|
|
|
|
let parsed = serde_json::from_slice::<ServerOperation>(&data)?;
|
|
|
|
debug!("Parsed operation: {:?}", parsed);
|
|
|
|
let response = match parsed {
|
|
|
|
ServerOperation::Query(op) => match op {
|
2021-02-08 15:58:46 -08:00
|
|
|
QueryOperation::StockInfo { stock } => state.stock_info(stock, &pool).await?,
|
2021-02-08 16:37:19 -08:00
|
|
|
QueryOperation::User(username) => state.user_info(username, &pool).await?,
|
2021-02-08 09:33:24 -08:00
|
|
|
},
|
|
|
|
ServerOperation::User(op) => match op {
|
|
|
|
UserOperation::Login { api_key } => state.login(api_key, &pool).await?,
|
|
|
|
UserOperation::Register { username, password } => {
|
|
|
|
state.register(username, password, &pool).await?
|
|
|
|
}
|
|
|
|
UserOperation::GetKey { username, password } => {
|
|
|
|
state.generate_api_key(username, password, &pool).await?
|
|
|
|
}
|
|
|
|
},
|
|
|
|
ServerOperation::Market(op) => match op {
|
2021-02-08 15:58:46 -08:00
|
|
|
MarketOperation::Buy(stock_name) => state.buy(stock_name, &pool)?,
|
|
|
|
MarketOperation::Sell(stock_name) => state.sell(stock_name, &pool)?,
|
2021-02-08 09:33:24 -08:00
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
socket
|
|
|
|
.write_all(serde_json::to_string(&response).unwrap().as_bytes())
|
|
|
|
.await?;
|
|
|
|
buffer.unsplit(data); // O(1)
|
2021-02-03 17:40:06 -08:00
|
|
|
buffer.clear();
|
|
|
|
}
|
|
|
|
}
|