improve renderstats by making it better defined and more flexible

This commit is contained in:
slonkazoid 2024-12-16 14:58:02 +03:00
parent 9eddbdb881
commit 734a6835c7
Signed by: slonk
SSH key fingerprint: SHA256:tbZfJX4IOvZ0LGWOWu5Ijo8jfMPi78TU7x1VoEeCIjM
5 changed files with 69 additions and 40 deletions

View file

@ -83,37 +83,36 @@ async fn main() -> eyre::Result<()> {
.instrument(info_span!("custom_template_watcher")), .instrument(info_span!("custom_template_watcher")),
); );
let posts: Arc<dyn PostManager + Send + Sync> = match config.engine { let cache = if config.cache.enable {
Engine::Markdown => { if config.cache.persistence && tokio::fs::try_exists(&config.cache.file).await? {
let cache = if config.cache.enable { info!("loading cache from file");
if config.cache.persistence && tokio::fs::try_exists(&config.cache.file).await? { let mut cache = load_cache(&config.cache).await.unwrap_or_else(|err| {
info!("loading cache from file"); error!("failed to load cache: {}", err);
let mut cache = load_cache(&config.cache).await.unwrap_or_else(|err| { info!("using empty cache");
error!("failed to load cache: {}", err); Default::default()
info!("using empty cache"); });
Default::default()
});
if cache.version() < CACHE_VERSION { if cache.version() < CACHE_VERSION {
warn!("cache version changed, clearing cache"); warn!("cache version changed, clearing cache");
cache = Default::default(); cache = Default::default();
}; };
Some(cache) Some(cache)
} else { } else {
Some(Default::default()) Some(Default::default())
}
} else {
None
}
.map(|cache| CacheGuard::new(cache, config.cache.clone()))
.map(Arc::new);
Arc::new(MarkdownPosts::new(Arc::clone(&config), cache.clone()).await?)
} }
} else {
None
}
.map(|cache| CacheGuard::new(cache, config.cache.clone()))
.map(Arc::new);
let posts: Arc<dyn PostManager + Send + Sync> = match config.engine {
Engine::Markdown => Arc::new(MarkdownPosts::new(Arc::clone(&config), cache.clone()).await?),
Engine::Blag => Arc::new(Blag::new( Engine::Blag => Arc::new(Blag::new(
config.dirs.posts.clone().into(), config.dirs.posts.clone().into(),
config.blag.bin.clone().into(), config.blag.bin.clone().into(),
cache.clone(),
)), )),
}; };

View file

@ -16,16 +16,24 @@ use tracing::{debug, error};
use crate::error::PostError; use crate::error::PostError;
use crate::post::Filter; use crate::post::Filter;
use super::cache::CacheGuard;
use super::{ApplyFilters, PostManager, PostMetadata, RenderStats, ReturnedPost}; use super::{ApplyFilters, PostManager, PostMetadata, RenderStats, ReturnedPost};
pub struct Blag { pub struct Blag {
root: Arc<Path>, root: Arc<Path>,
blag_bin: Arc<Path>, blag_bin: Arc<Path>,
_cache: Option<Arc<CacheGuard>>,
_fastblag: bool,
} }
impl Blag { impl Blag {
pub fn new(root: Arc<Path>, blag_bin: Arc<Path>) -> Blag { pub fn new(root: Arc<Path>, blag_bin: Arc<Path>, _cache: Option<Arc<CacheGuard>>) -> Blag {
Self { root, blag_bin } Self {
root,
blag_bin,
_cache,
_fastblag: false,
}
} }
} }
@ -94,6 +102,7 @@ impl PostManager for Blag {
name: &str, name: &str,
_query: &HashMap<String, Value>, _query: &HashMap<String, Value>,
) -> Result<ReturnedPost, PostError> { ) -> Result<ReturnedPost, PostError> {
let start = Instant::now();
let mut path = self.root.join(name); let mut path = self.root.join(name);
if name.ends_with(".sh") { if name.ends_with(".sh") {
@ -117,7 +126,6 @@ impl PostManager for Blag {
path.add_extension("sh"); path.add_extension("sh");
} }
let start = Instant::now();
let stat = tokio::fs::metadata(&path) let stat = tokio::fs::metadata(&path)
.await .await
.map_err(|err| match err.kind() { .map_err(|err| match err.kind() {
@ -146,6 +154,9 @@ impl PostManager for Blag {
let mut meta: PostMetadata = serde_json::from_str(&buf)?; let mut meta: PostMetadata = serde_json::from_str(&buf)?;
meta.name = name.to_string(); meta.name = name.to_string();
let parsed = start.elapsed();
let rendering = Instant::now();
buf.clear(); buf.clear();
reader.read_to_string(&mut buf).await?; reader.read_to_string(&mut buf).await?;
@ -157,12 +168,17 @@ impl PostManager for Blag {
return Err(PostError::RenderError(exit_status.to_string())); return Err(PostError::RenderError(exit_status.to_string()));
} }
let elapsed = start.elapsed(); let rendered = rendering.elapsed();
let total = start.elapsed();
Ok(ReturnedPost::Rendered( Ok(ReturnedPost::Rendered(
meta, meta,
buf, buf,
RenderStats::ParsedAndRendered(elapsed, elapsed, elapsed), RenderStats::Rendered {
parsed,
rendered,
total,
},
)) ))
} }

View file

@ -275,7 +275,11 @@ impl PostManager for MarkdownPosts {
Ok(ReturnedPost::Rendered( Ok(ReturnedPost::Rendered(
metadata, metadata,
rendered, rendered,
RenderStats::ParsedAndRendered(start.elapsed(), stats.0, stats.1), RenderStats::Rendered {
total: start.elapsed(),
parsed: stats.0,
rendered: stats.1,
},
)) ))
} }
} }

View file

@ -29,10 +29,16 @@ pub struct PostMetadata {
} }
#[derive(Serialize, Debug)] #[derive(Serialize, Debug)]
#[allow(unused)]
pub enum RenderStats { pub enum RenderStats {
Cached(Duration), Cached(Duration),
// format: Total, Parsed in, Rendered in Rendered {
ParsedAndRendered(Duration, Duration, Duration), total: Duration,
parsed: Duration,
rendered: Duration,
},
Fetched(Duration),
Unknown,
} }
#[allow(clippy::large_enum_variant)] // Raw will be returned very rarely #[allow(clippy::large_enum_variant)] // Raw will be returned very rarely

View file

@ -1,18 +1,22 @@
running <a href="{{bingus_info.repository}}" target="_blank">{{bingus_info.name}}</a> v{{bingus_info.version}} running
<a href="{{bingus_info.repository}}" target="_blank">{{bingus_info.name}}</a>
v{{bingus_info.version}}
{{#if rendered_in}} {{#if rendered_in}}
<b> - </b> <b> - </b>
{{/if}} {{/if}}
{{#each rendered_in}} {{#each rendered_in}}
{{#if (eq @key "ParsedAndRendered")}} {{#if (eq @key "Rendered")}}
<span class="tooltipped" title="parsing took {{duration this.1}}">parsed</span> <span class="tooltipped" title="parsing metadata took {{duration this.parsed}}">parsed meta</span>
and and
<span class="tooltipped" title="rendering took {{duration this.2}}">rendered</span> <span class="tooltipped" title="rendering took {{duration this.rendered}}">rendered</span>
in in
{{duration this.0}} {{duration this.total}}
{{else if (eq @key "Cached")}} {{else if (eq @key "Cached")}}
retrieved from cache in retrieved from cache in
{{duration this}} {{duration this}}
{{else if (eq @key "Fetched")}}
fetched in
{{duration this}}
{{/if}} {{/if}}
{{/each}} {{/each}}
{{#if raw_name}} {{#if raw_name}}