Skip to content

Commit 64b9922

Browse files
committed
ember_html: Use or_try_insert_with() to avoid unwrap() and expect() calls
1 parent eafc823 commit 64b9922

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed

src/middleware/ember_html.rs

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,12 @@ pub async fn serve_html(state: AppState, request: Request, next: Next) -> Respon
8080
.unwrap_or(Cow::Borrowed(OG_IMAGE_FALLBACK_URL));
8181

8282
// Fetch the HTML from cache given `og_image_url` as key or render it
83-
let html = RENDERED_HTML_CACHE
84-
.get_or_init(|| init_html_cache(state.config.html_render_cache_max_capacity))
85-
.get_with_by_ref(&og_image_url, async {
83+
let html_cache = RENDERED_HTML_CACHE
84+
.get_or_init(|| init_html_cache(state.config.html_render_cache_max_capacity));
85+
86+
let render_result = html_cache
87+
.entry_by_ref(&og_image_url)
88+
.or_try_insert_with::<_, minijinja::Error>(async {
8689
// `LazyLock::deref` blocks as long as its intializer is running in another thread.
8790
// Note that this won't take long, as the constructed Futures are not awaited
8891
// during initialization.
@@ -91,17 +94,23 @@ pub async fn serve_html(state: AppState, request: Request, next: Next) -> Respon
9194
// Render the HTML given the OG image URL
9295
let env = template_env.clone().await;
9396
let html = env
94-
.get_template(INDEX_TEMPLATE_NAME)
95-
.unwrap()
96-
.render(minijinja::context! { og_image_url})
97-
.expect("Error rendering index");
97+
.get_template(INDEX_TEMPLATE_NAME)?
98+
.render(minijinja::context! { og_image_url})?;
9899

99-
html
100+
Ok(html)
100101
})
101102
.await;
102103

103-
// Serve static Ember page to bootstrap the frontend
104-
axum::response::Html(html).into_response()
104+
match render_result {
105+
Ok(entry) => {
106+
// Serve static Ember page to bootstrap the frontend
107+
axum::response::Html(entry.into_value()).into_response()
108+
}
109+
Err(err) => {
110+
tracing::error!("Error rendering HTML: {:?}", err);
111+
StatusCode::INTERNAL_SERVER_ERROR.into_response()
112+
}
113+
}
105114
} else {
106115
// Return a 404 to crawlers that don't send `Accept: text/hml`.
107116
// This is to preserve legacy behavior and will likely change.

0 commit comments

Comments
 (0)