Skip to content

Commit

Permalink
clippy lints and very minor cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
gbmor committed Jan 12, 2020
1 parent db17ebf commit c3c3743
Show file tree
Hide file tree
Showing 11 changed files with 103 additions and 121 deletions.
17 changes: 8 additions & 9 deletions rtcoin-server/src/conn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,8 @@ pub fn init(mut conn: UnixStream, pipe: mpsc::Sender<db::Comm>) {
});
let json_in: Value = json::from_str(&json_in, Some(&mut conn)).unwrap();

match json_in["kind"].to_string().as_ref() {
"quit" => break,
_ => {}
if let "quit" = json_in["kind"].to_string().as_ref() {
break;
}

route(&mut conn, &json_in, &pipe);
Expand All @@ -61,7 +60,7 @@ fn route(conn: &mut UnixStream, json_in: &Value, pipe: &mpsc::Sender<db::Comm>)
let (tx, rx) = mpsc::channel::<db::Reply>();
let comm = json::to_comm(&json_in, tx);

if let None = comm {
if comm.is_none() {
return;
}

Expand All @@ -86,7 +85,7 @@ fn route(conn: &mut UnixStream, json_in: &Value, pipe: &mpsc::Sender<db::Comm>)
if resp.is_none() {
log::info!("Closing client connection");
let out = err::Resp::new(
01,
1,
"Worker Error",
"No response from worker. Closing connection.",
)
Expand All @@ -100,26 +99,26 @@ fn route(conn: &mut UnixStream, json_in: &Value, pipe: &mpsc::Sender<db::Comm>)
}

fn recv(recv: Result<db::Reply, mpsc::RecvError>, conn: &mut UnixStream) -> Option<db::Reply> {
return match recv {
match recv {
Ok(val) => Some(val),
Err(err) => {
let err = format!("{}", err);
let out = err::Resp::new(01, "Worker Error", &err);
let out = err::Resp::new(1, "Worker Error", &err);
let out = out.to_bytes();

conn.write_all(&out).unwrap();
log::error!("Error in Ledger Worker Response: {}", err);
None
}
};
}
}

// Response when the connection worker receives an
// external request specifying the "Disconnect" or
// "Query" actions.
fn invalid_request(conn: &mut UnixStream, kind: &str) {
let details = format!("\"{}\" is not an allowed request type", kind);
let msg = err::Resp::new(03, "Invalid Request", &details);
let msg = err::Resp::new(3, "Invalid Request", &details);
let msg = msg.to_bytes();

log::error!("Received invalid request from client: {}", details);
Expand Down
14 changes: 7 additions & 7 deletions rtcoin-server/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

use std::{path::Path, sync::mpsc};

use log::info;
use log;

use rusqlite::{Connection, OpenFlags, NO_PARAMS};

Expand Down Expand Up @@ -119,14 +119,14 @@ impl Comm {

pub fn kind(&self) -> &Kind {
match &self.kind {
Some(kind) => return &kind,
None => return &Kind::Empty,
Some(kind) => &kind,
None => &Kind::Empty,
}
}
pub fn args(&self) -> Vec<String> {
match &self.args {
Some(args) => return args.clone(),
None => return Vec::<String>::new(),
Some(args) => args.clone(),
None => Vec::<String>::new(),
}
}
}
Expand Down Expand Up @@ -173,7 +173,7 @@ impl DB {
// process the incoming Comms.
pub fn worker_thread(&self) -> Comm {
while let Ok(comm) = self.pipe.recv() {
info!("Ledger Worker :: Received {:?}", comm);
log::info!("Ledger Worker :: Received {:?}", comm);
match comm.kind {
Some(Kind::Register) => user::register(comm.clone(), &self.conn),
Some(Kind::Whoami) => query::whoami(comm.clone(), &self.conn),
Expand All @@ -187,7 +187,7 @@ impl DB {
Some(Kind::Resolve) => {}
Some(Kind::Second) => {}
Some(Kind::Query) => {}
Some(Kind::Disconnect) => return comm.clone(),
Some(Kind::Disconnect) => return comm,
_ => continue,
}
}
Expand Down
27 changes: 11 additions & 16 deletions rtcoin-server/src/err.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,12 @@
// See LICENSE file for detailed license information.
//

use std::{
fmt,
};
use std::fmt;

use log::{
error,
};
use log;

// Used for quickly serializing an error into bytes
// (or string) so that it may be sent across the socket.
// (or string) so that it may be sent across the socket.
// Current error codes:
// 01: Worker error
// 02: Could not parse request as JSON
Expand Down Expand Up @@ -51,9 +47,7 @@ impl Resp {
}

pub fn to_bytes(&self) -> Vec<u8> {
format!("{:#?}", self)
.as_bytes()
.to_owned()
format!("{:#?}", self).as_bytes().to_owned()
}
pub fn code(&self) -> u32 {
self.code
Expand All @@ -69,9 +63,10 @@ impl Resp {
// I found myself writing this same construction
// a few times repeatedly.
pub fn log_then_panic<T>(context: &str, err: T)
where T: fmt::Debug
{
let msg = format!("{}: {:?}", context, err);
error!("{}", msg);
panic!("{}", msg);
}
where
T: fmt::Debug,
{
let msg = format!("{}: {:?}", context, err);
log::error!("{}", msg);
panic!("{}", msg);
}
10 changes: 5 additions & 5 deletions rtcoin-server/src/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::db;
use crate::db::Kind;
use crate::err;

use log::error;
use log;
use serde_json::Value;

// Deserializes a JSON Value struct into a db::Comm,
Expand Down Expand Up @@ -51,19 +51,19 @@ pub fn to_comm(json: &Value, tx: mpsc::Sender<db::Reply>) -> Option<db::Comm> {
// TODO: This is an unnecessary function. I need to get rid of it
// and just call serde_json::from_str() directly
pub fn from_str(json_in: &str, conn: Option<&mut UnixStream>) -> Option<serde_json::Value> {
return match serde_json::from_str(&json_in) {
match serde_json::from_str(&json_in) {
Ok(val) => Some(val),
Err(err) => {
let err = format!("{}", err);
let out = err::Resp::new(02, "JSON Error", &err);
let out = err::Resp::new(2, "JSON Error", &err);

error!("\nError {}:\n{}\n{}", out.code(), out.kind(), out.details(),);
log::error!("\nError {}:\n{}\n{}", out.code(), out.kind(), out.details(),);
let out = out.to_bytes();

if let Some(conn) = conn {
conn.write_all(&out).unwrap();
}
None
}
};
}
}
36 changes: 18 additions & 18 deletions rtcoin-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::{error::Error, fs, os::unix::net::UnixListener, path::Path, process, sy

use ctrlc;

use log::{error, info, warn};
use log;

use num_cpus;
use rpassword;
Expand All @@ -31,7 +31,7 @@ use db::DB;

fn main() -> Result<(), Box<dyn Error>> {
logging::init();
info!("rtcoin-server is initializing.\n");
log::info!("rtcoin-server is initializing.\n");

eprintln!("\nrtcoin-server 0.1-dev");
eprintln!("\nPlease enter the ledger password:");
Expand All @@ -47,43 +47,43 @@ fn main() -> Result<(), Box<dyn Error>> {
eprintln!();
// Create communication channel to the ledger database, then
// spawn the ledger worker to listen for query requests.
info!("Starting ledger worker...");
log::info!("Starting ledger worker...");
let (tx, rx) = mpsc::channel::<db::Comm>();
thread::spawn(move || spawn_ledger_worker(db_key, rx));

// If the socket exists already, remove it.
let sock = Path::new(conn::SOCK);
if fs::metadata(sock).is_ok() {
warn!("Socket {} already exists.", conn::SOCK);
log::warn!("Socket {} already exists.", conn::SOCK);
fs::remove_file(sock)?;
}

// Handle SIGINT / ^C
let ctrlc_tx = tx.clone();
ctrlc::set_handler(move || {
warn!("^C / SIGINT Caught. Cleaning up ...");
log::warn!("^C / SIGINT Caught. Cleaning up ...");
if fs::metadata(sock).is_ok() {
info!("Removing socket file");
log::info!("Removing socket file");
fs::remove_file(sock).unwrap();
}

info!("SIGINT: Sending disconnect signal to ledger worker queue");
log::info!("SIGINT: Sending disconnect signal to ledger worker queue");
let (reply_tx, sigint_rx) = mpsc::channel::<db::Reply>();
let db_disconnect_signal = db::Comm::new(Some(db::Kind::Disconnect), None, Some(reply_tx));

match ctrlc_tx.send(db_disconnect_signal) {
Ok(_) => {}
Err(err) => error!(
Err(err) => log::error!(
"SIGINT: Failed to send disconnect signal to ledger worker: {}",
err
),
}
// Block to allow database to close
sigint_rx.recv().unwrap_or_else(|error| {
warn!("{:?}", error);
log::warn!("{:?}", error);
process::exit(1);
});
info!("¡Hasta luego!");
log::info!("¡Hasta luego!");
process::exit(0);
})
.unwrap_or_else(|error| {
Expand All @@ -93,7 +93,7 @@ fn main() -> Result<(), Box<dyn Error>> {

// Bind to the socket. Spawn a new connection
// worker thread for each client connection.
info!("Binding to socket: {}", conn::SOCK);
log::info!("Binding to socket: {}", conn::SOCK);
spawn_for_connections(&sock, tx);

// Tidy up
Expand All @@ -104,7 +104,7 @@ fn main() -> Result<(), Box<dyn Error>> {
fn spawn_ledger_worker(mut db_key: String, rx: mpsc::Receiver<db::Comm>) {
// This next call opens the actual database connection.
// It also creates the tables if they don't yet exist.
info!("Connecting to database: {}", db::PATH);
log::info!("Connecting to database: {}", db::PATH);
let ledger = DB::connect(db::PATH, db_key.clone(), rx);
db_key.zeroize();

Expand All @@ -113,15 +113,15 @@ fn spawn_ledger_worker(mut db_key: String, rx: mpsc::Receiver<db::Comm>) {
let ledger_worker = thread::Builder::new();
let ledger_worker = ledger_worker.name("Ledger Worker".into());

info!("Starting ledger worker process...");
log::info!("Starting ledger worker process...");
let worker_thread = ledger_worker
.spawn(move || {
// once the worker_thread() method returns,
// begin cleanup. so the whole process can exit.
let disconnect_comm = ledger.worker_thread();
match ledger.conn.close() {
Err(err) => error!("Error closing database connection: {:?}", err),
Ok(_) => info!("Database connection successfully closed"),
Err(err) => log::error!("Error closing database connection: {:?}", err),
Ok(_) => log::info!("Database connection successfully closed"),
}

// Once we've closed the DB connection, let the
Expand All @@ -140,7 +140,7 @@ fn spawn_ledger_worker(mut db_key: String, rx: mpsc::Receiver<db::Comm>) {

// Block execution until the thread we just
// spawned returns.
info!("Startup finished!");
log::info!("Startup finished!");
worker_thread.join().unwrap_or_else(|error| {
err::log_then_panic("Ledger Worker", error);
panic!() // otherwise rustc complains about return type
Expand All @@ -159,14 +159,14 @@ fn spawn_for_connections(sock: &Path, tx: mpsc::Sender<db::Comm>) {
// resource hogs.
let thread_num = num_cpus::get() * 4;
let pool = ThreadPool::with_name("Client Connection".into(), thread_num);
info!("Using pool of {} threads", thread_num);
log::info!("Using pool of {} threads", thread_num);

while let Ok((conn, addr)) = lstnr.accept() {
// This is the channel that allows
// clients to communicate with the
// ledger worker process.
let trx = tx.clone();
info!("New client connection: {:?}", addr);
log::info!("New client connection: {:?}", addr);
pool.execute(move || {
conn::init(conn, trx);
});
Expand Down
Loading

0 comments on commit c3c3743

Please sign in to comment.