Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Merge branch 'main' into randomized-tests-operation-script
Max Brunsfeld51cea1b1fb1b
diff --cc crates/collab/src/tests/randomized_integration_tests.rsindex e44e52196d2,950f12d1869..0b4aa3ec9bf--- a/crates/collab/src/tests/randomized_integration_tests.rs+++ b/crates/collab/src/tests/randomized_integration_tests.rs@@@ -348,189 -441,171 +348,189 @@@ async fn test_random_collaboration}}-async fn simulate_client(- mut client: TestClient,- mut op_start_signal: futures::channel::mpsc::UnboundedReceiver<()>,- can_hang_up: bool,- rng: Arc<Mutex<StdRng>>,- mut cx: TestAppContext,-) -> (TestClient, TestAppContext) {- // Setup language server- let mut language = Language::new(- LanguageConfig {- name: "Rust".into(),- path_suffixes: vec!["rs".to_string()],- ..Default::default()- },- None,- );- let _fake_language_servers = language- .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {- name: "the-fake-language-server",- capabilities: lsp::LanguageServer::full_capabilities(),- initializer: Some(Box::new({- let rng = rng.clone();- let fs = client.fs.clone();- move |fake_server: &mut FakeLanguageServer| {- fake_server.handle_request::<lsp::request::Completion, _, _>(- |_, _| async move {- Ok(Some(lsp::CompletionResponse::Array(vec![- lsp::CompletionItem {- text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {- range: lsp::Range::new(- lsp::Position::new(0, 0),- lsp::Position::new(0, 0),- ),- new_text: "the-new-text".to_string(),- })),- ..Default::default()- },- ])))- },- );-- fake_server.handle_request::<lsp::request::CodeActionRequest, _, _>(- |_, _| async move {- Ok(Some(vec![lsp::CodeActionOrCommand::CodeAction(- lsp::CodeAction {- title: "the-code-action".to_string(),- ..Default::default()- },- )]))- },- );+async fn apply_server_operation(+ deterministic: Arc<Deterministic>,+ server: &mut TestServer,+ clients: &mut Vec<(Rc<TestClient>, TestAppContext)>,+ client_tasks: &mut Vec<Task<()>>,+ operation_channels: &mut Vec<futures::channel::mpsc::UnboundedSender<usize>>,+ plan: Arc<Mutex<TestPlan>>,+ operation: Operation,+ cx: &mut TestAppContext,+) -> bool {+ match operation {+ Operation::AddConnection { user_id } => {+ let username;+ {+ let mut plan = plan.lock();+ let mut user = plan.user(user_id);+ if user.online {+ return false;+ }+ user.online = true;+ username = user.username.clone();+ };+ log::info!("Adding new connection for {}", username);+ let next_entity_id = (user_id.0 * 10_000) as usize;+ let mut client_cx = TestAppContext::new(+ cx.foreground_platform(),+ cx.platform(),+ deterministic.build_foreground(user_id.0 as usize),+ deterministic.build_background(),+ cx.font_cache(),+ cx.leak_detector(),+ next_entity_id,+ cx.function_name.clone(),+ );- fake_server.handle_request::<lsp::request::PrepareRenameRequest, _, _>(- |params, _| async move {- Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(- params.position,- params.position,- ))))- },- );+ let (operation_tx, operation_rx) = futures::channel::mpsc::unbounded();+ let client = Rc::new(server.create_client(&mut client_cx, &username).await);+ operation_channels.push(operation_tx);+ clients.push((client.clone(), client_cx.clone()));+ client_tasks.push(client_cx.foreground().spawn(simulate_client(+ client,+ operation_rx,+ plan.clone(),+ client_cx,+ )));++ log::info!("Added connection for {}", username);+ }- Operation::RemoveConnection { user_id } => {- log::info!("Simulating full disconnection of user {}", user_id);- fake_server.handle_request::<lsp::request::GotoDefinition, _, _>({- let fs = fs.clone();- let rng = rng.clone();- move |_, _| {- let fs = fs.clone();- let rng = rng.clone();- async move {- let files = fs.files().await;- let mut rng = rng.lock();- let count = rng.gen_range::<usize, _>(1..3);- let files = (0..count)- .map(|_| files.choose(&mut *rng).unwrap())- .collect::<Vec<_>>();- log::info!("LSP: Returning definitions in files {:?}", &files);- Ok(Some(lsp::GotoDefinitionResponse::Array(- files- .into_iter()- .map(|file| lsp::Location {- uri: lsp::Url::from_file_path(file).unwrap(),- range: Default::default(),- })- .collect(),- )))- }- }- });++ Operation::RemoveConnection {++ user_id: removed_user_id,++ } => {++ log::info!("Simulating full disconnection of user {}", removed_user_id);+ let client_ix = clients+ .iter()- .position(|(client, cx)| client.current_user_id(cx) == user_id);++ .position(|(client, cx)| client.current_user_id(cx) == removed_user_id);+ let Some(client_ix) = client_ix else { return false };+ let user_connection_ids = server+ .connection_pool+ .lock()- .user_connection_ids(user_id)++ .user_connection_ids(removed_user_id)+ .collect::<Vec<_>>();+ assert_eq!(user_connection_ids.len(), 1);+ let removed_peer_id = user_connection_ids[0].into();+ let (client, mut client_cx) = clients.remove(client_ix);+ let client_task = client_tasks.remove(client_ix);+ operation_channels.remove(client_ix);+ server.forbid_connections();+ server.disconnect_client(removed_peer_id);+ deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);+ deterministic.start_waiting();- log::info!("Waiting for user {} to exit...", user_id);++ log::info!("Waiting for user {} to exit...", removed_user_id);+ client_task.await;+ deterministic.finish_waiting();+ server.allow_connections();++ for project in client.remote_projects().iter() {+ project.read_with(&client_cx, |project, _| {+ assert!(+ project.is_read_only(),+ "project {:?} should be read only",+ project.remote_id()+ )+ });+ }- fake_server.handle_request::<lsp::request::DocumentHighlightRequest, _, _>({- let rng = rng.clone();- move |_, _| {- let mut highlights = Vec::new();- let highlight_count = rng.lock().gen_range(1..=5);- for _ in 0..highlight_count {- let start_row = rng.lock().gen_range(0..100);- let start_column = rng.lock().gen_range(0..100);- let start = PointUtf16::new(start_row, start_column);- let end_row = rng.lock().gen_range(0..100);- let end_column = rng.lock().gen_range(0..100);- let end = PointUtf16::new(end_row, end_column);- let range = if start > end { end..start } else { start..end };- highlights.push(lsp::DocumentHighlight {- range: range_to_lsp(range.clone()),- kind: Some(lsp::DocumentHighlightKind::READ),- });- }- highlights.sort_unstable_by_key(|highlight| {- (highlight.range.start, highlight.range.end)- });- async move { Ok(Some(highlights)) }+ for (client, cx) in clients {+ let contacts = server+ .app_state+ .db+ .get_contacts(client.current_user_id(cx))+ .await+ .unwrap();+ let pool = server.connection_pool.lock();+ for contact in contacts {- if let db::Contact::Accepted { user_id: id, .. } = contact {- if pool.is_user_online(id) {- assert_ne!(- id, user_id,- "removed client is still a contact of another peer"- );++ if let db::Contact::Accepted { user_id, busy, .. } = contact {++ if user_id == removed_user_id {++ assert!(!pool.is_user_online(user_id));++ assert!(!busy);}- });+ }}- })),- ..Default::default()- }))- .await;- client.language_registry.add(Arc::new(language));+ }- while op_start_signal.next().await.is_some() {- if let Err(error) =- randomly_mutate_client(&mut client, can_hang_up, rng.clone(), &mut cx).await- {- log::error!("{} error: {:?}", client.username, error);+ log::info!("{} removed", client.username);- plan.lock().user(user_id).online = false;++ plan.lock().user(removed_user_id).online = false;+ client_cx.update(|cx| {+ cx.clear_globals();+ drop(client);+ });}- cx.background().simulate_random_delay().await;- }- log::info!("{}: done", client.username);-- (client, cx)-}+ Operation::BounceConnection { user_id } => {+ log::info!("Simulating temporary disconnection of user {}", user_id);+ let user_connection_ids = server+ .connection_pool+ .lock()+ .user_connection_ids(user_id)+ .collect::<Vec<_>>();+ if user_connection_ids.is_empty() {+ return false;+ }+ assert_eq!(user_connection_ids.len(), 1);+ let peer_id = user_connection_ids[0].into();+ server.disconnect_client(peer_id);+ deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);+ }-async fn randomly_mutate_client(- client: &mut TestClient,- can_hang_up: bool,- rng: Arc<Mutex<StdRng>>,- cx: &mut TestAppContext,-) -> Result<()> {- let choice = rng.lock().gen_range(0..100);- match choice {- 0..=19 => randomly_mutate_active_call(client, can_hang_up, &rng, cx).await?,- 20..=49 => randomly_mutate_projects(client, &rng, cx).await?,- 50..=59 if !client.local_projects.is_empty() || !client.remote_projects.is_empty() => {- randomly_mutate_worktrees(client, &rng, cx).await?;+ Operation::RestartServer => {+ log::info!("Simulating server restart");+ server.reset().await;+ deterministic.advance_clock(RECEIVE_TIMEOUT);+ server.start().await.unwrap();+ deterministic.advance_clock(CLEANUP_TIMEOUT);+ let environment = &server.app_state.config.zed_environment;+ let stale_room_ids = server+ .app_state+ .db+ .stale_room_ids(environment, server.id())+ .await+ .unwrap();+ assert_eq!(stale_room_ids, vec![]);}- 60..=74 if !client.local_projects.is_empty() || !client.remote_projects.is_empty() => {- randomly_query_and_mutate_buffers(client, &rng, cx).await?;++ Operation::MutateClients {+ user_ids,+ batch_id,+ quiesce,+ } => {+ let mut applied = false;+ for user_id in user_ids {+ let client_ix = clients+ .iter()+ .position(|(client, cx)| client.current_user_id(cx) == user_id);+ let Some(client_ix) = client_ix else { continue };+ applied = true;+ if let Err(err) = operation_channels[client_ix].unbounded_send(batch_id) {+ // panic!("error signaling user {}, client {}", user_id, client_ix);+ }+ }++ if quiesce && applied {+ deterministic.run_until_parked();+ }++ return applied;}- 75..=84 => randomly_mutate_git(client, &rng).await,- _ => randomly_mutate_fs(client, &rng).await,}-- Ok(())+ true}-async fn randomly_mutate_active_call(- client: &mut TestClient,- can_hang_up: bool,- rng: &Mutex<StdRng>,+async fn apply_client_operation(+ client: &TestClient,+ operation: ClientOperation,cx: &mut TestAppContext,-) -> Result<()> {- let active_call = cx.read(ActiveCall::global);- if active_call.read_with(cx, |call, _| call.incoming().borrow().is_some()) {- if rng.lock().gen_bool(0.7) {+) -> Result<(), TestError> {+ match operation {+ ClientOperation::AcceptIncomingCall => {+ let active_call = cx.read(ActiveCall::global);+ if active_call.read_with(cx, |call, _| call.incoming().borrow().is_none()) {+ Err(TestError::Inapplicable)?;+ }+log::info!("{}: accepting incoming call", client.username);active_call.update(cx, |call, cx| call.accept_incoming(cx))@@@ -658,156 -831,249 +658,156 @@@FakeFs::new(cx.background().clone()),cx,)- })- .await?;- client.remote_projects.push(remote_project.clone());- remote_project- };+ }))+ })+ .ok_or(TestError::Inapplicable)?;- remote_project- } else {- client- .remote_projects- .choose(&mut *rng.lock())- .unwrap()- .clone()- }- };+ log::info!(+ "{}: joining remote project of user {}, root name {}",+ client.username,+ host_id,+ first_root_name,+ );- if active_call.read_with(cx, |call, _| call.room().is_some())- && project.read_with(cx, |project, _| project.is_local() && !project.is_shared())- {- match active_call- .update(cx, |call, cx| call.share_project(project.clone(), cx))- .await- {- Ok(project_id) => {- log::info!("{}: shared project with id {}", client.username, project_id);- }- Err(error) => {- log::error!("{}: error sharing project, {:?}", client.username, error);- }+ let project = project.await?;+ client.remote_projects_mut().push(project.clone());}- }- let choice = rng.lock().gen_range(0..100);- match choice {- 0..=19 if project.read_with(cx, |project, _| project.is_local()) => {- let paths = client.fs.paths().await;- let path = paths.choose(&mut *rng.lock()).unwrap();+ ClientOperation::CreateWorktreeEntry {+ project_root_name,+ is_local,+ full_path,+ is_dir,+ } => {+ let project = project_for_root_name(client, &project_root_name, cx)+ .ok_or(TestError::Inapplicable)?;+ let project_path = project_path_for_full_path(&project, &full_path, cx)+ .ok_or(TestError::Inapplicable)?;+log::info!(- "{}: finding/creating local worktree for path {:?}",+ "{}: creating {} at path {:?} in {} project {}",client.username,- path+ if is_dir { "dir" } else { "file" },+ full_path,+ if is_local { "local" } else { "remote" },+ project_root_name,);++ ensure_project_shared(&project, client, cx).await;project- .update(cx, |project, cx| {- project.find_or_create_local_worktree(&path, true, cx)- })- .await- .unwrap();+ .update(cx, |p, cx| p.create_entry(project_path, is_dir, cx))+ .unwrap()+ .await?;}- 20..=24 if project.read_with(cx, |project, _| project.is_remote()) => {++ ClientOperation::OpenBuffer {+ project_root_name,+ is_local,+ full_path,+ } => {+ let project = project_for_root_name(client, &project_root_name, cx)+ .ok_or(TestError::Inapplicable)?;+ let project_path = project_path_for_full_path(&project, &full_path, cx)+ .ok_or(TestError::Inapplicable)?;+log::info!(- "{}: dropping remote project {}",+ "{}: opening buffer {:?} in {} project {}",client.username,- project.read_with(cx, |project, _| project.remote_id().unwrap())+ full_path,+ if is_local { "local" } else { "remote" },+ project_root_name,);- cx.update(|_| {- client- .remote_projects- .retain(|remote_project| *remote_project != project);- client.buffers.remove(&project);- drop(project);- });+ ensure_project_shared(&project, client, cx).await;+ let buffer = project+ .update(cx, |project, cx| project.open_buffer(project_path, cx))+ .await?;+ client.buffers_for_project(&project).insert(buffer);}- _ => {}- }- Ok(())-}+ ClientOperation::EditBuffer {+ project_root_name,+ is_local,+ full_path,+ edits,+ } => {+ let project = project_for_root_name(client, &project_root_name, cx)+ .ok_or(TestError::Inapplicable)?;+ let buffer = buffer_for_full_path(client, &project, &full_path, cx)+ .ok_or(TestError::Inapplicable)?;-async fn randomly_mutate_worktrees(- client: &mut TestClient,- rng: &Mutex<StdRng>,- cx: &mut TestAppContext,-) -> Result<()> {- let project = choose_random_project(client, rng).unwrap();- let Some(worktree) = project.read_with(cx, |project, cx| {- project- .worktrees(cx)- .filter(|worktree| {- let worktree = worktree.read(cx);- worktree.is_visible()- && worktree.entries(false).any(|e| e.is_file())- && worktree.root_entry().map_or(false, |e| e.is_dir())- })- .choose(&mut *rng.lock())- }) else {- return Ok(())- };-- let (worktree_id, worktree_root_name) = worktree.read_with(cx, |worktree, _| {- (worktree.id(), worktree.root_name().to_string())- });-- let is_dir = rng.lock().gen::<bool>();- let mut new_path = PathBuf::new();- new_path.push(gen_file_name(rng));- if !is_dir {- new_path.set_extension("rs");- }- log::info!(- "{}: creating {:?} in worktree {} ({})",- client.username,- new_path,- worktree_id,- worktree_root_name,- );- project- .update(cx, |project, cx| {- project.create_entry((worktree_id, new_path), is_dir, cx)- })- .unwrap()- .await?;- Ok(())-}+ log::info!(+ "{}: editing buffer {:?} in {} project {} with {:?}",+ client.username,+ full_path,+ if is_local { "local" } else { "remote" },+ project_root_name,+ edits+ );-async fn randomly_query_and_mutate_buffers(- client: &mut TestClient,- rng: &Mutex<StdRng>,- cx: &mut TestAppContext,-) -> Result<()> {- let project = choose_random_project(client, rng).unwrap();- let buffers = client.buffers.entry(project.clone()).or_default();- let buffer = if buffers.is_empty() || rng.lock().gen() {- let Some(worktree) = project.read_with(cx, |project, cx| {- project- .worktrees(cx)- .filter(|worktree| {- let worktree = worktree.read(cx);- worktree.is_visible() && worktree.entries(false).any(|e| e.is_file())- })- .choose(&mut *rng.lock())- }) else {- return Ok(());- };-- let (worktree_root_name, project_path) = worktree.read_with(cx, |worktree, _| {- let entry = worktree- .entries(false)- .filter(|e| e.is_file())- .choose(&mut *rng.lock())- .unwrap();- (- worktree.root_name().to_string(),- (worktree.id(), entry.path.clone()),- )- });- log::info!(- "{}: opening path {:?} in worktree {} ({})",- client.username,- project_path.1,- project_path.0,- worktree_root_name,- );- let buffer = project- .update(cx, |project, cx| {- project.open_buffer(project_path.clone(), cx)- })- .await?;- log::info!(- "{}: opened path {:?} in worktree {} ({}) with buffer id {}",- client.username,- project_path.1,- project_path.0,- worktree_root_name,- buffer.read_with(cx, |buffer, _| buffer.remote_id())- );- buffers.insert(buffer.clone());- buffer- } else {- buffers.iter().choose(&mut *rng.lock()).unwrap().clone()- };-- let choice = rng.lock().gen_range(0..100);- match choice {- 0..=9 => {- cx.update(|cx| {- log::info!(- "{}: dropping buffer {:?}",- client.username,- buffer.read(cx).file().unwrap().full_path(cx)- );- buffers.remove(&buffer);- drop(buffer);- });- }- 10..=19 => {- let completions = project.update(cx, |project, cx| {- log::info!(- "{}: requesting completions for buffer {} ({:?})",- client.username,- buffer.read(cx).remote_id(),- buffer.read(cx).file().unwrap().full_path(cx)+ ensure_project_shared(&project, client, cx).await;+ buffer.update(cx, |buffer, cx| {+ let snapshot = buffer.snapshot();+ buffer.edit(+ edits.into_iter().map(|(range, text)| {+ let start = snapshot.clip_offset(range.start, Bias::Left);+ let end = snapshot.clip_offset(range.end, Bias::Right);+ (start..end, text)+ }),+ None,+ cx,);- let offset = rng.lock().gen_range(0..=buffer.read(cx).len());- project.completions(&buffer, offset, cx)});- let completions = cx.background().spawn(async move {- completions- .await- .map_err(|err| anyhow!("completions request failed: {:?}", err))- });- if rng.lock().gen_bool(0.3) {- log::info!("{}: detaching completions request", client.username);- cx.update(|cx| completions.detach_and_log_err(cx));- } else {- completions.await?;- }}- 20..=29 => {- let code_actions = project.update(cx, |project, cx| {- log::info!(- "{}: requesting code actions for buffer {} ({:?})",- client.username,- buffer.read(cx).remote_id(),- buffer.read(cx).file().unwrap().full_path(cx)- );- let range = buffer.read(cx).random_byte_range(0, &mut *rng.lock());- project.code_actions(&buffer, range, cx)- });- let code_actions = cx.background().spawn(async move {- code_actions- .await- .map_err(|err| anyhow!("code actions request failed: {:?}", err))++ ClientOperation::CloseBuffer {+ project_root_name,+ is_local,+ full_path,+ } => {+ let project = project_for_root_name(client, &project_root_name, cx)+ .ok_or(TestError::Inapplicable)?;+ let buffer = buffer_for_full_path(client, &project, &full_path, cx)+ .ok_or(TestError::Inapplicable)?;++ log::info!(+ "{}: closing buffer {:?} in {} project {}",+ client.username,+ full_path,+ if is_local { "local" } else { "remote" },+ project_root_name+ );++ ensure_project_shared(&project, client, cx).await;+ cx.update(|_| {+ client.buffers_for_project(&project).remove(&buffer);+ drop(buffer);});- if rng.lock().gen_bool(0.3) {- log::info!("{}: detaching code actions request", client.username);- cx.update(|cx| code_actions.detach_and_log_err(cx));- } else {- code_actions.await?;- }}- 30..=39 if buffer.read_with(cx, |buffer, _| buffer.is_dirty()) => {- let requested_version = buffer.update(cx, |buffer, cx| {- log::info!(- "{}: saving buffer {} ({:?})",- client.username,- buffer.remote_id(),- buffer.file().unwrap().full_path(cx)- );- buffer.version()- });++ ClientOperation::SaveBuffer {+ project_root_name,+ is_local,+ full_path,+ detach,+ } => {+ let project = project_for_root_name(client, &project_root_name, cx)+ .ok_or(TestError::Inapplicable)?;+ let buffer = buffer_for_full_path(client, &project, &full_path, cx)+ .ok_or(TestError::Inapplicable)?;++ log::info!(+ "{}: saving buffer {:?} in {} project {}{}",+ client.username,+ full_path,+ if is_local { "local" } else { "remote" },+ project_root_name,+ if detach { ", detaching" } else { ", awaiting" }+ );++ ensure_project_shared(&project, client, cx).await;- let (requested_version, save) =- buffer.update(cx, |buffer, cx| (buffer.version(), buffer.save(cx)));++ let requested_version = buffer.read_with(cx, |buffer, _| buffer.version());+ let save = project.update(cx, |project, cx| project.save_buffer(buffer, cx));let save = cx.background().spawn(async move {let (saved_version, _, _) = save.await@@@ -1960,27 -1216,14 +1960,15 @@@ fn gen_file_name(rng: &mut StdRng) -> Sname}-async fn child_file_paths(client: &TestClient, dir_path: &Path) -> Vec<PathBuf> {- let mut child_paths = client.fs.read_dir(dir_path).await.unwrap();- let mut child_file_paths = Vec::new();- while let Some(child_path) = child_paths.next().await {- let child_path = child_path.unwrap();- if client.fs.is_file(&child_path).await {- child_file_paths.push(child_path);- }+fn path_env_var(name: &str) -> Option<PathBuf> {+ let value = env::var(name).ok()?;+ let mut path = PathBuf::from(value);+ if path.is_relative() {+ let mut abs_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));+ abs_path.pop();+ abs_path.pop();+ abs_path.push(path);+ path = abs_path}- child_file_paths+ Some(path)}-- async fn child_file_paths(client: &TestClient, dir_path: &Path) -> Vec<PathBuf> {- let mut child_paths = client.fs.read_dir(dir_path).await.unwrap();- let mut child_file_paths = Vec::new();- while let Some(child_path) = child_paths.next().await {- let child_path = child_path.unwrap();- if client.fs.is_file(&child_path).await {- child_file_paths.push(child_path);- }- }- child_file_paths- }diff --cc crates/gpui/src/app/test_app_context.rsindex 3e75910475a,1366e7e6edb..1d467ae745b--- a/crates/gpui/src/app/test_app_context.rs+++ b/crates/gpui/src/app/test_app_context.rs@@@ -25,9 -24,10 +24,11 @@@ use crate::};use collections::BTreeMap;- use super::{AsyncAppContext, RefCounts};+ use super::{+ ref_counts::LeakDetector, window_input_handler::WindowInputHandler, AsyncAppContext, RefCounts,+ };+#[derive(Clone)]pub struct TestAppContext {cx: Rc<RefCell<MutableAppContext>>,foreground_platform: Rc<platform::test::ForegroundPlatform>,