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;
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 channel_store =
208 cx.add_model(|cx| ChannelStore::new(client.clone(), user_store.clone(), cx));
209 let app_state = Arc::new(workspace::AppState {
210 client: client.clone(),
211 user_store: user_store.clone(),
212 channel_store: channel_store.clone(),
213 languages: Arc::new(LanguageRegistry::test()),
214 fs: fs.clone(),
215 build_window_options: |_, _, _| Default::default(),
216 initialize_workspace: |_, _, _, _| Task::ready(Ok(())),
217 background_actions: || &[],
218 });
219
220 cx.update(|cx| {
221 theme::init((), cx);
222 Project::init(&client, cx);
223 client::init(&client, cx);
224 language::init(cx);
225 editor::init_settings(cx);
226 workspace::init(app_state.clone(), cx);
227 audio::init((), cx);
228 call::init(client.clone(), user_store.clone(), cx);
229 channel::init(&client);
230 });
231
232 client
233 .authenticate_and_connect(false, &cx.to_async())
234 .await
235 .unwrap();
236
237 let client = TestClient {
238 app_state,
239 username: name.to_string(),
240 state: Default::default(),
241 };
242 client.wait_for_current_user(cx).await;
243 client
244 }
245
246 pub fn disconnect_client(&self, peer_id: PeerId) {
247 self.connection_killers
248 .lock()
249 .remove(&peer_id)
250 .unwrap()
251 .store(true, SeqCst);
252 }
253
254 pub fn forbid_connections(&self) {
255 self.forbid_connections.store(true, SeqCst);
256 }
257
258 pub fn allow_connections(&self) {
259 self.forbid_connections.store(false, SeqCst);
260 }
261
262 pub async fn make_contacts(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
263 for ix in 1..clients.len() {
264 let (left, right) = clients.split_at_mut(ix);
265 let (client_a, cx_a) = left.last_mut().unwrap();
266 for (client_b, cx_b) in right {
267 client_a
268 .app_state
269 .user_store
270 .update(*cx_a, |store, cx| {
271 store.request_contact(client_b.user_id().unwrap(), cx)
272 })
273 .await
274 .unwrap();
275 cx_a.foreground().run_until_parked();
276 client_b
277 .app_state
278 .user_store
279 .update(*cx_b, |store, cx| {
280 store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
281 })
282 .await
283 .unwrap();
284 }
285 }
286 }
287
288 pub async fn make_channel(
289 &self,
290 channel: &str,
291 parent: Option<u64>,
292 admin: (&TestClient, &mut TestAppContext),
293 members: &mut [(&TestClient, &mut TestAppContext)],
294 ) -> u64 {
295 let (admin_client, admin_cx) = admin;
296 let channel_id = admin_client
297 .app_state
298 .channel_store
299 .update(admin_cx, |channel_store, cx| {
300 channel_store.create_channel(channel, parent, cx)
301 })
302 .await
303 .unwrap();
304
305 for (member_client, member_cx) in members {
306 admin_client
307 .app_state
308 .channel_store
309 .update(admin_cx, |channel_store, cx| {
310 channel_store.invite_member(
311 channel_id,
312 member_client.user_id().unwrap(),
313 false,
314 cx,
315 )
316 })
317 .await
318 .unwrap();
319
320 admin_cx.foreground().run_until_parked();
321
322 member_client
323 .app_state
324 .channel_store
325 .update(*member_cx, |channels, _| {
326 channels.respond_to_channel_invite(channel_id, true)
327 })
328 .await
329 .unwrap();
330 }
331
332 channel_id
333 }
334
335 pub async fn make_channel_tree(
336 &self,
337 channels: &[(&str, Option<&str>)],
338 creator: (&TestClient, &mut TestAppContext),
339 ) -> Vec<u64> {
340 let mut observed_channels = HashMap::default();
341 let mut result = Vec::new();
342 for (channel, parent) in channels {
343 let id;
344 if let Some(parent) = parent {
345 if let Some(parent_id) = observed_channels.get(parent) {
346 id = self
347 .make_channel(channel, Some(*parent_id), (creator.0, creator.1), &mut [])
348 .await;
349 } else {
350 panic!(
351 "Edge {}->{} referenced before {} was created",
352 parent, channel, parent
353 )
354 }
355 } else {
356 id = self
357 .make_channel(channel, None, (creator.0, creator.1), &mut [])
358 .await;
359 }
360
361 observed_channels.insert(channel, id);
362 result.push(id);
363 }
364
365 result
366 }
367
368 pub async fn create_room(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
369 self.make_contacts(clients).await;
370
371 let (left, right) = clients.split_at_mut(1);
372 let (_client_a, cx_a) = &mut left[0];
373 let active_call_a = cx_a.read(ActiveCall::global);
374
375 for (client_b, cx_b) in right {
376 let user_id_b = client_b.current_user_id(*cx_b).to_proto();
377 active_call_a
378 .update(*cx_a, |call, cx| call.invite(user_id_b, None, cx))
379 .await
380 .unwrap();
381
382 cx_b.foreground().run_until_parked();
383 let active_call_b = cx_b.read(ActiveCall::global);
384 active_call_b
385 .update(*cx_b, |call, cx| call.accept_incoming(cx))
386 .await
387 .unwrap();
388 }
389 }
390
391 pub async fn build_app_state(
392 test_db: &TestDb,
393 fake_server: &live_kit_client::TestServer,
394 ) -> Arc<AppState> {
395 Arc::new(AppState {
396 db: test_db.db().clone(),
397 live_kit_client: Some(Arc::new(fake_server.create_api_client())),
398 config: Default::default(),
399 })
400 }
401}
402
403impl Deref for TestServer {
404 type Target = Server;
405
406 fn deref(&self) -> &Self::Target {
407 &self.server
408 }
409}
410
411impl Drop for TestServer {
412 fn drop(&mut self) {
413 self.server.teardown();
414 self.test_live_kit_server.teardown().unwrap();
415 }
416}
417
418impl Deref for TestClient {
419 type Target = Arc<Client>;
420
421 fn deref(&self) -> &Self::Target {
422 &self.app_state.client
423 }
424}
425
426impl TestClient {
427 pub fn fs(&self) -> &FakeFs {
428 self.app_state.fs.as_fake()
429 }
430
431 pub fn channel_store(&self) -> &ModelHandle<ChannelStore> {
432 &self.app_state.channel_store
433 }
434
435 pub fn user_store(&self) -> &ModelHandle<UserStore> {
436 &self.app_state.user_store
437 }
438
439 pub fn language_registry(&self) -> &Arc<LanguageRegistry> {
440 &self.app_state.languages
441 }
442
443 pub fn client(&self) -> &Arc<Client> {
444 &self.app_state.client
445 }
446
447 pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
448 UserId::from_proto(
449 self.app_state
450 .user_store
451 .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
452 )
453 }
454
455 pub async fn wait_for_current_user(&self, cx: &TestAppContext) {
456 let mut authed_user = self
457 .app_state
458 .user_store
459 .read_with(cx, |user_store, _| user_store.watch_current_user());
460 while authed_user.next().await.unwrap().is_none() {}
461 }
462
463 pub async fn clear_contacts(&self, cx: &mut TestAppContext) {
464 self.app_state
465 .user_store
466 .update(cx, |store, _| store.clear_contacts())
467 .await;
468 }
469
470 pub fn local_projects<'a>(&'a self) -> impl Deref<Target = Vec<ModelHandle<Project>>> + 'a {
471 Ref::map(self.state.borrow(), |state| &state.local_projects)
472 }
473
474 pub fn remote_projects<'a>(&'a self) -> impl Deref<Target = Vec<ModelHandle<Project>>> + 'a {
475 Ref::map(self.state.borrow(), |state| &state.remote_projects)
476 }
477
478 pub fn local_projects_mut<'a>(
479 &'a self,
480 ) -> impl DerefMut<Target = Vec<ModelHandle<Project>>> + 'a {
481 RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
482 }
483
484 pub fn remote_projects_mut<'a>(
485 &'a self,
486 ) -> impl DerefMut<Target = Vec<ModelHandle<Project>>> + 'a {
487 RefMut::map(self.state.borrow_mut(), |state| &mut state.remote_projects)
488 }
489
490 pub fn buffers_for_project<'a>(
491 &'a self,
492 project: &ModelHandle<Project>,
493 ) -> impl DerefMut<Target = HashSet<ModelHandle<language::Buffer>>> + 'a {
494 RefMut::map(self.state.borrow_mut(), |state| {
495 state.buffers.entry(project.clone()).or_default()
496 })
497 }
498
499 pub fn buffers<'a>(
500 &'a self,
501 ) -> impl DerefMut<Target = HashMap<ModelHandle<Project>, HashSet<ModelHandle<language::Buffer>>>> + 'a
502 {
503 RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
504 }
505
506 pub fn channel_buffers<'a>(
507 &'a self,
508 ) -> impl DerefMut<Target = HashSet<ModelHandle<ChannelBuffer>>> + 'a {
509 RefMut::map(self.state.borrow_mut(), |state| &mut state.channel_buffers)
510 }
511
512 pub fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
513 self.app_state
514 .user_store
515 .read_with(cx, |store, _| ContactsSummary {
516 current: store
517 .contacts()
518 .iter()
519 .map(|contact| contact.user.github_login.clone())
520 .collect(),
521 outgoing_requests: store
522 .outgoing_contact_requests()
523 .iter()
524 .map(|user| user.github_login.clone())
525 .collect(),
526 incoming_requests: store
527 .incoming_contact_requests()
528 .iter()
529 .map(|user| user.github_login.clone())
530 .collect(),
531 })
532 }
533
534 pub async fn build_local_project(
535 &self,
536 root_path: impl AsRef<Path>,
537 cx: &mut TestAppContext,
538 ) -> (ModelHandle<Project>, WorktreeId) {
539 let project = cx.update(|cx| {
540 Project::local(
541 self.client().clone(),
542 self.app_state.user_store.clone(),
543 self.app_state.languages.clone(),
544 self.app_state.fs.clone(),
545 cx,
546 )
547 });
548 let (worktree, _) = project
549 .update(cx, |p, cx| {
550 p.find_or_create_local_worktree(root_path, true, cx)
551 })
552 .await
553 .unwrap();
554 worktree
555 .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
556 .await;
557 (project, worktree.read_with(cx, |tree, _| tree.id()))
558 }
559
560 pub async fn build_remote_project(
561 &self,
562 host_project_id: u64,
563 guest_cx: &mut TestAppContext,
564 ) -> ModelHandle<Project> {
565 let active_call = guest_cx.read(ActiveCall::global);
566 let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
567 room.update(guest_cx, |room, cx| {
568 room.join_project(
569 host_project_id,
570 self.app_state.languages.clone(),
571 self.app_state.fs.clone(),
572 cx,
573 )
574 })
575 .await
576 .unwrap()
577 }
578
579 pub fn build_workspace(
580 &self,
581 project: &ModelHandle<Project>,
582 cx: &mut TestAppContext,
583 ) -> WindowHandle<Workspace> {
584 cx.add_window(|cx| Workspace::new(0, project.clone(), self.app_state.clone(), cx))
585 }
586
587 pub async fn add_admin_to_channel(
588 &self,
589 user: (&TestClient, &mut TestAppContext),
590 channel: u64,
591 cx_self: &mut TestAppContext,
592 ) {
593 let (other_client, other_cx) = user;
594
595 self.app_state
596 .channel_store
597 .update(cx_self, |channel_store, cx| {
598 channel_store.invite_member(channel, other_client.user_id().unwrap(), true, cx)
599 })
600 .await
601 .unwrap();
602
603 cx_self.foreground().run_until_parked();
604
605 other_client
606 .app_state
607 .channel_store
608 .update(other_cx, |channels, _| {
609 channels.respond_to_channel_invite(channel, true)
610 })
611 .await
612 .unwrap();
613 }
614}
615
616impl Drop for TestClient {
617 fn drop(&mut self) {
618 self.app_state.client.teardown();
619 }
620}