use std::collections::VecDeque; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; use async_trait::async_trait; use rcom::app::{ AppState, Command, ConnectSshRequest, Effect, ListingRequest, ListingResult, PaneId, PreviewRequest, PreviewResult, SshConnection, }; use rcom::domain::{Entry, EntryKind, HostAlias, Location, SourceId}; use rcom::fs::{BackendRegistry, FsError, ReadFileSystem, ReadPrefix}; use rcom::runtime::EffectRunner; use rcom::ssh::{ConnectionManager, SshConnector}; use rcom::test_support::{FaultInjectFs, FsOperation, MemoryFs}; use tokio::sync::{Notify, Semaphore, mpsc}; struct MemoryConnector { fs: MemoryFs, } #[async_trait] impl SshConnector for MemoryConnector { async fn connect(&self, _host: &HostAlias) -> Result, FsError> { Ok(Arc::new(self.fs.clone())) } } struct SequenceConnector { backends: Mutex>>, } #[async_trait] impl SshConnector for SequenceConnector { async fn connect(&self, _host: &HostAlias) -> Result, FsError> { self.backends .lock() .unwrap() .pop_front() .ok_or_else(|| FsError::Other("unexpected reconnect".into())) } } struct OperationStats { started: AtomicUsize, active: AtomicUsize, max_active: AtomicUsize, finished: AtomicUsize, changed: Notify, release: Semaphore, } impl Default for OperationStats { fn default() -> Self { Self { started: AtomicUsize::new(0), active: AtomicUsize::new(0), max_active: AtomicUsize::new(0), finished: AtomicUsize::new(0), changed: Notify::new(), release: Semaphore::new(0), } } } impl OperationStats { fn start(self: &Arc) -> ActiveOperation { self.started.fetch_add(1, Ordering::SeqCst); let active = self.active.fetch_add(1, Ordering::SeqCst) + 1; self.max_active.fetch_max(active, Ordering::SeqCst); self.changed.notify_one(); ActiveOperation { stats: self.clone(), } } async fn wait_for_started(&self, expected: usize) { tokio::time::timeout(Duration::from_secs(2), async { while self.started.load(Ordering::SeqCst) < expected { self.changed.notified().await; } }) .await .expect("operation should start"); } async fn wait_for_active(&self, expected: usize) { tokio::time::timeout(Duration::from_secs(2), async { while self.active.load(Ordering::SeqCst) != expected { self.changed.notified().await; } }) .await .expect("active operation count should change"); } } struct ActiveOperation { stats: Arc, } impl Drop for ActiveOperation { fn drop(&mut self) { self.stats.active.fetch_sub(1, Ordering::SeqCst); self.stats.changed.notify_one(); } } struct SlowListingFs { inner: MemoryFs, stats: Arc, } impl SlowListingFs { async fn wait(&self) { let _permit = self.stats.release.acquire().await.unwrap(); self.stats.finished.fetch_add(1, Ordering::SeqCst); } } #[async_trait] impl ReadFileSystem for SlowListingFs { async fn list(&self, location: &Location) -> Result, FsError> { let _operation = self.stats.start(); self.wait().await; self.inner.list(location).await } async fn canonicalize(&self, location: &Location) -> Result { self.inner.canonicalize(location).await } async fn metadata(&self, location: &Location) -> Result { self.inner.metadata(location).await } async fn read_prefix(&self, location: &Location, limit: usize) -> Result { let _operation = self.stats.start(); self.wait().await; self.inner.read_prefix(location, limit).await } } struct BlockingConnector { backend: MemoryFs, stats: Arc, } #[async_trait] impl SshConnector for BlockingConnector { async fn connect(&self, _host: &HostAlias) -> Result, FsError> { let _operation = self.stats.start(); let _permit = self.stats.release.acquire().await.unwrap(); self.stats.finished.fetch_add(1, Ordering::SeqCst); Ok(Arc::new(self.backend.clone())) } } struct LateDisconnectFs { inner: MemoryFs, listing_started: Arc, preview_started: Arc, release: Arc, } #[async_trait] impl ReadFileSystem for LateDisconnectFs { async fn list(&self, _location: &Location) -> Result, FsError> { self.listing_started.notify_one(); let _permit = self.release.acquire().await.unwrap(); Err(FsError::Disconnected) } async fn canonicalize(&self, location: &Location) -> Result { self.inner.canonicalize(location).await } async fn metadata(&self, location: &Location) -> Result { self.inner.metadata(location).await } async fn read_prefix( &self, _location: &Location, _limit: usize, ) -> Result { self.preview_started.notify_one(); let _permit = self.release.acquire().await.unwrap(); Err(FsError::Disconnected) } } async fn next_command(results: &mut mpsc::Receiver) -> Command { tokio::time::timeout(Duration::from_secs(2), results.recv()) .await .unwrap() .unwrap() } async fn receive_listing_and_preview( results: &mut mpsc::Receiver, ) -> (ListingResult, PreviewResult) { let mut listing = None; let mut preview = None; for _ in 0..2 { match next_command(results).await { Command::ListingFinished(result) => { assert!(listing.is_none(), "duplicate listing result"); listing = Some(result); } Command::PreviewFinished(result) => { assert!(preview.is_none(), "duplicate preview result"); preview = Some(result); } other => panic!("unexpected command: {other:?}"), } } (listing.unwrap(), preview.unwrap()) } fn local_manager(fs: Arc) -> ConnectionManager { let registry = BackendRegistry::new(fs); ConnectionManager::new( Arc::new(MemoryConnector { fs: MemoryFs::navigation_fixture(), }), registry, ) } async fn exercise_listing_stress( connections: ConnectionManager, target: Location, session_epoch: Option, stats: Arc, ) { const OPERATIONS: u64 = 32; let (mut runner, mut results) = EffectRunner::new(connections); for generation in 1..=OPERATIONS { runner.execute(Effect::LoadListing(ListingRequest { pane: PaneId::Left, generation, target: target.clone(), session_epoch, })); stats.wait_for_started(generation as usize).await; stats.wait_for_active(1).await; assert_eq!(stats.finished.load(Ordering::SeqCst), 0); assert!(results.try_recv().is_err(), "superseded listing returned"); } stats.release.add_permits(1); let Command::ListingFinished(result) = next_command(&mut results).await else { panic!("expected latest listing result"); }; assert_eq!(result.generation, OPERATIONS); assert_eq!(result.target, target); assert!(result.result.is_ok()); stats.wait_for_active(0).await; assert_eq!(stats.started.load(Ordering::SeqCst), OPERATIONS as usize); assert_eq!(stats.finished.load(Ordering::SeqCst), 1); assert_eq!(stats.max_active.load(Ordering::SeqCst), 1); assert!(results.try_recv().is_err(), "old listing returned late"); } #[tokio::test] async fn local_listing_effect_returns_a_reducer_command() { let connections = local_manager(Arc::new(MemoryFs::navigation_fixture())); let (mut runner, mut results) = EffectRunner::new(connections); let request = ListingRequest { pane: PaneId::Left, generation: 7, target: Location::local("/workspace"), session_epoch: None, }; runner.execute(Effect::LoadListing(request)); let command = tokio::time::timeout(Duration::from_secs(2), results.recv()) .await .unwrap() .unwrap(); let Command::ListingFinished(result) = command else { panic!("expected listing result"); }; assert_eq!(result.generation, 7); assert_eq!(result.target, Location::local("/workspace")); let entries = result.result.unwrap(); assert!( entries .iter() .any(|entry| entry.kind == EntryKind::Directory) ); } #[tokio::test] async fn a_new_preview_aborts_the_previous_preview_task() { let delayed = Arc::new(FaultInjectFs::new(Arc::new(MemoryFs::navigation_fixture()))); delayed.delay_next(FsOperation::ReadPrefix, Duration::from_secs(60)); let connections = local_manager(delayed); let (mut runner, mut results) = EffectRunner::new(connections); let first = PreviewRequest { pane: PaneId::Left, generation: 1, target: Location::local("/workspace/readme.txt"), session_epoch: None, images_enabled: true, }; let second = PreviewRequest { generation: 2, ..first.clone() }; runner.execute(Effect::LoadPreview(first)); tokio::task::yield_now().await; runner.execute(Effect::LoadPreview(second)); let command = tokio::time::timeout(Duration::from_secs(2), results.recv()) .await .unwrap() .unwrap(); let Command::PreviewFinished(result) = command else { panic!("expected preview result"); }; assert_eq!(result.generation, 2); assert!(result.result.is_ok()); assert!( results.try_recv().is_err(), "aborted preview produced a result" ); } #[tokio::test] async fn connect_effect_returns_remote_home_and_session_epoch() { let connections = local_manager(Arc::new(MemoryFs::navigation_fixture())); let (mut runner, mut results) = EffectRunner::new(connections); let request = ConnectSshRequest { pane: PaneId::Right, generation: 3, host: HostAlias::new("edge"), expected_session_epoch: None, }; runner.execute(Effect::ConnectSsh(request)); let synchronization = tokio::time::timeout(Duration::from_secs(2), results.recv()) .await .unwrap() .unwrap(); let Command::SynchronizeSshEpoch { host, session_epoch, } = synchronization else { panic!("expected epoch synchronization before connect result"); }; assert_eq!(host, HostAlias::new("edge")); assert!(session_epoch > 0); let command = tokio::time::timeout(Duration::from_secs(2), results.recv()) .await .unwrap() .unwrap(); let Command::ConnectSshFinished(result) = command else { panic!("expected connect result"); }; let connection = result.result.unwrap(); assert_eq!( connection.location.source, SourceId::Ssh(HostAlias::new("edge")) ); assert!(connection.session_epoch > 0); } #[tokio::test] async fn late_old_epoch_disconnects_preserve_new_handle_for_both_panes() { let host = HostAlias::new("edge"); let listing_started = Arc::new(Notify::new()); let preview_started = Arc::new(Notify::new()); let release = Arc::new(Semaphore::new(0)); let old_backend = Arc::new(LateDisconnectFs { inner: MemoryFs::navigation_fixture(), listing_started: listing_started.clone(), preview_started: preview_started.clone(), release: release.clone(), }); let backends: VecDeque> = VecDeque::from([ old_backend as Arc, Arc::new(MemoryFs::navigation_fixture()), ]); let connections = ConnectionManager::new( Arc::new(SequenceConnector { backends: Mutex::new(backends), }), BackendRegistry::new(Arc::new(MemoryFs::navigation_fixture())), ); let first = connections.connect(&host).await.unwrap(); let preview_target = Location::ssh(host.clone(), "/home/user/welcome.txt"); let (mut runner, mut results) = EffectRunner::new(connections.clone()); runner.execute(Effect::LoadListing(ListingRequest { pane: PaneId::Left, generation: 1, target: first.home.clone(), session_epoch: Some(first.epoch), })); runner.execute(Effect::LoadPreview(PreviewRequest { pane: PaneId::Right, generation: 2, target: preview_target.clone(), session_epoch: Some(first.epoch), images_enabled: true, })); tokio::time::timeout(Duration::from_secs(2), listing_started.notified()) .await .expect("old listing should start"); tokio::time::timeout(Duration::from_secs(2), preview_started.notified()) .await .expect("old preview should start"); connections.invalidate_if_epoch(&host, first.epoch).await; let reconnected = connections.connect(&host).await.unwrap(); assert!(reconnected.epoch > first.epoch); release.add_permits(2); let (listing, preview) = receive_listing_and_preview(&mut results).await; assert_eq!(listing.pane, PaneId::Left); assert_eq!(preview.pane, PaneId::Right); assert_eq!(listing.session_epoch, Some(first.epoch)); assert_eq!(preview.session_epoch, Some(first.epoch)); assert_eq!(listing.result, Err(FsError::Disconnected)); assert_eq!(preview.result, Err(FsError::Disconnected)); assert_eq!( connections.current(&host).await.unwrap().epoch, reconnected.epoch ); assert!(connections.registry().backend(&reconnected.home).is_ok()); assert!( connections .resolve(&reconnected.home, Some(reconnected.epoch)) .await .is_ok() ); runner.execute(Effect::LoadListing(ListingRequest { pane: PaneId::Left, generation: 3, target: reconnected.home.clone(), session_epoch: Some(reconnected.epoch), })); runner.execute(Effect::LoadPreview(PreviewRequest { pane: PaneId::Right, generation: 4, target: preview_target, session_epoch: Some(reconnected.epoch), images_enabled: true, })); let (listing, preview) = receive_listing_and_preview(&mut results).await; assert!(listing.result.is_ok()); assert!(preview.result.is_ok()); assert_eq!(listing.session_epoch, Some(reconnected.epoch)); assert_eq!(preview.session_epoch, Some(reconnected.epoch)); } #[tokio::test] async fn old_epoch_resolve_errors_preserve_new_handle_for_both_panes() { let host = HostAlias::new("edge"); let connections = local_manager(Arc::new(MemoryFs::navigation_fixture())); let first = connections.connect(&host).await.unwrap(); connections.invalidate_if_epoch(&host, first.epoch).await; let reconnected = connections.connect(&host).await.unwrap(); let (mut runner, mut results) = EffectRunner::new(connections.clone()); runner.execute(Effect::LoadListing(ListingRequest { pane: PaneId::Left, generation: 5, target: first.home.clone(), session_epoch: Some(first.epoch), })); runner.execute(Effect::LoadPreview(PreviewRequest { pane: PaneId::Right, generation: 6, target: Location::ssh(host.clone(), "/home/user/welcome.txt"), session_epoch: Some(first.epoch), images_enabled: true, })); let (listing, preview) = receive_listing_and_preview(&mut results).await; assert_eq!(listing.result, Err(FsError::Disconnected)); assert_eq!(preview.result, Err(FsError::Disconnected)); assert_eq!( connections.current(&host).await.unwrap().epoch, reconnected.epoch ); assert!(connections.registry().backend(&reconnected.home).is_ok()); assert!( connections .resolve(&reconnected.home, Some(reconnected.epoch)) .await .is_ok() ); } #[tokio::test] async fn slow_local_listings_keep_only_the_latest_task_running() { let stats = Arc::new(OperationStats::default()); let fs = Arc::new(SlowListingFs { inner: MemoryFs::navigation_fixture(), stats: stats.clone(), }); exercise_listing_stress( local_manager(fs), Location::local("/workspace"), None, stats, ) .await; } #[tokio::test] async fn slow_remote_listings_keep_only_the_latest_task_running() { let stats = Arc::new(OperationStats::default()); let backend: Arc = Arc::new(SlowListingFs { inner: MemoryFs::navigation_fixture(), stats: stats.clone(), }); let connections = ConnectionManager::new( Arc::new(SequenceConnector { backends: Mutex::new(VecDeque::from([backend])), }), BackendRegistry::new(Arc::new(MemoryFs::navigation_fixture())), ); let host = HostAlias::new("edge"); let connection = connections.connect(&host).await.unwrap(); exercise_listing_stress( connections, connection.home.clone(), Some(connection.epoch), stats, ) .await; } #[tokio::test] async fn slow_connects_keep_only_the_latest_task_running() { const OPERATIONS: u64 = 32; let stats = Arc::new(OperationStats::default()); let connections = ConnectionManager::new( Arc::new(BlockingConnector { backend: MemoryFs::navigation_fixture(), stats: stats.clone(), }), BackendRegistry::new(Arc::new(MemoryFs::navigation_fixture())), ); let (mut runner, mut results) = EffectRunner::new(connections); for generation in 1..=OPERATIONS { runner.execute(Effect::ConnectSsh(ConnectSshRequest { pane: PaneId::Right, generation, host: HostAlias::new("edge"), expected_session_epoch: None, })); stats.wait_for_started(generation as usize).await; stats.wait_for_active(1).await; assert_eq!(stats.finished.load(Ordering::SeqCst), 0); assert!(results.try_recv().is_err(), "superseded connect returned"); } stats.release.add_permits(1); let Command::SynchronizeSshEpoch { session_epoch, .. } = next_command(&mut results).await else { panic!("expected latest epoch synchronization"); }; assert!(session_epoch > 0); let Command::ConnectSshFinished(result) = next_command(&mut results).await else { panic!("expected latest connect result"); }; assert_eq!(result.generation, OPERATIONS); assert!(result.result.is_ok()); stats.wait_for_active(0).await; assert_eq!(stats.started.load(Ordering::SeqCst), OPERATIONS as usize); assert_eq!(stats.finished.load(Ordering::SeqCst), 1); assert_eq!(stats.max_active.load(Ordering::SeqCst), 1); assert!(results.try_recv().is_err(), "old connect returned late"); } #[tokio::test] async fn listing_and_connect_abort_each_other_within_a_pane() { let listing_stats = Arc::new(OperationStats::default()); let connect_stats = Arc::new(OperationStats::default()); let connections = ConnectionManager::new( Arc::new(BlockingConnector { backend: MemoryFs::navigation_fixture(), stats: connect_stats.clone(), }), BackendRegistry::new(Arc::new(SlowListingFs { inner: MemoryFs::navigation_fixture(), stats: listing_stats.clone(), })), ); let (mut runner, mut results) = EffectRunner::new(connections); let listing = |generation| { Effect::LoadListing(ListingRequest { pane: PaneId::Left, generation, target: Location::local("/workspace"), session_epoch: None, }) }; runner.execute(listing(1)); listing_stats.wait_for_started(1).await; runner.execute(Effect::ConnectSsh(ConnectSshRequest { pane: PaneId::Left, generation: 2, host: HostAlias::new("edge"), expected_session_epoch: None, })); connect_stats.wait_for_started(1).await; listing_stats.wait_for_active(0).await; runner.execute(listing(3)); listing_stats.wait_for_started(2).await; connect_stats.wait_for_active(0).await; listing_stats.release.add_permits(1); let Command::ListingFinished(result) = next_command(&mut results).await else { panic!("expected replacement listing result"); }; assert_eq!(result.generation, 3); assert!(result.result.is_ok()); assert_eq!(listing_stats.finished.load(Ordering::SeqCst), 1); assert_eq!(connect_stats.finished.load(Ordering::SeqCst), 0); assert!(results.try_recv().is_err(), "cancelled navigation returned"); } #[tokio::test] async fn dropping_runner_aborts_all_listing_connect_and_preview_tasks() { let fs_stats = Arc::new(OperationStats::default()); let connect_stats = Arc::new(OperationStats::default()); let connections = ConnectionManager::new( Arc::new(BlockingConnector { backend: MemoryFs::navigation_fixture(), stats: connect_stats.clone(), }), BackendRegistry::new(Arc::new(SlowListingFs { inner: MemoryFs::navigation_fixture(), stats: fs_stats.clone(), })), ); let (mut runner, mut results) = EffectRunner::new(connections); runner.execute(Effect::LoadListing(ListingRequest { pane: PaneId::Left, generation: 1, target: Location::local("/workspace"), session_epoch: None, })); runner.execute(Effect::ConnectSsh(ConnectSshRequest { pane: PaneId::Right, generation: 2, host: HostAlias::new("edge"), expected_session_epoch: None, })); runner.execute(Effect::LoadPreview(PreviewRequest { pane: PaneId::Left, generation: 3, target: Location::local("/workspace/readme.txt"), session_epoch: None, images_enabled: true, })); fs_stats.wait_for_started(2).await; connect_stats.wait_for_started(1).await; fs_stats.wait_for_active(2).await; connect_stats.wait_for_active(1).await; drop(runner); fs_stats.wait_for_active(0).await; connect_stats.wait_for_active(0).await; assert_eq!(fs_stats.finished.load(Ordering::SeqCst), 0); assert_eq!(connect_stats.finished.load(Ordering::SeqCst), 0); assert!(results.try_recv().is_err(), "dropped task returned late"); } #[tokio::test] async fn failed_home_listing_retry_resolves_with_the_new_epoch() { let host = HostAlias::new("edge"); let home = Location::ssh(host.clone(), "/"); let connections = ConnectionManager::new( Arc::new(MemoryConnector { fs: MemoryFs::navigation_fixture(), }), BackendRegistry::new(Arc::new(MemoryFs::navigation_fixture())), ); let first = connections.connect(&host).await.unwrap(); let mut app = AppState::new(home.clone()); app.reduce(Command::TogglePaneMode); let initial_connect = app.reduce(Command::ConnectSsh(host.clone())); let initial_connect: [Effect; 1] = initial_connect.try_into().unwrap(); let [Effect::ConnectSsh(initial_request)] = initial_connect else { panic!("initial connect effect expected"); }; let initial_effects = app.reduce(Command::ConnectSshFinished(initial_request.into_result( Ok(SshConnection { location: home.clone(), session_epoch: first.epoch, }), ))); let initial_effects: [Effect; 1] = initial_effects.try_into().unwrap(); let [Effect::LoadListing(initial_listing)] = initial_effects else { panic!("initial home listing expected"); }; app.reduce(Command::ListingFinished( initial_listing.into_result(Ok(Vec::new())), )); connections.invalidate_if_epoch(&host, first.epoch).await; let second = connections.connect(&host).await.unwrap(); assert!(second.epoch > first.epoch); app.reduce(Command::SynchronizeSshEpoch { host: host.clone(), session_epoch: second.epoch, }); let reconnect = app.reduce(Command::ConnectSsh(host.clone())); let reconnect: [Effect; 1] = reconnect.try_into().unwrap(); let [Effect::ConnectSsh(reconnect)] = reconnect else { panic!("reconnect effect expected"); }; let effects = app.reduce(Command::ConnectSshFinished(reconnect.into_result(Ok( SshConnection { location: home.clone(), session_epoch: second.epoch, }, )))); let effects: [Effect; 1] = effects.try_into().unwrap(); let [Effect::LoadListing(home_listing)] = effects else { panic!("replacement home listing expected"); }; app.reduce(Command::ListingFinished( home_listing.into_result(Err(FsError::PermissionDenied)), )); assert_eq!(app.pane(PaneId::Left).location, home); assert_eq!(app.pane(PaneId::Left).session_epoch, Some(second.epoch)); assert_eq!(app.pane(PaneId::Right).session_epoch, Some(second.epoch)); let retry_effects = app.reduce(Command::Refresh); let retry_effects: [Effect; 1] = retry_effects.try_into().unwrap(); let [Effect::LoadListing(retry)] = retry_effects else { panic!("retry listing expected"); }; assert_eq!(retry.target, home); assert_eq!(retry.session_epoch, Some(second.epoch)); assert!( connections .resolve(&retry.target, retry.session_epoch) .await .is_ok() ); } struct DisconnectOnceConnector { backend: Arc, } #[async_trait] impl SshConnector for DisconnectOnceConnector { async fn connect(&self, _host: &HostAlias) -> Result, FsError> { Ok(self.backend.clone()) } } #[tokio::test] async fn disconnect_invalidates_current_handle_before_reconnect() { let backend = Arc::new(FaultInjectFs::new(Arc::new(MemoryFs::navigation_fixture()))); backend.fail_next(FsOperation::List, FsError::Disconnected); let host = HostAlias::new("edge"); let connections = ConnectionManager::new( Arc::new(DisconnectOnceConnector { backend }), BackendRegistry::new(Arc::new(MemoryFs::navigation_fixture())), ); let first = connections.connect(&host).await.unwrap(); let (mut runner, mut results) = EffectRunner::new(connections.clone()); runner.execute(Effect::LoadListing(ListingRequest { pane: PaneId::Left, generation: 1, target: first.home.clone(), session_epoch: Some(first.epoch), })); let Command::ListingFinished(result) = next_command(&mut results).await else { panic!("disconnect result expected"); }; assert_eq!(result.result, Err(FsError::Disconnected)); assert!(connections.current(&host).await.is_none()); let second = connections.connect(&host).await.unwrap(); assert!(second.epoch > first.epoch); assert!( connections .resolve(&second.home, Some(second.epoch)) .await .is_ok() ); }