Skip to content

Visual Studio Code, rebuilt in Rust

Rust
24.4 KB
Raw Blame
//! platform/update (update.ts, abstractUpdateService.ts, updateService.darwin.ts) for the port's macOS app: the feed
//! at product.json `updateUrl` names the newest build, which is downloaded in the background, verified and installed
//! by a helper after the app quits. On Linux (updateService.linux.ts) a found build waits in AvailableForDownload and
//! Download opens its link in the browser. The feed format is in port/notes.md ("Update feed").

pub mod install;
pub mod unattended_restart;

use std::io::Read;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::Duration;

use anyhow::{Context as _, bail};
use gpui::{App, AppContext, AsyncApp, Context, Entity, EventEmitter, Global, WeakEntity};
use serde_json::Value;

/// abstractUpdateService.ts: the first check 30 s after startup, then hourly with `update.mode: default`.
const FIRST_CHECK: Duration = Duration::from_secs(30);
const CHECK_INTERVAL: Duration = Duration::from_secs(60 * 60);
const PROGRESS_INTERVAL: Duration = Duration::from_millis(250);
/// Windows 10 1803 and later ship curl.exe in System32.
const CURL: &str = if cfg!(windows) { "curl" } else { "/usr/bin/curl" };

/// update.ts `State` of the darwin flow. Not reached on macOS: `Updating` (Windows), `Overwriting` and `Cancelling`.
#[derive(Clone, Debug, PartialEq)]
pub enum State {
    Uninitialized,
    Disabled(DisablementReason),
    /// `error` and `not_available` are one-time: the state keeps neither after its event.
    Idle { error: Option<String>, not_available: bool },
    CheckingForUpdates { explicit: bool },
    /// An update found on a metered connection, downloaded when asked or once the connection is not metered.
    AvailableForDownload { update: Update },
    /// `started_at` is `startTime`, for the tooltip's speed and time remaining.
    Downloading { update: Update, explicit: bool, downloaded_bytes: u64, total_bytes: Option<u64>, started_at: std::time::Instant },
    Downloaded { update: Update },
    /// `app` is the verified bundle in the staging folder.
    Ready { update: Update, app: PathBuf },
    Restarting { update: Update, app: PathBuf },
}

impl State {
    /// `StateType`, the value of the `updateState` context key.
    pub fn type_name(&self) -> &'static str {
        match self {
            State::Uninitialized => "uninitialized",
            State::Disabled(_) => "disabled",
            State::Idle { .. } => "idle",
            State::CheckingForUpdates { .. } => "checking for updates",
            State::AvailableForDownload { .. } => "available for download",
            State::Downloading { .. } => "downloading",
            State::Downloaded { .. } => "downloaded",
            State::Ready { .. } => "ready",
            State::Restarting { .. } => "restarting",
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DisablementReason {
    /// Not running from an app bundle (a build folder), as upstream out of sources.
    NotBuilt,
    ManuallyDisabled,
    /// No `updateUrl`, `commit` or `date` in product.json.
    MissingConfiguration,
}

/// `IUpdate`: one build in the feed.
#[derive(Clone, Debug, PartialEq)]
pub struct Update {
    /// The build's commit.
    pub version: String,
    /// The display version, `productVersion` with the feed's `release` (`product::with_release`).
    pub product_version: String,
    /// When the build was packaged, in ms since the epoch: a later build is newer.
    pub timestamp: i64,
    /// The zip's absolute URL (a relative one in the feed resolves against the feed's).
    pub url: String,
    pub sha256hash: String,
}

/// The running build: product.json's `version` and `release` (0 on a build from before releases), and `commit` and
/// `date`, which package-app writes (the commit only marks a built app, as upstream's; builds of one commit with other
/// versions are updates).
#[derive(Clone, Debug, PartialEq)]
pub struct Build {
    pub version: semver::Version,
    pub release: u64,
    pub commit: String,
    pub timestamp: i64,
}

impl Build {
    pub fn current() -> Option<Build> {
        let version = semver::Version::parse(crate::product::get("version").as_str()?).ok()?;
        let release = crate::product::get("release").as_u64().unwrap_or(0);
        let commit = crate::product::get("commit").as_str()?.to_owned();
        let date = crate::product::get("date").as_str()?;
        let timestamp = chrono::DateTime::parse_from_rfc3339(date).ok()?.timestamp_millis();
        Some(Build { version, release, commit, timestamp })
    }
}

/// The feed of a release channel (port addition, `update.releaseChannel`) under product.json `updateUrl`, a GitHub
/// repository's releases URL: `latest` is the newest release not marked pre-release (GitHub's `releases/latest`);
/// `pre-release` is the asset every release also puts on the release tagged `pre-release`. Each `platform` (VS Code's
/// target platform the app was built for, `darwin-arm64` or `darwin-x64`) has its own feed.
pub fn feed_url(update_url: &str, platform: &str, channel: &str) -> String {
    let update_url = update_url.trim_end_matches('/');
    match channel {
        "pre-release" => format!("{update_url}/download/pre-release/{platform}-prerelease.json"),
        _ => format!("{update_url}/latest/download/{platform}.json"),
    }
}

/// The feed's answer for `build`: its update when its (VS Code version, release, timestamp) is higher, in that order; a
/// lower one is never an update, so a channel switch does not downgrade. An entry without `release` is release 0. 204 is upstream's "no update"; 401, 403 and 404
/// are a missing or private release.
pub fn parse_feed(feed_url: &str, status: u16, body: &[u8], build: &Build) -> anyhow::Result<Option<Update>> {
    match status {
        200 => {}
        204 | 401 | 403 | 404 => return Ok(None),
        _ => bail!("Server returned {status}"),
    }
    let feed: Value = serde_json::from_slice(body).context("The update feed is not JSON")?;
    let text = |key: &str| feed[key].as_str().filter(|value| !value.is_empty());
    // checkForUpdateNoDownload: an entry without url, version or productVersion is no update.
    let (Some(version), Some(product_version), Some(url), Some(timestamp)) = (text("version"), text("productVersion"), text("url"), feed["timestamp"].as_i64()) else {
        return Ok(None);
    };
    let sha256hash = text("sha256hash").filter(|hash| hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit())).context("The update feed has no SHA-256 hash")?;
    let url = url::Url::parse(feed_url)?.join(url)?;
    let loopback = matches!(url.host_str(), Some("127.0.0.1" | "localhost" | "[::1]"));
    if url.scheme() != "https" && !(url.scheme() == "http" && loopback) {
        bail!("The update URL must use https: {url}");
    }
    let candidate = semver::Version::parse(product_version).with_context(|| format!("The update's version {product_version} is not a semantic version"))?;
    let release = match feed.get("release") {
        None => 0,
        Some(release) => release.as_u64().with_context(|| format!("The update's release {release} is not a non-negative integer"))?,
    };
    if (&candidate, release, timestamp) <= (&build.version, build.release, build.timestamp) {
        return Ok(None);
    }
    Ok(Some(Update { version: version.into(), product_version: crate::product::with_release(product_version, release), timestamp, url: url.into(), sha256hash: sha256hash.to_ascii_lowercase() }))
}

/// GETs the feed through curl (redirects followed, as a GitHub `releases/latest/download` URL needs): status and body.
pub fn fetch_feed(url: &str) -> anyhow::Result<(u16, Vec<u8>)> {
    let output = std::process::Command::new(CURL).args(["-sSL", "--max-time", "30", "-w", "\n%{http_code}", url]).output()?;
    if !output.status.success() {
        bail!("{}", String::from_utf8_lossy(&output.stderr).trim());
    }
    let split = output.stdout.iter().rposition(|byte| *byte == b'\n').context("curl wrote no status")?;
    let status = std::str::from_utf8(&output.stdout[split + 1..])?.parse()?;
    Ok((status, output.stdout[..split].to_vec()))
}

/// What a check needs: product.json `updateUrl`, the running build and its bundle.
#[derive(Clone)]
struct Config {
    update_url: String,
    build: Build,
    bundle: PathBuf,
    /// `<ShipIt>/update`: the download and its extracted bundle.
    staging: PathBuf,
}

impl Config {
    fn current() -> Result<Config, DisablementReason> {
        let bundle = install::running_bundle().ok_or(DisablementReason::NotBuilt)?;
        let update_url = crate::product::get("updateUrl").as_str().filter(|url| !url.is_empty()).ok_or(DisablementReason::MissingConfiguration)?;
        let build = Build::current().ok_or(DisablementReason::MissingConfiguration)?;
        Ok(Config { update_url: update_url.to_owned(), build, bundle, staging: install::shipit_dir().join("update") })
    }
}

/// The app's one update service (upstream's lives in the main process); windows subscribe to its state events.
pub struct UpdateService {
    state: State,
    config: Result<Config, DisablementReason>,
    mode: Option<String>,
    /// `update.releaseChannel`.
    channel: String,
    /// Bumped to cancel the scheduled checks.
    schedule: u64,
    /// `meteredConnectionService.isConnectionMetered`, which the windows report.
    metered: bool,
    /// An automatic check or download skipped on a metered connection, resumed once it is not metered.
    deferred: bool,
}

impl EventEmitter<State> for UpdateService {}

struct GlobalUpdateService(Entity<UpdateService>);

impl Global for GlobalUpdateService {}

/// The service, created with the first window. A download left by an earlier run is removed then.
pub fn service(cx: &mut App) -> Entity<UpdateService> {
    if let Some(global) = cx.try_global::<GlobalUpdateService>() {
        return global.0.clone();
    }
    let entity = cx.new(|cx: &mut Context<UpdateService>| {
        let config = Config::current();
        if let Ok(config) = &config {
            let _ = std::fs::remove_dir_all(&config.staging);
            cx.on_app_quit(|service: &mut UpdateService, _| {
                service.install_on_quit();
                async {}
            })
            .detach();
        }
        UpdateService { state: State::Uninitialized, config, mode: None, channel: "latest".into(), schedule: 0, metered: false, deferred: false }
    });
    cx.set_global(GlobalUpdateService(entity.clone()));
    entity
}

impl UpdateService {
    pub fn state(&self) -> &State {
        &self.state
    }

    fn set_state(&mut self, state: State, cx: &mut Context<Self>) {
        if self.state.type_name() != state.type_name() {
            eprintln!("[update] update#setState {}", state.type_name());
        }
        self.state = state.clone();
        self.deferred = false;
        cx.emit(state);
        cx.notify();
        if let State::Idle { .. } = self.state {
            self.state = State::Idle { error: None, not_available: false };
        }
    }

    /// `doReconfigure` for an `update.mode` value: `none` disables (cancelling a download or a pending update),
    /// `manual` checks only when asked, `start` once 30 s after startup, `default` also hourly after that. The
    /// release channel applies from the next check.
    pub fn reconfigure(&mut self, mode: &str, channel: &str, cx: &mut Context<Self>) {
        self.channel = channel.to_owned();
        if self.mode.as_deref() == Some(mode) {
            return;
        }
        self.mode = Some(mode.to_owned());
        let staging = match &self.config {
            Ok(config) => config.staging.clone(),
            Err(reason) => {
                let reason = *reason;
                eprintln!("[update] updates are disabled: {reason:?}");
                self.set_state(State::Disabled(reason), cx);
                return;
            }
        };
        self.schedule += 1;
        if mode == "none" {
            let _ = std::fs::remove_dir_all(staging);
            self.set_state(State::Disabled(DisablementReason::ManuallyDisabled), cx);
            return;
        }
        if matches!(self.state, State::Disabled(_) | State::Uninitialized) {
            self.set_state(State::Idle { error: None, not_available: false }, cx);
        }
        if mode == "manual" {
            return;
        }
        if self.deferred && !self.metered {
            self.resume_automatic_updates(cx);
            return;
        }
        self.schedule_check(FIRST_CHECK, mode != "start", cx);
    }

    /// `onDidChangeIsConnectionMetered`: a connection no longer metered resumes what it deferred.
    pub fn set_metered(&mut self, metered: bool, cx: &mut Context<Self>) {
        if self.metered == metered {
            return;
        }
        self.metered = metered;
        if !metered {
            self.resume_automatic_updates(cx);
        }
    }

    /// `resumeAutomaticUpdates`: a deferred download starts; from Idle, a check now, and hourly after it with
    /// `update.mode: default`.
    fn resume_automatic_updates(&mut self, cx: &mut Context<Self>) {
        let mode = self.mode.clone().unwrap_or_default();
        if self.config.is_err() || matches!(mode.as_str(), "" | "none" | "manual") {
            return;
        }
        if let State::AvailableForDownload { .. } = self.state {
            if self.deferred {
                self.download_update(false, cx);
            }
            return;
        }
        if !matches!(self.state, State::Idle { .. }) || (mode == "start" && !self.deferred) {
            return;
        }
        self.deferred = false;
        self.schedule += 1;
        self.schedule_check(Duration::ZERO, mode == "default", cx);
    }

    fn schedule_check(&mut self, first: Duration, repeat: bool, cx: &mut Context<Self>) {
        let id = self.schedule;
        cx.spawn(async move |this, cx| {
            let mut wait = first;
            loop {
                cx.background_executor().timer(wait).await;
                let current = this.update(cx, |this, cx| {
                    let current = this.schedule == id;
                    if current {
                        this.check_for_updates(false, cx);
                    }
                    current
                });
                if !current.unwrap_or(false) || !repeat {
                    return;
                }
                wait = CHECK_INTERVAL;
            }
        })
        .detach();
    }

    /// `checkForUpdates`: only from Idle, and an automatic one not on a metered connection. A newer build starts
    /// downloading at once, as Squirrel does.
    pub fn check_for_updates(&mut self, explicit: bool, cx: &mut Context<Self>) {
        let (State::Idle { .. }, Ok(config)) = (&self.state, &self.config) else { return };
        if !explicit && self.metered {
            eprintln!("[update] update#checkForUpdates - skipping automatic check because connection is metered");
            self.deferred = true;
            return;
        }
        let (config, channel) = (config.clone(), self.channel.clone());
        self.set_state(State::CheckingForUpdates { explicit }, cx);
        let found = cx.background_spawn(async move { find_update(&config, &channel) });
        cx.spawn(async move |this, cx| {
            let found = found.await;
            let _ = this.update(cx, |this, cx| {
                if this.state != (State::CheckingForUpdates { explicit }) {
                    return;
                }
                match found {
                    Ok(Some(update)) => this.found_update(update, explicit, cx),
                    Ok(None) => this.set_state(State::Idle { error: None, not_available: explicit }, cx),
                    Err(error) => this.on_error(error, cx),
                }
            });
        })
        .detach();
    }

    /// updateService.darwin.ts `onError`: back to Idle from a check or a download; the message only for an explicit
    /// check. The staged download is removed.
    fn on_error(&mut self, error: anyhow::Error, cx: &mut Context<Self>) {
        eprintln!("[update] UpdateService error: {error:#}");
        let message = match self.state {
            State::CheckingForUpdates { explicit } => explicit.then(|| format!("{error:#}")),
            State::Downloading { .. } => None,
            _ => return,
        };
        if let Ok(config) = &self.config {
            let _ = std::fs::remove_dir_all(&config.staging);
        }
        self.set_state(State::Idle { error: message, not_available: false }, cx);
    }

    /// The connection turned metered during an automatic check: `deferAutomaticDownload`, as the darwin flow's
    /// check without download (`checkForUpdateNoDownload`).
    fn found_update(&mut self, update: Update, explicit: bool, cx: &mut Context<Self>) {
        if cfg!(any(target_os = "linux", target_os = "windows")) {
            self.set_state(State::AvailableForDownload { update }, cx);
            return;
        }
        if explicit || !self.metered {
            self.download(update, explicit, cx);
            return;
        }
        eprintln!("[update] update#deferAutomaticDownload - deferring download because connection is metered");
        self.set_state(State::AvailableForDownload { update }, cx);
        self.deferred = true;
    }

    /// `downloadUpdate` (Download Update (1), the title bar entry): only from AvailableForDownload, and an automatic
    /// one not on a metered connection.
    pub fn download_update(&mut self, explicit: bool, cx: &mut Context<Self>) {
        let State::AvailableForDownload { update } = &self.state else { return };
        if !explicit && self.metered {
            eprintln!("[update] update#downloadUpdate - skipping download because connection is metered");
            self.deferred = true;
            return;
        }
        // Windows as Linux until the user setup updates in place (port/ledger.md decision "Windows updates").
        if cfg!(any(target_os = "linux", target_os = "windows")) {
            // updateService.linux.ts: the package type is unknown, so product.json `downloadUrl` beats the archive.
            let download_url = crate::product::get("downloadUrl").as_str().filter(|url| !url.is_empty()).unwrap_or(&update.url).to_owned();
            cx.open_url(&download_url);
            self.set_state(State::Idle { error: None, not_available: false }, cx);
            return;
        }
        let update = update.clone();
        self.download(update, explicit, cx);
    }

    fn download(&mut self, update: Update, explicit: bool, cx: &mut Context<Self>) {
        let Ok(config) = self.config.clone() else { return };
        self.set_state(State::Downloading { update: update.clone(), explicit, downloaded_bytes: 0, total_bytes: None, started_at: std::time::Instant::now() }, cx);
        cx.spawn(async move |this, cx| {
            // App Nap throttles a background app's timers and the processes it starts; the download and its
            // verification must not wait for the window to come to front.
            #[cfg(target_os = "macos")]
            let (process, activity) = {
                let process = objc2_foundation::NSProcessInfo::processInfo();
                let reason = objc2_foundation::NSString::from_str("Downloading an update");
                let activity = process.beginActivityWithOptions_reason(objc2_foundation::NSActivityOptions::UserInitiatedAllowingIdleSystemSleep, &reason);
                (process, activity)
            };
            let downloaded = download_and_verify(&this, &update, &config, cx).await;
            // SAFETY: `activity` is the token beginActivityWithOptions returned.
            #[cfg(target_os = "macos")]
            unsafe {
                process.endActivity(&activity)
            };
            let _ = this.update(cx, |this, cx| {
                if !matches!(this.state, State::Downloading { .. }) {
                    return;
                }
                match downloaded {
                    Ok(app) => {
                        eprintln!("[update] Update downloaded: {} ({}), verified at {}", update.product_version, update.version, app.display());
                        this.set_state(State::Downloaded { update: update.clone() }, cx);
                        this.set_state(State::Ready { update, app }, cx);
                    }
                    Err(error) => this.on_error(error, cx),
                }
            });
        })
        .detach();
    }

    /// The download's progress; false once the state left Downloading (updates were disabled).
    fn set_progress(&mut self, downloaded: u64, total: Option<u64>, cx: &mut Context<Self>) -> bool {
        let State::Downloading { update, explicit, started_at, .. } = &self.state else { return false };
        let state = State::Downloading { update: update.clone(), explicit: *explicit, downloaded_bytes: downloaded, total_bytes: total, started_at: *started_at };
        self.set_state(state, cx);
        true
    }

    /// `quitAndInstall`'s first step: Ready becomes Restarting; the caller quits the windows, and on a veto puts
    /// Ready back with `cancel_restart`. The helper starts when the app quits.
    pub fn begin_restart(&mut self, cx: &mut Context<Self>) -> bool {
        let State::Ready { update, app } = &self.state else { return false };
        let state = State::Restarting { update: update.clone(), app: app.clone() };
        self.set_state(state, cx);
        true
    }

    #[cfg(test)]
    pub(crate) fn set_state_for_tests(&mut self, state: State, cx: &mut Context<Self>) {
        self.set_state(state, cx);
    }

    pub fn cancel_restart(&mut self, cx: &mut Context<Self>) {
        if let State::Restarting { update, app } = &self.state {
            let state = State::Ready { update: update.clone(), app: app.clone() };
            self.set_state(state, cx);
        }
    }

    /// Squirrel installs a downloaded update when the app quits; Restart to Update also relaunches it.
    fn install_on_quit(&mut self) {
        let (State::Ready { app, .. } | State::Restarting { app, .. }, Ok(config)) = (&self.state, &self.config) else { return };
        let relaunch = matches!(self.state, State::Restarting { .. });
        if let Err(error) = install::spawn_helper(app, &config.bundle, relaunch) {
            eprintln!("[update] could not start the update helper: {error:#}");
        }
    }
}

/// Squirrel's read-only check (macOS), then the feed.
fn find_update(config: &Config, channel: &str) -> anyhow::Result<Option<Update>> {
    #[cfg(target_os = "macos")]
    install::check_writable(&config.bundle)?;
    let url = feed_url(&config.update_url, exthost::gallery::CURRENT_TARGET_PLATFORM, channel);
    let (status, body) = fetch_feed(&url)?;
    if status != 200 {
        eprintln!("[update] {url} answered {status}: no update");
    }
    parse_feed(&url, status, &body, &config.build)
}

/// Downloads the zip into `<ShipIt>/update` with curl, reporting its progress, then verifies it
/// (`install::verify_download`); answers the verified bundle.
async fn download_and_verify(this: &WeakEntity<UpdateService>, update: &Update, config: &Config, cx: &mut AsyncApp) -> anyhow::Result<PathBuf> {
    let staging = config.staging.clone();
    let _ = std::fs::remove_dir_all(&staging);
    std::fs::create_dir_all(&staging)?;
    let (zip, headers) = (staging.join("update.zip"), staging.join("headers"));
    let mut curl = Command::new(CURL).args(["-fsSL", "--max-time", "3600", "-D"]).arg(&headers).arg("-o").arg(&zip).arg(&update.url).stdout(Stdio::null()).stderr(Stdio::piped()).spawn()?;
    let status = loop {
        cx.background_executor().timer(PROGRESS_INTERVAL).await;
        if let Some(status) = curl.try_wait()? {
            break status;
        }
        let downloaded = std::fs::metadata(&zip).map_or(0, |metadata| metadata.len());
        let total = content_length(&std::fs::read_to_string(&headers).unwrap_or_default());
        if !this.update(cx, |this, cx| this.set_progress(downloaded, total, cx))? {
            let _ = curl.kill();
            bail!("The download was cancelled");
        }
    };
    if !status.success() {
        let mut stderr = String::new();
        curl.stderr.take().context("curl's stderr")?.read_to_string(&mut stderr)?;
        bail!("Could not download the update: {}", stderr.trim());
    }
    let (sha256hash, bundle) = (update.sha256hash.clone(), config.bundle.clone());
    cx.background_spawn(async move { install::verify_download(&zip, &sha256hash, &staging, &bundle) }).await
}

/// The last `Content-Length` of curl's header dump (each redirect adds a response).
fn content_length(headers: &str) -> Option<u64> {
    headers.lines().filter_map(|line| line.split_once(':').filter(|(name, _)| name.eq_ignore_ascii_case("content-length"))).last()?.1.trim().parse().ok()
}

#[cfg(test)]
mod tests;