//! Flow control on the graph stream. //! //! A `Channel` can be built with a plain closure, so these run against the real //! streaming code with no webview involved — what the closure receives is //! exactly what would have crossed the IPC boundary. use std::sync::{Arc, Mutex}; use gigit_git::testing::Fixture; use gigit_lib::{RecentsHandle, RepositoryId, WorkspaceHandle}; use tauri::ipc::Channel; /// Collects everything sent down a channel, as parsed JSON. #[derive(Clone, Default)] struct Received(Arc>>); impl Received { fn channel(&self) -> Channel { let events = Arc::clone(&self.0); Channel::new(move |body| { let json = match body { tauri::ipc::InvokeResponseBody::Json(text) => { serde_json::from_str(&text).expect("events should be valid json") } tauri::ipc::InvokeResponseBody::Raw(bytes) => { serde_json::from_slice(&bytes).expect("events should be valid json") } }; events.lock().expect("not poisoned").push(json); Ok(()) }) } fn events(&self) -> Vec { self.0.lock().expect("not poisoned").clone() } /// Every row across every batch, in the order they arrived. fn rows(&self) -> Vec { self.events() .into_iter() .filter(|event| event["event"] == "rows") .flat_map(|event| { event["data"]["rows"] .as_array() .expect("rows should be an array") .clone() }) .collect() } fn is_exhausted(&self) -> bool { self.events() .iter() .any(|event| event["event"] == "exhausted") } } fn workspace() -> WorkspaceHandle { // These tests say nothing about recents, but the workspace needs somewhere // to record them. A throwaway path under the temp directory keeps them off // the developer's real config directory. let file = std::env::temp_dir().join(format!("gigit-test-recents-{}.json", std::process::id())); let (recents, remembering) = RecentsHandle::new(file); tokio::spawn(remembering); let (handle, actor) = WorkspaceHandle::new(recents); tokio::spawn(actor); handle } /// A repository with `count` commits on a single branch. fn history(count: usize) -> Fixture { let fixture = Fixture::with_one_commit(); for step in 2..=count { fixture.commit(&format!("commit {step}")); } fixture } async fn open(workspace: &WorkspaceHandle, fixture: &Fixture) -> RepositoryId { workspace .open(fixture.path().to_path_buf()) .await .expect("should open") .id } #[tokio::test] async fn the_initial_budget_arrives_without_being_asked_for() { // The point of pushing rather than answering: rows are on their way before // the frontend says anything more. let fixture = history(20); let workspace = workspace(); let id = open(&workspace, &fixture).await; let received = Received::default(); workspace .stream_graph(id, received.channel(), 5) .await .expect("should start streaming"); assert_eq!(received.rows().len(), 5); } #[tokio::test] async fn nothing_is_sent_beyond_the_budget() { // The whole point of the budget: a large history does not flood the // channel just because it exists. let fixture = history(50); let workspace = workspace(); let id = open(&workspace, &fixture).await; let received = Received::default(); workspace .stream_graph(id, received.channel(), 10) .await .expect("should start streaming"); assert_eq!(received.rows().len(), 10); assert!( !received.is_exhausted(), "there are forty more commits to come" ); } #[tokio::test] async fn topping_up_the_budget_sends_more() { let fixture = history(30); let workspace = workspace(); let id = open(&workspace, &fixture).await; let received = Received::default(); workspace .stream_graph(id.clone(), received.channel(), 10) .await .expect("should start streaming"); assert_eq!(received.rows().len(), 10); workspace .request_more_rows(id.clone(), 10) .await .expect("should send more"); assert_eq!(received.rows().len(), 20); workspace .request_more_rows(id, 10) .await .expect("should send the rest"); assert_eq!(received.rows().len(), 30); } #[tokio::test] async fn rows_arrive_in_order_and_only_once() { let fixture = history(25); let workspace = workspace(); let id = open(&workspace, &fixture).await; let received = Received::default(); workspace .stream_graph(id.clone(), received.channel(), 10) .await .expect("should start streaming"); workspace .request_more_rows(id, 20) .await .expect("should send more"); let indices: Vec = received .rows() .iter() .map(|row| row["row"].as_u64().expect("row should be a number")) .collect(); assert_eq!( indices, (0..25).collect::>(), "resuming a stream must not repeat or skip a row" ); } #[tokio::test] async fn each_batch_says_where_it_starts() { // So the frontend can place a batch without counting what it has seen. let fixture = history(15); let workspace = workspace(); let id = open(&workspace, &fixture).await; let received = Received::default(); workspace .stream_graph(id.clone(), received.channel(), 5) .await .expect("should start streaming"); workspace .request_more_rows(id, 5) .await .expect("should send more"); let starts: Vec = received .events() .iter() .filter(|event| event["event"] == "rows") .map(|event| event["data"]["start"].as_u64().expect("a number")) .collect(); assert_eq!(starts, vec![0, 5]); } #[tokio::test] async fn the_end_of_the_history_is_announced() { let fixture = history(5); let workspace = workspace(); let id = open(&workspace, &fixture).await; let received = Received::default(); // A budget larger than the history. workspace .stream_graph(id, received.channel(), 100) .await .expect("should start streaming"); assert_eq!(received.rows().len(), 5); let end = received .events() .into_iter() .find(|event| event["event"] == "exhausted") .expect("the frontend has to be told there is no more"); assert_eq!(end["data"]["total"], 5); assert_eq!(end["data"]["degraded"], false); } #[tokio::test] async fn asking_for_more_after_the_end_is_harmless() { let fixture = history(3); let workspace = workspace(); let id = open(&workspace, &fixture).await; let received = Received::default(); workspace .stream_graph(id.clone(), received.channel(), 100) .await .expect("should start streaming"); // The frontend may well have decided to scroll before the exhausted event // reached it, so this has to be a no-op rather than an error. workspace .request_more_rows(id, 50) .await .expect("should not fail"); assert_eq!(received.rows().len(), 3); } #[tokio::test] async fn a_second_stream_replaces_the_first() { let fixture = history(20); let workspace = workspace(); let id = open(&workspace, &fixture).await; let first = Received::default(); let second = Received::default(); workspace .stream_graph(id.clone(), first.channel(), 5) .await .expect("should start streaming"); workspace .stream_graph(id.clone(), second.channel(), 5) .await .expect("should restart streaming"); // Topping up now feeds the new stream only. workspace .request_more_rows(id, 5) .await .expect("should send more"); assert_eq!(first.rows().len(), 5, "the replaced stream stopped"); assert_eq!(second.rows().len(), 10, "the new stream carried on"); } #[tokio::test] async fn a_restarted_stream_begins_again_from_the_top() { let fixture = history(10); let workspace = workspace(); let id = open(&workspace, &fixture).await; let first = Received::default(); workspace .stream_graph(id.clone(), first.channel(), 4) .await .expect("should start streaming"); let second = Received::default(); workspace .stream_graph(id, second.channel(), 4) .await .expect("should restart streaming"); let indices: Vec = second .rows() .iter() .map(|row| row["row"].as_u64().expect("a number")) .collect(); assert_eq!(indices, vec![0, 1, 2, 3], "a fresh stream is a fresh walk"); } #[tokio::test] async fn an_empty_repository_streams_nothing_and_says_so() { let fixture = Fixture::empty(); let workspace = workspace(); let id = open(&workspace, &fixture).await; let received = Received::default(); workspace .stream_graph(id, received.channel(), 50) .await .expect("should start streaming"); assert!(received.rows().is_empty()); assert!(received.is_exhausted()); } #[tokio::test] async fn streaming_a_closed_repository_fails_cleanly() { let fixture = history(5); let workspace = workspace(); let id = open(&workspace, &fixture).await; let received = Received::default(); workspace.close(id.clone()).await.expect("should close"); workspace .stream_graph(id, received.channel(), 10) .await .expect_err("a closed repository has nothing to stream"); assert!(received.events().is_empty()); } #[tokio::test] async fn the_graph_rows_carry_what_the_frontend_needs_to_draw() { let fixture = Fixture::with_one_commit(); fixture.branch_off("side"); fixture.commit("on the side"); fixture.checkout("main"); fixture.commit("on main"); fixture.merge(&["side"]); let workspace = workspace(); let id = open(&workspace, &fixture).await; let received = Received::default(); workspace .stream_graph(id, received.channel(), 50) .await .expect("should start streaming"); let rows = received.rows(); let merge = &rows[0]; // Field names cross as camelCase, which is what the TypeScript expects. assert!(merge["id"].is_string()); assert_eq!(merge["dot"], "merge"); assert!(merge["column"].is_number()); assert!(merge["lane"].is_number()); assert!(merge["width"].is_number()); assert!(merge["edges"].is_array()); assert!(merge["refs"].is_array()); assert!(merge["summary"].is_string()); let edge = &merge["edges"][0]; assert!(edge["fromColumn"].is_number(), "got {edge}"); assert!(edge["toColumn"].is_number()); assert!(edge["kind"].is_string()); }