Skip to main content

gitpoulpi_hosting/
flow_engine.rs

1//! Host-driven flows, the shared engine of the CLI, the MCP server and the
2//! TUI: create the issue, make the branch on the host, find what the host or a
3//! bot made for an issue, wait for it. Everything here is a function over a
4//! [`HostingClient`], so a fake transport tests it and the three frontends
5//! cannot drift apart. The loops (sleeping, cancelling, drawing a spinner) are
6//! the frontend's: it asks [`find_for_issue`] again after [`backoff`].
7
8use std::time::Duration;
9
10use gitpoulpi_core::workflow::{
11    branches_for_issue, issue_branch_pattern, slugify, BranchPattern, Fields, IssueDraft,
12    IssueFlow, WaitFor, DEFAULT_SLUG_MAX,
13};
14
15use crate::client::{CreatedIssue, CreatedPullRequest, HostingClient, NewIssue, NewPullRequest};
16use crate::issue_flow::{CreatedBranch, NewIssueBranch};
17use crate::model::{PrFilter, PullRequestSummary, StateFilter};
18use crate::{Error, Result};
19
20/// What the host (or a bot) made for an issue, as far as it could be told.
21#[derive(Debug, Clone, PartialEq, Eq, Default)]
22pub struct Found {
23    /// Branch names (without a remote), the host's links first.
24    pub branches: Vec<String>,
25    /// Merge / pull requests tied to the issue by the host or by name.
26    pub requests: Vec<PullRequestSummary>,
27    /// Sources that failed (a host without the endpoint, a 403): the rest
28    /// still answered.
29    pub notes: Vec<String>,
30}
31
32impl Found {
33    /// Whether what was found is what `wait` asked for.
34    pub fn satisfies(&self, wait: WaitFor) -> bool {
35        (wait.wants_branch() && !self.branches.is_empty())
36            || (wait.wants_request() && !self.requests.is_empty())
37    }
38
39    /// The branch to pick up: the one of the newest live request, else the
40    /// first branch found.
41    pub fn best_branch(&self) -> Option<&str> {
42        let live = self.requests.iter().find(|r| {
43            matches!(
44                r.state,
45                crate::model::PullRequestState::Open | crate::model::PullRequestState::Draft
46            )
47        });
48        live.map(|r| r.source_branch.as_str())
49            .or_else(|| self.requests.first().map(|r| r.source_branch.as_str()))
50            .or_else(|| self.branches.first().map(String::as_str))
51            .filter(|b| !b.is_empty())
52    }
53
54    /// The request that has `branch` as its source: its target is the
55    /// branch's parent.
56    pub fn request_of(&self, branch: &str) -> Option<&PullRequestSummary> {
57        self.requests.iter().find(|r| r.source_branch == branch)
58    }
59}
60
61/// How long to wait before asking the host again after `attempt` tries
62/// (0-based): 1 s, 2 s, 3 s, 5 s, 8 s, then every 10 s. Bounded so a bot that
63/// takes minutes costs a few dozen cheap calls, never a hammered host.
64/// `GITPOULPI_FLOW_POLL_MS` fixes the pause (tests and benches).
65pub fn backoff(attempt: u32) -> Duration {
66    if let Some(ms) = std::env::var("GITPOULPI_FLOW_POLL_MS")
67        .ok()
68        .and_then(|v| v.parse::<u64>().ok())
69    {
70        return Duration::from_millis(ms.max(10));
71    }
72    const STEPS: [u64; 5] = [1, 2, 3, 5, 8];
73    Duration::from_secs(STEPS.get(attempt as usize).copied().unwrap_or(10))
74}
75
76/// The text a branch search for `number` starts with, for each type's
77/// pattern (`feature/12` for `feature/{issue}-{slug}`), without duplicates.
78fn searches(flow: &IssueFlow, type_ids: &[String], number: u64) -> Vec<String> {
79    let mut out: Vec<String> = Vec::new();
80    for t in type_ids {
81        if let Ok(pattern) = issue_branch_pattern(flow, t) {
82            let s = format!("{}{number}", pattern.prefix());
83            if !out.contains(&s) {
84                out.push(s);
85            }
86        }
87    }
88    if out.is_empty() {
89        out.push(number.to_string());
90    }
91    out
92}
93
94/// Asks the host what exists for issue `number`: its own links, the branches
95/// matching the workflow's `branch_from_issue` and the requests whose source
96/// branch does. A source that fails is noted, not fatal; when every source
97/// fails the error of the first is returned.
98pub async fn find_for_issue(
99    client: &dyn HostingClient,
100    project: &str,
101    flow: &IssueFlow,
102    type_ids: &[String],
103    number: u64,
104) -> Result<Found> {
105    let mut found = Found::default();
106    let mut answered = false;
107    let mut first_error: Option<Error> = None;
108    let note = |what: &str, e: Error, found: &mut Found, first: &mut Option<Error>| {
109        found.notes.push(format!("{what}: {e}"));
110        if first.is_none() {
111            *first = Some(e);
112        }
113    };
114    let ids: Vec<&str> = type_ids.iter().map(String::as_str).collect();
115
116    match client.issue_links(project, number).await {
117        Ok(links) => {
118            answered = true;
119            found.branches.extend(links.branches);
120            found.requests.extend(links.requests);
121        }
122        Err(e) => note("the issue's links", e, &mut found, &mut first_error),
123    }
124    let mut names: Vec<String> = Vec::new();
125    for search in searches(flow, type_ids, number) {
126        match client.branch_names(project, &search).await {
127            Ok(rows) => {
128                answered = true;
129                names.extend(rows);
130            }
131            Err(e) => {
132                note("the branch search", e, &mut found, &mut first_error);
133                break;
134            }
135        }
136    }
137    for b in branches_for_issue(flow, &ids, &names, number) {
138        if !found.branches.contains(&b) {
139            found.branches.push(b);
140        }
141    }
142    // Requests the host did not link (Gitea, a bot that does not close the
143    // issue): their source branch carries the issue number.
144    if found.requests.is_empty() {
145        let filter = PrFilter {
146            state: StateFilter::Open,
147            ..PrFilter::default()
148        };
149        match client.list_pull_requests(project, &filter).await {
150            Ok(rows) => {
151                answered = true;
152                let sources: Vec<String> = rows.iter().map(|r| r.source_branch.clone()).collect();
153                let matching = branches_for_issue(flow, &ids, &sources, number);
154                found.requests.extend(
155                    rows.into_iter()
156                        .filter(|r| matching.contains(&r.source_branch)),
157                );
158            }
159            Err(e) => note("the request list", e, &mut found, &mut first_error),
160        }
161    }
162    for r in &found.requests {
163        if !r.source_branch.is_empty() && !found.branches.contains(&r.source_branch) {
164            found.branches.push(r.source_branch.clone());
165        }
166    }
167    if !answered {
168        if let Some(e) = first_error {
169            return Err(e);
170        }
171    }
172    Ok(found)
173}
174
175/// Creates the issue of `draft` on `project`.
176pub async fn create_issue(
177    client: &dyn HostingClient,
178    project: &str,
179    draft: &IssueDraft,
180    milestone: Option<u64>,
181) -> Result<CreatedIssue> {
182    client
183        .create_issue(&NewIssue {
184            project: project.to_string(),
185            title: draft.title.clone(),
186            body: draft.body.clone(),
187            labels: draft.labels.clone(),
188            assignees: draft.assignees.clone(),
189            milestone,
190            ..NewIssue::default()
191        })
192        .await
193}
194
195/// The name the host-made branch of issue `number` gets: the workflow's
196/// `branch_from_issue` with the type, the issue number and the title's slug.
197pub fn issue_branch_name(
198    flow: &IssueFlow,
199    type_id: &str,
200    number: u64,
201    title: &str,
202) -> std::result::Result<String, String> {
203    let pattern: BranchPattern =
204        issue_branch_pattern(flow, type_id).map_err(|e| format!("branch_from_issue: {e}"))?;
205    let mut fields = Fields::new();
206    fields.insert("issue".into(), number.to_string());
207    fields.insert("issue_key".into(), format!("{type_id}-{number}"));
208    let mut slug = slugify(title, DEFAULT_SLUG_MAX);
209    if slug.is_empty() {
210        slug = "issue".into();
211    }
212    fields.insert("slug".into(), slug);
213    pattern.render(&fields).map_err(|e| e.to_string())
214}
215
216/// What `host-creates-branch` made.
217#[derive(Debug, Clone, PartialEq, Eq)]
218pub struct HostMade {
219    pub branch: CreatedBranch,
220    pub request: Option<CreatedPullRequest>,
221    /// The merge request could not be opened (a host refuses one with no
222    /// commits of its own); the branch exists.
223    pub warning: Option<String>,
224}
225
226/// Creates `name` from `from` on the host for the issue and, when `open_request`,
227/// a draft merge request into `target` that closes the issue.
228#[allow(clippy::too_many_arguments)]
229pub async fn host_creates_branch(
230    client: &dyn HostingClient,
231    project: &str,
232    number: u64,
233    name: &str,
234    from: &str,
235    target: &str,
236    title: &str,
237    open_request: bool,
238) -> Result<HostMade> {
239    let branch = client
240        .create_issue_branch(&NewIssueBranch {
241            project: project.to_string(),
242            issue_number: number,
243            name: name.to_string(),
244            from: from.to_string(),
245        })
246        .await?;
247    let mut made = HostMade {
248        branch,
249        request: None,
250        warning: None,
251    };
252    if open_request {
253        let result = client
254            .create_pull_request(&NewPullRequest {
255                project: project.to_string(),
256                source_branch: made.branch.name.clone(),
257                target_branch: target.to_string(),
258                title: title.to_string(),
259                body: format!("Closes #{number}"),
260                draft: true,
261                ..NewPullRequest::default()
262            })
263            .await;
264        match result {
265            Ok(created) => made.request = Some(created),
266            Err(e) => {
267                made.warning = Some(format!(
268                    "the branch exists but the merge request could not be opened: {e}"
269                ))
270            }
271        }
272    }
273    Ok(made)
274}
275
276#[cfg(test)]
277mod tests {
278    use std::sync::Arc;
279
280    use gitpoulpi_config::IntegrationKind;
281
282    use crate::client::client_for;
283    use crate::http::RecordedTransport;
284    use crate::integration::Integration;
285
286    use super::*;
287
288    fn block_on<F: std::future::Future>(f: F) -> F::Output {
289        tokio::runtime::Builder::new_current_thread()
290            .enable_all()
291            .build()
292            .unwrap()
293            .block_on(f)
294    }
295
296    fn gitlab(t: Arc<RecordedTransport>) -> Box<dyn HostingClient> {
297        client_for(
298            Integration::new(
299                "gl",
300                IntegrationKind::GitlabSelfManaged,
301                "https://gl.example.com",
302            ),
303            "t".into(),
304            t,
305            &crate::trust::TrustGate::for_tests(),
306        )
307        .unwrap()
308    }
309
310    fn mr(iid: u64, state: &str, source: &str) -> String {
311        format!(
312            r#"{{"iid":{iid},"title":"t","state":"{state}","source_branch":"{source}","target_branch":"develop",
313            "source_project_id":1,"target_project_id":1,"web_url":"u","updated_at":""}}"#
314        )
315    }
316
317    #[test]
318    fn backoff_grows_then_stays_at_ten_seconds() {
319        if std::env::var("GITPOULPI_FLOW_POLL_MS").is_ok() {
320            return;
321        }
322        let secs: Vec<u64> = (0..8).map(|i| backoff(i).as_secs()).collect();
323        assert_eq!(secs, [1, 2, 3, 5, 8, 10, 10, 10]);
324    }
325
326    #[test]
327    fn nothing_yet_is_an_empty_answer_not_an_error() {
328        let t = Arc::new(
329            RecordedTransport::new()
330                .on("/related_merge_requests", 200, "[]")
331                .on("/closed_by", 200, "[]")
332                .on("/repository/branches", 200, "[]")
333                .on("/merge_requests", 200, "[]"),
334        );
335        let found = block_on(find_for_issue(
336            &*gitlab(t),
337            "g/p",
338            &IssueFlow::default(),
339            &["feature".to_string()],
340            12,
341        ))
342        .unwrap();
343        assert!(!found.satisfies(WaitFor::BranchOrMergeRequest));
344        assert!(found.best_branch().is_none());
345    }
346
347    #[test]
348    fn a_bot_branch_and_its_request_are_found_by_number_and_by_the_hosts_link() {
349        let t = Arc::new(
350            RecordedTransport::new()
351                .on(
352                    "/related_merge_requests",
353                    200,
354                    &format!("[{}]", mr(5, "opened", "feature/12-login")),
355                )
356                .on("/closed_by", 200, "[]")
357                .on(
358                    "/repository/branches",
359                    200,
360                    r#"[{"name":"feature/12-login"},{"name":"feature/120-x"}]"#,
361                ),
362        );
363        let found = block_on(find_for_issue(
364            &*gitlab(t),
365            "g/p",
366            &IssueFlow::default(),
367            &["feature".to_string(), "bugfix".to_string()],
368            12,
369        ))
370        .unwrap();
371        assert_eq!(found.branches, ["feature/12-login"]);
372        assert_eq!(found.best_branch(), Some("feature/12-login"));
373        assert_eq!(
374            found.request_of("feature/12-login").unwrap().target_branch,
375            "develop"
376        );
377        assert!(found.satisfies(WaitFor::Branch));
378        assert!(found.satisfies(WaitFor::MergeRequest));
379    }
380
381    #[test]
382    fn a_request_the_host_did_not_link_is_found_by_its_source_branch() {
383        let t = Arc::new(
384            RecordedTransport::new()
385                .on("/related_merge_requests", 200, "[]")
386                .on("/closed_by", 200, "[]")
387                .on("/repository/branches", 200, "[]")
388                .on(
389                    "/merge_requests",
390                    200,
391                    &format!(
392                        "[{},{}]",
393                        mr(6, "opened", "feature/12-a"),
394                        mr(7, "opened", "feature/13-b")
395                    ),
396                ),
397        );
398        let found = block_on(find_for_issue(
399            &*gitlab(t),
400            "g/p",
401            &IssueFlow::default(),
402            &["feature".to_string()],
403            12,
404        ))
405        .unwrap();
406        assert_eq!(found.requests.len(), 1);
407        assert_eq!(found.requests[0].number, 6);
408        // The request's branch is a branch of the issue too.
409        assert_eq!(found.branches, ["feature/12-a"]);
410    }
411
412    #[test]
413    fn when_every_source_fails_the_error_comes_back() {
414        let t = Arc::new(RecordedTransport::new().on("/projects/", 500, "{}"));
415        let r = block_on(find_for_issue(
416            &*gitlab(t),
417            "g/p",
418            &IssueFlow::default(),
419            &["feature".to_string()],
420            1,
421        ));
422        assert!(r.is_err());
423    }
424
425    #[test]
426    fn the_branch_name_follows_the_pattern() {
427        let flow = IssueFlow::default();
428        assert_eq!(
429            issue_branch_name(&flow, "feature", 12, "Login page!").unwrap(),
430            "feature/12-login-page"
431        );
432        assert_eq!(
433            issue_branch_name(&flow, "bugfix", 3, "???").unwrap(),
434            "bugfix/3-issue"
435        );
436    }
437
438    #[test]
439    fn host_creates_the_branch_then_a_draft_request_that_closes_the_issue() {
440        let t = Arc::new(
441            RecordedTransport::new()
442                .on("/repository/branches", 201, r#"{"name":"feature/12-x"}"#)
443                .on(
444                    "/merge_requests",
445                    201,
446                    r#"{"iid":9,"web_url":"https://gl.example.com/mr/9"}"#,
447                ),
448        );
449        let made = block_on(host_creates_branch(
450            &*gitlab(t.clone()),
451            "g/p",
452            12,
453            "feature/12-x",
454            "develop",
455            "develop",
456            "Login",
457            true,
458        ))
459        .unwrap();
460        assert_eq!(made.request.unwrap().number, 9);
461        let mr_request = &t.requests()[1];
462        let body: serde_json::Value =
463            serde_json::from_str(mr_request.body.as_deref().unwrap()).unwrap();
464        assert_eq!(body["description"], "Closes #12");
465        assert_eq!(body["source_branch"], "feature/12-x");
466        assert!(body["title"].as_str().unwrap().starts_with("Draft: "));
467    }
468
469    #[test]
470    fn a_refused_request_leaves_the_branch_and_a_warning() {
471        let t = Arc::new(
472            RecordedTransport::new()
473                .on("/repository/branches", 201, r#"{"name":"b"}"#)
474                .on("/merge_requests", 422, r#"{"message":"no commits"}"#),
475        );
476        let made = block_on(host_creates_branch(
477            &*gitlab(t),
478            "g/p",
479            1,
480            "b",
481            "main",
482            "main",
483            "t",
484            true,
485        ))
486        .unwrap();
487        assert!(made.request.is_none());
488        assert!(made.warning.unwrap().contains("could not be opened"));
489    }
490}