Skip to main content

ai6_source_jira/
lib.rs

1//! `ai6-source-jira`: the `jira` provider. As a Source it runs a JQL search for the issues
2//! that carry the configured labels; as a Tracker it reads, comments on, labels, transitions
3//! and creates issues of one project. Requests are blocking; the host calls them off its
4//! async runtime.
5
6#![doc = include_str!("../README.md")]
7#![forbid(unsafe_code)]
8#![warn(missing_docs)]
9
10ai6::guatiao::providers!(Jira);
11
12mod adf;
13
14use std::path::PathBuf;
15use std::sync::Mutex;
16use std::time::{Duration, Instant};
17
18use ai6::guatiao::library::ProviderError;
19use ai6::guatiao::{FromValue, Provider, Schema, Status, ToValue};
20use ai6::{
21    IssueSpec, PostedComment, Reply, ReplyBatch, ReplyPoll, Source, SourceBatch, SourceFacts,
22    SourceItem, SourcePoll, Tracker, TrackerCapabilities, TrackerIssue, TrackerLink, TrackerPost,
23    TrackerUpdate, settled_cursor,
24};
25use serde::{Deserialize, Serialize};
26use url::Url;
27
28/// The provider ID an Operation names under `sources`.
29pub const PROVIDER_ID: &str = "jira";
30
31const FIELDS: &str = "summary,description,labels,reporter,updated";
32const ISSUE_FIELDS: &str =
33    "summary,description,labels,reporter,assignee,updated,status,parent,priority";
34/// The longest summary Jira takes.
35const SUMMARY_BYTES: usize = 255;
36
37/// Which Jira API the site speaks.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, ToValue, FromValue, Schema)]
39#[map(crate = ::ai6::guatiao, rename_all = "lowercase")]
40enum Deployment {
41    /// Jira Cloud: REST v3, ADF text, token-paged `search/jql`.
42    Cloud,
43    /// Jira Server or Data Center: REST v2, plain text, offset-paged `search`.
44    Server,
45}
46
47/// How requests authenticate.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, ToValue, FromValue, Schema)]
49#[map(crate = ::ai6::guatiao, rename_all = "lowercase")]
50enum Auth {
51    /// `email:token` as HTTP Basic (Jira Cloud API tokens).
52    Basic,
53    /// A personal access token as a Bearer credential (Data Center).
54    Bearer,
55}
56
57/// One instance's settings, from `[operation.<id>.sources.<name>]`.
58///
59/// The Station reads its own keys (`provider`, `intake`, `interval_secs`, the status maps and
60/// what Agents may touch) and passes the rest here.
61#[derive(Debug, Clone, ToValue, FromValue, Schema)]
62#[map(crate = ::ai6::guatiao, deny_unknown_fields)]
63pub struct Settings {
64    /// The site root, for example `https://example.atlassian.net`.
65    #[schema(title = "Site")]
66    site: String,
67    /// A PEM file of certificate authorities to trust besides the public roots, by absolute path.
68    /// A set one is reported as a weakening: more authorities can vouch for this service.
69    #[schema(title = "Certificate authorities")]
70    ca_file: Option<PathBuf>,
71    /// The project key; a bare string under `sources` is this value.
72    #[schema(title = "Project")]
73    project: Option<String>,
74    /// Another spelling of `project`, which a bare string under `sources` is; set at most one.
75    #[schema(title = "Target")]
76    target: Option<String>,
77    /// An extra JQL condition, combined with the project and label filters by AND.
78    #[schema(title = "Extra JQL")]
79    jql: Option<String>,
80    /// An issue needs every one of these labels to become a Mission.
81    #[schema(title = "Intake labels")]
82    #[map(default = vec!["ai6-ready".to_owned()])]
83    labels: Vec<String>,
84    /// Which API the site speaks.
85    #[schema(title = "Deployment")]
86    #[map(default = Deployment::Cloud)]
87    deployment: Deployment,
88    /// How requests authenticate.
89    #[schema(title = "Authentication")]
90    #[map(default = Auth::Basic)]
91    auth: Auth,
92    /// The environment variable holding the account email (Basic authentication only).
93    #[schema(title = "Email variable", format = "credential-variable")]
94    email_env: Option<String>,
95    /// The environment variable holding the API token.
96    #[schema(
97        title = "Token variable",
98        format = "credential-variable:JIRA_API_TOKEN,JIRA_TOKEN"
99    )]
100    #[map(default = "JIRA_API_TOKEN".to_owned())]
101    token_env: String,
102    /// Seconds one request may take. 0 is refused.
103    #[schema(title = "A request may take", format = "seconds")]
104    #[map(default = 30)]
105    request_timeout_secs: u64,
106    /// Issues asked for per page. 0 is refused.
107    #[schema(title = "Issues per page")]
108    #[map(default = 50)]
109    page_size: u32,
110    /// Pages one poll reads at most. 0 is refused.
111    #[schema(title = "Pages per poll")]
112    #[map(default = 5)]
113    max_pages: u64,
114    /// Seconds a poll searches behind the cursor, for an issue the search showed after a newer
115    /// one. 0 searches from the cursor's minute.
116    #[schema(title = "Search behind the cursor by", format = "seconds")]
117    #[map(default = 60)]
118    settling_secs: u64,
119    /// Account IDs (Cloud) or user names (Server), besides the issue's reporter and
120    /// assignee, whose comments may answer a question.
121    #[schema(title = "People who may answer")]
122    #[map(default)]
123    reply_authors: Vec<String>,
124    /// The issue type a created issue has.
125    #[schema(title = "Type of a new issue")]
126    #[map(default = "Task".to_owned())]
127    issue_type: String,
128    /// The issue type of a child; default the project's first sub-task type.
129    #[schema(title = "Type of a child")]
130    subtask_type: Option<String>,
131    /// How long, in seconds, the project's answers are remembered.
132    #[schema(title = "Remember the project for", format = "seconds")]
133    #[map(default = 600)]
134    capability_ttl_secs: u64,
135    /// The issue link type that ties a child to a parent it cannot sit under.
136    #[schema(title = "Link type")]
137    #[map(default = "Relates".to_owned())]
138    link_type: String,
139    /// The page people read the issues on as a board; the project's boards page when unset (none
140    /// for an instance that reads by JQL alone). `https`.
141    #[schema(title = "Board address")]
142    board_url: Option<String>,
143}
144
145/// What the project's create metadata said, kept with the capabilities.
146#[derive(Debug, Clone)]
147struct Discovered {
148    capabilities: TrackerCapabilities,
149    /// The first sub-task issue type, when the project has one.
150    subtask_type: Option<String>,
151}
152
153/// Jira issues as an AI6 Source and Tracker.
154#[derive(Debug, Provider)]
155#[provider(
156    Source,
157    Tracker,
158    id = "jira",
159    name = "Jira issues",
160    config = Settings,
161    crate = ::ai6::guatiao
162)]
163pub struct Jira {
164    settings: Settings,
165    site: Url,
166    agent: ureq::Agent,
167    /// The project-level answers and when they were read.
168    discovered: Mutex<Option<(Instant, Discovered)>>,
169}
170
171impl Jira {
172    /// Builds the provider from the instance's settings.
173    ///
174    /// # Errors
175    ///
176    /// Returns a message for an unknown key, a missing project and JQL, a malformed key or
177    /// an insecure site address.
178    pub fn new(mut settings: Settings) -> Result<Self, String> {
179        if let Some(target) = settings.target.take() {
180            if settings.project.is_some() {
181                return Err("set `project` or `target`, not both".to_owned());
182            }
183            settings.project = Some(target);
184        }
185        if settings.project.is_none() && settings.jql.is_none() {
186            return Err("set `project` or `jql`".to_owned());
187        }
188        if let Some(project) = &settings.project
189            && (project.is_empty()
190                || !project
191                    .chars()
192                    .all(|c| c.is_ascii_alphanumeric() || c == '_'))
193        {
194            return Err("project must be a Jira project key such as GUA".to_owned());
195        }
196        if settings.token_env.trim().is_empty() {
197            return Err("token_env must name an environment variable".to_owned());
198        }
199        if settings.auth == Auth::Basic && settings.email_env.is_none() {
200            return Err("auth = \"basic\" needs email_env (or use auth = \"bearer\")".to_owned());
201        }
202        let site =
203            Url::parse(settings.site.trim_end_matches('/')).map_err(|e| format!("site: {e}"))?;
204        let loopback = matches!(site.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"));
205        if site.scheme() != "https" && !(site.scheme() == "http" && loopback) {
206            return Err("site must be https (http only on a loopback address)".to_owned());
207        }
208        if let Some(board) = &settings.board_url {
209            https_page(board).map_err(|e| format!("board_url: {e}"))?;
210        }
211        for (name, zero) in [
212            ("request_timeout_secs", settings.request_timeout_secs == 0),
213            ("page_size", settings.page_size == 0),
214            ("max_pages", settings.max_pages == 0),
215        ] {
216            if zero {
217                return Err(format!("{name} must be at least 1"));
218            }
219        }
220        let mut agent = ureq::Agent::config_builder()
221            .timeout_global(Some(Duration::from_secs(settings.request_timeout_secs)))
222            .max_redirects(0)
223            .http_status_as_error(false);
224        if let Some(ca_file) = &settings.ca_file {
225            agent = agent.tls_config(ai6::tls::trusting_file(ca_file)?);
226        }
227        let agent = agent.build().into();
228        Ok(Self {
229            settings,
230            site,
231            agent,
232            discovered: Mutex::new(None),
233        })
234    }
235
236    fn api(&self, path: &str) -> String {
237        let version = match self.settings.deployment {
238            Deployment::Cloud => 3,
239            Deployment::Server => 2,
240        };
241        format!(
242            "{}/rest/api/{version}{path}",
243            self.site.as_str().trim_end_matches('/')
244        )
245    }
246
247    fn authorization(&self) -> Result<String, ProviderError> {
248        let env = |name: &str| {
249            std::env::var(name)
250                .ok()
251                .filter(|value| !value.trim().is_empty())
252                .ok_or_else(|| {
253                    failure(&format!(
254                        "no credential: set the environment variable {name}"
255                    ))
256                })
257        };
258        let token = env(&self.settings.token_env)?;
259        Ok(match (self.settings.auth, &self.settings.email_env) {
260            (Auth::Basic, Some(email_env)) => {
261                let pair = format!("{}:{token}", env(email_env)?);
262                format!("Basic {}", data_encoding::BASE64.encode(pair.as_bytes()))
263            }
264            _ => format!("Bearer {token}"),
265        })
266    }
267
268    fn call<B: Serialize + ?Sized>(
269        &self,
270        method: &str,
271        url: &str,
272        query: &[(&str, String)],
273        body: Option<&B>,
274        rejected: &str,
275    ) -> Result<ureq::http::Response<ureq::Body>, ProviderError> {
276        let mut url = Url::parse(url).map_err(|e| failure(&format!("bad address: {e}")))?;
277        for (key, value) in query {
278            url.query_pairs_mut().append_pair(key, value);
279        }
280        let mut request = ureq::http::Request::builder()
281            .method(method)
282            .uri(url.as_str())
283            .header("Accept", "application/json")
284            .header("Authorization", self.authorization()?);
285        let bytes = match body {
286            Some(body) => {
287                request = request.header("Content-Type", "application/json");
288                serde_json::to_vec(body).map_err(|e| failure(&e.to_string()))?
289            }
290            None => Vec::new(),
291        };
292        let request = request
293            .body(bytes)
294            .map_err(|e| failure(&format!("bad request: {e}")))?;
295        let response = self
296            .agent
297            .run(request)
298            .map_err(|e| failure(&format!("request failed: {e}")))?;
299        self.check(&response, rejected)?;
300        Ok(response)
301    }
302
303    fn get(
304        &self,
305        url: &str,
306        query: &[(&str, String)],
307        rejected: &str,
308    ) -> Result<ureq::http::Response<ureq::Body>, ProviderError> {
309        self.call("GET", url, query, None::<&()>, rejected)
310    }
311
312    fn get_json<T: serde::de::DeserializeOwned>(
313        &self,
314        url: &str,
315        query: &[(&str, String)],
316        rejected: &str,
317    ) -> Result<T, ProviderError> {
318        read_json(self.get(url, query, rejected)?)
319    }
320
321    /// `rejected` is the message for a 400, which Jira gives for what was asked, not for who
322    /// asked.
323    fn check(
324        &self,
325        response: &ureq::http::Response<ureq::Body>,
326        rejected: &str,
327    ) -> Result<(), ProviderError> {
328        let status = response.status().as_u16();
329        match status {
330            200..=299 => Ok(()),
331            429 => Err(failure(&format!(
332                "Jira rate limit reached; retry after {}s",
333                response
334                    .headers()
335                    .get("retry-after")
336                    .and_then(|value| value.to_str().ok())
337                    .unwrap_or("60")
338            ))),
339            401 | 403 => Err(failure(&format!(
340                "Jira refused the credential in {}",
341                self.settings.token_env
342            ))),
343            // Cloud answers a refused credential on an issue with 404, not 401.
344            404 => Err(failure(&format!(
345                "Jira does not show this issue or endpoint to the credential in {}",
346                self.settings.token_env
347            ))),
348            410 => Err(failure(
349                "Jira has removed this API (check `deployment`: Cloud has no REST v2 search)",
350            )),
351            400 => Err(failure(rejected)),
352            other => Err(failure(&format!("Jira answered status {other}"))),
353        }
354    }
355
356    /// The JQL for one poll: the configured filters, then everything changed since the cursor.
357    fn jql(&self, cursor: Option<&str>) -> String {
358        let mut clauses = Vec::new();
359        if let Some(project) = &self.settings.project {
360            clauses.push(format!("project = \"{project}\""));
361        }
362        for label in &self.settings.labels {
363            clauses.push(format!("labels = \"{}\"", label.replace(['"', '\\'], "")));
364        }
365        if let Some(jql) = &self.settings.jql {
366            clauses.push(format!("({jql})"));
367        }
368        clauses.push("statusCategory != Done".to_owned());
369        if let Some(since) = cursor.and_then(jql_minute) {
370            clauses.push(format!("updated >= \"{since}\""));
371        }
372        format!("{} ORDER BY updated ASC", clauses.join(" AND "))
373    }
374
375    /// The issue key of `item`, which must be well formed and in this instance's project.
376    fn key<'a>(&self, item: &'a str) -> Result<&'a str, ProviderError> {
377        let well_formed = item.split_once('-').is_some_and(|(project, number)| {
378            !project.is_empty()
379                && project
380                    .chars()
381                    .all(|c| c.is_ascii_alphanumeric() || c == '_')
382                && !number.is_empty()
383                && number.bytes().all(|b| b.is_ascii_digit())
384        });
385        if !well_formed {
386            return Err(bad_value(&format!("{item:?} is not a Jira issue key")));
387        }
388        if let Some(project) = &self.settings.project
389            && item.split_once('-').map(|(prefix, _)| prefix) != Some(project.as_str())
390        {
391            return Err(bad_value(&format!(
392                "foreign item {item:?}: this instance serves project {project}"
393            )));
394        }
395        Ok(item)
396    }
397
398    fn text(&self, body: &str) -> JiraText {
399        match self.settings.deployment {
400            Deployment::Cloud => JiraText::Adf(adf::document(body)),
401            Deployment::Server => JiraText::Plain(body.to_owned()),
402        }
403    }
404
405    /// The transitions open on `key`: ID, name and the category of the status it leads to.
406    fn transitions(&self, key: &str) -> Result<Vec<(String, String, String)>, ProviderError> {
407        let listing: TransitionsResponse = self.get_json(
408            &self.api(&format!("/issue/{key}/transitions")),
409            &[],
410            &format!("Jira rejected listing the transitions of {key}"),
411        )?;
412        Ok(listing
413            .transitions
414            .into_iter()
415            .map(|transition| {
416                let category = transition
417                    .to
418                    .and_then(|to| to.status_category)
419                    .and_then(|cat| cat.key)
420                    .unwrap_or_default();
421                (transition.id, transition.name, category)
422            })
423            .collect())
424    }
425
426    fn transition(&self, key: &str, wanted: &str) -> Result<(), ProviderError> {
427        let transitions = self.transitions(key)?;
428        let id = transitions
429            .iter()
430            .find_map(|(id, name, _)| {
431                (id == wanted || name.eq_ignore_ascii_case(wanted)).then_some(id)
432            })
433            .ok_or_else(|| {
434                unsupported(
435                    &format!("make the transition {wanted:?} on {key}"),
436                    &format!(
437                        "make {}",
438                        transitions
439                            .iter()
440                            .map(|(_, name, _)| name.as_str())
441                            .collect::<Vec<_>>()
442                            .join(", ")
443                    ),
444                )
445            })?;
446        self.call(
447            "POST",
448            &self.api(&format!("/issue/{key}/transitions")),
449            &[],
450            Some(&TransitionRequest {
451                transition: IdRef { id },
452            }),
453            &format!("Jira rejected the transition {wanted:?} on {key}"),
454        )?;
455        Ok(())
456    }
457
458    /// Tells an empty search from a search that could see nothing.
459    ///
460    /// Cloud answers a search by a refused credential, or naming a project the credential
461    /// cannot see, with status 200 and no issues, so a revoked token would otherwise look
462    /// like no work for as long as it stays revoked. The project lookup answers 404 to both.
463    fn confirm_empty_search(&self) -> Result<(), ProviderError> {
464        let token_env = &self.settings.token_env;
465        let (url, unseen) = match &self.settings.project {
466            Some(project) => (
467                self.api(&format!("/project/{project}")),
468                format!(
469                    "Jira shows no project {project} to the credential in {token_env}: \
470                     the credential is refused or the key is wrong"
471                ),
472            ),
473            None => (
474                self.api("/myself"),
475                format!("Jira refused the credential in {token_env}"),
476            ),
477        };
478        let response = self
479            .agent
480            .get(&url)
481            .header("Accept", "application/json")
482            .header("Authorization", &self.authorization()?)
483            .call()
484            .map_err(|e| failure(&format!("request failed: {e}")))?;
485        match response.status().as_u16() {
486            404 => Err(failure(&unseen)),
487            _ => self.check(&response, &unseen),
488        }
489    }
490
491    /// Whether Jira says the credential may add comments in the project. An answer it does not
492    /// give (no project, a refused request, no such permission in the reply) is taken as yes.
493    fn may_comment(&self) -> bool {
494        let Some(project) = &self.settings.project else {
495            return true;
496        };
497        self.get_json::<PermissionsResponse>(
498            &self.api("/mypermissions"),
499            &[
500                ("projectKey", project.clone()),
501                ("permissions", "ADD_COMMENTS".to_owned()),
502            ],
503            "Jira rejected asking what the credential may do",
504        )
505        .ok()
506        .and_then(|reply| reply.permissions?.add_comments?.have_permission)
507        .unwrap_or(true)
508    }
509
510    fn discover(&self) -> Result<Discovered, ProviderError> {
511        let ttl = Duration::from_secs(self.settings.capability_ttl_secs);
512        if let Ok(cache) = self.discovered.lock()
513            && let Some((at, discovered)) = cache.as_ref()
514            && at.elapsed() < ttl
515        {
516            return Ok(discovered.clone());
517        }
518        let mut issue_types = Vec::new();
519        let mut subtask_type = None;
520        let mut create = false;
521        if let Some(project) = &self.settings.project {
522            let meta = self.get_json::<CreateMetaResponse>(
523                &self.api(&format!("/issue/createmeta/{project}/issuetypes")),
524                &[],
525                &format!("Jira rejected asking for the issue types of {project}"),
526            );
527            if meta.is_err() {
528                // A refused credential is an error here, not "this project cannot create".
529                self.confirm_empty_search()?;
530            }
531            if let Ok(meta) = meta {
532                let types = meta.issue_types.or(meta.values).unwrap_or_default();
533                create = !types.is_empty();
534                for kind in types {
535                    let Some(name) = kind.name else {
536                        continue;
537                    };
538                    if kind.subtask == Some(true) {
539                        subtask_type.get_or_insert(name);
540                    } else {
541                        issue_types.push(name);
542                    }
543                }
544            }
545        }
546        let priorities = self
547            .get_json::<Vec<PriorityDto>>(
548                &self.api("/priority"),
549                &[],
550                "Jira rejected listing the priorities",
551            )
552            .ok()
553            .map(|list| list.into_iter().map(|p| p.name).collect())
554            .unwrap_or_default();
555        let children = match (self.settings.deployment, &subtask_type) {
556            (Deployment::Cloud, _) => "parent",
557            (Deployment::Server, Some(_)) => "subtasks",
558            (Deployment::Server, None) => "none",
559        };
560        let comments = self.may_comment();
561        let discovered = Discovered {
562            capabilities: TrackerCapabilities {
563                comment: comments,
564                edit_comment: comments,
565                labels: Vec::new(),
566                free_labels: true,
567                transitions: Vec::new(),
568                assign: true,
569                close: true,
570                create,
571                issue_types,
572                priorities,
573                children: children.to_owned(),
574                links: vec!["issue_links".to_owned(), "remote_links".to_owned()],
575                replies: true,
576                visibility: "unknown".to_owned(),
577                markers: true,
578            },
579            subtask_type,
580        };
581        if let Ok(mut cache) = self.discovered.lock() {
582            *cache = Some((Instant::now(), discovered.clone()));
583        }
584        Ok(discovered)
585    }
586}
587
588impl TryFrom<Settings> for Jira {
589    type Error = ProviderError;
590
591    fn try_from(settings: Settings) -> Result<Self, Self::Error> {
592        Self::new(settings).map_err(|e| ProviderError::new(Status::GUATIAO_ERR_BAD_VALUE, &e))
593    }
594}
595
596impl Jira {
597    /// The issues changed since `since`, oldest change first, and whether more remain past the
598    /// pages one poll reads.
599    fn changed_issues(
600        &self,
601        since: Option<&str>,
602    ) -> Result<(Vec<SourceItem>, bool), ProviderError> {
603        let jql = self.jql(since);
604        let url = match self.settings.deployment {
605            Deployment::Cloud => self.api("/search/jql"),
606            Deployment::Server => self.api("/search"),
607        };
608        let query: Vec<(&str, String)> = vec![
609            ("jql", jql),
610            ("fields", FIELDS.to_owned()),
611            ("maxResults", self.settings.page_size.to_string()),
612        ];
613
614        let mut items = Vec::new();
615        let mut page_token: Option<String> = None;
616        let mut start_at = 0_u64;
617        let mut remaining = false;
618        for _ in 0..self.settings.max_pages {
619            let mut page_query = query.clone();
620            match self.settings.deployment {
621                Deployment::Cloud => {
622                    if let Some(token) = &page_token {
623                        page_query.push(("nextPageToken", token.clone()));
624                    }
625                }
626                Deployment::Server => page_query.push(("startAt", start_at.to_string())),
627            }
628            let response = self.get(
629                &url,
630                &page_query,
631                "Jira rejected the search (check `jql`, `project` and the labels)",
632            )?;
633            let body: SearchResponse = read_json(response)?;
634            let page_count = body.issues.len() as u64;
635            items.extend(body.issues.into_iter().map(|issue| self.item_of(issue)));
636            let more = match self.settings.deployment {
637                Deployment::Cloud => {
638                    page_token = body.next_page_token;
639                    page_token.is_some()
640                }
641                Deployment::Server => {
642                    start_at += page_count;
643                    page_count > 0 && body.total.is_some_and(|total| start_at < total)
644                }
645            };
646            remaining = more;
647            if !more {
648                break;
649            }
650        }
651        Ok((items, remaining))
652    }
653}
654
655impl Source for Jira {
656    fn poll(&self, request: SourcePoll) -> Result<SourceBatch, ProviderError> {
657        let since = request.cursor.as_deref().map(|cursor| {
658            settled_cursor(cursor, self.settings.settling_secs).unwrap_or_else(|| cursor.to_owned())
659        });
660        let (mut items, more) = self.changed_issues(since.as_deref())?;
661        // Pages filled by what the margin repeats would keep every poll from what follows them.
662        if more
663            && since != request.cursor
664            && !items.iter().any(|item| {
665                request
666                    .cursor
667                    .as_deref()
668                    .is_some_and(|cursor| is_after(&item.updated, cursor))
669            })
670        {
671            items = self.changed_issues(request.cursor.as_deref())?.0;
672        }
673        if items.is_empty() && self.settings.deployment == Deployment::Cloud {
674            self.confirm_empty_search()?;
675        }
676        // What the margin repeats is older than the cursor, which never moves back for it.
677        let mut cursor = request.cursor;
678        for item in &items {
679            if cursor
680                .as_deref()
681                .is_none_or(|current| is_after(&item.updated, current))
682            {
683                cursor = Some(item.updated.clone());
684            }
685        }
686        Ok(SourceBatch { items, cursor })
687    }
688
689    fn facts(&self) -> Result<SourceFacts, ProviderError> {
690        let mut credential_variables = vec![self.settings.token_env.clone()];
691        credential_variables.extend(self.settings.email_env.clone());
692        credential_variables.extend(CLI_TOKEN_VARIABLES.map(str::to_owned));
693        credential_variables.sort();
694        credential_variables.dedup();
695        Ok(SourceFacts {
696            web: (self.site.scheme() == "https")
697                .then(|| self.site.as_str().trim_end_matches('/').to_owned()),
698            project: self.settings.project.clone(),
699            intake_labels: self.settings.labels.clone(),
700            hosts: self
701                .site
702                .host_str()
703                .map(str::to_lowercase)
704                .into_iter()
705                .collect(),
706            credential_variables,
707        })
708    }
709
710    fn board_url(&self) -> Result<Option<String>, ProviderError> {
711        if let Some(board) = &self.settings.board_url {
712            return Ok(Some(board.clone()));
713        }
714        let Some(project) = self.settings.project.as_deref() else {
715            return Ok(None);
716        };
717        let site = self.site.as_str().trim_end_matches('/');
718        Ok(
719            (self.site.scheme() == "https").then(|| match self.settings.deployment {
720                Deployment::Cloud => format!("{site}/jira/software/projects/{project}/boards"),
721                Deployment::Server => format!("{site}/projects/{project}"),
722            }),
723        )
724    }
725}
726
727/// The variables other Jira tools read their token from, beside the one configured.
728const CLI_TOKEN_VARIABLES: [&str; 2] = ["JIRA_API_TOKEN", "JIRA_TOKEN"];
729
730impl Tracker for Jira {
731    fn capabilities(&self, item: Option<String>) -> Result<TrackerCapabilities, ProviderError> {
732        let mut capabilities = self.discover()?.capabilities;
733        if let Some(item) = item {
734            let key = self.key(&item)?;
735            capabilities.transitions = self
736                .transitions(key)?
737                .into_iter()
738                .map(|(_, name, _)| name)
739                .collect();
740        }
741        Ok(capabilities)
742    }
743
744    fn issue(&self, item: String) -> Result<TrackerIssue, ProviderError> {
745        let key = self.key(&item)?;
746        let issue: IssueDto = self.get_json(
747            &self.api(&format!("/issue/{key}")),
748            &[("fields", ISSUE_FIELDS.to_owned())],
749            &format!("Jira rejected reading {key}"),
750        )?;
751        Ok(self.issue_of(issue))
752    }
753
754    fn replies(&self, request: ReplyPoll) -> Result<ReplyBatch, ProviderError> {
755        let keys: Vec<&str> = request
756            .items
757            .iter()
758            .map(|item| self.key(item))
759            .collect::<Result<_, _>>()?;
760        let mut cursor = request.since.clone();
761        let mut replies = Vec::new();
762        if keys.is_empty() {
763            return Ok(ReplyBatch { replies, cursor });
764        }
765        for key in keys {
766            let mut who: Option<Vec<String>> = None;
767            let mut start_at = 0_u64;
768            for _ in 0..self.settings.max_pages {
769                let page: CommentsResponse = self.get_json(
770                    &self.api(&format!("/issue/{key}/comment")),
771                    &[
772                        ("orderBy", "created".to_owned()),
773                        ("expand", "properties".to_owned()),
774                        ("startAt", start_at.to_string()),
775                        ("maxResults", self.settings.page_size.to_string()),
776                    ],
777                    &format!("Jira rejected listing the comments on {key}"),
778                )?;
779                let count = page.comments.len() as u64;
780                for comment in page.comments {
781                    let updated = comment
782                        .updated
783                        .as_deref()
784                        .or(comment.created.as_deref())
785                        .unwrap_or_default()
786                        .to_owned();
787                    if request
788                        .since
789                        .as_deref()
790                        .is_some_and(|since| !is_after(&updated, since))
791                    {
792                        continue;
793                    }
794                    if cursor.as_deref().is_none_or(|c| is_after(&updated, c)) {
795                        cursor = Some(updated);
796                    }
797                    let author = comment.author;
798                    let author_id = author.as_ref().and_then(person_id).unwrap_or_default();
799                    let permitted = self.settings.reply_authors.contains(&author_id) || {
800                        if who.is_none() {
801                            who = Some(self.reporter_and_assignee(key));
802                        }
803                        who.as_deref()
804                            .is_some_and(|people| people.contains(&author_id))
805                    };
806                    let body = comment.body.map(JiraText::into_text).unwrap_or_default();
807                    let own = is_ai6_comment(comment.properties.as_deref());
808                    replies.push(Reply {
809                        id: comment.id,
810                        item: key.to_owned(),
811                        permitted: permitted && !author_id.is_empty(),
812                        own,
813                        author_id,
814                        author: author
815                            .and_then(|person| person.display_name)
816                            .unwrap_or_default(),
817                        body,
818                        created: comment.created.unwrap_or_default(),
819                    });
820                }
821                start_at += count;
822                if count == 0 || page.total.is_none_or(|total| start_at >= total) {
823                    break;
824                }
825            }
826        }
827        replies.sort_by(|a, b| a.created.cmp(&b.created));
828        Ok(ReplyBatch { replies, cursor })
829    }
830
831    fn post(&self, post: TrackerPost) -> Result<PostedComment, ProviderError> {
832        let key = self.key(&post.item)?;
833        if post.body.trim().is_empty() {
834            return Err(bad_value(
835                "the comment is empty, and Jira refuses such a comment",
836            ));
837        }
838        let rejected = format!("Jira rejected the comment on {key}");
839        let comment: CreatedCommentResponse = match &post.edit {
840            Some(id) => {
841                if id.is_empty() || !id.bytes().all(|b| b.is_ascii_digit()) {
842                    return Err(bad_value("a comment ID is a number"));
843                }
844                // The property stays through an edit that does not name it.
845                read_json(self.call(
846                    "PUT",
847                    &self.api(&format!("/issue/{key}/comment/{id}")),
848                    &[],
849                    Some(&EditCommentRequest {
850                        body: self.text(&post.body),
851                    }),
852                    &rejected,
853                )?)?
854            }
855            None => read_json(self.call(
856                "POST",
857                &self.api(&format!("/issue/{key}/comment")),
858                &[],
859                Some(&CreateCommentRequest {
860                    body: self.text(&post.body),
861                    properties: [CommentPropertyOut {
862                        key: COMMENT_PROPERTY,
863                        value: MarkerValue {
864                            marker: post.marker.as_deref().unwrap_or("comment"),
865                        },
866                    }],
867                }),
868                &rejected,
869            )?)?,
870        };
871        let id = comment.id;
872        Ok(PostedComment {
873            url: Some(format!(
874                "{}/browse/{key}?focusedCommentId={id}",
875                self.site.as_str().trim_end_matches('/')
876            )),
877            id,
878        })
879    }
880
881    fn update(&self, update: TrackerUpdate) -> Result<(), ProviderError> {
882        let key = self.key(&update.item)?;
883        if !update.add_labels.is_empty() || !update.remove_labels.is_empty() {
884            let edits: Vec<LabelEdit> = update
885                .add_labels
886                .iter()
887                .map(|label| LabelEdit::Add(jira_label(label)))
888                .chain(
889                    update
890                        .remove_labels
891                        .iter()
892                        .map(|label| LabelEdit::Remove(jira_label(label))),
893                )
894                .collect();
895            self.call(
896                "PUT",
897                &self.api(&format!("/issue/{key}")),
898                &[],
899                Some(&UpdateLabelsRequest {
900                    update: LabelsUpdateField { labels: edits },
901                }),
902                &format!("Jira rejected the labels of {key}"),
903            )?;
904        }
905        if update.add_assignees.len() > 1 {
906            return Err(bad_value("a Jira issue has one assignee"));
907        }
908        fn assignee_request<'a>(
909            deployment: &Deployment,
910            person: Option<&'a str>,
911        ) -> AssigneeRequest<'a> {
912            match deployment {
913                Deployment::Cloud => AssigneeRequest::Cloud { account_id: person },
914                Deployment::Server => AssigneeRequest::Server { name: person },
915            }
916        }
917        if let Some(person) = update.add_assignees.first() {
918            self.call(
919                "PUT",
920                &self.api(&format!("/issue/{key}/assignee")),
921                &[],
922                Some(&assignee_request(
923                    &self.settings.deployment,
924                    Some(person.as_str()),
925                )),
926                &format!("Jira rejected the assignee of {key}"),
927            )?;
928        } else if !update.remove_assignees.is_empty() {
929            self.call(
930                "PUT",
931                &self.api(&format!("/issue/{key}/assignee")),
932                &[],
933                Some(&assignee_request(&self.settings.deployment, None)),
934                &format!("Jira rejected clearing the assignee of {key}"),
935            )?;
936        }
937        if let Some(transition) = &update.transition {
938            self.transition(key, transition)?;
939        }
940        match update.state.as_deref() {
941            None => {}
942            Some(state @ ("closed" | "open")) => {
943                let wanted: &[&str] = if state == "closed" {
944                    &["done"]
945                } else {
946                    &["new", "indeterminate"]
947                };
948                let transitions = self.transitions(key)?;
949                let id = transitions
950                    .iter()
951                    .find_map(|(id, _, category)| wanted.contains(&category.as_str()).then_some(id))
952                    .ok_or_else(|| {
953                        unsupported(
954                            &format!("set {key} to {state}"),
955                            &format!(
956                                "make {}",
957                                transitions
958                                    .iter()
959                                    .map(|(_, name, _)| name.as_str())
960                                    .collect::<Vec<_>>()
961                                    .join(", ")
962                            ),
963                        )
964                    })?;
965                self.call(
966                    "POST",
967                    &self.api(&format!("/issue/{key}/transitions")),
968                    &[],
969                    Some(&TransitionRequest {
970                        transition: IdRef { id },
971                    }),
972                    &format!("Jira rejected the transition to {state} on {key}"),
973                )?;
974            }
975            Some(other) => {
976                return Err(bad_value(&format!(
977                    "state {other:?} is not `open` or `closed`"
978                )));
979            }
980        }
981        Ok(())
982    }
983
984    fn create(&self, spec: IssueSpec) -> Result<TrackerIssue, ProviderError> {
985        let Some(project) = &self.settings.project else {
986            return Err(unsupported(
987                "create issues without a project",
988                "read and comment on them; set `project` to create",
989            ));
990        };
991        let discovered = self.discover()?;
992        if !discovered.capabilities.create {
993            return Err(unsupported(
994                "create issues in this project",
995                "read and comment on them",
996            ));
997        }
998        let parent = spec
999            .parent
1000            .as_deref()
1001            .map(|parent| self.key(parent))
1002            .transpose()?;
1003        let standard = spec
1004            .issue_type
1005            .clone()
1006            .unwrap_or_else(|| self.settings.issue_type.clone());
1007        let child_type = self
1008            .settings
1009            .subtask_type
1010            .clone()
1011            .or(discovered.subtask_type.clone());
1012        // What may sit under what: on Cloud a standard type under an epic and a sub-task type
1013        // under a standard issue; on Server a sub-task type under anything. Anything else is
1014        // created beside its parent and linked to it.
1015        let (kind, attach) = match (parent, self.settings.deployment) {
1016            (None, _) => (standard, false),
1017            (Some(_), Deployment::Server) => (
1018                child_type.ok_or_else(|| {
1019                    unsupported(
1020                        "create a child without a sub-task type",
1021                        "create issues without a parent",
1022                    )
1023                })?,
1024                true,
1025            ),
1026            (Some(parent), Deployment::Cloud) => match self.hierarchy_level(parent)? {
1027                level if level > 0 => (standard, true),
1028                0 => match child_type {
1029                    Some(child) => (child, true),
1030                    None => (standard, false),
1031                },
1032                _ => (standard, false),
1033            },
1034        };
1035        let priorities = &discovered.capabilities.priorities;
1036        let fields = CreateIssueFields {
1037            project: KeyRef { key: project },
1038            summary: summary_of(&spec.title),
1039            issuetype: NameRef { name: kind },
1040            labels: spec.labels.iter().map(|label| jira_label(label)).collect(),
1041            description: (!spec.body.trim().is_empty()).then(|| self.text(&spec.body)),
1042            priority: spec
1043                .priority
1044                .as_deref()
1045                .filter(|priority| {
1046                    priorities.is_empty() || priorities.iter().any(|p| p == priority)
1047                })
1048                .map(|name| NameRefRef { name }),
1049            parent: parent.filter(|_| attach).map(|key| KeyRef { key }),
1050        };
1051        let created: CreatedIssueResponse = read_json(self.call(
1052            "POST",
1053            &self.api("/issue"),
1054            &[],
1055            Some(&CreateIssueRequest { fields }),
1056            "Jira rejected the new issue (check its type, labels and priority)",
1057        )?)?;
1058        let key = created.key;
1059        if let Some(parent) = parent.filter(|_| !attach) {
1060            self.link_issues(&key, parent, "the child")?;
1061        }
1062        self.issue(key)
1063    }
1064
1065    fn link(&self, link: TrackerLink) -> Result<(), ProviderError> {
1066        let from = self.key(&link.from)?;
1067        match (&link.to, &link.url) {
1068            (Some(to), _) => {
1069                self.link_issues(from, self.key(to)?, "the link")?;
1070            }
1071            (None, Some(url)) => {
1072                if !(url.starts_with("https://") || url.starts_with("http://")) {
1073                    return Err(bad_value("a remote link is an http or https address"));
1074                }
1075                self.call(
1076                    "POST",
1077                    &self.api(&format!("/issue/{from}/remotelink")),
1078                    &[],
1079                    Some(&RemoteLinkRequest {
1080                        relationship: &link.relation,
1081                        object: RemoteLinkObject { url, title: url },
1082                    }),
1083                    &format!("Jira rejected the remote link on {from}"),
1084                )?;
1085            }
1086            (None, None) => return Err(bad_value("a link names an issue or an address")),
1087        }
1088        Ok(())
1089    }
1090}
1091
1092#[derive(Debug, Clone, Serialize, Deserialize)]
1093#[serde(untagged)]
1094enum JiraText {
1095    Plain(String),
1096    Adf(adf::Document),
1097}
1098
1099impl JiraText {
1100    fn into_text(self) -> String {
1101        match self {
1102            Self::Plain(text) => text,
1103            Self::Adf(document) => adf::text(&document),
1104        }
1105    }
1106}
1107
1108#[derive(Deserialize)]
1109struct TransitionsResponse {
1110    #[serde(default)]
1111    transitions: Vec<TransitionDto>,
1112}
1113
1114#[derive(Deserialize)]
1115struct TransitionDto {
1116    id: String,
1117    name: String,
1118    to: Option<TransitionTargetDto>,
1119}
1120
1121#[derive(Deserialize)]
1122struct TransitionTargetDto {
1123    #[serde(rename = "statusCategory")]
1124    status_category: Option<StatusCategoryDto>,
1125}
1126
1127#[derive(Deserialize)]
1128struct StatusCategoryDto {
1129    key: Option<String>,
1130}
1131
1132#[derive(Serialize)]
1133struct TransitionRequest<'a> {
1134    transition: IdRef<'a>,
1135}
1136
1137#[derive(Serialize)]
1138struct IdRef<'a> {
1139    id: &'a str,
1140}
1141
1142#[derive(Deserialize)]
1143struct PermissionsResponse {
1144    permissions: Option<PermissionsDto>,
1145}
1146
1147#[derive(Deserialize)]
1148struct PermissionsDto {
1149    #[serde(rename = "ADD_COMMENTS")]
1150    add_comments: Option<PermissionEntryDto>,
1151}
1152
1153#[derive(Deserialize)]
1154struct PermissionEntryDto {
1155    #[serde(rename = "havePermission")]
1156    have_permission: Option<bool>,
1157}
1158
1159#[derive(Deserialize)]
1160struct CreateMetaResponse {
1161    #[serde(rename = "issueTypes")]
1162    issue_types: Option<Vec<IssueTypeMetaDto>>,
1163    values: Option<Vec<IssueTypeMetaDto>>,
1164}
1165
1166#[derive(Deserialize)]
1167struct IssueTypeMetaDto {
1168    name: Option<String>,
1169    subtask: Option<bool>,
1170}
1171
1172#[derive(Deserialize)]
1173struct PriorityDto {
1174    name: String,
1175}
1176
1177#[derive(Deserialize)]
1178struct SearchResponse {
1179    #[serde(default)]
1180    issues: Vec<IssueDto>,
1181    #[serde(rename = "nextPageToken")]
1182    next_page_token: Option<String>,
1183    total: Option<u64>,
1184}
1185
1186#[derive(Deserialize)]
1187struct PersonDto {
1188    #[serde(rename = "accountId")]
1189    account_id: Option<String>,
1190    key: Option<String>,
1191    name: Option<String>,
1192    #[serde(rename = "displayName")]
1193    display_name: Option<String>,
1194}
1195
1196#[derive(Deserialize)]
1197struct StatusDto {
1198    #[serde(rename = "statusCategory")]
1199    status_category: Option<StatusCategoryDto>,
1200}
1201
1202#[derive(Deserialize)]
1203struct KeyDto {
1204    key: String,
1205}
1206
1207#[derive(Deserialize)]
1208struct NameDto {
1209    name: String,
1210}
1211
1212#[derive(Deserialize)]
1213struct IssueDto {
1214    id: Option<String>,
1215    key: String,
1216    fields: IssueFieldsDto,
1217}
1218
1219#[derive(Deserialize)]
1220struct IssueFieldsDto {
1221    summary: String,
1222    description: Option<JiraText>,
1223    labels: Option<Vec<String>>,
1224    reporter: Option<PersonDto>,
1225    assignee: Option<PersonDto>,
1226    updated: String,
1227    status: Option<StatusDto>,
1228    parent: Option<KeyDto>,
1229    priority: Option<NameDto>,
1230}
1231
1232#[derive(Deserialize)]
1233struct IssueTypeWrapper {
1234    fields: Option<IssueTypeFields>,
1235}
1236
1237#[derive(Deserialize)]
1238struct IssueTypeFields {
1239    issuetype: Option<IssueTypeDto>,
1240}
1241
1242#[derive(Deserialize)]
1243struct IssueTypeDto {
1244    #[serde(rename = "hierarchyLevel")]
1245    hierarchy_level: Option<i64>,
1246    subtask: Option<bool>,
1247}
1248
1249#[derive(Deserialize)]
1250struct IssuePeopleWrapper {
1251    fields: Option<IssuePeopleFields>,
1252}
1253
1254#[derive(Deserialize)]
1255struct IssuePeopleFields {
1256    reporter: Option<PersonDto>,
1257    assignee: Option<PersonDto>,
1258}
1259
1260#[derive(Deserialize)]
1261struct CommentsResponse {
1262    #[serde(default)]
1263    comments: Vec<CommentDto>,
1264    total: Option<u64>,
1265}
1266
1267#[derive(Deserialize)]
1268struct CommentDto {
1269    id: String,
1270    author: Option<PersonDto>,
1271    body: Option<JiraText>,
1272    properties: Option<Vec<CommentPropertyDto>>,
1273    created: Option<String>,
1274    updated: Option<String>,
1275}
1276
1277#[derive(Deserialize)]
1278struct CommentPropertyDto {
1279    key: String,
1280}
1281
1282#[derive(Deserialize)]
1283struct CreatedCommentResponse {
1284    id: String,
1285}
1286
1287#[derive(Serialize)]
1288struct EditCommentRequest {
1289    body: JiraText,
1290}
1291
1292#[derive(Serialize)]
1293struct CreateCommentRequest<'a> {
1294    body: JiraText,
1295    properties: [CommentPropertyOut<'a>; 1],
1296}
1297
1298#[derive(Serialize)]
1299struct CommentPropertyOut<'a> {
1300    key: &'static str,
1301    value: MarkerValue<'a>,
1302}
1303
1304#[derive(Serialize)]
1305struct MarkerValue<'a> {
1306    marker: &'a str,
1307}
1308
1309#[derive(Serialize)]
1310struct UpdateLabelsRequest {
1311    update: LabelsUpdateField,
1312}
1313
1314#[derive(Serialize)]
1315struct LabelsUpdateField {
1316    labels: Vec<LabelEdit>,
1317}
1318
1319#[derive(Serialize)]
1320enum LabelEdit {
1321    #[serde(rename = "add")]
1322    Add(String),
1323    #[serde(rename = "remove")]
1324    Remove(String),
1325}
1326
1327#[derive(Serialize)]
1328#[serde(untagged)]
1329enum AssigneeRequest<'a> {
1330    Cloud {
1331        #[serde(rename = "accountId")]
1332        account_id: Option<&'a str>,
1333    },
1334    Server {
1335        name: Option<&'a str>,
1336    },
1337}
1338
1339#[derive(Serialize)]
1340struct CreateIssueRequest<'a> {
1341    fields: CreateIssueFields<'a>,
1342}
1343
1344#[derive(Serialize)]
1345struct CreateIssueFields<'a> {
1346    project: KeyRef<'a>,
1347    summary: String,
1348    issuetype: NameRef,
1349    labels: Vec<String>,
1350    #[serde(skip_serializing_if = "Option::is_none")]
1351    description: Option<JiraText>,
1352    #[serde(skip_serializing_if = "Option::is_none")]
1353    priority: Option<NameRefRef<'a>>,
1354    #[serde(skip_serializing_if = "Option::is_none")]
1355    parent: Option<KeyRef<'a>>,
1356}
1357
1358#[derive(Serialize)]
1359struct KeyRef<'a> {
1360    key: &'a str,
1361}
1362
1363#[derive(Serialize)]
1364struct NameRef {
1365    name: String,
1366}
1367
1368#[derive(Serialize)]
1369struct NameRefRef<'a> {
1370    name: &'a str,
1371}
1372
1373#[derive(Deserialize)]
1374struct CreatedIssueResponse {
1375    key: String,
1376}
1377
1378#[derive(Serialize)]
1379struct IssueLinkRequest<'a> {
1380    #[serde(rename = "type")]
1381    kind: NameRefRef<'a>,
1382    #[serde(rename = "inwardIssue")]
1383    inward_issue: KeyRef<'a>,
1384    #[serde(rename = "outwardIssue")]
1385    outward_issue: KeyRef<'a>,
1386}
1387
1388#[derive(Serialize)]
1389struct RemoteLinkRequest<'a> {
1390    relationship: &'a str,
1391    object: RemoteLinkObject<'a>,
1392}
1393
1394#[derive(Serialize)]
1395struct RemoteLinkObject<'a> {
1396    url: &'a str,
1397    title: &'a str,
1398}
1399
1400fn read_json<T: serde::de::DeserializeOwned>(
1401    mut response: ureq::http::Response<ureq::Body>,
1402) -> Result<T, ProviderError> {
1403    response
1404        .body_mut()
1405        .read_json()
1406        .map_err(|e| failure(&format!("unreadable response: {e}")))
1407}
1408
1409/// The comment entity property AI6 sets on every comment it writes. A person's comment cannot carry
1410/// it by accident, whoever's account it is on: Jira's UI sets no property, and only a comment read
1411/// with `expand=properties` shows one. Tested on Jira Cloud's REST API v3.
1412const COMMENT_PROPERTY: &str = "dev.coqui.ai6";
1413
1414/// Whether AI6 wrote `comment`, read with `expand=properties`.
1415fn is_ai6_comment(properties: Option<&[CommentPropertyDto]>) -> bool {
1416    properties.is_some_and(|properties| {
1417        properties
1418            .iter()
1419            .any(|property| property.key == COMMENT_PROPERTY)
1420    })
1421}
1422
1423/// A person's stable ID: the Cloud account ID, else the Server user key or name.
1424fn person_id(person: &PersonDto) -> Option<String> {
1425    [&person.account_id, &person.key, &person.name]
1426        .into_iter()
1427        .flatten()
1428        .find(|id| !id.is_empty())
1429        .cloned()
1430}
1431
1432/// A title as a summary: one line of at most [`SUMMARY_BYTES`], cut on a character boundary.
1433fn summary_of(title: &str) -> String {
1434    let line = title.lines().next().unwrap_or_default();
1435    let mut end = line.len().min(SUMMARY_BYTES);
1436    while !line.is_char_boundary(end) {
1437        end -= 1;
1438    }
1439    line[..end].to_owned()
1440}
1441
1442/// Whether timestamp `a` is later than `b`. Each carries the account's offset, which a change of
1443/// clock moves, so the text alone does not order them; text that does not parse compares as text.
1444fn is_after(a: &str, b: &str) -> bool {
1445    match (instant(a), instant(b)) {
1446        (Some(a), Some(b)) => a > b,
1447        _ => a > b,
1448    }
1449}
1450
1451/// `2026-11-01T22:57:12.421+0700` as milliseconds since the Unix epoch.
1452fn instant(text: &str) -> Option<i64> {
1453    let at = time::OffsetDateTime::parse(
1454        text,
1455        &time::format_description::well_known::Iso8601::DEFAULT,
1456    )
1457    .ok()?;
1458    Some(at.unix_timestamp() * 1_000 + i64::from(at.millisecond()))
1459}
1460
1461/// Jira labels cannot hold whitespace.
1462fn jira_label(label: &str) -> String {
1463    label.split_whitespace().collect::<Vec<_>>().join("-")
1464}
1465
1466impl Jira {
1467    /// Links two issues of this project with the instance's `link_type`.
1468    fn link_issues(&self, from: &str, to: &str, what: &str) -> Result<(), ProviderError> {
1469        self.call(
1470            "POST",
1471            &self.api("/issueLink"),
1472            &[],
1473            Some(&IssueLinkRequest {
1474                kind: NameRefRef {
1475                    name: &self.settings.link_type,
1476                },
1477                inward_issue: KeyRef { key: from },
1478                outward_issue: KeyRef { key: to },
1479            }),
1480            &format!(
1481                "Jira rejected {what} from {from} to {to} (check `link_type`: {})",
1482                self.settings.link_type
1483            ),
1484        )?;
1485        Ok(())
1486    }
1487
1488    /// An issue's level: above 0 an epic, 0 a standard issue, below 0 a sub-task.
1489    fn hierarchy_level(&self, key: &str) -> Result<i64, ProviderError> {
1490        let issue: IssueTypeWrapper = self.get_json(
1491            &self.api(&format!("/issue/{key}")),
1492            &[("fields", "issuetype".to_owned())],
1493            &format!("Jira rejected reading {key}"),
1494        )?;
1495        let kind = issue.fields.and_then(|fields| fields.issuetype);
1496        Ok(kind
1497            .as_ref()
1498            .and_then(|kind| kind.hierarchy_level)
1499            .unwrap_or_else(|| {
1500                if kind.and_then(|kind| kind.subtask) == Some(true) {
1501                    -1
1502                } else {
1503                    0
1504                }
1505            }))
1506    }
1507
1508    /// The reporter's and assignee's IDs: the people who may answer for an issue.
1509    fn reporter_and_assignee(&self, key: &str) -> Vec<String> {
1510        self.get_json::<IssuePeopleWrapper>(
1511            &self.api(&format!("/issue/{key}")),
1512            &[("fields", "reporter,assignee".to_owned())],
1513            &format!("Jira rejected reading {key}"),
1514        )
1515        .ok()
1516        .and_then(|issue| issue.fields)
1517        .map(|fields| {
1518            [fields.reporter, fields.assignee]
1519                .into_iter()
1520                .flatten()
1521                .filter_map(|person| person_id(&person))
1522                .collect()
1523        })
1524        .unwrap_or_default()
1525    }
1526
1527    fn issue_of(&self, issue: IssueDto) -> TrackerIssue {
1528        let native_id = issue.id.clone().unwrap_or_default();
1529        let done = issue
1530            .fields
1531            .status
1532            .as_ref()
1533            .and_then(|status| status.status_category.as_ref())
1534            .and_then(|cat| cat.key.as_deref())
1535            == Some("done");
1536        let assignees = issue
1537            .fields
1538            .assignee
1539            .as_ref()
1540            .and_then(person_id)
1541            .into_iter()
1542            .collect();
1543        let parent = issue
1544            .fields
1545            .parent
1546            .as_ref()
1547            .map(|parent| parent.key.clone());
1548        let author_id = issue.fields.reporter.as_ref().and_then(person_id);
1549        let priority = issue
1550            .fields
1551            .priority
1552            .as_ref()
1553            .map(|priority| priority.name.clone());
1554        let item = self.item_of(issue);
1555        TrackerIssue {
1556            id: item.id,
1557            native_id,
1558            title: item.title,
1559            body: item.body,
1560            state: if done { "closed" } else { "open" }.to_owned(),
1561            labels: item.labels,
1562            assignees,
1563            url: item.url,
1564            updated: item.updated,
1565            parent,
1566            author_id,
1567            priority,
1568            code: item.code,
1569            code_tag: item.code_tag,
1570        }
1571    }
1572}
1573
1574fn unsupported(what: &str, can: &str) -> ProviderError {
1575    ProviderError::new(
1576        Status::GUATIAO_ERR_UNSUPPORTED,
1577        &format!("Jira cannot {what}; it can {can}"),
1578    )
1579}
1580
1581fn bad_value(message: &str) -> ProviderError {
1582    ProviderError::new(Status::GUATIAO_ERR_BAD_VALUE, message)
1583}
1584
1585impl Jira {
1586    fn item_of(&self, issue: IssueDto) -> SourceItem {
1587        let key = issue.key;
1588        let description = issue
1589            .fields
1590            .description
1591            .map(JiraText::into_text)
1592            .unwrap_or_default();
1593        SourceItem {
1594            id: key.clone(),
1595            title: issue.fields.summary,
1596            body: description,
1597            url: Some(format!(
1598                "{}/browse/{key}",
1599                self.site.as_str().trim_end_matches('/')
1600            )),
1601            labels: issue.fields.labels.unwrap_or_default(),
1602            author: issue
1603                .fields
1604                .reporter
1605                .and_then(|reporter| reporter.display_name),
1606            updated: issue.fields.updated,
1607            code: Some(key),
1608            code_tag: None,
1609            event: None,
1610        }
1611    }
1612}
1613
1614/// Turns Jira's `2026-10-02T09:30:00.000+0000` into the `2026-10-02 09:30` JQL accepts.
1615///
1616/// JQL compares at minute precision in the caller's time zone, which is the zone Jira
1617/// already used for the timestamp, so the date and time are kept as written.
1618fn jql_minute(updated: &str) -> Option<String> {
1619    let minute = updated.get(..16)?;
1620    let (date, time) = minute.split_once('T')?;
1621    let valid = date.len() == 10
1622        && time.len() == 5
1623        && date
1624            .bytes()
1625            .chain(time.bytes())
1626            .all(|b| b.is_ascii_digit() || b == b'-' || b == b':');
1627    valid.then(|| format!("{date} {time}"))
1628}
1629
1630/// Checks that a configured page is a plain `https` address with a host and no credentials.
1631fn https_page(text: &str) -> Result<(), String> {
1632    let url = Url::parse(text).map_err(|error| error.to_string())?;
1633    if url.scheme() != "https"
1634        || url.host_str().is_none()
1635        || !url.username().is_empty()
1636        || url.password().is_some()
1637    {
1638        return Err("must be an https address without credentials".to_owned());
1639    }
1640    Ok(())
1641}
1642
1643fn failure(message: &str) -> ProviderError {
1644    ProviderError::new(Status::GUATIAO_ERR_INTERNAL, message)
1645}
1646
1647#[cfg(test)]
1648mod tests {
1649    use super::*;
1650
1651    trait FromText: Sized {
1652        fn from_settings(text: &str) -> Result<Self, String>;
1653    }
1654
1655    impl FromText for Jira {
1656        fn from_settings(text: &str) -> Result<Self, String> {
1657            Jira::new(ai6::provider_settings::settings_from_text(
1658                ai6::bootstrap::format::Format::Toml,
1659                text,
1660            )?)
1661        }
1662    }
1663
1664    #[test]
1665    fn the_facts_name_the_page_the_labels_the_hosts_and_the_credential_variables() {
1666        let facts = |text: &str| Jira::from_settings(text).unwrap().facts().unwrap();
1667        let cloud = facts(
1668            "site = \"https://example.atlassian.net/\"
1669project = \"OPS\"
1670             email_env = \"MAIL\"",
1671        );
1672        assert_eq!(cloud.web.as_deref(), Some("https://example.atlassian.net"));
1673        assert_eq!(cloud.project.as_deref(), Some("OPS"));
1674        assert_eq!(cloud.intake_labels, ["ai6-ready"]);
1675        assert_eq!(cloud.hosts, ["example.atlassian.net"]);
1676        for name in ["JIRA_API_TOKEN", "JIRA_TOKEN", "MAIL"] {
1677            assert!(
1678                cloud.credential_variables.iter().any(|v| v == name),
1679                "{name}"
1680            );
1681        }
1682        let query = facts(
1683            "site = \"https://other.atlassian.net\"
1684auth = \"bearer\"
1685jql = \"labels = ready\"",
1686        );
1687        assert_eq!(query.project, None, "a query alone has no project");
1688    }
1689
1690    #[test]
1691    fn the_board_is_the_projects_page_unless_the_settings_name_another() {
1692        let board = |text: &str| Jira::from_settings(text).unwrap().board_url().unwrap();
1693        let cloud =
1694            "site = \"https://example.atlassian.net/\"\nproject = \"OPS\"\nauth = \"bearer\"";
1695        assert_eq!(
1696            board(cloud).as_deref(),
1697            Some("https://example.atlassian.net/jira/software/projects/OPS/boards")
1698        );
1699        assert_eq!(
1700            board(&format!("{cloud}\ndeployment = \"server\"")).as_deref(),
1701            Some("https://example.atlassian.net/projects/OPS")
1702        );
1703        assert_eq!(
1704            board(&format!(
1705                "{cloud}\nboard_url = \"https://example.atlassian.net/b/7\""
1706            ))
1707            .as_deref(),
1708            Some("https://example.atlassian.net/b/7")
1709        );
1710        assert_eq!(
1711            board(
1712                "site = \"https://example.atlassian.net\"\nauth = \"bearer\"\njql = \"labels = ready\""
1713            ),
1714            None,
1715            "a query alone names no project"
1716        );
1717        assert_eq!(
1718            board("site = \"http://127.0.0.1:9\"\nproject = \"OPS\"\nauth = \"bearer\""),
1719            None
1720        );
1721        assert!(
1722            Jira::from_settings(&format!(
1723                "{cloud}\nboard_url = \"http://example.atlassian.net/b\""
1724            ))
1725            .is_err()
1726        );
1727    }
1728
1729    #[test]
1730    fn timestamps_order_by_the_instant_they_name_and_not_their_text() {
1731        let east = "2026-11-01T22:57:12.421+0700";
1732        let utc = "2026-11-01T15:57:12.421+0000";
1733        assert_eq!(instant(east), instant(utc));
1734        assert_eq!(instant("1970-01-01T00:00:01.5Z"), Some(1_500));
1735        assert_eq!(
1736            instant("2024-02-29T23:59:59.999-0800"),
1737            Some(1_709_279_999_999),
1738            "a leap day west of UTC"
1739        );
1740        assert_eq!(instant("2100-03-01T00:00:00Z"), Some(4_107_542_400_000));
1741        assert_eq!(
1742            instant("2026-02-29T00:00:00Z"),
1743            None,
1744            "2026 is not a leap year"
1745        );
1746        assert!(
1747            is_after("2026-11-01T15:57:13.000+0000", east),
1748            "later, though its text sorts first"
1749        );
1750        assert!(!is_after(east, utc));
1751        assert!(
1752            is_after("b", "a"),
1753            "text that does not parse compares as text"
1754        );
1755    }
1756
1757    #[test]
1758    fn a_summary_is_one_line_cut_on_a_character_boundary() {
1759        assert_eq!(summary_of("one\ntwo"), "one");
1760        let long = "ñ".repeat(200);
1761        let cut = summary_of(&long);
1762        assert!(cut.len() <= SUMMARY_BYTES && cut.chars().all(|c| c == 'ñ'));
1763        assert_eq!(cut.len(), 254);
1764    }
1765
1766    #[test]
1767    fn cursors_become_minute_precision_jql_times() {
1768        assert_eq!(
1769            jql_minute("2026-10-02T09:30:45.123+0000").as_deref(),
1770            Some("2026-10-02 09:30")
1771        );
1772        assert_eq!(jql_minute("garbage"), None);
1773        assert_eq!(jql_minute("2026-10-02"), None);
1774    }
1775
1776    #[test]
1777    fn settings_are_checked_before_any_request() {
1778        let ok = "site = \"https://x.atlassian.net\"\nproject = \"GUA\"\nemail_env = \"E\"";
1779        assert!(Jira::from_settings(ok).is_ok());
1780        assert!(Jira::from_settings(&ok.replace("project", "target")).is_ok());
1781        assert!(Jira::from_settings(&format!("{ok}\nsurprise = 1")).is_err());
1782        assert!(
1783            Jira::from_settings("site = \"https://x.atlassian.net\"\nemail_env = \"E\"").is_err()
1784        );
1785        assert!(Jira::from_settings(&ok.replace("GUA", "G\\\" OR 1=1")).is_err());
1786        assert!(Jira::from_settings("site = \"https://x\"\nproject = \"G\"").is_err());
1787        assert!(
1788            Jira::from_settings("site = \"https://x\"\nproject = \"G\"\nauth = \"bearer\"").is_ok()
1789        );
1790        assert!(
1791            Jira::from_settings(
1792                "site = \"http://example.com\"\nproject = \"G\"\nauth = \"bearer\""
1793            )
1794            .is_err()
1795        );
1796    }
1797
1798    #[test]
1799    fn the_search_is_filtered_by_project_labels_and_cursor() {
1800        let jira = Jira::from_settings(
1801            "site = \"https://x\"\nproject = \"GUA\"\nauth = \"bearer\"\njql = \"component = Core\"",
1802        )
1803        .unwrap();
1804        assert_eq!(
1805            jira.jql(Some("2026-10-02T09:30:45.123+0000")),
1806            "project = \"GUA\" AND labels = \"ai6-ready\" AND (component = Core) AND \
1807             statusCategory != Done AND updated >= \"2026-10-02 09:30\" ORDER BY updated ASC"
1808        );
1809    }
1810}