Skip to main content

subspace_client_github/issue_report/
submission.rs

1//! One-shot creation. Browser and clipboard actions belong to the host.
2
3use serde::Deserialize;
4use serde_json::{Value, json};
5use std::time::Instant;
6use subspace_core::credentials::Credential;
7use subspace_core::http::{TIMEOUT, status};
8
9use super::{BrowserFallback, Error, ErrorKind, IssueRepository, PreparedReport, http};
10use crate::Client;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum TransportKind {
14    Authenticated,
15    Browser,
16}
17
18/// Owns the reviewed snapshot and captured credential. Intentionally not Clone.
19pub struct ReportPlan {
20    report: PreparedReport,
21    credential: Option<Credential>,
22    fallback: BrowserFallback,
23}
24
25impl ReportPlan {
26    pub fn report(&self) -> &PreparedReport {
27        &self.report
28    }
29    pub fn transport(&self) -> TransportKind {
30        if self.credential.is_some() {
31            TransportKind::Authenticated
32        } else {
33            TransportKind::Browser
34        }
35    }
36    pub fn browser_fallback(&self) -> &BrowserFallback {
37        &self.fallback
38    }
39    /// Effective body for the selected transport, including diagnostic trimming.
40    pub fn body(&self) -> &str {
41        if self.credential.is_some() {
42            self.report.body()
43        } else {
44            self.fallback.body()
45        }
46    }
47    pub fn title(&self) -> &str {
48        self.report.title()
49    }
50}
51
52#[derive(Debug)]
53pub struct CreatedIssue {
54    url: String,
55    number: u64,
56    applied_labels: Vec<String>,
57    skipped_labels: Vec<String>,
58}
59
60impl CreatedIssue {
61    // qual:allow(dry, boilerplate) reason: "Only a verified created-issue URL can leave the client for browser use."
62    pub fn url(&self) -> &str {
63        &self.url
64    }
65    // qual:allow(dry, boilerplate) reason: "The positive number stays bound to its verified repository URL."
66    pub fn number(&self) -> u64 {
67        self.number
68    }
69    // qual:api
70    // qual:allow(dry, boilerplate) reason: "Label results are readonly post-creation evidence, not a mutable retry request."
71    pub fn applied_labels(&self) -> &[String] {
72        &self.applied_labels
73    }
74    // qual:api
75    // qual:allow(dry, boilerplate) reason: "The host can explain omitted labels while retaining the confirmed issue link."
76    pub fn skipped_labels(&self) -> &[String] {
77        &self.skipped_labels
78    }
79}
80
81#[derive(Debug)]
82pub enum Outcome {
83    Created(CreatedIssue),
84    /// An editor still needs to be opened, and the user still needs to submit.
85    Browser(BrowserFallback),
86}
87
88// qual:allow(coupling, oi) reason: "This child module keeps the headless reporting methods on the existing credential-owning GitHub client."
89impl Client {
90    /// Resolve credentials in the existing priority, using gh's active account.
91    /// Performs no HTTP request and never switches or refreshes an account.
92    pub fn prepare_issue_report(&self, report: PreparedReport) -> ReportPlan {
93        let fallback = report.browser_fallback();
94        ReportPlan {
95            report,
96            credential: self.credential(None).ok(),
97            fallback,
98        }
99    }
100
101    /// Consume the review plan. No automatic retry, including parse failures.
102    pub fn submit_issue_report(&self, plan: ReportPlan) -> Result<Outcome, Error> {
103        let Some(credential) = plan.credential else {
104            return Ok(Outcome::Browser(plan.fallback));
105        };
106        let deadline = Instant::now() + TIMEOUT;
107        let mut created = create(self, &credential, &plan.report, deadline)?;
108        let repository = plan.report.repository();
109        apply_labels((self, &credential), repository, &mut created, deadline);
110        Ok(Outcome::Created(created))
111    }
112}
113
114fn create(
115    client: &Client,
116    credential: &Credential,
117    report: &PreparedReport,
118    deadline: Instant,
119) -> Result<CreatedIssue, Error> {
120    let repository = report.repository();
121    let path = format!("/repos/{}/issues", repository.as_str());
122    // Labels are a separate best-effort operation: they cannot reject creation.
123    let body = json!({"title":report.title(), "body":report.body()});
124    let response = http::send(client, credential, &path, Some(&body), deadline)
125        .map_err(|()| Error::from(ErrorKind::UncertainCreation))?;
126    if response.status != ureq::http::StatusCode::CREATED.as_u16() {
127        return Err(creation_failure(&response).into());
128    }
129    let mut created = parse_created(&response.body, repository)?;
130    created.skipped_labels = report.requested_labels().into();
131    Ok(created)
132}
133
134fn parse_created(bytes: &[u8], repository: &IssueRepository) -> Result<CreatedIssue, Error> {
135    #[derive(Deserialize)]
136    struct Created {
137        number: u64,
138        html_url: String,
139    }
140    let response: Created =
141        serde_json::from_slice(bytes).map_err(|_| Error::from(ErrorKind::UncertainCreation))?;
142    if !repository.is_created_issue_url(&response.html_url)
143        || !response
144            .html_url
145            .ends_with(&format!("/{}", response.number))
146    {
147        return Err(ErrorKind::UncertainCreation.into());
148    }
149    Ok(CreatedIssue {
150        url: response.html_url,
151        number: response.number,
152        applied_labels: Vec::new(),
153        skipped_labels: Vec::new(),
154    })
155}
156
157fn creation_failure(response: &http::Response) -> ErrorKind {
158    if response.rate_limited {
159        return ErrorKind::RateLimited;
160    }
161    match response.status {
162        status::UNAUTHORIZED => ErrorKind::Authentication,
163        status::FORBIDDEN => ErrorKind::AccessDenied,
164        status::NOT_FOUND => ErrorKind::RepositoryUnavailable,
165        status::BAD_REQUEST | 422 => ErrorKind::Rejected,
166        _ => ErrorKind::UncertainCreation,
167    }
168}
169
170fn apply_labels(
171    (client, credential): (&Client, &Credential),
172    repository: &IssueRepository,
173    created: &mut CreatedIssue,
174    deadline: Instant,
175) {
176    let available: Vec<String> = created
177        .skipped_labels
178        .iter()
179        .filter(|label| label_exists((client, credential), repository, label, deadline))
180        .cloned()
181        .collect();
182    if available.is_empty() {
183        return;
184    }
185    let path = format!(
186        "/repos/{}/issues/{}/labels",
187        repository.as_str(),
188        created.number
189    );
190    let body = json!({"labels":available});
191    let Ok(response) = http::send(client, credential, &path, Some(&body), deadline) else {
192        return;
193    };
194    // A success must confirm each applied label; an uncertain label response
195    // leaves a usable issue link and never triggers another create request.
196    let confirmed = confirmed_labels(&response);
197    created
198        .skipped_labels
199        .retain(|label| !confirmed.contains(label));
200    created.applied_labels = available
201        .into_iter()
202        .filter(|label| confirmed.contains(label))
203        .collect();
204}
205
206fn label_exists(
207    (client, credential): (&Client, &Credential),
208    repository: &IssueRepository,
209    label: &str,
210    deadline: Instant,
211) -> bool {
212    let encoded: String = url::form_urlencoded::byte_serialize(label.as_bytes()).collect();
213    let path = format!("/repos/{}/labels/{encoded}", repository.as_str());
214    let Ok(response) = http::send(client, credential, &path, None, deadline) else {
215        return false;
216    };
217    response.status == ureq::http::StatusCode::OK.as_u16()
218        && serde_json::from_slice::<Value>(&response.body)
219            .is_ok_and(|value| value["name"].as_str() == Some(label))
220}
221
222fn confirmed_labels(response: &http::Response) -> Vec<String> {
223    if !status::is_success(response.status) {
224        return Vec::new();
225    }
226    serde_json::from_slice::<Vec<Value>>(&response.body)
227        .unwrap_or_default()
228        .iter()
229        .filter_map(|value| value["name"].as_str().map(str::to_owned))
230        .collect()
231}