Visual Studio Code, rebuilt in Rust
Rust
use std::io::{Read, Write};
use std::net::TcpListener;
use serde_json::json;
use super::*;
fn build() -> Build {
Build { version: semver::Version::parse("1.148.0").unwrap(), release: 0, commit: "aaaa".into(), timestamp: 1_000 }
}
fn entry(version: &str, timestamp: i64) -> Vec<u8> {
release(version, "1.148.0", timestamp)
}
fn release(version: &str, product_version: &str, timestamp: i64) -> Vec<u8> {
json!({ "version": version, "productVersion": product_version, "timestamp": timestamp, "url": "VSRustium-darwin-arm64.zip", "sha256hash": "AB".repeat(32) }).to_string().into_bytes()
}
const FEED: &str = "https://github.com/rokartur/vsrustium/releases/latest/download/darwin-arm64.json";
#[test]
fn each_channel_has_its_feed_under_the_releases_url() {
let releases = "https://github.com/rokartur/vsrustium/releases";
assert_eq!(feed_url(releases, "darwin-arm64", "latest"), FEED);
assert_eq!(feed_url(&format!("{releases}/"), "darwin-arm64", "pre-release"), "https://github.com/rokartur/vsrustium/releases/download/pre-release/darwin-arm64-prerelease.json");
assert_eq!(feed_url(releases, "darwin-x64", "latest"), "https://github.com/rokartur/vsrustium/releases/latest/download/darwin-x64.json");
assert_eq!(feed_url(releases, "darwin-x64", "pre-release"), "https://github.com/rokartur/vsrustium/releases/download/pre-release/darwin-x64-prerelease.json");
}
#[test]
fn a_higher_version_is_an_update_and_a_lower_one_never() {
let on = |version: &str, timestamp: i64| Build { version: semver::Version::parse(version).unwrap(), release: 0, commit: "aaaa".into(), timestamp };
let offered = |feed: &[u8], build: &Build| parse_feed(FEED, 200, feed, build).unwrap().map(|update| update.product_version);
// Only stable releases: the next stable.
assert_eq!(offered(&release("bbbb", "1.148.0", 2_000), &on("1.147.0", 1_000)).as_deref(), Some("1.148.0"));
// A newer Insiders build on the pre-release channel, then a later build of the same Insiders version.
assert_eq!(offered(&release("bbbb", "1.149.0-insider", 3_000), &on("1.148.0", 2_000)).as_deref(), Some("1.149.0-insider"));
assert_eq!(offered(&release("dddd", "1.149.0-insider", 3_500), &on("1.149.0-insider", 3_000)).as_deref(), Some("1.149.0-insider"));
// The stable of the running Insiders version, on either channel.
assert_eq!(offered(&release("cccc", "1.149.0", 4_000), &on("1.149.0-insider", 3_000)).as_deref(), Some("1.149.0"));
// Switched to latest on an Insiders build newer than the latest stable: no downgrade, even from a later build.
assert_eq!(offered(&release("cccc", "1.148.0", 4_000), &on("1.149.0-insider", 3_000)), None);
// The same version: only a later build.
assert_eq!(offered(&release("cccc", "1.148.0", 2_500), &on("1.148.0", 2_000)).as_deref(), Some("1.148.0"));
assert!(parse_feed(FEED, 200, &release("cccc", "next", 4_000), &on("1.148.0", 2_000)).is_err());
}
#[test]
fn the_vscode_version_then_the_release_then_the_timestamp_decide() {
let on = |version: &str, release: u64, timestamp: i64| Build { version: semver::Version::parse(version).unwrap(), release, commit: "aaaa".into(), timestamp };
let offered = |release: Option<u64>, product_version: &str, timestamp: i64, build: &Build| {
let mut feed = json!({ "version": "bbbb", "productVersion": product_version, "timestamp": timestamp, "url": "VSRustium-darwin-arm64.zip", "sha256hash": "ab".repeat(32) });
if let Some(release) = release {
feed["release"] = json!(release);
}
parse_feed(FEED, 200, feed.to_string().as_bytes(), build).unwrap().map(|update| update.product_version)
};
// The same VS Code version, a higher release: an update even when built earlier.
assert_eq!(offered(Some(2), "1.148.0", 500, &on("1.148.0", 1, 1_000)).as_deref(), Some("1.148.0.2"));
// A lower release is never one, even built later.
assert_eq!(offered(Some(1), "1.148.0", 2_000, &on("1.148.0", 2, 1_000)), None);
// The same release: only a later build.
assert_eq!(offered(Some(2), "1.148.0-insider", 2_000, &on("1.148.0-insider", 2, 1_000)).as_deref(), Some("1.148.0.2-insider"));
assert_eq!(offered(Some(2), "1.148.0", 1_000, &on("1.148.0", 2, 1_000)), None);
// A higher VS Code version with release 1 beats a lower one with release 9, and never the other way.
assert_eq!(offered(Some(1), "1.149.0", 500, &on("1.148.0", 9, 1_000)).as_deref(), Some("1.149.0.1"));
assert_eq!(offered(Some(9), "1.148.0", 2_000, &on("1.149.0", 1, 1_000)), None);
// An entry without a release (published before releases) is release 0, as is a build without one.
assert_eq!(offered(None, "1.148.0", 2_000, &on("1.148.0", 1, 1_000)), None);
assert_eq!(offered(Some(1), "1.148.0", 500, &on("1.148.0", 0, 1_000)).as_deref(), Some("1.148.0.1"));
assert_eq!(offered(None, "1.148.0", 2_000, &on("1.148.0", 0, 1_000)).as_deref(), Some("1.148.0"));
}
#[test]
fn a_release_that_is_not_a_non_negative_integer_is_refused() {
for release in [json!("2"), json!(-1), json!(1.5), json!(null)] {
let mut feed: Value = serde_json::from_slice(&entry("bbbb", 2_000)).unwrap();
feed["release"] = release.clone();
assert!(parse_feed(FEED, 200, feed.to_string().as_bytes(), &build()).is_err(), "{release}");
}
}
#[test]
fn a_later_build_is_an_update_with_its_zip_beside_the_feed() {
let update = parse_feed(FEED, 200, &entry("bbbb", 2_000), &build()).unwrap().unwrap();
assert_eq!(update.url, "https://github.com/rokartur/vsrustium/releases/latest/download/VSRustium-darwin-arm64.zip");
assert_eq!(update.sha256hash, "ab".repeat(32));
assert_eq!((update.version.as_str(), update.product_version.as_str(), update.timestamp), ("bbbb", "1.148.0", 2_000));
}
#[test]
fn the_same_or_an_older_build_is_no_update() {
assert_eq!(parse_feed(FEED, 200, &entry("bbbb", 1_000), &build()).unwrap(), None);
assert_eq!(parse_feed(FEED, 200, &entry("bbbb", 500), &build()).unwrap(), None);
}
#[test]
fn no_content_and_a_missing_or_private_release_are_no_update() {
for status in [204, 401, 403, 404] {
assert_eq!(parse_feed(FEED, status, b"Not Found", &build()).unwrap(), None, "{status}");
}
assert!(parse_feed(FEED, 500, b"", &build()).is_err());
assert!(parse_feed(FEED, 200, b"<html>", &build()).is_err());
}
#[test]
fn an_entry_without_url_version_or_product_version_is_no_update() {
for key in ["url", "version", "productVersion", "timestamp"] {
let mut feed: Value = serde_json::from_slice(&entry("bbbb", 2_000)).unwrap();
feed.as_object_mut().unwrap().remove(key);
assert_eq!(parse_feed(FEED, 200, feed.to_string().as_bytes(), &build()).unwrap(), None, "{key}");
}
}
#[test]
fn a_feed_without_a_sha256_or_with_a_plain_http_zip_is_refused() {
let mut feed: Value = serde_json::from_slice(&entry("bbbb", 2_000)).unwrap();
feed["sha256hash"] = json!("abc");
assert!(parse_feed(FEED, 200, feed.to_string().as_bytes(), &build()).is_err());
feed["sha256hash"] = json!("ab".repeat(32));
feed["url"] = json!("http://example.com/VSRustium.zip");
assert!(parse_feed(FEED, 200, feed.to_string().as_bytes(), &build()).is_err());
feed["url"] = json!("file:///tmp/VSRustium.zip");
assert!(parse_feed(FEED, 200, feed.to_string().as_bytes(), &build()).is_err());
let local = parse_feed("http://127.0.0.1:8080/darwin-arm64.json", 200, &entry("bbbb", 2_000), &build()).unwrap().unwrap();
assert_eq!(local.url, "http://127.0.0.1:8080/VSRustium-darwin-arm64.zip");
}
/// Answers each request with the next reply, on 127.0.0.1: the releases URL and the requested paths.
fn serve(replies: &'static [&'static str]) -> (String, std::sync::mpsc::Receiver<String>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let (paths, received) = std::sync::mpsc::channel();
std::thread::spawn(move || {
for reply in replies {
let (mut stream, _) = listener.accept().unwrap();
let mut request = [0; 1024];
let read = stream.read(&mut request).unwrap();
let _ = paths.send(String::from_utf8_lossy(&request[..read]).split(' ').nth(1).unwrap_or_default().to_owned());
stream.write_all(reply.as_bytes()).unwrap();
}
});
(url, received)
}
fn service_with(config: Result<Config, DisablementReason>, cx: &mut gpui::TestAppContext) -> (Entity<UpdateService>, std::rc::Rc<std::cell::RefCell<Vec<State>>>) {
let service = cx.new(|_| UpdateService { state: State::Uninitialized, config, mode: None, channel: "latest".into(), schedule: 0, metered: false, deferred: false });
let events = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
let seen = events.clone();
cx.update(|cx| cx.subscribe(&service, move |_, state: &State, _| seen.borrow_mut().push(state.clone())).detach());
(service, events)
}
fn config(update_url: String, bundle: &std::path::Path) -> Config {
Config { update_url, build: build(), bundle: bundle.to_path_buf(), staging: bundle.with_file_name("staging") }
}
fn writable_bundle(name: &str) -> PathBuf {
let bundle = std::env::temp_dir().join(format!("vsrustium-service-{name}-{}/VSRustium.app", std::process::id()));
std::fs::create_dir_all(&bundle).unwrap();
bundle
}
#[gpui::test]
fn a_build_without_a_feed_or_bundle_stays_disabled(cx: &mut gpui::TestAppContext) {
let (service, events) = service_with(Err(DisablementReason::MissingConfiguration), cx);
service.update(cx, |service, cx| {
service.reconfigure("default", "latest", cx);
service.check_for_updates(true, cx);
});
assert_eq!(*events.borrow(), [State::Disabled(DisablementReason::MissingConfiguration)]);
}
#[gpui::test]
fn update_mode_none_disables_and_manual_enables_again(cx: &mut gpui::TestAppContext) {
let bundle = writable_bundle("mode");
let (service, events) = service_with(Ok(config("http://127.0.0.1:9/feed.json".into(), &bundle)), cx);
service.update(cx, |service, cx| {
service.reconfigure("none", "latest", cx);
service.check_for_updates(true, cx);
service.reconfigure("none", "latest", cx);
service.reconfigure("manual", "latest", cx);
});
let idle = State::Idle { error: None, not_available: false };
assert_eq!(*events.borrow(), [State::Disabled(DisablementReason::ManuallyDisabled), idle.clone()]);
assert_eq!(service.read_with(cx, |service, _| service.state().clone()), idle);
}
#[gpui::test]
fn an_explicit_check_without_an_update_says_so_once(cx: &mut gpui::TestAppContext) {
let bundle = writable_bundle("none");
let (url, _) = serve(&["HTTP/1.1 404 Not Found\r\nContent-Length: 9\r\nConnection: close\r\n\r\nNot Found"]);
let (service, events) = service_with(Ok(config(url, &bundle)), cx);
service.update(cx, |service, cx| {
service.reconfigure("manual", "latest", cx);
service.check_for_updates(true, cx);
// Only from Idle: a second check while one runs does nothing.
service.check_for_updates(true, cx);
});
cx.run_until_parked();
let events = events.borrow();
assert_eq!(events[1..], [State::CheckingForUpdates { explicit: true }, State::Idle { error: None, not_available: true }]);
assert_eq!(service.read_with(cx, |service, _| service.state().clone()), State::Idle { error: None, not_available: false });
}
#[gpui::test]
#[cfg(target_os = "macos")]
fn a_read_only_bundle_fails_the_check_with_squirrels_message_when_explicit(cx: &mut gpui::TestAppContext) {
let bundle = PathBuf::from("/System/Applications/Calculator.app");
let (service, events) = service_with(Ok(Config { update_url: "http://127.0.0.1:9".into(), build: build(), bundle, staging: std::env::temp_dir().join("vsrustium-service-unused") }), cx);
service.update(cx, |service, cx| {
service.reconfigure("manual", "latest", cx);
service.check_for_updates(false, cx);
});
cx.run_until_parked();
service.update(cx, |service, cx| service.check_for_updates(true, cx));
cx.run_until_parked();
let events = events.borrow();
assert_eq!(events[2], State::Idle { error: None, not_available: false });
let State::Idle { error: Some(error), .. } = &events[4] else { panic!("{:?}", events[4]) };
assert!(error.starts_with("Cannot update while running on a read-only volume."));
}
#[gpui::test]
fn the_release_channel_picks_the_feed_from_the_next_check(cx: &mut gpui::TestAppContext) {
let bundle = writable_bundle("channel");
const NONE: &str = "HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n";
let (url, paths) = serve(&[NONE, NONE]);
let (service, _) = service_with(Ok(config(url, &bundle)), cx);
service.update(cx, |service, cx| {
service.reconfigure("manual", "pre-release", cx);
service.check_for_updates(true, cx);
});
cx.run_until_parked();
service.update(cx, |service, cx| {
service.reconfigure("manual", "latest", cx);
service.check_for_updates(true, cx);
});
cx.run_until_parked();
let platform = exthost::gallery::CURRENT_TARGET_PLATFORM;
assert_eq!(paths.try_iter().collect::<Vec<_>>(), [format!("/download/pre-release/{platform}-prerelease.json"), format!("/latest/download/{platform}.json")]);
}
#[gpui::test]
fn a_metered_connection_defers_the_automatic_check_until_it_is_not_metered(cx: &mut gpui::TestAppContext) {
let bundle = writable_bundle("metered-check");
let (url, paths) = serve(&["HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n"]);
let (service, events) = service_with(Ok(config(url, &bundle)), cx);
service.update(cx, |service, cx| {
service.reconfigure("default", "latest", cx);
service.set_metered(true, cx);
service.check_for_updates(false, cx);
});
cx.run_until_parked();
assert_eq!(service.read_with(cx, |service, _| (service.state().type_name(), service.deferred)), ("idle", true));
assert_eq!(paths.try_iter().count(), 0);
service.update(cx, |service, cx| service.set_metered(false, cx));
cx.executor().advance_clock(Duration::from_millis(1));
cx.run_until_parked();
assert_eq!(paths.try_iter().collect::<Vec<_>>(), [format!("/latest/download/{}.json", exthost::gallery::CURRENT_TARGET_PLATFORM)]);
assert!(events.borrow().contains(&State::CheckingForUpdates { explicit: false }));
}
#[gpui::test]
#[cfg(target_os = "macos")]
fn an_update_found_on_a_metered_connection_waits_for_download(cx: &mut gpui::TestAppContext) {
let bundle = writable_bundle("metered-download");
let body = String::from_utf8(release("bbbb", "1.149.0", 2_000)).unwrap();
let reply: &'static str = Box::leak(format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).into_boxed_str());
let (url, _) = serve(Box::leak(Box::new([reply])));
let (service, events) = service_with(Ok(config(url, &bundle)), cx);
service.update(cx, |service, cx| {
service.reconfigure("manual", "latest", cx);
service.check_for_updates(false, cx);
// The connection turns metered while the feed is fetched.
service.set_metered(true, cx);
});
cx.run_until_parked();
let available = service.read_with(cx, |service, _| (service.state().type_name(), service.deferred));
assert_eq!(available, ("available for download", true));
service.update(cx, |service, cx| {
service.download_update(false, cx);
assert_eq!(service.state().type_name(), "available for download", "an automatic download waits");
service.download_update(true, cx);
assert_eq!(service.state().type_name(), "downloading", "Download Update (1) downloads on a metered connection");
});
let State::AvailableForDownload { update } = &events.borrow()[2] else { panic!("{:?}", events.borrow()) };
assert_eq!(update.product_version, "1.149.0");
}
#[gpui::test]
#[cfg(target_os = "macos")]
fn a_deferred_download_starts_once_the_connection_is_not_metered(cx: &mut gpui::TestAppContext) {
let bundle = writable_bundle("metered-resume");
let (service, _) = service_with(Ok(config("http://127.0.0.1:9/feed.json".into(), &bundle)), cx);
let update = Update { version: "bbbb".into(), product_version: "1.149.0".into(), timestamp: 2_000, url: "http://127.0.0.1:9/a.zip".into(), sha256hash: "ab".repeat(32) };
service.update(cx, |service, cx| {
service.reconfigure("manual", "latest", cx);
service.set_metered(true, cx);
service.state = State::AvailableForDownload { update };
service.deferred = true;
service.set_metered(false, cx);
assert_eq!(service.state().type_name(), "available for download", "update.mode manual resumes nothing");
service.mode = Some("default".into());
service.set_metered(true, cx);
service.set_metered(false, cx);
assert_eq!(service.state().type_name(), "downloading");
});
}
#[gpui::test]
#[cfg(target_os = "linux")]
fn an_update_found_on_linux_waits_and_download_opens_its_link(cx: &mut gpui::TestAppContext) {
let bundle = writable_bundle("linux-download");
let body = String::from_utf8(release("bbbb", "1.149.0", 2_000)).unwrap();
let reply: &'static str = Box::leak(format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).into_boxed_str());
let (url, _) = serve(Box::leak(Box::new([reply])));
let (service, _) = service_with(Ok(config(url, &bundle)), cx);
service.update(cx, |service, cx| {
service.reconfigure("manual", "latest", cx);
service.check_for_updates(true, cx);
});
cx.run_until_parked();
let State::AvailableForDownload { update } = service.read_with(cx, |service, _| service.state().clone()) else { panic!("no update found") };
service.update(cx, |service, cx| service.download_update(true, cx));
assert_eq!(cx.opened_url(), Some(update.url));
assert_eq!(service.read_with(cx, |service, _| service.state().type_name()), "idle");
}
#[gpui::test]
fn restart_starts_only_from_ready_and_a_veto_puts_ready_back(cx: &mut gpui::TestAppContext) {
let bundle = writable_bundle("restart");
let (service, _) = service_with(Ok(config("http://127.0.0.1:9/feed.json".into(), &bundle)), cx);
let update = Update { version: "bbbb".into(), product_version: "1.148.0".into(), timestamp: 2_000, url: "https://example.com/a.zip".into(), sha256hash: "ab".repeat(32) };
let ready = State::Ready { update: update.clone(), app: bundle.clone() };
service.update(cx, |service, cx| {
assert!(!service.begin_restart(cx));
service.state = ready.clone();
assert!(service.begin_restart(cx));
assert_eq!(service.state().type_name(), "restarting");
service.cancel_restart(cx);
assert_eq!(*service.state(), ready);
});
}
#[test]
fn the_content_length_is_the_last_responses() {
assert_eq!(content_length("HTTP/1.1 302 Found\r\ncontent-length: 0\r\n\r\nHTTP/1.1 200 OK\r\nContent-Length: 1234\r\n\r\n"), Some(1234));
assert_eq!(content_length(""), None);
}
#[test]
fn fetch_feed_reads_the_status_and_body_of_a_local_feed() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://{}/darwin-arm64.json", listener.local_addr().unwrap());
let server = std::thread::spawn(move || {
for reply in ["HTTP/1.1 404 Not Found\r\nContent-Length: 9\r\nConnection: close\r\n\r\nNot Found", "HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\n{\n}\n"] {
let (mut stream, _) = listener.accept().unwrap();
let mut request = [0; 1024];
let _ = stream.read(&mut request).unwrap();
stream.write_all(reply.as_bytes()).unwrap();
}
});
assert_eq!(fetch_feed(&url).unwrap(), (404, b"Not Found".to_vec()));
assert_eq!(fetch_feed(&url).unwrap(), (200, b"{\n}\n".to_vec()));
server.join().unwrap();
}