Skip to content

Commit

Permalink
Make Cache-Control configurable.
Browse files Browse the repository at this point in the history
  • Loading branch information
jsha committed Jun 22, 2022
1 parent a854363 commit 1627bf3
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
11 changes: 11 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@ pub struct Config {
// Content Security Policy
pub(crate) csp_report_only: bool,

// Cache-Control header
// If both are absent, don't generate the header. If only one is present,
// generate just that directive. Values are in seconds.
pub(crate) cache_control_stale_while_revalidate: Option<u32>,
pub(crate) cache_control_max_age: Option<u32>,

// Build params
pub(crate) build_attempts: u16,
pub(crate) rustwide_workspace: PathBuf,
Expand Down Expand Up @@ -130,6 +136,11 @@ impl Config {

csp_report_only: env("DOCSRS_CSP_REPORT_ONLY", false)?,

cache_control_stale_while_revalidate: maybe_env(
"CACHE_CONTROL_STALE_WHILE_REVALIDATE",
)?,
cache_control_max_age: maybe_env("CACHE_CONTROL_MAX_AGE")?,

local_archive_cache_path: env(
"DOCSRS_ARCHIVE_INDEX_CACHE_PATH",
prefix.join("archive_cache"),
Expand Down
22 changes: 15 additions & 7 deletions src/web/rustdoc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,13 +235,13 @@ impl RustdocPage {
let is_latest_url = self.is_latest_url;
// Build the page of documentation
let ctx = ctry!(req, tera::Context::from_serialize(self));
let config = extension!(req, Config);
// Extract the head and body of the rustdoc file so that we can insert it into our own html
// while logging OOM errors from html rewriting
let html = match utils::rewrite_lol(rustdoc_html, max_parse_memory, ctx, templates) {
Err(RewritingError::MemoryLimitExceeded(..)) => {
metrics.html_rewrite_ooms.inc();

let config = extension!(req, Config);
let err = anyhow!(
"Failed to serve the rustdoc file '{}' because rewriting it surpassed the memory limit of {} bytes",
file_path, config.max_parse_memory,
Expand All @@ -259,13 +259,21 @@ impl RustdocPage {
.headers
.set(CacheControl(vec![CacheDirective::MaxAge(0)]));
} else {
response.headers.set(CacheControl(vec![
CacheDirective::Extension(
let mut directives = vec![];
if let Some(seconds) = config.cache_control_stale_while_revalidate {
directives.push(CacheDirective::Extension(
"stale-while-revalidate".to_string(),
Some("2592000".to_string()), // sixty days
),
CacheDirective::MaxAge(600u32), // ten minutes
]));
Some(format!("{}", seconds)),
));
}

if let Some(seconds) = config.cache_control_max_age {
directives.push(CacheDirective::MaxAge(seconds));
}

if !directives.empty() {
response.headers.set(CacheControl(directives));
}
}
Ok(response)
}
Expand Down

0 comments on commit 1627bf3

Please sign in to comment.