Skip to content

Commit 7e9803f

Browse files
committed
perf: cache CSS bundle and theme list in LazyLock at startup
1 parent 448a619 commit 7e9803f

2 files changed

Lines changed: 16 additions & 10 deletions

File tree

src/main.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,19 +89,23 @@ async fn resource(body: &str, content_type: &str, cache: bool) -> Result<Respons
8989
Ok(res)
9090
}
9191

92-
async fn style() -> Result<Response<Body>, String> {
92+
static STYLE_CSS: LazyLock<String> = LazyLock::new(|| {
9393
let mut res = include_str!("../static/style.css").to_string();
9494
for file in ThemeAssets::iter() {
9595
res.push('\n');
9696
let theme = ThemeAssets::get(file.as_ref()).unwrap();
9797
res.push_str(std::str::from_utf8(theme.data.as_ref()).unwrap());
9898
}
99+
res
100+
});
101+
102+
async fn style() -> Result<Response<Body>, String> {
99103
Ok(
100104
Response::builder()
101105
.status(200)
102106
.header("content-type", "text/css")
103107
.header("Cache-Control", "public, max-age=1209600, s-maxage=86400")
104-
.body(res.to_string().into())
108+
.body(Body::from(STYLE_CSS.clone()))
105109
.unwrap_or_default(),
106110
)
107111
}

src/utils.rs

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -692,18 +692,20 @@ where
692692
#[include = "*.css"]
693693
pub struct ThemeAssets;
694694

695+
static AVAILABLE_THEMES: LazyLock<Vec<String>> = LazyLock::new(|| {
696+
let mut themes = vec!["system".to_string()];
697+
for file in ThemeAssets::iter() {
698+
let chunks: Vec<&str> = file.as_ref().split(".css").collect();
699+
themes.push(chunks[0].to_owned());
700+
}
701+
themes
702+
});
703+
695704
impl Preferences {
696705
/// Build preferences from cookies
697706
pub fn new(req: &Request<Body>) -> Self {
698-
// Read available theme names from embedded css files.
699-
// Always make the default "system" theme available.
700-
let mut themes = vec!["system".to_string()];
701-
for file in ThemeAssets::iter() {
702-
let chunks: Vec<&str> = file.as_ref().split(".css").collect();
703-
themes.push(chunks[0].to_owned());
704-
}
705707
Self {
706-
available_themes: themes,
708+
available_themes: AVAILABLE_THEMES.clone(),
707709
theme: setting(req, "theme"),
708710
front_page: setting(req, "front_page"),
709711
layout: setting(req, "layout"),

0 commit comments

Comments
 (0)