pipedash-plugin-azure-devops 0.10.0

Azure DevOps Pipelines plugin for Pipedash
Documentation
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
use std::sync::Arc;
use std::time::Duration;

use bytes::Bytes;
use pipedash_plugin_api::{
    check_response,
    map_send_error,
    next_log_chunk,
    redact_url,
    LogCursor,
    LogRead,
    LogSink,
    PluginError,
    PluginResult,
    RetryPolicy,
};
use reqwest::{
    header::{
        ACCEPT,
        CONTENT_TYPE,
    },
    Method,
    StatusCode,
    Url,
};
use serde::de::DeserializeOwned;
use serde_json::{
    json,
    Value,
};

use crate::log_tail::{
    BoundaryScan,
    LogPosition,
    Scan,
    Tally,
};
use crate::types::{
    Build,
    Definition,
    DefinitionDetail,
    ListResponse,
    Project,
    Timeline,
};

const API_VERSION: &str = "7.0";
const CONTINUATION_HEADER: &str = "x-ms-continuationtoken";
const PAGE_SIZE: usize = 100;
const MAX_PAGES: usize = 100;
const LOG_TIMEOUT: Duration = Duration::from_secs(900);

pub(crate) struct AzureDevOpsClient {
    http_client: Arc<reqwest::Client>,
    base_url: Url,
    token: String,
    retry_policy: RetryPolicy,
}

impl AzureDevOpsClient {
    pub fn new(http_client: Arc<reqwest::Client>, base_url: Url, token: String) -> Self {
        Self {
            http_client,
            base_url,
            token,
            retry_policy: RetryPolicy::default(),
        }
    }

    pub fn server_url(&self) -> &Url {
        &self.base_url
    }

    pub async fn ping(&self) -> PluginResult<()> {
        self.list::<Project>(None, "_apis/projects", &[], 1, 1)
            .await
            .map(drop)
    }

    pub async fn list_projects(&self) -> PluginResult<Vec<Project>> {
        self.list(None, "_apis/projects", &[], PAGE_SIZE, usize::MAX)
            .await
    }

    pub async fn list_definitions(&self, project: &str) -> PluginResult<Vec<Definition>> {
        self.list(
            Some(project),
            "_apis/build/definitions",
            &[("includeLatestBuilds", "true".to_string())],
            PAGE_SIZE,
            usize::MAX,
        )
        .await
    }

    pub async fn has_definitions(&self, project: &str) -> PluginResult<bool> {
        let definitions: Vec<Definition> = self
            .list(Some(project), "_apis/build/definitions", &[], 1, 1)
            .await?;
        Ok(!definitions.is_empty())
    }

    pub async fn get_definition(
        &self, project: &str, definition_id: i64,
    ) -> PluginResult<DefinitionDetail> {
        let path = format!("_apis/build/definitions/{definition_id}");
        let (definition, _) = self.get_json(Some(project), &path, &[]).await?;
        Ok(definition)
    }

    pub async fn list_builds(
        &self, project: &str, definition_id: i64, limit: usize,
    ) -> PluginResult<Vec<Build>> {
        self.list(
            Some(project),
            "_apis/build/builds",
            &[
                ("definitions", definition_id.to_string()),
                ("queryOrder", "queueTimeDescending".to_string()),
            ],
            limit,
            limit,
        )
        .await
    }

    pub async fn get_build(&self, project: &str, build_id: i64) -> PluginResult<Build> {
        let path = format!("_apis/build/builds/{build_id}");
        let (build, _) = self.get_json(Some(project), &path, &[]).await?;
        Ok(build)
    }

    pub async fn get_timeline(&self, project: &str, build_id: i64) -> PluginResult<Timeline> {
        let path = format!("_apis/build/builds/{build_id}/timeline");
        let (timeline, _) = self.get_json(Some(project), &path, &[]).await?;
        Ok(timeline)
    }

    pub async fn stream_build_log(
        &self, project: &str, build_id: i64, log_id: i64, attempt: i64, from: Option<&LogCursor>,
        sink: &mut LogSink,
    ) -> PluginResult<LogRead> {
        let mut resume = match from {
            None => None,
            Some(cursor) => {
                let known = cursor
                    .parse::<LogPosition>()
                    .filter(|position| position.is_for(build_id, log_id, attempt));
                if known.is_none() {
                    sink.restart()?;
                }
                known
            }
        };
        let mut opened = None;
        if let Some(position) = resume.as_mut() {
            opened = self
                .open_after_boundary(project, build_id, log_id, position)
                .await?;
            if opened.is_none() {
                sink.restart()?;
                resume = None;
            }
        }
        let (mut response, rest) = match opened {
            Some(opened) => opened,
            None => (
                self.open_build_log(project, build_id, log_id, None).await?,
                Bytes::new(),
            ),
        };

        let mut tally = resume.as_ref().map_or_else(Tally::default, Tally::resume);
        let mut eol = resume.as_ref().is_some_and(|position| position.open);
        let mut chunk = Some(rest);
        while let Some(bytes) = chunk {
            if !bytes.is_empty() {
                if std::mem::take(&mut eol) {
                    sink.write(Bytes::from_static(b"\n")).await?;
                }
                tally.feed(&bytes);
                sink.write(bytes).await?;
            }
            chunk = next_log_chunk(&mut response).await?;
        }

        let appended = resume.is_some();
        let next = match resume {
            Some(position) if !tally.fed() => position,
            _ => tally.position(build_id, log_id, attempt),
        };
        let cursor = LogCursor::new(&next)?;
        Ok(if appended {
            LogRead::append(cursor)
        } else {
            LogRead::replace(Some(cursor))
        })
    }

    async fn open_after_boundary(
        &self, project: &str, build_id: i64, log_id: i64, position: &mut LogPosition,
    ) -> PluginResult<Option<(reqwest::Response, Bytes)>> {
        if position.lines == 0 {
            let response = self.open_build_log(project, build_id, log_id, None).await?;
            return Ok(Some((response, Bytes::new())));
        }
        if position.first_line.is_none() {
            let Some(start) = position.probe_line() else {
                return Ok(None);
            };
            let mut probe = self
                .open_build_log(project, build_id, log_id, Some(start))
                .await?;
            match first_line_hash(&mut probe).await? {
                Some((hash, _)) if position.settle(hash) => {}
                _ => return Ok(None),
            }
        }
        let Some(start) = position.boundary_line() else {
            return Ok(None);
        };
        let mut response = self
            .open_build_log(project, build_id, log_id, Some(start))
            .await?;
        Ok(match first_line_hash(&mut response).await? {
            Some((hash, rest)) if hash == position.last => Some((response, rest)),
            _ => None,
        })
    }

    async fn open_build_log(
        &self, project: &str, build_id: i64, log_id: i64, start_line: Option<u64>,
    ) -> PluginResult<reqwest::Response> {
        let path = format!("_apis/build/builds/{build_id}/logs/{log_id}");
        let query: Vec<_> = start_line
            .map(|line| ("startLine", line.to_string()))
            .into_iter()
            .collect();
        let url = self.url(Some(project), &path, &query)?;
        let response = self
            .retry_policy
            .retry_unsent(&url, || {
                self.authorized(Method::GET, &url)
                    .header(ACCEPT, "text/plain")
                    .timeout(LOG_TIMEOUT)
                    .send()
            })
            .await?;
        if matches!(response.status(), StatusCode::NOT_FOUND | StatusCode::GONE) {
            return Err(PluginError::PipelineNotFound(format!(
                "Log {log_id} of build {build_id} is no longer available"
            )));
        }
        signed_in(response).await
    }

    pub async fn queue_build(&self, project: &str, body: &Value) -> PluginResult<Build> {
        let response = self
            .send_json(Method::POST, project, "_apis/build/builds", body)
            .await?;
        parse(response).await
    }

    pub async fn cancel_build(&self, project: &str, build_id: i64) -> PluginResult<()> {
        let path = format!("_apis/build/builds/{build_id}");
        self.send_json(
            Method::PATCH,
            project,
            &path,
            &json!({ "status": "cancelling" }),
        )
        .await
        .map(drop)
    }

    fn url(
        &self, project: Option<&str>, path: &str, query: &[(&str, String)],
    ) -> PluginResult<Url> {
        let mut url = self.base_url.clone();
        url.path_segments_mut()
            .map_err(|()| PluginError::InvalidConfig("Invalid Azure DevOps URL".to_string()))?
            .pop_if_empty()
            .extend(project)
            .extend(path.split('/'));
        url.query_pairs_mut()
            .append_pair("api-version", API_VERSION)
            .extend_pairs(query);
        Ok(url)
    }

    fn authorized(&self, method: Method, url: &Url) -> reqwest::RequestBuilder {
        self.http_client
            .request(method, url.clone())
            .basic_auth("", Some(&self.token))
    }

    fn request(&self, method: Method, url: &Url) -> reqwest::RequestBuilder {
        self.authorized(method, url)
            .header(ACCEPT, "application/json")
    }

    async fn send_json(
        &self, method: Method, project: &str, path: &str, body: &Value,
    ) -> PluginResult<reqwest::Response> {
        let url = self.url(Some(project), path, &[])?;
        let response = self
            .retry_policy
            .retry_unsent(&url, || {
                self.request(method.clone(), &url).json(body).send()
            })
            .await?;
        signed_in(response).await
    }

    async fn get_json<T: DeserializeOwned>(
        &self, project: Option<&str>, path: &str, query: &[(&str, String)],
    ) -> PluginResult<(T, Option<String>)> {
        let url = self.url(project, path, query)?;
        self.retry_policy
            .retry(|| async {
                let response = self
                    .request(Method::GET, &url)
                    .send()
                    .await
                    .map_err(|e| map_send_error(e, &url))?;
                let response = signed_in(response).await?;
                let continuation = response
                    .headers()
                    .get(CONTINUATION_HEADER)
                    .and_then(|value| value.to_str().ok())
                    .filter(|token| !token.is_empty())
                    .map(str::to_string);
                Ok((parse(response).await?, continuation))
            })
            .await
    }

    async fn list<T: DeserializeOwned>(
        &self, project: Option<&str>, path: &str, query: &[(&str, String)], page_size: usize,
        max: usize,
    ) -> PluginResult<Vec<T>> {
        let mut items = Vec::new();
        let mut continuation: Option<String> = None;
        for _ in 0..MAX_PAGES {
            if items.len() >= max {
                break;
            }
            let mut page_query = query.to_vec();
            page_query.push(("$top", page_size.min(max - items.len()).to_string()));
            if let Some(token) = continuation.take() {
                page_query.push(("continuationToken", token));
            }
            let (page, next): (ListResponse<T>, _) =
                self.get_json(project, path, &page_query).await?;
            items.extend(page.value);
            continuation = next;
            if continuation.is_none() {
                break;
            }
        }
        if continuation.is_some() && items.len() < max {
            return Err(PluginError::ApiError(format!(
                "Azure DevOps list {path} still has more items after {MAX_PAGES} pages"
            )));
        }
        items.truncate(max);
        Ok(items)
    }
}

async fn first_line_hash(response: &mut reqwest::Response) -> PluginResult<Option<(u64, Bytes)>> {
    let mut scan = BoundaryScan::new();
    while let Some(chunk) = next_log_chunk(response).await? {
        match scan.feed(chunk) {
            Scan::More => {}
            Scan::Line(hash, rest) => return Ok(Some((hash, rest))),
            Scan::TooLong => return Ok(None),
        }
    }
    Ok(scan.finish().map(|hash| (hash, Bytes::new())))
}

async fn signed_in(response: reqwest::Response) -> PluginResult<reqwest::Response> {
    let response = check_response(response).await?;
    let status = response.status();
    let html = response
        .headers()
        .get(CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.get(..9))
        .is_some_and(|media_type| media_type.eq_ignore_ascii_case("text/html"));
    if status == StatusCode::NON_AUTHORITATIVE_INFORMATION || status.is_redirection() || html {
        return Err(PluginError::AuthenticationFailed(format!(
            "{} from {}: Azure DevOps answered with a sign-in page instead of data. Check that the personal access token is valid and has not expired",
            status.as_u16(),
            redact_url(response.url())
        )));
    }
    Ok(response)
}

async fn parse<T: DeserializeOwned>(response: reqwest::Response) -> PluginResult<T> {
    let url = redact_url(response.url());
    response.json().await.map_err(|e| {
        PluginError::ApiError(format!(
            "Failed to parse Azure DevOps API response from {url}: {}",
            e.without_url()
        ))
    })
}