tag2upload_service_manager/
gitlab.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188

use crate::prelude::*;
use webhook::*;

#[derive(Deserialize, Eq, PartialEq)]
#[derive(derive_more::Display, derive_more::FromStr)]
#[serde(transparent)]
pub struct ProjectId(pub u64);

#[derive(Deserialize)]
pub struct Payload {
    object_kind: String,
    after: GitObjectIdOrNull,
    #[serde(rename = "ref")]
    tag_ref_name: String,
    project: Project,
    message: String,
}

#[derive(Deserialize)]
struct Project {
    git_http_url: String,
    id: ProjectId,
}

impl SomeWebhookPayload for Payload {
    type Forge = Forge1;
}

pub struct DbData {
    project_id: ProjectId,
}

impl TryFrom<Payload> for RawWebhookPayloadData<DbData> {
    type Error = WebError;
    fn try_from(p: Payload) -> Result<RawWebhookPayloadData<DbData>,
                                      WebError> {
        let Payload { object_kind, after, tag_ref_name, project, message } = p;
        let Project { git_http_url, id: project_id } = project;

        let tag_objectid = after.try_into().map_err(
            |UnexpectedNullGitObjectId| NFR::TagIsBeingDeleted
        )?;

        if object_kind != "tag_push" {
            return Err(WE::MisconfiguredWebhook(anyhow!(
                "unexpected event {:?}", object_kind
            )));
        }
        let tag_name = tag_ref_name.strip_prefix("refs/tags/")
            .ok_or_else(|| WE::MalfunctioningWebhook(anyhow!(
                "tag ref name doesn't start refs/tags/"
            )))?
            .to_owned();

        let tag_meta = t2umeta::Parsed::from_tag_message(&message)?;

        let repo_git_url = git_http_url;
        let forge_data = DbData { project_id };

        Ok(RawWebhookPayloadData {
            repo_git_url,
            tag_objectid,
            tag_name,
            tag_meta,
            forge_data,
        })
    }
}

impl FromStr for DbData {
    type Err = IE;

    fn from_str(s: &str) -> Result<Self, IE> {
        let project_id = s.parse().into_internal("parse project id")?;
        Ok(DbData {
            project_id,
        })
    }
}
impl Display for DbData {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let DbData {
            project_id,
        } = self;
        Display::fmt(project_id, f)?;
        Ok(())
    }
}

#[derive(Default, Debug)]
pub struct Forge1;

#[derive(Deserialize)]
struct TagResponse {
    #[serde(rename = "target")]
    tag_objid: GitObjectId,

    created_at: humantime_serde::Serde<SystemTime>,
}

#[async_trait]
impl SomeForge for Forge1 {
    type DbData = DbData where Self: Sized;

    fn kind_name(&self) -> &'static str { "gitlab" }

    fn namever_str(&self) -> &str { "gitlab-1" }

    async fn make_progress(
        &self,
        host: &Hostname,
        task_tmpdir: &str,
    ) -> Result<(), QuitTask> {
        let globals = globals();

        let mut job = JobInWorkflow::start_for_forge(
            &host,
            self.namever_str(),
        ).await?;

        let jid = job.jid;

        let db_data = job.forge_db_data(self)?;

        trace!(%host, %jid, "fetching tag");

        /*
         * We make the API call to fetch the tag, too,
         * just because we need the tag's timestamp,
         * which gitlab doesn't put in the webhook.
         *
         * URL example,
 https://salsa.debian.org/api/v4/projects/36575/repository/tags/debian%2f1.39
         */
        let url = (|| {
            let mut url: Url = format!("https://{}", &job.data.forge_host)
                // no trailing slash needed, path_segments extend will add
                .parse().context("parse initial forge_host https url")?;
            url.path_segments_mut()
                .map_err(|()| internal!("path no segments?"))?
                .extend([
                    "api", "v4", "projects",
                    &db_data.project_id.to_string(),
                    "repository", "tags",
                    &job.data.tag_name,
                ]);
            Ok::<_, AE>(url)
        })()
            .into_internal("construct tag API url")?;

        trace!(%jid, %url, "gitab tag info");

        test_hook_url!(url);

        let outcome = async {
            let TagResponse {
                created_at,
                tag_objid: confirmed_tag,
            } = globals.http_fetch_json(url.clone())
                .await
                .context("fetch tag info")
                .map_err(PE::Forge)?;

            trace!(%jid, ?created_at, "gitab tag date");

            MismatchError::check(
                "tag object id",
                &job.data.tag_objectid,
                &confirmed_tag,
            )?;

            let _is_recent_enough = globals.check_tag_recency(*created_at)?;

            gitclone::fetch_tags_via_clone(
                &mut job,
                &task_tmpdir,
            ).await
        }.await;

        fetcher::record_fetch_outcome(
            job,
            outcome,
        )?;

        Ok(())
    }
}