crates/brain/src/session/worker.rs 8.2 KiB raw
1
//! Serialized repository I/O for the interactive session.
2
//!
3
//! All repository and filesystem I/O initiated by the UI must be represented by
4
//! a [`Command`] and executed here. Keeping the backend and writable review state
5
//! in this worker makes blocking the terminal event loop difficult by construction.
6
7
use std::collections::BTreeMap;
8
use std::sync::mpsc::{self, Sender};
9
use std::thread;
10
11
use rustik_diff::{DiffDocument, DiffOptions, DiffViewer, HunkId};
12
use rustik_repo::Oid;
13
14
use crate::backend::{Accepted, AcceptedHunk, Backend, Brain, Commit};
15
use crate::comments::ReviewComments;
16
17
use super::commit::{CommitReview, CommitSlot};
18
use super::event::TerminalEvent;
19
use super::{HistoryStatus, reviewed_slots};
20
21
/// One review-state mutation executed by the repository worker.
22
pub(super) enum ReviewMutation {
23
    /// Replaces the exact accepted-hunk state.
24
    SetAccepted(Accepted),
25
    /// Toggles one commit's rejected decision.
26
    ToggleRejected {
27
        /// Commit whose decision changes.
28
        commit: Oid,
29
    },
30
    /// Toggles one commit's dropped decision.
31
    ToggleDropped {
32
        /// Commit whose decision changes.
33
        commit: Oid,
34
    },
35
}
36
37
/// Inputs needed to construct one commit viewer.
38
pub(super) struct LoadCommit {
39
    /// Session commit index.
40
    pub(super) index: usize,
41
    /// Commit metadata.
42
    pub(super) commit: Commit,
43
    /// Previously cached split document.
44
    pub(super) document: Option<DiffDocument>,
45
    /// Previously cached exact hunk identities.
46
    pub(super) identities: Option<BTreeMap<HunkId, AcceptedHunk>>,
47
    /// Viewer construction options.
48
    pub(super) options: DiffOptions,
49
    /// Review comments used to decorate the viewer.
50
    pub(super) comments: ReviewComments,
51
}
52
53
/// Blocking operation sent from the UI to the repository worker.
54
pub(super) enum Command {
55
    /// Loads and constructs one commit viewer.
56
    LoadCommit(Box<LoadCommit>),
57
    /// Loads history documents and aggregate status.
58
    LoadHistory {
59
        /// Commits to load, oldest first.
60
        commits: Vec<Commit>,
61
        /// Review comments used to count annotations per commit.
62
        comments: ReviewComments,
63
    },
64
    /// Loads file sources into a focused hunk viewer.
65
    LoadSources {
66
        /// Viewer awaiting file contents.
67
        viewer: Box<DiffViewer>,
68
        /// Hunk that owns the viewer.
69
        hunk: HunkId,
70
    },
71
    /// Persists one review-state mutation.
72
    Mutate(ReviewMutation),
73
    /// Persists one comment-store delta.
74
    WriteComments {
75
        /// Review-wide store before the local mutation.
76
        previous: ReviewComments,
77
        /// Review-wide store after the local mutation.
78
        updated: ReviewComments,
79
    },
80
    /// Stops the worker after all preceding commands.
81
    Shutdown,
82
}
83
84
/// State returned after one repository mutation.
85
pub(super) enum Persisted {
86
    /// Updated review decisions.
87
    Review(Box<Brain>),
88
    /// Updated review comments.
89
    Comments(ReviewComments),
90
}
91
92
/// Typed result returned to the terminal event loop.
93
pub(super) enum Output {
94
    /// One commit viewer finished loading.
95
    CommitLoaded {
96
        /// Session commit index.
97
        index: usize,
98
        /// Loaded viewer or its user-facing failure.
99
        result: Box<Result<CommitReview, String>>,
100
    },
101
    /// History state finished loading.
102
    HistoryLoaded(Box<Result<(Vec<CommitSlot>, HistoryStatus), String>>),
103
    /// Focused hunk sources finished loading.
104
    SourcesLoaded {
105
        /// Hunk that owns the viewer.
106
        hunk: HunkId,
107
        /// Populated viewer or its user-facing failure.
108
        result: Box<Result<DiffViewer, String>>,
109
    },
110
    /// A state mutation finished persisting.
111
    Persisted(Box<Result<Persisted, String>>),
112
}
113
114
/// Handle used by the UI to enqueue repository commands.
115
pub(super) struct Worker {
116
    /// Command sender owned by the terminal session.
117
    commands: Sender<Command>,
118
    /// Worker thread joined only after queued commands have completed.
119
    thread: Option<thread::JoinHandle<()>>,
120
}
121
122
impl Worker {
123
    /// Starts the serialized repository worker.
124
    pub(super) fn spawn(
125
        backend: Box<dyn Backend>,
126
        brain: Brain,
127
        events: Sender<TerminalEvent>,
128
    ) -> Self {
129
        let (commands, receiver) = mpsc::channel();
130
        let thread = thread::spawn(move || {
131
            let mut brain = brain;
132
            while let Ok(command) = receiver.recv() {
133
                let output = match command {
134
                    Command::LoadCommit(load) => {
135
                        let LoadCommit {
136
                            index,
137
                            commit,
138
                            document,
139
                            identities,
140
                            options,
141
                            comments,
142
                        } = *load;
143
                        let result = (|| {
144
                            let document = match document {
145
                                Some(document) => document,
146
                                None => backend.diff_document(commit.id)?.split_hunks(),
147
                            };
148
                            CommitReview::load(
149
                                &commit, document, identities, options, &brain, &comments,
150
                            )
151
                        })()
152
                        .map_err(|error| error.to_string());
153
                        Output::CommitLoaded {
154
                            index,
155
                            result: Box::new(result),
156
                        }
157
                    }
158
                    Command::LoadHistory { commits, comments } => {
159
                        let result = reviewed_slots(commits, &*backend, &brain, &comments)
160
                            .map_err(|error| error.to_string());
161
                        Output::HistoryLoaded(Box::new(result))
162
                    }
163
                    Command::LoadSources { viewer, hunk } => {
164
                        let mut viewer = *viewer;
165
                        let result = viewer
166
                            .load_file_sources(|oid| brain.read_blob(oid))
167
                            .map(|()| viewer)
168
                            .map_err(|error| error.to_string());
169
                        Output::SourcesLoaded {
170
                            hunk,
171
                            result: Box::new(result),
172
                        }
173
                    }
174
                    Command::Mutate(mutation) => {
175
                        let result = match mutation {
176
                            ReviewMutation::SetAccepted(accepted) => brain.set_accepted(accepted),
177
                            ReviewMutation::ToggleRejected { commit } => {
178
                                brain.toggle_commit_rejected(commit)
179
                            }
180
                            ReviewMutation::ToggleDropped { commit } => {
181
                                brain.toggle_commit_dropped(commit)
182
                            }
183
                        }
184
                        .map(|()| Persisted::Review(Box::new(brain.clone())))
185
                        .map_err(|error| error.to_string());
186
                        Output::Persisted(Box::new(result))
187
                    }
188
                    Command::WriteComments { previous, updated } => {
189
                        let result = brain
190
                            .merge_comments(&previous, &updated)
191
                            .map(Persisted::Comments)
192
                            .map_err(|error| error.to_string());
193
                        Output::Persisted(Box::new(result))
194
                    }
195
                    Command::Shutdown => break,
196
                };
197
                if events
198
                    .send(TerminalEvent::Worker(Box::new(output)))
199
                    .is_err()
200
                {
201
                    break;
202
                }
203
            }
204
        });
205
        Self {
206
            commands,
207
            thread: Some(thread),
208
        }
209
    }
210
211
    /// Enqueues one blocking operation without waiting for it.
212
    pub(super) fn send(&self, command: Command) -> Result<(), String> {
213
        self.commands
214
            .send(command)
215
            .map_err(|_| "repository worker stopped unexpectedly".to_owned())
216
    }
217
}
218
219
impl Drop for Worker {
220
    fn drop(&mut self) {
221
        let _ = self.commands.send(Command::Shutdown);
222
        if let Some(thread) = self.thread.take() {
223
            let _ = thread.join();
224
        }
225
    }
226
}