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