Skip to main content

ocre/
errors.rs

1//! Error reporting (Rails' `Rails.error`): report errors with context to the logs and to services such as Sentry.
2//!
3//! Every [`Ctx`](crate::Ctx) has a [`Reporter`], [`Ctx::errors`](crate::Ctx::errors).
4//! A report is logged at once (as an `error`, `warn` or `info` line with its
5//! context) and handed to each [`Subscriber`] the app registered with
6//! [`subscribe`]. Ocre reports on its own, with `handled: false`:
7//!
8//! | Source | When |
9//! |---|---|
10//! | `ocre.request` | a handler returned [`Error::Internal`](crate::Error::Internal) (a 500) |
11//! | `ocre.job` | a background job failed (it is retried or discarded) |
12//! | `ocre.cron` | a scheduled task failed |
13//! | `ocre.mailbox` | the inbound email handler failed |
14//!
15//! ```no_run
16//! use axum::extract::State;
17//! use ocre::{Ctx, Result, errors::{Options, Severity}};
18//!
19//! async fn sync_orders(State(ctx): State<Ctx>) -> Result<&'static str> {
20//!     ctx.errors().set_context("tenant", "acme"); // added to every report of this request
21//!
22//!     // Rails.error.handle: report and go on with a fallback.
23//!     let rates: Vec<f64> = ctx.errors().handle(fetch_rates().await).unwrap_or_default();
24//!
25//!     // Rails.error.record: report, then fail the request.
26//!     ctx.errors().record(charge().await)?;
27//!
28//!     // Rails.error.report, with options.
29//!     if rates.is_empty() {
30//!         let options = Options::new().severity(Severity::Info).context("provider", "ecb").source("rates");
31//!         ctx.errors().report(&"no exchange rates today", options);
32//!     }
33//!     Ok("OK")
34//! }
35//!
36//! async fn fetch_rates() -> Result<Vec<f64>> {
37//!     Ok(vec![1.08])
38//! }
39//! async fn charge() -> Result<()> {
40//!     Ok(())
41//! }
42//! # let _ = sync_orders;
43//! ```
44//!
45//! # Subscribers
46//!
47//! Register them once per Worker instance, in the `start` event of
48//! `src/lib.rs` (Ocre's initializer):
49//!
50//! ```no_run
51//! #[worker::event(start)]
52//! fn start() {
53//!     ocre::errors::subscribe(ocre::errors::Sentry);
54//! }
55//! ```
56//!
57//! [`Sentry`] sends each report to the project of the `SENTRY_DSN` secret
58//! (sentry.io or any Sentry-compatible service, such as GlitchTip or
59//! Bugsink). Other services implement [`Subscriber`]: it turns a [`Report`]
60//! into the HTTP request to send ([`Delivery`]), and Ocre sends it with
61//! `fetch` once the response is ready. [`scrub`] (or [`Report::scrubbed`])
62//! takes emails, credentials and tokens out of a report before it leaves
63//! the app, and normalizes ids and durations so one error groups as one
64//! issue.
65//!
66//! # Free plan
67//!
68//! Reports cost nothing until a subscriber sends one: then each delivery is
69//! one subrequest (50 per request on the free plan), made after the
70//! handler, before the response goes out, so an error response waits for
71//! it. Only reports that happen are sent; a request without errors makes no
72//! subrequest.
73
74mod scrub;
75
76use std::{
77    fmt::Display,
78    sync::{Arc, Mutex, PoisonError},
79};
80
81use serde::Serialize;
82use serde_json::{Map, Value, json};
83
84use crate::{config::Environment, log::Logger};
85pub use scrub::scrub;
86
87/// How bad a report is (Rails' `severity:`).
88///
89/// # Examples
90///
91/// ```
92/// assert_eq!(ocre::errors::Severity::Warning.as_str(), "warning");
93/// ```
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub enum Severity {
96    /// A failure: the default of [`Reporter::record`] and of Ocre's own reports.
97    Error,
98    /// Handled, worth looking at: the default of [`Reporter::report`] and [`Reporter::handle`].
99    Warning,
100    /// For information.
101    Info,
102}
103
104impl Severity {
105    /// `error`, `warning` or `info`, as Sentry names levels.
106    ///
107    /// # Examples
108    ///
109    /// ```
110    /// assert_eq!(ocre::errors::Severity::Error.as_str(), "error");
111    /// ```
112    pub fn as_str(self) -> &'static str {
113        match self {
114            Self::Error => "error",
115            Self::Warning => "warning",
116            Self::Info => "info",
117        }
118    }
119
120    fn level(self) -> crate::log::Level {
121        match self {
122            Self::Error => crate::log::Level::Error,
123            Self::Warning => crate::log::Level::Warn,
124            Self::Info => crate::log::Level::Info,
125        }
126    }
127}
128
129/// Options of one report (Rails' `handled:`, `severity:`, `context:`, `source:`).
130///
131/// Defaults: handled, [`Severity::Warning`], no context, source `application`.
132///
133/// # Examples
134///
135/// ```
136/// use ocre::errors::{Options, Severity};
137///
138/// let options = Options::new().handled(false).severity(Severity::Error).context("order_id", 42).source("billing");
139/// # let _ = options;
140/// ```
141#[derive(Debug, Clone)]
142pub struct Options {
143    handled: bool,
144    severity: Severity,
145    context: Map<String, Value>,
146    source: String,
147    except: Vec<&'static str>,
148}
149
150impl Default for Options {
151    fn default() -> Self {
152        Self {
153            handled: true,
154            severity: Severity::Warning,
155            context: Map::new(),
156            source: "application".to_owned(),
157            except: Vec::new(),
158        }
159    }
160}
161
162impl Options {
163    /// The defaults: handled, warning, no context, source `application`.
164    ///
165    /// # Examples
166    ///
167    /// ```
168    /// let _ = ocre::errors::Options::new();
169    /// ```
170    pub fn new() -> Self {
171        Self::default()
172    }
173
174    /// Whether the app recovered from the error (`false` for errors that failed the request or job).
175    ///
176    /// # Examples
177    ///
178    /// ```
179    /// let _ = ocre::errors::Options::new().handled(false);
180    /// ```
181    pub fn handled(mut self, handled: bool) -> Self {
182        self.handled = handled;
183        self
184    }
185
186    /// The report's [`Severity`].
187    ///
188    /// # Examples
189    ///
190    /// ```
191    /// let _ = ocre::errors::Options::new().severity(ocre::errors::Severity::Info);
192    /// ```
193    pub fn severity(mut self, severity: Severity) -> Self {
194        self.severity = severity;
195        self
196    }
197
198    /// Adds a context entry, merged over the request's [`Reporter::set_context`] entries.
199    ///
200    /// A value that does not serialize is `null`.
201    ///
202    /// # Examples
203    ///
204    /// ```
205    /// let _ = ocre::errors::Options::new().context("user_id", 7);
206    /// ```
207    pub fn context(mut self, key: &str, value: impl Serialize) -> Self {
208        self.context.insert(key.to_owned(), serde_json::to_value(value).unwrap_or(Value::Null));
209        self
210    }
211
212    /// Where the error comes from, e.g. `billing` (Rails' `source:`).
213    ///
214    /// # Examples
215    ///
216    /// ```
217    /// let _ = ocre::errors::Options::new().source("webhooks");
218    /// ```
219    pub fn source(mut self, source: &str) -> Self {
220        self.source = source.to_owned();
221        self
222    }
223
224    /// Does not send this report to the subscriber named `name` (Rails' `Rails.error.disable`).
225    ///
226    /// For errors a subscriber should not see, such as the failure of its
227    /// own service. The report is still logged.
228    ///
229    /// # Examples
230    ///
231    /// ```
232    /// let _ = ocre::errors::Options::new().except("sentry");
233    /// ```
234    pub fn except(mut self, subscriber: &'static str) -> Self {
235        self.except.push(subscriber);
236        self
237    }
238}
239
240/// One reported error, as subscribers receive it.
241///
242/// # Examples
243///
244/// ```
245/// use ocre::errors::{Options, Reporter};
246///
247/// let reporter = Reporter::default();
248/// reporter.report(&"quota exceeded", Options::new().context("plan", "free"));
249/// let report = &reporter.take()[0];
250/// assert_eq!((report.message.as_str(), report.class.as_str()), ("quota exceeded", "&str"));
251/// assert_eq!(report.context["plan"], "free");
252/// ```
253#[derive(Debug, Clone, PartialEq)]
254pub struct Report {
255    /// The error's type, e.g. `ocre::error::Error` (Sentry's exception type).
256    pub class: String,
257    /// The error's text (`Display`).
258    pub message: String,
259    /// Whether the app recovered from it.
260    pub handled: bool,
261    /// How bad it is.
262    pub severity: Severity,
263    /// The request's context, then the report's own entries.
264    pub context: Map<String, Value>,
265    /// Where it comes from: `application`, `ocre.request`, `ocre.job`...
266    pub source: String,
267    /// When it was reported, in Unix seconds.
268    pub timestamp: i64,
269    /// Development or production, from the build profile.
270    pub environment: Environment,
271    except: Vec<&'static str>,
272}
273
274/// An HTTP `POST` a [`Subscriber`] asks Ocre to send for a report.
275///
276/// # Examples
277///
278/// ```
279/// let delivery = ocre::errors::Delivery {
280///     url: "https://errors.example/api/reports".into(),
281///     headers: vec![("content-type".into(), "application/json".into())],
282///     body: "{}".into(),
283/// };
284/// # let _ = delivery;
285/// ```
286#[derive(Debug, Clone, PartialEq)]
287pub struct Delivery {
288    /// Where to `POST`.
289    pub url: String,
290    /// Request headers, e.g. an API key.
291    pub headers: Vec<(String, String)>,
292    /// The request body.
293    pub body: String,
294}
295
296/// An error-reporting service (Rails' error subscribers): turns a [`Report`] into the request to send.
297///
298/// `vars` looks up a Worker variable or secret by name (the service's key).
299/// Return `None` to send nothing, e.g. when the key is not set. Ocre sends
300/// the [`Delivery`] with `fetch` and logs a failed send; it never retries.
301///
302/// # Examples
303///
304/// ```
305/// use ocre::errors::{Delivery, Report, Subscriber};
306///
307/// /// Posts each error to a webhook (a chat channel, an incident tool...).
308/// struct Webhook;
309///
310/// impl Subscriber for Webhook {
311///     fn name(&self) -> &'static str {
312///         "webhook"
313///     }
314///
315///     fn deliver(&self, report: &Report, vars: &dyn Fn(&str) -> Option<String>) -> Option<Delivery> {
316///         let url = vars("ERRORS_WEBHOOK_URL")?;
317///         let body = serde_json::json!({ "text": format!("{}: {}", report.source, report.message) }).to_string();
318///         Some(Delivery { url, headers: vec![("content-type".into(), "application/json".into())], body })
319///     }
320/// }
321///
322/// ocre::errors::subscribe(Webhook);
323/// ```
324pub trait Subscriber: Send + Sync {
325    /// A short name, for [`Options::except`] and failure logs: `sentry`.
326    fn name(&self) -> &'static str;
327
328    /// The request to send for `report`, if any.
329    fn deliver(&self, report: &Report, vars: &dyn Fn(&str) -> Option<String>) -> Option<Delivery>;
330}
331
332static SUBSCRIBERS: Mutex<Vec<Arc<dyn Subscriber>>> = Mutex::new(Vec::new());
333
334/// Registers a subscriber for every report of this Worker instance (Rails' `Rails.error.subscribe`).
335///
336/// Call it from the `start` event (see the [module documentation](self)),
337/// which runs once per instance; a second subscriber with the same
338/// [`name`](Subscriber::name) replaces the first.
339///
340/// # Examples
341///
342/// ```
343/// ocre::errors::subscribe(ocre::errors::Sentry);
344/// ```
345pub fn subscribe(subscriber: impl Subscriber + 'static) {
346    let mut subscribers = SUBSCRIBERS.lock().unwrap_or_else(PoisonError::into_inner);
347    subscribers.retain(|existing| existing.name() != subscriber.name());
348    subscribers.push(Arc::new(subscriber));
349}
350
351/// The deliveries of `reports` for every registered subscriber, with the
352/// subscriber's name: what the runtime sends after a request or job.
353pub(crate) fn deliveries(reports: &[Report], vars: &dyn Fn(&str) -> Option<String>) -> Vec<(&'static str, Delivery)> {
354    let subscribers = SUBSCRIBERS.lock().unwrap_or_else(PoisonError::into_inner).clone();
355    let mut out = Vec::new();
356    for report in reports {
357        for subscriber in subscribers.iter().filter(|s| !report.except.contains(&s.name())) {
358            if let Some(delivery) = subscriber.deliver(report, vars) {
359                out.push((subscriber.name(), delivery));
360            }
361        }
362    }
363    out
364}
365
366#[derive(Debug, Default)]
367struct State {
368    context: Map<String, Value>,
369    pending: Vec<Report>,
370}
371
372/// The error reporter of one request, job batch or cron run: [`Ctx::errors`](crate::Ctx::errors).
373///
374/// Cheap to clone; clones share their context and pending reports.
375/// `Reporter::default()` builds one for unit tests, whose reports are read
376/// back with [`take`](Self::take).
377///
378/// # Examples
379///
380/// ```
381/// use ocre::errors::{Reporter, Severity};
382///
383/// let reporter = Reporter::default();
384/// let value: Option<i32> = reporter.handle("x".parse::<i32>());
385/// assert_eq!(value, None);
386/// let reports = reporter.take();
387/// assert_eq!((reports[0].handled, reports[0].severity), (true, Severity::Warning));
388/// ```
389#[derive(Debug, Clone, Default)]
390pub struct Reporter {
391    state: Arc<Mutex<State>>,
392    log: Logger,
393}
394
395impl Reporter {
396    /// A reporter whose log lines carry the fields of `log` (the request id...).
397    pub(crate) fn new(log: Logger) -> Self {
398        Self { state: Arc::default(), log }
399    }
400
401    fn lock(&self) -> std::sync::MutexGuard<'_, State> {
402        self.state.lock().unwrap_or_else(PoisonError::into_inner)
403    }
404
405    /// Adds context to every later report of this request or job (Rails' `Rails.error.set_context`).
406    ///
407    /// # Examples
408    ///
409    /// ```
410    /// let reporter = ocre::errors::Reporter::default();
411    /// reporter.set_context("user_id", 7);
412    /// reporter.report(&"oops", ocre::errors::Options::new());
413    /// assert_eq!(reporter.take()[0].context["user_id"], 7);
414    /// ```
415    pub fn set_context(&self, key: &str, value: impl Serialize) {
416        self.lock().context.insert(key.to_owned(), serde_json::to_value(value).unwrap_or(Value::Null));
417    }
418
419    /// Reports an error (Rails' `Rails.error.report`): logs it and queues it for the subscribers.
420    ///
421    /// # Examples
422    ///
423    /// ```
424    /// let reporter = ocre::errors::Reporter::default();
425    /// let err = ocre::Error::internal("webhook signature mismatch");
426    /// reporter.report(&err, ocre::errors::Options::new().source("webhooks"));
427    /// assert_eq!(reporter.take()[0].message, "internal error: webhook signature mismatch");
428    /// ```
429    pub fn report<E: Display + ?Sized>(&self, error: &E, options: Options) {
430        self.push(std::any::type_name::<E>(), error.to_string(), options, true);
431    }
432
433    /// Reports the error of `result`, if any, as handled, and returns its value (Rails' `Rails.error.handle`).
434    ///
435    /// `.unwrap_or(fallback)` gives Rails' `fallback:`. Only errors of the
436    /// result's type are caught: other errors propagate with `?` before
437    /// reaching it (Rails' class filter).
438    ///
439    /// # Examples
440    ///
441    /// ```
442    /// let reporter = ocre::errors::Reporter::default();
443    /// assert_eq!(reporter.handle("4".parse::<u8>()), Some(4));
444    /// assert_eq!(reporter.handle("x".parse::<u8>()).unwrap_or(1), 1);
445    /// assert_eq!(reporter.take().len(), 1);
446    /// ```
447    pub fn handle<T, E: Display>(&self, result: Result<T, E>) -> Option<T> {
448        result.map_err(|err| self.report(&err, Options::new())).ok()
449    }
450
451    /// Reports the error of `result`, if any, as unhandled, and returns `result` unchanged (Rails' `Rails.error.record`).
452    ///
453    /// # Examples
454    ///
455    /// ```
456    /// use ocre::errors::{Reporter, Severity};
457    ///
458    /// let reporter = Reporter::default();
459    /// assert!(reporter.record("x".parse::<u8>()).is_err());
460    /// let report = &reporter.take()[0];
461    /// assert_eq!((report.handled, report.severity), (false, Severity::Error));
462    /// ```
463    pub fn record<T, E: Display>(&self, result: Result<T, E>) -> Result<T, E> {
464        result.inspect_err(|err| self.report(err, Options::new().handled(false).severity(Severity::Error)))
465    }
466
467    /// Reports something that should never happen (Rails' `Rails.error.unexpected`).
468    ///
469    /// Panics in debug builds (`ocre dev`, tests), so the bug is seen at
470    /// once; in release builds it is reported as an error and the code goes on.
471    ///
472    /// # Panics
473    ///
474    /// In debug builds, always.
475    ///
476    /// # Examples
477    ///
478    /// ```should_panic
479    /// ocre::errors::Reporter::default().unexpected("a paid order has no invoice");
480    /// ```
481    #[track_caller]
482    pub fn unexpected(&self, message: impl Display) {
483        self.unexpected_in(&message, cfg!(debug_assertions));
484    }
485
486    #[track_caller]
487    fn unexpected_in(&self, message: &dyn Display, raise: bool) {
488        assert!(!raise, "unexpected: {message}");
489        let location = std::panic::Location::caller().to_string();
490        let options = Options::new().severity(Severity::Error).context("location", location).source("unexpected");
491        self.push("unexpected", message.to_string(), options, true);
492    }
493
494    /// Ocre's own report of an unhandled error from `source` (`ocre.request`...);
495    /// `log: false` when the caller already logged its own line (jobs, cron).
496    pub(crate) fn report_unhandled(&self, message: &str, source: &str, context: Map<String, Value>, log: bool) {
497        let mut options = Options::new().handled(false).severity(Severity::Error).source(source);
498        options.context = context;
499        self.push("ocre::Error", message.to_owned(), options, log);
500    }
501
502    /// Takes the reports made so far, for the subscribers (or a test).
503    ///
504    /// # Examples
505    ///
506    /// ```
507    /// let reporter = ocre::errors::Reporter::default();
508    /// assert!(reporter.take().is_empty());
509    /// ```
510    pub fn take(&self) -> Vec<Report> {
511        std::mem::take(&mut self.lock().pending)
512    }
513
514    fn push(&self, class: &str, message: String, options: Options, logged: bool) {
515        let mut state = self.lock();
516        let mut context = state.context.clone();
517        context.extend(options.context);
518        let report = Report {
519            class: class.to_owned(),
520            message,
521            handled: options.handled,
522            severity: options.severity,
523            context,
524            source: options.source,
525            timestamp: crate::now(),
526            environment: Environment::current(),
527            except: options.except,
528        };
529        if logged {
530            let prefix = if report.source.starts_with("ocre.") { "[ocre] " } else { "" };
531            let mut log = self.log.with("error_class", &report.class).with("handled", report.handled);
532            log = log.with("source", &report.source);
533            for (key, value) in &report.context {
534                log = log.with(key, value);
535            }
536            log.log(report.severity.level(), &format_args!("{prefix}{}", report.message));
537        }
538        state.pending.push(report);
539    }
540}
541
542/// Worker secret holding the Sentry DSN: `https://<key>@<host>/<project id>`.
543///
544/// # Examples
545///
546/// ```
547/// assert_eq!(ocre::errors::SENTRY_DSN, "SENTRY_DSN");
548/// ```
549pub const SENTRY_DSN: &str = "SENTRY_DSN";
550
551/// Sends reports to Sentry or a Sentry-compatible service, as envelopes (the Sentry ingestion protocol).
552///
553/// Reads the DSN from the [`SENTRY_DSN`] secret (`ocre secrets push
554/// SENTRY_DSN --file .prod.vars`); without it, sends nothing. The optional
555/// `SENTRY_RELEASE` variable sets the release. Each report becomes one
556/// event: the error as the exception (type [`Report::class`], value
557/// [`Report::message`], mechanism [`Report::source`] and `handled`), the
558/// severity as level, the environment, `request_id` as a tag and the
559/// context (filtered like logs) as extra data. One subrequest per report.
560///
561/// # Examples
562///
563/// ```
564/// use ocre::errors::{Options, Reporter, Sentry, Subscriber};
565///
566/// let reporter = Reporter::default();
567/// reporter.report(&"boom", Options::new());
568/// let report = &reporter.take()[0];
569/// let dsn = |name: &str| (name == "SENTRY_DSN").then(|| "https://abc@o1.ingest.sentry.io/42".to_owned());
570/// let delivery = Sentry.deliver(report, &dsn).unwrap();
571/// assert_eq!(delivery.url, "https://o1.ingest.sentry.io/api/42/envelope/");
572/// assert!(Sentry.deliver(report, &|_| None).is_none());
573/// ```
574#[derive(Debug, Clone, Copy)]
575pub struct Sentry;
576
577impl Subscriber for Sentry {
578    fn name(&self) -> &'static str {
579        "sentry"
580    }
581
582    fn deliver(&self, report: &Report, vars: &dyn Fn(&str) -> Option<String>) -> Option<Delivery> {
583        let dsn = vars(SENTRY_DSN)?;
584        let Some((scheme, key, host, project)) = parse_dsn(&dsn) else {
585            crate::error::log_internal(&format!(
586                "{SENTRY_DSN} is not a Sentry DSN (https://<key>@<host>/<project id>)"
587            ));
588            return None;
589        };
590        let event_id: String = crate::token::random_bytes::<16>().iter().map(|b| format!("{b:02x}")).collect();
591        let mut tags = json!({ "source": report.source });
592        if let Some(id) = report.context.get("request_id") {
593            tags["request_id"] = id.clone();
594        }
595        let mut event = json!({
596            "event_id": event_id,
597            "timestamp": report.timestamp,
598            "platform": "other",
599            "level": report.severity.as_str(),
600            "logger": report.source,
601            "environment": report.environment.as_str(),
602            "exception": { "values": [{
603                "type": report.class,
604                "value": report.message,
605                "mechanism": { "type": report.source, "handled": report.handled },
606            }] },
607            "tags": tags,
608            "extra": crate::security::filter_json(&Value::Object(report.context.clone())),
609            "sdk": { "name": "ocre", "version": env!("CARGO_PKG_VERSION") },
610        });
611        if let Some(release) = vars("SENTRY_RELEASE") {
612            event["release"] = release.into();
613        }
614        let header = json!({ "event_id": event_id, "dsn": dsn });
615        let body = format!("{header}\n{}\n{event}\n", json!({ "type": "event" }));
616        let auth =
617            format!("Sentry sentry_version=7, sentry_key={key}, sentry_client=ocre/{}", env!("CARGO_PKG_VERSION"));
618        Some(Delivery {
619            url: format!("{scheme}://{host}/api/{project}/envelope/"),
620            headers: vec![
621                ("content-type".to_owned(), "application/x-sentry-envelope".to_owned()),
622                ("x-sentry-auth".to_owned(), auth),
623            ],
624            body,
625        })
626    }
627}
628
629/// `https://key@host/path/42` into (`https`, `key`, `host/path`, `42`).
630fn parse_dsn(dsn: &str) -> Option<(&str, &str, &str, &str)> {
631    let (scheme, rest) = dsn.trim().split_once("://")?;
632    let (key, location) = rest.split_once('@')?;
633    let key = key.split(':').next().unwrap_or(key);
634    let (host, project) = location.trim_end_matches('/').rsplit_once('/')?;
635    let valid =
636        !key.is_empty() && !host.is_empty() && !project.is_empty() && project.bytes().all(|b| b.is_ascii_digit());
637    valid.then_some((scheme, key, host, project))
638}
639
640/// What the development error page shows of the request.
641#[derive(Debug, Clone, Default)]
642pub(crate) struct RequestDetails {
643    pub request_id: String,
644    pub method: String,
645    pub path: String,
646    /// Filtered with `security::filter_parameters`.
647    pub query: String,
648    /// Filtered: `cookie`, `authorization` and sensitive names hidden.
649    pub headers: Vec<(String, String)>,
650}
651
652impl RequestDetails {
653    /// The request's id, method and path; the query and headers only for
654    /// the development error page (`dev`).
655    pub fn new(
656        request_id: &str,
657        method: &str,
658        uri: &axum::http::Uri,
659        headers: &axum::http::HeaderMap,
660        dev: bool,
661    ) -> Self {
662        let mut details = Self {
663            request_id: request_id.to_owned(),
664            method: method.to_owned(),
665            path: uri.path().to_owned(),
666            ..Self::default()
667        };
668        if dev {
669            details.query = crate::security::filter_parameters(uri.query().unwrap_or_default());
670            details.headers = headers
671                .iter()
672                .map(|(name, value)| {
673                    (name.to_string(), shown_header(name.as_str(), value.to_str().unwrap_or("(binary)")))
674                })
675                .collect();
676        }
677        details
678    }
679
680    /// The logger of the request: every line carries its id, method and path.
681    pub fn logger(&self) -> Logger {
682        Logger::new().with("request_id", &self.request_id).with("method", &self.method).with("path", &self.path)
683    }
684}
685
686/// What `serve` does with the router's response: reports an
687/// [`Error::Internal`](crate::Error::Internal) (logged with the request's
688/// fields), sets `X-Request-Id`, logs the `debug` request line, and in
689/// debug builds (`dev`) adds `Server-Timing` and shows the development
690/// error page (HTML) or the internal message as `error.detail` (JSON).
691pub(crate) async fn finish(
692    mut response: axum::response::Response,
693    request: &RequestDetails,
694    reporter: &Reporter,
695    timings: &crate::instrument::Timings,
696    total_ms: f64,
697    dev: bool,
698) -> axum::response::Response {
699    use axum::http::HeaderValue;
700
701    if let Some(crate::error::InternalError(message)) = response.extensions_mut().remove() {
702        let context = Map::from_iter([
703            ("request_id".to_owned(), Value::from(request.request_id.as_str())),
704            ("method".to_owned(), Value::from(request.method.as_str())),
705            ("path".to_owned(), Value::from(request.path.as_str())),
706        ]);
707        reporter.report_unhandled(&message, "ocre.request", context, true);
708        if dev {
709            response = dev_response(response, &message, request, timings).await;
710        }
711    }
712    if let Ok(id) = HeaderValue::from_str(&request.request_id) {
713        response.headers_mut().entry("x-request-id").or_insert(id);
714    }
715    if dev && let Ok(value) = HeaderValue::from_str(&timings.server_timing(total_ms)) {
716        response.headers_mut().insert("server-timing", value);
717    }
718    let status = response.status().as_u16();
719    let mut line = timings.summary(&request.method, &request.path, status, total_ms);
720    // Rails' verbose redirect logs: where a redirect sends the browser.
721    if let Some(location) = response.headers().get(axum::http::header::LOCATION).and_then(|value| value.to_str().ok()) {
722        line.push_str(&format!(" -> {location}"));
723    }
724    reporter.log.debug(line);
725    response
726}
727
728/// The development form of a 500: the error page with the internal
729/// message, or the JSON error with `detail`.
730async fn dev_response(
731    response: axum::response::Response,
732    message: &str,
733    request: &RequestDetails,
734    timings: &crate::instrument::Timings,
735) -> axum::response::Response {
736    use axum::http::{HeaderValue, header};
737
738    let content_type = response.headers().get(header::CONTENT_TYPE).and_then(|value| value.to_str().ok());
739    let (html, json) =
740        content_type.map_or((false, false), |value| (value.starts_with("text/html"), value.contains("json")));
741    let (mut parts, body) = response.into_parts();
742    let body = if html {
743        dev_page(parts.status.as_u16(), message, request, &timings.statements())
744    } else if json {
745        let bytes = axum::body::to_bytes(body, 1 << 20).await.unwrap_or_default();
746        let mut value: Value = serde_json::from_slice(&bytes).unwrap_or_else(|_| json!({ "error": {} }));
747        value["error"]["detail"] = Value::from(message);
748        value.to_string()
749    } else {
750        return axum::response::Response::from_parts(parts, body);
751    };
752    parts.headers.remove(header::CONTENT_LENGTH);
753    if html {
754        parts.headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("text/html; charset=utf-8"));
755    }
756    axum::response::Response::from_parts(parts, axum::body::Body::from(body))
757}
758
759/// The development error page (debug builds only): the internal message,
760/// the request and the D1 statements it ran (Rails' development exception page).
761pub(crate) fn dev_page(
762    status: u16,
763    message: &str,
764    request: &RequestDetails,
765    statements: &[crate::instrument::Timing],
766) -> String {
767    let e = escape;
768    let mut page = format!(
769        "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>{status} {title}</title><style>body{{font-family:system-ui,sans-serif;margin:2rem;max-width:70rem}}h1{{color:#b3261e}}pre{{background:#f6f6f6;padding:1rem;overflow:auto;white-space:pre-wrap}}table{{border-collapse:collapse}}td,th{{border:1px solid #ddd;padding:.25rem .5rem;text-align:left;vertical-align:top}}</style></head><body>",
770        title = e(message.lines().next().unwrap_or(message))
771    );
772    page.push_str(&format!("<h1>{status} Internal server error</h1><pre>{}</pre>", e(message)));
773    page.push_str("<p>This page shows because the Worker is a debug build (<code>ocre dev</code>). After <code>ocre deploy</code>, users see the error page and the details go to the logs and error reporters.</p>");
774    page.push_str(&format!(
775        "<h2>Request</h2><table><tr><th>Request id</th><td>{}</td></tr><tr><th>Method</th><td>{}</td></tr><tr><th>Path</th><td>{}</td></tr><tr><th>Query</th><td>{}</td></tr></table>",
776        e(&request.request_id),
777        e(&request.method),
778        e(&request.path),
779        e(&request.query)
780    ));
781    page.push_str("<h2>Headers</h2><table>");
782    for (name, value) in &request.headers {
783        page.push_str(&format!("<tr><th>{}</th><td>{}</td></tr>", e(name), e(value)));
784    }
785    page.push_str(&format!("</table><h2>D1 statements ({})</h2><table>", statements.len()));
786    for statement in statements {
787        page.push_str(&format!("<tr><td>{} ms</td><td><code>{}</code></td></tr>", statement.ms, e(&statement.sql)));
788    }
789    page.push_str("</table></body></html>");
790    page
791}
792
793/// Header values shown on the development error page: secrets hidden.
794pub(crate) fn shown_header(name: &str, value: &str) -> String {
795    let hidden = ["cookie", "authorization", "proxy-authorization"].contains(&name)
796        || crate::security::filter_json(&json!({ name: value }))[name] != json!(value);
797    if hidden { "[FILTERED]".to_owned() } else { value.to_owned() }
798}
799
800fn escape(text: &str) -> String {
801    text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
802}
803
804#[cfg(test)]
805#[path = "../tests/errors.rs"]
806mod tests;