This commit is contained in:
onyinyang 2023-07-21 16:11:10 -04:00
parent 572928a271
commit 35f62ed213
No known key found for this signature in database
GPG Key ID: 156A6435430C2036
4 changed files with 60 additions and 52 deletions

View File

@ -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<P: AsRef<Path>>(
path: P,
) -> Result<lox_context::LoxServerContext, Box<dyn Error>> {
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<DirEntry> {
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())
}

View File

@ -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<P: AsRef<Path>>(
path: P,
) -> Result<lox_context::LoxServerContext, Box<dyn Error>> {
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,18 +130,7 @@ async fn context_manager(db_path: Option<PathBuf>, 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 {
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
{
} 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 {
@ -160,7 +141,6 @@ async fn context_manager(db_path: Option<PathBuf>, mut context_rx: mpsc::Receive
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<PathBuf>, 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 } => {

View File

@ -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<Body> {
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<Body> {
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<Body> {
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<Body> {
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<Body> {
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<Body> {
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<Body> {
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<Body> {
let req_str = serde_json::to_string(&request).unwrap();
Request::builder()
.header("Content-Type", "application/json")
.method("POST")

View File

@ -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 {