Skip to main content

verctl_core/
stop.rs

1//! The stop record a failed `release` run writes into its draft Release.
2//!
3//! When a registry upload fails, the run appends one HTML comment line to the
4//! draft's body, so the rendered page does not show it:
5//!
6//! ```text
7//! <!-- verctl:stop {"package":"shrub-process","version":"0.7.0","cause":"429 Too Many Requests","retry_after":"Fri, 13 Nov 2026 19:00:00 GMT"} -->
8//! ```
9//!
10//! `status` reads it from the draft it already looks up. Anyone who can edit
11//! the draft can edit the record, so it is display only: no decision reads
12//! it, and what is live always comes from the registry. Publishing the draft
13//! writes the notes alone, which drops the record.
14
15use anyhow::{Context, Result};
16use ctl_core::formatdoc;
17use serde::{Deserialize, Serialize};
18
19/// What opens a stop record's line.
20const OPEN: &str = "<!-- verctl:stop ";
21
22/// What closes a stop record's line.
23const CLOSE: &str = " -->";
24
25/// Why the last `release` run stopped, as it reported it.
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27#[serde(deny_unknown_fields)]
28#[non_exhaustive]
29pub struct Stop {
30    /// The package whose upload failed, such as a workspace member.
31    pub package: String,
32    /// The version it was uploading.
33    pub version: String,
34    /// What stopped it: `429 Too Many Requests` for a registry rate limit,
35    /// or the first line of the error otherwise.
36    pub cause: String,
37    /// The time the registry gave for the next attempt, as it wrote it.
38    /// `None` when it gave none.
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub retry_after: Option<String>,
41}
42
43impl Stop {
44    /// A stop of `package` at `version` for `cause`.
45    #[must_use]
46    pub fn new(package: &str, version: &str, cause: &str, retry_after: Option<String>) -> Self {
47        Self {
48            package: package.to_owned(),
49            version: version.to_owned(),
50            cause: cause.to_owned(),
51            retry_after,
52        }
53    }
54}
55
56/// The stop record a Release body contains.
57///
58/// Not `#[non_exhaustive]`: the binary prints each state, and an exhaustive
59/// match makes a new variant fail the build until it is printed.
60#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
61#[serde(tag = "state", rename_all = "kebab-case")]
62pub enum Record {
63    /// The body contains no record.
64    #[default]
65    Absent,
66    /// The record parsed.
67    Read(Stop),
68    /// A `verctl:stop` comment is there but does not parse. It is never
69    /// trusted in part.
70    Unreadable,
71}
72
73/// The stop record in `body`: the first `verctl:stop` line.
74#[must_use]
75pub fn read(body: &str) -> Record {
76    let Some(line) = body.lines().map(str::trim).find(|line| is_record(line)) else {
77        return Record::Absent;
78    };
79    line.strip_prefix(OPEN)
80        .and_then(|rest| rest.strip_suffix(CLOSE))
81        .and_then(|json| serde_json::from_str(json).ok())
82        .map_or(Record::Unreadable, Record::Read)
83}
84
85/// `body` with its stop records replaced by one for `stop`, on its own line
86/// after the notes.
87///
88/// `-->` inside a value is written as `--\u003e`, which JSON reads back the
89/// same, so a cause cannot end the comment early.
90///
91/// # Errors
92///
93/// Returns an error when `stop` cannot be encoded as JSON.
94pub fn write(body: &str, stop: &Stop) -> Result<String> {
95    let json = serde_json::to_string(stop)
96        .context("encode the stop record")?
97        .replace("-->", "--\\u003e");
98    let notes = body
99        .lines()
100        .filter(|line| !is_record(line.trim()))
101        .collect::<Vec<_>>()
102        .join("\n");
103    Ok(formatdoc! {"
104        {notes}
105
106        {OPEN}{json}{CLOSE}
107        ",
108        notes = notes.trim_end(),
109    })
110}
111
112fn is_record(line: &str) -> bool {
113    line.starts_with(OPEN.trim_end())
114}
115
116#[cfg(test)]
117mod tests {
118    use indoc::indoc;
119
120    use super::{Record, Stop, read, write};
121
122    fn limited() -> Stop {
123        Stop::new(
124            "shrub-process",
125            "0.7.0",
126            "429 Too Many Requests",
127            Some("Fri, 13 Nov 2026 19:00:00 GMT".to_owned()),
128        )
129    }
130
131    #[test]
132    fn a_record_reads_back_as_written() {
133        let notes = indoc! {"
134            ## shrub 0.7.0
135
136            - Notes.
137        "};
138        let body = write(notes, &limited()).unwrap();
139        assert_eq!(
140            body,
141            indoc! {r#"
142                ## shrub 0.7.0
143
144                - Notes.
145
146                <!-- verctl:stop {"package":"shrub-process","version":"0.7.0","cause":"429 Too Many Requests","retry_after":"Fri, 13 Nov 2026 19:00:00 GMT"} -->
147            "#}
148        );
149        assert_eq!(read(&body), Record::Read(limited()));
150    }
151
152    #[test]
153    fn an_unknown_field_is_unreadable() {
154        let body = indoc! {r#"
155            - Notes.
156
157            <!-- verctl:stop {"package":"a","version":"1.0.0","cause":"x","extra":true} -->
158        "#};
159        assert_eq!(read(body), Record::Unreadable);
160    }
161
162    #[test]
163    fn a_comment_that_is_not_json_is_unreadable() {
164        assert_eq!(read("<!-- verctl:stop not json -->"), Record::Unreadable);
165        assert_eq!(read("<!-- verctl:stop"), Record::Unreadable);
166    }
167
168    #[test]
169    fn a_body_with_no_record_has_none() {
170        let body = indoc! {"
171            ## demo 1.0.0
172
173            <!-- a comment -->
174        "};
175        assert_eq!(read(body), Record::Absent);
176    }
177
178    #[test]
179    fn writing_a_record_twice_keeps_one() {
180        let first = write("- Notes.", &Stop::new("a", "1.0.0", "exit 1", None)).unwrap();
181        let second = write(&first, &limited()).unwrap();
182        assert_eq!(second.matches("verctl:stop").count(), 1, "{second}");
183        assert!(second.starts_with("- Notes."), "{second}");
184        assert_eq!(read(&second), Record::Read(limited()));
185    }
186
187    #[test]
188    fn a_cause_cannot_close_the_comment() {
189        let stop = Stop::new("a", "1.0.0", "saw --> here", None);
190        let body = write("", &stop).unwrap();
191        assert_eq!(body.matches("-->").count(), 1, "{body}");
192        assert_eq!(read(&body), Record::Read(stop));
193    }
194}