Skip to main content

redmine_api/
api.rs

1//! Redmine API
2//!
3//! [`Redmine Documentation`](https://www.redmine.org/projects/redmine/wiki/rest_api)
4//!
5//! - [x] authentication
6//! - [x] pagination
7//!   - [x] add Pageable instances to all types that need them
8//!   - [x] figure out a way to write a general "fetch all pages" function (problem is the different key name in the wrapper)
9//! - [x] impersonation
10//! - [x] attachments
11//! - [x] add all the wrappers I somehow missed
12//!   - [x] check if admin and send_information truly are not part of the user hash in Create/UpdateUser or if the wiki docs are wrong (admin is, send_information is not)
13//! - [x] test include parameters and add relevant data to the return types
14//! - [x] async support
15//!
16//! Potential breaking changes ahead
17//! - [ ] use Enum for sort column
18//! - [ ] typed ids
19//! - [ ] change project_id_or_name to Enum
20//! - [ ] extra filter expressions I overlooked/did not know about
21//! - [ ] parameters that are more flexible than they appear
22
23pub mod attachments;
24pub mod custom_fields;
25pub mod enumerations;
26pub mod files;
27pub mod groups;
28pub mod issue_categories;
29pub mod issue_relations;
30pub mod issue_statuses;
31pub mod issues;
32pub mod my_account;
33pub mod news;
34pub mod project_memberships;
35pub mod projects;
36pub mod queries;
37pub mod roles;
38pub mod search;
39#[cfg(test)]
40pub mod test_container;
41#[cfg(test)]
42pub mod test_helpers;
43pub mod time_entries;
44pub mod trackers;
45pub mod uploads;
46pub mod users;
47pub mod versions;
48pub mod wiki_pages;
49
50use futures::future::FutureExt as _;
51
52use std::str::from_utf8;
53
54use serde::Deserialize;
55use serde::Deserializer;
56use serde::Serialize as _;
57use serde::de::DeserializeOwned;
58
59use reqwest::Method;
60use std::borrow::Cow;
61
62use reqwest::Url;
63use tracing::{debug, error, trace};
64
65/// main API client object (sync)
66#[derive(derive_more::Debug)]
67#[expect(
68    clippy::struct_field_names,
69    reason = "redmine_url disambiguates from the impersonate_user_id and matches public accessor naming"
70)]
71pub struct Redmine {
72    /// the reqwest client we use to perform our API requests
73    client: reqwest::blocking::Client,
74    /// the redmine base url
75    redmine_url: Url,
76    /// a redmine API key, usually 40 hex digits where the letters (a-f) are lower case
77    #[debug(skip)]
78    api_key: String,
79    /// the user id we want to impersonate, only works if the API key we use has admin privileges
80    impersonate_user_id: Option<u64>,
81}
82
83/// main API client object (async)
84#[derive(derive_more::Debug)]
85pub struct RedmineAsync {
86    /// the reqwest client we use to perform our API requests
87    client: reqwest::Client,
88    /// the redmine base url
89    redmine_url: Url,
90    /// a redmine API key, usually 40 hex digits where the letters (a-f) are lower case
91    #[debug(skip)]
92    api_key: String,
93    /// the user id we want to impersonate, only works if the API key we use has admin privileges
94    impersonate_user_id: Option<u64>,
95}
96
97/// helper function to parse the redmine URL in the environment variable
98fn parse_url<'de, D>(deserializer: D) -> Result<url::Url, D::Error>
99where
100    D: Deserializer<'de>,
101{
102    let buf = String::deserialize(deserializer)?;
103
104    url::Url::parse(&buf).map_err(serde::de::Error::custom)
105}
106
107/// used to deserialize the required options from the environment
108#[derive(Debug, Clone, serde::Deserialize)]
109struct EnvOptions {
110    /// a redmine API key, usually 40 hex digits where the letters (a-f) are lower case
111    redmine_api_key: String,
112
113    /// the redmine base url
114    #[serde(deserialize_with = "parse_url")]
115    redmine_url: url::Url,
116}
117
118/// Return value from paged requests, includes the actual value as well as
119/// pagination data
120#[derive(Debug, Clone)]
121pub struct ResponsePage<T> {
122    /// The actual value returned by Redmine deserialized into a user provided type
123    pub values: Vec<T>,
124    /// The total number of values that could be returned by requesting all pages
125    pub total_count: u64,
126    /// The offset from the start (zero-based)
127    pub offset: u64,
128    /// How many entries were returned
129    pub limit: u64,
130}
131
132impl Redmine {
133    /// create a [Redmine] object
134    ///
135    /// # Errors
136    ///
137    /// This will return [`crate::Error::ReqwestError`] if initialization of Reqwest client is failed.
138    pub fn new(
139        client: reqwest::blocking::Client,
140        redmine_url: url::Url,
141        api_key: &str,
142    ) -> Result<Self, crate::Error> {
143        Ok(Self {
144            client,
145            redmine_url,
146            api_key: api_key.to_string(),
147            impersonate_user_id: None,
148        })
149    }
150
151    /// create a [Redmine] object from the environment variables
152    ///
153    /// REDMINE_API_KEY
154    /// REDMINE_URL
155    ///
156    /// # Errors
157    ///
158    /// This will return an error if the environment variables are
159    /// missing or the URL can not be parsed
160    pub fn from_env(client: reqwest::blocking::Client) -> Result<Self, crate::Error> {
161        let env_options = envy::from_env::<EnvOptions>()?;
162
163        let redmine_url = env_options.redmine_url;
164        let api_key = env_options.redmine_api_key;
165
166        Self::new(client, redmine_url, &api_key)
167    }
168
169    /// Sets the user id of a user to impersonate in all future API calls
170    ///
171    /// this requires Redmine admin privileges
172    pub const fn impersonate_user(&mut self, id: u64) {
173        self.impersonate_user_id = Some(id);
174    }
175
176    /// returns the redmine base url
177    #[must_use]
178    pub const fn redmine_url(&self) -> &Url {
179        &self.redmine_url
180    }
181
182    /// returns the issue URL for a given issue id
183    ///
184    /// this is mostly for convenience since we are already storing the
185    /// redmine URL and it works entirely on the client
186    #[must_use]
187    #[expect(
188        clippy::missing_panics_doc,
189        clippy::unwrap_used,
190        reason = "join cannot fail for a constant relative URL"
191    )]
192    pub fn issue_url(&self, issue_id: u64) -> Url {
193        let Self { redmine_url, .. } = self;
194        // we can unwrap here because we know /issues/<number>
195        // parses successfully as an url fragment
196        redmine_url.join(&format!("/issues/{issue_id}")).unwrap()
197    }
198
199    /// internal method for shared logic between the methods below which
200    /// diff in how they parse the response body and how often they call this
201    fn rest(
202        &self,
203        method: reqwest::Method,
204        endpoint: &str,
205        parameters: QueryParams,
206        mime_type_and_body: Option<(&str, Vec<u8>)>,
207    ) -> Result<(reqwest::StatusCode, bytes::Bytes), crate::Error> {
208        let Self {
209            client,
210            redmine_url,
211            api_key,
212            impersonate_user_id,
213        } = self;
214        let mut url = redmine_url.join(endpoint)?;
215        parameters.add_to_url(&mut url);
216        debug!(%url, %method, "Calling redmine");
217        let req = client
218            .request(method.clone(), url.clone())
219            .header("x-redmine-api-key", api_key);
220        let req = if let Some(user_id) = impersonate_user_id {
221            req.header("X-Redmine-Switch-User", format!("{user_id}"))
222        } else {
223            req
224        };
225        let req = if let Some((mime, data)) = mime_type_and_body {
226            if let Ok(request_body) = from_utf8(&data) {
227                trace!("Request body (Content-Type: {}):\n{}", mime, request_body);
228            } else {
229                trace!(
230                    "Request body (Content-Type: {}) could not be parsed as UTF-8:\n{:?}",
231                    mime, data
232                );
233            }
234            req.body(data).header("Content-Type", mime)
235        } else {
236            req
237        };
238        let result = req.send();
239        if let Err(ref e) = result {
240            error!(%url, %method, "Redmine send error: {:?}", e);
241        }
242        let result = result?;
243        let status = result.status();
244        let response_body = result.bytes()?;
245        match from_utf8(&response_body) {
246            Ok(response_body) => {
247                trace!("Response body:\n{}", &response_body);
248            }
249            Err(e) => {
250                trace!(
251                    "Response body that could not be parsed as utf8 because of {}:\n{:?}",
252                    &e, &response_body
253                );
254            }
255        }
256        if status.is_client_error() {
257            error!(%url, %method, "Redmine status error (client error): {:?} response: {:?}", status, from_utf8(&response_body));
258            return Err(crate::Error::HttpErrorResponse(status));
259        } else if status.is_server_error() {
260            error!(%url, %method, "Redmine status error (server error): {:?} response: {:?}", status, from_utf8(&response_body));
261            return Err(crate::Error::HttpErrorResponse(status));
262        }
263        Ok((status, response_body))
264    }
265
266    /// use this with endpoints that have no response body, e.g. those just deleting
267    /// a Redmine object
268    ///
269    /// # Errors
270    ///
271    /// This can return an error if the endpoint returns an error when creating the request
272    /// body or when the web request fails
273    pub fn ignore_response_body<E>(&self, endpoint: &E) -> Result<(), crate::Error>
274    where
275        E: Endpoint,
276    {
277        let method = endpoint.method();
278        let url = endpoint.endpoint();
279        let parameters = endpoint.parameters();
280        let mime_type_and_body = endpoint.body()?;
281        self.rest(method, &url, parameters, mime_type_and_body)?;
282        Ok(())
283    }
284
285    /// use this with endpoints which return a JSON response but do not support pagination
286    ///
287    /// # Errors
288    ///
289    /// This can return an error if the endpoint returns an error when creating the request body,
290    /// when the web request fails or when the response can not be parsed as a JSON object
291    /// into the result type
292    pub fn json_response_body<E, R>(&self, endpoint: &E) -> Result<R, crate::Error>
293    where
294        E: Endpoint + ReturnsJsonResponse + NoPagination,
295        R: DeserializeOwned + std::fmt::Debug,
296    {
297        let method = endpoint.method();
298        let url = endpoint.endpoint();
299        let parameters = endpoint.parameters();
300        let mime_type_and_body = endpoint.body()?;
301        let (status, response_body) = self.rest(method, &url, parameters, mime_type_and_body)?;
302        if response_body.is_empty() {
303            Err(crate::Error::EmptyResponseBody(status))
304        } else {
305            let result = serde_json::from_slice::<R>(&response_body);
306            if let Ok(ref parsed_response_body) = result {
307                trace!("Parsed response body:\n{:#?}", parsed_response_body);
308            }
309            Ok(result?)
310        }
311    }
312
313    /// use this to get a single page of a paginated JSON response
314    /// # Errors
315    ///
316    /// This can return an error if the endpoint returns an error when creating the
317    /// request body, when the web request fails, when the response can not be parsed
318    /// as a JSON object, when any of the pagination keys or the value key are missing
319    /// in the JSON object or when the values can not be parsed as the result type.
320    pub fn json_response_body_page<E, R>(
321        &self,
322        endpoint: &E,
323        offset: u64,
324        limit: u64,
325    ) -> Result<ResponsePage<R>, crate::Error>
326    where
327        E: Endpoint + ReturnsJsonResponse + Pageable,
328        R: DeserializeOwned + std::fmt::Debug,
329    {
330        let method = endpoint.method();
331        let url = endpoint.endpoint();
332        let mut parameters = endpoint.parameters();
333        parameters.push("offset", offset);
334        parameters.push("limit", limit);
335        let mime_type_and_body = endpoint.body()?;
336        let (status, response_body) = self.rest(method, &url, parameters, mime_type_and_body)?;
337        if response_body.is_empty() {
338            Err(crate::Error::EmptyResponseBody(status))
339        } else {
340            let json_value_response_body: serde_json::Value =
341                serde_json::from_slice(&response_body)?;
342            let json_object_response_body = json_value_response_body.as_object();
343            if let Some(json_object_response_body) = json_object_response_body {
344                let total_count = json_object_response_body
345                    .get("total_count")
346                    .ok_or_else(|| crate::Error::PaginationKeyMissing("total_count".to_string()))?
347                    .as_u64()
348                    .ok_or_else(|| {
349                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
350                    })?;
351                let offset = json_object_response_body
352                    .get("offset")
353                    .ok_or_else(|| crate::Error::PaginationKeyMissing("offset".to_string()))?
354                    .as_u64()
355                    .ok_or_else(|| {
356                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
357                    })?;
358                let limit = json_object_response_body
359                    .get("limit")
360                    .ok_or_else(|| crate::Error::PaginationKeyMissing("limit".to_string()))?
361                    .as_u64()
362                    .ok_or_else(|| {
363                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
364                    })?;
365                let response_wrapper_key = endpoint.response_wrapper_key();
366                let inner_response_body = json_object_response_body
367                    .get(&response_wrapper_key)
368                    .ok_or(crate::Error::PaginationKeyMissing(response_wrapper_key))?;
369                let result = serde_json::from_value::<Vec<R>>(inner_response_body.to_owned());
370                if let Ok(ref parsed_response_body) = result {
371                    trace!(%total_count, %offset, %limit, "Parsed response body:\n{:?}", parsed_response_body);
372                }
373                Ok(ResponsePage {
374                    values: result?,
375                    total_count,
376                    offset,
377                    limit,
378                })
379            } else {
380                Err(crate::Error::NonObjectResponseBody(status))
381            }
382        }
383    }
384
385    /// use this to get the results for all pages of a paginated JSON response
386    ///
387    /// # Errors
388    ///
389    /// This can return an error if the endpoint returns an error when creating the
390    /// request body, when any of the web requests fails, when the response can not be
391    /// parsed as a JSON object, when any of the pagination keys or the value key are missing
392    /// in the JSON object or when the values can not be parsed as the result type.
393    ///
394    #[expect(
395        clippy::arithmetic_side_effects,
396        reason = "u64 pagination counters; overflow requires impossibly many results"
397    )]
398    pub fn json_response_body_all_pages<E, R>(&self, endpoint: &E) -> Result<Vec<R>, crate::Error>
399    where
400        E: Endpoint + ReturnsJsonResponse + Pageable,
401        R: DeserializeOwned + std::fmt::Debug,
402    {
403        let method = endpoint.method();
404        let url = endpoint.endpoint();
405        let mut offset = 0;
406        let limit = 100;
407        let mut total_results = vec![];
408        loop {
409            let mut page_parameters = endpoint.parameters();
410            page_parameters.push("offset", offset);
411            page_parameters.push("limit", limit);
412            let mime_type_and_body = endpoint.body()?;
413            let (status, response_body) =
414                self.rest(method.clone(), &url, page_parameters, mime_type_and_body)?;
415            if response_body.is_empty() {
416                return Err(crate::Error::EmptyResponseBody(status));
417            }
418            let json_value_response_body: serde_json::Value =
419                serde_json::from_slice(&response_body)?;
420            let json_object_response_body = json_value_response_body.as_object();
421            if let Some(json_object_response_body) = json_object_response_body {
422                let total_count: u64 = json_object_response_body
423                    .get("total_count")
424                    .ok_or_else(|| crate::Error::PaginationKeyMissing("total_count".to_string()))?
425                    .as_u64()
426                    .ok_or_else(|| {
427                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
428                    })?;
429                let response_offset: u64 = json_object_response_body
430                    .get("offset")
431                    .ok_or_else(|| crate::Error::PaginationKeyMissing("offset".to_string()))?
432                    .as_u64()
433                    .ok_or_else(|| {
434                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
435                    })?;
436                let response_limit: u64 = json_object_response_body
437                    .get("limit")
438                    .ok_or_else(|| crate::Error::PaginationKeyMissing("limit".to_string()))?
439                    .as_u64()
440                    .ok_or_else(|| {
441                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
442                    })?;
443                let response_wrapper_key = endpoint.response_wrapper_key();
444                let inner_response_body = json_object_response_body
445                    .get(&response_wrapper_key)
446                    .ok_or(crate::Error::PaginationKeyMissing(response_wrapper_key))?;
447                let result = serde_json::from_value::<Vec<R>>(inner_response_body.to_owned());
448                if let Ok(ref parsed_response_body) = result {
449                    trace!(%total_count, %offset, %limit, "Parsed response body:\n{:?}", parsed_response_body);
450                }
451                total_results.extend(result?);
452                if total_count < (response_offset + response_limit) {
453                    break;
454                }
455                offset += limit;
456            } else {
457                return Err(crate::Error::NonObjectResponseBody(status));
458            }
459        }
460        Ok(total_results)
461    }
462
463    /// use this to get the results for all pages of a paginated JSON response
464    /// as an Iterator
465    pub const fn json_response_body_all_pages_iter<'a, 'e, 'i, E, R>(
466        &'a self,
467        endpoint: &'e E,
468    ) -> AllPages<'i, E, R>
469    where
470        E: Endpoint + ReturnsJsonResponse + Pageable,
471        R: DeserializeOwned + std::fmt::Debug,
472        'a: 'i,
473        'e: 'i,
474    {
475        AllPages::new(self, endpoint)
476    }
477}
478
479impl RedmineAsync {
480    /// create a [RedmineAsync] object
481    ///
482    /// # Errors
483    ///
484    /// This will return [`crate::Error::ReqwestError`] if initialization of Reqwest client is failed.
485    pub fn new(
486        client: reqwest::Client,
487        redmine_url: url::Url,
488        api_key: &str,
489    ) -> Result<std::sync::Arc<Self>, crate::Error> {
490        Ok(std::sync::Arc::new(Self {
491            client,
492            redmine_url,
493            api_key: api_key.to_string(),
494            impersonate_user_id: None,
495        }))
496    }
497
498    /// create a [RedmineAsync] object from the environment variables
499    ///
500    /// REDMINE_API_KEY
501    /// REDMINE_URL
502    ///
503    /// # Errors
504    ///
505    /// This will return an error if the environment variables are
506    /// missing or the URL can not be parsed
507    pub fn from_env(client: reqwest::Client) -> Result<std::sync::Arc<Self>, crate::Error> {
508        let env_options = envy::from_env::<EnvOptions>()?;
509
510        let redmine_url = env_options.redmine_url;
511        let api_key = env_options.redmine_api_key;
512
513        Self::new(client, redmine_url, &api_key)
514    }
515
516    /// Sets the user id of a user to impersonate in all future API calls
517    ///
518    /// this requires Redmine admin privileges
519    pub const fn impersonate_user(&mut self, id: u64) {
520        self.impersonate_user_id = Some(id);
521    }
522
523    /// returns the redmine base url
524    #[must_use]
525    pub const fn redmine_url(&self) -> &Url {
526        &self.redmine_url
527    }
528
529    /// returns the issue URL for a given issue id
530    ///
531    /// this is mostly for convenience since we are already storing the
532    /// redmine URL and it works entirely on the client
533    #[must_use]
534    #[expect(
535        clippy::missing_panics_doc,
536        clippy::unwrap_used,
537        reason = "join cannot fail for a constant relative URL"
538    )]
539    pub fn issue_url(&self, issue_id: u64) -> Url {
540        let Self { redmine_url, .. } = self;
541        // we can unwrap here because we know /issues/<number>
542        // parses successfully as an url fragment
543        redmine_url.join(&format!("/issues/{issue_id}")).unwrap()
544    }
545
546    /// internal method for shared logic between the methods below which
547    /// diff in how they parse the response body and how often they call this
548    async fn rest(
549        self: std::sync::Arc<Self>,
550        method: reqwest::Method,
551        endpoint: &str,
552        parameters: QueryParams<'_>,
553        mime_type_and_body: Option<(&str, Vec<u8>)>,
554    ) -> Result<(reqwest::StatusCode, bytes::Bytes), crate::Error> {
555        let Self {
556            client,
557            redmine_url,
558            api_key,
559            impersonate_user_id,
560        } = self.as_ref();
561        let mut url = redmine_url.join(endpoint)?;
562        parameters.add_to_url(&mut url);
563        debug!(%url, %method, "Calling redmine");
564        let req = client
565            .request(method.clone(), url.clone())
566            .header("x-redmine-api-key", api_key);
567        let req = if let Some(user_id) = impersonate_user_id {
568            req.header("X-Redmine-Switch-User", format!("{user_id}"))
569        } else {
570            req
571        };
572        let req = if let Some((mime, data)) = mime_type_and_body {
573            if let Ok(request_body) = from_utf8(&data) {
574                trace!("Request body (Content-Type: {}):\n{}", mime, request_body);
575            } else {
576                trace!(
577                    "Request body (Content-Type: {}) could not be parsed as UTF-8:\n{:?}",
578                    mime, data
579                );
580            }
581            req.body(data).header("Content-Type", mime)
582        } else {
583            req
584        };
585        let result = req.send().await;
586        if let Err(ref e) = result {
587            error!(%url, %method, "Redmine send error: {:?}", e);
588        }
589        let result = result?;
590        let status = result.status();
591        let response_body = result.bytes().await?;
592        match from_utf8(&response_body) {
593            Ok(response_body) => {
594                trace!("Response body:\n{}", &response_body);
595            }
596            Err(e) => {
597                trace!(
598                    "Response body that could not be parsed as utf8 because of {}:\n{:?}",
599                    &e, &response_body
600                );
601            }
602        }
603        if status.is_client_error() {
604            error!(%url, %method, "Redmine status error (client error): {:?} response: {:?}", status, from_utf8(&response_body));
605            return Err(crate::Error::HttpErrorResponse(status));
606        } else if status.is_server_error() {
607            error!(%url, %method, "Redmine status error (server error): {:?} response: {:?}", status, from_utf8(&response_body));
608            return Err(crate::Error::HttpErrorResponse(status));
609        }
610        Ok((status, response_body))
611    }
612
613    /// use this with endpoints that have no response body, e.g. those just deleting
614    /// a Redmine object
615    ///
616    /// # Errors
617    ///
618    /// This can return an error if the endpoint returns an error when creating the request
619    /// body or when the web request fails
620    pub async fn ignore_response_body<E>(
621        self: std::sync::Arc<Self>,
622        endpoint: impl EndpointParameter<E>,
623    ) -> Result<(), crate::Error>
624    where
625        E: Endpoint,
626    {
627        let endpoint: std::sync::Arc<E> = endpoint.into_arc();
628        let method = endpoint.method();
629        let url = endpoint.endpoint();
630        let parameters = endpoint.parameters();
631        let mime_type_and_body = endpoint.body()?;
632        self.rest(method, &url, parameters, mime_type_and_body)
633            .await?;
634        Ok(())
635    }
636
637    /// use this with endpoints which return a JSON response but do not support pagination
638    ///
639    /// you can use it with those that support pagination but they will only return the first page
640    ///
641    /// # Errors
642    ///
643    /// This can return an error if the endpoint returns an error when creating the request body,
644    /// when the web request fails or when the response can not be parsed as a JSON object
645    /// into the result type
646    pub async fn json_response_body<E, R>(
647        self: std::sync::Arc<Self>,
648        endpoint: impl EndpointParameter<E>,
649    ) -> Result<R, crate::Error>
650    where
651        E: Endpoint + ReturnsJsonResponse + NoPagination,
652        R: DeserializeOwned + std::fmt::Debug,
653    {
654        let endpoint: std::sync::Arc<E> = endpoint.into_arc();
655        let method = endpoint.method();
656        let url = endpoint.endpoint();
657        let parameters = endpoint.parameters();
658        let mime_type_and_body = endpoint.body()?;
659        let (status, response_body) = self
660            .rest(method, &url, parameters, mime_type_and_body)
661            .await?;
662        if response_body.is_empty() {
663            Err(crate::Error::EmptyResponseBody(status))
664        } else {
665            let result = serde_json::from_slice::<R>(&response_body);
666            if let Ok(ref parsed_response_body) = result {
667                trace!("Parsed response body:\n{:#?}", parsed_response_body);
668            }
669            Ok(result?)
670        }
671    }
672
673    /// use this to get a single page of a paginated JSON response
674    /// # Errors
675    ///
676    /// This can return an error if the endpoint returns an error when creating the
677    /// request body, when the web request fails, when the response can not be parsed
678    /// as a JSON object, when any of the pagination keys or the value key are missing
679    /// in the JSON object or when the values can not be parsed as the result type.
680    pub async fn json_response_body_page<E, R>(
681        self: std::sync::Arc<Self>,
682        endpoint: impl EndpointParameter<E>,
683        offset: u64,
684        limit: u64,
685    ) -> Result<ResponsePage<R>, crate::Error>
686    where
687        E: Endpoint + ReturnsJsonResponse + Pageable,
688        R: DeserializeOwned + std::fmt::Debug,
689    {
690        let endpoint: std::sync::Arc<E> = endpoint.into_arc();
691        let method = endpoint.method();
692        let url = endpoint.endpoint();
693        let mut parameters = endpoint.parameters();
694        parameters.push("offset", offset);
695        parameters.push("limit", limit);
696        let mime_type_and_body = endpoint.body()?;
697        let (status, response_body) = self
698            .rest(method, &url, parameters, mime_type_and_body)
699            .await?;
700        if response_body.is_empty() {
701            Err(crate::Error::EmptyResponseBody(status))
702        } else {
703            let json_value_response_body: serde_json::Value =
704                serde_json::from_slice(&response_body)?;
705            let json_object_response_body = json_value_response_body.as_object();
706            if let Some(json_object_response_body) = json_object_response_body {
707                let total_count = json_object_response_body
708                    .get("total_count")
709                    .ok_or_else(|| crate::Error::PaginationKeyMissing("total_count".to_string()))?
710                    .as_u64()
711                    .ok_or_else(|| {
712                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
713                    })?;
714                let offset = json_object_response_body
715                    .get("offset")
716                    .ok_or_else(|| crate::Error::PaginationKeyMissing("offset".to_string()))?
717                    .as_u64()
718                    .ok_or_else(|| {
719                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
720                    })?;
721                let limit = json_object_response_body
722                    .get("limit")
723                    .ok_or_else(|| crate::Error::PaginationKeyMissing("limit".to_string()))?
724                    .as_u64()
725                    .ok_or_else(|| {
726                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
727                    })?;
728                let response_wrapper_key = endpoint.response_wrapper_key();
729                let inner_response_body = json_object_response_body
730                    .get(&response_wrapper_key)
731                    .ok_or(crate::Error::PaginationKeyMissing(response_wrapper_key))?;
732                let result = serde_json::from_value::<Vec<R>>(inner_response_body.to_owned());
733                if let Ok(ref parsed_response_body) = result {
734                    trace!(%total_count, %offset, %limit, "Parsed response body:\n{:?}", parsed_response_body);
735                }
736                Ok(ResponsePage {
737                    values: result?,
738                    total_count,
739                    offset,
740                    limit,
741                })
742            } else {
743                Err(crate::Error::NonObjectResponseBody(status))
744            }
745        }
746    }
747
748    /// use this to get the results for all pages of a paginated JSON response
749    ///
750    /// # Errors
751    ///
752    /// This can return an error if the endpoint returns an error when creating the
753    /// request body, when any of the web requests fails, when the response can not be
754    /// parsed as a JSON object, when any of the pagination keys or the value key are missing
755    /// in the JSON object or when the values can not be parsed as the result type.
756    ///
757    #[expect(
758        clippy::arithmetic_side_effects,
759        clippy::clone_on_ref_ptr,
760        reason = "u64 pagination counters; cloning an Arc<Self> is intentional to keep the Arc alive across the await"
761    )]
762    pub async fn json_response_body_all_pages<E, R>(
763        self: std::sync::Arc<Self>,
764        endpoint: impl EndpointParameter<E>,
765    ) -> Result<Vec<R>, crate::Error>
766    where
767        E: Endpoint + ReturnsJsonResponse + Pageable,
768        R: DeserializeOwned + std::fmt::Debug,
769    {
770        let endpoint: std::sync::Arc<E> = endpoint.into_arc();
771        let method = endpoint.method();
772        let url = endpoint.endpoint();
773        let mut offset = 0;
774        let limit = 100;
775        let mut total_results = vec![];
776        loop {
777            let mut page_parameters = endpoint.parameters();
778            page_parameters.push("offset", offset);
779            page_parameters.push("limit", limit);
780            let mime_type_and_body = endpoint.body()?;
781            let (status, response_body) = self
782                .clone()
783                .rest(method.clone(), &url, page_parameters, mime_type_and_body)
784                .await?;
785            if response_body.is_empty() {
786                return Err(crate::Error::EmptyResponseBody(status));
787            }
788            let json_value_response_body: serde_json::Value =
789                serde_json::from_slice(&response_body)?;
790            let json_object_response_body = json_value_response_body.as_object();
791            if let Some(json_object_response_body) = json_object_response_body {
792                let total_count: u64 = json_object_response_body
793                    .get("total_count")
794                    .ok_or_else(|| crate::Error::PaginationKeyMissing("total_count".to_string()))?
795                    .as_u64()
796                    .ok_or_else(|| {
797                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
798                    })?;
799                let response_offset: u64 = json_object_response_body
800                    .get("offset")
801                    .ok_or_else(|| crate::Error::PaginationKeyMissing("offset".to_string()))?
802                    .as_u64()
803                    .ok_or_else(|| {
804                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
805                    })?;
806                let response_limit: u64 = json_object_response_body
807                    .get("limit")
808                    .ok_or_else(|| crate::Error::PaginationKeyMissing("limit".to_string()))?
809                    .as_u64()
810                    .ok_or_else(|| {
811                        crate::Error::PaginationKeyHasWrongType("total_count".to_string())
812                    })?;
813                let response_wrapper_key = endpoint.response_wrapper_key();
814                let inner_response_body = json_object_response_body
815                    .get(&response_wrapper_key)
816                    .ok_or(crate::Error::PaginationKeyMissing(response_wrapper_key))?;
817                let result = serde_json::from_value::<Vec<R>>(inner_response_body.to_owned());
818                if let Ok(ref parsed_response_body) = result {
819                    trace!(%total_count, %offset, %limit, "Parsed response body:\n{:?}", parsed_response_body);
820                }
821                total_results.extend(result?);
822                if total_count < (response_offset + response_limit) {
823                    break;
824                }
825                offset += limit;
826            } else {
827                return Err(crate::Error::NonObjectResponseBody(status));
828            }
829        }
830        Ok(total_results)
831    }
832
833    /// use this to get the results for all pages of a paginated JSON response
834    /// as a Stream
835    pub fn json_response_body_all_pages_stream<E, R>(
836        self: std::sync::Arc<Self>,
837        endpoint: impl EndpointParameter<E>,
838    ) -> AllPagesAsync<E, R>
839    where
840        E: Endpoint + ReturnsJsonResponse + Pageable,
841        R: DeserializeOwned + std::fmt::Debug,
842    {
843        let endpoint: std::sync::Arc<E> = endpoint.into_arc();
844        AllPagesAsync::new(self, endpoint)
845    }
846}
847
848/// A trait representing a parameter value.
849pub trait ParamValue<'a> {
850    /// The parameter value as a string.
851    fn as_value(&self) -> Cow<'a, str>;
852}
853
854impl ParamValue<'static> for bool {
855    fn as_value(&self) -> Cow<'static, str> {
856        if *self { "true".into() } else { "false".into() }
857    }
858}
859
860impl<'a> ParamValue<'a> for &'a str {
861    fn as_value(&self) -> Cow<'a, str> {
862        (*self).into()
863    }
864}
865
866impl ParamValue<'static> for String {
867    fn as_value(&self) -> Cow<'static, str> {
868        self.clone().into()
869    }
870}
871
872impl<'a> ParamValue<'a> for &'a String {
873    fn as_value(&self) -> Cow<'a, str> {
874        (*self).into()
875    }
876}
877
878/// serialize a [`Vec<T>`] where T implements [ToString] as a string
879/// of comma-separated values
880impl<T> ParamValue<'static> for Vec<T>
881where
882    T: ToString,
883{
884    fn as_value(&self) -> Cow<'static, str> {
885        self.iter()
886            .map(|e| e.to_string())
887            .collect::<Vec<_>>()
888            .join(",")
889            .into()
890    }
891}
892
893/// serialize a [`&Vec<T>`](Vec<T>) where T implements [ToString] as a string
894/// of comma-separated values
895impl<'a, T> ParamValue<'a> for &'a Vec<T>
896where
897    T: ToString,
898{
899    fn as_value(&self) -> Cow<'a, str> {
900        self.iter()
901            .map(|e| e.to_string())
902            .collect::<Vec<_>>()
903            .join(",")
904            .into()
905    }
906}
907
908impl<'a> ParamValue<'a> for Cow<'a, str> {
909    fn as_value(&self) -> Self {
910        self.clone()
911    }
912}
913
914impl<'a> ParamValue<'a> for &'a Cow<'a, str> {
915    fn as_value(&self) -> Cow<'a, str> {
916        (*self).clone()
917    }
918}
919
920impl ParamValue<'static> for u64 {
921    fn as_value(&self) -> Cow<'static, str> {
922        format!("{self}").into()
923    }
924}
925
926impl ParamValue<'static> for f64 {
927    fn as_value(&self) -> Cow<'static, str> {
928        format!("{self}").into()
929    }
930}
931
932impl ParamValue<'static> for time::OffsetDateTime {
933    #[expect(
934        clippy::unwrap_used,
935        reason = "RFC 3339 formatting cannot fail for a fully-populated OffsetDateTime"
936    )]
937    fn as_value(&self) -> Cow<'static, str> {
938        self.format(&time::format_description::well_known::Rfc3339)
939            .unwrap()
940            .into()
941    }
942}
943
944impl ParamValue<'static> for time::Date {
945    #[expect(
946        clippy::unwrap_used,
947        reason = "the format description literal is a constant valid format"
948    )]
949    fn as_value(&self) -> Cow<'static, str> {
950        let format = time::macros::format_description!(version = 3, "[year]-[month]-[day]");
951        self.format(&format).unwrap().into()
952    }
953}
954
955/// Filter for a comparable date time filters for past
956/// used for filters on created_on, updated_on fields
957#[derive(Debug, Clone)]
958pub enum DateTimeFilterPast {
959    /// an exact match
960    ExactMatch(time::OffsetDateTime),
961    /// a range match (inclusive)
962    Range(time::OffsetDateTime, time::OffsetDateTime),
963    /// we only want values less than or equal to the parameter
964    LessThanOrEqual(time::OffsetDateTime),
965    /// we only want values greater than or equal to the parameter
966    GreaterThanOrEqual(time::OffsetDateTime),
967    /// less than n days ago
968    LessThanDaysAgo(u32),
969    /// more than n days ago
970    MoreThanDaysAgo(u32),
971    /// within the past n days
972    WithinPastDays(u32),
973    /// exactly n days ago
974    ExactDaysAgo(u32),
975    /// today
976    Today,
977    /// yesterday
978    Yesterday,
979    /// this week
980    ThisWeek,
981    /// last week
982    LastWeek,
983    /// last 2 weeks
984    LastTwoWeeks,
985    /// this month
986    ThisMonth,
987    /// last month
988    LastMonth,
989    /// this year
990    ThisYear,
991    /// unset value (NULL in DB)
992    Unset,
993    /// any value (NOT NULL in DB)
994    Any,
995}
996
997impl std::fmt::Display for DateTimeFilterPast {
998    #[expect(
999        clippy::expect_used,
1000        reason = "the format_description!() macro produces a known-good format that cannot fail at runtime"
1001    )]
1002    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1003        let format =
1004            time::macros::format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]Z");
1005        match self {
1006            Self::ExactMatch(v) => {
1007                write!(
1008                    f,
1009                    "{}",
1010                    v.format(&format).expect(
1011                        "Error formatting OffsetDateTime in DateTimeFilterPast::ExactMatch"
1012                    )
1013                )
1014            }
1015            Self::Range(v_start, v_end) => {
1016                write!(
1017                    f,
1018                    "><{}|{}",
1019                    v_start.format(&format).expect(
1020                        "Error formatting first OffsetDateTime in DateTimeFilterPast::Range"
1021                    ),
1022                    v_end.format(&format).expect(
1023                        "Error formatting second OffsetDateTime in DateTimeFilterPast::Range"
1024                    ),
1025                )
1026            }
1027            Self::LessThanOrEqual(v) => {
1028                write!(
1029                    f,
1030                    "<={}",
1031                    v.format(&format).expect(
1032                        "Error formatting OffsetDateTime in DateTimeFilterPast::LessThanOrEqual"
1033                    )
1034                )
1035            }
1036            Self::GreaterThanOrEqual(v) => {
1037                write!(
1038                    f,
1039                    ">={}",
1040                    v.format(&format).expect(
1041                        "Error formatting OffsetDateTime in DateTimeFilterPast::GreaterThanOrEqual"
1042                    )
1043                )
1044            }
1045            Self::LessThanDaysAgo(d) => {
1046                write!(f, ">t-{d}")
1047            }
1048            Self::MoreThanDaysAgo(d) => {
1049                write!(f, "<t-{d}")
1050            }
1051            Self::WithinPastDays(d) => {
1052                write!(f, "><t-{d}")
1053            }
1054            Self::ExactDaysAgo(d) => {
1055                write!(f, "t-{d}")
1056            }
1057            Self::Today => {
1058                write!(f, "t")
1059            }
1060            Self::Yesterday => {
1061                write!(f, "ld")
1062            }
1063            Self::ThisWeek => {
1064                write!(f, "w")
1065            }
1066            Self::LastWeek => {
1067                write!(f, "lw")
1068            }
1069            Self::LastTwoWeeks => {
1070                write!(f, "l2w")
1071            }
1072            Self::ThisMonth => {
1073                write!(f, "m")
1074            }
1075            Self::LastMonth => {
1076                write!(f, "lm")
1077            }
1078            Self::ThisYear => {
1079                write!(f, "y")
1080            }
1081            Self::Unset => {
1082                write!(f, "!*")
1083            }
1084            Self::Any => {
1085                write!(f, "*")
1086            }
1087        }
1088    }
1089}
1090
1091/// Filter options for subject and description
1092#[derive(Debug, Clone)]
1093pub enum StringFieldFilter {
1094    /// match exactly this value
1095    ExactMatch(String),
1096    /// match this substring of the actual value
1097    SubStringMatch(String),
1098}
1099
1100impl std::fmt::Display for StringFieldFilter {
1101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1102        match self {
1103            Self::ExactMatch(s) => {
1104                write!(f, "{s}")
1105            }
1106            Self::SubStringMatch(s) => {
1107                write!(f, "~{s}")
1108            }
1109        }
1110    }
1111}
1112
1113/// A filter for a custom field, consisting of its ID and a StringFieldFilter for its value.
1114#[derive(Debug, Clone)]
1115pub struct CustomFieldFilter {
1116    /// The ID of the custom field to filter by.
1117    pub id: u64,
1118    /// The value to filter the custom field by, using a `StringFieldFilter`.
1119    pub value: StringFieldFilter,
1120}
1121
1122/// Filter for float values, supporting various comparison operators.
1123#[derive(Debug, Clone)]
1124pub enum FloatFilter {
1125    /// An exact match for the float value.
1126    ExactMatch(f64),
1127    /// A range match (inclusive) for two float values.
1128    Range(f64, f64),
1129    /// Values less than or equal to the specified float.
1130    LessThanOrEqual(f64),
1131    /// Values greater than or equal to the specified float.
1132    GreaterThanOrEqual(f64),
1133    /// Any value (equivalent to `> 0`).
1134    Any,
1135    /// No value (equivalent to `= 0`).
1136    None,
1137}
1138
1139impl std::fmt::Display for FloatFilter {
1140    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1141        match self {
1142            Self::ExactMatch(v) => write!(f, "{v}"),
1143            Self::Range(v_start, v_end) => write!(f, "><{v_start}|{v_end}"),
1144            Self::LessThanOrEqual(v) => write!(f, "<={v}"),
1145            Self::GreaterThanOrEqual(v) => write!(f, ">={v}"),
1146            Self::Any => write!(f, "*"),
1147            Self::None => write!(f, "!*"),
1148        }
1149    }
1150}
1151
1152/// Filter for integer values, supporting various comparison operators.
1153#[derive(Debug, Clone)]
1154pub enum IntegerFilter {
1155    /// An exact match for the integer value.
1156    ExactMatch(u64),
1157    /// A range match (inclusive) for two integer values.
1158    Range(u64, u64),
1159    /// Values less than or equal to the specified integer.
1160    LessThanOrEqual(u64),
1161    /// Values greater than or equal to the specified integer.
1162    GreaterThanOrEqual(u64),
1163    /// Any value (equivalent to `> 0`).
1164    Any,
1165    /// No value (equivalent to `= 0`).
1166    None,
1167}
1168
1169impl std::fmt::Display for IntegerFilter {
1170    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1171        match self {
1172            Self::ExactMatch(v) => write!(f, "{v}"),
1173            Self::Range(v_start, v_end) => write!(f, "><{v_start}|{v_end}"),
1174            Self::LessThanOrEqual(v) => write!(f, "<={v}"),
1175            Self::GreaterThanOrEqual(v) => write!(f, ">={v}"),
1176            Self::Any => write!(f, "*"),
1177            Self::None => write!(f, "!*"),
1178        }
1179    }
1180}
1181
1182/// Filter for tracker IDs.
1183#[derive(Debug, Clone)]
1184pub enum TrackerFilter {
1185    /// Match any tracker.
1186    Any,
1187    /// Match no tracker.
1188    None,
1189    /// Match a specific list of trackers.
1190    TheseTrackers(Vec<u64>),
1191    /// Match any tracker but a specific list of trackers.
1192    NotTheseTrackers(Vec<u64>),
1193}
1194
1195impl std::fmt::Display for TrackerFilter {
1196    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1197        match self {
1198            Self::Any => write!(f, "*"),
1199            Self::None => write!(f, "!*"),
1200            Self::TheseTrackers(ids) => {
1201                let s: String = ids
1202                    .iter()
1203                    .map(|e| e.to_string())
1204                    .collect::<Vec<_>>()
1205                    .join(",");
1206                write!(f, "{s}")
1207            }
1208            Self::NotTheseTrackers(ids) => {
1209                let s: String = ids
1210                    .iter()
1211                    .map(|e| format!("!{e}"))
1212                    .collect::<Vec<_>>()
1213                    .join(",");
1214                write!(f, "{s}")
1215            }
1216        }
1217    }
1218}
1219
1220/// Filter for activity IDs.
1221#[derive(Debug, Clone)]
1222pub enum ActivityFilter {
1223    /// Match any activity.
1224    Any,
1225    /// Match no activity.
1226    None,
1227    /// Match a specific list of activities.
1228    TheseActivities(Vec<u64>),
1229    /// Match any activity but a specific list of activities.
1230    NotTheseActivities(Vec<u64>),
1231}
1232
1233impl std::fmt::Display for ActivityFilter {
1234    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1235        match self {
1236            Self::Any => write!(f, "*"),
1237            Self::None => write!(f, "!*"),
1238            Self::TheseActivities(ids) => {
1239                let s: String = ids
1240                    .iter()
1241                    .map(|e| e.to_string())
1242                    .collect::<Vec<_>>()
1243                    .join(",");
1244                write!(f, "{s}")
1245            }
1246            Self::NotTheseActivities(ids) => {
1247                let s: String = ids
1248                    .iter()
1249                    .map(|e| format!("!{e}"))
1250                    .collect::<Vec<_>>()
1251                    .join(",");
1252                write!(f, "{s}")
1253            }
1254        }
1255    }
1256}
1257
1258/// Filter for fixed version IDs.
1259#[derive(Debug, Clone)]
1260pub enum VersionFilter {
1261    /// Match any version.
1262    Any,
1263    /// Match no version.
1264    None,
1265    /// Match a specific list of versions.
1266    TheseVersions(Vec<u64>),
1267    /// Match any version but a specific list of versions.
1268    NotTheseVersions(Vec<u64>),
1269}
1270
1271impl std::fmt::Display for VersionFilter {
1272    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1273        match self {
1274            Self::Any => write!(f, "*"),
1275            Self::None => write!(f, "!*"),
1276            Self::TheseVersions(ids) => {
1277                let s: String = ids
1278                    .iter()
1279                    .map(|e| e.to_string())
1280                    .collect::<Vec<_>>()
1281                    .join(",");
1282                write!(f, "{s}")
1283            }
1284            Self::NotTheseVersions(ids) => {
1285                let s: String = ids
1286                    .iter()
1287                    .map(|e| format!("!{e}"))
1288                    .collect::<Vec<_>>()
1289                    .join(",");
1290                write!(f, "{s}")
1291            }
1292        }
1293    }
1294}
1295
1296/// Filter for date values, supporting various comparison operators.
1297#[derive(Debug, Clone)]
1298pub enum DateFilter {
1299    /// an exact match
1300    ExactMatch(time::Date),
1301    /// a range match (inclusive)
1302    Range(time::Date, time::Date),
1303    /// we only want values less than or equal to the parameter
1304    LessThanOrEqual(time::Date),
1305    /// we only want values greater than or equal to the parameter
1306    GreaterThanOrEqual(time::Date),
1307    /// less than n days ago
1308    LessThanDaysAgo(u32),
1309    /// more than n days ago
1310    MoreThanDaysAgo(u32),
1311    /// within the past n days
1312    WithinPastDays(u32),
1313    /// exactly n days ago
1314    ExactDaysAgo(u32),
1315    /// in less than n days
1316    InLessThanDays(u32),
1317    /// in more than n days
1318    InMoreThanDays(u32),
1319    /// in the next n days
1320    WithinFutureDays(u32),
1321    /// in exactly n days
1322    InExactDays(u32),
1323    /// today
1324    Today,
1325    /// yesterday
1326    Yesterday,
1327    /// tomorrow
1328    Tomorrow,
1329    /// this week
1330    ThisWeek,
1331    /// last week
1332    LastWeek,
1333    /// last 2 weeks
1334    LastTwoWeeks,
1335    /// next week
1336    NextWeek,
1337    /// this month
1338    ThisMonth,
1339    /// last month
1340    LastMonth,
1341    /// next month
1342    NextMonth,
1343    /// this year
1344    ThisYear,
1345    /// unset value (NULL in DB)
1346    Unset,
1347    /// any value (NOT NULL in DB)
1348    Any,
1349}
1350
1351impl std::fmt::Display for DateFilter {
1352    #[expect(
1353        clippy::expect_used,
1354        reason = "the format_description!() macro produces a known-good format that cannot fail at runtime"
1355    )]
1356    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1357        let format = time::macros::format_description!("[year]-[month]-[day]");
1358        match self {
1359            Self::ExactMatch(v) => {
1360                write!(
1361                    f,
1362                    "{}",
1363                    v.format(&format)
1364                        .expect("Error formatting Date in DateFilter::ExactMatch")
1365                )
1366            }
1367            Self::Range(v_start, v_end) => {
1368                write!(
1369                    f,
1370                    "><{}|{}",
1371                    v_start
1372                        .format(&format)
1373                        .expect("Error formatting first Date in DateFilter::Range"),
1374                    v_end
1375                        .format(&format)
1376                        .expect("Error formatting second Date in DateFilter::Range"),
1377                )
1378            }
1379            Self::LessThanOrEqual(v) => {
1380                write!(
1381                    f,
1382                    "<={}",
1383                    v.format(&format)
1384                        .expect("Error formatting Date in DateFilter::LessThanOrEqual")
1385                )
1386            }
1387            Self::GreaterThanOrEqual(v) => {
1388                write!(
1389                    f,
1390                    ">={}",
1391                    v.format(&format)
1392                        .expect("Error formatting Date in DateFilter::GreaterThanOrEqual")
1393                )
1394            }
1395            Self::LessThanDaysAgo(d) => {
1396                write!(f, ">t-{d}")
1397            }
1398            Self::MoreThanDaysAgo(d) => {
1399                write!(f, "<t-{d}")
1400            }
1401            Self::WithinPastDays(d) => {
1402                write!(f, "><t-{d}")
1403            }
1404            Self::ExactDaysAgo(d) => {
1405                write!(f, "t-{d}")
1406            }
1407            Self::InLessThanDays(d) => {
1408                write!(f, "<t+{d}")
1409            }
1410            Self::InMoreThanDays(d) => {
1411                write!(f, ">t+{d}")
1412            }
1413            Self::WithinFutureDays(d) => {
1414                write!(f, "><t+{d}")
1415            }
1416            Self::InExactDays(d) => {
1417                write!(f, "t+{d}")
1418            }
1419            Self::Today => {
1420                write!(f, "t")
1421            }
1422            Self::Yesterday => {
1423                write!(f, "ld")
1424            }
1425            Self::Tomorrow => {
1426                write!(f, "nd")
1427            }
1428            Self::ThisWeek => {
1429                write!(f, "w")
1430            }
1431            Self::LastWeek => {
1432                write!(f, "lw")
1433            }
1434            Self::LastTwoWeeks => {
1435                write!(f, "l2w")
1436            }
1437            Self::NextWeek => {
1438                write!(f, "nw")
1439            }
1440            Self::ThisMonth => {
1441                write!(f, "m")
1442            }
1443            Self::LastMonth => {
1444                write!(f, "lm")
1445            }
1446            Self::NextMonth => {
1447                write!(f, "nm")
1448            }
1449            Self::ThisYear => {
1450                write!(f, "y")
1451            }
1452            Self::Unset => {
1453                write!(f, "!*")
1454            }
1455            Self::Any => {
1456                write!(f, "*")
1457            }
1458        }
1459    }
1460}
1461
1462/// A structure for query parameters.
1463#[derive(Debug, Default, Clone)]
1464pub struct QueryParams<'a> {
1465    /// the actual parameters
1466    params: Vec<(Cow<'a, str>, Cow<'a, str>)>,
1467}
1468
1469impl<'a> QueryParams<'a> {
1470    /// Push a single parameter.
1471    pub fn push<'b, K, V>(&mut self, key: K, value: V) -> &mut Self
1472    where
1473        K: Into<Cow<'a, str>>,
1474        V: ParamValue<'b>,
1475        'b: 'a,
1476    {
1477        self.params.push((key.into(), value.as_value()));
1478        self
1479    }
1480
1481    /// Push a single parameter.
1482    pub fn push_opt<'b, K, V>(&mut self, key: K, value: Option<V>) -> &mut Self
1483    where
1484        K: Into<Cow<'a, str>>,
1485        V: ParamValue<'b>,
1486        'b: 'a,
1487    {
1488        if let Some(value) = value {
1489            self.params.push((key.into(), value.as_value()));
1490        }
1491        self
1492    }
1493
1494    /// Push a set of parameters.
1495    pub fn extend<'b, I, K, V>(&mut self, iter: I) -> &mut Self
1496    where
1497        I: Iterator<Item = (K, V)>,
1498        K: Into<Cow<'a, str>>,
1499        V: ParamValue<'b>,
1500        'b: 'a,
1501    {
1502        self.params
1503            .extend(iter.map(|(key, value)| (key.into(), value.as_value())));
1504        self
1505    }
1506
1507    /// Add the parameters to a URL.
1508    pub fn add_to_url(&self, url: &mut Url) {
1509        let mut pairs = url.query_pairs_mut();
1510        pairs.extend_pairs(self.params.iter());
1511    }
1512}
1513
1514/// A trait for providing the necessary information for a single REST API endpoint.
1515pub trait Endpoint {
1516    /// The HTTP method to use for the endpoint.
1517    fn method(&self) -> Method;
1518    /// The path to the endpoint.
1519    fn endpoint(&self) -> Cow<'static, str>;
1520
1521    /// Query parameters for the endpoint.
1522    fn parameters(&self) -> QueryParams<'_> {
1523        QueryParams::default()
1524    }
1525
1526    /// The body for the endpoint.
1527    ///
1528    /// Returns the `Content-Encoding` header for the data as well as the data itself.
1529    ///
1530    /// # Errors
1531    ///
1532    /// The default implementation will never return an error
1533    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, crate::Error> {
1534        Ok(None)
1535    }
1536}
1537
1538/// A trait to indicate that an endpoint is expected to return a JSON result
1539pub trait ReturnsJsonResponse {}
1540
1541/// A trait to indicate that an endpoint requires pagination to yield all results
1542/// or in other words that the non-pagination API should not be used on it or one
1543/// might miss some results
1544#[diagnostic::on_unimplemented(
1545    message = "{Self} is an endpoint that either returns nothing or requires pagination, use `.ignore_response_body(&endpoint)`, `.json_response_body_page(&endpoint, offset, limit)` or `.json_response_body_all_pages(&endpoint)` instead of `.json_response_body(&endpoint)`"
1546)]
1547pub trait NoPagination {}
1548
1549/// A trait to indicate that an endpoint is pageable.
1550#[diagnostic::on_unimplemented(
1551    message = "{Self} is an endpoint that does not implement pagination or returns nothing, use `.ignore_response_body(&endpoint)` or `.json_response_body(&endpoint)` instead of `.json_response_body_page(&endpoint, offset, limit)` or `.json_response_body_all_pages(&endpoint)`"
1552)]
1553pub trait Pageable {
1554    /// returns the name of the key in the response that contains the list of results
1555    fn response_wrapper_key(&self) -> String;
1556}
1557
1558/// helper to parse created_on and updated_on in the correct format
1559/// (default time serde implementation seems to use a different format)
1560///
1561/// # Errors
1562///
1563/// This will return an error if the underlying string can not be deserialized or
1564/// can not be parsed as an RFC3339 date and time
1565pub fn deserialize_rfc3339<'de, D>(deserializer: D) -> Result<time::OffsetDateTime, D::Error>
1566where
1567    D: serde::Deserializer<'de>,
1568{
1569    let s = String::deserialize(deserializer)?;
1570
1571    time::OffsetDateTime::parse(&s, &time::format_description::well_known::Rfc3339)
1572        .map_err(serde::de::Error::custom)
1573}
1574
1575/// helper to serialize created_on and updated_on in the correct format
1576/// (default time serde implementation seems to use a different format)
1577///
1578/// # Errors
1579///
1580/// This will return an error if the date time can not be formatted as an RFC3339
1581/// date time or the resulting string can not be serialized
1582pub fn serialize_rfc3339<S>(t: &time::OffsetDateTime, serializer: S) -> Result<S::Ok, S::Error>
1583where
1584    S: serde::Serializer,
1585{
1586    let s = t
1587        .format(&time::format_description::well_known::Rfc3339)
1588        .map_err(serde::ser::Error::custom)?;
1589
1590    s.serialize(serializer)
1591}
1592
1593/// helper to parse created_on and updated_on in the correct format
1594/// (default time serde implementation seems to use a different format)
1595///
1596/// # Errors
1597///
1598/// This will return an error if the underlying string can not be deserialized
1599/// or it can not be parsed as an RFC3339 date and time
1600pub fn deserialize_optional_rfc3339<'de, D>(
1601    deserializer: D,
1602) -> Result<Option<time::OffsetDateTime>, D::Error>
1603where
1604    D: serde::Deserializer<'de>,
1605{
1606    let s = <Option<String> as Deserialize<'de>>::deserialize(deserializer)?;
1607
1608    if let Some(s) = s {
1609        Ok(Some(
1610            time::OffsetDateTime::parse(&s, &time::format_description::well_known::Rfc3339)
1611                .map_err(serde::de::Error::custom)?,
1612        ))
1613    } else {
1614        Ok(None)
1615    }
1616}
1617
1618/// helper to serialize created_on and updated_on in the correct format
1619/// (default time serde implementation seems to use a different format)
1620///
1621/// # Errors
1622///
1623/// This will return an error if the parameter can not be formatted as RFC3339
1624/// or the resulting string can not be serialized
1625pub fn serialize_optional_rfc3339<S>(
1626    t: &Option<time::OffsetDateTime>,
1627    serializer: S,
1628) -> Result<S::Ok, S::Error>
1629where
1630    S: serde::Serializer,
1631{
1632    if let Some(t) = t {
1633        let s = t
1634            .format(&time::format_description::well_known::Rfc3339)
1635            .map_err(serde::ser::Error::custom)?;
1636
1637        s.serialize(serializer)
1638    } else {
1639        let n: Option<String> = None;
1640        n.serialize(serializer)
1641    }
1642}
1643
1644/// represents an Iterator over all result pages
1645#[derive(Debug)]
1646pub struct AllPages<'i, E, R> {
1647    /// the redmine object to fetch data from
1648    redmine: &'i Redmine,
1649    /// the endpoint to request data from
1650    endpoint: &'i E,
1651    /// the offset to fetch next
1652    offset: u64,
1653    /// the limit for each fetch
1654    limit: u64,
1655    /// the cached total count value from the last request
1656    total_count: Option<u64>,
1657    /// the number of elements already yielded
1658    yielded: u64,
1659    /// the cached values from the last fetch that have not been
1660    /// consumed yet, in reverse order to allow pop to remove them
1661    reversed_rest: Vec<R>,
1662}
1663
1664impl<'i, E, R> AllPages<'i, E, R> {
1665    /// create a new AllPages Iterator
1666    pub const fn new(redmine: &'i Redmine, endpoint: &'i E) -> Self {
1667        Self {
1668            redmine,
1669            endpoint,
1670            offset: 0,
1671            limit: 100,
1672            total_count: None,
1673            yielded: 0,
1674            reversed_rest: Vec::new(),
1675        }
1676    }
1677}
1678
1679impl<E, R> Iterator for AllPages<'_, E, R>
1680where
1681    E: Endpoint + ReturnsJsonResponse + Pageable,
1682    R: DeserializeOwned + std::fmt::Debug,
1683{
1684    type Item = Result<R, crate::Error>;
1685
1686    #[expect(
1687        clippy::arithmetic_side_effects,
1688        reason = "u64 pagination counters; overflow requires impossibly many results"
1689    )]
1690    fn next(&mut self) -> Option<Self::Item> {
1691        if let Some(next) = self.reversed_rest.pop() {
1692            self.yielded += 1;
1693            return Some(Ok(next));
1694        }
1695        if let Some(total_count) = self.total_count
1696            && self.offset > total_count
1697        {
1698            return None;
1699        }
1700        match self
1701            .redmine
1702            .json_response_body_page(self.endpoint, self.offset, self.limit)
1703        {
1704            Err(e) => Some(Err(e)),
1705            Ok(ResponsePage {
1706                values,
1707                total_count,
1708                offset,
1709                limit,
1710            }) => {
1711                self.total_count = Some(total_count);
1712                self.offset = offset + limit;
1713                self.reversed_rest = values;
1714                self.reversed_rest.reverse();
1715                if let Some(next) = self.reversed_rest.pop() {
1716                    self.yielded += 1;
1717                    return Some(Ok(next));
1718                }
1719                None
1720            }
1721        }
1722    }
1723
1724    #[expect(
1725        clippy::arithmetic_side_effects,
1726        clippy::cast_possible_truncation,
1727        clippy::as_conversions,
1728        reason = "remaining = total_count - yielded; size_hint upper bound is best-effort"
1729    )]
1730    fn size_hint(&self) -> (usize, Option<usize>) {
1731        if let Some(total_count) = self.total_count {
1732            (
1733                self.reversed_rest.len(),
1734                Some((total_count - self.yielded) as usize),
1735            )
1736        } else {
1737            (0, None)
1738        }
1739    }
1740}
1741
1742/// represents an async Stream over all result pages
1743#[pin_project::pin_project]
1744pub struct AllPagesAsync<E, R> {
1745    /// the inner future while we are fetching new data
1746    #[expect(
1747        clippy::type_complexity,
1748        reason = "boxed pinned future signature is intrinsically nested"
1749    )]
1750    #[pin]
1751    inner: Option<
1752        std::pin::Pin<Box<dyn futures::Future<Output = Result<ResponsePage<R>, crate::Error>>>>,
1753    >,
1754    /// the redmine object to fetch data from
1755    redmine: std::sync::Arc<RedmineAsync>,
1756    /// the endpoint to request data from
1757    endpoint: std::sync::Arc<E>,
1758    /// the offset to fetch next
1759    offset: u64,
1760    /// the limit for each fetch
1761    limit: u64,
1762    /// the cached total count value from the last request
1763    total_count: Option<u64>,
1764    /// the number of elements already yielded
1765    yielded: u64,
1766    /// the cached values from the last fetch that have not been
1767    /// consumed yet, in reverse order to allow pop to remove them
1768    reversed_rest: Vec<R>,
1769}
1770
1771impl<E, R> std::fmt::Debug for AllPagesAsync<E, R>
1772where
1773    R: std::fmt::Debug,
1774{
1775    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1776        f.debug_struct("AllPagesAsync")
1777            .field("redmine", &self.redmine)
1778            .field("offset", &self.offset)
1779            .field("limit", &self.limit)
1780            .field("total_count", &self.total_count)
1781            .field("yielded", &self.yielded)
1782            .field("reversed_rest", &self.reversed_rest)
1783            .finish()
1784    }
1785}
1786
1787impl<E, R> AllPagesAsync<E, R> {
1788    /// create a new AllPagesAsync Stream
1789    pub fn new(redmine: std::sync::Arc<RedmineAsync>, endpoint: std::sync::Arc<E>) -> Self {
1790        Self {
1791            inner: None,
1792            redmine,
1793            endpoint,
1794            offset: 0,
1795            limit: 100,
1796            total_count: None,
1797            yielded: 0,
1798            reversed_rest: Vec::new(),
1799        }
1800    }
1801}
1802
1803impl<E, R> futures::stream::Stream for AllPagesAsync<E, R>
1804where
1805    E: Endpoint + ReturnsJsonResponse + Pageable + 'static,
1806    R: DeserializeOwned + std::fmt::Debug + 'static,
1807{
1808    type Item = Result<R, crate::Error>;
1809
1810    #[expect(
1811        clippy::arithmetic_side_effects,
1812        clippy::clone_on_ref_ptr,
1813        clippy::renamed_function_params,
1814        reason = "u64 pagination counters; Arc clones are intentional; ctx parameter name is preserved for clarity"
1815    )]
1816    fn poll_next(
1817        mut self: std::pin::Pin<&mut Self>,
1818        ctx: &mut std::task::Context<'_>,
1819    ) -> std::task::Poll<Option<Self::Item>> {
1820        if let Some(mut inner) = self.inner.take() {
1821            match inner.as_mut().poll(ctx) {
1822                std::task::Poll::Pending => {
1823                    self.inner = Some(inner);
1824                    std::task::Poll::Pending
1825                }
1826                std::task::Poll::Ready(Err(e)) => std::task::Poll::Ready(Some(Err(e))),
1827                std::task::Poll::Ready(Ok(ResponsePage {
1828                    values,
1829                    total_count,
1830                    offset,
1831                    limit,
1832                })) => {
1833                    self.total_count = Some(total_count);
1834                    self.offset = offset + limit;
1835                    self.reversed_rest = values;
1836                    self.reversed_rest.reverse();
1837                    if let Some(next) = self.reversed_rest.pop() {
1838                        self.yielded += 1;
1839                        return std::task::Poll::Ready(Some(Ok(next)));
1840                    }
1841                    std::task::Poll::Ready(None)
1842                }
1843            }
1844        } else {
1845            if let Some(next) = self.reversed_rest.pop() {
1846                self.yielded += 1;
1847                return std::task::Poll::Ready(Some(Ok(next)));
1848            }
1849            if let Some(total_count) = self.total_count
1850                && self.offset > total_count
1851            {
1852                return std::task::Poll::Ready(None);
1853            }
1854            self.inner = Some(
1855                self.redmine
1856                    .clone()
1857                    .json_response_body_page(self.endpoint.clone(), self.offset, self.limit)
1858                    .boxed_local(),
1859            );
1860            self.poll_next(ctx)
1861        }
1862    }
1863
1864    #[expect(
1865        clippy::arithmetic_side_effects,
1866        clippy::cast_possible_truncation,
1867        clippy::as_conversions,
1868        reason = "remaining = total_count - yielded; size_hint upper bound is best-effort"
1869    )]
1870    fn size_hint(&self) -> (usize, Option<usize>) {
1871        if let Some(total_count) = self.total_count {
1872            (
1873                self.reversed_rest.len(),
1874                Some((total_count - self.yielded) as usize),
1875            )
1876        } else {
1877            (0, None)
1878        }
1879    }
1880}
1881
1882/// trait to allow both `&E` and `std::sync::Arc<E>` as parameters for endpoints
1883/// we can not just use Into because that tries to treat &Endpoint as the value E
1884/// and screws up our other trait bounds
1885///
1886/// if we just used Arc the users would have to change all old call sites
1887pub trait EndpointParameter<E> {
1888    /// convert the endpoint parameter into an Arc
1889    fn into_arc(self) -> std::sync::Arc<E>;
1890}
1891
1892impl<E> EndpointParameter<E> for &E
1893where
1894    E: Clone,
1895{
1896    fn into_arc(self) -> std::sync::Arc<E> {
1897        std::sync::Arc::new(self.to_owned())
1898    }
1899}
1900
1901impl<E> EndpointParameter<E> for std::sync::Arc<E> {
1902    fn into_arc(self) -> Self {
1903        self
1904    }
1905}