Skip to content

Cache the current Rust version. #652

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 14, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ version = "0.1.0"
authors = ["Ashley Williams <[email protected]>"]

[dependencies]
lazy_static = "1.2.0"
rand = "0.6"
rocket = "0.4"
serde = "1.0"
Expand Down
2 changes: 2 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate lazy_static;
extern crate rand;
extern crate reqwest;
#[macro_use]
Expand Down
31 changes: 29 additions & 2 deletions src/rust_version.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,39 @@
use reqwest;
use std::sync::RwLock;
use std::thread;
use std::time::Instant;
use toml;

lazy_static! {
static ref CACHE: RwLock<Option<(String, Instant)>> = RwLock::new(None);
}

const CACHE_TTL_SECS: u64 = 120;

pub fn rust_version() -> Option<String> {
cached_rust_version().or_else(fetch_rust_version)
}

fn cached_rust_version() -> Option<String> {
let cached = CACHE.read().unwrap();
let (version, timestamp) = cached.as_ref()?;
if timestamp.elapsed().as_secs() > CACHE_TTL_SECS {
// Update the cache in the background.
thread::spawn(fetch_rust_version);
}
Some(version.clone())
}

fn fetch_rust_version() -> Option<String> {
let manifest = reqwest::get("https://static.rust-lang.org/dist/channel-rust-stable.toml")
.ok()?
.text()
.ok()?;
let manifest = manifest.parse::<toml::Value>().ok()?;
let rust_version = manifest["pkg"]["rust"]["version"].as_str()?.to_string();
Some(rust_version[..rust_version.find(' ')?].to_string())
let rust_version = manifest["pkg"]["rust"]["version"].as_str()?;
let version = rust_version[..rust_version.find(' ')?].to_string();

// Update the cache.
*CACHE.write().unwrap() = Some((version.clone(), Instant::now()));
Some(version)
}