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 const 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 attached when an error occurs.
120 ///
121 /// Note: if you pass an already-formatted `String` (e.g. `format!(...)`),
122 /// that formatting still happens eagerly before calling `.with_context(...)`.
123 ///
124 /// # Arguments
125 ///
126 /// * `context` - Any type implementing `IntoErrorContext`
127 ///
128 /// # Examples
129 ///
130 /// ```rust
131 /// use error_rail::async_ext::AsyncErrorPipeline;
132 ///
133 /// let pipeline = AsyncErrorPipeline::new(async { Err::<(), _>("error") })
134 /// .with_context("operation context");
135 /// ```
136 #[inline]
137 pub fn with_context<C>(
138 self,
139 context: C,
140 ) -> AsyncErrorPipeline<impl Future<Output = Result<T, ComposableError<E>>>>
141 where
142 C: IntoErrorContext,
143 {
144 AsyncErrorPipeline { future: self.future.ctx(context) }
145 }
146
147 /// Marks the error as transient or permanent based on a closure.
148 ///
149 /// This allows for flexible retry control without implementing the [`crate::traits::TransientError`]
150 /// trait for the error type.
151 ///
152 /// # Arguments
153 ///
154 /// * `classifier` - A closure that returns `true` if the error should be treated as transient
155 ///
156 /// # Examples
157 ///
158 /// ```rust
159 /// use error_rail::prelude_async::*;
160 /// use error_rail::types::MarkedError;
161 ///
162 /// async fn example() -> Result<(), MarkedError<String, impl Fn(&String) -> bool>> {
163 /// AsyncErrorPipeline::new(async { Err("error".to_string()) })
164 /// .mark_transient_if(|e: &String| e.contains("error"))
165 /// .finish()
166 /// .await
167 /// }
168 /// ```
169 #[inline]
170 pub fn mark_transient_if<F>(
171 self,
172 classifier: F,
173 ) -> AsyncErrorPipeline<impl Future<Output = Result<T, MarkedError<E, F>>>>
174 where
175 F: Fn(&E) -> bool,
176 {
177 let fut = self.future;
178 AsyncErrorPipeline {
179 future: async move { fut.await.map_err(|e| MarkedError { inner: e, classifier }) },
180 }
181 }
182
183 /// Adds a lazily-evaluated context using a closure.
184 ///
185 /// The closure is only called when an error occurs, avoiding
186 /// any computation on the success path.
187 ///
188 /// # Arguments
189 ///
190 /// * `f` - A closure that produces the error context
191 ///
192 /// # Examples
193 ///
194 /// ```rust,no_run
195 /// use error_rail::async_ext::AsyncErrorPipeline;
196 ///
197 /// #[derive(Debug)]
198 /// struct User;
199 ///
200 /// #[derive(Debug)]
201 /// struct ApiError;
202 ///
203 /// async fn fetch_user(_id: u64) -> Result<User, ApiError> {
204 /// Err(ApiError)
205 /// }
206 ///
207 /// let id = 42u64;
208 /// let _pipeline = AsyncErrorPipeline::new(fetch_user(id))
209 /// .with_context_fn(|| format!("user_id: {}", id));
210 /// ```
211 #[inline]
212 pub fn with_context_fn<F, C>(
213 self,
214 f: F,
215 ) -> AsyncErrorPipeline<impl Future<Output = Result<T, ComposableError<E>>>>
216 where
217 F: FnOnce() -> C,
218 C: IntoErrorContext,
219 {
220 AsyncErrorPipeline { future: self.future.with_ctx(f) }
221 }
222
223 /// Transforms the success value using a mapping function.
224 #[inline]
225 pub fn map<U, F>(self, f: F) -> AsyncErrorPipeline<impl Future<Output = Result<U, E>>>
226 where
227 F: FnOnce(T) -> U,
228 {
229 let fut = self.future;
230 AsyncErrorPipeline { future: async move { fut.await.map(f) } }
231 }
232
233 /// Transforms the pipeline using a fallible function.
234 ///
235 /// This is an alias for `and_then`.
236 #[inline]
237 pub fn step<U, F>(self, f: F) -> AsyncErrorPipeline<impl Future<Output = Result<U, E>>>
238 where
239 F: FnOnce(T) -> Result<U, E>,
240 {
241 let fut = self.future;
242 AsyncErrorPipeline { future: async move { fut.await.and_then(f) } }
243 }
244
245 /// Attempts to recover from an error using a fallback value.
246 #[inline]
247 pub fn fallback(self, value: T) -> AsyncErrorPipeline<impl Future<Output = Result<T, E>>> {
248 let fut = self.future;
249 AsyncErrorPipeline { future: async move { fut.await.or(Ok(value)) } }
250 }
251
252 /// Attempts to recover from an error using a safe recovery function.
253 #[inline]
254 pub fn recover_safe<F>(self, f: F) -> AsyncErrorPipeline<impl Future<Output = Result<T, E>>>
255 where
256 F: FnOnce(E) -> T,
257 {
258 let fut = self.future;
259 AsyncErrorPipeline { future: async move { Ok(fut.await.unwrap_or_else(f)) } }
260 }
261
262 /// Adds a tag indicating this error was retried.
263 #[inline]
264 pub fn with_retry_context(
265 self,
266 attempt: u32,
267 ) -> AsyncErrorPipeline<impl Future<Output = Result<T, ComposableError<E>>>> {
268 use crate::types::utils::u32_to_cow;
269 let attempt_str = u32_to_cow(attempt);
270
271 AsyncErrorPipeline {
272 future: self
273 .future
274 .with_ctx(move || crate::ErrorContext::metadata("retry_attempt", attempt_str)),
275 }
276 }
277}
278
279impl<Fut, T, E> AsyncErrorPipeline<Fut>
280where
281 Fut: Future<Output = Result<T, ComposableError<E>>>,
282{
283 /// Completes the pipeline and returns a boxed error result.
284 ///
285 /// This is the recommended way to finish a pipeline when returning
286 /// from a function, as it provides minimal stack footprint.
287 ///
288 /// # Examples
289 ///
290 /// ```rust
291 /// use error_rail::prelude_async::*;
292 ///
293 /// async fn example() -> BoxedResult<i32, &'static str> {
294 /// AsyncErrorPipeline::new(async { Err("error") })
295 /// .with_context("operation failed")
296 /// .finish_boxed()
297 /// .await
298 /// }
299 /// ```
300 #[inline]
301 pub async fn finish_boxed(self) -> Result<T, Box<ComposableError<E>>> {
302 self.future.await.map_err(Box::new)
303 }
304
305 /// Maps the error type using a transformation function.
306 ///
307 /// # Arguments
308 ///
309 /// * `f` - A function that transforms `ComposableError<E>` to `ComposableError<E2>`
310 ///
311 /// # Examples
312 ///
313 /// ```rust
314 /// use error_rail::async_ext::AsyncErrorPipeline;
315 ///
316 /// let pipeline = AsyncErrorPipeline::new(async { Err::<(), _>("error") })
317 /// .with_context("context")
318 /// .map_err(|e| e.map_core(|_| "new error"));
319 /// ```
320 #[inline]
321 pub fn map_err<F, E2>(
322 self,
323 f: F,
324 ) -> AsyncErrorPipeline<impl Future<Output = Result<T, ComposableError<E2>>>>
325 where
326 F: FnOnce(ComposableError<E>) -> ComposableError<E2>,
327 {
328 let fut = self.future;
329 AsyncErrorPipeline { future: async move { fut.await.map_err(f) } }
330 }
331}