Skip to content

Commit

Permalink
add anyhow
Browse files Browse the repository at this point in the history
  • Loading branch information
kfatyuip committed Aug 5, 2024
1 parent 76fea8b commit 256163d
Show file tree
Hide file tree
Showing 6 changed files with 49 additions and 43 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ ip_limit = ["dep:ipnet"]
log = ["dep:log"]

[dependencies]
anyhow = "1.0.86"
async-mutex = "1.4.0"
async-rwlock = "1.3.0"
chrono = { version = "0.4.38", features = ["clock", "now"] }
Expand Down
28 changes: 18 additions & 10 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,22 @@ use clap::{command, Parser};
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
use serde_yml::Value;
use std::{collections::HashMap, env::current_dir, fs, path::PathBuf, sync::{Arc, Mutex}, time::Duration};
use std::{
collections::HashMap,
env::current_dir,
fs,
path::PathBuf,
sync::{Arc, Mutex},
time::Duration,
};

lazy_static! {
pub static ref CONFIG_PATH: Mutex<String> = Mutex::new("".to_owned());
pub static ref DEFAULT_CONFIG: Config = init_config();
pub static ref CONFIG: Arc<RwLock<Config>> = Arc::new(RwLock::new((*DEFAULT_CONFIG).clone()));
pub static ref ARGS: Args = Args::parse();
pub static ref DEFAULT_TICK: Duration = Duration::from_millis(1024);
}

#[derive(Serialize, Deserialize, Clone)]
pub struct Config {
Expand All @@ -27,8 +42,8 @@ impl Default for Config {
info: "Powered by Rust".to_owned(),
root: current_dir().unwrap_or(".".into()),
error_page: Some("404.html".to_owned().into()),
tick: None,
cache: None,
tick: Some(*DEFAULT_TICK),
cache: Some(CacheConfig::default()),
},
allowlist: None,
blocklist: None,
Expand Down Expand Up @@ -99,13 +114,6 @@ pub struct Args {
pub port: Option<i32>,
}

lazy_static! {
pub static ref CONFIG_PATH: Mutex<String> = Mutex::new("".to_owned());
pub static ref DEFAULT_CONFIG: Config = init_config();
pub static ref CONFIG: Arc<RwLock<Config>> = Arc::new(RwLock::new((*DEFAULT_CONFIG).clone()));
pub static ref ARGS: Args = Args::parse();
}

pub fn init_config() -> Config {
let config_path = CONFIG_PATH.lock().unwrap();
let default_config = Config::default();
Expand Down
16 changes: 8 additions & 8 deletions src/init.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
use crate::config::{init_config, CONFIG, DEFAULT_CONFIG};
use crate::config::{init_config, CONFIG, DEFAULT_CONFIG, DEFAULT_TICK};
use anyhow::Result;
use async_mutex::Mutex;
use async_rwlock::RwLock;
use lazy_static::lazy_static;
use log4rs::Handle;
use lru::LruCache;
use signal_hook::{consts::SIGHUP, iterator::Signals};
use std::{
env::set_current_dir, error::Error, io, num::NonZeroUsize, sync::Arc, thread, time::Duration,
};
use std::{env::set_current_dir, error::Error, io, num::NonZeroUsize, sync::Arc, thread};

#[cfg(feature = "log")]
use {
Expand All @@ -22,7 +21,6 @@ use {

lazy_static! {
pub static ref T: Arc<RwLock<Option<i32>>> = Arc::new(RwLock::new(None));
pub static ref DEFAULT_TICK: Duration = Duration::from_millis(1024);
pub static ref LOGGER_HANDLE: Mutex<Option<Handle>> = Mutex::new(None);
}

Expand Down Expand Up @@ -137,15 +135,17 @@ where
}

#[cfg(feature = "log")]
pub async fn init_logger<C>(config: C)
pub async fn init_logger<C>(config: C) -> Result<(), log::SetLoggerError>
where
C: Deref<Target = Config>,
{
let config = build_logger_config(config).await;
*LOGGER_HANDLE.lock().await = Some(log4rs::init_config(config).unwrap())
*LOGGER_HANDLE.lock().await = Some(log4rs::init_config(config)?);

Ok(())
}

pub async fn init_signal() -> Result<(), Box<dyn Error>> {
pub async fn init_signal() -> io::Result<()> {
let mut signals = Signals::new([SIGHUP])?;

tokio::spawn(async move {
Expand Down
29 changes: 11 additions & 18 deletions src/route.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::config::{LocationConfig, CONFIG};
use anyhow::{anyhow, Context, Result};
use serde_yml::from_value;
use std::{
fmt::Write,
io::{ErrorKind, Result},
path::{Path, PathBuf},
};
use tokio::fs::{self, read_dir, DirEntry};
Expand All @@ -18,23 +18,16 @@ pub async fn location_index(path: PathBuf, location: &str) -> Result<String> {

for (s, v) in &config.locations.clone().unwrap_or_default() {
if root_relative(s) == location.trim_end_matches('/') {
match from_value::<LocationConfig>(v.clone()) {
Ok(_location) => {
if let Some(index) = _location.index {
return fs::read_to_string(root_relative(
PathBuf::from(location)
.join(index.clone())
.as_path()
.to_str()
.unwrap(),
))
.await;
} else if _location.auto_index.is_none() || !_location.auto_index.unwrap() {
return Err(ErrorKind::Unsupported.into());
}
}
_ => {
continue;
if let Ok(_location) = from_value::<LocationConfig>(v.clone()) {
if let Some(index) = _location.index {
let path = PathBuf::from(location).join(index.clone());
let _path = root_relative(path.as_path().to_str().unwrap());

return fs::read_to_string(_path)
.await
.with_context(move || format!("failed to read path {}", _path));
} else if _location.auto_index.is_none() || !_location.auto_index.unwrap() {
return Err(anyhow!("Index not supported"));
}
}
}
Expand Down
17 changes: 10 additions & 7 deletions src/zest.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
use crate::{
config::{Config, ARGS, CONFIG, CONFIG_PATH, DEFAULT_CONFIG},
init::{init_cache, init_signal, DATE_FORMAT, DEFAULT_TICK, FILE_CACHE, INDEX_CACHE, T},
config::{Config, ARGS, CONFIG, CONFIG_PATH, DEFAULT_CONFIG, DEFAULT_TICK},
init::{init_cache, init_signal, DATE_FORMAT, FILE_CACHE, INDEX_CACHE, T},
route::{location_index, mime_match, root_relative, status_page},
};

use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use mime::Mime;
use std::{
collections::HashMap, env::set_current_dir, error::Error, io, ops::Deref, path::Path, sync::Arc,
collections::HashMap, env::set_current_dir, error::Error, ops::Deref, path::Path, sync::Arc,
};

#[cfg(feature = "log")]
Expand Down Expand Up @@ -67,7 +68,7 @@ impl<'a> Response<'a> {
}
}

async fn handle_connection<S>(mut stream: S) -> io::Result<(i32, String)>
async fn handle_connection<S>(mut stream: S) -> Result<(i32, String)>
where
S: AsyncReadExt + AsyncWriteExt + Unpin,
{
Expand Down Expand Up @@ -305,12 +306,14 @@ pub async fn zest_main() -> Result<(), Box<dyn Error>> {
set_current_dir(config.clone().server.root)?;

#[cfg(feature = "log")]
init_logger(&config.clone()).await;
init_logger(&config.clone())
.await
.context("failed to init logger")?;

init_signal().await.unwrap();
init_signal().await.context("failed to init signal")?;

#[cfg(feature = "lru_cache")]
init_cache().await.unwrap();
init_cache().await.context("failed to init lru cache")?;

loop {
let _config = CONFIG.try_read().unwrap();
Expand Down

0 comments on commit 256163d

Please sign in to comment.