web-net 0.10.0

Web layer on serve-net: URL normalization, sites and base paths, a compiled router with 404 and 405, gate checkpoints for authentication and authorization, hooks, error pages, and a render trait that reads typed views.
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
//! Errors: what a handler returns, and what a build refuses.
//!
//! Every refusal and error becomes a response through one function: the
//! status, the site's error template for it (or a built-in page that cannot
//! fail), a generic message, and the request's reference. The code and the
//! detail go to the events only.

use std::fmt;

type Source = Box<dyn std::error::Error + Send + Sync>;

/// A handler error: a status, a stable code, and an optional source kept for
/// the logs. The visitor sees the status, a generic message, and the
/// request's reference; never the code or the source.
///
/// ```
/// use web_net::Error;
///
/// let e = Error::not_found("blog.no_post");
/// assert_eq!((e.status(), e.code()), (404, "blog.no_post"));
///
/// let io = std::io::Error::other("disk gone");
/// let e = Error::internal("blog.read").with_source(io);
/// assert_eq!(e.status(), 500);
/// assert!(e.source_ref().is_some());
/// ```
pub struct Error {
    status: u16,
    code: &'static str,
    source: Option<Source>,
}

impl Error {
    /// An error with `status` (400 to 599; anything else is treated as 500).
    ///
    /// ```
    /// use web_net::Error;
    ///
    /// assert_eq!(Error::new(429, "rate.limited").status(), 429);
    /// // A status outside 400 to 599 is treated as 500.
    /// assert_eq!(Error::new(200, "not.an.error").status(), 500);
    /// ```
    #[must_use]
    pub fn new(status: u16, code: &'static str) -> Self {
        let status = if (400..=599).contains(&status) {
            status
        } else {
            500
        };
        Self {
            status,
            code,
            source: None,
        }
    }

    /// 400 Bad Request.
    ///
    /// ```
    /// let e = web_net::Error::bad_request("search.no_query");
    /// assert_eq!((e.status(), e.code()), (400, "search.no_query"));
    /// ```
    #[must_use]
    pub fn bad_request(code: &'static str) -> Self {
        Self::new(400, code)
    }

    /// 403 Forbidden.
    ///
    /// ```
    /// use web_net::{App, Error, get};
    ///
    /// let app = App::builder()
    ///     .route(get("/admin", |_cx| Err(Error::forbidden("admin.closed"))))
    ///     .build()?;
    /// let r = serve_net::testing::respond(&app, b"GET /admin HTTP/1.1\r\nHost: localhost\r\n\r\n");
    /// assert_eq!(r.status, 403);
    /// # Ok::<(), web_net::BuildError>(())
    /// ```
    #[must_use]
    pub fn forbidden(code: &'static str) -> Self {
        Self::new(403, code)
    }

    /// 404 Not Found.
    ///
    /// ```
    /// let e = web_net::Error::not_found("blog.no_post");
    /// assert_eq!((e.status(), e.code()), (404, "blog.no_post"));
    /// ```
    #[must_use]
    pub fn not_found(code: &'static str) -> Self {
        Self::new(404, code)
    }

    /// 409 Conflict.
    ///
    /// ```
    /// let e = web_net::Error::conflict("user.name_taken");
    /// assert_eq!((e.status(), e.code()), (409, "user.name_taken"));
    /// ```
    #[must_use]
    pub fn conflict(code: &'static str) -> Self {
        Self::new(409, code)
    }

    /// 422 Unprocessable Content: the request was understood and refused
    /// (a form with errors).
    ///
    /// ```
    /// let e = web_net::Error::unprocessable("signup.weak_password");
    /// assert_eq!((e.status(), e.code()), (422, "signup.weak_password"));
    /// ```
    #[must_use]
    pub fn unprocessable(code: &'static str) -> Self {
        Self::new(422, code)
    }

    /// 500 Internal Server Error: our fault, not the visitor's.
    ///
    /// ```
    /// let e = web_net::Error::internal("report.parse");
    /// assert_eq!((e.status(), e.code()), (500, "report.parse"));
    /// ```
    #[must_use]
    pub fn internal(code: &'static str) -> Self {
        Self::new(500, code)
    }

    /// 503 Service Unavailable.
    ///
    /// ```
    /// let e = web_net::Error::unavailable("db.down");
    /// assert_eq!((e.status(), e.code()), (503, "db.down"));
    /// ```
    #[must_use]
    pub fn unavailable(code: &'static str) -> Self {
        Self::new(503, code)
    }

    /// Keeps `source` for the logs.
    ///
    /// ```
    /// use web_net::Error;
    ///
    /// let io = std::io::Error::other("no such file");
    /// let e = Error::internal("config.read").with_source(io);
    /// assert_eq!(e.source_ref().map(|s| s.to_string()), Some("no such file".to_owned()));
    /// ```
    #[must_use]
    pub fn with_source(mut self, source: impl Into<Source>) -> Self {
        self.source = Some(source.into());
        self
    }

    /// The status.
    ///
    /// ```
    /// assert_eq!(web_net::Error::conflict("cart.changed").status(), 409);
    /// ```
    #[must_use]
    pub const fn status(&self) -> u16 {
        self.status
    }

    /// The code.
    ///
    /// ```
    /// assert_eq!(web_net::Error::not_found("blog.no_post").code(), "blog.no_post");
    /// ```
    #[must_use]
    pub const fn code(&self) -> &'static str {
        self.code
    }

    /// The source, if one was kept.
    ///
    /// ```
    /// use web_net::Error;
    ///
    /// assert!(Error::internal("x").source_ref().is_none());
    /// let e = Error::internal("x").with_source(std::io::Error::other("disk gone"));
    /// assert!(e.source_ref().is_some());
    /// ```
    #[must_use]
    pub fn source_ref(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
        self.source.as_deref()
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Error")
            .field("status", &self.status)
            .field("code", &self.code)
            .field("source", &self.source.as_ref().map(|s| s.to_string()))
            .finish()
    }
}

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

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source
            .as_deref()
            .map(|s| s as &(dyn std::error::Error + 'static))
    }
}

impl From<crate::Denial> for Error {
    fn from(d: crate::Denial) -> Self {
        Self::new(d.status(), d.code())
    }
}

impl From<form_net::FormError> for Error {
    /// The form's status (400, 413, 415, 422, or 403 for a token) and code.
    fn from(e: form_net::FormError) -> Self {
        Self::new(e.status_hint(), e.code()).with_source(e)
    }
}

impl From<crate::RenderError> for Error {
    fn from(e: crate::RenderError) -> Self {
        Self::internal(e.code()).with_source(e)
    }
}

/// The handler result.
///
/// ```
/// use web_net::{App, Context, Error, Guest, Result, get};
///
/// fn show(cx: &mut Context<'_, Guest>) -> Result {
///     let id: u32 = cx.param_as("id")?;
///     if id == 0 {
///         return Err(Error::not_found("post.none"));
///     }
///     cx.text(200, "a post")
/// }
///
/// let app = App::builder().route(get("/posts/:id", show)).build()?;
/// let r = serve_net::testing::respond(&app, b"GET /posts/0 HTTP/1.1\r\nHost: localhost\r\n\r\n");
/// assert_eq!(r.status, 404);
/// # Ok::<(), web_net::BuildError>(())
/// ```
pub type Result<T = (), E = Error> = std::result::Result<T, E>;

/// One thing wrong with an application's declaration.
///
/// ```
/// let err = web_net::App::builder().base("blog").build().unwrap_err();
/// let p = &err.problems()[0];
/// assert_eq!(p.subject, "base");
/// assert!(p.message.contains("/blog"));
/// ```
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Problem {
    /// The route or setting it is about (`"GET /admin"`, `"host"`).
    pub subject: String,
    /// What is wrong and what to do.
    pub message: String,
}

/// Why [`Builder::build`](crate::Builder::build) refused: every problem
/// found, not only the first.
///
/// ```
/// let err = web_net::App::builder().base("blog").https_only().build().unwrap_err();
/// assert!(err.to_string().starts_with("the application has 2 problem(s)"));
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BuildError {
    problems: Vec<Problem>,
}

impl BuildError {
    pub(crate) fn new(problems: Vec<Problem>) -> Self {
        Self { problems }
    }

    /// The problems, in declaration order.
    ///
    /// ```
    /// let err = web_net::App::builder().base("blog").https_only().build().unwrap_err();
    /// let subjects: Vec<&str> = err.problems().iter().map(|p| p.subject.as_str()).collect();
    /// assert_eq!(subjects.len(), 2);
    /// assert!(subjects.contains(&"base"));
    /// ```
    #[must_use]
    pub fn problems(&self) -> &[Problem] {
        &self.problems
    }
}

impl fmt::Display for BuildError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "the application has {} problem(s):", self.problems.len())?;
        for p in &self.problems {
            write!(f, "\n  {}: {}", p.subject, p.message)?;
        }
        Ok(())
    }
}

impl std::error::Error for BuildError {}

/// The generic reason phrase shown for a status.
pub(crate) fn title(status: u16) -> &'static str {
    match status {
        400 => "Bad Request",
        401 => "Unauthorized",
        403 => "Forbidden",
        404 => "Not Found",
        405 => "Method Not Allowed",
        409 => "Conflict",
        410 => "Gone",
        413 => "Content Too Large",
        415 => "Unsupported Media Type",
        421 => "Misdirected Request",
        422 => "Unprocessable Content",
        429 => "Too Many Requests",
        500 => "Internal Server Error",
        501 => "Not Implemented",
        503 => "Service Unavailable",
        s if s < 500 => "Request Refused",
        _ => "Server Error",
    }
}

/// The generic message shown for a status.
pub(crate) fn message(status: u16) -> &'static str {
    match status {
        400 => "The request could not be understood.",
        401 => "Please sign in to continue.",
        403 => "You do not have access to this page.",
        404 => "The page was not found.",
        405 => "This page does not accept that kind of request.",
        421 => "This server does not serve that address.",
        422 => "The request could not be processed.",
        429 => "Too many requests. Please wait a moment and try again.",
        503 => "The service is unavailable right now. Please try again shortly.",
        s if s < 500 => "The request was refused.",
        _ => "Something went wrong on our side.",
    }
}

/// The built-in error page: fixed markup, the status, its title and message,
/// and the reference. Nothing from the request appears in it except the
/// reference, which web-net makes itself.
pub(crate) fn builtin_page(status: u16, reference: &str, out: &mut Vec<u8>) {
    let t = title(status);
    out.extend_from_slice(
        b"<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><title>",
    );
    push_status(status, out);
    out.push(b' ');
    out.extend_from_slice(t.as_bytes());
    out.extend_from_slice(
        b"</title><meta name=\"viewport\" content=\"width=device-width\"></head>\n<body><h1>",
    );
    out.extend_from_slice(t.as_bytes());
    out.extend_from_slice(b"</h1><p>");
    out.extend_from_slice(message(status).as_bytes());
    out.extend_from_slice(b"</p><p><small>Reference: ");
    out.extend_from_slice(reference.as_bytes());
    out.extend_from_slice(b"</small></p></body></html>\n");
}

/// The error reply for a client that prefers JSON: the same facts as the
/// page, no detail.
pub(crate) fn json_body(status: u16, reference: &str, out: &mut Vec<u8>) {
    out.extend_from_slice(b"{\"status\":");
    push_status(status, out);
    out.extend_from_slice(b",\"title\":\"");
    out.extend_from_slice(title(status).as_bytes());
    out.extend_from_slice(b"\",\"message\":\"");
    out.extend_from_slice(message(status).as_bytes());
    out.extend_from_slice(b"\",\"reference\":\"");
    // The reference is hex digits, a dash, and digits: nothing to escape.
    out.extend_from_slice(reference.as_bytes());
    out.extend_from_slice(b"\"}");
}

fn push_status(status: u16, out: &mut Vec<u8>) {
    let s = status.min(999);
    out.push(b'0' + (s / 100) as u8);
    out.push(b'0' + (s / 10 % 10) as u8);
    out.push(b'0' + (s % 10) as u8);
}

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

    #[test]
    fn test_status_clamped() {
        assert_eq!(Error::new(200, "x").status(), 500);
        assert_eq!(Error::new(302, "x").status(), 500);
        assert_eq!(Error::new(418, "x").status(), 418);
    }

    #[test]
    fn test_builtin_page_has_no_detail() {
        let mut out = Vec::new();
        builtin_page(404, "c7-r2", &mut out);
        let s = String::from_utf8(out).unwrap();
        assert!(s.contains("<title>404 Not Found</title>"));
        assert!(s.contains("Reference: c7-r2"));
    }

    #[test]
    fn test_build_error_lists_all() {
        let e = BuildError::new(vec![
            Problem {
                subject: "GET /".into(),
                message: "a".into(),
            },
            Problem {
                subject: "GET /b".into(),
                message: "b".into(),
            },
        ]);
        assert_eq!(e.problems().len(), 2);
        assert!(e.to_string().contains("2 problem(s)"));
    }
}