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