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_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#[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 client: reqwest::blocking::Client,
72 redmine_url: Url,
74 #[debug(skip)]
76 api_key: String,
77 impersonate_user_id: Option<u64>,
79}
80
81#[derive(derive_more::Debug)]
83pub struct RedmineAsync {
84 client: reqwest::Client,
86 redmine_url: Url,
88 #[debug(skip)]
90 api_key: String,
91 impersonate_user_id: Option<u64>,
93}
94
95fn 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#[derive(Debug, Clone, serde::Deserialize)]
107struct EnvOptions {
108 redmine_api_key: String,
110
111 #[serde(deserialize_with = "parse_url")]
113 redmine_url: url::Url,
114}
115
116#[derive(Debug, Clone)]
119pub struct ResponsePage<T> {
120 pub values: Vec<T>,
122 pub total_count: u64,
124 pub offset: u64,
126 pub limit: u64,
128}
129
130impl Redmine {
131 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 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 pub const fn impersonate_user(&mut self, id: u64) {
171 self.impersonate_user_id = Some(id);
172 }
173
174 #[must_use]
176 pub const fn redmine_url(&self) -> &Url {
177 &self.redmine_url
178 }
179
180 #[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 redmine_url.join(&format!("/issues/{issue_id}")).unwrap()
195 }
196
197 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 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 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 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 #[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 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 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 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 pub const fn impersonate_user(&mut self, id: u64) {
518 self.impersonate_user_id = Some(id);
519 }
520
521 #[must_use]
523 pub const fn redmine_url(&self) -> &Url {
524 &self.redmine_url
525 }
526
527 #[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 redmine_url.join(&format!("/issues/{issue_id}")).unwrap()
542 }
543
544 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 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 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 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 #[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 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
846pub trait ParamValue<'a> {
848 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
876impl<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
891impl<'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#[derive(Debug, Clone)]
956pub enum DateTimeFilterPast {
957 ExactMatch(time::OffsetDateTime),
959 Range(time::OffsetDateTime, time::OffsetDateTime),
961 LessThanOrEqual(time::OffsetDateTime),
963 GreaterThanOrEqual(time::OffsetDateTime),
965 LessThanDaysAgo(u32),
967 MoreThanDaysAgo(u32),
969 WithinPastDays(u32),
971 ExactDaysAgo(u32),
973 Today,
975 Yesterday,
977 ThisWeek,
979 LastWeek,
981 LastTwoWeeks,
983 ThisMonth,
985 LastMonth,
987 ThisYear,
989 Unset,
991 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#[derive(Debug, Clone)]
1091pub enum StringFieldFilter {
1092 ExactMatch(String),
1094 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#[derive(Debug, Clone)]
1113pub struct CustomFieldFilter {
1114 pub id: u64,
1116 pub value: StringFieldFilter,
1118}
1119
1120#[derive(Debug, Clone)]
1122pub enum FloatFilter {
1123 ExactMatch(f64),
1125 Range(f64, f64),
1127 LessThanOrEqual(f64),
1129 GreaterThanOrEqual(f64),
1131 Any,
1133 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#[derive(Debug, Clone)]
1152pub enum IntegerFilter {
1153 ExactMatch(u64),
1155 Range(u64, u64),
1157 LessThanOrEqual(u64),
1159 GreaterThanOrEqual(u64),
1161 Any,
1163 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#[derive(Debug, Clone)]
1182pub enum TrackerFilter {
1183 Any,
1185 None,
1187 TheseTrackers(Vec<u64>),
1189 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#[derive(Debug, Clone)]
1220pub enum ActivityFilter {
1221 Any,
1223 None,
1225 TheseActivities(Vec<u64>),
1227 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#[derive(Debug, Clone)]
1258pub enum VersionFilter {
1259 Any,
1261 None,
1263 TheseVersions(Vec<u64>),
1265 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#[derive(Debug, Clone)]
1296pub enum DateFilter {
1297 ExactMatch(time::Date),
1299 Range(time::Date, time::Date),
1301 LessThanOrEqual(time::Date),
1303 GreaterThanOrEqual(time::Date),
1305 LessThanDaysAgo(u32),
1307 MoreThanDaysAgo(u32),
1309 WithinPastDays(u32),
1311 ExactDaysAgo(u32),
1313 InLessThanDays(u32),
1315 InMoreThanDays(u32),
1317 WithinFutureDays(u32),
1319 InExactDays(u32),
1321 Today,
1323 Yesterday,
1325 Tomorrow,
1327 ThisWeek,
1329 LastWeek,
1331 LastTwoWeeks,
1333 NextWeek,
1335 ThisMonth,
1337 LastMonth,
1339 NextMonth,
1341 ThisYear,
1343 Unset,
1345 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#[derive(Debug, Default, Clone)]
1462pub struct QueryParams<'a> {
1463 params: Vec<(Cow<'a, str>, Cow<'a, str>)>,
1465}
1466
1467impl<'a> QueryParams<'a> {
1468 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 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 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 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
1512pub trait Endpoint {
1514 fn method(&self) -> Method;
1516 fn endpoint(&self) -> Cow<'static, str>;
1518
1519 fn parameters(&self) -> QueryParams<'_> {
1521 QueryParams::default()
1522 }
1523
1524 fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, crate::Error> {
1532 Ok(None)
1533 }
1534}
1535
1536pub trait ReturnsJsonResponse {}
1538
1539#[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#[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 fn response_wrapper_key(&self) -> String;
1554}
1555
1556pub 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
1573pub 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
1591pub 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
1616pub 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#[derive(Debug)]
1644pub struct AllPages<'i, E, R> {
1645 redmine: &'i Redmine,
1647 endpoint: &'i E,
1649 offset: u64,
1651 limit: u64,
1653 total_count: Option<u64>,
1655 yielded: u64,
1657 reversed_rest: Vec<R>,
1660}
1661
1662impl<'i, E, R> AllPages<'i, E, R> {
1663 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#[pin_project::pin_project]
1742pub struct AllPagesAsync<E, R> {
1743 #[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 redmine: std::sync::Arc<RedmineAsync>,
1754 endpoint: std::sync::Arc<E>,
1756 offset: u64,
1758 limit: u64,
1760 total_count: Option<u64>,
1762 yielded: u64,
1764 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 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
1880pub trait EndpointParameter<E> {
1886 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}