1use crate::{
  2    db::{self, NewUserParams, UserId},
  3    rpc::{CLEANUP_TIMEOUT, RECONNECT_TIMEOUT},
  4    tests::{TestClient, TestServer},
  5};
  6use async_trait::async_trait;
  7use futures::StreamExt;
  8use gpui::{BackgroundExecutor, Task, TestAppContext};
  9use parking_lot::Mutex;
 10use rand::prelude::*;
 11use rpc::RECEIVE_TIMEOUT;
 12use serde::{Deserialize, Serialize, de::DeserializeOwned};
 13use settings::SettingsStore;
 14use std::sync::OnceLock;
 15use std::{
 16    env,
 17    path::PathBuf,
 18    rc::Rc,
 19    sync::{
 20        Arc,
 21        atomic::{AtomicBool, Ordering::SeqCst},
 22    },
 23};
 24
 25fn plan_load_path() -> &'static Option<PathBuf> {
 26    static PLAN_LOAD_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
 27    PLAN_LOAD_PATH.get_or_init(|| path_env_var("LOAD_PLAN"))
 28}
 29
 30fn plan_save_path() -> &'static Option<PathBuf> {
 31    static PLAN_SAVE_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
 32    PLAN_SAVE_PATH.get_or_init(|| path_env_var("SAVE_PLAN"))
 33}
 34
 35fn max_peers() -> usize {
 36    static MAX_PEERS: OnceLock<usize> = OnceLock::new();
 37    *MAX_PEERS.get_or_init(|| {
 38        env::var("MAX_PEERS")
 39            .map(|i| i.parse().expect("invalid `MAX_PEERS` variable"))
 40            .unwrap_or(3)
 41    })
 42}
 43
 44fn max_operations() -> usize {
 45    static MAX_OPERATIONS: OnceLock<usize> = OnceLock::new();
 46    *MAX_OPERATIONS.get_or_init(|| {
 47        env::var("OPERATIONS")
 48            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
 49            .unwrap_or(10)
 50    })
 51}
 52
 53static LOADED_PLAN_JSON: Mutex<Option<Vec<u8>>> = Mutex::new(None);
 54static LAST_PLAN: Mutex<Option<Box<dyn Send + FnOnce() -> Vec<u8>>>> = Mutex::new(None);
 55
 56struct TestPlan<T: RandomizedTest> {
 57    rng: StdRng,
 58    replay: bool,
 59    stored_operations: Vec<(StoredOperation<T::Operation>, Arc<AtomicBool>)>,
 60    max_operations: usize,
 61    operation_ix: usize,
 62    users: Vec<UserTestPlan>,
 63    next_batch_id: usize,
 64    allow_server_restarts: bool,
 65    allow_client_reconnection: bool,
 66    allow_client_disconnection: bool,
 67}
 68
 69pub struct UserTestPlan {
 70    pub user_id: UserId,
 71    pub username: String,
 72    pub allow_client_disconnection: bool,
 73    next_root_id: usize,
 74    operation_ix: usize,
 75    online: bool,
 76}
 77
 78#[derive(Clone, Debug, Serialize, Deserialize)]
 79#[serde(untagged)]
 80enum StoredOperation<T> {
 81    Server(ServerOperation),
 82    Client {
 83        user_id: UserId,
 84        batch_id: usize,
 85        operation: T,
 86    },
 87}
 88
 89#[derive(Clone, Debug, Serialize, Deserialize)]
 90enum ServerOperation {
 91    AddConnection {
 92        user_id: UserId,
 93    },
 94    RemoveConnection {
 95        user_id: UserId,
 96    },
 97    BounceConnection {
 98        user_id: UserId,
 99    },
100    RestartServer,
101    MutateClients {
102        batch_id: usize,
103        #[serde(skip_serializing)]
104        #[serde(skip_deserializing)]
105        user_ids: Vec<UserId>,
106        quiesce: bool,
107    },
108}
109
110pub enum TestError {
111    Inapplicable,
112    Other(anyhow::Error),
113}
114
115#[async_trait(?Send)]
116pub trait RandomizedTest: 'static + Sized {
117    type Operation: Send + Clone + Serialize + DeserializeOwned;
118
119    fn generate_operation(
120        client: &TestClient,
121        rng: &mut StdRng,
122        plan: &mut UserTestPlan,
123        cx: &TestAppContext,
124    ) -> Self::Operation;
125
126    async fn apply_operation(
127        client: &TestClient,
128        operation: Self::Operation,
129        cx: &mut TestAppContext,
130    ) -> Result<(), TestError>;
131
132    async fn initialize(server: &mut TestServer, users: &[UserTestPlan]);
133
134    async fn on_client_added(_client: &Rc<TestClient>, _cx: &mut TestAppContext) {}
135
136    async fn on_quiesce(server: &mut TestServer, client: &mut [(Rc<TestClient>, TestAppContext)]);
137}
138
139pub async fn run_randomized_test<T: RandomizedTest>(
140    cx: &mut TestAppContext,
141    executor: BackgroundExecutor,
142    rng: StdRng,
143) {
144    let mut server = TestServer::start(executor.clone()).await;
145    let plan = TestPlan::<T>::new(&mut server, rng).await;
146
147    LAST_PLAN.lock().replace({
148        let plan = plan.clone();
149        Box::new(move || plan.lock().serialize())
150    });
151
152    let mut clients = Vec::new();
153    let mut client_tasks = Vec::new();
154    let mut operation_channels = Vec::new();
155    loop {
156        let Some((next_operation, applied)) = plan.lock().next_server_operation(&clients) else {
157            break;
158        };
159        applied.store(true, SeqCst);
160        let did_apply = TestPlan::apply_server_operation(
161            plan.clone(),
162            executor.clone(),
163            &mut server,
164            &mut clients,
165            &mut client_tasks,
166            &mut operation_channels,
167            next_operation,
168            cx,
169        )
170        .await;
171        if !did_apply {
172            applied.store(false, SeqCst);
173        }
174    }
175
176    drop(operation_channels);
177    executor.start_waiting();
178    futures::future::join_all(client_tasks).await;
179    executor.finish_waiting();
180
181    executor.run_until_parked();
182    T::on_quiesce(&mut server, &mut clients).await;
183
184    for (client, cx) in clients {
185        cx.update(|cx| {
186            let settings = cx.remove_global::<SettingsStore>();
187            cx.clear_globals();
188            cx.set_global(settings);
189            theme::init(theme::LoadThemes::JustBase, cx);
190            drop(client);
191        });
192    }
193    executor.run_until_parked();
194
195    if let Some(path) = plan_save_path() {
196        eprintln!("saved test plan to path {:?}", path);
197        std::fs::write(path, plan.lock().serialize()).unwrap();
198    }
199}
200
201pub fn save_randomized_test_plan() {
202    if let Some(serialize_plan) = LAST_PLAN.lock().take()
203        && let Some(path) = plan_save_path()
204    {
205        eprintln!("saved test plan to path {:?}", path);
206        std::fs::write(path, serialize_plan()).unwrap();
207    }
208}
209
210impl<T: RandomizedTest> TestPlan<T> {
211    pub async fn new(server: &mut TestServer, mut rng: StdRng) -> Arc<Mutex<Self>> {
212        let allow_server_restarts = rng.random_bool(0.7);
213        let allow_client_reconnection = rng.random_bool(0.7);
214        let allow_client_disconnection = rng.random_bool(0.1);
215
216        let mut users = Vec::new();
217        for ix in 0..max_peers() {
218            let username = format!("user-{}", ix + 1);
219            let user_id = server
220                .app_state
221                .db
222                .create_user(
223                    &format!("{username}@example.com"),
224                    None,
225                    false,
226                    NewUserParams {
227                        github_login: username.clone(),
228                        github_user_id: ix as i32,
229                    },
230                )
231                .await
232                .unwrap()
233                .user_id;
234            users.push(UserTestPlan {
235                user_id,
236                username,
237                online: false,
238                next_root_id: 0,
239                operation_ix: 0,
240                allow_client_disconnection,
241            });
242        }
243
244        T::initialize(server, &users).await;
245
246        let plan = Arc::new(Mutex::new(Self {
247            replay: false,
248            allow_server_restarts,
249            allow_client_reconnection,
250            allow_client_disconnection,
251            stored_operations: Vec::new(),
252            operation_ix: 0,
253            next_batch_id: 0,
254            max_operations: max_operations(),
255            users,
256            rng,
257        }));
258
259        if let Some(path) = plan_load_path() {
260            let json = LOADED_PLAN_JSON
261                .lock()
262                .get_or_insert_with(|| {
263                    eprintln!("loaded test plan from path {:?}", path);
264                    std::fs::read(path).unwrap()
265                })
266                .clone();
267            plan.lock().deserialize(json);
268        }
269
270        plan
271    }
272
273    fn deserialize(&mut self, json: Vec<u8>) {
274        let stored_operations: Vec<StoredOperation<T::Operation>> =
275            serde_json::from_slice(&json).unwrap();
276        self.replay = true;
277        self.stored_operations = stored_operations
278            .iter()
279            .cloned()
280            .enumerate()
281            .map(|(i, mut operation)| {
282                let did_apply = Arc::new(AtomicBool::new(false));
283                if let StoredOperation::Server(ServerOperation::MutateClients {
284                    batch_id: current_batch_id,
285                    user_ids,
286                    ..
287                }) = &mut operation
288                {
289                    assert!(user_ids.is_empty());
290                    user_ids.extend(stored_operations[i + 1..].iter().filter_map(|operation| {
291                        if let StoredOperation::Client {
292                            user_id, batch_id, ..
293                        } = operation
294                            && batch_id == current_batch_id
295                        {
296                            return Some(user_id);
297                        }
298                        None
299                    }));
300                    user_ids.sort_unstable();
301                }
302                (operation, did_apply)
303            })
304            .collect()
305    }
306
307    fn serialize(&mut self) -> Vec<u8> {
308        // Format each operation as one line
309        let mut json = Vec::new();
310        json.push(b'[');
311        for (operation, applied) in &self.stored_operations {
312            if !applied.load(SeqCst) {
313                continue;
314            }
315            if json.len() > 1 {
316                json.push(b',');
317            }
318            json.extend_from_slice(b"\n  ");
319            serde_json::to_writer(&mut json, operation).unwrap();
320        }
321        json.extend_from_slice(b"\n]\n");
322        json
323    }
324
325    fn next_server_operation(
326        &mut self,
327        clients: &[(Rc<TestClient>, TestAppContext)],
328    ) -> Option<(ServerOperation, Arc<AtomicBool>)> {
329        if self.replay {
330            while let Some(stored_operation) = self.stored_operations.get(self.operation_ix) {
331                self.operation_ix += 1;
332                if let (StoredOperation::Server(operation), applied) = stored_operation {
333                    return Some((operation.clone(), applied.clone()));
334                }
335            }
336            None
337        } else {
338            let operation = self.generate_server_operation(clients)?;
339            let applied = Arc::new(AtomicBool::new(false));
340            self.stored_operations
341                .push((StoredOperation::Server(operation.clone()), applied.clone()));
342            Some((operation, applied))
343        }
344    }
345
346    fn next_client_operation(
347        &mut self,
348        client: &TestClient,
349        current_batch_id: usize,
350        cx: &TestAppContext,
351    ) -> Option<(T::Operation, Arc<AtomicBool>)> {
352        let current_user_id = client.current_user_id(cx);
353        let user_ix = self
354            .users
355            .iter()
356            .position(|user| user.user_id == current_user_id)
357            .unwrap();
358        let user_plan = &mut self.users[user_ix];
359
360        if self.replay {
361            while let Some(stored_operation) = self.stored_operations.get(user_plan.operation_ix) {
362                user_plan.operation_ix += 1;
363                if let (
364                    StoredOperation::Client {
365                        user_id, operation, ..
366                    },
367                    applied,
368                ) = stored_operation
369                    && user_id == ¤t_user_id
370                {
371                    return Some((operation.clone(), applied.clone()));
372                }
373            }
374            None
375        } else {
376            if self.operation_ix == self.max_operations {
377                return None;
378            }
379            self.operation_ix += 1;
380            let operation = T::generate_operation(
381                client,
382                &mut self.rng,
383                self.users
384                    .iter_mut()
385                    .find(|user| user.user_id == current_user_id)
386                    .unwrap(),
387                cx,
388            );
389            let applied = Arc::new(AtomicBool::new(false));
390            self.stored_operations.push((
391                StoredOperation::Client {
392                    user_id: current_user_id,
393                    batch_id: current_batch_id,
394                    operation: operation.clone(),
395                },
396                applied.clone(),
397            ));
398            Some((operation, applied))
399        }
400    }
401
402    fn generate_server_operation(
403        &mut self,
404        clients: &[(Rc<TestClient>, TestAppContext)],
405    ) -> Option<ServerOperation> {
406        if self.operation_ix == self.max_operations {
407            return None;
408        }
409
410        Some(loop {
411            break match self.rng.random_range(0..100) {
412                0..=29 if clients.len() < self.users.len() => {
413                    let user = self
414                        .users
415                        .iter()
416                        .filter(|u| !u.online)
417                        .choose(&mut self.rng)
418                        .unwrap();
419                    self.operation_ix += 1;
420                    ServerOperation::AddConnection {
421                        user_id: user.user_id,
422                    }
423                }
424                30..=34 if clients.len() > 1 && self.allow_client_disconnection => {
425                    let (client, cx) = &clients[self.rng.random_range(0..clients.len())];
426                    let user_id = client.current_user_id(cx);
427                    self.operation_ix += 1;
428                    ServerOperation::RemoveConnection { user_id }
429                }
430                35..=39 if clients.len() > 1 && self.allow_client_reconnection => {
431                    let (client, cx) = &clients[self.rng.random_range(0..clients.len())];
432                    let user_id = client.current_user_id(cx);
433                    self.operation_ix += 1;
434                    ServerOperation::BounceConnection { user_id }
435                }
436                40..=44 if self.allow_server_restarts && clients.len() > 1 => {
437                    self.operation_ix += 1;
438                    ServerOperation::RestartServer
439                }
440                _ if !clients.is_empty() => {
441                    let count = self
442                        .rng
443                        .random_range(1..10)
444                        .min(self.max_operations - self.operation_ix);
445                    let batch_id = util::post_inc(&mut self.next_batch_id);
446                    let mut user_ids = (0..count)
447                        .map(|_| {
448                            let ix = self.rng.random_range(0..clients.len());
449                            let (client, cx) = &clients[ix];
450                            client.current_user_id(cx)
451                        })
452                        .collect::<Vec<_>>();
453                    user_ids.sort_unstable();
454                    ServerOperation::MutateClients {
455                        user_ids,
456                        batch_id,
457                        quiesce: self.rng.random_bool(0.7),
458                    }
459                }
460                _ => continue,
461            };
462        })
463    }
464
465    async fn apply_server_operation(
466        plan: Arc<Mutex<Self>>,
467        deterministic: BackgroundExecutor,
468        server: &mut TestServer,
469        clients: &mut Vec<(Rc<TestClient>, TestAppContext)>,
470        client_tasks: &mut Vec<Task<()>>,
471        operation_channels: &mut Vec<futures::channel::mpsc::UnboundedSender<usize>>,
472        operation: ServerOperation,
473        cx: &mut TestAppContext,
474    ) -> bool {
475        match operation {
476            ServerOperation::AddConnection { user_id } => {
477                let username;
478                {
479                    let mut plan = plan.lock();
480                    let user = plan.user(user_id);
481                    if user.online {
482                        return false;
483                    }
484                    user.online = true;
485                    username = user.username.clone();
486                };
487                log::info!("adding new connection for {}", username);
488
489                let mut client_cx = cx.new_app();
490
491                let (operation_tx, operation_rx) = futures::channel::mpsc::unbounded();
492                let client = Rc::new(server.create_client(&mut client_cx, &username).await);
493                operation_channels.push(operation_tx);
494                clients.push((client.clone(), client_cx.clone()));
495
496                let foreground_executor = client_cx.foreground_executor().clone();
497                let simulate_client =
498                    Self::simulate_client(plan.clone(), client, operation_rx, client_cx);
499                client_tasks.push(foreground_executor.spawn(simulate_client));
500
501                log::info!("added connection for {}", username);
502            }
503
504            ServerOperation::RemoveConnection {
505                user_id: removed_user_id,
506            } => {
507                log::info!("simulating full disconnection of user {}", removed_user_id);
508                let client_ix = clients
509                    .iter()
510                    .position(|(client, cx)| client.current_user_id(cx) == removed_user_id);
511                let Some(client_ix) = client_ix else {
512                    return false;
513                };
514                let user_connection_ids = server
515                    .connection_pool
516                    .lock()
517                    .user_connection_ids(removed_user_id)
518                    .collect::<Vec<_>>();
519                assert_eq!(user_connection_ids.len(), 1);
520                let removed_peer_id = user_connection_ids[0].into();
521                let (client, client_cx) = clients.remove(client_ix);
522                let client_task = client_tasks.remove(client_ix);
523                operation_channels.remove(client_ix);
524                server.forbid_connections();
525                server.disconnect_client(removed_peer_id);
526                deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
527                deterministic.start_waiting();
528                log::info!("waiting for user {} to exit...", removed_user_id);
529                client_task.await;
530                deterministic.finish_waiting();
531                server.allow_connections();
532
533                for project in client.dev_server_projects().iter() {
534                    project.read_with(&client_cx, |project, cx| {
535                        assert!(
536                            project.is_disconnected(cx),
537                            "project {:?} should be read only",
538                            project.remote_id()
539                        )
540                    });
541                }
542
543                for (client, cx) in clients {
544                    let contacts = server
545                        .app_state
546                        .db
547                        .get_contacts(client.current_user_id(cx))
548                        .await
549                        .unwrap();
550                    let pool = server.connection_pool.lock();
551                    for contact in contacts {
552                        if let db::Contact::Accepted { user_id, busy, .. } = contact
553                            && user_id == removed_user_id
554                        {
555                            assert!(!pool.is_user_online(user_id));
556                            assert!(!busy);
557                        }
558                    }
559                }
560
561                log::info!("{} removed", client.username);
562                plan.lock().user(removed_user_id).online = false;
563                client_cx.update(|cx| {
564                    cx.clear_globals();
565                    drop(client);
566                });
567            }
568
569            ServerOperation::BounceConnection { user_id } => {
570                log::info!("simulating temporary disconnection of user {}", user_id);
571                let user_connection_ids = server
572                    .connection_pool
573                    .lock()
574                    .user_connection_ids(user_id)
575                    .collect::<Vec<_>>();
576                if user_connection_ids.is_empty() {
577                    return false;
578                }
579                assert_eq!(user_connection_ids.len(), 1);
580                let peer_id = user_connection_ids[0].into();
581                server.disconnect_client(peer_id);
582                deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
583            }
584
585            ServerOperation::RestartServer => {
586                log::info!("simulating server restart");
587                server.reset().await;
588                deterministic.advance_clock(RECEIVE_TIMEOUT);
589                server.start().await.unwrap();
590                deterministic.advance_clock(CLEANUP_TIMEOUT);
591                let environment = &server.app_state.config.zed_environment;
592                let (stale_room_ids, _) = server
593                    .app_state
594                    .db
595                    .stale_server_resource_ids(environment, server.id())
596                    .await
597                    .unwrap();
598                assert_eq!(stale_room_ids, vec![]);
599            }
600
601            ServerOperation::MutateClients {
602                user_ids,
603                batch_id,
604                quiesce,
605            } => {
606                let mut applied = false;
607                for user_id in user_ids {
608                    let client_ix = clients
609                        .iter()
610                        .position(|(client, cx)| client.current_user_id(cx) == user_id);
611                    let Some(client_ix) = client_ix else { continue };
612                    applied = true;
613                    if let Err(err) = operation_channels[client_ix].unbounded_send(batch_id) {
614                        log::error!("error signaling user {user_id}: {err}");
615                    }
616                }
617
618                if quiesce && applied {
619                    deterministic.run_until_parked();
620                    T::on_quiesce(server, clients).await;
621                }
622
623                return applied;
624            }
625        }
626        true
627    }
628
629    async fn simulate_client(
630        plan: Arc<Mutex<Self>>,
631        client: Rc<TestClient>,
632        mut operation_rx: futures::channel::mpsc::UnboundedReceiver<usize>,
633        mut cx: TestAppContext,
634    ) {
635        T::on_client_added(&client, &mut cx).await;
636
637        while let Some(batch_id) = operation_rx.next().await {
638            let Some((operation, applied)) =
639                plan.lock().next_client_operation(&client, batch_id, &cx)
640            else {
641                break;
642            };
643            applied.store(true, SeqCst);
644            match T::apply_operation(&client, operation, &mut cx).await {
645                Ok(()) => {}
646                Err(TestError::Inapplicable) => {
647                    applied.store(false, SeqCst);
648                    log::info!("skipped operation");
649                }
650                Err(TestError::Other(error)) => {
651                    log::error!("{} error: {}", client.username, error);
652                }
653            }
654            cx.executor().simulate_random_delay().await;
655        }
656        log::info!("{}: done", client.username);
657    }
658
659    fn user(&mut self, user_id: UserId) -> &mut UserTestPlan {
660        self.users
661            .iter_mut()
662            .find(|user| user.user_id == user_id)
663            .unwrap()
664    }
665}
666
667impl UserTestPlan {
668    pub fn next_root_dir_name(&mut self) -> String {
669        let user_id = self.user_id;
670        let root_id = util::post_inc(&mut self.next_root_id);
671        format!("dir-{user_id}-{root_id}")
672    }
673}
674
675impl From<anyhow::Error> for TestError {
676    fn from(value: anyhow::Error) -> Self {
677        Self::Other(value)
678    }
679}
680
681fn path_env_var(name: &str) -> Option<PathBuf> {
682    let value = env::var(name).ok()?;
683    let mut path = PathBuf::from(value);
684    if path.is_relative() {
685        let mut abs_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
686        abs_path.pop();
687        abs_path.pop();
688        abs_path.push(path);
689        path = abs_path
690    }
691    Some(path)
692}