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