//! Serialized repository I/O for the interactive session. //! //! All repository and filesystem I/O initiated by the UI must be represented by //! a [`Command`] and executed here. Keeping the backend and writable review state //! in this worker makes blocking the terminal event loop difficult by construction. use std::collections::{BTreeMap, BTreeSet}; use std::sync::mpsc::{self, Sender}; use std::thread; use rustik_diff::{DiffDocument, DiffOptions, DiffViewer, HunkId}; use rustik_repo::Oid; use crate::backend::{AcceptedHunk, Backend, Brain, Commit, FilePatches}; use crate::comments::ReviewComments; use super::commit::{CommitReview, CommitSlot}; use super::event::TerminalEvent; use super::{HistoryStatus, reviewed_slots}; /// One review-state mutation executed by the repository worker. pub(super) enum ReviewMutation { /// Accepts exact hunk identities and projects their patches. Accept { /// Identities being accepted. identities: Vec, /// File patches used to update the projected tree. patches: Vec, }, /// Rejects exact hunk identities and rebuilds their projected files. Reject { /// Identities being rejected. identities: BTreeSet, /// File patches used to update the projected tree. patches: Vec, }, /// Toggles one commit's rejected decision. ToggleRejected { /// Commit whose decision changes. commit: Oid, }, /// Toggles one commit's dropped decision. ToggleDropped { /// Commit whose decision changes. commit: Oid, }, } /// Inputs needed to construct one commit viewer. pub(super) struct LoadCommit { /// Session commit index. pub(super) index: usize, /// Commit metadata. pub(super) commit: Commit, /// Previously cached split document. pub(super) document: Option, /// Previously cached exact hunk identities. pub(super) identities: Option>, /// Viewer construction options. pub(super) options: DiffOptions, /// Review comments used to decorate the viewer. pub(super) comments: ReviewComments, } /// Blocking operation sent from the UI to the repository worker. pub(super) enum Command { /// Loads and constructs one commit viewer. LoadCommit(Box), /// Loads history documents and aggregate status. LoadHistory { /// Commits to load, oldest first. commits: Vec, /// Review comments used to count annotations per commit. comments: ReviewComments, }, /// Loads file sources into a focused hunk viewer. LoadSources { /// Viewer awaiting file contents. viewer: Box, /// Hunk that owns the viewer. hunk: HunkId, }, /// Persists one review-state mutation. Mutate(ReviewMutation), /// Persists the complete encoded comment store. WriteComments { /// Encoded JSONL comment data. encoded: String, }, /// Stops the worker after all preceding commands. Shutdown, } /// Typed result returned to the terminal event loop. pub(super) enum Output { /// One commit viewer finished loading. CommitLoaded { /// Session commit index. index: usize, /// Loaded viewer or its user-facing failure. result: Box>, }, /// History state finished loading. HistoryLoaded(Box, HistoryStatus), String>>), /// Focused hunk sources finished loading. SourcesLoaded { /// Hunk that owns the viewer. hunk: HunkId, /// Populated viewer or its user-facing failure. result: Box>, }, /// A state mutation finished persisting. Persisted(Box, String>>), } /// Handle used by the UI to enqueue repository commands. pub(super) struct Worker { /// Command sender owned by the terminal session. commands: Sender, /// Worker thread joined only after queued commands have completed. thread: Option>, } impl Worker { /// Starts the serialized repository worker. pub(super) fn spawn( backend: Box, brain: Brain, events: Sender, ) -> Self { let (commands, receiver) = mpsc::channel(); let thread = thread::spawn(move || { let mut brain = brain; while let Ok(command) = receiver.recv() { let output = match command { Command::LoadCommit(load) => { let LoadCommit { index, commit, document, identities, options, comments, } = *load; let result = (|| { let document = match document { Some(document) => document, None => backend.diff_document(commit.id)?.split_hunks(), }; CommitReview::load( &commit, document, identities, options, &brain, &comments, ) })() .map_err(|error| error.to_string()); Output::CommitLoaded { index, result: Box::new(result), } } Command::LoadHistory { commits, comments } => { let result = reviewed_slots(commits, &*backend, &brain, &comments) .map_err(|error| error.to_string()); Output::HistoryLoaded(Box::new(result)) } Command::LoadSources { viewer, hunk } => { let mut viewer = *viewer; let result = viewer .load_file_sources(|oid| brain.read_blob(oid)) .map(|()| viewer) .map_err(|error| error.to_string()); Output::SourcesLoaded { hunk, result: Box::new(result), } } Command::Mutate(mutation) => { let result = match mutation { ReviewMutation::Accept { identities, patches, } => brain.accept(identities, patches), ReviewMutation::Reject { identities, patches, } => brain.reject(&identities, patches), ReviewMutation::ToggleRejected { commit } => { brain.toggle_commit_rejected(commit) } ReviewMutation::ToggleDropped { commit } => { brain.toggle_commit_dropped(commit) } } .map(|()| Some(brain.clone())) .map_err(|error| error.to_string()); Output::Persisted(Box::new(result)) } Command::WriteComments { encoded } => { let result = brain .write_comments(&encoded) .map(|()| None) .map_err(|error| error.to_string()); Output::Persisted(Box::new(result)) } Command::Shutdown => break, }; if events .send(TerminalEvent::Worker(Box::new(output))) .is_err() { break; } } }); Self { commands, thread: Some(thread), } } /// Enqueues one blocking operation without waiting for it. pub(super) fn send(&self, command: Command) -> Result<(), String> { self.commands .send(command) .map_err(|_| "repository worker stopped unexpectedly".to_owned()) } } impl Drop for Worker { fn drop(&mut self) { let _ = self.commands.send(Command::Shutdown); if let Some(thread) = self.thread.take() { let _ = thread.join(); } } }