1pub 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#[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 client: reqwest::blocking::Client,
74 redmine_url: Url,
76 #[debug(skip)]
78 api_key: String,
79 impersonate_user_id: Option<u64>,
81}
82
83#[derive(derive_more::Debug)]
85pub struct RedmineAsync {
86 client: reqwest::Client,
88 redmine_url: Url,
90 #[debug(skip)]
92 api_key: String,
93 impersonate_user_id: Option<u64>,
95}
96
97fn 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#[derive(Debug, Clone, serde::Deserialize)]
109struct EnvOptions {
110 redmine_api_key: String,
112
113 #[serde(deserialize_with = "parse_url")]
115 redmine_url: url::Url,
116}
117
118#[derive(Debug, Clone)]
121pub struct ResponsePage<T> {
122 pub values: Vec<T>,
124 pub total_count: u64,
126 pub offset: u64,
128 pub limit: u64,
130}
131
132impl Redmine {
133 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 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 pub const fn impersonate_user(&mut self, id: u64) {
173 self.impersonate_user_id = Some(id);
174 }
175
176 #[must_use]
178 pub const fn redmine_url(&self) -> &Url {
179 &self.redmine_url
180 }
181
182 #[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 redmine_url.join(&format!("/issues/{issue_id}")).unwrap()
197 }
198
199 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 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 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 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 #[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 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 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 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 pub const fn impersonate_user(&mut self, id: u64) {
520 self.impersonate_user_id = Some(id);
521 }
522
523 #[must_use]
525 pub const fn redmine_url(&self) -> &Url {
526 &self.redmine_url
527 }
528
529 #[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 redmine_url.join(&format!("/issues/{issue_id}")).unwrap()
544 }
545
546 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 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 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 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 #[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 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
848pub trait ParamValue<'a> {
850 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
878impl<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
893impl<'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#[derive(Debug, Clone)]
958pub enum DateTimeFilterPast {
959 ExactMatch(time::OffsetDateTime),
961 Range(time::OffsetDateTime, time::OffsetDateTime),
963 LessThanOrEqual(time::OffsetDateTime),
965 GreaterThanOrEqual(time::OffsetDateTime),
967 LessThanDaysAgo(u32),
969 MoreThanDaysAgo(u32),
971 WithinPastDays(u32),
973 ExactDaysAgo(u32),
975 Today,
977 Yesterday,
979 ThisWeek,
981 LastWeek,
983 LastTwoWeeks,
985 ThisMonth,
987 LastMonth,
989 ThisYear,
991 Unset,
993 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#[derive(Debug, Clone)]
1093pub enum StringFieldFilter {
1094 ExactMatch(String),
1096 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#[derive(Debug, Clone)]
1115pub struct CustomFieldFilter {
1116 pub id: u64,
1118 pub value: StringFieldFilter,
1120}
1121
1122#[derive(Debug, Clone)]
1124pub enum FloatFilter {
1125 ExactMatch(f64),
1127 Range(f64, f64),
1129 LessThanOrEqual(f64),
1131 GreaterThanOrEqual(f64),
1133 Any,
1135 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#[derive(Debug, Clone)]
1154pub enum IntegerFilter {
1155 ExactMatch(u64),
1157 Range(u64, u64),
1159 LessThanOrEqual(u64),
1161 GreaterThanOrEqual(u64),
1163 Any,
1165 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#[derive(Debug, Clone)]
1184pub enum TrackerFilter {
1185 Any,
1187 None,
1189 TheseTrackers(Vec<u64>),
1191 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#[derive(Debug, Clone)]
1222pub enum ActivityFilter {
1223 Any,
1225 None,
1227 TheseActivities(Vec<u64>),
1229 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#[derive(Debug, Clone)]
1260pub enum VersionFilter {
1261 Any,
1263 None,
1265 TheseVersions(Vec<u64>),
1267 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#[derive(Debug, Clone)]
1298pub enum DateFilter {
1299 ExactMatch(time::Date),
1301 Range(time::Date, time::Date),
1303 LessThanOrEqual(time::Date),
1305 GreaterThanOrEqual(time::Date),
1307 LessThanDaysAgo(u32),
1309 MoreThanDaysAgo(u32),
1311 WithinPastDays(u32),
1313 ExactDaysAgo(u32),
1315 InLessThanDays(u32),
1317 InMoreThanDays(u32),
1319 WithinFutureDays(u32),
1321 InExactDays(u32),
1323 Today,
1325 Yesterday,
1327 Tomorrow,
1329 ThisWeek,
1331 LastWeek,
1333 LastTwoWeeks,
1335 NextWeek,
1337 ThisMonth,
1339 LastMonth,
1341 NextMonth,
1343 ThisYear,
1345 Unset,
1347 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#[derive(Debug, Default, Clone)]
1464pub struct QueryParams<'a> {
1465 params: Vec<(Cow<'a, str>, Cow<'a, str>)>,
1467}
1468
1469impl<'a> QueryParams<'a> {
1470 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 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 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 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
1514pub trait Endpoint {
1516 fn method(&self) -> Method;
1518 fn endpoint(&self) -> Cow<'static, str>;
1520
1521 fn parameters(&self) -> QueryParams<'_> {
1523 QueryParams::default()
1524 }
1525
1526 fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, crate::Error> {
1534 Ok(None)
1535 }
1536}
1537
1538pub trait ReturnsJsonResponse {}
1540
1541#[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#[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 fn response_wrapper_key(&self) -> String;
1556}
1557
1558pub 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
1575pub 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
1593pub 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
1618pub 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#[derive(Debug)]
1646pub struct AllPages<'i, E, R> {
1647 redmine: &'i Redmine,
1649 endpoint: &'i E,
1651 offset: u64,
1653 limit: u64,
1655 total_count: Option<u64>,
1657 yielded: u64,
1659 reversed_rest: Vec<R>,
1662}
1663
1664impl<'i, E, R> AllPages<'i, E, R> {
1665 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#[pin_project::pin_project]
1744pub struct AllPagesAsync<E, R> {
1745 #[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 redmine: std::sync::Arc<RedmineAsync>,
1756 endpoint: std::sync::Arc<E>,
1758 offset: u64,
1760 limit: u64,
1762 total_count: Option<u64>,
1764 yielded: u64,
1766 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 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
1882pub trait EndpointParameter<E> {
1888 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}