error_rail/async_ext/pipeline.rs
1//! Async error pipeline for chainable error handling.
2//!
3//! Provides `AsyncErrorPipeline`, the async counterpart to [`ErrorPipeline`](crate::ErrorPipeline).
4
5use core::future::Future;
6
7use crate::traits::IntoErrorContext;
8use crate::types::alloc_type::Box;
9use crate::types::{ComposableError, MarkedError};
10
11use super::future_ext::FutureResultExt;
12
13/// Async error pipeline for chainable error handling.
14///
15/// This is the async counterpart to [`ErrorPipeline`](crate::ErrorPipeline),
16/// providing fluent, chainable error context accumulation for async operations.
17///
18/// # Examples
19///
20/// ## Basic Usage
21///
22/// ```rust,no_run
23/// use error_rail::prelude_async::*;
24///
25/// #[derive(Debug)]
26/// struct Data;
27///
28/// #[derive(Debug)]
29/// struct ApiError;
30///
31/// async fn fetch_data(_id: u64) -> Result<Data, ApiError> {
32/// Err(ApiError)
33/// }
34///
35/// async fn example(id: u64) -> BoxedResult<Data, ApiError> {
36/// AsyncErrorPipeline::new(fetch_data(id))
37/// .with_context("fetching data")
38/// .finish_boxed()
39/// .await
40/// }
41/// ```
42///
43/// ## With Multiple Contexts
44///
45/// ```rust,no_run
46/// use error_rail::prelude_async::*;
47///
48/// #[derive(Debug)]
49/// struct Order;
50///
51/// #[derive(Debug)]
52/// struct OrderError;
53///
54/// async fn load_order(_order_id: u64) -> Result<Order, OrderError> {
55/// Err(OrderError)
56/// }
57///
58/// async fn process_order(order_id: u64) -> BoxedResult<Order, OrderError> {
59/// AsyncErrorPipeline::new(load_order(order_id))
60/// .with_context(group!(
61/// message("loading order"),
62/// metadata("order_id", format!("{}", order_id))
63/// ))
64/// .finish_boxed()
65/// .await
66/// }
67/// ```
68pub struct AsyncErrorPipeline<Fut> {
69 future: Fut,
70}
71
72impl<Fut> AsyncErrorPipeline<Fut> {
73 /// Creates a new async error pipeline from a future.
74 ///
75 /// # Arguments
76 ///
77 /// * `future` - A future that returns a `Result<T, E>`
78 ///
79 /// # Examples
80 ///
81 /// ```rust
82 /// use error_rail::async_ext::AsyncErrorPipeline;
83 ///
84 /// let pipeline = AsyncErrorPipeline::new(async { Ok::<_, &str>(42) });
85 /// ```
86 #[inline]
87 pub fn new(future: Fut) -> Self {
88 Self { future }
89 }
90
91 /// Completes the pipeline and returns the inner future.
92 ///
93 /// This method consumes the pipeline and returns a future that
94 /// produces the original `Result<T, E>`.
95 ///
96 /// # Examples
97 ///
98 /// ```rust
99 /// use error_rail::async_ext::AsyncErrorPipeline;
100 ///
101 /// async fn example() -> Result<i32, &'static str> {
102 /// AsyncErrorPipeline::new(async { Ok(42) })
103 /// .finish()
104 /// .await
105 /// }
106 /// ```
107 #[inline]
108 pub fn finish(self) -> Fut {
109 self.future
110 }
111}
112
113impl<Fut, T, E> AsyncErrorPipeline<Fut>
114where
115 Fut: Future<Output = Result<T, E>>,
116{
117 /// Adds a context that will be attached to any error.
118 ///
119 /// The context is only evaluated when an error occurs (lazy evaluation).
120 ///
121 /// # Arguments
122 ///
123 /// * `context` - Any type implementing `IntoErrorContext`
124 ///
125 /// # Examples
126 ///
127 /// ```rust
128 /// use error_rail::async_ext::AsyncErrorPipeline;
129 ///
130 /// let pipeline = AsyncErrorPipeline::new(async { Err::<(), _>("error") })
131 /// .with_context("operation context");
132 /// ```
133 #[inline]
134 pub fn with_context<C>(
135 self,
136 context: C,
137 ) -> AsyncErrorPipeline<impl Future<Output = Result<T, ComposableError<E>>>>
138 where
139 C: IntoErrorContext,
140 {
141 AsyncErrorPipeline { future: self.future.ctx(context) }
142 }
143
144 /// Marks the error as transient or permanent based on a closure.
145 ///
146 /// This allows for flexible retry control without implementing the [`crate::traits::TransientError`]
147 /// trait for the error type.
148 ///
149 /// # Arguments
150 ///
151 /// * `classifier` - A closure that returns `true` if the error should be treated as transient
152 ///
153 /// # Examples
154 ///
155 /// ```rust
156 /// use error_rail::prelude_async::*;
157 /// use error_rail::types::MarkedError;
158 ///
159 /// async fn example() -> Result<(), MarkedError<String, impl Fn(&String) -> bool>> {
160 /// AsyncErrorPipeline::new(async { Err("error".to_string()) })
161 /// .mark_transient_if(|e: &String| e.contains("error"))
162 /// .finish()
163 /// .await
164 /// }
165 /// ```
166 #[inline]
167 pub fn mark_transient_if<F>(
168 self,
169 classifier: F,
170 ) -> AsyncErrorPipeline<impl Future<Output = Result<T, MarkedError<E, F>>>>
171 where
172 F: Fn(&E) -> bool + Send + 'static,
173 E: Send + 'static,
174 T: Send + 'static,
175 {
176 AsyncErrorPipeline {
177 future: async move {
178 self.future
179 .await
180 .map_err(|e| MarkedError { inner: e, classifier })
181 },
182 }
183 }
184
185 /// Adds a lazily-evaluated context using a closure.
186 ///
187 /// The closure is only called when an error occurs, avoiding
188 /// any computation on the success path.
189 ///
190 /// # Arguments
191 ///
192 /// * `f` - A closure that produces the error context
193 ///
194 /// # Examples
195 ///
196 /// ```rust,no_run
197 /// use error_rail::async_ext::AsyncErrorPipeline;
198 ///
199 /// #[derive(Debug)]
200 /// struct User;
201 ///
202 /// #[derive(Debug)]
203 /// struct ApiError;
204 ///
205 /// async fn fetch_user(_id: u64) -> Result<User, ApiError> {
206 /// Err(ApiError)
207 /// }
208 ///
209 /// let id = 42u64;
210 /// let _pipeline = AsyncErrorPipeline::new(fetch_user(id))
211 /// .with_context_fn(|| format!("user_id: {}", id));
212 /// ```
213 #[inline]
214 pub fn with_context_fn<F, C>(
215 self,
216 f: F,
217 ) -> AsyncErrorPipeline<impl Future<Output = Result<T, ComposableError<E>>>>
218 where
219 F: FnOnce() -> C,
220 C: IntoErrorContext,
221 {
222 AsyncErrorPipeline { future: self.future.with_ctx(f) }
223 }
224}
225
226impl<Fut, T, E> AsyncErrorPipeline<Fut>
227where
228 Fut: Future<Output = Result<T, ComposableError<E>>>,
229{
230 /// Completes the pipeline and returns a boxed error result.
231 ///
232 /// This is the recommended way to finish a pipeline when returning
233 /// from a function, as it provides minimal stack footprint.
234 ///
235 /// # Examples
236 ///
237 /// ```rust
238 /// use error_rail::prelude_async::*;
239 ///
240 /// async fn example() -> BoxedResult<i32, &'static str> {
241 /// AsyncErrorPipeline::new(async { Err("error") })
242 /// .with_context("operation failed")
243 /// .finish_boxed()
244 /// .await
245 /// }
246 /// ```
247 #[inline]
248 pub async fn finish_boxed(self) -> Result<T, Box<ComposableError<E>>> {
249 self.future.await.map_err(Box::new)
250 }
251
252 /// Maps the error type using a transformation function.
253 ///
254 /// # Arguments
255 ///
256 /// * `f` - A function that transforms `ComposableError<E>` to `ComposableError<E2>`
257 ///
258 /// # Examples
259 ///
260 /// ```rust
261 /// use error_rail::async_ext::AsyncErrorPipeline;
262 ///
263 /// let pipeline = AsyncErrorPipeline::new(async { Err::<(), _>("error") })
264 /// .with_context("context")
265 /// .map_err(|e| e.map_core(|_| "new error"));
266 /// ```
267 #[inline]
268 pub fn map_err<F, E2>(
269 self,
270 f: F,
271 ) -> AsyncErrorPipeline<impl Future<Output = Result<T, ComposableError<E2>>>>
272 where
273 F: FnOnce(ComposableError<E>) -> ComposableError<E2>,
274 {
275 AsyncErrorPipeline { future: async move { self.future.await.map_err(f) } }
276 }
277}