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