Skip to main content

ntex_error/
utils.rs

1use std::task::{Context, Poll};
2use std::{borrow::Cow, cell::RefCell, convert, error::Error as StdError, fmt, io, path, pin::Pin};
3
4use ntex_bytes::ByteString;
5
6use crate::{Error, ErrorDiagnostic, ResultType};
7
8/// The retry policy of the error.
9pub trait Retryable {
10    /// Returns `true` if the failed operation can be retried.
11    fn is_retryable(&self) -> bool;
12}
13
14impl<E: Retryable> Retryable for Error<E> {
15    fn is_retryable(&self) -> bool {
16        self.inner.error.is_retryable()
17    }
18}
19
20impl<T, E> Retryable for Result<T, E>
21where
22    E: Retryable,
23{
24    fn is_retryable(&self) -> bool {
25        match self {
26            Ok(_) => false,
27            Err(err) => err.is_retryable(),
28        }
29    }
30}
31
32/// Helper type holding a result classification signature.
33#[derive(Copy, Clone, Debug, PartialEq, Eq)]
34pub struct ResultSignature(pub &'static str);
35
36impl ResultSignature {
37    /// Creates a new `ResultSignature`.
38    pub fn new(sig: &'static str) -> Self {
39        Self(sig)
40    }
41
42    /// Returns a stable identifier for the result classification.
43    pub fn signature(self) -> &'static str {
44        self.0
45    }
46}
47
48impl<'a, E: ErrorDiagnostic> From<&'a E> for ResultSignature {
49    fn from(err: &'a E) -> Self {
50        ResultSignature::new(err.signature())
51    }
52}
53
54impl<'a, T, E: ErrorDiagnostic> From<&'a Result<T, E>> for ResultSignature {
55    fn from(result: &'a Result<T, E>) -> Self {
56        match result {
57            Ok(_) => ResultSignature(ResultType::Success.as_str()),
58            Err(err) => ResultSignature(err.signature()),
59        }
60    }
61}
62
63impl ErrorDiagnostic for convert::Infallible {
64    fn signature(&self) -> &'static str {
65        unreachable!()
66    }
67}
68
69impl ErrorDiagnostic for io::Error {
70    fn signature(&self) -> &'static str {
71        match self.kind() {
72            io::ErrorKind::InvalidData => "std-io-InvalidData",
73            io::ErrorKind::InvalidInput => "std-io-InvalidInput",
74            io::ErrorKind::Unsupported => "std-io-Unsupported",
75            io::ErrorKind::UnexpectedEof => "std-io-UnexpectedEof",
76            io::ErrorKind::BrokenPipe => "std-io-BrokenPipe",
77            io::ErrorKind::ConnectionReset => "std-io-ConnectionReset",
78            io::ErrorKind::ConnectionAborted => "std-io-ConnectionAborted",
79            io::ErrorKind::NotConnected => "std-io-NotConnected",
80            io::ErrorKind::TimedOut => "std-io-TimedOut",
81            _ => "std-io-Error",
82        }
83    }
84}
85
86/// Marker diagnostic type representing a successful result.
87///
88/// Its signature is [`ResultType::Success`].
89#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
90pub struct Success;
91
92impl StdError for Success {}
93
94impl ErrorDiagnostic for Success {
95    fn signature(&self) -> &'static str {
96        ResultType::Success.as_str()
97    }
98}
99
100impl fmt::Display for Success {
101    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
102        write!(f, "Success")
103    }
104}
105
106/// Executes a future and ensures an error service is set.
107///
108/// If the error does not already have a service, the provided service is assigned.
109pub fn with_service<F, T, E>(svc: &'static str, fut: F) -> impl Future<Output = F::Output>
110where
111    F: Future<Output = Result<T, Error<E>>>,
112    E: ErrorDiagnostic + Clone,
113{
114    WithService { fut, svc }
115}
116
117pin_project_lite::pin_project! {
118    struct WithService<F> {
119        #[pin]
120        fut: F,
121        svc: &'static str,
122    }
123}
124
125impl<F, T, E> Future for WithService<F>
126where
127    F: Future<Output = Result<T, Error<E>>>,
128    E: ErrorDiagnostic + Clone,
129{
130    type Output = F::Output;
131
132    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
133        let this = self.project();
134        let svc = *this.svc;
135        this.fut.poll(cx).map_err(|err| {
136            if err.service().is_none() {
137                err.with_service(svc)
138            } else {
139                err
140            }
141        })
142    }
143}
144
145/// Generates a Rust module path from the given source file path.
146///
147/// The path is resolved relative to the crate directory (the parent of `src`),
148/// e.g. `/p/my-crate/src/net/io.rs` becomes `my_crate::net::io`.
149pub fn module_path(file_path: &str) -> ByteString {
150    module_path_ext("", "", "::", "", file_path)
151}
152
153/// Generates a Rust module path from the given source file path,
154/// prepending `prefix`.
155pub fn module_path_prefix(prefix: &'static str, file_path: &str) -> ByteString {
156    module_path_ext(prefix, "", "::", "", file_path)
157}
158
159/// Generates a `/`-separated file path relative to the crate's parent directory.
160///
161/// e.g. `/p/my-crate/src/net/io.rs` becomes `my-crate/src/net/io.rs`.
162pub fn module_path_fs(file_path: &str) -> ByteString {
163    module_path_ext("", "/src", "/", ".rs", file_path)
164}
165
166fn module_path_ext(
167    prefix: &'static str,
168    mod_sep: &'static str,
169    sep: &'static str,
170    suffix: &'static str,
171    file_path: &str,
172) -> ByteString {
173    type HashMap<K, V> = std::collections::HashMap<K, V, foldhash::fast::RandomState>;
174    type Key = (&'static str, &'static str, &'static str, &'static str);
175    thread_local! {
176        static CACHE: RefCell<HashMap<Key, HashMap<String, ByteString>>> = RefCell::new(HashMap::default());
177    }
178
179    let key = (prefix, mod_sep, sep, suffix);
180    let cached = CACHE.with(|cache| {
181        if let Some(c) = cache.borrow().get(&key) {
182            c.get(file_path).cloned()
183        } else {
184            None
185        }
186    });
187
188    if let Some(cached) = cached {
189        cached
190    } else {
191        let normalized_file_path = normalize_file_path(file_path);
192        let (module_name, module_root) = module_root_from_file(mod_sep, &normalized_file_path);
193        let module = module_path_from_file_with_root(
194            prefix,
195            sep,
196            &normalized_file_path,
197            &module_name,
198            &module_root,
199            suffix,
200        );
201
202        let _ = CACHE.with(|cache| {
203            cache
204                .borrow_mut()
205                .entry(key)
206                .or_default()
207                .insert(file_path.to_string(), module.clone())
208        });
209        module
210    }
211}
212
213fn normalize_file_path(file_path: &str) -> String {
214    let path = path::Path::new(file_path);
215    if path.is_absolute() {
216        return path.to_string_lossy().into_owned();
217    }
218
219    match std::env::current_dir() {
220        Ok(cwd) => cwd.join(path).to_string_lossy().into_owned(),
221        Err(_) => file_path.to_string(),
222    }
223}
224
225fn module_root_from_file(mod_sep: &str, file_path: &str) -> (String, path::PathBuf) {
226    let normalized = file_path.replace('\\', "/");
227    if let Some((root, _)) = normalized.rsplit_once("/src/") {
228        let mut root = path::PathBuf::from(root);
229        let mod_name = root
230            .file_name()
231            .map_or(Cow::Borrowed("crate"), |s| s.to_string_lossy());
232        let mod_name = if mod_sep.is_empty() {
233            mod_name.replace('-', "_")
234        } else {
235            mod_name.to_string()
236        };
237        root.push("src");
238        return (format!("{mod_name}{mod_sep}"), root);
239    }
240
241    let path = path::Path::new(file_path)
242        .parent()
243        .map_or_else(|| path::PathBuf::from("."), path::Path::to_path_buf);
244
245    let m = path
246        .parent()
247        .and_then(|p| p.file_name())
248        .map_or_else(|| Cow::Borrowed("crate"), |p| p.to_string_lossy());
249
250    (format!("{m}{mod_sep}"), path)
251}
252
253fn module_path_from_file(sep: &str, file_path: &str) -> String {
254    let normalized = file_path.replace('\\', "/");
255    let relative = normalized
256        .split_once("/src/")
257        .map_or(normalized.as_str(), |(_, tail)| tail);
258
259    if relative == "lib.rs" || relative == "main.rs" {
260        return relative.to_string();
261    }
262
263    let without_ext = relative.strip_suffix(".rs").unwrap_or(relative);
264    if without_ext.ends_with("/mod") {
265        let parent = without_ext.strip_suffix("/mod").unwrap_or(without_ext);
266        let parent = parent.trim_matches('/');
267        return parent.replace('/', sep);
268    }
269
270    let module = without_ext.trim_matches('/').replace('/', sep);
271    if module.is_empty() {
272        "crate".to_string()
273    } else {
274        module
275    }
276}
277
278fn module_path_from_file_with_root(
279    prefix: &str,
280    sep: &str,
281    file_path: &str,
282    module_name: &str,
283    module_root: &path::Path,
284    suffix: &str,
285) -> ByteString {
286    let normalized = file_path.replace('\\', "/");
287    let module_root_norm = module_root.to_string_lossy().replace('\\', "/");
288    // filesystem roots (`/`, `C:/`) already end with a separator
289    let module_root_norm = module_root_norm.trim_end_matches('/');
290
291    let Some(relative) = normalized.strip_prefix(&(module_root_norm.to_string() + "/")) else {
292        return format!(
293            "{prefix}{module_name}{sep}{}{suffix}",
294            module_path_from_file(sep, file_path)
295        )
296        .into();
297    };
298    if relative == "lib.rs" || relative == "main.rs" {
299        return ByteString::from(format!("{prefix}{module_name}{sep}{relative}"));
300    }
301
302    let without_ext = relative.strip_suffix(".rs").unwrap_or(relative);
303    if without_ext.ends_with("/mod") {
304        let parent = without_ext.strip_suffix("/mod").unwrap_or(without_ext);
305        let parent = parent.trim_matches('/');
306        return format!(
307            "{prefix}{module_name}{sep}{}{sep}mod{suffix}",
308            parent.replace('/', sep)
309        )
310        .into();
311    }
312
313    let module = without_ext.trim_matches('/').replace('/', sep);
314    if module.is_empty() {
315        ByteString::from(format!("{prefix}{module_name}{suffix}"))
316    } else {
317        format!("{prefix}{module_name}{sep}{module}{suffix}").into()
318    }
319}
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324
325    /// STATEMENT: `module_path` maps a source file path to a Rust module path, and
326    /// `module_path_fs` to a crate-relative file path, on Unix and Windows separators.
327    ///
328    /// HOW:
329    /// - Convert `lib.rs`, `main.rs`, `mod.rs`, nested and degenerate paths; expect the
330    ///   documented module names, including the `crate` fallback.
331    /// - Convert a Windows path with backslashes; expect the same module path.
332    /// - Check `module_path_prefix` prepends the prefix and `module_path_fs` keeps the crate
333    ///   directory name.
334    #[test]
335    fn module_paths() {
336        assert_eq!(module_path("/p/my-crate/src/lib.rs"), "my_crate::lib.rs");
337        assert_eq!(module_path("/p/my-crate/src/main.rs"), "my_crate::main.rs");
338        assert_eq!(
339            module_path("/p/my-crate/src/net/mod.rs"),
340            "my_crate::net::mod"
341        );
342        assert_eq!(
343            module_path("/p/my-crate/src/net/io.rs"),
344            "my_crate::net::io"
345        );
346        assert_eq!(module_path("/p/my-crate/src/.rs"), "my_crate");
347        assert_eq!(module_path("/p/my-crate/src/a/src/b.rs"), "a::b");
348        assert_eq!(module_path("/a/b/c.rs"), "a::c");
349        assert_eq!(module_path("/c.rs"), "crate::c");
350        assert_eq!(module_path("src/lib.rs"), "ntex_error::lib.rs");
351        assert_eq!(
352            module_path("C:\\p\\my-crate\\src\\net\\io.rs"),
353            "my_crate::net::io"
354        );
355        // cached
356        assert_eq!(
357            module_path("/p/my-crate/src/net/io.rs"),
358            "my_crate::net::io"
359        );
360
361        assert_eq!(
362            module_path_prefix("pfx::", "/p/my-crate/src/net/io.rs"),
363            "pfx::my_crate::net::io"
364        );
365        assert_eq!(
366            module_path_fs("/p/my-crate/src/lib.rs"),
367            "my-crate/src/lib.rs"
368        );
369        assert_eq!(
370            module_path_fs("/p/my-crate/src/net/mod.rs"),
371            "my-crate/src/net/mod.rs"
372        );
373        assert_eq!(
374            module_path_fs("/p/my-crate/src/net/io.rs"),
375            "my-crate/src/net/io.rs"
376        );
377        assert_eq!(module_path_fs("/p/my-crate/src/.rs"), "my-crate/src.rs");
378    }
379
380    /// STATEMENT: The module-path cache keeps separate entries per output format.
381    ///
382    /// HOW:
383    /// - Resolve one path with `module_path`, then `module_path_fs`, then `module_path` again.
384    /// - Expect each call to return its own format, not the cached result of the other.
385    #[test]
386    fn module_path_cache_per_format() {
387        // the same file path must not share cache entries between formats
388        let p = "/p/other-crate/src/x/y.rs";
389        assert_eq!(module_path(p), "other_crate::x::y");
390        assert_eq!(module_path_fs(p), "other-crate/src/x/y.rs");
391        assert_eq!(module_path(p), "other_crate::x::y");
392    }
393
394    /// STATEMENT: `module_path_from_file` strips the `src` prefix, drops `mod.rs` and the
395    /// `.rs` extension, and joins segments with the given separator.
396    ///
397    /// HOW:
398    /// - Convert `lib.rs`, `main.rs`, `net/mod.rs`, `net/io.rs` and `.rs` with `::`.
399    /// - Convert a path without `src` using `/`.
400    /// - Expect the listed module paths, with `crate` for an empty name.
401    #[test]
402    fn module_path_from_file_variants() {
403        assert_eq!(module_path_from_file("::", "/x/src/lib.rs"), "lib.rs");
404        assert_eq!(module_path_from_file("::", "/x/src/main.rs"), "main.rs");
405        assert_eq!(module_path_from_file("::", "/x/src/net/mod.rs"), "net");
406        assert_eq!(module_path_from_file("::", "/x/src/net/io.rs"), "net::io");
407        assert_eq!(module_path_from_file("::", "/x/src/.rs"), "crate");
408        assert_eq!(module_path_from_file("/", "a/b.rs"), "a/b");
409    }
410}