Skip to content

Commit faefbce

Browse files
committed
Cache the current Rust version.
Currently, every time the home page is rendered, the web server downloads a TOML file from static.rust-lang.org and parses it to find the current Rust version. This adds a significant amount of latency to the home page. This patch caches the version in memory for up to 10 minutes. This greatly speeds up home page rendering, at the cost of a 10-minute delay before a new version is reflected on the home page.
1 parent 7b16422 commit faefbce

File tree

4 files changed

+28
-0
lines changed

4 files changed

+28
-0
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ version = "0.1.0"
44
authors = ["Ashley Williams <[email protected]>"]
55

66
[dependencies]
7+
lazy_static = "1.2.0"
78
rand = "0.6"
89
rocket = "0.4"
910
serde = "1.0"

src/main.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
#![feature(proc_macro_hygiene, decl_macro)]
22

3+
#[macro_use]
4+
extern crate lazy_static;
35
extern crate rand;
46
extern crate reqwest;
57
#[macro_use]

src/rust_version.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,31 @@
1+
use std::{
2+
sync::RwLock,
3+
time::Instant,
4+
};
15
use reqwest;
26
use toml;
37

8+
lazy_static! {
9+
static ref CACHE: RwLock<Option<(String, Instant)>> = RwLock::new(None);
10+
}
11+
12+
const CACHE_TTL_SECS: u64 = 600;
13+
414
pub fn rust_version() -> Option<String> {
15+
// Use cached version if available.
16+
if let Some((version, timestamp)) = &*CACHE.read().unwrap() {
17+
if timestamp.elapsed().as_secs() < CACHE_TTL_SECS {
18+
return Some(version.clone())
19+
}
20+
}
21+
22+
// Update the cache if it's missing or expired.
23+
let version = fetch_rust_version()?;
24+
*CACHE.write().unwrap() = Some((version.clone(), Instant::now()));
25+
Some(version)
26+
}
27+
28+
fn fetch_rust_version() -> Option<String> {
529
let manifest = reqwest::get("https://static.rust-lang.org/dist/channel-rust-stable.toml")
630
.ok()?
731
.text()

0 commit comments

Comments
 (0)