Skip to main content

interprex_github/
jobs.rs

1//! GitHub Actions operations owned by the jobs domain.
2//!
3//! Dispatch and cancellation use Octocrab's typed operations because their
4//! successful responses have no JSON body. Run responses are normalized into a
5//! small status and conclusion vocabularies; new GitHub values become
6//! `Unknown` rather than causing deserialization failure or silently
7//! pretending to be completed. An omitted workflow name remains absent.
8
9use async_trait::async_trait;
10use interprex::{
11    DispatchInputs, JobsProvider, ProviderError, Repository, Result, RunConclusion, RunId,
12    RunStatus, WorkflowRun,
13};
14use serde::Deserialize;
15
16use crate::{GithubProvider, client::external};
17
18#[derive(Deserialize)]
19struct GithubRun {
20    id: u64,
21    name: Option<String>,
22    head_sha: String,
23    status: String,
24    conclusion: Option<String>,
25    html_url: String,
26}
27
28fn normalize_run(value: GithubRun) -> Result<WorkflowRun> {
29    let status = match value.status.as_str() {
30        "queued" | "waiting" | "pending" => RunStatus::Queued,
31        "in_progress" | "requested" => RunStatus::InProgress,
32        "completed" => RunStatus::Completed,
33        _ => RunStatus::Unknown,
34    };
35    let conclusion = value.conclusion.map(|value| match value.as_str() {
36        "success" => RunConclusion::Success,
37        "failure" => RunConclusion::Failure,
38        "neutral" => RunConclusion::Neutral,
39        "cancelled" => RunConclusion::Cancelled,
40        "skipped" => RunConclusion::Skipped,
41        "timed_out" => RunConclusion::TimedOut,
42        "action_required" => RunConclusion::ActionRequired,
43        "stale" => RunConclusion::Stale,
44        "startup_failure" => RunConclusion::StartupFailure,
45        _ => RunConclusion::Unknown,
46    });
47    Ok(WorkflowRun {
48        id: RunId::new(value.id).map_err(|error| ProviderError::Unrepresentable {
49            provider: "github",
50            fact: error.to_string(),
51        })?,
52        workflow_name: value.name,
53        head_sha: value.head_sha,
54        status,
55        conclusion,
56        html_url: value.html_url,
57    })
58}
59
60#[async_trait]
61impl JobsProvider for GithubProvider {
62    #[tracing::instrument(
63        name = "interprex.provider.jobs.dispatch",
64        skip_all,
65        fields(interprex.provider.name = "github")
66    )]
67    async fn dispatch(
68        &self,
69        repository: &Repository,
70        workflow: &str,
71        git_ref: &str,
72        inputs: &DispatchInputs,
73    ) -> Result<()> {
74        self.user()?
75            .actions()
76            .create_workflow_dispatch(repository.owner(), repository.name(), workflow, git_ref)
77            .inputs(serde_json::Value::Object(
78                inputs.0.clone().into_iter().collect(),
79            ))
80            .send()
81            .await
82            .map_err(|error| external("dispatch workflow", error))?;
83        Ok(())
84    }
85
86    #[tracing::instrument(
87        name = "interprex.provider.jobs.run",
88        skip_all,
89        fields(interprex.provider.name = "github")
90    )]
91    async fn run(&self, repository: &Repository, run_id: RunId) -> Result<WorkflowRun> {
92        let response: GithubRun = self
93            .user()?
94            .get(
95                format!("/repos/{repository}/actions/runs/{}", run_id.get()),
96                None::<&()>,
97            )
98            .await
99            .map_err(|error| {
100                crate::client::read_error(
101                    "read workflow run",
102                    format!("workflow run {} in {repository}", run_id.get()),
103                    error,
104                )
105            })?;
106        normalize_run(response)
107    }
108
109    #[tracing::instrument(
110        name = "interprex.provider.jobs.cancel_run",
111        skip_all,
112        fields(interprex.provider.name = "github")
113    )]
114    async fn cancel_run(&self, repository: &Repository, run_id: RunId) -> Result<()> {
115        self.user()?
116            .actions()
117            .cancel_workflow_run(repository.owner(), repository.name(), run_id.get().into())
118            .await
119            .map_err(|error| external("cancel workflow run", error))?;
120        Ok(())
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use super::{GithubRun, normalize_run};
127    use interprex::{RunConclusion, RunStatus};
128
129    #[test]
130    fn run_fixture_normalizes_status_without_exporting_octocrab_types() {
131        let response: GithubRun =
132            serde_json::from_str(include_str!("../tests/fixtures/workflow_run.json"))
133                .expect("fixture");
134        let run = normalize_run(response).expect("normalizes");
135        assert_eq!(run.status, RunStatus::Completed);
136        assert_eq!(run.workflow_name.as_deref(), Some("quality"));
137        assert_eq!(run.conclusion, Some(RunConclusion::Success));
138    }
139
140    #[test]
141    fn omitted_name_stays_absent_and_new_conclusions_are_explicitly_unknown() {
142        let response: GithubRun = serde_json::from_str(
143            r#"{
144                "id": 123456,
145                "head_sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
146                "status": "completed",
147                "conclusion": "future_value",
148                "html_url": "https://example.invalid/run"
149            }"#,
150        )
151        .expect("response");
152        let run = normalize_run(response).expect("normalizes");
153        assert_eq!(run.workflow_name, None);
154        assert_eq!(run.conclusion, Some(RunConclusion::Unknown));
155    }
156}