jira_query 1.7.2

Access tickets on a remote Jira instance.
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
411
412
413
414
415
416
417
418
419
420
421
422
423
/*
Copyright 2022 Marek Suchánek <msuchane@redhat.com>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Jira API documentation:
// * https://docs.atlassian.com/software/jira/docs/api/REST/latest/
// * https://docs.atlassian.com/jira-software/REST/latest/

use crate::errors::JiraQueryError;
use crate::issue_model::{CloudSearchResults, Issue, JqlResults};

// The prefix of every subsequent REST request.
// This string comes directly after the host in the URL.
const REST_PREFIX: &str = "rest/api/2";

const MAX_KEYS_PER_URL_CHUNK: usize = 50;

/// Configuration and credentials to access a Jira instance.
pub struct JiraInstance {
    pub host: String,
    pub auth: Auth,
    pub pagination: Pagination,
    client: reqwest::Client,
    is_cloud: bool,
}

/// The authentication method used to contact Jira.
pub enum Auth {
    Anonymous,
    ApiKey(String),
    Basic { user: String, password: String },
}

// We could set a default enum variant and derive, but that raises the MSRV to 1.62.
impl Default for Auth {
    fn default() -> Self {
        Self::Anonymous
    }
}

/// Controls the upper limit of how many tickets the response from Jira can contain:
///
/// * `Default`: Use the default settings of this instance, which sets an arbitrary limit on the number of tickets.
/// * `MaxResults`: Set the upper limit to this value. Note that each instance has a maximum allowed value,
/// and if you set `MaxResults` higher than that, the instance uses its own maximum allowed value.
/// * `ChunkSize`: Access the tickets in a series of requests, each accessing the number of tickets equal to the chunk size.
/// This enables you to access an unlimited number of tickets, as long as the chunk size is smaller
/// than the maximum allowed results size for the instance.
pub enum Pagination {
    Default,
    MaxResults(u32),
    ChunkSize(u32),
}

// We could set a default enum variant and derive, but that raises the MSRV to 1.62.
impl Default for Pagination {
    fn default() -> Self {
        Self::Default
    }
}

/// The method of the request to Jira. Either request specific IDs,
/// or use a free-form JQL search query.
enum Method<'a> {
    Key(&'a str),
    Keys(&'a [&'a str]),
    Search(&'a str),
}

impl<'a> Method<'a> {
    fn url_fragment(&self, is_cloud: bool) -> String {
        match self {
            Self::Key(id) => format!("issue/{id}"),
            Self::Keys(ids) => {
                let jql = format!("id%20in%20({})", ids.join(","));
                if is_cloud {
                    // The cloud-specific path
                    format!("search/jql?jql={jql}")
                } else {
                    // The local-specific
                    format!("search?jql={jql}")
                }
            }
            Self::Search(query) => {
                if is_cloud {
                    // The cloud-specific path
                    format!("search/jql?jql={query}")
                } else {
                    // The local-specific path
                    format!("search?jql={query}")
                }
            }
        }
    }
}

impl JiraInstance {
    /// Create a new `BzInstance` struct using a host URL, with default values
    /// for all options.
    pub fn at(host: String) -> Result<Self, JiraQueryError> {
        // TODO: This function takes host as a String, even though client is happy with &str.
        // The String is only used in the host struct attribute.
        let client = reqwest::Client::new();

        Ok(Self {
            host,
            client,
            auth: Auth::default(),
            pagination: Pagination::default(),
            is_cloud: false,
        })
    }

    #[must_use]
    pub fn for_cloud(mut self) -> Self {
        self.is_cloud = true;
        self
    }

    /// Set the authentication method of this `JiraInstance`.
    #[must_use]
    pub fn authenticate(mut self, auth: Auth) -> Self {
        self.auth = auth;
        self
    }

    /// Set the http client of this `JiraInstance`.
    #[must_use]
    pub fn with_client(mut self, client: reqwest::Client) -> Self {
        self.client = client;
        self
    }

    /// Set the pagination method of this `JiraInstance`.
    #[must_use]
    pub const fn paginate(mut self, pagination: Pagination) -> Self {
        self.pagination = pagination;
        self
    }

    /// Based on the request method, form a complete, absolute URL
    /// to download the tickets from the REST API.
    #[must_use]
    fn path(&self, method: &Method, start_at: u32) -> String {
        let max_results = match self.pagination {
            Pagination::Default => String::new(),
            // For both MaxResults and ChunkSIze, set the maxResults size to the value set in the variant.
            // The maxResults size is relevant for ChunkSize in that each chunk requires its own results
            // to be at least this large.
            Pagination::MaxResults(n) | Pagination::ChunkSize(n) => format!("&maxResults={n}"),
        };

        // The `startAt` option is only valid with JQL. With a URL by key, it breaks the REST query.
        let start_at = match method {
            Method::Key(_) => String::new(),
            Method::Keys(_) | Method::Search(_) => format!("&startAt={start_at}"),
        };

        // For search-based methods, explicitly request all fields to ensure
        // the response contains the data needed for deserialization.
        let fields_param = match method {
            Method::Key(_) => String::new(),
            Method::Keys(_) | Method::Search(_) => "&fields=*all".to_string(),
        };

        format!(
            "{}/{}/{}{}{}{}",
            self.host,
            REST_PREFIX,
            method.url_fragment(self.is_cloud),
            max_results,
            start_at,
            fields_param
        )
    }

    /// Build a URL for Jira Cloud's enhanced search endpoint (`/search/jql`),
    /// which uses cursor-based pagination with `nextPageToken`.
    #[must_use]
    fn cloud_path(&self, method: &Method, next_page_token: Option<&str>) -> String {
        let max_results = match self.pagination {
            Pagination::Default => String::new(),
            Pagination::MaxResults(n) | Pagination::ChunkSize(n) => format!("&maxResults={n}"),
        };

        let token_param = match next_page_token {
            Some(token) => format!("&nextPageToken={token}"),
            None => String::new(),
        };

        // For search-based methods, explicitly request all fields.
        let fields_param = match method {
            Method::Key(_) => String::new(),
            Method::Keys(_) | Method::Search(_) => "&fields=*all".to_string(),
        };

        format!(
            "{}/{}/{}{}{}{}",
            self.host,
            REST_PREFIX,
            method.url_fragment(self.is_cloud),
            max_results,
            token_param,
            fields_param
        )
    }

    /// Download the specified URL using the configured authentication.
    async fn authenticated_get(&self, url: &str) -> Result<reqwest::Response, reqwest::Error> {
        let request_builder = self.client.get(url);
        let authenticated = match &self.auth {
            Auth::Anonymous => request_builder,
            Auth::ApiKey(key) => request_builder.header("Authorization", &format!("Bearer {key}")),
            Auth::Basic { user, password } => request_builder.basic_auth(user, Some(password)),
        };
        authenticated.send().await
    }

    // This method uses a separate implementation from `issues` because Jira provides a way
    // to request a single ticket specifically. That conveniently handles error cases
    // where no tickets might match, or more than one might.
    /// Access a single issue by its key.
    pub async fn issue(&self, key: &str) -> Result<Issue, JiraQueryError> {
        let url = self.path(&Method::Key(key), 0);

        // Gets an issue by ID and deserializes the JSON to data variable
        let issue = self.authenticated_get(&url).await?.json::<Issue>().await?;

        log::debug!("{:#?}", issue);

        Ok(issue)
    }

    /// Access several issues by their keys.
    ///
    /// If the list of keys is empty, returns an empty list back with no errors.
    pub async fn issues(&self, keys: &[&str]) -> Result<Vec<Issue>, JiraQueryError> {
        if keys.is_empty() {
            return Ok(Vec::new());
        }

        let mut all_collected_issues: Vec<Issue> = Vec::with_capacity(keys.len());

        // Chunk keys into batches to avoid creating a URL that is too long.
        for key_chunk in keys.chunks(20) {
            if key_chunk.is_empty() {
                continue;
            }

            log::debug!(
                "Fetching batch of {} keys: {}",
                key_chunk.len(),
                key_chunk.join(", ")
            );

            let method = Method::Keys(key_chunk);

            // For Cloud, use cursor-based pagination even for ID-based searches,
            // because the search/jql endpoint always requires it.
            if self.is_cloud {
                let mut issues_from_chunk = self.cloud_paginated_issues(&method).await?;
                all_collected_issues.append(&mut issues_from_chunk);
            } else {
                let mut issues_from_chunk = self.chunk_of_issues(&method, 0).await?;
                all_collected_issues.append(&mut issues_from_chunk);
            }
        }

        if !keys.is_empty() && all_collected_issues.is_empty() {
            Err(JiraQueryError::NoIssues)
        } else {
            Ok(all_collected_issues)
        }
    }

    /// Download all issues specified in the request as a series of chunks or pages.
    /// The request controls whether the download works with IDs or JQL.
    /// This function only processes the resulting pages coming back from Jira
    /// and stops the iteration at the last page.
    ///
    /// See the Jira documentation:
    /// <https://confluence.atlassian.com/jirakb/changing-maxresults-parameter-for-jira-rest-api-779160706.html>.
    async fn paginated_issues(
        &self,
        method: &Method<'_>,
        chunk_size: u32,
    ) -> Result<Vec<Issue>, JiraQueryError> {
        let mut all_issues = Vec::new();
        let mut start_at = 0;

        loop {
            let mut chunk_issues = self.chunk_of_issues(method, start_at).await?;
            // Calculate the length now before the content moves to `all_issues`.
            let page_size = chunk_issues.len();
            all_issues.append(&mut chunk_issues);

            // If this page contains fewer issues than the chunk size,
            // it's the last page. Stop the loop.
            if page_size < chunk_size as usize {
                break;
            }

            start_at += chunk_size;
        }

        Ok(all_issues)
    }

    /// Download all issues using Jira Cloud's cursor-based pagination.
    ///
    /// The Cloud `search/jql` endpoint uses `nextPageToken` for pagination
    /// instead of offset-based `startAt`. Each response includes a `nextPageToken`
    /// field; when it's absent (or `isLast` is true), all pages have been fetched.
    async fn cloud_paginated_issues(
        &self,
        method: &Method<'_>,
    ) -> Result<Vec<Issue>, JiraQueryError> {
        let mut all_issues = Vec::new();
        let mut next_page_token: Option<String> = None;

        loop {
            let url = self.cloud_path(method, next_page_token.as_deref());

            log::debug!("Cloud paginated request: {}", url);

            let response = self.authenticated_get(&url).await?;
            let results = response.json::<CloudSearchResults>().await?;

            log::debug!("{:#?}", results);

            let page_size = results.issues.len();
            all_issues.extend(results.issues);

            // Stop if: no issues returned, or this is the last page, or no next token.
            if page_size == 0 {
                break;
            }
            if results.is_last.unwrap_or(false) {
                break;
            }
            match results.next_page_token {
                Some(token) if !token.is_empty() => {
                    next_page_token = Some(token);
                }
                _ => {
                    // No next page token means this is the last page.
                    break;
                }
            }
        }

        Ok(all_issues)
    }

    /// Download a specific list (chunk) of issues.
    /// Reused elsewhere as a building block of different pagination methods.
    async fn chunk_of_issues(
        &self,
        method: &Method<'_>,
        start_at: u32,
    ) -> Result<Vec<Issue>, JiraQueryError> {
        let url = self.path(method, start_at);

        let results = self
            .authenticated_get(&url)
            .await?
            .json::<JqlResults>()
            .await?;

        log::debug!("{:#?}", results);

        Ok(results.issues)
    }

    /// Access issues using a free-form JQL search.
    ///
    /// An example of a query: `project="CentOS Stream" AND priority = High`.
    pub async fn search(&self, query: &str) -> Result<Vec<Issue>, JiraQueryError> {
        let method = Method::Search(query);

        if self.is_cloud {
            // For Cloud, always use cursor-based pagination regardless of the
            // Pagination setting, because the search/jql endpoint requires it.
            self.cloud_paginated_issues(&method).await
        } else if let Pagination::ChunkSize(chunk_size) = self.pagination {
            // If Pagination is set to ChunkSize, split the issue keys into chunk by chunk size
            // and request each chunk separately.
            self.paginated_issues(&method, chunk_size).await
        } else {
            // If Pagination is not set to ChunkSize, use a single chunk request for all issues.
            let issues = self.chunk_of_issues(&method, 0).await?;

            Ok(issues)
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        let result = 2 + 2;
        assert_eq!(result, 4);
    }
    // #[test]
    // fn issues() {
    //     let results = crate::issues("todo", &["todo"], "todo");
    //     eprintln!("{:#?}", results);
    //     assert_eq!(results.issues.len(), todo);
    // }
}