1use crate::{
2 db::{tests::TestDb, NewUserParams, UserId},
3 executor::Executor,
4 rpc::{Server, CLEANUP_TIMEOUT, RECONNECT_TIMEOUT},
5 AppState, Config,
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::{BackgroundExecutor, Context, Model, TestAppContext, View, VisualTestContext};
17use language::LanguageRegistry;
18use node_runtime::FakeNodeRuntime;
19
20use notifications::NotificationStore;
21use parking_lot::Mutex;
22use project::{Project, WorktreeId};
23use rpc::{proto::ChannelRole, RECEIVE_TIMEOUT};
24use settings::SettingsStore;
25use std::{
26 cell::{Ref, RefCell, RefMut},
27 env,
28 ops::{Deref, DerefMut},
29 path::Path,
30 sync::{
31 atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
32 Arc,
33 },
34};
35use util::http::FakeHttpClient;
36use workspace::{Workspace, WorkspaceStore};
37
38pub struct TestServer {
39 pub app_state: Arc<AppState>,
40 pub test_live_kit_server: Arc<live_kit_client::TestServer>,
41 server: Arc<Server>,
42 connection_killers: Arc<Mutex<HashMap<PeerId, Arc<AtomicBool>>>>,
43 forbid_connections: Arc<AtomicBool>,
44 _test_db: TestDb,
45}
46
47pub struct TestClient {
48 pub username: String,
49 pub app_state: Arc<workspace::AppState>,
50 channel_store: Model<ChannelStore>,
51 notification_store: Model<NotificationStore>,
52 state: RefCell<TestClientState>,
53}
54
55#[derive(Default)]
56struct TestClientState {
57 local_projects: Vec<Model<Project>>,
58 remote_projects: Vec<Model<Project>>,
59 buffers: HashMap<Model<Project>, HashSet<Model<language::Buffer>>>,
60 channel_buffers: HashSet<Model<ChannelBuffer>>,
61}
62
63pub struct ContactsSummary {
64 pub current: Vec<String>,
65 pub outgoing_requests: Vec<String>,
66 pub incoming_requests: Vec<String>,
67}
68
69impl TestServer {
70 pub async fn start(deterministic: BackgroundExecutor) -> Self {
71 static NEXT_LIVE_KIT_SERVER_ID: AtomicUsize = AtomicUsize::new(0);
72
73 let use_postgres = env::var("USE_POSTGRES").ok();
74 let use_postgres = use_postgres.as_deref();
75 let test_db = if use_postgres == Some("true") || use_postgres == Some("1") {
76 TestDb::postgres(deterministic.clone())
77 } else {
78 TestDb::sqlite(deterministic.clone())
79 };
80 let live_kit_server_id = NEXT_LIVE_KIT_SERVER_ID.fetch_add(1, SeqCst);
81 let live_kit_server = live_kit_client::TestServer::create(
82 format!("http://livekit.{}.test", live_kit_server_id),
83 format!("devkey-{}", live_kit_server_id),
84 format!("secret-{}", live_kit_server_id),
85 deterministic.clone(),
86 )
87 .unwrap();
88 let app_state = Self::build_app_state(&test_db, &live_kit_server).await;
89 let epoch = app_state
90 .db
91 .create_server(&app_state.config.zed_environment)
92 .await
93 .unwrap();
94 let server = Server::new(
95 epoch,
96 app_state.clone(),
97 Executor::Deterministic(deterministic.clone()),
98 );
99 server.start().await.unwrap();
100 // Advance clock to ensure the server's cleanup task is finished.
101 deterministic.advance_clock(CLEANUP_TIMEOUT);
102 Self {
103 app_state,
104 server,
105 connection_killers: Default::default(),
106 forbid_connections: Default::default(),
107 _test_db: test_db,
108 test_live_kit_server: live_kit_server,
109 }
110 }
111
112 pub async fn reset(&self) {
113 self.app_state.db.reset();
114 let epoch = self
115 .app_state
116 .db
117 .create_server(&self.app_state.config.zed_environment)
118 .await
119 .unwrap();
120 self.server.reset(epoch);
121 }
122
123 pub async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
124 cx.update(|cx| {
125 if cx.has_global::<SettingsStore>() {
126 panic!("Same cx used to create two test clients")
127 }
128 let settings = SettingsStore::test(cx);
129 cx.set_global(settings);
130 });
131
132 let http = FakeHttpClient::with_404_response();
133 let user_id = if let Ok(Some(user)) = self.app_state.db.get_user_by_github_login(name).await
134 {
135 user.id
136 } else {
137 self.app_state
138 .db
139 .create_user(
140 &format!("{name}@example.com"),
141 false,
142 NewUserParams {
143 github_login: name.into(),
144 github_user_id: 0,
145 },
146 )
147 .await
148 .expect("creating user failed")
149 .user_id
150 };
151 let client_name = name.to_string();
152 let mut client = cx.update(|cx| Client::new(http.clone(), cx));
153 let server = self.server.clone();
154 let db = self.app_state.db.clone();
155 let connection_killers = self.connection_killers.clone();
156 let forbid_connections = self.forbid_connections.clone();
157
158 Arc::get_mut(&mut client)
159 .unwrap()
160 .set_id(user_id.to_proto())
161 .override_authenticate(move |cx| {
162 cx.spawn(|_| async move {
163 let access_token = "the-token".to_string();
164 Ok(Credentials {
165 user_id: user_id.to_proto(),
166 access_token,
167 })
168 })
169 })
170 .override_establish_connection(move |credentials, cx| {
171 assert_eq!(credentials.user_id, user_id.0 as u64);
172 assert_eq!(credentials.access_token, "the-token");
173
174 let server = server.clone();
175 let db = db.clone();
176 let connection_killers = connection_killers.clone();
177 let forbid_connections = forbid_connections.clone();
178 let client_name = client_name.clone();
179 cx.spawn(move |cx| async move {
180 if forbid_connections.load(SeqCst) {
181 Err(EstablishConnectionError::other(anyhow!(
182 "server is forbidding connections"
183 )))
184 } else {
185 let (client_conn, server_conn, killed) =
186 Connection::in_memory(cx.background_executor().clone());
187 let (connection_id_tx, connection_id_rx) = oneshot::channel();
188 let user = db
189 .get_user_by_id(user_id)
190 .await
191 .expect("retrieving user failed")
192 .unwrap();
193 cx.background_executor()
194 .spawn(server.handle_connection(
195 server_conn,
196 client_name,
197 user,
198 Some(connection_id_tx),
199 Executor::Deterministic(cx.background_executor().clone()),
200 ))
201 .detach();
202 let connection_id = connection_id_rx.await.unwrap();
203 connection_killers
204 .lock()
205 .insert(connection_id.into(), killed);
206 Ok(client_conn)
207 }
208 })
209 });
210
211 let fs = FakeFs::new(cx.executor());
212 let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
213 let workspace_store = cx.new_model(|cx| WorkspaceStore::new(client.clone(), cx));
214 let mut language_registry = LanguageRegistry::test();
215 language_registry.set_executor(cx.executor());
216 let app_state = Arc::new(workspace::AppState {
217 client: client.clone(),
218 user_store: user_store.clone(),
219 workspace_store,
220 languages: Arc::new(language_registry),
221 fs: fs.clone(),
222 build_window_options: |_, _, _| Default::default(),
223 node_runtime: FakeNodeRuntime::new(),
224 });
225
226 cx.update(|cx| {
227 theme::init(theme::LoadThemes::JustBase, 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: BackgroundExecutor,
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.executor().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.executor().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.executor().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: Config {
418 http_port: 0,
419 database_url: "".into(),
420 database_max_connections: 0,
421 api_token: "".into(),
422 invite_link_prefix: "".into(),
423 live_kit_server: None,
424 live_kit_key: None,
425 live_kit_secret: None,
426 rust_log: None,
427 log_json: None,
428 zed_environment: "test".into(),
429 },
430 })
431 }
432}
433
434impl Deref for TestServer {
435 type Target = Server;
436
437 fn deref(&self) -> &Self::Target {
438 &self.server
439 }
440}
441
442impl Drop for TestServer {
443 fn drop(&mut self) {
444 self.server.teardown();
445 self.test_live_kit_server.teardown().unwrap();
446 }
447}
448
449impl Deref for TestClient {
450 type Target = Arc<Client>;
451
452 fn deref(&self) -> &Self::Target {
453 &self.app_state.client
454 }
455}
456
457impl TestClient {
458 pub fn fs(&self) -> &FakeFs {
459 self.app_state.fs.as_fake()
460 }
461
462 pub fn channel_store(&self) -> &Model<ChannelStore> {
463 &self.channel_store
464 }
465
466 pub fn notification_store(&self) -> &Model<NotificationStore> {
467 &self.notification_store
468 }
469
470 pub fn user_store(&self) -> &Model<UserStore> {
471 &self.app_state.user_store
472 }
473
474 pub fn language_registry(&self) -> &Arc<LanguageRegistry> {
475 &self.app_state.languages
476 }
477
478 pub fn client(&self) -> &Arc<Client> {
479 &self.app_state.client
480 }
481
482 pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
483 UserId::from_proto(
484 self.app_state
485 .user_store
486 .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
487 )
488 }
489
490 pub async fn wait_for_current_user(&self, cx: &TestAppContext) {
491 let mut authed_user = self
492 .app_state
493 .user_store
494 .read_with(cx, |user_store, _| user_store.watch_current_user());
495 while authed_user.next().await.unwrap().is_none() {}
496 }
497
498 pub async fn clear_contacts(&self, cx: &mut TestAppContext) {
499 self.app_state
500 .user_store
501 .update(cx, |store, _| store.clear_contacts())
502 .await;
503 }
504
505 pub fn local_projects<'a>(&'a self) -> impl Deref<Target = Vec<Model<Project>>> + 'a {
506 Ref::map(self.state.borrow(), |state| &state.local_projects)
507 }
508
509 pub fn remote_projects<'a>(&'a self) -> impl Deref<Target = Vec<Model<Project>>> + 'a {
510 Ref::map(self.state.borrow(), |state| &state.remote_projects)
511 }
512
513 pub fn local_projects_mut<'a>(&'a self) -> impl DerefMut<Target = Vec<Model<Project>>> + 'a {
514 RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
515 }
516
517 pub fn remote_projects_mut<'a>(&'a self) -> impl DerefMut<Target = Vec<Model<Project>>> + 'a {
518 RefMut::map(self.state.borrow_mut(), |state| &mut state.remote_projects)
519 }
520
521 pub fn buffers_for_project<'a>(
522 &'a self,
523 project: &Model<Project>,
524 ) -> impl DerefMut<Target = HashSet<Model<language::Buffer>>> + 'a {
525 RefMut::map(self.state.borrow_mut(), |state| {
526 state.buffers.entry(project.clone()).or_default()
527 })
528 }
529
530 pub fn buffers<'a>(
531 &'a self,
532 ) -> impl DerefMut<Target = HashMap<Model<Project>, HashSet<Model<language::Buffer>>>> + 'a
533 {
534 RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
535 }
536
537 pub fn channel_buffers<'a>(
538 &'a self,
539 ) -> impl DerefMut<Target = HashSet<Model<ChannelBuffer>>> + 'a {
540 RefMut::map(self.state.borrow_mut(), |state| &mut state.channel_buffers)
541 }
542
543 pub fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
544 self.app_state
545 .user_store
546 .read_with(cx, |store, _| ContactsSummary {
547 current: store
548 .contacts()
549 .iter()
550 .map(|contact| contact.user.github_login.clone())
551 .collect(),
552 outgoing_requests: store
553 .outgoing_contact_requests()
554 .iter()
555 .map(|user| user.github_login.clone())
556 .collect(),
557 incoming_requests: store
558 .incoming_contact_requests()
559 .iter()
560 .map(|user| user.github_login.clone())
561 .collect(),
562 })
563 }
564
565 pub async fn build_local_project(
566 &self,
567 root_path: impl AsRef<Path>,
568 cx: &mut TestAppContext,
569 ) -> (Model<Project>, WorktreeId) {
570 let project = self.build_empty_local_project(cx);
571 let (worktree, _) = project
572 .update(cx, |p, cx| {
573 p.find_or_create_local_worktree(root_path, true, cx)
574 })
575 .await
576 .unwrap();
577 worktree
578 .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
579 .await;
580 (project, worktree.read_with(cx, |tree, _| tree.id()))
581 }
582
583 pub fn build_empty_local_project(&self, cx: &mut TestAppContext) -> Model<Project> {
584 cx.update(|cx| {
585 Project::local(
586 self.client().clone(),
587 self.app_state.node_runtime.clone(),
588 self.app_state.user_store.clone(),
589 self.app_state.languages.clone(),
590 self.app_state.fs.clone(),
591 cx,
592 )
593 })
594 }
595
596 pub async fn build_remote_project(
597 &self,
598 host_project_id: u64,
599 guest_cx: &mut TestAppContext,
600 ) -> Model<Project> {
601 let active_call = guest_cx.read(ActiveCall::global);
602 let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
603 room.update(guest_cx, |room, cx| {
604 room.join_project(
605 host_project_id,
606 self.app_state.languages.clone(),
607 self.app_state.fs.clone(),
608 cx,
609 )
610 })
611 .await
612 .unwrap()
613 }
614
615 pub fn build_workspace<'a>(
616 &'a self,
617 project: &Model<Project>,
618 cx: &'a mut TestAppContext,
619 ) -> (View<Workspace>, &'a mut VisualTestContext) {
620 cx.add_window_view(|cx| Workspace::new(0, project.clone(), self.app_state.clone(), cx))
621 }
622}
623
624impl Drop for TestClient {
625 fn drop(&mut self) {
626 self.app_state.client.teardown();
627 }
628}