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//! (sign-in, sign-out, organisation or team 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 signed out or has no organisation,
42/// and then nothing is 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, organisation and team keys that references are recognised
53/// against, with the app origin that issue links use.
54#[derive(Clone, PartialEq, Eq)]
55#[non_exhaustive]
56pub struct IssueScope {
57    pub profile_id: String,
58    pub profile_name: String,
59    pub app_origin: String,
60    pub organisation_id: String,
61    /// The keys to recognise: the loaded team keys, archived teams included,
62    /// or the profile's fallback keys while none are loaded.
63    pub team_keys: Vec<String>,
64    /// The Linear workspace whose issue links name these issues, the first
65    /// path segment of its links. `None` recognises no Linear link.
66    pub linear_workspace: Option<String>,
67}
68
69impl IssueScope {
70    pub fn new(
71        profile_id: &str,
72        profile_name: &str,
73        app_origin: &str,
74        organisation_id: &str,
75    ) -> Self {
76        Self {
77            profile_id: profile_id.into(),
78            profile_name: profile_name.into(),
79            app_origin: app_origin.into(),
80            organisation_id: organisation_id.into(),
81            team_keys: Vec::new(),
82            linear_workspace: None,
83        }
84    }
85
86    // qual:api (the app supplies its Linear workspace)
87    pub fn with_linear_workspace(mut self, workspace: &str) -> Self {
88        self.linear_workspace = (!workspace.is_empty()).then(|| workspace.to_owned());
89        self
90    }
91
92    pub fn with_team_keys(mut self, keys: impl IntoIterator<Item = impl Into<String>>) -> Self {
93        self.team_keys = keys.into_iter().map(Into::into).collect();
94        self
95    }
96
97    /// Bind a navigation URL to the profile and organisation that resolved it.
98    // qual:api
99    pub fn navigation_url(&self, url: &str) -> Option<String> {
100        let mut url = url::Url::parse(url).ok()?;
101        if url.origin().ascii_serialization() != self.app_origin {
102            return None;
103        }
104        url.query_pairs_mut()
105            .clear()
106            .append_pair("orgId", &self.organisation_id)
107            .append_pair("profile", &self.profile_id);
108        Some(url.into())
109    }
110}
111
112/// Asks for summaries of issue identifiers, such as `NET-827`, in one
113/// profile. The answer has one [`Resolution`] per identifier, in order. A
114/// profile that is not the responder's current one resolves as unavailable,
115/// never as another profile's issue.
116#[derive(Clone, PartialEq, Eq)]
117pub struct Resolve {
118    profile_id: String,
119    identifiers: Vec<String>,
120}
121
122impl Resolve {
123    /// Keeps the first [`MAX_RESOLVE`] distinct identifiers, in order.
124    pub fn new(profile_id: &str, identifiers: impl IntoIterator<Item = impl Into<String>>) -> Self {
125        let mut distinct: Vec<String> = Vec::new();
126        for identifier in identifiers.into_iter().map(Into::into) {
127            if distinct.len() == MAX_RESOLVE {
128                break;
129            }
130            if !distinct.contains(&identifier) {
131                distinct.push(identifier);
132            }
133        }
134        Self {
135            profile_id: profile_id.into(),
136            identifiers: distinct,
137        }
138    }
139
140    // qual:api
141    pub fn profile_id(&self) -> &str {
142        &self.profile_id
143    }
144
145    pub fn identifiers(&self) -> &[String] {
146        &self.identifiers
147    }
148}
149
150impl Request for Resolve {
151    type Contract = Issues;
152    const NAME: &'static str = "resolve";
153    type Response = Vec<Resolution>;
154}
155
156/// What the responder knows about one identifier.
157#[derive(Clone, PartialEq, Eq)]
158#[non_exhaustive]
159pub struct Resolution {
160    pub identifier: String,
161    pub state: ResolutionState,
162}
163
164impl Resolution {
165    pub fn new(identifier: &str, state: ResolutionState) -> Self {
166        Self {
167            identifier: identifier.into(),
168            state,
169        }
170    }
171}
172
173#[derive(Clone, PartialEq, Eq)]
174#[non_exhaustive]
175pub enum ResolutionState {
176    Available(IssueSummary),
177    /// The issue cannot be shown with this profile. This never says whether
178    /// it exists.
179    Unavailable,
180    /// A read has started; [`Changed`] follows when it lands.
181    Pending,
182    SignedOut,
183    /// The read failed for another reason, such as the network.
184    Failed,
185}
186
187/// The workflow category of an issue's state, which picks its glyph.
188#[derive(Clone, Copy, Debug, PartialEq, Eq)]
189#[non_exhaustive]
190pub enum StateType {
191    Triage,
192    Backlog,
193    Unstarted,
194    Started,
195    Completed,
196    Canceled,
197    Duplicate,
198}
199
200/// An issue's workflow state: its name and category.
201// qual:api — adopted in phases 3 and 4 of the board-contracts plan.
202#[derive(Clone, PartialEq, Eq)]
203#[non_exhaustive]
204pub struct IssueState {
205    pub name: String,
206    pub kind: StateType,
207}
208
209impl IssueState {
210    pub fn new(name: &str, kind: StateType) -> Self {
211        Self {
212            name: name.into(),
213            kind,
214        }
215    }
216}
217
218/// The few fields a reference tooltip or link shows.
219#[derive(Clone, PartialEq, Eq)]
220#[non_exhaustive]
221pub struct IssueSummary {
222    pub identifier: String,
223    pub title: String,
224    /// The issue's page, for opening it outside Subspace.
225    pub url: String,
226    pub state: IssueState,
227    pub tracker: bool,
228    pub archived: bool,
229    /// The assignee's display name.
230    pub assignee: Option<String>,
231}
232
233impl IssueSummary {
234    pub fn new(identifier: &str, title: &str, url: &str, state: IssueState) -> Self {
235        Self {
236            identifier: identifier.into(),
237            title: title.into(),
238            url: url.into(),
239            state,
240            tracker: false,
241            archived: false,
242            assignee: None,
243        }
244    }
245
246    /// Whether the issue is a tracker and whether it is archived.
247    pub fn with_markers(mut self, tracker: bool, archived: bool) -> Self {
248        self.tracker = tracker;
249        self.archived = archived;
250        self
251    }
252
253    pub fn with_assignee(mut self, assignee: Option<&str>) -> Self {
254        self.assignee = assignee.map(str::to_owned);
255        self
256    }
257}