From 68ccdf09a44744a7fb8ccdc17a4f61343561c18a Mon Sep 17 00:00:00 2001 From: Dietmar Maurer Date: Tue, 14 Apr 2020 13:45:45 +0200 Subject: [PATCH] src/config/user.rs: implement user config cache --- src/config/user.rs | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/src/config/user.rs b/src/config/user.rs index 12ce3680..d4bfb35b 100644 --- a/src/config/user.rs +++ b/src/config/user.rs @@ -1,6 +1,8 @@ +use std::collections::HashMap; +use std::sync::{Arc, RwLock}; + use failure::*; use lazy_static::lazy_static; -use std::collections::HashMap; use serde::{Serialize, Deserialize}; use serde_json::json; @@ -139,6 +141,41 @@ pub fn config() -> Result<(SectionConfigData, [u8;32]), Error> { Ok((data, digest)) } +pub fn cached_config() -> Result<(Arc,[u8;32]), Error> { + + struct ConfigCache { + data: Option<(Arc,[u8;32])>, + last_mtime: i64, + last_mtime_nsec: i64, + } + + lazy_static! { + static ref CACHED_CONFIG: RwLock = RwLock::new( + ConfigCache { data: None, last_mtime: 0, last_mtime_nsec: 0 }); + } + + let stat = nix::sys::stat::stat(USER_CFG_FILENAME)?; + + { // limit scope + let cache = CACHED_CONFIG.read().unwrap(); + if stat.st_mtime == cache.last_mtime && stat.st_mtime_nsec == cache.last_mtime_nsec { + if let Some((ref config, ref digest)) = cache.data { + return Ok((config.clone(), *digest)); + } + } + } + + let (config, digest) = config()?; + let config = Arc::new(config); + + let mut cache = CACHED_CONFIG.write().unwrap(); + cache.last_mtime = stat.st_mtime; + cache.last_mtime_nsec = stat.st_mtime_nsec; + cache.data = Some((config.clone(), digest.clone())); + + Ok((config, digest)) +} + pub fn save_config(config: &SectionConfigData) -> Result<(), Error> { let raw = CONFIG.write(USER_CFG_FILENAME, &config)?;