test_server.rs

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