1use crate::{
2 db::{NewUserParams, TestDb, UserId},
3 executor::Executor,
4 rpc::{Server, CLEANUP_TIMEOUT},
5 AppState,
6};
7use anyhow::anyhow;
8use call::ActiveCall;
9use client::{
10 self, proto::PeerId, Client, Connection, Credentials, EstablishConnectionError, UserStore,
11};
12use collections::{HashMap, HashSet};
13use fs::FakeFs;
14use futures::{channel::oneshot, StreamExt as _};
15use gpui::{
16 elements::*, executor::Deterministic, AnyElement, Entity, ModelHandle, TestAppContext, View,
17 ViewContext, ViewHandle, WeakViewHandle,
18};
19use language::LanguageRegistry;
20use parking_lot::Mutex;
21use project::{Project, WorktreeId};
22use settings::SettingsStore;
23use std::{
24 cell::{Ref, RefCell, RefMut},
25 env,
26 ops::{Deref, DerefMut},
27 path::Path,
28 sync::{
29 atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
30 Arc,
31 },
32};
33use util::http::FakeHttpClient;
34use workspace::Workspace;
35
36mod integration_tests;
37mod randomized_integration_tests;
38
39struct TestServer {
40 app_state: Arc<AppState>,
41 server: Arc<Server>,
42 connection_killers: Arc<Mutex<HashMap<PeerId, Arc<AtomicBool>>>>,
43 forbid_connections: Arc<AtomicBool>,
44 _test_db: TestDb,
45 test_live_kit_server: Arc<live_kit_client::TestServer>,
46}
47
48impl TestServer {
49 async fn start(deterministic: &Arc<Deterministic>) -> Self {
50 static NEXT_LIVE_KIT_SERVER_ID: AtomicUsize = AtomicUsize::new(0);
51
52 let use_postgres = env::var("USE_POSTGRES").ok();
53 let use_postgres = use_postgres.as_deref();
54 let test_db = if use_postgres == Some("true") || use_postgres == Some("1") {
55 TestDb::postgres(deterministic.build_background())
56 } else {
57 TestDb::sqlite(deterministic.build_background())
58 };
59 let live_kit_server_id = NEXT_LIVE_KIT_SERVER_ID.fetch_add(1, SeqCst);
60 let live_kit_server = live_kit_client::TestServer::create(
61 format!("http://livekit.{}.test", live_kit_server_id),
62 format!("devkey-{}", live_kit_server_id),
63 format!("secret-{}", live_kit_server_id),
64 deterministic.build_background(),
65 )
66 .unwrap();
67 let app_state = Self::build_app_state(&test_db, &live_kit_server).await;
68 let epoch = app_state
69 .db
70 .create_server(&app_state.config.zed_environment)
71 .await
72 .unwrap();
73 let server = Server::new(
74 epoch,
75 app_state.clone(),
76 Executor::Deterministic(deterministic.build_background()),
77 );
78 server.start().await.unwrap();
79 // Advance clock to ensure the server's cleanup task is finished.
80 deterministic.advance_clock(CLEANUP_TIMEOUT);
81 Self {
82 app_state,
83 server,
84 connection_killers: Default::default(),
85 forbid_connections: Default::default(),
86 _test_db: test_db,
87 test_live_kit_server: live_kit_server,
88 }
89 }
90
91 async fn reset(&self) {
92 self.app_state.db.reset();
93 let epoch = self
94 .app_state
95 .db
96 .create_server(&self.app_state.config.zed_environment)
97 .await
98 .unwrap();
99 self.server.reset(epoch);
100 }
101
102 async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
103 cx.update(|cx| {
104 cx.set_global(SettingsStore::test(cx));
105 });
106
107 let http = FakeHttpClient::with_404_response();
108 let user_id = if let Ok(Some(user)) = self.app_state.db.get_user_by_github_login(name).await
109 {
110 user.id
111 } else {
112 self.app_state
113 .db
114 .create_user(
115 &format!("{name}@example.com"),
116 false,
117 NewUserParams {
118 github_login: name.into(),
119 github_user_id: 0,
120 invite_count: 0,
121 },
122 )
123 .await
124 .expect("creating user failed")
125 .user_id
126 };
127 let client_name = name.to_string();
128 let mut client = cx.read(|cx| Client::new(http.clone(), cx));
129 let server = self.server.clone();
130 let db = self.app_state.db.clone();
131 let connection_killers = self.connection_killers.clone();
132 let forbid_connections = self.forbid_connections.clone();
133
134 Arc::get_mut(&mut client)
135 .unwrap()
136 .set_id(user_id.0 as usize)
137 .override_authenticate(move |cx| {
138 cx.spawn(|_| async move {
139 let access_token = "the-token".to_string();
140 Ok(Credentials {
141 user_id: user_id.0 as u64,
142 access_token,
143 })
144 })
145 })
146 .override_establish_connection(move |credentials, cx| {
147 assert_eq!(credentials.user_id, user_id.0 as u64);
148 assert_eq!(credentials.access_token, "the-token");
149
150 let server = server.clone();
151 let db = db.clone();
152 let connection_killers = connection_killers.clone();
153 let forbid_connections = forbid_connections.clone();
154 let client_name = client_name.clone();
155 cx.spawn(move |cx| async move {
156 if forbid_connections.load(SeqCst) {
157 Err(EstablishConnectionError::other(anyhow!(
158 "server is forbidding connections"
159 )))
160 } else {
161 let (client_conn, server_conn, killed) =
162 Connection::in_memory(cx.background());
163 let (connection_id_tx, connection_id_rx) = oneshot::channel();
164 let user = db
165 .get_user_by_id(user_id)
166 .await
167 .expect("retrieving user failed")
168 .unwrap();
169 cx.background()
170 .spawn(server.handle_connection(
171 server_conn,
172 client_name,
173 user,
174 Some(connection_id_tx),
175 Executor::Deterministic(cx.background()),
176 ))
177 .detach();
178 let connection_id = connection_id_rx.await.unwrap();
179 connection_killers
180 .lock()
181 .insert(connection_id.into(), killed);
182 Ok(client_conn)
183 }
184 })
185 });
186
187 let fs = FakeFs::new(cx.background());
188 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
189 let app_state = Arc::new(workspace::AppState {
190 client: client.clone(),
191 user_store: user_store.clone(),
192 languages: Arc::new(LanguageRegistry::test()),
193 fs: fs.clone(),
194 build_window_options: |_, _, _| Default::default(),
195 initialize_workspace: |_, _, _, _| unimplemented!(),
196 background_actions: || &[],
197 });
198
199 cx.update(|cx| {
200 theme::init((), cx);
201 Project::init(&client, cx);
202 client::init(&client, cx);
203 language::init(cx);
204 editor::init_settings(cx);
205 workspace::init(app_state.clone(), cx);
206 call::init(client.clone(), user_store.clone(), cx);
207 });
208
209 client
210 .authenticate_and_connect(false, &cx.to_async())
211 .await
212 .unwrap();
213
214 let client = TestClient {
215 client,
216 username: name.to_string(),
217 state: Default::default(),
218 user_store,
219 fs,
220 language_registry: Arc::new(LanguageRegistry::test()),
221 };
222 client.wait_for_current_user(cx).await;
223 client
224 }
225
226 fn disconnect_client(&self, peer_id: PeerId) {
227 self.connection_killers
228 .lock()
229 .remove(&peer_id)
230 .unwrap()
231 .store(true, SeqCst);
232 }
233
234 fn forbid_connections(&self) {
235 self.forbid_connections.store(true, SeqCst);
236 }
237
238 fn allow_connections(&self) {
239 self.forbid_connections.store(false, SeqCst);
240 }
241
242 async fn make_contacts(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
243 for ix in 1..clients.len() {
244 let (left, right) = clients.split_at_mut(ix);
245 let (client_a, cx_a) = left.last_mut().unwrap();
246 for (client_b, cx_b) in right {
247 client_a
248 .user_store
249 .update(*cx_a, |store, cx| {
250 store.request_contact(client_b.user_id().unwrap(), cx)
251 })
252 .await
253 .unwrap();
254 cx_a.foreground().run_until_parked();
255 client_b
256 .user_store
257 .update(*cx_b, |store, cx| {
258 store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
259 })
260 .await
261 .unwrap();
262 }
263 }
264 }
265
266 async fn create_room(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
267 self.make_contacts(clients).await;
268
269 let (left, right) = clients.split_at_mut(1);
270 let (_client_a, cx_a) = &mut left[0];
271 let active_call_a = cx_a.read(ActiveCall::global);
272
273 for (client_b, cx_b) in right {
274 let user_id_b = client_b.current_user_id(*cx_b).to_proto();
275 active_call_a
276 .update(*cx_a, |call, cx| call.invite(user_id_b, None, cx))
277 .await
278 .unwrap();
279
280 cx_b.foreground().run_until_parked();
281 let active_call_b = cx_b.read(ActiveCall::global);
282 active_call_b
283 .update(*cx_b, |call, cx| call.accept_incoming(cx))
284 .await
285 .unwrap();
286 }
287 }
288
289 async fn build_app_state(
290 test_db: &TestDb,
291 fake_server: &live_kit_client::TestServer,
292 ) -> Arc<AppState> {
293 Arc::new(AppState {
294 db: test_db.db().clone(),
295 live_kit_client: Some(Arc::new(fake_server.create_api_client())),
296 config: Default::default(),
297 })
298 }
299}
300
301impl Deref for TestServer {
302 type Target = Server;
303
304 fn deref(&self) -> &Self::Target {
305 &self.server
306 }
307}
308
309impl Drop for TestServer {
310 fn drop(&mut self) {
311 self.server.teardown();
312 self.test_live_kit_server.teardown().unwrap();
313 }
314}
315
316struct TestClient {
317 client: Arc<Client>,
318 username: String,
319 state: RefCell<TestClientState>,
320 pub user_store: ModelHandle<UserStore>,
321 language_registry: Arc<LanguageRegistry>,
322 fs: Arc<FakeFs>,
323}
324
325#[derive(Default)]
326struct TestClientState {
327 local_projects: Vec<ModelHandle<Project>>,
328 remote_projects: Vec<ModelHandle<Project>>,
329 buffers: HashMap<ModelHandle<Project>, HashSet<ModelHandle<language::Buffer>>>,
330}
331
332impl Deref for TestClient {
333 type Target = Arc<Client>;
334
335 fn deref(&self) -> &Self::Target {
336 &self.client
337 }
338}
339
340struct ContactsSummary {
341 pub current: Vec<String>,
342 pub outgoing_requests: Vec<String>,
343 pub incoming_requests: Vec<String>,
344}
345
346impl TestClient {
347 pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
348 UserId::from_proto(
349 self.user_store
350 .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
351 )
352 }
353
354 async fn wait_for_current_user(&self, cx: &TestAppContext) {
355 let mut authed_user = self
356 .user_store
357 .read_with(cx, |user_store, _| user_store.watch_current_user());
358 while authed_user.next().await.unwrap().is_none() {}
359 }
360
361 async fn clear_contacts(&self, cx: &mut TestAppContext) {
362 self.user_store
363 .update(cx, |store, _| store.clear_contacts())
364 .await;
365 }
366
367 fn local_projects<'a>(&'a self) -> impl Deref<Target = Vec<ModelHandle<Project>>> + 'a {
368 Ref::map(self.state.borrow(), |state| &state.local_projects)
369 }
370
371 fn remote_projects<'a>(&'a self) -> impl Deref<Target = Vec<ModelHandle<Project>>> + 'a {
372 Ref::map(self.state.borrow(), |state| &state.remote_projects)
373 }
374
375 fn local_projects_mut<'a>(&'a self) -> impl DerefMut<Target = Vec<ModelHandle<Project>>> + 'a {
376 RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
377 }
378
379 fn remote_projects_mut<'a>(&'a self) -> impl DerefMut<Target = Vec<ModelHandle<Project>>> + 'a {
380 RefMut::map(self.state.borrow_mut(), |state| &mut state.remote_projects)
381 }
382
383 fn buffers_for_project<'a>(
384 &'a self,
385 project: &ModelHandle<Project>,
386 ) -> impl DerefMut<Target = HashSet<ModelHandle<language::Buffer>>> + 'a {
387 RefMut::map(self.state.borrow_mut(), |state| {
388 state.buffers.entry(project.clone()).or_default()
389 })
390 }
391
392 fn buffers<'a>(
393 &'a self,
394 ) -> impl DerefMut<Target = HashMap<ModelHandle<Project>, HashSet<ModelHandle<language::Buffer>>>> + 'a
395 {
396 RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
397 }
398
399 fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
400 self.user_store.read_with(cx, |store, _| ContactsSummary {
401 current: store
402 .contacts()
403 .iter()
404 .map(|contact| contact.user.github_login.clone())
405 .collect(),
406 outgoing_requests: store
407 .outgoing_contact_requests()
408 .iter()
409 .map(|user| user.github_login.clone())
410 .collect(),
411 incoming_requests: store
412 .incoming_contact_requests()
413 .iter()
414 .map(|user| user.github_login.clone())
415 .collect(),
416 })
417 }
418
419 async fn build_local_project(
420 &self,
421 root_path: impl AsRef<Path>,
422 cx: &mut TestAppContext,
423 ) -> (ModelHandle<Project>, WorktreeId) {
424 let project = cx.update(|cx| {
425 Project::local(
426 self.client.clone(),
427 self.user_store.clone(),
428 self.language_registry.clone(),
429 self.fs.clone(),
430 cx,
431 )
432 });
433 let (worktree, _) = project
434 .update(cx, |p, cx| {
435 p.find_or_create_local_worktree(root_path, true, cx)
436 })
437 .await
438 .unwrap();
439 worktree
440 .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
441 .await;
442 (project, worktree.read_with(cx, |tree, _| tree.id()))
443 }
444
445 async fn build_remote_project(
446 &self,
447 host_project_id: u64,
448 guest_cx: &mut TestAppContext,
449 ) -> ModelHandle<Project> {
450 let active_call = guest_cx.read(ActiveCall::global);
451 let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
452 room.update(guest_cx, |room, cx| {
453 room.join_project(
454 host_project_id,
455 self.language_registry.clone(),
456 self.fs.clone(),
457 cx,
458 )
459 })
460 .await
461 .unwrap()
462 }
463
464 fn build_workspace(
465 &self,
466 project: &ModelHandle<Project>,
467 cx: &mut TestAppContext,
468 ) -> ViewHandle<Workspace> {
469 struct WorkspaceContainer {
470 workspace: Option<WeakViewHandle<Workspace>>,
471 }
472
473 impl Entity for WorkspaceContainer {
474 type Event = ();
475 }
476
477 impl View for WorkspaceContainer {
478 fn ui_name() -> &'static str {
479 "WorkspaceContainer"
480 }
481
482 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
483 if let Some(workspace) = self
484 .workspace
485 .as_ref()
486 .and_then(|workspace| workspace.upgrade(cx))
487 {
488 ChildView::new(&workspace, cx).into_any()
489 } else {
490 Empty::new().into_any()
491 }
492 }
493 }
494
495 // We use a workspace container so that we don't need to remove the window in order to
496 // drop the workspace and we can use a ViewHandle instead.
497 let (window_id, container) = cx.add_window(|_| WorkspaceContainer { workspace: None });
498 let workspace = cx.add_view(window_id, |cx| Workspace::test_new(project.clone(), cx));
499 container.update(cx, |container, cx| {
500 container.workspace = Some(workspace.downgrade());
501 cx.notify();
502 });
503 workspace
504 }
505}
506
507impl Drop for TestClient {
508 fn drop(&mut self) {
509 self.client.teardown();
510 }
511}