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