Skip to main content

subspace_contracts/
issues.rs

1//! The `issues` contract: recognising issue references in text and resolving
2//! them to short summaries, between a board that holds an issue tracker
3//! session (the responder) and boards that show text mentioning issues.
4//!
5//! The responder answers both requests at once from memory. A reference it
6//! has not resolved yet is [`ResolutionState::Pending`]: the responder starts
7//! the read itself and publishes [`Changed`] when it lands. It also publishes
8//! [`Changed`] when it starts and stops, and whenever the scope changes
9//! (availability, API origin or project keys). Subscribers keep nothing
10//! across a [`Changed`]: they ask again for the scope and for the references
11//! they show. When no board responds, as when the Issues board is disabled,
12//! both requests are unavailable and references show as plain text.
13//!
14//! Summaries are issue content, so these types do not implement `Debug`:
15//! nothing logs them by accident. No message carries credentials.
16
17pub mod recognition;
18
19use crate::{Contract, Event, Request};
20
21pub struct Issues;
22
23impl Contract for Issues {
24    const NAME: &'static str = "issues";
25    const VERSION: u32 = 1;
26}
27
28/// At most this many identifiers in one [`Resolve`], as in a batch read.
29pub const MAX_RESOLVE: usize = 50;
30
31/// The scope changed or pending resolutions finished: ask again.
32#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
33pub struct Changed;
34
35impl Event for Changed {
36    type Contract = Issues;
37    const NAME: &'static str = "changed";
38}
39
40/// Asks for the scope in which issue references are recognised now. The
41/// answer is `None` while the responder is unavailable, and then nothing is
42/// recognised.
43#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
44pub struct CurrentScope;
45
46impl Request for CurrentScope {
47    type Contract = Issues;
48    const NAME: &'static str = "current-scope";
49    type Response = Option<IssueScope>;
50}
51
52/// The profile, API origin and project keys used to resolve references.
53#[derive(Clone, PartialEq, Eq)]
54#[non_exhaustive]
55pub struct IssueScope {
56    pub profile_id: String,
57    pub profile_name: String,
58    pub api_origin: String,
59    /// Loaded project keys, including archived projects.
60    pub project_keys: Vec<String>,
61}
62
63impl IssueScope {
64    pub fn new(profile_id: &str, profile_name: &str, api_origin: &str) -> Self {
65        Self {
66            profile_id: profile_id.into(),
67            profile_name: profile_name.into(),
68            api_origin: api_origin.into(),
69            project_keys: Vec::new(),
70        }
71    }
72
73    pub fn with_project_keys(mut self, keys: impl IntoIterator<Item = impl Into<String>>) -> Self {
74        self.project_keys = keys.into_iter().map(Into::into).collect();
75        self
76    }
77
78    /// Bind a navigation URL to the profile and API that resolved it.
79    // qual:api - Consumed by app crates through the Framework facade.
80    pub fn navigation_url(&self, url: &str) -> Option<String> {
81        let (mut url, _) = self.parse_issue_url(url)?;
82        url.query_pairs_mut()
83            .clear()
84            .append_pair("profile", &self.profile_id);
85        Some(url.into())
86    }
87
88    /// Read a navigation target only within this exact API and profile scope.
89    // qual:api - Consumed by app crates through the Framework facade.
90    pub fn navigation_identifier(&self, url: &str) -> Option<String> {
91        let (url, identifier) = self.parse_issue_url(url)?;
92        let query: Vec<_> = url.query_pairs().collect();
93        (query.len() == 1 && query[0].0 == "profile" && query[0].1 == self.profile_id)
94            .then_some(identifier)
95    }
96
97    fn parse_issue_url(&self, url: &str) -> Option<(url::Url, String)> {
98        let url = url::Url::parse(url).ok()?;
99        let api = url::Url::parse(&self.api_origin).ok()?;
100        if url.origin() != api.origin()
101            || !url.username().is_empty()
102            || url.password().is_some()
103            || url.fragment().is_some()
104        {
105            return None;
106        }
107        let prefix = format!("{}/v1/issues/", api.path().trim_end_matches('/'));
108        let identifier = url.path().strip_prefix(&prefix)?;
109        let keys =
110            recognition::ReferenceRecognizer::new(self.project_keys.iter().map(String::as_str), []);
111        if !keys.recognises(identifier) {
112            return None;
113        }
114        let identifier = identifier.to_owned();
115        Some((url, identifier))
116    }
117}
118
119/// Asks for summaries of issue identifiers, such as `SUB-827`, in one
120/// profile. The answer has one [`Resolution`] per identifier, in order. A
121/// profile that is not the responder's current one resolves as unavailable,
122/// never as another profile's issue.
123#[derive(Clone, PartialEq, Eq)]
124pub struct Resolve {
125    profile_id: String,
126    identifiers: Vec<String>,
127}
128
129impl Resolve {
130    /// Keeps the first [`MAX_RESOLVE`] distinct identifiers, in order.
131    pub fn new(profile_id: &str, identifiers: impl IntoIterator<Item = impl Into<String>>) -> Self {
132        let mut distinct: Vec<String> = Vec::new();
133        for identifier in identifiers.into_iter().map(Into::into) {
134            if distinct.len() == MAX_RESOLVE {
135                break;
136            }
137            if !distinct.contains(&identifier) {
138                distinct.push(identifier);
139            }
140        }
141        Self {
142            profile_id: profile_id.into(),
143            identifiers: distinct,
144        }
145    }
146
147    // qual:api
148    pub fn profile_id(&self) -> &str {
149        &self.profile_id
150    }
151
152    pub fn identifiers(&self) -> &[String] {
153        &self.identifiers
154    }
155}
156
157impl Request for Resolve {
158    type Contract = Issues;
159    const NAME: &'static str = "resolve";
160    type Response = Vec<Resolution>;
161}
162
163/// Asks the responder to read issue identifiers again, because the asker
164/// has just changed them in the tracker, such as Channels after a tracker
165/// command. The responder forgets what it holds for each identifier in the
166/// named profile and starts a fresh read, as [`Resolve`] does for one it
167/// has never seen; [`Changed`] follows when the reads land. A profile that
168/// is not the responder's current one changes nothing. Same limits as
169/// [`Resolve`]: the first [`MAX_RESOLVE`] distinct identifiers.
170#[derive(Clone, PartialEq, Eq)]
171pub struct Refresh(Resolve);
172
173impl Refresh {
174    pub fn new(profile_id: &str, identifiers: impl IntoIterator<Item = impl Into<String>>) -> Self {
175        Self(Resolve::new(profile_id, identifiers))
176    }
177
178    // qual:api
179    pub fn profile_id(&self) -> &str {
180        self.0.profile_id()
181    }
182
183    pub fn identifiers(&self) -> &[String] {
184        self.0.identifiers()
185    }
186}
187
188impl Request for Refresh {
189    type Contract = Issues;
190    const NAME: &'static str = "refresh";
191    type Response = ();
192}
193
194/// What the responder knows about one identifier.
195#[derive(Clone, PartialEq, Eq)]
196#[non_exhaustive]
197pub struct Resolution {
198    pub identifier: String,
199    pub state: ResolutionState,
200}
201
202impl Resolution {
203    pub fn new(identifier: &str, state: ResolutionState) -> Self {
204        Self {
205            identifier: identifier.into(),
206            state,
207        }
208    }
209}
210
211#[derive(Clone, PartialEq, Eq)]
212#[non_exhaustive]
213pub enum ResolutionState {
214    Available(IssueSummary),
215    /// The issue cannot be shown with this profile. This never says whether
216    /// it exists.
217    Unavailable,
218    /// A read has started; [`Changed`] follows when it lands.
219    Pending,
220    SignedOut,
221    /// The read failed for another reason, such as the network.
222    Failed,
223}
224
225/// The workflow category of an issue's state, which picks its glyph.
226#[derive(Clone, Copy, Debug, PartialEq, Eq)]
227#[non_exhaustive]
228pub enum StateType {
229    Triage,
230    Backlog,
231    Unstarted,
232    Started,
233    Completed,
234    Canceled,
235    Duplicate,
236}
237
238/// An issue's workflow state: its name and category.
239// qual:api — adopted in phases 3 and 4 of the board-contracts plan.
240#[derive(Clone, PartialEq, Eq)]
241#[non_exhaustive]
242pub struct IssueState {
243    pub name: String,
244    pub kind: StateType,
245}
246
247impl IssueState {
248    pub fn new(name: &str, kind: StateType) -> Self {
249        Self {
250            name: name.into(),
251            kind,
252        }
253    }
254}
255
256mod summary;
257pub use summary::{IssuePerson, IssueProgress, IssueSummary, LatestActivity, PullRequestSummary};