Skip to content

Visual Studio Code, rebuilt in Rust

Rust

perf(exthost): wake the session loop instead of polling every 20 ms

rokartur2eee2e01d92e
diff --git a/native/crates/app/src/host_sync.rs b/native/crates/app/src/host_sync.rs
index d59e911c97f..fd114da87c4 100644
--- a/native/crates/app/src/host_sync.rs
+++ b/native/crates/app/src/host_sync.rs
@@ -5,7 +5,6 @@
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
-use std::sync::mpsc::Sender;
use futures::FutureExt;
use futures::channel::oneshot;
@@ -15,6 +14,7 @@ use config::model::Change;
use config::service::Settings;
use exthost::extension_management::Job;
use exthost::main_thread_configuration::changed_args;
+use exthost::WakingSender;
use exthost::scan::ScannedExtension;
use files::operations::{self, FileEdit, FileUndo, WorkingCopyFiles};
use serde_json::{Value, json};
@@ -90,7 +90,7 @@ impl FileWork {
}
pub struct HostSync {
- sender: Sender<HostMessage>,
+ sender: WakingSender<HostMessage>,
/// The documents the host has, in the order they were added: their URI string and `UriComponents`.
documents: Vec<(String, Value)>,
/// The snapshot ids of the visible editors the host has, one per group showing a text editor.
@@ -137,8 +137,8 @@ const TAB_MOVE: u8 = 3;
const CODE_EDITOR_ID: &str = "vs.editor.ICodeEditor:1";
impl HostSync {
- pub fn new(sender: Sender<HostMessage>) -> Self {
- HostSync { sender, documents: Vec::new(), editors: Vec::new(), editor_positions: serde_json::Map::new(), editor_options: HashMap::new(), active_editor: None, visible_lines: None, tabs: vec![(0, Vec::new())], active_group: 0, search_tabs: HashMap::new(), terminal_tabs: HashMap::new(), webview_tabs: HashMap::new(), activations: HashMap::new(), activation_events: HashSet::new(), installed_extensions_registered: false, configuration_scopes: false, untitled_names_from_content: true, notebooks: Default::default() }
+ pub fn new(sender: impl Into<WakingSender<HostMessage>>) -> Self {
+ HostSync { sender: sender.into(), documents: Vec::new(), editors: Vec::new(), editor_positions: serde_json::Map::new(), editor_options: HashMap::new(), active_editor: None, visible_lines: None, tabs: vec![(0, Vec::new())], active_group: 0, search_tabs: HashMap::new(), terminal_tabs: HashMap::new(), webview_tabs: HashMap::new(), activations: HashMap::new(), activation_events: HashSet::new(), installed_extensions_registered: false, configuration_scopes: false, untitled_names_from_content: true, notebooks: Default::default() }
}
pub fn editor_ids(&self) -> &[String] {
@@ -1012,7 +1012,7 @@ mod tests {
let paths = SessionPaths { app_root: &app_root, user_data: &user_data, workspace: Some(&workspace) };
let init = init_data(&paths, &extensions, "1.147.0");
let entry = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../out-exthost/bootstrap-exthost.js");
- let host = ExtensionHost::start(HostOptions { runtime: Runtime::Bun, entry: &entry, extra_env: vec![], extra_args: vec![] }, &init).unwrap();
+ let host = ExtensionHost::start(HostOptions { runtime: Runtime::Bun, entry: &entry, extra_env: vec![], extra_args: vec![], inbox: Default::default() }, &init).unwrap();
let mut session = Session::new(host);
session.start(&extensions, Some(workspace_data(&init, &workspace))).unwrap();
diff --git a/native/crates/app/src/main.rs b/native/crates/app/src/main.rs
index 0b6adb75bbb..ea01d959df3 100644
--- a/native/crates/app/src/main.rs
+++ b/native/crates/app/src/main.rs
@@ -157,7 +157,7 @@ use exthost::main_thread_workspace::MainThreadWorkspace;
use exthost::rpc::Arg;
use exthost::scan::{ScannedExtension, scan_builtin_extensions};
use exthost::session::{ForwardedRequest, Session, SessionPaths, init_data, workspace_data};
-use exthost::{ExtensionHost, HostOptions, Runtime};
+use exthost::{ExtensionHost, HostOptions, Inbox, Runtime, WakingSender};
use futures::StreamExt;
use futures::channel::mpsc::{UnboundedSender, unbounded};
use gpui::{App, Bounds, Keystroke, TitlebarOptions, Window, WindowBounds, WindowOptions, point, prelude::*, px, size};
@@ -550,10 +550,12 @@ pub(crate) fn open_window(request: WindowRequest, cx: &mut App) -> anyhow::Resul
let (host_sender, host_receiver) = channel();
let (request_sender, requests) = unbounded::<ForwardedRequest>();
let (reply_sender, replies) = channel::<(u32, Result<serde_json::Value, serde_json::Value>)>();
+ let inbox = Inbox::default();
+ let reply_sender = WakingSender::new(reply_sender, inbox.waker());
let (main_thread_sender, main_thread_requests) = unbounded::<HostRequest>();
let main_thread = WorkbenchMainThread { requests: main_thread_sender, messages: host_receiver, waiting: Vec::new(), content_providers: Default::default(), extensions: window_extensions };
let languages = Languages::new(&extensions);
- let mut host = HostSync::new(host_sender);
+ let mut host = HostSync::new(WakingSender::new(host_sender, inbox.waker()));
host.configuration_scopes = development.is_some();
host.send_color_theme(theme.kind);
perf::mark("code/willCreateWorkbenchContributions/1");
@@ -648,13 +650,13 @@ pub(crate) fn open_window(request: WindowRequest, cx: &mut App) -> anyhow::Resul
workbench.open_protocol_url(url, window, cx);
}
let (session_ended, ended) = futures::channel::oneshot::channel::<()>();
- workbench.watch_session_end(session_closed.clone(), ended, cx);
+ workbench.watch_session_end(session_closed.clone(), inbox.waker(), ended, cx);
let start = workbench.extension_host_started(cx);
std::thread::Builder::new()
.name("exthost-session".into())
.spawn(move || {
let runs_tests = development.as_ref().is_some_and(|development| development.tests_path.is_some());
- if let Err(error) = run_extension_host(runtime, app_root, extensions, settings, storage, workspace_trusted, user_data, workspace, development, host_debug, main_thread, request_sender, replies, &sender, &session_closed) {
+ if let Err(error) = run_extension_host(runtime, app_root, extensions, settings, storage, workspace_trusted, user_data, workspace, development, host_debug, main_thread, request_sender, replies, inbox, &sender, &session_closed) {
if runs_tests {
eprintln!("extension host failed: {error:#}");
std::process::exit(1);
@@ -755,6 +757,7 @@ fn run_extension_host(
main_thread: WorkbenchMainThread,
workbench_requests: UnboundedSender<ForwardedRequest>,
workbench_replies: Receiver<(u32, Result<serde_json::Value, serde_json::Value>)>,
+ inbox: Inbox,
status: &UnboundedSender<String>,
window_closed: &std::sync::atomic::AtomicBool,
) -> anyhow::Result<()> {
@@ -777,7 +780,8 @@ fn run_extension_host(
Some(port) => (Runtime::Node, host_debug.node_args(port)),
None => (runtime, Vec::new()),
};
- let host = ExtensionHost::start(HostOptions { runtime, entry: &entry, extra_env: host_debug.env, extra_args }, &init)?;
+ let waker = inbox.waker();
+ let host = ExtensionHost::start(HostOptions { runtime, entry: &entry, extra_env: host_debug.env, extra_args, inbox }, &init)?;
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();
@@ -787,8 +791,8 @@ fn run_extension_host(
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())?);
- session.workspace = Some(MainThreadWorkspace::new(folders, settings.clone(), &app_root));
+ 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;
@@ -816,14 +820,14 @@ fn run_extension_host(
if development.is_some_and(|development| development.tests_path.is_some()) {
session.execute_extension_tests();
}
- // The short pump timeout bounds how long a workbench change waits before the host hears of it.
+ // 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(std::sync::atomic::Ordering::Relaxed) {
return Ok(());
}
session.flush_main_thread();
- if !session.pump(Duration::from_millis(20))? {
+ if !session.pump(session.idle_timeout())? {
break;
}
}
diff --git a/native/crates/app/src/main_thread.rs b/native/crates/app/src/main_thread.rs
index 9eb49325f08..f62be21363e 100644
--- a/native/crates/app/src/main_thread.rs
+++ b/native/crates/app/src/main_thread.rs
@@ -118,6 +118,10 @@ impl MainThread for WorkbenchMainThread {
Some(result.map(|value| if value.is_null() { Reply::Empty } else { Reply::Json(value) }))
}
+ fn polls(&self) -> bool {
+ self.waiting.iter().any(|(_, cancellable, _)| *cancellable)
+ }
+
fn flush(&mut self, session: &mut Session) {
for message in self.messages.try_iter() {
if let Some(work) = message.files {
diff --git a/native/crates/app/src/workbench/extension_host_restart.rs b/native/crates/app/src/workbench/extension_host_restart.rs
index 39158409512..49b59cf75ef 100644
--- a/native/crates/app/src/workbench/extension_host_restart.rs
+++ b/native/crates/app/src/workbench/extension_host_restart.rs
@@ -4,7 +4,7 @@
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
-use std::sync::mpsc::{Sender, channel};
+use std::sync::mpsc::channel;
use config::configuration::Overrides;
use exthost::extension_development::ExtensionDevelopment;
@@ -12,7 +12,7 @@ use exthost::extension_management::{WindowExtensions, add_user_extensions};
use exthost::main_thread_storage::MainThreadStorage;
use exthost::scan::ScannedExtension;
use exthost::session::ForwardedRequest;
-use exthost::Runtime;
+use exthost::{Inbox, Runtime, WakingSender};
use futures::StreamExt;
use futures::channel::mpsc::{UnboundedReceiver, unbounded};
use gpui::{App, Context, PromptLevel, Task, Window};
@@ -178,11 +178,13 @@ impl Workbench {
let (host_sender, host_receiver) = channel();
let (request_sender, requests) = unbounded::<ForwardedRequest>();
let (reply_sender, replies) = channel();
+ let inbox = Inbox::default();
+ 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 window_extensions = WindowExtensions { builtins: self.extensions_viewlet.builtins.clone(), user, running: extensions.clone(), proposed_api: self.proposed_api.clone() };
let main_thread = WorkbenchMainThread { requests: main_thread_sender, messages: host_receiver, waiting: Vec::new(), content_providers: Default::default(), extensions: window_extensions };
- let mut host = HostSync::new(host_sender);
+ let mut host = HostSync::new(WakingSender::new(host_sender, inbox.waker()));
host.configuration_scopes = self.host.configuration_scopes;
host.untitled_names_from_content = self.host.untitled_names_from_content;
host.search_tabs = std::mem::take(&mut self.host.search_tabs);
@@ -201,14 +203,14 @@ impl Workbench {
let workspace = self.workspace().cloned();
let window_closed = Arc::new(AtomicBool::new(false));
let (session_ended, ended) = futures::channel::oneshot::channel::<()>();
- self.watch_session_end(window_closed.clone(), ended, cx);
+ self.watch_session_end(window_closed.clone(), inbox.waker(), ended, cx);
let development = self.development_without_tests();
let host_debug = self.extension_host_debug.clone();
let start = self.extension_host_started(cx);
std::thread::Builder::new()
.name("exthost-session".into())
.spawn(move || {
- let started = crate::run_extension_host(runtime, app_root, extensions, settings, storage, trusted, user_data, workspace, development, host_debug, main_thread, request_sender, replies, &status, &window_closed);
+ let started = crate::run_extension_host(runtime, app_root, extensions, settings, storage, trusted, user_data, workspace, development, host_debug, main_thread, request_sender, replies, inbox, &status, &window_closed);
if let Err(error) = started {
let _ = status.unbounded_send(format!("extension host failed: {error:#}"));
}
@@ -262,7 +264,7 @@ impl Workbench {
}
/// Answers the host requests the session forwards to the workbench, each on the window's thread.
-pub fn serve_host_requests(mut requests: UnboundedReceiver<ForwardedRequest>, reply_sender: Sender<(u32, Result<Value, Value>)>, window: &mut Window, cx: &mut Context<Workbench>) {
+pub fn serve_host_requests(mut requests: UnboundedReceiver<ForwardedRequest>, reply_sender: WakingSender<(u32, Result<Value, Value>)>, window: &mut Window, cx: &mut Context<Workbench>) {
cx.spawn_in(window, async move |workbench, cx| {
while let Some(request) = requests.next().await {
let req = request.req;
diff --git a/native/crates/app/src/workbench/host.rs b/native/crates/app/src/workbench/host.rs
index 323fc4787bd..9238fdccdd7 100644
--- a/native/crates/app/src/workbench/host.rs
+++ b/native/crates/app/src/workbench/host.rs
@@ -6,6 +6,7 @@ use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
+use exthost::Waker;
use exthost::extension_development::{ExtensionDevelopment, ExtensionHostDebug};
use futures::channel::oneshot;
use gpui::{App, Context, Window, WindowHandle};
@@ -85,8 +86,12 @@ impl Workbench {
/// The window's extension host session ends once the workbench is released (its window closed); `ended` answers
/// when the session thread is done with the window's storage.
- pub fn watch_session_end(&mut self, closed: Arc<AtomicBool>, ended: oneshot::Receiver<()>, cx: &mut Context<Self>) {
- cx.on_release(move |_, _| closed.store(true, Ordering::Relaxed)).detach();
+ pub fn watch_session_end(&mut self, closed: Arc<AtomicBool>, waker: Waker, ended: oneshot::Receiver<()>, cx: &mut Context<Self>) {
+ cx.on_release(move |_, _| {
+ closed.store(true, Ordering::Relaxed);
+ waker.wake();
+ })
+ .detach();
self.lifecycle.session_ended = Some(ended);
}
diff --git a/native/crates/exthost/src/bin/exthost-probe.rs b/native/crates/exthost/src/bin/exthost-probe.rs
index e1b6d361e44..693bd40ea00 100644
--- a/native/crates/exthost/src/bin/exthost-probe.rs
+++ b/native/crates/exthost/src/bin/exthost-probe.rs
@@ -16,7 +16,7 @@ use exthost::extension_management::{Job, UserExtensions, WindowExtensions};
use exthost::rpc::{Arg, Reply};
use exthost::scan::{extension_identifier, scan_builtin_extensions};
use exthost::session::{Session, SessionPaths, init_data, workspace_data};
-use exthost::{ExtensionHost, HostOptions, Runtime};
+use exthost::{ExtensionHost, HostOptions, Inbox, Runtime};
use serde_json::{Value, json};
fn main() -> anyhow::Result<()> {
@@ -47,7 +47,9 @@ fn main() -> anyhow::Result<()> {
let init = init_data(&paths, &extensions, "1.147.0");
let started = Instant::now();
- let host = ExtensionHost::start(HostOptions { runtime, entry: &entry, extra_env: vec![], extra_args: vec![] }, &init)?;
+ let inbox = Inbox::default();
+ let waker = inbox.waker();
+ let host = ExtensionHost::start(HostOptions { runtime, entry: &entry, extra_env: vec![], extra_args: vec![], inbox }, &init)?;
let handshake_ms = started.elapsed().as_secs_f64() * 1000.0;
let mut session = Session::new(host);
let described: Vec<(&str, &Value)> = extensions.iter().map(|extension| (extension.id.as_str(), &extension.description)).collect();
@@ -55,7 +57,7 @@ fn main() -> anyhow::Result<()> {
session.configuration = Some(MainThreadConfiguration::new(settings.clone(), false));
if let Some(workspace) = &workspace {
let folders = workspace.folders.iter().map(|folder| folder.path.clone()).collect();
- session.workspace = Some(MainThreadWorkspace::new(folders, settings, paths.app_root));
+ session.workspace = Some(MainThreadWorkspace::new(folders, settings, paths.app_root, waker));
}
session.start(&extensions, workspace.as_ref().map(|workspace| workspace_data(&init, workspace)))?;
let started_ms = started.elapsed().as_secs_f64() * 1000.0;
diff --git a/native/crates/exthost/src/lib.rs b/native/crates/exthost/src/lib.rs
index a610b670619..1b4a5f77315 100644
--- a/native/crates/exthost/src/lib.rs
+++ b/native/crates/exthost/src/lib.rs
@@ -36,7 +36,7 @@ use std::path::{Path, PathBuf};
use std::process::{Child, Command};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, Mutex};
-use std::time::Duration;
+use std::time::{Duration, Instant};
use frame::{Frame, FrameReader, FrameType, encode_frame};
#[cfg(windows)]
@@ -95,6 +95,71 @@ pub fn proxy_name(rpc_id: u8) -> &'static str {
pub enum Incoming {
Message(Vec<u8>),
Closed,
+ /// Work for the session that came from elsewhere (`Waker::wake`).
+ Wake,
+}
+
+/// What a session waits on: its host's messages and the wakes of its `Waker`s. Made before the host starts, so the
+/// workbench can queue work for a session that is not up yet.
+pub struct Inbox {
+ sender: Sender<Incoming>,
+ receiver: Receiver<Incoming>,
+}
+
+impl Default for Inbox {
+ fn default() -> Self {
+ let (sender, receiver) = channel();
+ Inbox { sender, receiver }
+ }
+}
+
+impl Inbox {
+ pub fn waker(&self) -> Waker {
+ Waker(self.sender.clone())
+ }
+}
+
+/// Ends the session's wait for its host after work for it was queued elsewhere: by the workbench, a file watcher or a
+/// search.
+#[derive(Clone)]
+pub struct Waker(Sender<Incoming>);
+
+impl Waker {
+ pub fn wake(&self) {
+ let _ = self.0.send(Incoming::Wake);
+ }
+}
+
+/// A queue's sender whose items wake the session that reads the queue; one from a bare `Sender` wakes nothing.
+pub struct WakingSender<T> {
+ sender: Sender<T>,
+ waker: Option<Waker>,
+}
+
+impl<T> WakingSender<T> {
+ pub fn new(sender: Sender<T>, waker: Waker) -> Self {
+ WakingSender { sender, waker: Some(waker) }
+ }
+
+ pub fn send(&self, item: T) -> Result<(), std::sync::mpsc::SendError<T>> {
+ self.sender.send(item)?;
+ if let Some(waker) = &self.waker {
+ waker.wake();
+ }
+ Ok(())
+ }
+}
+
+impl<T> Clone for WakingSender<T> {
+ fn clone(&self) -> Self {
+ WakingSender { sender: self.sender.clone(), waker: self.waker.clone() }
+ }
+}
+
+impl<T> From<Sender<T>> for WakingSender<T> {
+ fn from(sender: Sender<T>) -> Self {
+ WakingSender { sender, waker: None }
+ }
}
struct WriterState {
@@ -117,6 +182,7 @@ pub struct HostOptions<'a> {
pub entry: &'a Path,
pub extra_env: Vec<(String, String)>,
pub extra_args: Vec<String>,
+ pub inbox: Inbox,
}
impl ExtensionHost {
@@ -147,7 +213,7 @@ impl ExtensionHost {
let stream = accept_with_timeout(&mut listener, Duration::from_secs(30))?;
let reader_stream = stream.try_clone()?;
let writer = Arc::new(Mutex::new(WriterState { stream, outgoing_id: 0, incoming_id: 0 }));
- let (sender, incoming) = channel();
+ let Inbox { sender, receiver: incoming } = options.inbox;
spawn_reader(reader_stream, writer.clone(), sender);
let host = ExtensionHost { child, writer, incoming, socket_path };
@@ -158,10 +224,15 @@ impl ExtensionHost {
}
fn expect_one_byte(&self, expected: u8) -> anyhow::Result<()> {
- match self.incoming.recv_timeout(Duration::from_secs(30))? {
- Incoming::Message(bytes) if bytes == [expected] => Ok(()),
- Incoming::Message(bytes) => anyhow::bail!("expected handshake message {expected}, got {bytes:?}"),
- Incoming::Closed => anyhow::bail!("extension host closed the socket during the handshake"),
+ let deadline = Instant::now() + Duration::from_secs(30);
+ loop {
+ match self.incoming.recv_timeout(deadline.saturating_duration_since(Instant::now()))? {
+ Incoming::Message(bytes) if bytes == [expected] => return Ok(()),
+ Incoming::Message(bytes) => anyhow::bail!("expected handshake message {expected}, got {bytes:?}"),
+ Incoming::Closed => anyhow::bail!("extension host closed the socket during the handshake"),
+ // The work stays queued for the session's first look after the handshake.
+ Incoming::Wake => {}
+ }
}
}
@@ -188,10 +259,10 @@ impl ExtensionHost {
/// A host that never sends anything, over a socket pair whose other end is `peer`.
#[cfg(test)]
- pub(crate) fn silent() -> (Self, Stream) {
+ pub(crate) fn silent(inbox: Inbox) -> (Self, Stream) {
let (stream, peer) = Stream::pair().unwrap();
let writer = Arc::new(Mutex::new(WriterState { stream: stream.try_clone().unwrap(), outgoing_id: 0, incoming_id: 0 }));
- let (sender, incoming) = channel();
+ let Inbox { sender, receiver: incoming } = inbox;
spawn_reader(stream, writer.clone(), sender);
let child = Command::new("sleep").arg("60").spawn().unwrap();
(ExtensionHost { child, writer, incoming, socket_path: PathBuf::new() }, peer)
diff --git a/native/crates/exthost/src/main_thread.rs b/native/crates/exthost/src/main_thread.rs
index 08578d5342b..3abad97ca4a 100644
--- a/native/crates/exthost/src/main_thread.rs
+++ b/native/crates/exthost/src/main_thread.rs
@@ -15,6 +15,12 @@ pub trait MainThread: Send {
/// Sends what the workbench queued for the host since the last call.
fn flush(&mut self, session: &mut Session);
+
+ /// Whether the session must look again without a wake: a cancellable request's caller cancels it by dropping its
+ /// receiver, which wakes nothing.
+ fn polls(&self) -> bool {
+ false
+ }
}
/// Host requests that arrived while the main thread handler was calling the host; served once it returns.
diff --git a/native/crates/exthost/src/main_thread_files.rs b/native/crates/exthost/src/main_thread_files.rs
index 2c12cfa5c9f..525257d24a3 100644
--- a/native/crates/exthost/src/main_thread_files.rs
+++ b/native/crates/exthost/src/main_thread_files.rs
@@ -4,7 +4,7 @@
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
-use std::sync::mpsc::{Receiver, Sender, channel};
+use std::sync::mpsc::{Receiver, channel};
use std::sync::{Arc, Mutex};
use std::time::Duration;
@@ -18,6 +18,7 @@ use files::{FileError, FileSystem, Mode, Resource, Stat};
use serde_json::{Value, json};
use crate::rpc::{Arg, Message, Reply};
+use crate::{Waker, WakingSender};
use crate::scan::{ScannedExtension, file_uri};
use crate::session::{CallResult, Session};
use crate::settings_file_system;
@@ -43,7 +44,7 @@ pub struct MainThreadFiles {
/// Correlated extension watchers and `vscode-userdata` watchers each get their own, so their events carry the
/// session and the scheme.
correlated: HashMap<u64, Watcher>,
- sender: Sender<Events>,
+ sender: WakingSender<Events>,
receiver: Receiver<Events>,
/// `RemoteFileSystemProvider`s by scheme.
providers: HashMap<String, ExtensionProvider>,
@@ -58,8 +59,9 @@ pub struct MainThreadFiles {
impl MainThreadFiles {
/// `WorkspaceWatcher.watchWorkspace`: each folder recursively, minus its `files.watcherExclude` patterns set to true.
- pub fn new(folders: &[(PathBuf, Vec<String>)], extensions: &[ScannedExtension], settings: Arc<Mutex<Settings>>) -> anyhow::Result<Self> {
+ pub fn new(folders: &[(PathBuf, Vec<String>)], extensions: &[ScannedExtension], settings: Arc<Mutex<Settings>>, waker: Waker) -> anyhow::Result<Self> {
let (sender, receiver) = channel();
+ let sender = WakingSender::new(sender, waker);
let workspace_sender = sender.clone();
let mut watcher = Watcher::new(move |changes| {
let _ = workspace_sender.send((None, "file", changes));
@@ -577,7 +579,7 @@ mod tests {
#[test]
fn user_data_watch_events_keep_their_scheme() {
let settings = Arc::new(Mutex::new(Settings::load(Registry::with_extensions(&[]), PathBuf::from("/nonexistent/User"), None)));
- let mut main_thread = MainThreadFiles::new(&[], &[], settings).unwrap();
+ let mut main_thread = MainThreadFiles::new(&[], &[], settings, crate::Inbox::default().waker()).unwrap();
let path = PathBuf::from("/nonexistent/User/settings.json");
main_thread.sender.send((Some(7), files::user_data::SCHEME, vec![Change { path: path.clone(), kind: ChangeType::Added }])).unwrap();
main_thread.sender.send((None, "file", vec![Change { path: path.clone(), kind: ChangeType::Updated }])).unwrap();
diff --git a/native/crates/exthost/src/main_thread_workspace.rs b/native/crates/exthost/src/main_thread_workspace.rs
index c588d30264a..f152ed1ac33 100644
--- a/native/crates/exthost/src/main_thread_workspace.rs
+++ b/native/crates/exthost/src/main_thread_workspace.rs
@@ -4,7 +4,7 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
-use std::sync::mpsc::{Receiver, Sender, channel};
+use std::sync::mpsc::{Receiver, channel};
use std::sync::{Arc, Mutex};
use config::configuration::Overrides;
@@ -13,6 +13,7 @@ use search::ripgrep::Cancellation;
use serde_json::{Value, json};
use crate::rpc::{Arg, Message, Reply};
+use crate::{Waker, WakingSender};
use crate::scan::file_uri;
/// What a search thread hands back to the session thread, in the order the host must see it.
@@ -28,13 +29,14 @@ pub struct MainThreadWorkspace {
rg: PathBuf,
/// Running searches by the request that started them.
searches: HashMap<u32, Arc<Cancellation>>,
- sender: Sender<(u32, Outgoing)>,
+ sender: WakingSender<(u32, Outgoing)>,
receiver: Receiver<(u32, Outgoing)>,
}
impl MainThreadWorkspace {
- pub fn new(folders: Vec<PathBuf>, settings: Arc<Mutex<Settings>>, app_root: &Path) -> Self {
+ pub fn new(folders: Vec<PathBuf>, settings: Arc<Mutex<Settings>>, app_root: &Path, waker: Waker) -> Self {
let (sender, receiver) = channel();
+ let sender = WakingSender::new(sender, waker);
MainThreadWorkspace { folders, settings, rg: search::ripgrep::rg_path(app_root), searches: HashMap::new(), sender, receiver }
}
diff --git a/native/crates/exthost/src/session.rs b/native/crates/exthost/src/session.rs
index 19289c6399c..5e253f6366f 100644
--- a/native/crates/exthost/src/session.rs
+++ b/native/crates/exthost/src/session.rs
@@ -555,13 +555,16 @@ impl Session {
};
self.results.insert(req, result);
}
- // An answer can come while a `call` waits (an extension's activate awaiting a forwarded request).
- timeout = timeout.min(Duration::from_millis(20));
+ // Held answers go out on a later pump, which no message wakes.
+ if self.forward.as_ref().is_some_and(|forward| !forward.held.is_empty()) {
+ timeout = timeout.min(Duration::from_millis(20));
+ }
}
let Some(incoming) = self.host.recv_timeout(timeout) else { return Ok(true) };
let bytes = match incoming {
Incoming::Message(bytes) => bytes,
Incoming::Closed => return Ok(false),
+ Incoming::Wake => return Ok(true),
};
match rpc::decode(&bytes)? {
Message::Request { req, rpc_id, method, args, .. } if proxy_name(rpc_id) == "MainThreadConfiguration" && self.configuration.is_some() => {
@@ -681,6 +684,13 @@ impl Session {
}
}
+ /// How long the session's own loop waits for its host: until a message or a `Waker` comes, or 20 ms while host
+ /// requests wait for their turn or the workbench may cancel one.
+ pub fn idle_timeout(&self) -> Duration {
+ let polls = !self.waiting.requests.is_empty() || self.main_thread.as_ref().is_some_and(|main_thread| main_thread.polls());
+ if polls { Duration::from_millis(20) } else { Duration::MAX }
+ }
+
/// Sends what the workbench queued for the host; host requests arriving meanwhile wait, as in `serve`.
pub fn flush_main_thread(&mut self) {
if self.waiting.busy {
@@ -899,7 +909,7 @@ mod tests {
}
}
- let (host, _peer) = ExtensionHost::silent();
+ let (host, _peer) = ExtensionHost::silent(crate::Inbox::default());
let mut session = Session::new(host);
let asked = std::sync::Arc::new(std::sync::Mutex::new(None));
let (replies, workbench_replies) = std::sync::mpsc::channel();
@@ -909,4 +919,22 @@ mod tests {
std::thread::spawn(move || done.send(session.ask_workbench("workbench", "debugMemory", Vec::new())).unwrap());
assert_eq!(answer.recv_timeout(std::time::Duration::from_secs(5)).expect("ask_workbench hung"), Some(Ok(json!("answered"))));
}
+
+ #[test]
+ fn an_idle_session_sleeps_until_it_is_woken() {
+ let inbox = crate::Inbox::default();
+ let waker = inbox.waker();
+ let (host, _peer) = ExtensionHost::silent(inbox);
+ let mut session = Session::new(host);
+ session.forward(&[], |_| {}, std::sync::mpsc::channel().1);
+ assert_eq!(session.idle_timeout(), Duration::MAX);
+ let started = Instant::now();
+ std::thread::spawn(move || {
+ std::thread::sleep(Duration::from_millis(300));
+ waker.wake();
+ });
+ assert!(session.pump(Duration::from_secs(5)).unwrap());
+ let waited = started.elapsed();
+ assert!(waited >= Duration::from_millis(300) && waited < Duration::from_secs(5), "{waited:?}");
+ }
}