1use crate::{
2 db::{self, NewUserParams, UserId},
3 rpc::{CLEANUP_TIMEOUT, RECONNECT_TIMEOUT},
4 tests::{TestClient, TestServer},
5};
6use anyhow::{anyhow, Result};
7use call::ActiveCall;
8use client::RECEIVE_TIMEOUT;
9use collections::{BTreeMap, HashMap};
10use editor::Bias;
11use fs::{repository::GitFileStatus, FakeFs, Fs as _};
12use futures::StreamExt as _;
13use gpui::{executor::Deterministic, ModelHandle, Task, TestAppContext};
14use language::{range_to_lsp, FakeLspAdapter, Language, LanguageConfig, PointUtf16};
15use lsp::FakeLanguageServer;
16use parking_lot::Mutex;
17use pretty_assertions::assert_eq;
18use project::{search::SearchQuery, Project, ProjectPath};
19use rand::{
20 distributions::{Alphanumeric, DistString},
21 prelude::*,
22};
23use serde::{Deserialize, Serialize};
24use settings::SettingsStore;
25use std::{
26 env,
27 ops::Range,
28 path::{Path, PathBuf},
29 rc::Rc,
30 sync::{
31 atomic::{AtomicBool, Ordering::SeqCst},
32 Arc,
33 },
34};
35use util::ResultExt;
36
37lazy_static::lazy_static! {
38 static ref PLAN_LOAD_PATH: Option<PathBuf> = path_env_var("LOAD_PLAN");
39 static ref PLAN_SAVE_PATH: Option<PathBuf> = path_env_var("SAVE_PLAN");
40}
41static LOADED_PLAN_JSON: Mutex<Option<Vec<u8>>> = Mutex::new(None);
42static PLAN: Mutex<Option<Arc<Mutex<TestPlan>>>> = Mutex::new(None);
43
44#[gpui::test(iterations = 100, on_failure = "on_failure")]
45async fn test_random_collaboration(
46 cx: &mut TestAppContext,
47 deterministic: Arc<Deterministic>,
48 rng: StdRng,
49) {
50 deterministic.forbid_parking();
51
52 let max_peers = env::var("MAX_PEERS")
53 .map(|i| i.parse().expect("invalid `MAX_PEERS` variable"))
54 .unwrap_or(3);
55 let max_operations = env::var("OPERATIONS")
56 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
57 .unwrap_or(10);
58
59 let mut server = TestServer::start(&deterministic).await;
60 let db = server.app_state.db.clone();
61
62 let mut users = Vec::new();
63 for ix in 0..max_peers {
64 let username = format!("user-{}", ix + 1);
65 let user_id = db
66 .create_user(
67 &format!("{username}@example.com"),
68 false,
69 NewUserParams {
70 github_login: username.clone(),
71 github_user_id: (ix + 1) as i32,
72 invite_count: 0,
73 },
74 )
75 .await
76 .unwrap()
77 .user_id;
78 users.push(UserTestPlan {
79 user_id,
80 username,
81 online: false,
82 next_root_id: 0,
83 operation_ix: 0,
84 });
85 }
86
87 for (ix, user_a) in users.iter().enumerate() {
88 for user_b in &users[ix + 1..] {
89 server
90 .app_state
91 .db
92 .send_contact_request(user_a.user_id, user_b.user_id)
93 .await
94 .unwrap();
95 server
96 .app_state
97 .db
98 .respond_to_contact_request(user_b.user_id, user_a.user_id, true)
99 .await
100 .unwrap();
101 }
102 }
103
104 let plan = Arc::new(Mutex::new(TestPlan::new(rng, users, max_operations)));
105
106 if let Some(path) = &*PLAN_LOAD_PATH {
107 let json = LOADED_PLAN_JSON
108 .lock()
109 .get_or_insert_with(|| {
110 eprintln!("loaded test plan from path {:?}", path);
111 std::fs::read(path).unwrap()
112 })
113 .clone();
114 plan.lock().deserialize(json);
115 }
116
117 PLAN.lock().replace(plan.clone());
118
119 let mut clients = Vec::new();
120 let mut client_tasks = Vec::new();
121 let mut operation_channels = Vec::new();
122
123 loop {
124 let Some((next_operation, applied)) = plan.lock().next_server_operation(&clients) else {
125 break;
126 };
127 applied.store(true, SeqCst);
128 let did_apply = apply_server_operation(
129 deterministic.clone(),
130 &mut server,
131 &mut clients,
132 &mut client_tasks,
133 &mut operation_channels,
134 plan.clone(),
135 next_operation,
136 cx,
137 )
138 .await;
139 if !did_apply {
140 applied.store(false, SeqCst);
141 }
142 }
143
144 drop(operation_channels);
145 deterministic.start_waiting();
146 futures::future::join_all(client_tasks).await;
147 deterministic.finish_waiting();
148 deterministic.run_until_parked();
149
150 check_consistency_between_clients(&clients);
151
152 for (client, mut cx) in clients {
153 cx.update(|cx| {
154 let store = cx.remove_global::<SettingsStore>();
155 cx.clear_globals();
156 cx.set_global(store);
157 drop(client);
158 });
159 }
160
161 deterministic.run_until_parked();
162}
163
164fn on_failure() {
165 if let Some(plan) = PLAN.lock().clone() {
166 if let Some(path) = &*PLAN_SAVE_PATH {
167 eprintln!("saved test plan to path {:?}", path);
168 std::fs::write(path, plan.lock().serialize()).unwrap();
169 }
170 }
171}
172
173async fn apply_server_operation(
174 deterministic: Arc<Deterministic>,
175 server: &mut TestServer,
176 clients: &mut Vec<(Rc<TestClient>, TestAppContext)>,
177 client_tasks: &mut Vec<Task<()>>,
178 operation_channels: &mut Vec<futures::channel::mpsc::UnboundedSender<usize>>,
179 plan: Arc<Mutex<TestPlan>>,
180 operation: Operation,
181 cx: &mut TestAppContext,
182) -> bool {
183 match operation {
184 Operation::AddConnection { user_id } => {
185 let username;
186 {
187 let mut plan = plan.lock();
188 let user = plan.user(user_id);
189 if user.online {
190 return false;
191 }
192 user.online = true;
193 username = user.username.clone();
194 };
195 log::info!("Adding new connection for {}", username);
196 let next_entity_id = (user_id.0 * 10_000) as usize;
197 let mut client_cx = TestAppContext::new(
198 cx.foreground_platform(),
199 cx.platform(),
200 deterministic.build_foreground(user_id.0 as usize),
201 deterministic.build_background(),
202 cx.font_cache(),
203 cx.leak_detector(),
204 next_entity_id,
205 cx.function_name.clone(),
206 );
207
208 let (operation_tx, operation_rx) = futures::channel::mpsc::unbounded();
209 let client = Rc::new(server.create_client(&mut client_cx, &username).await);
210 operation_channels.push(operation_tx);
211 clients.push((client.clone(), client_cx.clone()));
212 client_tasks.push(client_cx.foreground().spawn(simulate_client(
213 client,
214 operation_rx,
215 plan.clone(),
216 client_cx,
217 )));
218
219 log::info!("Added connection for {}", username);
220 }
221
222 Operation::RemoveConnection {
223 user_id: removed_user_id,
224 } => {
225 log::info!("Simulating full disconnection of user {}", removed_user_id);
226 let client_ix = clients
227 .iter()
228 .position(|(client, cx)| client.current_user_id(cx) == removed_user_id);
229 let Some(client_ix) = client_ix else {
230 return false;
231 };
232 let user_connection_ids = server
233 .connection_pool
234 .lock()
235 .user_connection_ids(removed_user_id)
236 .collect::<Vec<_>>();
237 assert_eq!(user_connection_ids.len(), 1);
238 let removed_peer_id = user_connection_ids[0].into();
239 let (client, mut client_cx) = clients.remove(client_ix);
240 let client_task = client_tasks.remove(client_ix);
241 operation_channels.remove(client_ix);
242 server.forbid_connections();
243 server.disconnect_client(removed_peer_id);
244 deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
245 deterministic.start_waiting();
246 log::info!("Waiting for user {} to exit...", removed_user_id);
247 client_task.await;
248 deterministic.finish_waiting();
249 server.allow_connections();
250
251 for project in client.remote_projects().iter() {
252 project.read_with(&client_cx, |project, _| {
253 assert!(
254 project.is_read_only(),
255 "project {:?} should be read only",
256 project.remote_id()
257 )
258 });
259 }
260
261 for (client, cx) in clients {
262 let contacts = server
263 .app_state
264 .db
265 .get_contacts(client.current_user_id(cx))
266 .await
267 .unwrap();
268 let pool = server.connection_pool.lock();
269 for contact in contacts {
270 if let db::Contact::Accepted { user_id, busy, .. } = contact {
271 if user_id == removed_user_id {
272 assert!(!pool.is_user_online(user_id));
273 assert!(!busy);
274 }
275 }
276 }
277 }
278
279 log::info!("{} removed", client.username);
280 plan.lock().user(removed_user_id).online = false;
281 client_cx.update(|cx| {
282 cx.clear_globals();
283 drop(client);
284 });
285 }
286
287 Operation::BounceConnection { user_id } => {
288 log::info!("Simulating temporary disconnection of user {}", user_id);
289 let user_connection_ids = server
290 .connection_pool
291 .lock()
292 .user_connection_ids(user_id)
293 .collect::<Vec<_>>();
294 if user_connection_ids.is_empty() {
295 return false;
296 }
297 assert_eq!(user_connection_ids.len(), 1);
298 let peer_id = user_connection_ids[0].into();
299 server.disconnect_client(peer_id);
300 deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
301 }
302
303 Operation::RestartServer => {
304 log::info!("Simulating server restart");
305 server.reset().await;
306 deterministic.advance_clock(RECEIVE_TIMEOUT);
307 server.start().await.unwrap();
308 deterministic.advance_clock(CLEANUP_TIMEOUT);
309 let environment = &server.app_state.config.zed_environment;
310 let (stale_room_ids, _) = server
311 .app_state
312 .db
313 .stale_server_resource_ids(environment, server.id())
314 .await
315 .unwrap();
316 assert_eq!(stale_room_ids, vec![]);
317 }
318
319 Operation::MutateClients {
320 user_ids,
321 batch_id,
322 quiesce,
323 } => {
324 let mut applied = false;
325 for user_id in user_ids {
326 let client_ix = clients
327 .iter()
328 .position(|(client, cx)| client.current_user_id(cx) == user_id);
329 let Some(client_ix) = client_ix else { continue };
330 applied = true;
331 if let Err(err) = operation_channels[client_ix].unbounded_send(batch_id) {
332 log::error!("error signaling user {user_id}: {err}");
333 }
334 }
335
336 if quiesce && applied {
337 deterministic.run_until_parked();
338 check_consistency_between_clients(&clients);
339 }
340
341 return applied;
342 }
343 }
344 true
345}
346
347async fn apply_client_operation(
348 client: &TestClient,
349 operation: ClientOperation,
350 cx: &mut TestAppContext,
351) -> Result<(), TestError> {
352 match operation {
353 ClientOperation::AcceptIncomingCall => {
354 let active_call = cx.read(ActiveCall::global);
355 if active_call.read_with(cx, |call, _| call.incoming().borrow().is_none()) {
356 Err(TestError::Inapplicable)?;
357 }
358
359 log::info!("{}: accepting incoming call", client.username);
360 active_call
361 .update(cx, |call, cx| call.accept_incoming(cx))
362 .await?;
363 }
364
365 ClientOperation::RejectIncomingCall => {
366 let active_call = cx.read(ActiveCall::global);
367 if active_call.read_with(cx, |call, _| call.incoming().borrow().is_none()) {
368 Err(TestError::Inapplicable)?;
369 }
370
371 log::info!("{}: declining incoming call", client.username);
372 active_call.update(cx, |call, cx| call.decline_incoming(cx))?;
373 }
374
375 ClientOperation::LeaveCall => {
376 let active_call = cx.read(ActiveCall::global);
377 if active_call.read_with(cx, |call, _| call.room().is_none()) {
378 Err(TestError::Inapplicable)?;
379 }
380
381 log::info!("{}: hanging up", client.username);
382 active_call.update(cx, |call, cx| call.hang_up(cx)).await?;
383 }
384
385 ClientOperation::InviteContactToCall { user_id } => {
386 let active_call = cx.read(ActiveCall::global);
387
388 log::info!("{}: inviting {}", client.username, user_id,);
389 active_call
390 .update(cx, |call, cx| call.invite(user_id.to_proto(), None, cx))
391 .await
392 .log_err();
393 }
394
395 ClientOperation::OpenLocalProject { first_root_name } => {
396 log::info!(
397 "{}: opening local project at {:?}",
398 client.username,
399 first_root_name
400 );
401
402 let root_path = Path::new("/").join(&first_root_name);
403 client.fs().create_dir(&root_path).await.unwrap();
404 client
405 .fs()
406 .create_file(&root_path.join("main.rs"), Default::default())
407 .await
408 .unwrap();
409 let project = client.build_local_project(root_path, cx).await.0;
410 ensure_project_shared(&project, client, cx).await;
411 client.local_projects_mut().push(project.clone());
412 }
413
414 ClientOperation::AddWorktreeToProject {
415 project_root_name,
416 new_root_path,
417 } => {
418 let project = project_for_root_name(client, &project_root_name, cx)
419 .ok_or(TestError::Inapplicable)?;
420
421 log::info!(
422 "{}: finding/creating local worktree at {:?} to project with root path {}",
423 client.username,
424 new_root_path,
425 project_root_name
426 );
427
428 ensure_project_shared(&project, client, cx).await;
429 if !client.fs().paths(false).contains(&new_root_path) {
430 client.fs().create_dir(&new_root_path).await.unwrap();
431 }
432 project
433 .update(cx, |project, cx| {
434 project.find_or_create_local_worktree(&new_root_path, true, cx)
435 })
436 .await
437 .unwrap();
438 }
439
440 ClientOperation::CloseRemoteProject { project_root_name } => {
441 let project = project_for_root_name(client, &project_root_name, cx)
442 .ok_or(TestError::Inapplicable)?;
443
444 log::info!(
445 "{}: closing remote project with root path {}",
446 client.username,
447 project_root_name,
448 );
449
450 let ix = client
451 .remote_projects()
452 .iter()
453 .position(|p| p == &project)
454 .unwrap();
455 cx.update(|_| {
456 client.remote_projects_mut().remove(ix);
457 client.buffers().retain(|p, _| *p != project);
458 drop(project);
459 });
460 }
461
462 ClientOperation::OpenRemoteProject {
463 host_id,
464 first_root_name,
465 } => {
466 let active_call = cx.read(ActiveCall::global);
467 let project = active_call
468 .update(cx, |call, cx| {
469 let room = call.room().cloned()?;
470 let participant = room
471 .read(cx)
472 .remote_participants()
473 .get(&host_id.to_proto())?;
474 let project_id = participant
475 .projects
476 .iter()
477 .find(|project| project.worktree_root_names[0] == first_root_name)?
478 .id;
479 Some(room.update(cx, |room, cx| {
480 room.join_project(
481 project_id,
482 client.language_registry().clone(),
483 FakeFs::new(cx.background().clone()),
484 cx,
485 )
486 }))
487 })
488 .ok_or(TestError::Inapplicable)?;
489
490 log::info!(
491 "{}: joining remote project of user {}, root name {}",
492 client.username,
493 host_id,
494 first_root_name,
495 );
496
497 let project = project.await?;
498 client.remote_projects_mut().push(project.clone());
499 }
500
501 ClientOperation::CreateWorktreeEntry {
502 project_root_name,
503 is_local,
504 full_path,
505 is_dir,
506 } => {
507 let project = project_for_root_name(client, &project_root_name, cx)
508 .ok_or(TestError::Inapplicable)?;
509 let project_path = project_path_for_full_path(&project, &full_path, cx)
510 .ok_or(TestError::Inapplicable)?;
511
512 log::info!(
513 "{}: creating {} at path {:?} in {} project {}",
514 client.username,
515 if is_dir { "dir" } else { "file" },
516 full_path,
517 if is_local { "local" } else { "remote" },
518 project_root_name,
519 );
520
521 ensure_project_shared(&project, client, cx).await;
522 project
523 .update(cx, |p, cx| p.create_entry(project_path, is_dir, cx))
524 .unwrap()
525 .await?;
526 }
527
528 ClientOperation::OpenBuffer {
529 project_root_name,
530 is_local,
531 full_path,
532 } => {
533 let project = project_for_root_name(client, &project_root_name, cx)
534 .ok_or(TestError::Inapplicable)?;
535 let project_path = project_path_for_full_path(&project, &full_path, cx)
536 .ok_or(TestError::Inapplicable)?;
537
538 log::info!(
539 "{}: opening buffer {:?} in {} project {}",
540 client.username,
541 full_path,
542 if is_local { "local" } else { "remote" },
543 project_root_name,
544 );
545
546 ensure_project_shared(&project, client, cx).await;
547 let buffer = project
548 .update(cx, |project, cx| project.open_buffer(project_path, cx))
549 .await?;
550 client.buffers_for_project(&project).insert(buffer);
551 }
552
553 ClientOperation::EditBuffer {
554 project_root_name,
555 is_local,
556 full_path,
557 edits,
558 } => {
559 let project = project_for_root_name(client, &project_root_name, cx)
560 .ok_or(TestError::Inapplicable)?;
561 let buffer = buffer_for_full_path(client, &project, &full_path, cx)
562 .ok_or(TestError::Inapplicable)?;
563
564 log::info!(
565 "{}: editing buffer {:?} in {} project {} with {:?}",
566 client.username,
567 full_path,
568 if is_local { "local" } else { "remote" },
569 project_root_name,
570 edits
571 );
572
573 ensure_project_shared(&project, client, cx).await;
574 buffer.update(cx, |buffer, cx| {
575 let snapshot = buffer.snapshot();
576 buffer.edit(
577 edits.into_iter().map(|(range, text)| {
578 let start = snapshot.clip_offset(range.start, Bias::Left);
579 let end = snapshot.clip_offset(range.end, Bias::Right);
580 (start..end, text)
581 }),
582 None,
583 cx,
584 );
585 });
586 }
587
588 ClientOperation::CloseBuffer {
589 project_root_name,
590 is_local,
591 full_path,
592 } => {
593 let project = project_for_root_name(client, &project_root_name, cx)
594 .ok_or(TestError::Inapplicable)?;
595 let buffer = buffer_for_full_path(client, &project, &full_path, cx)
596 .ok_or(TestError::Inapplicable)?;
597
598 log::info!(
599 "{}: closing buffer {:?} in {} project {}",
600 client.username,
601 full_path,
602 if is_local { "local" } else { "remote" },
603 project_root_name
604 );
605
606 ensure_project_shared(&project, client, cx).await;
607 cx.update(|_| {
608 client.buffers_for_project(&project).remove(&buffer);
609 drop(buffer);
610 });
611 }
612
613 ClientOperation::SaveBuffer {
614 project_root_name,
615 is_local,
616 full_path,
617 detach,
618 } => {
619 let project = project_for_root_name(client, &project_root_name, cx)
620 .ok_or(TestError::Inapplicable)?;
621 let buffer = buffer_for_full_path(client, &project, &full_path, cx)
622 .ok_or(TestError::Inapplicable)?;
623
624 log::info!(
625 "{}: saving buffer {:?} in {} project {}, {}",
626 client.username,
627 full_path,
628 if is_local { "local" } else { "remote" },
629 project_root_name,
630 if detach { "detaching" } else { "awaiting" }
631 );
632
633 ensure_project_shared(&project, client, cx).await;
634 let requested_version = buffer.read_with(cx, |buffer, _| buffer.version());
635 let save = project.update(cx, |project, cx| project.save_buffer(buffer.clone(), cx));
636 let save = cx.spawn(|cx| async move {
637 save.await
638 .map_err(|err| anyhow!("save request failed: {:?}", err))?;
639 assert!(buffer
640 .read_with(&cx, |buffer, _| { buffer.saved_version().to_owned() })
641 .observed_all(&requested_version));
642 anyhow::Ok(())
643 });
644 if detach {
645 cx.update(|cx| save.detach_and_log_err(cx));
646 } else {
647 save.await?;
648 }
649 }
650
651 ClientOperation::RequestLspDataInBuffer {
652 project_root_name,
653 is_local,
654 full_path,
655 offset,
656 kind,
657 detach,
658 } => {
659 let project = project_for_root_name(client, &project_root_name, cx)
660 .ok_or(TestError::Inapplicable)?;
661 let buffer = buffer_for_full_path(client, &project, &full_path, cx)
662 .ok_or(TestError::Inapplicable)?;
663
664 log::info!(
665 "{}: request LSP {:?} for buffer {:?} in {} project {}, {}",
666 client.username,
667 kind,
668 full_path,
669 if is_local { "local" } else { "remote" },
670 project_root_name,
671 if detach { "detaching" } else { "awaiting" }
672 );
673
674 use futures::{FutureExt as _, TryFutureExt as _};
675 let offset = buffer.read_with(cx, |b, _| b.clip_offset(offset, Bias::Left));
676 let request = cx.foreground().spawn(project.update(cx, |project, cx| {
677 match kind {
678 LspRequestKind::Rename => project
679 .prepare_rename(buffer, offset, cx)
680 .map_ok(|_| ())
681 .boxed(),
682 LspRequestKind::Completion => project
683 .completions(&buffer, offset, cx)
684 .map_ok(|_| ())
685 .boxed(),
686 LspRequestKind::CodeAction => project
687 .code_actions(&buffer, offset..offset, cx)
688 .map_ok(|_| ())
689 .boxed(),
690 LspRequestKind::Definition => project
691 .definition(&buffer, offset, cx)
692 .map_ok(|_| ())
693 .boxed(),
694 LspRequestKind::Highlights => project
695 .document_highlights(&buffer, offset, cx)
696 .map_ok(|_| ())
697 .boxed(),
698 }
699 }));
700 if detach {
701 request.detach();
702 } else {
703 request.await?;
704 }
705 }
706
707 ClientOperation::SearchProject {
708 project_root_name,
709 is_local,
710 query,
711 detach,
712 } => {
713 let project = project_for_root_name(client, &project_root_name, cx)
714 .ok_or(TestError::Inapplicable)?;
715
716 log::info!(
717 "{}: search {} project {} for {:?}, {}",
718 client.username,
719 if is_local { "local" } else { "remote" },
720 project_root_name,
721 query,
722 if detach { "detaching" } else { "awaiting" }
723 );
724
725 let mut search = project.update(cx, |project, cx| {
726 project.search(
727 SearchQuery::text(query, false, false, Vec::new(), Vec::new()),
728 cx,
729 )
730 });
731 drop(project);
732 let search = cx.background().spawn(async move {
733 let mut results = HashMap::default();
734 while let Some((buffer, ranges)) = search.next().await {
735 results.entry(buffer).or_insert(ranges);
736 }
737 results
738 });
739 search.await;
740 }
741
742 ClientOperation::WriteFsEntry {
743 path,
744 is_dir,
745 content,
746 } => {
747 if !client
748 .fs()
749 .directories(false)
750 .contains(&path.parent().unwrap().to_owned())
751 {
752 return Err(TestError::Inapplicable);
753 }
754
755 if is_dir {
756 log::info!("{}: creating dir at {:?}", client.username, path);
757 client.fs().create_dir(&path).await.unwrap();
758 } else {
759 let exists = client.fs().metadata(&path).await?.is_some();
760 let verb = if exists { "updating" } else { "creating" };
761 log::info!("{}: {} file at {:?}", verb, client.username, path);
762
763 client
764 .fs()
765 .save(&path, &content.as_str().into(), text::LineEnding::Unix)
766 .await
767 .unwrap();
768 }
769 }
770
771 ClientOperation::GitOperation { operation } => match operation {
772 GitOperation::WriteGitIndex {
773 repo_path,
774 contents,
775 } => {
776 if !client.fs().directories(false).contains(&repo_path) {
777 return Err(TestError::Inapplicable);
778 }
779
780 for (path, _) in contents.iter() {
781 if !client.fs().files().contains(&repo_path.join(path)) {
782 return Err(TestError::Inapplicable);
783 }
784 }
785
786 log::info!(
787 "{}: writing git index for repo {:?}: {:?}",
788 client.username,
789 repo_path,
790 contents
791 );
792
793 let dot_git_dir = repo_path.join(".git");
794 let contents = contents
795 .iter()
796 .map(|(path, contents)| (path.as_path(), contents.clone()))
797 .collect::<Vec<_>>();
798 if client.fs().metadata(&dot_git_dir).await?.is_none() {
799 client.fs().create_dir(&dot_git_dir).await?;
800 }
801 client.fs().set_index_for_repo(&dot_git_dir, &contents);
802 }
803 GitOperation::WriteGitBranch {
804 repo_path,
805 new_branch,
806 } => {
807 if !client.fs().directories(false).contains(&repo_path) {
808 return Err(TestError::Inapplicable);
809 }
810
811 log::info!(
812 "{}: writing git branch for repo {:?}: {:?}",
813 client.username,
814 repo_path,
815 new_branch
816 );
817
818 let dot_git_dir = repo_path.join(".git");
819 if client.fs().metadata(&dot_git_dir).await?.is_none() {
820 client.fs().create_dir(&dot_git_dir).await?;
821 }
822 client.fs().set_branch_name(&dot_git_dir, new_branch);
823 }
824 GitOperation::WriteGitStatuses {
825 repo_path,
826 statuses,
827 git_operation,
828 } => {
829 if !client.fs().directories(false).contains(&repo_path) {
830 return Err(TestError::Inapplicable);
831 }
832 for (path, _) in statuses.iter() {
833 if !client.fs().files().contains(&repo_path.join(path)) {
834 return Err(TestError::Inapplicable);
835 }
836 }
837
838 log::info!(
839 "{}: writing git statuses for repo {:?}: {:?}",
840 client.username,
841 repo_path,
842 statuses
843 );
844
845 let dot_git_dir = repo_path.join(".git");
846
847 let statuses = statuses
848 .iter()
849 .map(|(path, val)| (path.as_path(), val.clone()))
850 .collect::<Vec<_>>();
851
852 if client.fs().metadata(&dot_git_dir).await?.is_none() {
853 client.fs().create_dir(&dot_git_dir).await?;
854 }
855
856 if git_operation {
857 client
858 .fs()
859 .set_status_for_repo_via_git_operation(&dot_git_dir, statuses.as_slice());
860 } else {
861 client.fs().set_status_for_repo_via_working_copy_change(
862 &dot_git_dir,
863 statuses.as_slice(),
864 );
865 }
866 }
867 },
868 }
869 Ok(())
870}
871
872fn check_consistency_between_clients(clients: &[(Rc<TestClient>, TestAppContext)]) {
873 for (client, client_cx) in clients {
874 for guest_project in client.remote_projects().iter() {
875 guest_project.read_with(client_cx, |guest_project, cx| {
876 let host_project = clients.iter().find_map(|(client, cx)| {
877 let project = client
878 .local_projects()
879 .iter()
880 .find(|host_project| {
881 host_project.read_with(cx, |host_project, _| {
882 host_project.remote_id() == guest_project.remote_id()
883 })
884 })?
885 .clone();
886 Some((project, cx))
887 });
888
889 if !guest_project.is_read_only() {
890 if let Some((host_project, host_cx)) = host_project {
891 let host_worktree_snapshots =
892 host_project.read_with(host_cx, |host_project, cx| {
893 host_project
894 .worktrees(cx)
895 .map(|worktree| {
896 let worktree = worktree.read(cx);
897 (worktree.id(), worktree.snapshot())
898 })
899 .collect::<BTreeMap<_, _>>()
900 });
901 let guest_worktree_snapshots = guest_project
902 .worktrees(cx)
903 .map(|worktree| {
904 let worktree = worktree.read(cx);
905 (worktree.id(), worktree.snapshot())
906 })
907 .collect::<BTreeMap<_, _>>();
908
909 assert_eq!(
910 guest_worktree_snapshots.values().map(|w| w.abs_path()).collect::<Vec<_>>(),
911 host_worktree_snapshots.values().map(|w| w.abs_path()).collect::<Vec<_>>(),
912 "{} has different worktrees than the host for project {:?}",
913 client.username, guest_project.remote_id(),
914 );
915
916 for (id, host_snapshot) in &host_worktree_snapshots {
917 let guest_snapshot = &guest_worktree_snapshots[id];
918 assert_eq!(
919 guest_snapshot.root_name(),
920 host_snapshot.root_name(),
921 "{} has different root name than the host for worktree {}, project {:?}",
922 client.username,
923 id,
924 guest_project.remote_id(),
925 );
926 assert_eq!(
927 guest_snapshot.abs_path(),
928 host_snapshot.abs_path(),
929 "{} has different abs path than the host for worktree {}, project: {:?}",
930 client.username,
931 id,
932 guest_project.remote_id(),
933 );
934 assert_eq!(
935 guest_snapshot.entries(false).collect::<Vec<_>>(),
936 host_snapshot.entries(false).collect::<Vec<_>>(),
937 "{} has different snapshot than the host for worktree {:?} ({:?}) and project {:?}",
938 client.username,
939 host_snapshot.abs_path(),
940 id,
941 guest_project.remote_id(),
942 );
943 assert_eq!(guest_snapshot.repositories().collect::<Vec<_>>(), host_snapshot.repositories().collect::<Vec<_>>(),
944 "{} has different repositories than the host for worktree {:?} and project {:?}",
945 client.username,
946 host_snapshot.abs_path(),
947 guest_project.remote_id(),
948 );
949 assert_eq!(guest_snapshot.scan_id(), host_snapshot.scan_id(),
950 "{} has different scan id than the host for worktree {:?} and project {:?}",
951 client.username,
952 host_snapshot.abs_path(),
953 guest_project.remote_id(),
954 );
955 }
956 }
957 }
958
959 for buffer in guest_project.opened_buffers(cx) {
960 let buffer = buffer.read(cx);
961 assert_eq!(
962 buffer.deferred_ops_len(),
963 0,
964 "{} has deferred operations for buffer {:?} in project {:?}",
965 client.username,
966 buffer.file().unwrap().full_path(cx),
967 guest_project.remote_id(),
968 );
969 }
970 });
971 }
972
973 let buffers = client.buffers().clone();
974 for (guest_project, guest_buffers) in &buffers {
975 let project_id = if guest_project.read_with(client_cx, |project, _| {
976 project.is_local() || project.is_read_only()
977 }) {
978 continue;
979 } else {
980 guest_project
981 .read_with(client_cx, |project, _| project.remote_id())
982 .unwrap()
983 };
984 let guest_user_id = client.user_id().unwrap();
985
986 let host_project = clients.iter().find_map(|(client, cx)| {
987 let project = client
988 .local_projects()
989 .iter()
990 .find(|host_project| {
991 host_project.read_with(cx, |host_project, _| {
992 host_project.remote_id() == Some(project_id)
993 })
994 })?
995 .clone();
996 Some((client.user_id().unwrap(), project, cx))
997 });
998
999 let (host_user_id, host_project, host_cx) =
1000 if let Some((host_user_id, host_project, host_cx)) = host_project {
1001 (host_user_id, host_project, host_cx)
1002 } else {
1003 continue;
1004 };
1005
1006 for guest_buffer in guest_buffers {
1007 let buffer_id = guest_buffer.read_with(client_cx, |buffer, _| buffer.remote_id());
1008 let host_buffer = host_project.read_with(host_cx, |project, cx| {
1009 project.buffer_for_id(buffer_id, cx).unwrap_or_else(|| {
1010 panic!(
1011 "host does not have buffer for guest:{}, peer:{:?}, id:{}",
1012 client.username,
1013 client.peer_id(),
1014 buffer_id
1015 )
1016 })
1017 });
1018 let path = host_buffer
1019 .read_with(host_cx, |buffer, cx| buffer.file().unwrap().full_path(cx));
1020
1021 assert_eq!(
1022 guest_buffer.read_with(client_cx, |buffer, _| buffer.deferred_ops_len()),
1023 0,
1024 "{}, buffer {}, path {:?} has deferred operations",
1025 client.username,
1026 buffer_id,
1027 path,
1028 );
1029 assert_eq!(
1030 guest_buffer.read_with(client_cx, |buffer, _| buffer.text()),
1031 host_buffer.read_with(host_cx, |buffer, _| buffer.text()),
1032 "{}, buffer {}, path {:?}, differs from the host's buffer",
1033 client.username,
1034 buffer_id,
1035 path
1036 );
1037
1038 let host_file = host_buffer.read_with(host_cx, |b, _| b.file().cloned());
1039 let guest_file = guest_buffer.read_with(client_cx, |b, _| b.file().cloned());
1040 match (host_file, guest_file) {
1041 (Some(host_file), Some(guest_file)) => {
1042 assert_eq!(guest_file.path(), host_file.path());
1043 assert_eq!(guest_file.is_deleted(), host_file.is_deleted());
1044 assert_eq!(
1045 guest_file.mtime(),
1046 host_file.mtime(),
1047 "guest {} mtime does not match host {} for path {:?} in project {}",
1048 guest_user_id,
1049 host_user_id,
1050 guest_file.path(),
1051 project_id,
1052 );
1053 }
1054 (None, None) => {}
1055 (None, _) => panic!("host's file is None, guest's isn't"),
1056 (_, None) => panic!("guest's file is None, hosts's isn't"),
1057 }
1058
1059 let host_diff_base =
1060 host_buffer.read_with(host_cx, |b, _| b.diff_base().map(ToString::to_string));
1061 let guest_diff_base = guest_buffer
1062 .read_with(client_cx, |b, _| b.diff_base().map(ToString::to_string));
1063 assert_eq!(
1064 guest_diff_base, host_diff_base,
1065 "guest {} diff base does not match host's for path {path:?} in project {project_id}",
1066 client.username
1067 );
1068
1069 let host_saved_version =
1070 host_buffer.read_with(host_cx, |b, _| b.saved_version().clone());
1071 let guest_saved_version =
1072 guest_buffer.read_with(client_cx, |b, _| b.saved_version().clone());
1073 assert_eq!(
1074 guest_saved_version, host_saved_version,
1075 "guest {} saved version does not match host's for path {path:?} in project {project_id}",
1076 client.username
1077 );
1078
1079 let host_saved_version_fingerprint =
1080 host_buffer.read_with(host_cx, |b, _| b.saved_version_fingerprint());
1081 let guest_saved_version_fingerprint =
1082 guest_buffer.read_with(client_cx, |b, _| b.saved_version_fingerprint());
1083 assert_eq!(
1084 guest_saved_version_fingerprint, host_saved_version_fingerprint,
1085 "guest {} saved fingerprint does not match host's for path {path:?} in project {project_id}",
1086 client.username
1087 );
1088
1089 let host_saved_mtime = host_buffer.read_with(host_cx, |b, _| b.saved_mtime());
1090 let guest_saved_mtime = guest_buffer.read_with(client_cx, |b, _| b.saved_mtime());
1091 assert_eq!(
1092 guest_saved_mtime, host_saved_mtime,
1093 "guest {} saved mtime does not match host's for path {path:?} in project {project_id}",
1094 client.username
1095 );
1096
1097 let host_is_dirty = host_buffer.read_with(host_cx, |b, _| b.is_dirty());
1098 let guest_is_dirty = guest_buffer.read_with(client_cx, |b, _| b.is_dirty());
1099 assert_eq!(guest_is_dirty, host_is_dirty,
1100 "guest {} dirty status does not match host's for path {path:?} in project {project_id}",
1101 client.username
1102 );
1103
1104 let host_has_conflict = host_buffer.read_with(host_cx, |b, _| b.has_conflict());
1105 let guest_has_conflict = guest_buffer.read_with(client_cx, |b, _| b.has_conflict());
1106 assert_eq!(guest_has_conflict, host_has_conflict,
1107 "guest {} conflict status does not match host's for path {path:?} in project {project_id}",
1108 client.username
1109 );
1110 }
1111 }
1112 }
1113}
1114
1115struct TestPlan {
1116 rng: StdRng,
1117 replay: bool,
1118 stored_operations: Vec<(StoredOperation, Arc<AtomicBool>)>,
1119 max_operations: usize,
1120 operation_ix: usize,
1121 users: Vec<UserTestPlan>,
1122 next_batch_id: usize,
1123 allow_server_restarts: bool,
1124 allow_client_reconnection: bool,
1125 allow_client_disconnection: bool,
1126}
1127
1128struct UserTestPlan {
1129 user_id: UserId,
1130 username: String,
1131 next_root_id: usize,
1132 operation_ix: usize,
1133 online: bool,
1134}
1135
1136#[derive(Clone, Debug, Serialize, Deserialize)]
1137#[serde(untagged)]
1138enum StoredOperation {
1139 Server(Operation),
1140 Client {
1141 user_id: UserId,
1142 batch_id: usize,
1143 operation: ClientOperation,
1144 },
1145}
1146
1147#[derive(Clone, Debug, Serialize, Deserialize)]
1148enum Operation {
1149 AddConnection {
1150 user_id: UserId,
1151 },
1152 RemoveConnection {
1153 user_id: UserId,
1154 },
1155 BounceConnection {
1156 user_id: UserId,
1157 },
1158 RestartServer,
1159 MutateClients {
1160 batch_id: usize,
1161 #[serde(skip_serializing)]
1162 #[serde(skip_deserializing)]
1163 user_ids: Vec<UserId>,
1164 quiesce: bool,
1165 },
1166}
1167
1168#[derive(Clone, Debug, Serialize, Deserialize)]
1169enum ClientOperation {
1170 AcceptIncomingCall,
1171 RejectIncomingCall,
1172 LeaveCall,
1173 InviteContactToCall {
1174 user_id: UserId,
1175 },
1176 OpenLocalProject {
1177 first_root_name: String,
1178 },
1179 OpenRemoteProject {
1180 host_id: UserId,
1181 first_root_name: String,
1182 },
1183 AddWorktreeToProject {
1184 project_root_name: String,
1185 new_root_path: PathBuf,
1186 },
1187 CloseRemoteProject {
1188 project_root_name: String,
1189 },
1190 OpenBuffer {
1191 project_root_name: String,
1192 is_local: bool,
1193 full_path: PathBuf,
1194 },
1195 SearchProject {
1196 project_root_name: String,
1197 is_local: bool,
1198 query: String,
1199 detach: bool,
1200 },
1201 EditBuffer {
1202 project_root_name: String,
1203 is_local: bool,
1204 full_path: PathBuf,
1205 edits: Vec<(Range<usize>, Arc<str>)>,
1206 },
1207 CloseBuffer {
1208 project_root_name: String,
1209 is_local: bool,
1210 full_path: PathBuf,
1211 },
1212 SaveBuffer {
1213 project_root_name: String,
1214 is_local: bool,
1215 full_path: PathBuf,
1216 detach: bool,
1217 },
1218 RequestLspDataInBuffer {
1219 project_root_name: String,
1220 is_local: bool,
1221 full_path: PathBuf,
1222 offset: usize,
1223 kind: LspRequestKind,
1224 detach: bool,
1225 },
1226 CreateWorktreeEntry {
1227 project_root_name: String,
1228 is_local: bool,
1229 full_path: PathBuf,
1230 is_dir: bool,
1231 },
1232 WriteFsEntry {
1233 path: PathBuf,
1234 is_dir: bool,
1235 content: String,
1236 },
1237 GitOperation {
1238 operation: GitOperation,
1239 },
1240}
1241
1242#[derive(Clone, Debug, Serialize, Deserialize)]
1243enum GitOperation {
1244 WriteGitIndex {
1245 repo_path: PathBuf,
1246 contents: Vec<(PathBuf, String)>,
1247 },
1248 WriteGitBranch {
1249 repo_path: PathBuf,
1250 new_branch: Option<String>,
1251 },
1252 WriteGitStatuses {
1253 repo_path: PathBuf,
1254 statuses: Vec<(PathBuf, GitFileStatus)>,
1255 git_operation: bool,
1256 },
1257}
1258
1259#[derive(Clone, Debug, Serialize, Deserialize)]
1260enum LspRequestKind {
1261 Rename,
1262 Completion,
1263 CodeAction,
1264 Definition,
1265 Highlights,
1266}
1267
1268enum TestError {
1269 Inapplicable,
1270 Other(anyhow::Error),
1271}
1272
1273impl From<anyhow::Error> for TestError {
1274 fn from(value: anyhow::Error) -> Self {
1275 Self::Other(value)
1276 }
1277}
1278
1279impl TestPlan {
1280 fn new(mut rng: StdRng, users: Vec<UserTestPlan>, max_operations: usize) -> Self {
1281 Self {
1282 replay: false,
1283 allow_server_restarts: rng.gen_bool(0.7),
1284 allow_client_reconnection: rng.gen_bool(0.7),
1285 allow_client_disconnection: rng.gen_bool(0.1),
1286 stored_operations: Vec::new(),
1287 operation_ix: 0,
1288 next_batch_id: 0,
1289 max_operations,
1290 users,
1291 rng,
1292 }
1293 }
1294
1295 fn deserialize(&mut self, json: Vec<u8>) {
1296 let stored_operations: Vec<StoredOperation> = serde_json::from_slice(&json).unwrap();
1297 self.replay = true;
1298 self.stored_operations = stored_operations
1299 .iter()
1300 .cloned()
1301 .enumerate()
1302 .map(|(i, mut operation)| {
1303 if let StoredOperation::Server(Operation::MutateClients {
1304 batch_id: current_batch_id,
1305 user_ids,
1306 ..
1307 }) = &mut operation
1308 {
1309 assert!(user_ids.is_empty());
1310 user_ids.extend(stored_operations[i + 1..].iter().filter_map(|operation| {
1311 if let StoredOperation::Client {
1312 user_id, batch_id, ..
1313 } = operation
1314 {
1315 if batch_id == current_batch_id {
1316 return Some(user_id);
1317 }
1318 }
1319 None
1320 }));
1321 user_ids.sort_unstable();
1322 }
1323 (operation, Arc::new(AtomicBool::new(false)))
1324 })
1325 .collect()
1326 }
1327
1328 fn serialize(&mut self) -> Vec<u8> {
1329 // Format each operation as one line
1330 let mut json = Vec::new();
1331 json.push(b'[');
1332 for (operation, applied) in &self.stored_operations {
1333 if !applied.load(SeqCst) {
1334 continue;
1335 }
1336 if json.len() > 1 {
1337 json.push(b',');
1338 }
1339 json.extend_from_slice(b"\n ");
1340 serde_json::to_writer(&mut json, operation).unwrap();
1341 }
1342 json.extend_from_slice(b"\n]\n");
1343 json
1344 }
1345
1346 fn next_server_operation(
1347 &mut self,
1348 clients: &[(Rc<TestClient>, TestAppContext)],
1349 ) -> Option<(Operation, Arc<AtomicBool>)> {
1350 if self.replay {
1351 while let Some(stored_operation) = self.stored_operations.get(self.operation_ix) {
1352 self.operation_ix += 1;
1353 if let (StoredOperation::Server(operation), applied) = stored_operation {
1354 return Some((operation.clone(), applied.clone()));
1355 }
1356 }
1357 None
1358 } else {
1359 let operation = self.generate_server_operation(clients)?;
1360 let applied = Arc::new(AtomicBool::new(false));
1361 self.stored_operations
1362 .push((StoredOperation::Server(operation.clone()), applied.clone()));
1363 Some((operation, applied))
1364 }
1365 }
1366
1367 fn next_client_operation(
1368 &mut self,
1369 client: &TestClient,
1370 current_batch_id: usize,
1371 cx: &TestAppContext,
1372 ) -> Option<(ClientOperation, Arc<AtomicBool>)> {
1373 let current_user_id = client.current_user_id(cx);
1374 let user_ix = self
1375 .users
1376 .iter()
1377 .position(|user| user.user_id == current_user_id)
1378 .unwrap();
1379 let user_plan = &mut self.users[user_ix];
1380
1381 if self.replay {
1382 while let Some(stored_operation) = self.stored_operations.get(user_plan.operation_ix) {
1383 user_plan.operation_ix += 1;
1384 if let (
1385 StoredOperation::Client {
1386 user_id, operation, ..
1387 },
1388 applied,
1389 ) = stored_operation
1390 {
1391 if user_id == ¤t_user_id {
1392 return Some((operation.clone(), applied.clone()));
1393 }
1394 }
1395 }
1396 None
1397 } else {
1398 let operation = self.generate_client_operation(current_user_id, client, cx)?;
1399 let applied = Arc::new(AtomicBool::new(false));
1400 self.stored_operations.push((
1401 StoredOperation::Client {
1402 user_id: current_user_id,
1403 batch_id: current_batch_id,
1404 operation: operation.clone(),
1405 },
1406 applied.clone(),
1407 ));
1408 Some((operation, applied))
1409 }
1410 }
1411
1412 fn generate_server_operation(
1413 &mut self,
1414 clients: &[(Rc<TestClient>, TestAppContext)],
1415 ) -> Option<Operation> {
1416 if self.operation_ix == self.max_operations {
1417 return None;
1418 }
1419
1420 Some(loop {
1421 break match self.rng.gen_range(0..100) {
1422 0..=29 if clients.len() < self.users.len() => {
1423 let user = self
1424 .users
1425 .iter()
1426 .filter(|u| !u.online)
1427 .choose(&mut self.rng)
1428 .unwrap();
1429 self.operation_ix += 1;
1430 Operation::AddConnection {
1431 user_id: user.user_id,
1432 }
1433 }
1434 30..=34 if clients.len() > 1 && self.allow_client_disconnection => {
1435 let (client, cx) = &clients[self.rng.gen_range(0..clients.len())];
1436 let user_id = client.current_user_id(cx);
1437 self.operation_ix += 1;
1438 Operation::RemoveConnection { user_id }
1439 }
1440 35..=39 if clients.len() > 1 && self.allow_client_reconnection => {
1441 let (client, cx) = &clients[self.rng.gen_range(0..clients.len())];
1442 let user_id = client.current_user_id(cx);
1443 self.operation_ix += 1;
1444 Operation::BounceConnection { user_id }
1445 }
1446 40..=44 if self.allow_server_restarts && clients.len() > 1 => {
1447 self.operation_ix += 1;
1448 Operation::RestartServer
1449 }
1450 _ if !clients.is_empty() => {
1451 let count = self
1452 .rng
1453 .gen_range(1..10)
1454 .min(self.max_operations - self.operation_ix);
1455 let batch_id = util::post_inc(&mut self.next_batch_id);
1456 let mut user_ids = (0..count)
1457 .map(|_| {
1458 let ix = self.rng.gen_range(0..clients.len());
1459 let (client, cx) = &clients[ix];
1460 client.current_user_id(cx)
1461 })
1462 .collect::<Vec<_>>();
1463 user_ids.sort_unstable();
1464 Operation::MutateClients {
1465 user_ids,
1466 batch_id,
1467 quiesce: self.rng.gen_bool(0.7),
1468 }
1469 }
1470 _ => continue,
1471 };
1472 })
1473 }
1474
1475 fn generate_client_operation(
1476 &mut self,
1477 user_id: UserId,
1478 client: &TestClient,
1479 cx: &TestAppContext,
1480 ) -> Option<ClientOperation> {
1481 if self.operation_ix == self.max_operations {
1482 return None;
1483 }
1484
1485 self.operation_ix += 1;
1486 let call = cx.read(ActiveCall::global);
1487 Some(loop {
1488 match self.rng.gen_range(0..100_u32) {
1489 // Mutate the call
1490 0..=29 => {
1491 // Respond to an incoming call
1492 if call.read_with(cx, |call, _| call.incoming().borrow().is_some()) {
1493 break if self.rng.gen_bool(0.7) {
1494 ClientOperation::AcceptIncomingCall
1495 } else {
1496 ClientOperation::RejectIncomingCall
1497 };
1498 }
1499
1500 match self.rng.gen_range(0..100_u32) {
1501 // Invite a contact to the current call
1502 0..=70 => {
1503 let available_contacts =
1504 client.user_store().read_with(cx, |user_store, _| {
1505 user_store
1506 .contacts()
1507 .iter()
1508 .filter(|contact| contact.online && !contact.busy)
1509 .cloned()
1510 .collect::<Vec<_>>()
1511 });
1512 if !available_contacts.is_empty() {
1513 let contact = available_contacts.choose(&mut self.rng).unwrap();
1514 break ClientOperation::InviteContactToCall {
1515 user_id: UserId(contact.user.id as i32),
1516 };
1517 }
1518 }
1519
1520 // Leave the current call
1521 71.. => {
1522 if self.allow_client_disconnection
1523 && call.read_with(cx, |call, _| call.room().is_some())
1524 {
1525 break ClientOperation::LeaveCall;
1526 }
1527 }
1528 }
1529 }
1530
1531 // Mutate projects
1532 30..=59 => match self.rng.gen_range(0..100_u32) {
1533 // Open a new project
1534 0..=70 => {
1535 // Open a remote project
1536 if let Some(room) = call.read_with(cx, |call, _| call.room().cloned()) {
1537 let existing_remote_project_ids = cx.read(|cx| {
1538 client
1539 .remote_projects()
1540 .iter()
1541 .map(|p| p.read(cx).remote_id().unwrap())
1542 .collect::<Vec<_>>()
1543 });
1544 let new_remote_projects = room.read_with(cx, |room, _| {
1545 room.remote_participants()
1546 .values()
1547 .flat_map(|participant| {
1548 participant.projects.iter().filter_map(|project| {
1549 if existing_remote_project_ids.contains(&project.id) {
1550 None
1551 } else {
1552 Some((
1553 UserId::from_proto(participant.user.id),
1554 project.worktree_root_names[0].clone(),
1555 ))
1556 }
1557 })
1558 })
1559 .collect::<Vec<_>>()
1560 });
1561 if !new_remote_projects.is_empty() {
1562 let (host_id, first_root_name) =
1563 new_remote_projects.choose(&mut self.rng).unwrap().clone();
1564 break ClientOperation::OpenRemoteProject {
1565 host_id,
1566 first_root_name,
1567 };
1568 }
1569 }
1570 // Open a local project
1571 else {
1572 let first_root_name = self.next_root_dir_name(user_id);
1573 break ClientOperation::OpenLocalProject { first_root_name };
1574 }
1575 }
1576
1577 // Close a remote project
1578 71..=80 => {
1579 if !client.remote_projects().is_empty() {
1580 let project = client
1581 .remote_projects()
1582 .choose(&mut self.rng)
1583 .unwrap()
1584 .clone();
1585 let first_root_name = root_name_for_project(&project, cx);
1586 break ClientOperation::CloseRemoteProject {
1587 project_root_name: first_root_name,
1588 };
1589 }
1590 }
1591
1592 // Mutate project worktrees
1593 81.. => match self.rng.gen_range(0..100_u32) {
1594 // Add a worktree to a local project
1595 0..=50 => {
1596 let Some(project) =
1597 client.local_projects().choose(&mut self.rng).cloned()
1598 else {
1599 continue;
1600 };
1601 let project_root_name = root_name_for_project(&project, cx);
1602 let mut paths = client.fs().paths(false);
1603 paths.remove(0);
1604 let new_root_path = if paths.is_empty() || self.rng.gen() {
1605 Path::new("/").join(&self.next_root_dir_name(user_id))
1606 } else {
1607 paths.choose(&mut self.rng).unwrap().clone()
1608 };
1609 break ClientOperation::AddWorktreeToProject {
1610 project_root_name,
1611 new_root_path,
1612 };
1613 }
1614
1615 // Add an entry to a worktree
1616 _ => {
1617 let Some(project) = choose_random_project(client, &mut self.rng) else {
1618 continue;
1619 };
1620 let project_root_name = root_name_for_project(&project, cx);
1621 let is_local = project.read_with(cx, |project, _| project.is_local());
1622 let worktree = project.read_with(cx, |project, cx| {
1623 project
1624 .worktrees(cx)
1625 .filter(|worktree| {
1626 let worktree = worktree.read(cx);
1627 worktree.is_visible()
1628 && worktree.entries(false).any(|e| e.is_file())
1629 && worktree.root_entry().map_or(false, |e| e.is_dir())
1630 })
1631 .choose(&mut self.rng)
1632 });
1633 let Some(worktree) = worktree else { continue };
1634 let is_dir = self.rng.gen::<bool>();
1635 let mut full_path =
1636 worktree.read_with(cx, |w, _| PathBuf::from(w.root_name()));
1637 full_path.push(gen_file_name(&mut self.rng));
1638 if !is_dir {
1639 full_path.set_extension("rs");
1640 }
1641 break ClientOperation::CreateWorktreeEntry {
1642 project_root_name,
1643 is_local,
1644 full_path,
1645 is_dir,
1646 };
1647 }
1648 },
1649 },
1650
1651 // Query and mutate buffers
1652 60..=90 => {
1653 let Some(project) = choose_random_project(client, &mut self.rng) else {
1654 continue;
1655 };
1656 let project_root_name = root_name_for_project(&project, cx);
1657 let is_local = project.read_with(cx, |project, _| project.is_local());
1658
1659 match self.rng.gen_range(0..100_u32) {
1660 // Manipulate an existing buffer
1661 0..=70 => {
1662 let Some(buffer) = client
1663 .buffers_for_project(&project)
1664 .iter()
1665 .choose(&mut self.rng)
1666 .cloned()
1667 else {
1668 continue;
1669 };
1670
1671 let full_path = buffer
1672 .read_with(cx, |buffer, cx| buffer.file().unwrap().full_path(cx));
1673
1674 match self.rng.gen_range(0..100_u32) {
1675 // Close the buffer
1676 0..=15 => {
1677 break ClientOperation::CloseBuffer {
1678 project_root_name,
1679 is_local,
1680 full_path,
1681 };
1682 }
1683 // Save the buffer
1684 16..=29 if buffer.read_with(cx, |b, _| b.is_dirty()) => {
1685 let detach = self.rng.gen_bool(0.3);
1686 break ClientOperation::SaveBuffer {
1687 project_root_name,
1688 is_local,
1689 full_path,
1690 detach,
1691 };
1692 }
1693 // Edit the buffer
1694 30..=69 => {
1695 let edits = buffer.read_with(cx, |buffer, _| {
1696 buffer.get_random_edits(&mut self.rng, 3)
1697 });
1698 break ClientOperation::EditBuffer {
1699 project_root_name,
1700 is_local,
1701 full_path,
1702 edits,
1703 };
1704 }
1705 // Make an LSP request
1706 _ => {
1707 let offset = buffer.read_with(cx, |buffer, _| {
1708 buffer.clip_offset(
1709 self.rng.gen_range(0..=buffer.len()),
1710 language::Bias::Left,
1711 )
1712 });
1713 let detach = self.rng.gen();
1714 break ClientOperation::RequestLspDataInBuffer {
1715 project_root_name,
1716 full_path,
1717 offset,
1718 is_local,
1719 kind: match self.rng.gen_range(0..5_u32) {
1720 0 => LspRequestKind::Rename,
1721 1 => LspRequestKind::Highlights,
1722 2 => LspRequestKind::Definition,
1723 3 => LspRequestKind::CodeAction,
1724 4.. => LspRequestKind::Completion,
1725 },
1726 detach,
1727 };
1728 }
1729 }
1730 }
1731
1732 71..=80 => {
1733 let query = self.rng.gen_range('a'..='z').to_string();
1734 let detach = self.rng.gen_bool(0.3);
1735 break ClientOperation::SearchProject {
1736 project_root_name,
1737 is_local,
1738 query,
1739 detach,
1740 };
1741 }
1742
1743 // Open a buffer
1744 81.. => {
1745 let worktree = project.read_with(cx, |project, cx| {
1746 project
1747 .worktrees(cx)
1748 .filter(|worktree| {
1749 let worktree = worktree.read(cx);
1750 worktree.is_visible()
1751 && worktree.entries(false).any(|e| e.is_file())
1752 })
1753 .choose(&mut self.rng)
1754 });
1755 let Some(worktree) = worktree else { continue };
1756 let full_path = worktree.read_with(cx, |worktree, _| {
1757 let entry = worktree
1758 .entries(false)
1759 .filter(|e| e.is_file())
1760 .choose(&mut self.rng)
1761 .unwrap();
1762 if entry.path.as_ref() == Path::new("") {
1763 Path::new(worktree.root_name()).into()
1764 } else {
1765 Path::new(worktree.root_name()).join(&entry.path)
1766 }
1767 });
1768 break ClientOperation::OpenBuffer {
1769 project_root_name,
1770 is_local,
1771 full_path,
1772 };
1773 }
1774 }
1775 }
1776
1777 // Update a git related action
1778 91..=95 => {
1779 break ClientOperation::GitOperation {
1780 operation: self.generate_git_operation(client),
1781 };
1782 }
1783
1784 // Create or update a file or directory
1785 96.. => {
1786 let is_dir = self.rng.gen::<bool>();
1787 let content;
1788 let mut path;
1789 let dir_paths = client.fs().directories(false);
1790
1791 if is_dir {
1792 content = String::new();
1793 path = dir_paths.choose(&mut self.rng).unwrap().clone();
1794 path.push(gen_file_name(&mut self.rng));
1795 } else {
1796 content = Alphanumeric.sample_string(&mut self.rng, 16);
1797
1798 // Create a new file or overwrite an existing file
1799 let file_paths = client.fs().files();
1800 if file_paths.is_empty() || self.rng.gen_bool(0.5) {
1801 path = dir_paths.choose(&mut self.rng).unwrap().clone();
1802 path.push(gen_file_name(&mut self.rng));
1803 path.set_extension("rs");
1804 } else {
1805 path = file_paths.choose(&mut self.rng).unwrap().clone()
1806 };
1807 }
1808 break ClientOperation::WriteFsEntry {
1809 path,
1810 is_dir,
1811 content,
1812 };
1813 }
1814 }
1815 })
1816 }
1817
1818 fn generate_git_operation(&mut self, client: &TestClient) -> GitOperation {
1819 fn generate_file_paths(
1820 repo_path: &Path,
1821 rng: &mut StdRng,
1822 client: &TestClient,
1823 ) -> Vec<PathBuf> {
1824 let mut paths = client
1825 .fs()
1826 .files()
1827 .into_iter()
1828 .filter(|path| path.starts_with(repo_path))
1829 .collect::<Vec<_>>();
1830
1831 let count = rng.gen_range(0..=paths.len());
1832 paths.shuffle(rng);
1833 paths.truncate(count);
1834
1835 paths
1836 .iter()
1837 .map(|path| path.strip_prefix(repo_path).unwrap().to_path_buf())
1838 .collect::<Vec<_>>()
1839 }
1840
1841 let repo_path = client
1842 .fs()
1843 .directories(false)
1844 .choose(&mut self.rng)
1845 .unwrap()
1846 .clone();
1847
1848 match self.rng.gen_range(0..100_u32) {
1849 0..=25 => {
1850 let file_paths = generate_file_paths(&repo_path, &mut self.rng, client);
1851
1852 let contents = file_paths
1853 .into_iter()
1854 .map(|path| (path, Alphanumeric.sample_string(&mut self.rng, 16)))
1855 .collect();
1856
1857 GitOperation::WriteGitIndex {
1858 repo_path,
1859 contents,
1860 }
1861 }
1862 26..=63 => {
1863 let new_branch = (self.rng.gen_range(0..10) > 3)
1864 .then(|| Alphanumeric.sample_string(&mut self.rng, 8));
1865
1866 GitOperation::WriteGitBranch {
1867 repo_path,
1868 new_branch,
1869 }
1870 }
1871 64..=100 => {
1872 let file_paths = generate_file_paths(&repo_path, &mut self.rng, client);
1873
1874 let statuses = file_paths
1875 .into_iter()
1876 .map(|paths| {
1877 (
1878 paths,
1879 match self.rng.gen_range(0..3_u32) {
1880 0 => GitFileStatus::Added,
1881 1 => GitFileStatus::Modified,
1882 2 => GitFileStatus::Conflict,
1883 _ => unreachable!(),
1884 },
1885 )
1886 })
1887 .collect::<Vec<_>>();
1888
1889 let git_operation = self.rng.gen::<bool>();
1890
1891 GitOperation::WriteGitStatuses {
1892 repo_path,
1893 statuses,
1894 git_operation,
1895 }
1896 }
1897 _ => unreachable!(),
1898 }
1899 }
1900
1901 fn next_root_dir_name(&mut self, user_id: UserId) -> String {
1902 let user_ix = self
1903 .users
1904 .iter()
1905 .position(|user| user.user_id == user_id)
1906 .unwrap();
1907 let root_id = util::post_inc(&mut self.users[user_ix].next_root_id);
1908 format!("dir-{user_id}-{root_id}")
1909 }
1910
1911 fn user(&mut self, user_id: UserId) -> &mut UserTestPlan {
1912 let ix = self
1913 .users
1914 .iter()
1915 .position(|user| user.user_id == user_id)
1916 .unwrap();
1917 &mut self.users[ix]
1918 }
1919}
1920
1921async fn simulate_client(
1922 client: Rc<TestClient>,
1923 mut operation_rx: futures::channel::mpsc::UnboundedReceiver<usize>,
1924 plan: Arc<Mutex<TestPlan>>,
1925 mut cx: TestAppContext,
1926) {
1927 // Setup language server
1928 let mut language = Language::new(
1929 LanguageConfig {
1930 name: "Rust".into(),
1931 path_suffixes: vec!["rs".to_string()],
1932 ..Default::default()
1933 },
1934 None,
1935 );
1936 let _fake_language_servers = language
1937 .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
1938 name: "the-fake-language-server",
1939 capabilities: lsp::LanguageServer::full_capabilities(),
1940 initializer: Some(Box::new({
1941 let fs = client.app_state.fs.clone();
1942 move |fake_server: &mut FakeLanguageServer| {
1943 fake_server.handle_request::<lsp::request::Completion, _, _>(
1944 |_, _| async move {
1945 Ok(Some(lsp::CompletionResponse::Array(vec![
1946 lsp::CompletionItem {
1947 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1948 range: lsp::Range::new(
1949 lsp::Position::new(0, 0),
1950 lsp::Position::new(0, 0),
1951 ),
1952 new_text: "the-new-text".to_string(),
1953 })),
1954 ..Default::default()
1955 },
1956 ])))
1957 },
1958 );
1959
1960 fake_server.handle_request::<lsp::request::CodeActionRequest, _, _>(
1961 |_, _| async move {
1962 Ok(Some(vec![lsp::CodeActionOrCommand::CodeAction(
1963 lsp::CodeAction {
1964 title: "the-code-action".to_string(),
1965 ..Default::default()
1966 },
1967 )]))
1968 },
1969 );
1970
1971 fake_server.handle_request::<lsp::request::PrepareRenameRequest, _, _>(
1972 |params, _| async move {
1973 Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
1974 params.position,
1975 params.position,
1976 ))))
1977 },
1978 );
1979
1980 fake_server.handle_request::<lsp::request::GotoDefinition, _, _>({
1981 let fs = fs.clone();
1982 move |_, cx| {
1983 let background = cx.background();
1984 let mut rng = background.rng();
1985 let count = rng.gen_range::<usize, _>(1..3);
1986 let files = fs.as_fake().files();
1987 let files = (0..count)
1988 .map(|_| files.choose(&mut *rng).unwrap().clone())
1989 .collect::<Vec<_>>();
1990 async move {
1991 log::info!("LSP: Returning definitions in files {:?}", &files);
1992 Ok(Some(lsp::GotoDefinitionResponse::Array(
1993 files
1994 .into_iter()
1995 .map(|file| lsp::Location {
1996 uri: lsp::Url::from_file_path(file).unwrap(),
1997 range: Default::default(),
1998 })
1999 .collect(),
2000 )))
2001 }
2002 }
2003 });
2004
2005 fake_server.handle_request::<lsp::request::DocumentHighlightRequest, _, _>(
2006 move |_, cx| {
2007 let mut highlights = Vec::new();
2008 let background = cx.background();
2009 let mut rng = background.rng();
2010
2011 let highlight_count = rng.gen_range(1..=5);
2012 for _ in 0..highlight_count {
2013 let start_row = rng.gen_range(0..100);
2014 let start_column = rng.gen_range(0..100);
2015 let end_row = rng.gen_range(0..100);
2016 let end_column = rng.gen_range(0..100);
2017 let start = PointUtf16::new(start_row, start_column);
2018 let end = PointUtf16::new(end_row, end_column);
2019 let range = if start > end { end..start } else { start..end };
2020 highlights.push(lsp::DocumentHighlight {
2021 range: range_to_lsp(range.clone()),
2022 kind: Some(lsp::DocumentHighlightKind::READ),
2023 });
2024 }
2025 highlights.sort_unstable_by_key(|highlight| {
2026 (highlight.range.start, highlight.range.end)
2027 });
2028 async move { Ok(Some(highlights)) }
2029 },
2030 );
2031 }
2032 })),
2033 ..Default::default()
2034 }))
2035 .await;
2036 client.app_state.languages.add(Arc::new(language));
2037
2038 while let Some(batch_id) = operation_rx.next().await {
2039 let Some((operation, applied)) = plan.lock().next_client_operation(&client, batch_id, &cx)
2040 else {
2041 break;
2042 };
2043 applied.store(true, SeqCst);
2044 match apply_client_operation(&client, operation, &mut cx).await {
2045 Ok(()) => {}
2046 Err(TestError::Inapplicable) => {
2047 applied.store(false, SeqCst);
2048 log::info!("skipped operation");
2049 }
2050 Err(TestError::Other(error)) => {
2051 log::error!("{} error: {}", client.username, error);
2052 }
2053 }
2054 cx.background().simulate_random_delay().await;
2055 }
2056 log::info!("{}: done", client.username);
2057}
2058
2059fn buffer_for_full_path(
2060 client: &TestClient,
2061 project: &ModelHandle<Project>,
2062 full_path: &PathBuf,
2063 cx: &TestAppContext,
2064) -> Option<ModelHandle<language::Buffer>> {
2065 client
2066 .buffers_for_project(project)
2067 .iter()
2068 .find(|buffer| {
2069 buffer.read_with(cx, |buffer, cx| {
2070 buffer.file().unwrap().full_path(cx) == *full_path
2071 })
2072 })
2073 .cloned()
2074}
2075
2076fn project_for_root_name(
2077 client: &TestClient,
2078 root_name: &str,
2079 cx: &TestAppContext,
2080) -> Option<ModelHandle<Project>> {
2081 if let Some(ix) = project_ix_for_root_name(&*client.local_projects(), root_name, cx) {
2082 return Some(client.local_projects()[ix].clone());
2083 }
2084 if let Some(ix) = project_ix_for_root_name(&*client.remote_projects(), root_name, cx) {
2085 return Some(client.remote_projects()[ix].clone());
2086 }
2087 None
2088}
2089
2090fn project_ix_for_root_name(
2091 projects: &[ModelHandle<Project>],
2092 root_name: &str,
2093 cx: &TestAppContext,
2094) -> Option<usize> {
2095 projects.iter().position(|project| {
2096 project.read_with(cx, |project, cx| {
2097 let worktree = project.visible_worktrees(cx).next().unwrap();
2098 worktree.read(cx).root_name() == root_name
2099 })
2100 })
2101}
2102
2103fn root_name_for_project(project: &ModelHandle<Project>, cx: &TestAppContext) -> String {
2104 project.read_with(cx, |project, cx| {
2105 project
2106 .visible_worktrees(cx)
2107 .next()
2108 .unwrap()
2109 .read(cx)
2110 .root_name()
2111 .to_string()
2112 })
2113}
2114
2115fn project_path_for_full_path(
2116 project: &ModelHandle<Project>,
2117 full_path: &Path,
2118 cx: &TestAppContext,
2119) -> Option<ProjectPath> {
2120 let mut components = full_path.components();
2121 let root_name = components.next().unwrap().as_os_str().to_str().unwrap();
2122 let path = components.as_path().into();
2123 let worktree_id = project.read_with(cx, |project, cx| {
2124 project.worktrees(cx).find_map(|worktree| {
2125 let worktree = worktree.read(cx);
2126 if worktree.root_name() == root_name {
2127 Some(worktree.id())
2128 } else {
2129 None
2130 }
2131 })
2132 })?;
2133 Some(ProjectPath { worktree_id, path })
2134}
2135
2136async fn ensure_project_shared(
2137 project: &ModelHandle<Project>,
2138 client: &TestClient,
2139 cx: &mut TestAppContext,
2140) {
2141 let first_root_name = root_name_for_project(project, cx);
2142 let active_call = cx.read(ActiveCall::global);
2143 if active_call.read_with(cx, |call, _| call.room().is_some())
2144 && project.read_with(cx, |project, _| project.is_local() && !project.is_shared())
2145 {
2146 match active_call
2147 .update(cx, |call, cx| call.share_project(project.clone(), cx))
2148 .await
2149 {
2150 Ok(project_id) => {
2151 log::info!(
2152 "{}: shared project {} with id {}",
2153 client.username,
2154 first_root_name,
2155 project_id
2156 );
2157 }
2158 Err(error) => {
2159 log::error!(
2160 "{}: error sharing project {}: {:?}",
2161 client.username,
2162 first_root_name,
2163 error
2164 );
2165 }
2166 }
2167 }
2168}
2169
2170fn choose_random_project(client: &TestClient, rng: &mut StdRng) -> Option<ModelHandle<Project>> {
2171 client
2172 .local_projects()
2173 .iter()
2174 .chain(client.remote_projects().iter())
2175 .choose(rng)
2176 .cloned()
2177}
2178
2179fn gen_file_name(rng: &mut StdRng) -> String {
2180 let mut name = String::new();
2181 for _ in 0..10 {
2182 let letter = rng.gen_range('a'..='z');
2183 name.push(letter);
2184 }
2185 name
2186}
2187
2188fn path_env_var(name: &str) -> Option<PathBuf> {
2189 let value = env::var(name).ok()?;
2190 let mut path = PathBuf::from(value);
2191 if path.is_relative() {
2192 let mut abs_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
2193 abs_path.pop();
2194 abs_path.pop();
2195 abs_path.push(path);
2196 path = abs_path
2197 }
2198 Some(path)
2199}