Skip to content

Visual Studio Code, rebuilt in Rust

Rust
13.6 KB
Raw Blame
//! One extension host start per window: the channels, the `HostSync` the workbench queues on, the `exthost-session`
//! thread and the loops of the window's thread that serve it. main.rs `open_window` starts a window's first host,
//! `workbench/extension_host_restart.rs` every later one.

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, channel};
use std::sync::{Arc, Mutex};

use config::configuration::Overrides;
use config::service::Settings;
use config::workspace::Workspace;
use exthost::extension_development::{ExtensionDevelopment, ExtensionHostDebug};
use exthost::extension_management::WindowExtensions;
use exthost::main_thread_configuration::MainThreadConfiguration;
use exthost::main_thread_files::MainThreadFiles;
use exthost::main_thread_secret_state::MainThreadSecretState;
use exthost::main_thread_storage::MainThreadStorage;
use exthost::main_thread_workspace::MainThreadWorkspace;
use exthost::rpc::Arg;
use exthost::scan::ScannedExtension;
use exthost::session::{ForwardedRequest, Session, SessionPaths, init_data, workspace_data};
use exthost::{ExtensionHost, HostOptions, Inbox, Runtime, WakingSender};
use futures::StreamExt;
use futures::channel::mpsc::{UnboundedSender, unbounded};
use futures::channel::oneshot;
use gpui::{Context, Window};
use serde_json::{Value, json};
use storage::state::FileStorage;

use crate::host_sync::{HostMessage, HostSync};
use crate::languages::Languages;
use crate::main_thread::{HostRequest, WorkbenchMainThread};
use crate::theme::ThemeKind;
use crate::workbench::Workbench;
use crate::workbench::extension_host_restart::{serve_host_requests, serve_main_thread_requests};
use crate::{main_thread_commands, main_thread_status_bar, perf, product};

/// How a window's hosts run: set by `open_window`, the same for each restart.
#[derive(Clone)]
pub(crate) struct HostLaunch {
    pub process: HostProcess,
    /// `--user-data-dir`, whose `User` folder has the settings and the global storage.
    pub user_data: PathBuf,
}

#[derive(Clone)]
pub(crate) enum HostProcess {
    /// A Bun process (Node with `--node`) that runs the host bundle.
    Runtime(Runtime),
    /// `ExtensionHost::silent`: the test gets the init data and its end of the host's socket.
    #[cfg(test)]
    Silent(std::sync::mpsc::Sender<(Value, exthost::SilentPeer)>),
}

/// A host that does not run yet: what the workbench queues for it waits in `messages`.
pub(crate) struct HostStart {
    inbox: Inbox,
    messages: Receiver<HostMessage>,
}

impl HostStart {
    /// The `HostSync` of a new host, with the color theme and the language ids queued first.
    pub fn new(theme: ThemeKind, languages: &Languages) -> (HostStart, HostSync) {
        let (sender, messages) = channel();
        let inbox = Inbox::default();
        let host = HostSync::new(WakingSender::new(sender, inbox.waker()));
        host.send_color_theme(theme);
        host.send_language_ids(languages);
        (HostStart { inbox, messages }, host)
    }
}

impl Workbench {
    /// Runs the host of `start` with the window's running extensions, settings, storage, trust and workspace as they
    /// are now. The receiver fires when its eager extensions activated.
    pub(crate) fn spawn_extension_host(&mut self, start: HostStart, launch: HostLaunch, development: Option<ExtensionDevelopment>, window: &mut Window, cx: &mut Context<Self>) -> oneshot::Receiver<()> {
        let HostStart { inbox, messages } = start;
        let (status, mut status_lines) = unbounded::<String>();
        let (request_sender, requests) = unbounded::<ForwardedRequest>();
        let (reply_sender, replies) = channel();
        let reply_sender = WakingSender::new(reply_sender, inbox.waker());
        let (main_thread_sender, main_thread_requests) = unbounded::<HostRequest>();
        let user = self.extensions_viewlet.user.as_ref().expect("the user extensions are set at startup").clone_for_profile();
        let extensions = WindowExtensions { builtins: self.extensions_viewlet.builtins.clone(), user, running: self.extensions.clone(), proposed_api: self.proposed_api.clone() };
        let main_thread = WorkbenchMainThread { requests: main_thread_sender, messages, waiting: Vec::new(), content_providers: Default::default(), extensions };
        let window_state = WindowState {
            launch,
            app_root: self.app_root.clone(),
            extensions: self.extensions.clone(),
            settings: self.settings.clone(),
            storage: MainThreadStorage { profile: self.profile_storage.clone(), workspace: self.workspace_storage.clone() },
            workspace_trusted: self.workspace_trust.is_trusted(),
            workspace: self.workspace().cloned(),
            development,
            host_debug: self.extension_host_debug.clone(),
        };
        let window_closed = Arc::new(AtomicBool::new(false));
        let (session_ended, ended) = oneshot::channel::<()>();
        self.watch_session_end(window_closed.clone(), inbox.waker(), ended, cx);
        let start = self.extension_host_started(cx);
        std::thread::Builder::new()
            .name("exthost-session".into())
            .spawn(move || {
                let runs_tests = window_state.development.as_ref().is_some_and(|development| development.tests_path.is_some());
                if let Err(error) = run_extension_host(window_state, main_thread, request_sender, replies, inbox, &status, &window_closed) {
                    if runs_tests {
                        eprintln!("extension host failed: {error:#}");
                        std::process::exit(1);
                    }
                    let _ = status.unbounded_send(format!("extension host failed: {error:#}"));
                }
                let _ = session_ended.send(());
            })
            .expect("spawn exthost session thread");
        serve_host_requests(requests, reply_sender, window, cx);
        serve_main_thread_requests(main_thread_requests, window, cx);
        let (activated_sender, activated) = oneshot::channel();
        let mut activated_sender = Some(activated_sender);
        cx.spawn_in(window, async move |workbench, cx| {
            while let Some(line) = status_lines.next().await {
                eprintln!("{line}");
                if line == EXITED_LINE {
                    let _ = workbench.update_in(cx, |workbench, window, cx| workbench.extension_host_exited(start, window, cx));
                }
                if line.starts_with(HANDSHAKE_PREFIX) {
                    let _ = workbench.update(cx, |workbench, _| {
                        workbench.host.installed_extensions_registered = true;
                        workbench.store_custom_editors_memento();
                    });
                    if start == 1 {
                        perf::mark("code/didLoadExtensions");
                    }
                }
                if line.starts_with(ACTIVATED_PREFIX)
                    && let Some(sender) = activated_sender.take()
                {
                    let _ = sender.send(());
                }
            }
        })
        .detach();
        activated
    }
}

/// What the session thread takes from the window, read when the host starts.
struct WindowState {
    launch: HostLaunch,
    app_root: PathBuf,
    extensions: Vec<ScannedExtension>,
    settings: Arc<Mutex<Settings>>,
    storage: MainThreadStorage,
    workspace_trusted: bool,
    workspace: Option<Workspace>,
    development: Option<ExtensionDevelopment>,
    host_debug: ExtensionHostDebug,
}

/// The extension host bundle: in the app files of VSRustium.app, else port/tools/build-exthost's output in the checkout.
fn exthost_entry(app_root: &Path) -> PathBuf {
    let bundled = app_root.join("out-exthost/bootstrap-exthost.js");
    if bundled.is_file() {
        return bundled;
    }
    Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../out-exthost/bootstrap-exthost.js")).to_path_buf()
}

/// Owns the session for the life of the host: handshake, one call each way, then serves host requests and
/// forwards what the workbench tells the host.
fn run_extension_host(
    window_state: WindowState,
    main_thread: WorkbenchMainThread,
    workbench_requests: UnboundedSender<ForwardedRequest>,
    workbench_replies: Receiver<(u32, Result<Value, Value>)>,
    inbox: Inbox,
    status: &UnboundedSender<String>,
    window_closed: &AtomicBool,
) -> anyhow::Result<()> {
    let WindowState { launch, app_root, extensions, settings, mut storage, workspace_trusted, workspace, development, host_debug } = window_state;
    let user_data = launch.user_data;
    let paths = SessionPaths { app_root: &app_root, user_data: &user_data, workspace: workspace.as_ref() };
    let extension_tests = development.as_ref().is_some_and(|development| development.tests_path.is_some());
    let mut init = init_data(&paths, &extensions, &crate::VERSION);
    init["quality"] = json!(product::quality());
    // localProcessExtensionHost.ts: console stacks are forwarded unless a packaged (built) stable build runs.
    init["consoleForward"]["includeStack"] = json!(!(product::is_bundled(&app_root) && product::is_stable()));
    // StateService of main.ts: `storage.json` in the global storage folder.
    let global_storage = user_data.join("User/globalStorage");
    std::fs::create_dir_all(&global_storage)?;
    init["telemetryInfo"] = storage.telemetry_info(&mut FileStorage::open(&global_storage.join("storage.json")));
    if let Some(development) = &development {
        development.add_to_init_data(&mut init);
    }
    init["environment"]["isExtensionDevelopmentDebug"] = json!(host_debug.port.is_some());
    let waker = inbox.waker();
    let host = match launch.process {
        HostProcess::Runtime(runtime) => {
            let entry = exthost_entry(&app_root);
            let (runtime, extra_args) = match host_debug.port {
                Some(port) => (Runtime::Node, host_debug.node_args(port)),
                None => (runtime, Vec::new()),
            };
            ExtensionHost::start(HostOptions { runtime, entry: &entry, extra_env: host_debug.env.into_iter().chain(files::unc::utility_process_env()).collect(), extra_args, inbox }, &init)?
        }
        #[cfg(test)]
        HostProcess::Silent(opened) => {
            let (host, peer) = ExtensionHost::silent(inbox);
            opened.send((init.clone(), peer))?;
            host
        }
    };
    let _ = status.unbounded_send(format!("{HANDSHAKE_PREFIX}{}", host.child.id()));
    let mut session = Session::new(host);
    let folders: Vec<PathBuf> = workspace.iter().flat_map(|workspace| workspace.folders.iter().map(|folder| folder.path.clone())).collect();
    let mut watched = Vec::new();
    for folder in &folders {
        let excludes = settings.lock().unwrap().get_value(Some("files.watcherExclude"), &Overrides { resource: Some(folder), ..Overrides::default() });
        let excludes: Vec<String> = excludes.as_ref().and_then(|excludes| excludes.as_object()).into_iter().flatten().filter(|(_, on)| **on == true).map(|(pattern, _)| pattern.clone()).collect();
        watched.push((folder.clone(), excludes));
    }
    session.files = Some(MainThreadFiles::new(&watched, &extensions, settings.clone(), waker.clone())?);
    session.workspace = Some(MainThreadWorkspace::new(folders, settings.clone(), &app_root, waker));
    session.configuration = Some(MainThreadConfiguration::new(settings, development.is_some()));
    session.storage = Some(storage);
    session.workspace_trusted = workspace_trusted;
    // secrets.ts: without encryption the secret storage falls back to memory.
    session.secrets = Some(match extension_tests {
        true => MainThreadSecretState::in_memory(),
        false => MainThreadSecretState::keychain().unwrap_or_else(|error| {
            eprintln!("[secrets] the Keychain is unavailable, secrets stay in memory: {error}");
            MainThreadSecretState::in_memory()
        }),
    });
    session.forward(main_thread_commands::path, move |request| {
        let _ = workbench_requests.unbounded_send(request);
    }, workbench_replies);
    session.main_thread = Some(Box::new(main_thread));
    session.notify("ExtHostStatusBar", "$acceptStaticEntries", vec![json!(main_thread_status_bar::static_entry_dtos(&extensions))]);
    perf::mark("code/willStartExtensionHost");
    session.start(&extensions, workspace.as_ref().map(|workspace| workspace_data(&init, workspace)))?;
    perf::mark("code/didStartExtensionHost");
    // No timeout: a host paused in a debugger answers once it runs on.
    let reply = session.request("ExtHostExtensionService", "$test_latency", vec![Arg::Json(json!(7))], None)?;
    let _ = status.unbounded_send(format!("main -> host: $test_latency(7) = {reply:?}"));
    let _ = status.unbounded_send(format!("host -> main: {} requests so far", session.log.host_calls.values().sum::<u32>()));
    let _ = status.unbounded_send(format!("{ACTIVATED_PREFIX}{}", session.log.activated.join(", ")));
    if extension_tests {
        session.execute_extension_tests();
    }
    // Workbench changes, answers, file events and the window's close wake the wait (`exthost::Waker`).
    loop {
        // A closed window's host goes with its session (ExtensionHost's drop terminates it).
        if window_closed.load(Ordering::Relaxed) {
            return Ok(());
        }
        session.flush_main_thread();
        if !session.pump(session.idle_timeout())? {
            break;
        }
    }
    if let Some(code) = session.extension_tests_exit_code() {
        drop(session);
        std::process::exit(code);
    }
    let _ = status.unbounded_send(EXITED_LINE.into());
    Ok(())
}

const ACTIVATED_PREFIX: &str = "eager extensions activated: ";
const HANDSHAKE_PREFIX: &str = "handshake done, pid ";
const EXITED_LINE: &str = "extension host exited";