Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Hot reloading #930

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,9 @@ object_store = { version = "0.11.0", default-features = false }
# cache
moka = { version = "0.12.7", features = ["sync"], optional = true }

notify-debouncer-full = { version = "0.4.0" }
tower-livereload = { version = "0.9.4" }

# Scheduler
tokio-cron-scheduler = { version = "0.11.0", features = ["signal"] }
english-to-cron = { version = "0.1.2" }
Expand Down
112 changes: 108 additions & 4 deletions src/controller/views/engines.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,112 @@
use std::path::Path;
use std::{
path::Path,
sync::{Arc, RwLock},
time::Duration,
};

use tower_livereload::LiveReloadLayer;

use notify_debouncer_full::{
new_debouncer,
notify::{EventKind, RecommendedWatcher, RecursiveMode},
DebounceEventResult, Debouncer, FileIdMap,
};
use serde::Serialize;

use crate::{controller::views::ViewRenderer, Error, Result};

const VIEWS_DIR: &str = "assets/views";

#[derive(Clone, Debug)]
pub struct TeraView {
pub struct ReloadableTera {
#[cfg(debug_assertions)]
_debouncer: Arc<Debouncer<RecommendedWatcher, FileIdMap>>,

#[cfg(debug_assertions)]
pub tera: Arc<RwLock<tera::Tera>>,

// #[cfg(debug_assertions)]
// pub reload_layer: LiveReloadLayer,

#[cfg(not(debug_assertions))]
pub tera: tera::Tera,
}

impl ReloadableTera {
pub fn new(root_path: &str, path_str: &str) -> Result<Self> {
let tera = tera::Tera::new(path_str)?;

#[cfg(debug_assertions)]
let (debouncer, tera) = {
let tera = Arc::new(RwLock::new(tera));
let debouncer =
Self::create_reload_debouncer(Duration::from_millis(500), tera.clone(), root_path);

(Arc::new(debouncer), tera)
};

Ok(Self {
#[cfg(debug_assertions)]
_debouncer: debouncer,
tera,
})
}

fn create_reload_debouncer(
delay: Duration,
tera: Arc<RwLock<tera::Tera>>,
root_path: &str,
) -> Debouncer<RecommendedWatcher, FileIdMap> {
let mut debouncer =
new_debouncer(
delay,
None,
move |result: DebounceEventResult| match result {
Ok(events) => events.iter().for_each(|event| match event.kind {
EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_) => {
let mut write_lock =
tera.write().expect("Failed to acquire tera write lock");

write_lock.full_reload().expect("Failed to full reload");
}
_ => {}
}),
Err(errors) => errors.iter().for_each(|error| println!("{error:?}")),
},
)
.unwrap();

debouncer
.watch(root_path, RecursiveMode::Recursive)
.unwrap();

debouncer
}

#[cfg(debug_assertions)]
pub fn get(&self) -> std::sync::RwLockReadGuard<tera::Tera> {
self.tera.read().unwrap()
}

#[cfg(debug_assertions)]
pub fn get_mut(&mut self) -> std::sync::RwLockWriteGuard<tera::Tera> {
self.tera.write().unwrap()
}

#[cfg(not(debug_assertions))]
pub fn get(&self) -> &tera::Tera {
&self.tera
}

#[cfg(not(debug_assertions))]
pub fn get_mut(&mut self) -> &mut tera::Tera {
&mut self.tera
}
}

#[derive(Clone, Debug)]
pub struct TeraView {
pub tera: ReloadableTera,
pub default_context: tera::Context,
}

Expand All @@ -35,13 +133,17 @@ impl TeraView {
)));
}

let tera = tera::Tera::new(
let tera = ReloadableTera::new(
path.as_ref()
.to_str()
.ok_or_else(|| Error::string("invalid blob"))?,
path.as_ref()
.join("**")
.join("*.html")
.to_str()
.ok_or_else(|| Error::string("invalid blob"))?,
)?;

let ctx = tera::Context::default();
Ok(Self {
tera,
Expand Down Expand Up @@ -75,7 +177,9 @@ impl ViewRenderer for TeraView {
}
*/

Ok(self.tera.render(key, &context)?)
let tera = self.tera.get();

Ok(tera.render(key, &context)?)
}
}

Expand Down