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::{channel_buffer::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 admin: (&TestClient, &mut TestAppContext),
292 members: &mut [(&TestClient, &mut TestAppContext)],
293 ) -> u64 {
294 let (admin_client, admin_cx) = admin;
295 let channel_id = admin_client
296 .app_state
297 .channel_store
298 .update(admin_cx, |channel_store, cx| {
299 channel_store.create_channel(channel, None, cx)
300 })
301 .await
302 .unwrap();
303
304 for (member_client, member_cx) in members {
305 admin_client
306 .app_state
307 .channel_store
308 .update(admin_cx, |channel_store, cx| {
309 channel_store.invite_member(
310 channel_id,
311 member_client.user_id().unwrap(),
312 false,
313 cx,
314 )
315 })
316 .await
317 .unwrap();
318
319 admin_cx.foreground().run_until_parked();
320
321 member_client
322 .app_state
323 .channel_store
324 .update(*member_cx, |channels, _| {
325 channels.respond_to_channel_invite(channel_id, true)
326 })
327 .await
328 .unwrap();
329 }
330
331 channel_id
332 }
333
334 pub async fn create_room(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
335 self.make_contacts(clients).await;
336
337 let (left, right) = clients.split_at_mut(1);
338 let (_client_a, cx_a) = &mut left[0];
339 let active_call_a = cx_a.read(ActiveCall::global);
340
341 for (client_b, cx_b) in right {
342 let user_id_b = client_b.current_user_id(*cx_b).to_proto();
343 active_call_a
344 .update(*cx_a, |call, cx| call.invite(user_id_b, None, cx))
345 .await
346 .unwrap();
347
348 cx_b.foreground().run_until_parked();
349 let active_call_b = cx_b.read(ActiveCall::global);
350 active_call_b
351 .update(*cx_b, |call, cx| call.accept_incoming(cx))
352 .await
353 .unwrap();
354 }
355 }
356
357 pub async fn build_app_state(
358 test_db: &TestDb,
359 fake_server: &live_kit_client::TestServer,
360 ) -> Arc<AppState> {
361 Arc::new(AppState {
362 db: test_db.db().clone(),
363 live_kit_client: Some(Arc::new(fake_server.create_api_client())),
364 config: Default::default(),
365 })
366 }
367}
368
369impl Deref for TestServer {
370 type Target = Server;
371
372 fn deref(&self) -> &Self::Target {
373 &self.server
374 }
375}
376
377impl Drop for TestServer {
378 fn drop(&mut self) {
379 self.server.teardown();
380 self.test_live_kit_server.teardown().unwrap();
381 }
382}
383
384impl Deref for TestClient {
385 type Target = Arc<Client>;
386
387 fn deref(&self) -> &Self::Target {
388 &self.app_state.client
389 }
390}
391
392impl TestClient {
393 pub fn fs(&self) -> &FakeFs {
394 self.app_state.fs.as_fake()
395 }
396
397 pub fn channel_store(&self) -> &ModelHandle<ChannelStore> {
398 &self.app_state.channel_store
399 }
400
401 pub fn user_store(&self) -> &ModelHandle<UserStore> {
402 &self.app_state.user_store
403 }
404
405 pub fn language_registry(&self) -> &Arc<LanguageRegistry> {
406 &self.app_state.languages
407 }
408
409 pub fn client(&self) -> &Arc<Client> {
410 &self.app_state.client
411 }
412
413 pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
414 UserId::from_proto(
415 self.app_state
416 .user_store
417 .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
418 )
419 }
420
421 pub async fn wait_for_current_user(&self, cx: &TestAppContext) {
422 let mut authed_user = self
423 .app_state
424 .user_store
425 .read_with(cx, |user_store, _| user_store.watch_current_user());
426 while authed_user.next().await.unwrap().is_none() {}
427 }
428
429 pub async fn clear_contacts(&self, cx: &mut TestAppContext) {
430 self.app_state
431 .user_store
432 .update(cx, |store, _| store.clear_contacts())
433 .await;
434 }
435
436 pub fn local_projects<'a>(&'a self) -> impl Deref<Target = Vec<ModelHandle<Project>>> + 'a {
437 Ref::map(self.state.borrow(), |state| &state.local_projects)
438 }
439
440 pub fn remote_projects<'a>(&'a self) -> impl Deref<Target = Vec<ModelHandle<Project>>> + 'a {
441 Ref::map(self.state.borrow(), |state| &state.remote_projects)
442 }
443
444 pub fn local_projects_mut<'a>(
445 &'a self,
446 ) -> impl DerefMut<Target = Vec<ModelHandle<Project>>> + 'a {
447 RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
448 }
449
450 pub fn remote_projects_mut<'a>(
451 &'a self,
452 ) -> impl DerefMut<Target = Vec<ModelHandle<Project>>> + 'a {
453 RefMut::map(self.state.borrow_mut(), |state| &mut state.remote_projects)
454 }
455
456 pub fn buffers_for_project<'a>(
457 &'a self,
458 project: &ModelHandle<Project>,
459 ) -> impl DerefMut<Target = HashSet<ModelHandle<language::Buffer>>> + 'a {
460 RefMut::map(self.state.borrow_mut(), |state| {
461 state.buffers.entry(project.clone()).or_default()
462 })
463 }
464
465 pub fn buffers<'a>(
466 &'a self,
467 ) -> impl DerefMut<Target = HashMap<ModelHandle<Project>, HashSet<ModelHandle<language::Buffer>>>> + 'a
468 {
469 RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
470 }
471
472 pub fn channel_buffers<'a>(
473 &'a self,
474 ) -> impl DerefMut<Target = HashSet<ModelHandle<ChannelBuffer>>> + 'a {
475 RefMut::map(self.state.borrow_mut(), |state| &mut state.channel_buffers)
476 }
477
478 pub fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
479 self.app_state
480 .user_store
481 .read_with(cx, |store, _| ContactsSummary {
482 current: store
483 .contacts()
484 .iter()
485 .map(|contact| contact.user.github_login.clone())
486 .collect(),
487 outgoing_requests: store
488 .outgoing_contact_requests()
489 .iter()
490 .map(|user| user.github_login.clone())
491 .collect(),
492 incoming_requests: store
493 .incoming_contact_requests()
494 .iter()
495 .map(|user| user.github_login.clone())
496 .collect(),
497 })
498 }
499
500 pub async fn build_local_project(
501 &self,
502 root_path: impl AsRef<Path>,
503 cx: &mut TestAppContext,
504 ) -> (ModelHandle<Project>, WorktreeId) {
505 let project = cx.update(|cx| {
506 Project::local(
507 self.client().clone(),
508 self.app_state.user_store.clone(),
509 self.app_state.languages.clone(),
510 self.app_state.fs.clone(),
511 cx,
512 )
513 });
514 let (worktree, _) = project
515 .update(cx, |p, cx| {
516 p.find_or_create_local_worktree(root_path, true, cx)
517 })
518 .await
519 .unwrap();
520 worktree
521 .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
522 .await;
523 (project, worktree.read_with(cx, |tree, _| tree.id()))
524 }
525
526 pub async fn build_remote_project(
527 &self,
528 host_project_id: u64,
529 guest_cx: &mut TestAppContext,
530 ) -> ModelHandle<Project> {
531 let active_call = guest_cx.read(ActiveCall::global);
532 let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
533 room.update(guest_cx, |room, cx| {
534 room.join_project(
535 host_project_id,
536 self.app_state.languages.clone(),
537 self.app_state.fs.clone(),
538 cx,
539 )
540 })
541 .await
542 .unwrap()
543 }
544
545 pub fn build_workspace(
546 &self,
547 project: &ModelHandle<Project>,
548 cx: &mut TestAppContext,
549 ) -> WindowHandle<Workspace> {
550 cx.add_window(|cx| Workspace::new(0, project.clone(), self.app_state.clone(), cx))
551 }
552}
553
554impl Drop for TestClient {
555 fn drop(&mut self) {
556 self.app_state.client.teardown();
557 }
558}