diff --git a/crates/lox-distributor/src/file_reader.rs b/crates/lox-distributor/src/file_reader.rs new file mode 100644 index 0000000..7eb0844 --- /dev/null +++ b/crates/lox-distributor/src/file_reader.rs @@ -0,0 +1,38 @@ +use crate::lox_context; +use chrono::prelude::*; +use std::{ + env, + error::Error, + fs::{DirEntry, File}, + io::BufReader, + path::Path, +}; + +pub fn read_context_from_file>( + path: P, +) -> Result> { + let file = File::open(path)?; + let reader = BufReader::new(file); + let context = serde_json::from_reader(reader)?; + Ok(context) +} + +pub fn write_context_to_file(context: lox_context::LoxServerContext) { + let mut date = Local::now().format("%Y-%m-%d_%H:%M:%S").to_string(); + let path = "_lox.json"; + date.push_str(path); + let file = File::create(&date).expect("Unable to write to file!"); + let _ = serde_json::to_writer(file, &context); +} + +pub fn check_db_exists() -> Option { + let current_path = env::current_dir().expect("Unable to access current dir"); + std::fs::read_dir(current_path) + .expect("Couldn't read local directory") + .flatten() // Remove failed + .filter(|f| { + f.metadata().unwrap().is_file() + && (f.file_name().into_string().unwrap().contains("_lox.json")) + }) // Filter out directories (only consider files) + .max_by_key(|x| x.metadata().unwrap().modified().unwrap()) +} diff --git a/crates/lox-distributor/src/main.rs b/crates/lox-distributor/src/main.rs index ece2d32..d516a3d 100644 --- a/crates/lox-distributor/src/main.rs +++ b/crates/lox-distributor/src/main.rs @@ -1,4 +1,4 @@ -use chrono::{prelude::*, Utc}; +use chrono::Utc; use clap::Parser; use futures::future; use futures::StreamExt; @@ -12,18 +12,19 @@ use lox_library::{BridgeAuth, BridgeDb}; use rdsys_backend::{proto::ResourceDiff, start_stream}; use serde::Deserialize; -use std::env; + use std::{ convert::Infallible, - error::Error, fs::File, io::BufReader, net::SocketAddr, - path::{Path, PathBuf}, + path::PathBuf, sync::{Arc, Mutex}, time::Duration, }; +mod file_reader; +use file_reader::{check_db_exists, read_context_from_file, write_context_to_file}; mod lox_context; mod request_handler; use request_handler::handle; @@ -122,15 +123,6 @@ async fn create_context_manager( } } -fn read_context_from_file>( - path: P, -) -> Result> { - let file = File::open(path)?; - let reader = BufReader::new(file); - let context = serde_json::from_reader(reader)?; - Ok(context) -} - // Context Manager handles the Lox BridgeDB and Bridge Authority, ensuring // that the DB can be updated from the rdsys stream and client requests // can be responded to with an updated BridgeDB state @@ -138,29 +130,17 @@ async fn context_manager(db_path: Option, mut context_rx: mpsc::Receive let context: lox_context::LoxServerContext; if let Some(existing_db) = db_path.as_deref() { context = read_context_from_file(existing_db).unwrap(); + } else if let Some(last_modified_file) = check_db_exists() { + println!("Reading from file {:?}", last_modified_file); + context = read_context_from_file(&last_modified_file.path()).unwrap(); } else { - let current_path = env::current_dir().expect("Unable to access current dir"); - if let Some(last_modified_file) = std::fs::read_dir(current_path) - .expect("Couldn't read local directory") - .flatten() // Remove failed - .filter(|f| { - f.metadata().unwrap().is_file() - && (f.file_name().into_string().unwrap().contains("_lox.json")) - }) // Filter out directories (only consider files) - .max_by_key(|x| x.metadata().unwrap().modified().unwrap()) - // Get the most recently modified file - { - println!("Reading from file {:?}", last_modified_file); - context = read_context_from_file(&last_modified_file.path()).unwrap(); - } else { - let new_db = BridgeDb::new(); - let new_ba = BridgeAuth::new(new_db.pubkey); - context = lox_context::LoxServerContext { - db: Arc::new(Mutex::new(new_db)), - ba: Arc::new(Mutex::new(new_ba)), - extra_bridges: Arc::new(Mutex::new(Vec::new())), - to_be_replaced_bridges: Arc::new(Mutex::new(Vec::new())), - }; + let new_db = BridgeDb::new(); + let new_ba = BridgeAuth::new(new_db.pubkey); + context = lox_context::LoxServerContext { + db: Arc::new(Mutex::new(new_db)), + ba: Arc::new(Mutex::new(new_ba)), + extra_bridges: Arc::new(Mutex::new(Vec::new())), + to_be_replaced_bridges: Arc::new(Mutex::new(Vec::new())), } } @@ -309,12 +289,7 @@ async fn context_manager(db_path: Option, mut context_rx: mpsc::Receive */ context.allocate_leftover_bridges(); context.encrypt_table(); - let mut date = Local::now().format("%Y-%m-%d_%H:%M:%S").to_string(); - let path = "_lox.json"; - date.push_str(path); - let file = File::create(&date).expect("Unable to write to file!"); - let _ = serde_json::to_writer(file, &context); - + write_context_to_file(context.clone()); sleep(Duration::from_millis(1)).await; } Request { req, sender } => { diff --git a/crates/lox-distributor/src/request_handler.rs b/crates/lox-distributor/src/request_handler.rs index f47ea3c..5416b36 100644 --- a/crates/lox-distributor/src/request_handler.rs +++ b/crates/lox-distributor/src/request_handler.rs @@ -81,7 +81,6 @@ mod tests { cred::BucketReachability, proto, BridgeAuth, BridgeDb, }; - use rand::RngCore; use std::sync::{Arc, Mutex}; @@ -127,7 +126,6 @@ mod tests { fn openinvite(&self, request: proto::open_invite::Request) -> Request { let req_str = serde_json::to_string(&request).unwrap(); - Request::builder() .header("Content-Type", "application/json") .method("POST") @@ -138,7 +136,6 @@ mod tests { fn trustpromo(&self, request: proto::trust_promotion::Request) -> Request { let req_str = serde_json::to_string(&request).unwrap(); - Request::builder() .header("Content-Type", "application/json") .method("POST") @@ -149,7 +146,6 @@ mod tests { fn trustmigration(&self, request: proto::migration::Request) -> Request { let req_str = serde_json::to_string(&request).unwrap(); - Request::builder() .header("Content-Type", "application/json") .method("POST") @@ -160,7 +156,6 @@ mod tests { fn levelup(&self, request: proto::level_up::Request) -> Request { let req_str = serde_json::to_string(&request).unwrap(); - Request::builder() .header("Content-Type", "application/json") .method("POST") @@ -171,7 +166,6 @@ mod tests { fn issueinvite(&self, request: proto::issue_invite::Request) -> Request { let req_str = serde_json::to_string(&request).unwrap(); - Request::builder() .header("Content-Type", "application/json") .method("POST") @@ -182,7 +176,6 @@ mod tests { fn redeeminvite(&self, request: proto::redeem_invite::Request) -> Request { let req_str = serde_json::to_string(&request).unwrap(); - Request::builder() .header("Content-Type", "application/json") .method("POST") @@ -193,7 +186,6 @@ mod tests { fn checkblockage(&self, request: proto::check_blockage::Request) -> Request { let req_str = serde_json::to_string(&request).unwrap(); - Request::builder() .header("Content-Type", "application/json") .method("POST") @@ -204,7 +196,6 @@ mod tests { fn blockagemigration(&self, request: proto::blockage_migration::Request) -> Request { let req_str = serde_json::to_string(&request).unwrap(); - Request::builder() .header("Content-Type", "application/json") .method("POST") diff --git a/crates/lox-library/src/lib.rs b/crates/lox-library/src/lib.rs index 57c092d..2704c0e 100644 --- a/crates/lox-library/src/lib.rs +++ b/crates/lox-library/src/lib.rs @@ -686,7 +686,9 @@ impl BridgeAuth { .any(|&x| x.1 + EXPIRY_DATE < self.today()) { // If there are expired blockages, separate them from the fresh blockages - let (expired, fresh): (Vec<(u32, u32)>, Vec<(u32, u32)>) = self.bridge_table.blocked_keys + let (expired, fresh): (Vec<(u32, u32)>, Vec<(u32, u32)>) = self + .bridge_table + .blocked_keys .iter() .partition(|&x| x.1 + EXPIRY_DATE < self.today()); for item in expired { @@ -738,7 +740,9 @@ impl BridgeAuth { //Perhaps EXPIRY_DATE should be changed to an earlier time { // If so, separate them from the fresh open invitation indexes - let (expired, fresh): (Vec<(u32, u32)>, Vec<(u32, u32)>) = self.bridge_table.open_inv_keys + let (expired, fresh): (Vec<(u32, u32)>, Vec<(u32, u32)>) = self + .bridge_table + .open_inv_keys .iter() .partition(|&x| x.1 + EXPIRY_DATE < self.today()); for item in expired {