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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
use reqwest::multipart::{Form, Part};
use reqwest::{Body, StatusCode};
use serde::de::Deserializer;
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use std::time::Duration;
use thiserror::Error;
use tokio::io::{AsyncWrite, AsyncWriteExt};
use url::Url;
use zip::result::ZipError;

fn deserialize_null_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
    T: Default + Deserialize<'de>,
    D: Deserializer<'de>,
{
    let opt = Option::deserialize(deserializer)?;
    Ok(opt.unwrap_or_default())
}

const GITLAB_TRACE_UPDATE_INTERVAL: &str = "X-GitLab-Trace-Update-Interval";

#[derive(Debug, Clone, Serialize)]
struct FeaturesInfo {
    refspecs: bool,
}

#[derive(Debug, Clone, Serialize)]
struct VersionInfo {
    features: FeaturesInfo,
}

#[derive(Debug, Clone, Serialize)]
struct JobRequest<'a> {
    token: &'a str,
    info: VersionInfo,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "lowercase")]
#[allow(dead_code)]
pub enum JobState {
    Pending,
    Running,
    Success,
    Failed,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename = "lower_case")]
struct JobUpdate<'a> {
    token: &'a str,
    state: JobState,
}

#[derive(Debug, Clone)]
pub struct JobUpdateReply {
    pub trace_update_interval: Option<Duration>,
}

#[derive(Debug, Clone)]
pub struct TraceReply {
    pub trace_update_interval: Option<Duration>,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub(crate) struct JobVariable {
    pub key: String,
    #[serde(deserialize_with = "deserialize_null_default")]
    pub value: String,
    pub public: bool,
    pub masked: bool,
}

fn variable_hash<'de, D>(deserializer: D) -> Result<HashMap<String, JobVariable>, D::Error>
where
    D: Deserializer<'de>,
{
    let hash = Vec::<JobVariable>::deserialize(deserializer)?
        .drain(..)
        .map(|v| (v.key.clone(), v))
        .collect();
    Ok(hash)
}

#[derive(Copy, Clone, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum JobStepWhen {
    Always,
    OnFailure,
    OnSuccess,
}

/// Phase of the gitlab job steps
#[derive(Copy, Clone, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum Phase {
    /// script step; Practically this is before_script + script as defined in the gitlab job yaml
    Script,
    /// after_script step
    AfterScript,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub(crate) struct JobStep {
    pub name: Phase,
    pub script: Vec<String>,
    pub timeout: u32,
    pub when: JobStepWhen,
    pub allow_failure: bool,
}

#[derive(Copy, Clone, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ArtifactWhen {
    Always,
    OnFailure,
    OnSuccess,
}

impl Default for ArtifactWhen {
    fn default() -> Self {
        Self::OnSuccess
    }
}

#[derive(Copy, Clone, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ArtifactFormat {
    Zip,
    Gzip,
    Raw,
}

impl Default for ArtifactFormat {
    fn default() -> Self {
        Self::Zip
    }
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub(crate) struct JobArtifact {
    pub name: Option<String>,
    #[serde(default, deserialize_with = "deserialize_null_default")]
    pub untracked: bool,
    pub paths: Vec<String>,
    #[serde(deserialize_with = "deserialize_null_default")]
    pub when: ArtifactWhen,
    pub artifact_type: String,
    #[serde(deserialize_with = "deserialize_null_default")]
    pub artifact_format: ArtifactFormat,
    pub expire_in: Option<String>,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub(crate) struct JobArtifactFile {
    pub filename: String,
    pub size: usize,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub(crate) struct JobDependency {
    pub id: u64,
    pub name: String,
    pub token: String,
    pub artifacts_file: Option<JobArtifactFile>,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub(crate) struct JobResponse {
    pub id: u64,
    pub token: String,
    pub allow_git_fetch: bool,
    #[serde(deserialize_with = "variable_hash")]
    pub variables: HashMap<String, JobVariable>,
    pub steps: Vec<JobStep>,
    #[serde(deserialize_with = "deserialize_null_default")]
    pub dependencies: Vec<JobDependency>,
    #[serde(deserialize_with = "deserialize_null_default")]
    pub artifacts: Vec<JobArtifact>,
    #[serde(flatten)]
    unparsed: JsonValue,
}

impl JobResponse {
    pub fn step(&self, name: Phase) -> Option<&JobStep> {
        self.steps.iter().find(|s| s.name == name)
    }
}

#[derive(Error, Debug)]
pub enum Error {
    #[error("Unexpected reply code {0}")]
    UnexpectedStatus(StatusCode),
    #[error("Request failure {0}")]
    Request(#[from] reqwest::Error),
    #[error("Failed to write to destination {0}")]
    WriteFailure(#[source] futures::io::Error),
    #[error("Failed to parse zip file: {0}")]
    ZipFile(#[from] ZipError),
    #[error("Empty trace")]
    EmptyTrace,
}

#[derive(Clone, Debug)]
pub(crate) struct Client {
    client: reqwest::Client,
    url: Url,
    token: String,
}

impl Client {
    pub fn new(url: Url, token: String) -> Self {
        Self {
            client: reqwest::Client::new(),
            url,
            token,
        }
    }

    pub async fn request_job(&self) -> Result<Option<JobResponse>, Error> {
        let request = JobRequest {
            token: &self.token,
            info: VersionInfo {
                // Setting `refspecs` is required to run detached MR pipelines.
                features: FeaturesInfo { refspecs: true },
            },
        };

        let mut url = self.url.clone();
        url.path_segments_mut()
            .unwrap()
            .extend(&["api", "v4", "jobs", "request"]);

        let r = self
            .client
            .post(url)
            .json(&request)
            .send()
            .await?
            .error_for_status()?;

        match r.status() {
            StatusCode::CREATED => Ok(Some(r.json().await?)),
            StatusCode::NO_CONTENT => Ok(None),
            _ => Err(Error::UnexpectedStatus(r.status())),
        }
    }

    pub async fn update_job(
        &self,
        id: u64,
        token: &str,
        state: JobState,
    ) -> Result<JobUpdateReply, Error> {
        let mut url = self.url.clone();
        let id_s = format!("{}", id);
        url.path_segments_mut()
            .unwrap()
            .extend(&["api", "v4", "jobs", &id_s]);

        let update = JobUpdate { token, state };

        let r = self.client.put(url).json(&update).send().await?;
        let trace_update_interval = r
            .headers()
            .get(GITLAB_TRACE_UPDATE_INTERVAL)
            .and_then(|v| Some(Duration::from_secs(v.to_str().ok()?.parse().ok()?)));
        match r.status() {
            StatusCode::OK => Ok(JobUpdateReply {
                trace_update_interval,
            }),
            _ => Err(Error::UnexpectedStatus(r.status())),
        }
    }

    pub async fn trace<B>(
        &self,
        id: u64,
        token: &str,
        body: B,
        start: usize,
        length: usize,
    ) -> Result<TraceReply, Error>
    where
        B: Into<Body>,
    {
        if length == 0 {
            return Err(Error::EmptyTrace);
        }

        let mut url = self.url.clone();
        let id_s = format!("{}", id);
        url.path_segments_mut()
            .unwrap()
            .extend(&["api", "v4", "jobs", &id_s, "trace"]);

        let range = format!("{}-{}", start, start + length - 1);

        let r = self
            .client
            .patch(url)
            .header("JOB-TOKEN", token)
            .header(reqwest::header::CONTENT_RANGE, range)
            .body(body)
            .send()
            .await?;

        let trace_update_interval = r
            .headers()
            .get(GITLAB_TRACE_UPDATE_INTERVAL)
            .and_then(|v| Some(Duration::from_secs(v.to_str().ok()?.parse().ok()?)));

        match r.status() {
            StatusCode::ACCEPTED => Ok(TraceReply {
                trace_update_interval,
            }),
            _ => Err(Error::UnexpectedStatus(r.status())),
        }
    }

    pub async fn download_artifact<D: AsyncWrite + Unpin>(
        &self,
        id: u64,
        token: &str,
        mut dest: D,
    ) -> Result<(), Error> {
        let mut url = self.url.clone();
        let id_s = format!("{}", id);
        url.path_segments_mut()
            .unwrap()
            .extend(&["api", "v4", "jobs", &id_s, "artifacts"]);

        let mut r = self
            .client
            .get(url)
            .header("JOB-TOKEN", token)
            .send()
            .await?;

        match r.status() {
            StatusCode::OK => {
                while let Some(ref chunk) = r.chunk().await? {
                    dest.write_all(chunk).await.map_err(Error::WriteFailure)?
                }
                Ok(())
            }
            _ => Err(Error::UnexpectedStatus(r.status())),
        }
    }

    pub async fn upload_artifact<D>(
        &self,
        id: u64,
        token: &str,
        name: &str,
        data: D,
    ) -> Result<(), Error>
    where
        D: Into<Body>,
    {
        let part = Part::stream(data).file_name(name.to_string());
        let form = Form::new().part("file", part);

        let mut url = self.url.clone();
        let id_s = format!("{}", id);
        url.path_segments_mut()
            .unwrap()
            .extend(&["api", "v4", "jobs", &id_s, "artifacts"]);

        let r = self
            .client
            .post(url)
            .header("JOB-TOKEN", token)
            .multipart(form)
            .send()
            .await?;

        match r.status() {
            StatusCode::CREATED => Ok(()),
            _ => Err(Error::UnexpectedStatus(r.status())),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use gitlab_runner_mock::GitlabRunnerMock;
    use serde_json::json;

    #[test]
    fn deserialize_variables() {
        #[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
        struct Test {
            #[serde(deserialize_with = "variable_hash")]
            variables: HashMap<String, JobVariable>,
        }

        let json = json!({
            "variables": [
                { "key": "VAR1", "value": "1", "public": true, "masked": false },
                { "key": "VAR2", "value": "2", "public": false, "masked": true }
            ]
        });

        let t: Test = serde_json::from_str(&json.to_string()).expect("Failed to deserialize json");
        assert_eq!(2, t.variables.len());
        let v = t.variables.get("VAR1").unwrap();
        assert_eq!(
            &JobVariable {
                key: "VAR1".to_string(),
                value: "1".to_string(),
                public: true,
                masked: false
            },
            v
        );
        let v = t.variables.get("VAR2").unwrap();
        assert_eq!(
            &JobVariable {
                key: "VAR2".to_string(),
                value: "2".to_string(),
                public: false,
                masked: true
            },
            v
        );
    }

    #[tokio::test]
    async fn no_job() {
        let mock = GitlabRunnerMock::start().await;

        let client = Client::new(mock.uri(), mock.runner_token().to_string());

        let job = client.request_job().await.unwrap();

        assert_eq!(None, job);
    }

    #[tokio::test]
    async fn process_job() {
        let mock = GitlabRunnerMock::start().await;
        mock.add_dummy_job("process job".to_string());

        let client = Client::new(mock.uri(), mock.runner_token().to_string());

        if let Some(job) = client.request_job().await.unwrap() {
            client
                .update_job(job.id, &job.token, JobState::Success)
                .await
                .unwrap();
        } else {
            panic!("No job!")
        }

        let job = client.request_job().await.unwrap();
        assert_eq!(None, job);
    }
}