working example for hotreload with async

This commit is contained in:
Paul 2022-01-23 20:39:20 +01:00
parent 473883f6dc
commit b5484c2bcd
2 changed files with 51 additions and 47 deletions

View File

@ -8,6 +8,9 @@ use serde_json::Value as JsonValue;
use std::fs::File; use std::fs::File;
use std::io::Read; use std::io::Read;
use std::string::String; use std::string::String;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::time::sleep;
#[derive(Debug)] #[derive(Debug)]
pub enum ReloadFrequency { pub enum ReloadFrequency {
@ -69,16 +72,19 @@ impl Context {
}*/ }*/
} }
pub async fn hotreload(rwctx: &tokio::sync::RwLock<Context>) { pub async fn hotreload(ctx: Context, ctxsender: &tokio::sync::mpsc::Sender<Context>) {
let mut ctx = rwctx.write().await; println!("function hotreload, {:?}", ctxsender);
let configfile = ctx.configfile.clone(); let mut sendctx = ctx.clone();
loop {
let events = match ctx.inotify.read_events() { let events = match ctx.inotify.read_events() {
Ok(ev) => ev, Ok(ev) => ev,
Err(_) => vec![], Err(_) => vec![],
}; };
if events.len() > 0 { if events.len() > 0 {
println!("Reloading {cfg}", cfg = ctx.configfile); sendctx.cfg.load(&sendctx.configfile).await;
ctx.cfg.load(configfile.as_str()).await; }
println!("Sending {:?}", ctx);
ctxsender.send(sendctx.clone()).await;
} }
} }
@ -115,7 +121,8 @@ impl<'a> Config {
} }
}; };
let mut contents = String::new(); let mut contents = String::new();
file.read_to_string(&mut contents).unwrap(); let fread = file.read_to_string(&mut contents).unwrap();
println!("{} {} {}", configfile, contents, fread);
let parse: Result<JsonValue, JsonError> = serde_json::from_str(contents.as_str()); let parse: Result<JsonValue, JsonError> = serde_json::from_str(contents.as_str());
*self = match parse { *self = match parse {
Ok(cfg) => { Ok(cfg) => {
@ -163,11 +170,10 @@ impl<'a> Config {
Ok(_) => true, Ok(_) => true,
Err(_) => false, Err(_) => false,
}; };
if fileexists { if !fileexists {
file = File::create(configfile).unwrap(); file = File::create(configfile).unwrap();
} else {
file = File::open(configfile).unwrap();
}
serde_json::to_writer_pretty(file, &self).unwrap(); serde_json::to_writer_pretty(file, &self).unwrap();
sleep(Duration::from_secs(1)).await;
}
} }
} }

View File

@ -2,12 +2,9 @@ use crate::config::{hotreload, Context};
use crate::zabbix::api::*; use crate::zabbix::api::*;
use launchy::Color; use launchy::Color;
use launchy::{self, Canvas, CanvasLayout, CanvasLayoutPoller, MsgPollingWrapper, Pad}; use launchy::{self, Canvas, CanvasLayout, CanvasLayoutPoller, MsgPollingWrapper, Pad};
//use std::process::exit;
//use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::Arc;
use std::thread::sleep;
use std::time::Duration; use std::time::Duration;
use tokio::sync::RwLock; use tokio::sync::mpsc;
use tokio::time::sleep;
const MATRIX_WIDTH: i32 = 8; const MATRIX_WIDTH: i32 = 8;
const MATRIX_SIZE: i32 = MATRIX_WIDTH * MATRIX_WIDTH; const MATRIX_SIZE: i32 = MATRIX_WIDTH * MATRIX_WIDTH;
@ -15,34 +12,32 @@ const REQUEST_WAITFOR: i32 = 5;
const ZERO_COLOR: f32 = 0.; const ZERO_COLOR: f32 = 0.;
const ONE_COLOR: f32 = 1.; const ONE_COLOR: f32 = 1.;
pub async fn run() { const POLLER_ITER: u64 = 17;
println!("test1 🦀");
let ctx = Context::new().await; fn log(num: i64) {
println!("test2 🦀"); return println!("test{} 🦀", num);
let e = Arc::new(RwLock::new(ctx));
let mutedctx = e.clone();
println!("test3 🦀{}", e);
loop {
println!("test4 🦀");
tokio::spawn(async move { test(&mutedctx) });
println!("test5 🦀");
/*tokio::select! {
_ = test(&mutedctx) => {
println!("fn test 🦀 {:?}", mutedctx);
}
_ = hotreload(&mutedctx) => {
println!("fn hotreload 🦀 {:?}", mutedctx);
}
};*/
}
} }
async fn test(roctx: &'static tokio::sync::RwLock<Context>) { pub async fn run<'a>() {
let ctx = roctx.read().await; log(1);
println!("{:?}", ctx); let ctx = Context::new().await;
let zabbix_data = get_zabbix_problems(&ctx.cfg).await.unwrap(); log(2);
println!("{} {:?}", zabbix_data, ctx.cfg); let (tx1, mut rx1) = mpsc::channel(1);
sleep(Duration::from_secs(ctx.cfg.refresh.unwrap())); log(3);
let t1 = tokio::task::spawn(async move { test(&mut rx1).await });
let t2 = tokio::task::spawn(async move { hotreload(ctx.clone(), &tx1).await });
tokio::join!(t1, t2);
log(4);
}
async fn test<'a>(ctxreceiver: &'a mut tokio::sync::mpsc::Receiver<Context>) {
while let Some(val) = ctxreceiver.recv().await {
println!("Fetching zabbix problems, {:?}", val.cfg);
let zabbix_data = get_zabbix_problems(&val.cfg).await.unwrap();
println!("{}", zabbix_data["result"][0]);
println!("sleeping during {}", val.cfg.refresh.unwrap());
sleep(Duration::from_secs(val.cfg.refresh.unwrap())).await;
}
} }
fn initpad() -> (CanvasLayout<'static>, CanvasLayoutPoller) { fn initpad() -> (CanvasLayout<'static>, CanvasLayoutPoller) {
@ -63,7 +58,10 @@ fn initpad() -> (CanvasLayout<'static>, CanvasLayoutPoller) {
fn input(canvas: &mut CanvasLayout, poller: &mut CanvasLayoutPoller) { fn input(canvas: &mut CanvasLayout, poller: &mut CanvasLayoutPoller) {
for color in (0u64..).map(|f| Color::red_green_color(f as f32 / 60.0 / 2.5)) { for color in (0u64..).map(|f| Color::red_green_color(f as f32 / 60.0 / 2.5)) {
for msg in poller.iter_for_millis(17).filter(|msg| msg.is_press()) { for msg in poller
.iter_for_millis(POLLER_ITER)
.filter(|msg| msg.is_press())
{
canvas[msg.pad()] = color; canvas[msg.pad()] = color;
println!("{msg:?}", msg = msg.pad()) println!("{msg:?}", msg = msg.pad())
} }