Skip to main content

artifactize_core/review/
draft.rs

1//! A single draft holds the reviewer's issues, the verdict chosen and the places a reviewer
2//! pointed at.
3use std::path::Path;
4
5use serde::{Deserialize, Serialize};
6
7use crate::{
8    human::{self, GREEN_WITH_ISSUES, RED_WITHOUT_ISSUE},
9    runtime::Verdict,
10    store::Receipts,
11    types::{RequestId, ReviewerId, Timestamp},
12};
13
14#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "camelCase")]
16pub struct Draft {
17    pub verdict: Option<Verdict>,
18    /// What must change, oldest first.
19    #[serde(default)]
20    pub issues: Vec<String>,
21    #[serde(default)]
22    pub points: Vec<Point>,
23}
24
25/// A location recorded alongside the draft, not part of the verdict's answer.
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Point {
28    pub text: String,
29    pub source: String,
30    pub at: Timestamp,
31}
32
33impl Point {
34    pub(crate) fn earlier_notes(text: String) -> Self {
35        // Drafts used to have no timestamp. The epoch denotes an unknown original time.
36        Self {
37            text,
38            source: "Earlier notes".into(),
39            at: Timestamp::new(time::OffsetDateTime::UNIX_EPOCH).expect("epoch is sortable"),
40        }
41    }
42}
43
44/// Whether a verdict can be submitted, or the sentence saying what is missing.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub enum Readiness {
47    Ready,
48    Blocked(String),
49}
50
51/// Changes are applied to the saved draft, not a caller's potentially stale snapshot.
52#[derive(Debug, Clone, Serialize, Deserialize)]
53#[serde(tag = "kind", rename_all = "camelCase")]
54pub enum DraftEdit {
55    Verdict {
56        verdict: Verdict,
57    },
58    AddIssue {
59        text: String,
60    },
61    /// Refused if issue `index` is no longer `previous`.
62    EditIssue {
63        index: u32,
64        previous: String,
65        text: String,
66    },
67    /// Refused if issue `index` is no longer `previous`.
68    RemoveIssue {
69        index: u32,
70        previous: String,
71    },
72}
73
74/// The refusal for an issue without text.
75pub const EMPTY_ISSUE: &str = "An issue needs text; remove it instead.";
76/// The refusal for changing an issue another surface changed first.
77pub const ISSUE_CHANGED: &str = "This issue changed; reload the review draft.";
78
79impl DraftEdit {
80    /// Refuse an edit that is invalid whatever the saved draft holds.
81    pub fn check(&self) -> Result<(), String> {
82        match self {
83            Self::AddIssue { text } | Self::EditIssue { text, .. } if text.trim().is_empty() => {
84                Err(EMPTY_ISSUE.into())
85            }
86            _ => Ok(()),
87        }
88    }
89}
90
91impl Draft {
92    /// Whether `verdict` can be submitted now: RED with an issue, GREEN without one.
93    pub fn readiness(&self, verdict: Verdict) -> Readiness {
94        match (verdict, self.issues.is_empty()) {
95            (Verdict::Red, true) => Readiness::Blocked(RED_WITHOUT_ISSUE.into()),
96            (Verdict::Green, false) => Readiness::Blocked(GREEN_WITH_ISSUES.into()),
97            _ => Readiness::Ready,
98        }
99    }
100
101    pub(crate) fn submission(&self) -> Result<super::Submission, String> {
102        let verdict = self
103            .verdict
104            .ok_or("Choose GREEN or RED before submitting.")?;
105        super::Submission::new(verdict, self.issues.clone())
106    }
107
108    /// Points can keep changing until settlement; a different answer must be submitted again.
109    pub(crate) fn same_answer(&self, other: &Self) -> bool {
110        self.verdict == other.verdict && self.issues == other.issues
111    }
112
113    pub fn edit(&mut self, edit: DraftEdit) -> Result<(), String> {
114        edit.check()?;
115        match edit {
116            DraftEdit::Verdict { verdict } => self.verdict = Some(verdict),
117            DraftEdit::AddIssue { text } => self.issues.push(text),
118            DraftEdit::EditIssue {
119                index,
120                previous,
121                text,
122            } => *self.issue(index, &previous)? = text,
123            DraftEdit::RemoveIssue { index, previous } => {
124                self.issue(index, &previous)?;
125                self.issues.remove(index as usize);
126            }
127        }
128        Ok(())
129    }
130
131    /// Issue `index`, if it still reads `previous`.
132    fn issue(&mut self, index: u32, previous: &str) -> Result<&mut String, String> {
133        self.issues
134            .get_mut(index as usize)
135            .filter(|issue| *issue == previous)
136            .ok_or_else(|| ISSUE_CHANGED.into())
137    }
138}
139
140/// Read this reviewer's draft, including while the review is released.
141pub async fn read_draft(
142    state: &Path,
143    request: &RequestId,
144    reviewer: &ReviewerId,
145) -> Result<Option<Draft>, String> {
146    with_receipts(state, request, async |receipts| {
147        receipts.read_review_draft(request, reviewer).await
148    })
149    .await
150}
151
152/// Apply an edit atomically, only while `reviewer` holds the active review.
153pub async fn edit_draft(
154    state: &Path,
155    request: &RequestId,
156    reviewer: &ReviewerId,
157    edit: DraftEdit,
158) -> Result<Draft, String> {
159    with_receipts(state, request, async |receipts| {
160        receipts
161            .change_review_draft(request, reviewer, |_, draft| draft.edit(edit))
162            .await
163    })
164    .await
165}
166
167/// Record one Point. The append and claim check share a write transaction.
168pub async fn append_point(
169    state: &Path,
170    request: &RequestId,
171    reviewer: &ReviewerId,
172    text: &str,
173    source: &str,
174) -> Result<Draft, String> {
175    if text.trim().is_empty() || source.trim().is_empty() {
176        return Err("A review point needs text and a source.".into());
177    }
178    let text = text.to_owned();
179    let source = source.to_owned();
180    with_receipts(state, request, async |receipts| {
181        receipts
182            .change_review_draft(request, reviewer, move |_, draft| {
183                draft.points.push(Point {
184                    text,
185                    source,
186                    at: Timestamp::now(),
187                });
188                Ok(())
189            })
190            .await
191    })
192    .await
193}
194
195/// Remove the point the caller saw, not whichever point now occupies its old position.
196pub async fn remove_point(
197    state: &Path,
198    request: &RequestId,
199    reviewer: &ReviewerId,
200    point: Point,
201) -> Result<Draft, String> {
202    with_receipts(state, request, async |receipts| {
203        receipts
204            .change_review_draft(request, reviewer, move |_, draft| {
205                let index = draft
206                    .points
207                    .iter()
208                    .position(|saved| *saved == point)
209                    .ok_or("This point is no longer in the review draft.")?;
210                draft.points.remove(index);
211                Ok(())
212            })
213            .await
214    })
215    .await
216}
217
218async fn with_receipts<T>(
219    state: &Path,
220    request: &RequestId,
221    work: impl AsyncFnOnce(&Receipts) -> Result<T, String>,
222) -> Result<T, String> {
223    let (receipts, _) = human::open(state, request).await?;
224    let result = work(&receipts).await;
225    let closed = receipts.close().await;
226    result.and_then(|value| closed.map(|()| value))
227}
228
229#[cfg(test)]
230mod tests;