navree-http 1.6.0

Navree HttpModule: Navree's router and extractors, default Tower layers, JSON errors, controllers and route metadata.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
//! [`AppError`]: every HTTP error, rendered in Navree's JSON error shape.

use std::any::Any;
use std::collections::BTreeMap;
use std::error::Error as StdError;
use std::fmt;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;

use http::header::{CONTENT_TYPE, HeaderName, HeaderValue, RETRY_AFTER, X_CONTENT_TYPE_OPTIONS};
use http::{HeaderMap, StatusCode};
use navree_kernel::__private::is_app_module;
use navree_kernel::{AppContext, BoxError};
use serde::Serialize;

use crate::body::Body;
use crate::codes;
use crate::options::ErrorOptions;
use crate::response::{IntoResponse, Response};

/// The content type of every error response.
pub const ERROR_CONTENT_TYPE: &str = "application/json";

/// The default message of a 500: internals never reach the client.
const INTERNAL_MESSAGE: &str = "Internal server error";

/// The result type of handlers: `Result<T>` fails with an [`AppError`].
pub type Result<T, E = AppError> = std::result::Result<T, E>;

/// An HTTP error. Handlers, extractors, guards and layers return it; it
/// renders in Navree's JSON error shape, as `application/json`:
///
/// ```json
/// {"statusCode": 404, "message": "Deal not found", "error": "Not Found", "code": "not_found"}
/// ```
///
/// - `statusCode` is the HTTP status.
/// - `message` is the [`detail`](AppError::detail) when there is one, else
///   the [`title`](AppError::title) (the reason phrase by default, and
///   `"Internal server error"` for 500s). For validation errors it is every
///   field message, flattened in field order.
/// - `error` is the reason phrase of the status (`"Not Found"`).
/// - `code` is the machine-readable [`code`](AppError::code) a front end
///   maps to a translation key: one of the framework's stable
///   [`codes`](crate::codes), or an app's own
///   ([`with_code`](AppError::with_code)). `http.errors.code = false`
///   leaves it out.
/// - `errors` (validation errors only) maps fields to their messages:
///
/// ```json
/// {"statusCode": 400, "message": ["email must be a valid email address"],
///  "error": "Bad Request", "code": "validation_failed",
///  "errors": {"email": ["email must be a valid email address"]}}
/// ```
///
/// The request id is in the `X-Request-Id` response header, not the body.
/// Any error type converts into a 500 with `?` (its message is logged,
/// never sent); modules turn their own error types into specific statuses
/// with [`ModuleBuilderHttpExt::map_error`](crate::ModuleBuilderHttpExt::map_error).
///
/// `AppError` deliberately does not implement `std::error::Error`, which is
/// what makes the blanket `From<E: Into<BoxError>>` conversion possible.
pub struct AppError {
    /// The HTTP status.
    pub status: StatusCode,
    /// The machine-readable code, rendered as `code` (`"not_found"`,
    /// `"validation_failed"`, `"campaign_already_running"`): lower snake
    /// case, stable across releases, what a front end maps to a translation
    /// key. Empty leaves the member out.
    pub code: String,
    /// The default message, rendered as `message` when there is no
    /// [`detail`](AppError::detail): the reason phrase for statuses built
    /// with [`from_status`](AppError::from_status).
    pub title: String,
    /// A human-readable explanation of this occurrence, rendered as
    /// `message`.
    pub detail: Option<String>,
    /// Field errors (`{"field.path": ["message"]}`), for 400 validation
    /// responses. Boxed, like `headers`, to keep `Result<T, AppError>` small.
    pub errors: Option<Box<BTreeMap<String, Vec<String>>>>,
    /// Extra response headers (`Retry-After`, `WWW-Authenticate`, ...).
    pub headers: Box<HeaderMap>,
    /// The underlying error, logged for 5xx responses and never sent.
    pub source: Option<BoxError>,
}

impl AppError {
    /// An error with an explicit status, code and title (the default
    /// message).
    pub fn new(status: StatusCode, code: impl Into<String>, title: impl Into<String>) -> Self {
        Self {
            status,
            code: code.into(),
            title: title.into(),
            detail: None,
            errors: None,
            headers: Box::default(),
            source: None,
        }
    }

    /// The default error for `status`: its reason phrase as the title, and
    /// a code derived from it.
    pub fn from_status(status: StatusCode) -> Self {
        let reason = status.canonical_reason().unwrap_or("Error");
        match status.as_u16() {
            401 => Self::new(status, codes::UNAUTHENTICATED, reason),
            500 => Self::new(status, codes::INTERNAL_ERROR, INTERNAL_MESSAGE),
            _ => Self::new(status, slug(reason), reason),
        }
    }

    /// 400 with a message.
    pub fn bad_request(detail: impl Into<String>) -> Self {
        Self::from_status(StatusCode::BAD_REQUEST).with_detail(detail)
    }

    /// 400 `invalid_filter` with a message: a list filter that names an
    /// unknown field or has a malformed value.
    pub fn invalid_filter(detail: impl Into<String>) -> Self {
        Self::bad_request(detail).with_code(codes::INVALID_FILTER)
    }

    /// 401: the request is not authenticated.
    pub fn unauthenticated() -> Self {
        Self::from_status(StatusCode::UNAUTHORIZED)
    }

    /// 401 `two_factor_required` `"Two-factor authentication required"`:
    /// the password was right, and the account also needs a second factor.
    pub fn two_factor_required() -> Self {
        Self::unauthenticated()
            .with_code(codes::TWO_FACTOR_REQUIRED)
            .with_detail("Two-factor authentication required")
    }

    /// 403: the user may not do this.
    pub fn forbidden() -> Self {
        Self::from_status(StatusCode::FORBIDDEN)
    }

    /// 404.
    pub fn not_found() -> Self {
        Self::from_status(StatusCode::NOT_FOUND)
    }

    /// 409 with a message.
    pub fn conflict(detail: impl Into<String>) -> Self {
        Self::from_status(StatusCode::CONFLICT).with_detail(detail)
    }

    /// 409 `limit_reached` with a message: a plan or quota limit stops the
    /// change (seats, projects, monthly sends).
    pub fn limit_reached(detail: impl Into<String>) -> Self {
        Self::conflict(detail).with_code(codes::LIMIT_REACHED)
    }

    /// 403 `demo_read_only` `"Demo workspaces are read-only."`: a write in a
    /// workspace that only shows sample data.
    pub fn demo_read_only() -> Self {
        Self::forbidden()
            .with_code(codes::DEMO_READ_ONLY)
            .with_detail("Demo workspaces are read-only.")
    }

    /// 403 `"Invalid CSRF token"`: the CSRF token is missing or does not
    /// match the session.
    pub fn csrf_mismatch() -> Self {
        Self::new(
            StatusCode::FORBIDDEN,
            codes::CSRF_TOKEN_MISMATCH,
            "Invalid CSRF token",
        )
    }

    /// 419 `page_expired` `"Page Expired"`: the page was open too long, or the
    /// session it belongs to changed, so what it sends can't be trusted. The
    /// user reloads and tries again.
    pub fn page_expired() -> Self {
        Self::new(
            StatusCode::from_u16(419).unwrap_or(StatusCode::BAD_REQUEST),
            codes::PAGE_EXPIRED,
            "Page Expired",
        )
    }

    /// 400 with field errors (`{"field.path": ["message"]}`): `message` is
    /// every field message, flattened in field order, and `errors` the map.
    pub fn validation(errors: BTreeMap<String, Vec<String>>) -> Self {
        let mut error = Self::new(
            StatusCode::BAD_REQUEST,
            codes::VALIDATION_FAILED,
            "Bad Request",
        );
        error.errors = Some(Box::new(errors));
        error
    }

    /// 413: the request body is larger than `limit` bytes.
    pub fn payload_too_large(limit: usize) -> Self {
        Self::from_status(StatusCode::PAYLOAD_TOO_LARGE)
            .with_detail(format!("The request body must not exceed {limit} bytes."))
    }

    /// 429 with a `Retry-After` header (whole seconds, at least 1).
    pub fn too_many_requests(retry_after: Duration) -> Self {
        let secs = retry_after_secs(retry_after);
        Self::from_status(StatusCode::TOO_MANY_REQUESTS)
            .with_header(RETRY_AFTER, HeaderValue::from(secs))
    }

    /// 503 with a message.
    pub fn service_unavailable(detail: impl Into<String>) -> Self {
        Self::from_status(StatusCode::SERVICE_UNAVAILABLE).with_detail(detail)
    }

    /// 500 caused by `err`. The client sees `"Internal server error"`; the
    /// error is logged.
    pub fn internal(err: impl Into<BoxError>) -> Self {
        let mut error = Self::from_status(StatusCode::INTERNAL_SERVER_ERROR);
        error.source = Some(err.into());
        error
    }

    /// Sets the message.
    pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
        self.detail = Some(detail.into());
        self
    }

    /// Sets the machine-readable `code` (lower snake case, such as
    /// `campaign_already_running`); the status and the message stay.
    pub fn with_code(mut self, code: impl Into<String>) -> Self {
        self.code = code.into();
        self
    }

    /// Adds a response header.
    pub fn with_header(mut self, name: HeaderName, value: HeaderValue) -> Self {
        self.headers.insert(name, value);
        self
    }

    /// Records the underlying error (logged for 5xx responses, never sent).
    pub fn with_source(mut self, source: impl Into<BoxError>) -> Self {
        self.source = Some(source.into());
        self
    }

    /// The response body:
    /// `{"statusCode", "message", "error", "code"}`, plus `"errors"` for
    /// validation errors.
    pub fn body(&self) -> serde_json::Value {
        self.body_as(ErrorFormat::default())
    }

    /// The response body in `format`.
    pub(crate) fn body_as(&self, format: ErrorFormat) -> serde_json::Value {
        serde_json::to_value(self.wire(format)).unwrap_or_default()
    }

    fn wire(&self, format: ErrorFormat) -> ErrorBody<'_> {
        let errors = self.errors.as_deref();
        let message = match errors {
            Some(errors) if !errors.is_empty() => {
                Message::Many(errors.values().flatten().map(String::as_str).collect())
            }
            _ => Message::One(self.detail.as_deref().unwrap_or(&self.title)),
        };
        let code = (format.code && !self.code.is_empty()).then_some(self.code.as_str());
        ErrorBody {
            status_code: self.status.as_u16(),
            message,
            error: self.status.canonical_reason().unwrap_or(&self.title),
            code,
            errors,
        }
    }

    /// Takes the error out of a response rendered by
    /// [`into_response`](IntoResponse::into_response), so a pipeline other
    /// than the HTTP server's (navree-micro's message handlers) can map and
    /// log it the way the HTTP error layer does. `None` for any other
    /// response, and once the error has been taken.
    pub fn take_from(response: &mut Response) -> Option<AppError> {
        response
            .extensions_mut()
            .remove::<PendingError>()
            .and_then(|pending| pending.take())
    }

    /// Renders the response in `format` (the pipeline sets `X-Request-Id`
    /// itself).
    pub(crate) fn render(&self, format: ErrorFormat) -> Response {
        let body = serde_json::to_vec(&self.wire(format)).unwrap_or_default();
        let mut response = Response::new(Body::from(body));
        *response.status_mut() = self.status;
        let headers = response.headers_mut();
        for (name, value) in self.headers.iter() {
            headers.insert(name, value.clone());
        }
        headers.insert(CONTENT_TYPE, HeaderValue::from_static(ERROR_CONTENT_TYPE));
        headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
        response
    }

    /// An extractor rejection (or a plain-text error response) with
    /// `status` and `text`: a client error shows `text` as its message, a
    /// server error logs it. A 422 (well-formed JSON of the wrong shape) is a
    /// 400, like every other input error.
    pub(crate) fn rejection(status: StatusCode, text: impl Into<String>) -> Self {
        let status = if status == StatusCode::UNPROCESSABLE_ENTITY {
            StatusCode::BAD_REQUEST
        } else {
            status
        };
        let error = Self::from_status(status);
        let text = text.into();
        let text = text.trim();
        if text.is_empty() {
            error
        } else if status.is_client_error() {
            error.with_detail(text)
        } else {
            error.with_source(text.to_owned())
        }
    }

    /// The error and its source chain, for logs.
    pub(crate) fn log_chain(&self) -> String {
        let mut out = format!("{} {}", self.status.as_u16(), self.title);
        if let Some(detail) = &self.detail {
            out.push_str(": ");
            out.push_str(detail);
        }
        let mut next: Option<&(dyn StdError + 'static)> = self
            .source
            .as_deref()
            .map(|e| e as &(dyn StdError + 'static));
        while let Some(error) = next {
            out.push_str(": ");
            out.push_str(&error.to_string());
            next = error.source();
        }
        out
    }
}

/// `Retry-After` in whole seconds, rounded up, at least 1.
pub(crate) fn retry_after_secs(d: Duration) -> u64 {
    let secs = d.as_secs() + u64::from(d.subsec_nanos() > 0);
    secs.max(1)
}

/// `"Payment Required"` → `"payment_required"`.
fn slug(title: &str) -> String {
    title
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() {
                c.to_ascii_lowercase()
            } else {
                '_'
            }
        })
        .collect()
}

/// How error bodies are rendered: `http.errors`, read once at boot.
#[derive(Clone, Copy, Debug)]
pub(crate) struct ErrorFormat {
    /// Render the `code` member (`http.errors.code`).
    pub(crate) code: bool,
}

impl Default for ErrorFormat {
    fn default() -> Self {
        Self { code: true }
    }
}

impl From<&ErrorOptions> for ErrorFormat {
    fn from(options: &ErrorOptions) -> Self {
        Self { code: options.code }
    }
}

/// The wire format, members in their documented order.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct ErrorBody<'a> {
    status_code: u16,
    message: Message<'a>,
    error: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    code: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    errors: Option<&'a BTreeMap<String, Vec<String>>>,
}

/// `message`: one string, or every validation message.
#[derive(Serialize)]
#[serde(untagged)]
enum Message<'a> {
    One(&'a str),
    Many(Vec<&'a str>),
}

impl fmt::Debug for AppError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AppError")
            .field("status", &self.status)
            .field("code", &self.code)
            .field("title", &self.title)
            .field("detail", &self.detail)
            .field("errors", &self.errors)
            .field("source", &self.source)
            .finish_non_exhaustive()
    }
}

impl fmt::Display for AppError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {}", self.status.as_u16(), self.title)?;
        if let Some(detail) = &self.detail {
            write!(f, ": {detail}")?;
        }
        Ok(())
    }
}

/// Any error converts into a 500 (`?` in handlers), like `anyhow`.
impl<E: Into<BoxError>> From<E> for AppError {
    fn from(error: E) -> Self {
        Self::internal(error)
    }
}

/// The rendered response carries the error itself, so the pipeline can map
/// and log it.
impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let mut response = self.render(ErrorFormat::default());
        response
            .extensions_mut()
            .insert(PendingError(Arc::new(Mutex::new(Some(self)))));
        response
    }
}

/// An [`AppError`] travelling in response extensions until the error layer
/// maps, logs and renders it.
#[derive(Clone)]
pub(crate) struct PendingError(Arc<Mutex<Option<AppError>>>);

impl PendingError {
    pub(crate) fn take(&self) -> Option<AppError> {
        self.0.lock().unwrap_or_else(PoisonError::into_inner).take()
    }
}

/// Maps errors of one type (anywhere in an [`AppError`]'s source chain) to a
/// specific [`AppError`]. Contributed with
/// [`ModuleBuilderHttpExt::map_error`](crate::ModuleBuilderHttpExt::map_error).
#[derive(Clone)]
pub struct ErrorMapper {
    type_name: &'static str,
    map: Arc<MapFn>,
    map_any: Arc<MapAnyFn>,
}

type MapFn = dyn Fn(&(dyn StdError + 'static)) -> Option<AppError> + Send + Sync;

type MapAnyFn = dyn Fn(&(dyn Any + Send + Sync)) -> Option<AppError> + Send + Sync;

impl ErrorMapper {
    /// A mapper for errors of type `E`; returning `None` keeps the 500.
    pub fn new<E: StdError + 'static>(f: fn(&E) -> Option<AppError>) -> Self {
        Self {
            type_name: std::any::type_name::<E>(),
            map: Arc::new(move |error| error.downcast_ref::<E>().and_then(f)),
            map_any: Arc::new(move |error| error.downcast_ref::<E>().and_then(f)),
        }
    }

    /// Applies the first matching mapper to `error`'s source chain; `None`
    /// when no mapper matches. The HTTP pipeline does this for every 500
    /// with a source; other protocols (navree-grpc) and code that reports
    /// errors outside a response (MCP tool results, for example) collect the
    /// app's mappers with `ctx.contributions::<ErrorMapper>()` and call it
    /// too.
    ///
    /// ```
    /// use http::StatusCode;
    /// use navree_http::{AppError, ErrorMapper};
    ///
    /// #[derive(Debug)]
    /// struct Missing;
    ///
    /// impl std::fmt::Display for Missing {
    ///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    ///         f.write_str("missing")
    ///     }
    /// }
    ///
    /// impl std::error::Error for Missing {}
    ///
    /// let mappers = [ErrorMapper::new(|_: &Missing| Some(AppError::not_found()))];
    /// let mapped = ErrorMapper::apply(&mappers, &AppError::internal(Missing)).unwrap();
    /// assert_eq!(mapped.status, StatusCode::NOT_FOUND);
    /// assert!(ErrorMapper::apply(&mappers, &AppError::internal("other")).is_none());
    /// ```
    pub fn apply(mappers: &[ErrorMapper], error: &AppError) -> Option<AppError> {
        error
            .source
            .as_deref()
            .and_then(|source| Self::apply_to(mappers, source))
    }

    /// Applies the first matching mapper to `error` and then to its source
    /// chain.
    pub fn apply_to(mappers: &[ErrorMapper], error: &(dyn StdError + 'static)) -> Option<AppError> {
        let mut next = Some(error);
        while let Some(cause) = next {
            for mapper in mappers {
                if let Some(mapped) = (mapper.map)(cause) {
                    return Some(mapped);
                }
            }
            next = cause.source();
        }
        None
    }

    /// Applies the first mapper whose error type `error` is, for errors held
    /// as `dyn Any` (a GraphQL resolver error keeps its source that way).
    pub fn apply_any(mappers: &[ErrorMapper], error: &(dyn Any + Send + Sync)) -> Option<AppError> {
        mappers.iter().find_map(|mapper| (mapper.map_any)(error))
    }
}

impl fmt::Debug for ErrorMapper {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ErrorMapper")
            .field("error_type", &self.type_name)
            .finish()
    }
}

/// The refusal of each [`ErrorMapper`] that a module acting for a plugin the kernel does not
/// find first-party contributes for an error type of another crate, in module order: such a
/// mapper answers that error wherever the app's own code raises it, with the plugin's status
/// and text, and before the app's mapper of the same type when the app imports the plugin. So
/// only a module of the app maps another crate's errors; a plugin maps the error types of its
/// own crate. An app whose mappers all come from modules that act for no plugin reads nothing
/// more. navree-micro, navree-mcp, navree-graphql and navree-grpc, which answer their handlers'
/// errors with the same mappers, refuse them with this in an app with no `HttpModule`.
pub fn mappers_of_plugins(ctx: &AppContext) -> Vec<String> {
    let contributed = ctx.contributions::<ErrorMapper>();
    if contributed
        .iter()
        .all(|mapper| is_app_module(ctx, mapper.module.id))
    {
        return Vec::new();
    }
    let plugins = ctx.plugins().plugins;
    contributed
        .iter()
        .filter_map(|mapper| {
            let module = mapper.module.id;
            let plugin = plugins.iter().find(|plugin| {
                !plugin.first_party && plugin.modules.iter().any(|member| member.id == module)
            })?;
            let error = mapper.value.type_name;
            let outer = error.split_once('<').map_or(error, |(outer, _)| outer);
            let own = outer
                .strip_prefix(plugin.info.crate_name)
                .is_some_and(|rest| rest.starts_with("::"));
            if own {
                return None;
            }
            let reason = navree_kernel::__private::acts_for_reason(ctx, module);
            Some(format!(
                "plugin `{}` answers the app's errors of type `{error}` (m.map_error in `{}`{reason}), a type of another crate; only a module of the app maps another crate's errors: remove the plugin or update it to a version that maps only its own errors, and to use the plugin's mapping, register it from a module of the app (m.map_error)",
                plugin.info.name, mapper.module.name
            ))
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Clippy's `result_large_err` fires at 128 bytes; every crate returning
    /// `navree_http::Result<T>` would have to silence it.
    #[test]
    fn app_error_stays_small_enough_for_result() {
        assert!(
            std::mem::size_of::<AppError>() < 128,
            "AppError is {} bytes",
            std::mem::size_of::<AppError>()
        );
    }

    #[derive(Debug)]
    struct Taken;

    impl fmt::Display for Taken {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("taken")
        }
    }

    impl StdError for Taken {}

    #[derive(Debug)]
    struct Wrapped(Taken);

    impl fmt::Display for Wrapped {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("wrapped")
        }
    }

    impl StdError for Wrapped {
        fn source(&self) -> Option<&(dyn StdError + 'static)> {
            Some(&self.0)
        }
    }

    fn mappers() -> Vec<ErrorMapper> {
        vec![ErrorMapper::new::<Taken>(|_| {
            Some(AppError::conflict("already taken"))
        })]
    }

    #[test]
    fn mappers_apply_to_a_source_chain() {
        let mappers = mappers();
        let mapped = ErrorMapper::apply(&mappers, &AppError::internal(Wrapped(Taken))).unwrap();
        assert_eq!(mapped.status, StatusCode::CONFLICT);
        let mapped = ErrorMapper::apply_to(&mappers, &Wrapped(Taken)).unwrap();
        assert_eq!(mapped.detail.as_deref(), Some("already taken"));
        assert!(ErrorMapper::apply(&mappers, &AppError::internal("other")).is_none());
        assert!(ErrorMapper::apply(&mappers, &AppError::not_found()).is_none());
    }

    #[test]
    fn mappers_apply_to_errors_held_as_any() {
        let mappers = mappers();
        let held: Arc<dyn Any + Send + Sync> = Arc::new(Taken);
        let mapped = ErrorMapper::apply_any(&mappers, &*held).unwrap();
        assert_eq!(mapped.status, StatusCode::CONFLICT);
        let other: Arc<dyn Any + Send + Sync> = Arc::new(Wrapped(Taken));
        assert!(ErrorMapper::apply_any(&mappers, &*other).is_none());
    }

    /// One body snapshot per framework error: the stable `code` follows
    /// `error`.
    #[test]
    fn framework_errors_render_their_stable_codes() {
        use serde_json::json;

        let errors = BTreeMap::from([(
            "email".to_owned(),
            vec!["email must be a valid email address".to_owned()],
        )]);
        let cases = [
            (
                AppError::bad_request("The export is empty."),
                json!({"statusCode": 400, "message": "The export is empty.", "error": "Bad Request", "code": "bad_request"}),
            ),
            (
                AppError::validation(errors.clone()),
                json!({
                    "statusCode": 400,
                    "message": ["email must be a valid email address"],
                    "error": "Bad Request",
                    "code": "validation_failed",
                    "errors": {"email": ["email must be a valid email address"]},
                }),
            ),
            (
                AppError::invalid_filter("Unknown filter `colour`."),
                json!({"statusCode": 400, "message": "Unknown filter `colour`.", "error": "Bad Request", "code": "invalid_filter"}),
            ),
            (
                AppError::unauthenticated(),
                json!({"statusCode": 401, "message": "Unauthorized", "error": "Unauthorized", "code": "unauthenticated"}),
            ),
            (
                AppError::two_factor_required(),
                json!({"statusCode": 401, "message": "Two-factor authentication required", "error": "Unauthorized", "code": "two_factor_required"}),
            ),
            (
                AppError::forbidden(),
                json!({"statusCode": 403, "message": "Forbidden", "error": "Forbidden", "code": "forbidden"}),
            ),
            (
                AppError::csrf_mismatch(),
                json!({"statusCode": 403, "message": "Invalid CSRF token", "error": "Forbidden", "code": "csrf_token_mismatch"}),
            ),
            (
                AppError::demo_read_only(),
                json!({"statusCode": 403, "message": "Demo workspaces are read-only.", "error": "Forbidden", "code": "demo_read_only"}),
            ),
            (
                AppError::not_found(),
                json!({"statusCode": 404, "message": "Not Found", "error": "Not Found", "code": "not_found"}),
            ),
            (
                AppError::conflict("Email taken"),
                json!({"statusCode": 409, "message": "Email taken", "error": "Conflict", "code": "conflict"}),
            ),
            (
                AppError::limit_reached("Your plan includes 5 seats."),
                json!({"statusCode": 409, "message": "Your plan includes 5 seats.", "error": "Conflict", "code": "limit_reached"}),
            ),
            (
                AppError::payload_too_large(16),
                json!({"statusCode": 413, "message": "The request body must not exceed 16 bytes.", "error": "Payload Too Large", "code": "payload_too_large"}),
            ),
            (
                AppError::page_expired(),
                json!({"statusCode": 419, "message": "Page Expired", "error": "Page Expired", "code": "page_expired"}),
            ),
            (
                AppError::too_many_requests(Duration::from_secs(3)),
                json!({"statusCode": 429, "message": "Too Many Requests", "error": "Too Many Requests", "code": "too_many_requests"}),
            ),
            (
                AppError::internal("db password=hunter2"),
                json!({"statusCode": 500, "message": "Internal server error", "error": "Internal Server Error", "code": "internal_error"}),
            ),
            (
                AppError::service_unavailable("Try again later."),
                json!({"statusCode": 503, "message": "Try again later.", "error": "Service Unavailable", "code": "service_unavailable"}),
            ),
        ];
        for (error, body) in cases {
            assert!(
                codes::ALL.contains(&error.code.as_str()),
                "`{}` is in the table of stable codes",
                error.code
            );
            assert_eq!(error.body(), body, "{error}");
        }
    }

    #[test]
    fn statuses_without_a_constructor_derive_their_code() {
        let cases = [
            (StatusCode::METHOD_NOT_ALLOWED, codes::METHOD_NOT_ALLOWED),
            (
                StatusCode::UNSUPPORTED_MEDIA_TYPE,
                codes::UNSUPPORTED_MEDIA_TYPE,
            ),
            (StatusCode::PAYMENT_REQUIRED, "payment_required"),
            (StatusCode::GONE, "gone"),
        ];
        for (status, code) in cases {
            assert_eq!(AppError::from_status(status).code, code, "{status}");
        }
    }

    #[test]
    fn with_code_sets_the_rendered_code() {
        let error = AppError::conflict("The campaign is already running.")
            .with_code("campaign_already_running");
        assert_eq!(error.status, StatusCode::CONFLICT);
        assert_eq!(error.code, "campaign_already_running");
        assert_eq!(
            error.body(),
            serde_json::json!({
                "statusCode": 409,
                "message": "The campaign is already running.",
                "error": "Conflict",
                "code": "campaign_already_running",
            })
        );
    }

    #[test]
    fn code_comes_after_error_and_before_errors() {
        let errors = BTreeMap::from([("name".to_owned(), vec!["name is required".to_owned()])]);
        let response = AppError::validation(errors).render(ErrorFormat::default());
        let text = futures_util::FutureExt::now_or_never(http_body_util::BodyExt::collect(
            response.into_body(),
        ))
        .expect("a full body")
        .expect("collects")
        .to_bytes();
        let text = String::from_utf8_lossy(&text);
        let positions: Vec<usize> = [
            "\"statusCode\"",
            "\"message\"",
            "\"error\"",
            "\"code\"",
            "\"errors\"",
        ]
        .iter()
        .map(|key| text.find(key).expect(key))
        .collect();
        assert!(positions.is_sorted(), "member order: {text}");
    }

    #[test]
    fn the_code_is_left_out_when_turned_off_or_empty() {
        let off = ErrorFormat { code: false };
        let body = AppError::not_found().body_as(off);
        assert_eq!(
            body,
            serde_json::json!({"statusCode": 404, "message": "Not Found", "error": "Not Found"})
        );
        let empty = AppError::new(StatusCode::IM_A_TEAPOT, "", "Short and stout");
        assert!(empty.body().get("code").is_none(), "{}", empty.body());
    }

    #[test]
    fn statuses_have_codes_and_titles() {
        assert_eq!(AppError::unauthenticated().status, StatusCode::UNAUTHORIZED);
        assert_eq!(AppError::unauthenticated().title, "Unauthorized");
        assert_eq!(AppError::forbidden().code, "forbidden");
        assert_eq!(AppError::forbidden().title, "Forbidden");
        assert_eq!(
            AppError::from_status(StatusCode::TOO_MANY_REQUESTS).title,
            "Too Many Requests"
        );
        let teapot = AppError::from_status(StatusCode::IM_A_TEAPOT);
        assert_eq!(teapot.code, "i_m_a_teapot");
        assert_eq!(teapot.title, "I'm a teapot");
    }

    #[test]
    fn csrf_mismatch_is_403_invalid_csrf_token() {
        let error = AppError::csrf_mismatch();
        assert_eq!(error.status, StatusCode::FORBIDDEN);
        assert_eq!(error.code, "csrf_token_mismatch");
        assert_eq!(
            error.body(),
            serde_json::json!({
                "statusCode": 403,
                "message": "Invalid CSRF token",
                "error": "Forbidden",
                "code": "csrf_token_mismatch",
            })
        );
    }

    #[test]
    fn body_uses_detail_as_message_and_reason_phrase_as_error() {
        assert_eq!(
            AppError::not_found().body(),
            serde_json::json!({"statusCode": 404, "message": "Not Found", "error": "Not Found", "code": "not_found"})
        );
        assert_eq!(
            AppError::conflict("Email taken").body(),
            serde_json::json!({"statusCode": 409, "message": "Email taken", "error": "Conflict", "code": "conflict"})
        );
        let custom = AppError::new(
            StatusCode::UNAUTHORIZED,
            "invalid_signature",
            "Invalid signature.",
        );
        assert_eq!(
            custom.body(),
            serde_json::json!({
                "statusCode": 401,
                "message": "Invalid signature.",
                "error": "Unauthorized",
                "code": "invalid_signature",
            })
        );
        let odd = AppError::from_status(StatusCode::from_u16(599).unwrap());
        assert_eq!(odd.body()["error"], "Error", "no reason phrase");
    }

    #[test]
    fn validation_is_400_with_flattened_messages_in_field_order() {
        let errors = BTreeMap::from([
            (
                "name".to_owned(),
                vec!["name should not be empty".to_owned()],
            ),
            (
                "email".to_owned(),
                vec![
                    "email must be a valid email address".to_owned(),
                    "email must be shorter than or equal to 255 characters".to_owned(),
                ],
            ),
        ]);
        let error = AppError::validation(errors.clone()).with_detail("ignored when rendering");
        assert_eq!(error.status, StatusCode::BAD_REQUEST);
        assert_eq!(error.code, "validation_failed");
        assert_eq!(
            error.body(),
            serde_json::json!({
                "statusCode": 400,
                "message": [
                    "email must be a valid email address",
                    "email must be shorter than or equal to 255 characters",
                    "name should not be empty",
                ],
                "error": "Bad Request",
                "code": "validation_failed",
                "errors": errors,
            })
        );
        let empty = AppError::validation(BTreeMap::new());
        assert_eq!(empty.body()["message"], "Bad Request");
        assert_eq!(empty.body()["errors"], serde_json::json!({}));
    }

    #[test]
    fn rendered_errors_are_application_json() {
        let response = AppError::not_found().render(ErrorFormat::default());
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
        assert_eq!(response.headers()[CONTENT_TYPE], ERROR_CONTENT_TYPE);
        assert_eq!(ERROR_CONTENT_TYPE, "application/json");
    }

    #[test]
    fn too_many_requests_rounds_retry_after_up() {
        let error = AppError::too_many_requests(Duration::from_millis(1500));
        assert_eq!(error.headers[RETRY_AFTER], "2");
        let error = AppError::too_many_requests(Duration::ZERO);
        assert_eq!(error.headers[RETRY_AFTER], "1");
    }

    #[test]
    fn internal_keeps_source_but_renders_no_detail() {
        let error = AppError::internal(std::io::Error::other("db password=hunter2"));
        assert_eq!(
            error.body(),
            serde_json::json!({
                "statusCode": 500,
                "message": "Internal server error",
                "error": "Internal Server Error",
                "code": "internal_error",
            })
        );
        assert!(error.log_chain().contains("hunter2"), "logged, not sent");
    }

    #[test]
    fn take_from_returns_the_error_a_response_carries_once() {
        let mut response = AppError::conflict("Taken").into_response();
        let error = AppError::take_from(&mut response).expect("the pending error");
        assert_eq!(error.status, StatusCode::CONFLICT);
        assert_eq!(error.detail.as_deref(), Some("Taken"));
        assert!(AppError::take_from(&mut response).is_none(), "taken once");
        let mut plain = (StatusCode::OK, "fine").into_response();
        assert!(AppError::take_from(&mut plain).is_none());
    }

    #[test]
    fn mappers_apply_to_the_source_chain() {
        #[derive(Debug)]
        struct Missing;
        impl fmt::Display for Missing {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("missing")
            }
        }
        impl StdError for Missing {}
        let mappers = [ErrorMapper::new::<Missing>(|_| Some(AppError::not_found()))];
        let mapped = ErrorMapper::apply(&mappers, &AppError::internal(Missing)).expect("mapped");
        assert_eq!(mapped.status, StatusCode::NOT_FOUND);
        assert!(ErrorMapper::apply(&mappers, &AppError::internal("other")).is_none());
        assert!(ErrorMapper::apply(&[], &AppError::internal(Missing)).is_none());
    }

    #[test]
    fn strings_convert_with_question_mark() {
        fn fails() -> Result<()> {
            Err("boom")?
        }
        let error = fails().unwrap_err();
        assert_eq!(error.status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(error.source.unwrap().to_string(), "boom");
    }
}