fix(scheduler) fn type

This commit is contained in:
lumither committed 2024-11-17 21:06:36 -08:00
1 parent d98aa3f745
commit a123ff9f3f
11 files changed
+103 -10

No files matched your search

@@ -0,0 +1,24 @@
use dirs::home_dir;
use std::env;
pub fn task() {
// get dir
let git_work_dir_path = &env::var("GIT_WORK_DIR").unwrap_or_else(|e| {
if let Ok(default_log_path) = env::var("WORK_DIR") {
if default_log_path.starts_with('~') {
let home_path = home_dir().unwrap_or_else(|| panic!("Cannot find home directory"));
home_path
.join(default_log_path.strip_prefix("~/").unwrap())
.into_os_string()
.into_string()
.expect(
"[fatal] failed to parse env `WORK_DIR`, try to use absolute path instead",
)
} else {
default_log_path
}
} else {
panic!("[fatal] failed to parse env `GIT_WORK_DIR`: {}", e);
}
});
}
+1
View File
@@ -0,0 +1 @@
pub mod check_update;
+1
View File
@@ -1,4 +1,5 @@
mod api;
pub mod cron;
use crate::blog::api::{
get_page_count::get_page_count, get_post::get_post, get_post_list::get_post_list,
+35 -3
View File
@@ -1,11 +1,17 @@
use std::env;
use crate::logger;
use std::{
backtrace::{Backtrace, BacktraceStatus},
env, panic,
panic::PanicHookInfo,
};
use tracing::{error, event, span, Level};
use tracing_appender::non_blocking::WorkerGuard;
pub fn logger_init() -> (WorkerGuard, WorkerGuard) {
logger::init()
let ret = logger::init();
panic::set_hook(Box::new(panic_hook));
ret
}
pub fn load_env() {
@@ -22,3 +28,29 @@ pub fn load_env() {
println!("[info] no .env file referred, starting up")
}
}
fn panic_hook(panic_info: &PanicHookInfo) {
let payload = panic_info.payload();
// panic_info.
let payload = if let Some(s) = payload.downcast_ref::<&str>() {
Some(&**s)
} else {
payload.downcast_ref::<String>().map(|s| s.as_str())
};
// let location = panic_info.location().map(|l| l.to_string());
// let backtrace = Backtrace::capture();
// let note = (backtrace.status() == BacktraceStatus::Disabled)
// .then_some("run with RUST_BACKTRACE=1 environment variable to display a backtrace");
// (Some(backtrace), note)
// };
//
// panic_info.
if let Some(location) = panic_info.location() {
eprintln!("err filename: {}", location.file())
}
event!(target: "test", Level::ERROR, "panic hook: {:?}", panic_info);
}
+8 -1
View File
@@ -9,5 +9,12 @@ async fn main() {
init::load_env();
let _guards = init::logger_init();
server::start().await;
// panic!("test");
match server::start().await {
Ok(_) => {}
Err(e) => {
panic!("server start failed: {}", e);
}
};
}
+4
View File
@@ -156,6 +156,10 @@ impl Scheduler {
self.tasks.write()?.insert(id, Arc::new(task));
Ok(id)
}
pub fn new() -> Self {
Self::default()
}
}
#[cfg(test)]
@@ -11,12 +11,19 @@ pub struct BasicTask {
}
impl BasicTask {
pub fn new(func: fn(), cron_expr: &str) -> Result<Self, Box<dyn Error>> {
pub fn new<F>(func: F, cron_expr: &str) -> Result<Self, Box<dyn Error>>
where
F: TaskFunc,
{
Ok(BasicTask {
schedule: Schedule::from_str(cron_expr)?,
func: Box::new(func),
})
}
pub fn to_task(self) -> Box<dyn Task> {
Box::new(self)
}
}
impl Task for BasicTask {
+17 -1
View File
@@ -1,9 +1,12 @@
use std::env;
use std::error::Error;
use std::num::ParseIntError;
use std::process::exit;
use std::str::FromStr;
use crate::blog;
use crate::scheduler::tasks::basic::BasicTask;
use crate::scheduler::Scheduler;
use axum::Router;
use sqlx::{
postgres::{PgConnectOptions, PgPoolOptions},
@@ -11,7 +14,7 @@ use sqlx::{
};
use tracing::{error, info, warn};
pub async fn start() {
pub async fn start() -> Result<(), Box<dyn Error>> {
let port: u32 = match env::var("BACKEND_PORT") {
Ok(value) => value.parse().unwrap_or_else(|e: ParseIntError| {
warn!("failed to parse BACKEND_PORT: {}", e.to_string());
@@ -35,6 +38,18 @@ pub async fn start() {
}
};
// cron task
let scheduler = Scheduler::new();
let test_str = "hello world".to_string();
// scheduler.insert(
// BasicTask::new(
// move || blog::cron::check_update::task(test_str.clone()),
// "* * * * * *",
// )?
// .to_task(),
// )?;
// http server
let app = Router::new()
.nest("blog", blog::get_router())
.with_state(db_pool);
@@ -50,6 +65,7 @@ pub async fn start() {
error!("failed to start axum: {}", e.to_string());
exit(1);
});
Ok(())
}
fn parse_db_uri() -> String {