web-net 0.9.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
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
//! Rendering: a template engine behind a trait, reading typed values
//! through a view.
//!
//! No JSON sits between the data and the engine. An engine resolves the
//! names a template uses to [`Key`]s once, when it compiles the template,
//! and reads values by key while it renders: a match or an index per value,
//! no allocation, no parsing. Escaping for each output context (HTML text,
//! attribute, URL, script) is the engine's job; web-net never escapes for it.

use std::fmt;

/// A template the engine resolved at build time. Its meaning belongs to the
/// engine.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TemplateId(pub u32);

/// A template engine.
///
/// The view type is the engine's: an engine that reads any view through
/// web-net's [`View`] trait (an adapter for a dynamic engine) uses
/// `type View = dyn View`; an engine that compiles templates against the
/// application's own types uses that type, and reads it directly.
///
/// ```
/// use web_net::{Output, Render, RenderError, TemplateId, Value, View};
///
/// /// Writes the view's `title` field and nothing else.
/// struct TitleOnly;
///
/// impl Render for TitleOnly {
///     type View<'a> = dyn View + 'a;
///     fn template(&self, name: &str) -> Option<TemplateId> {
///         (name == "title").then_some(TemplateId(0))
///     }
///     fn render(&self, _t: TemplateId, view: &dyn View, out: &mut Output<'_>) -> Result<(), RenderError> {
///         let key = view.shape().key("title").ok_or(RenderError::new("demo.no_title"))?;
///         match view.get(key) {
///             Value::Text(t) => out.write(t.as_bytes()), // a real engine escapes here
///             _ => Err(RenderError::new("demo.not_text")),
///         }
///     }
/// }
/// ```
pub trait Render: Send + Sync + 'static {
    /// What a handler hands the engine, for any lifetime of the data it
    /// borrows: `dyn View + 'a` for a dynamic engine, the application's own
    /// type (`Page`, or `Page<'a>`) for a typed one.
    type View<'a>: ?Sized;

    /// Resolves a template name. Called at build time for every template a
    /// route names, so an unknown name stops the application from starting.
    fn template(&self, name: &str) -> Option<TemplateId>;

    /// Renders `template` against `view` into `out`.
    ///
    /// # Errors
    ///
    /// A [`RenderError`]; the request is answered with a 500 error page and
    /// the detail goes to the events, never to the visitor.
    fn render(
        &self,
        template: TemplateId,
        view: &Self::View<'_>,
        out: &mut Output<'_>,
    ) -> Result<(), RenderError>;

    /// Writes the page for a refusal or an error, from the facts web-net
    /// shows a visitor. `Ok(false)` (the default) leaves it to web-net's
    /// built-in page; so does an error, which is not reported further.
    ///
    /// # Errors
    ///
    /// A [`RenderError`]; web-net then sends its built-in page.
    fn error_page(&self, page: &ErrorPage<'_>, out: &mut Output<'_>) -> Result<bool, RenderError> {
        let _ = (page, out);
        Ok(false)
    }
}

/// The engine of an application without one: `Cx::render` answers 500
/// `render.no_engine`, and error pages are web-net's own.
#[derive(Clone, Copy, Debug, Default)]
pub struct NoRender;

impl Render for NoRender {
    type View<'a> = dyn View + 'a;

    fn template(&self, _name: &str) -> Option<TemplateId> {
        None
    }

    fn render(
        &self,
        _template: TemplateId,
        _view: &(dyn View + '_),
        _out: &mut Output<'_>,
    ) -> Result<(), RenderError> {
        Err(RenderError::new("render.no_engine"))
    }
}

/// What an error page shows: the status, its generic title and message, and
/// the request's reference. Never the code or the cause.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ErrorPage<'a> {
    /// The status (`404`).
    pub status: u16,
    /// Its generic title (`Not Found`).
    pub title: &'a str,
    /// Its generic message.
    pub message: &'a str,
    /// The request's reference, as the visitor quotes it.
    pub reference: &'a str,
}

impl<'a> ErrorPage<'a> {
    /// An error page's facts, for an engine's own tests (web-net makes the
    /// real ones).
    ///
    /// ```
    /// let p = web_net::ErrorPage::new(404, "Not Found", "The page was not found.", "1a-2");
    /// assert_eq!((p.status, p.reference), (404, "1a-2"));
    /// ```
    #[must_use]
    pub const fn new(status: u16, title: &'a str, message: &'a str, reference: &'a str) -> Self {
        Self {
            status,
            title,
            message,
            reference,
        }
    }
}

/// A field or method of a view, resolved from a name by its [`Shape`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Key(pub u32);

/// Identifies a shape so an engine can cache name resolutions per shape.
/// [`ShapeId::ANONYMOUS`] says "do not cache".
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ShapeId(pub u64);

impl ShapeId {
    /// A shape whose keys may differ between instances: resolve names per
    /// render.
    pub const ANONYMOUS: Self = Self(0);
}

/// The names a view answers.
pub trait Shape {
    /// The shape's identity. Two views with the same id resolve every name
    /// to the same key.
    fn id(&self) -> ShapeId;

    /// The key for a field or method name.
    fn key(&self, name: &str) -> Option<Key>;
}

/// What a template reads.
pub trait View {
    /// The names this view answers.
    fn shape(&self) -> &dyn Shape;

    /// A field by key. The hot path: no allocation.
    fn get(&self, key: Key) -> Value<'_>;

    /// A method with arguments (`variations.options("size")`). The result is
    /// passed to `with`, so it may borrow a value computed for the call.
    /// The default answers [`Value::Absent`].
    fn call(&self, key: Key, args: &[Value<'_>], with: &mut dyn FnMut(Value<'_>)) {
        let _ = (key, args);
        with(Value::Absent);
    }
}

/// A sequence a template can loop over.
pub trait List {
    /// The number of items.
    fn len(&self) -> usize;

    /// Whether the list is empty.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// An item, or [`Value::Absent`] past the end.
    fn get(&self, index: usize) -> Value<'_>;
}

/// Markup that is trusted as it is: written without escaping. Making one is
/// a visible, searchable step (`SafeHtml::trusted`), and the place to
/// sanitize is where the markup was produced (when content is saved), not
/// here.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct SafeHtml<'a>(&'a str);

impl<'a> SafeHtml<'a> {
    /// Marks `html` as trusted markup.
    #[must_use]
    pub const fn trusted(html: &'a str) -> Self {
        Self(html)
    }

    /// The markup.
    #[must_use]
    pub const fn as_str(&self) -> &'a str {
        self.0
    }
}

impl fmt::Debug for SafeHtml<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "SafeHtml({} bytes)", self.0.len())
    }
}

/// One value read from a view.
#[non_exhaustive]
#[derive(Clone, Copy)]
pub enum Value<'a> {
    /// Nothing here (a missing field, an empty optional).
    Absent,
    /// A boolean.
    Bool(bool),
    /// An integer.
    Int(i64),
    /// A float.
    Float(f64),
    /// Text, escaped for its context by the engine.
    Text(&'a str),
    /// Trusted markup, written as it is.
    Html(SafeHtml<'a>),
    /// A computed value (money, a date), written as text and escaped.
    Display(&'a dyn fmt::Display),
    /// A nested object.
    View(&'a dyn View),
    /// A sequence.
    List(&'a dyn List),
}

impl Value<'_> {
    /// Whether this is [`Value::Absent`].
    #[must_use]
    pub const fn is_absent(&self) -> bool {
        matches!(self, Self::Absent)
    }

    /// The text, for [`Value::Text`].
    #[must_use]
    pub const fn as_text(&self) -> Option<&str> {
        match self {
            Self::Text(t) => Some(t),
            _ => None,
        }
    }
}

impl fmt::Debug for Value<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Absent => f.write_str("Absent"),
            Self::Bool(b) => write!(f, "Bool({b})"),
            Self::Int(i) => write!(f, "Int({i})"),
            Self::Float(x) => write!(f, "Float({x})"),
            Self::Text(t) => write!(f, "Text({t:?})"),
            Self::Html(h) => write!(f, "{h:?}"),
            Self::Display(_) => f.write_str("Display(..)"),
            Self::View(_) => f.write_str("View(..)"),
            Self::List(l) => write!(f, "List({} items)", l.len()),
        }
    }
}

/// A ready-made view over a slice of named values, for small pages, error
/// pages, and tests. Its shape is anonymous: names are looked up per render.
///
/// ```
/// use web_net::{Fields, Value, View};
///
/// let view = Fields(&[("title", Value::Text("Hello")), ("count", Value::Int(3))]);
/// let key = view.shape().key("count").unwrap();
/// assert!(matches!(view.get(key), Value::Int(3)));
/// ```
#[derive(Clone, Copy, Debug)]
pub struct Fields<'a>(pub &'a [(&'a str, Value<'a>)]);

impl Shape for Fields<'_> {
    fn id(&self) -> ShapeId {
        ShapeId::ANONYMOUS
    }

    fn key(&self, name: &str) -> Option<Key> {
        self.0
            .iter()
            .position(|(n, _)| *n == name)
            .map(|i| Key(i as u32))
    }
}

impl View for Fields<'_> {
    fn shape(&self) -> &dyn Shape {
        self
    }

    fn get(&self, key: Key) -> Value<'_> {
        self.0
            .get(key.0 as usize)
            .map_or(Value::Absent, |(_, v)| *v)
    }
}

/// Where an engine writes: the reply body, reused between requests, with a
/// size budget.
pub struct Output<'a> {
    buf: &'a mut Vec<u8>,
    limit: usize,
}

impl<'a> Output<'a> {
    /// An output over `buf`, refusing to grow past `limit` bytes.
    #[must_use]
    pub fn new(buf: &'a mut Vec<u8>, limit: usize) -> Self {
        Self { buf, limit }
    }

    /// Appends bytes.
    ///
    /// # Errors
    ///
    /// `render.too_large` when the page would pass the budget.
    #[inline]
    pub fn write(&mut self, bytes: &[u8]) -> Result<(), RenderError> {
        if self.buf.len() + bytes.len() > self.limit {
            return Err(RenderError::new("render.too_large"));
        }
        self.buf.extend_from_slice(bytes);
        Ok(())
    }

    /// Appends a string.
    ///
    /// # Errors
    ///
    /// As [`write`](Self::write).
    #[inline]
    pub fn write_str(&mut self, s: &str) -> Result<(), RenderError> {
        self.write(s.as_bytes())
    }

    /// The buffer itself, for an engine that writes into a `Vec<u8>`. The
    /// budget is checked when the engine returns: a page past it is refused
    /// with `render.too_large`.
    pub fn buffer(&mut self) -> &mut Vec<u8> {
        self.buf
    }

    /// Whether the budget was passed (checked after the engine returns).
    pub(crate) fn over(&self) -> bool {
        self.buf.len() > self.limit
    }

    /// Bytes written so far.
    #[must_use]
    pub fn len(&self) -> usize {
        self.buf.len()
    }

    /// Whether nothing was written yet.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.buf.is_empty()
    }

    /// The bytes still allowed.
    #[must_use]
    pub fn remaining(&self) -> usize {
        self.limit.saturating_sub(self.buf.len())
    }
}

impl fmt::Debug for Output<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Output")
            .field("len", &self.buf.len())
            .field("limit", &self.limit)
            .finish()
    }
}

/// A render failure. The code is stable; the detail is for logs only.
pub struct RenderError {
    code: &'static str,
    detail: Option<Box<str>>,
}

impl RenderError {
    /// A failure with a stable code (`"luminess.missing_block"`).
    #[must_use]
    pub const fn new(code: &'static str) -> Self {
        Self { code, detail: None }
    }

    /// Adds a detail for the logs (a template name, a line number).
    #[must_use]
    pub fn with_detail(mut self, detail: impl Into<Box<str>>) -> Self {
        self.detail = Some(detail.into());
        self
    }

    /// The code.
    #[must_use]
    pub const fn code(&self) -> &'static str {
        self.code
    }

    /// The detail, if any.
    #[must_use]
    pub fn detail(&self) -> Option<&str> {
        self.detail.as_deref()
    }
}

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

impl fmt::Display for RenderError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.detail {
            Some(d) => write!(f, "render failed ({}): {d}", self.code),
            None => write!(f, "render failed ({})", self.code),
        }
    }
}

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

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

    #[test]
    fn test_output_budget() {
        let mut buf = Vec::new();
        let mut out = Output::new(&mut buf, 4);
        out.write(b"abc").unwrap();
        assert_eq!(out.remaining(), 1);
        assert_eq!(out.write(b"de").unwrap_err().code(), "render.too_large");
        out.write(b"d").unwrap();
        assert_eq!(buf, b"abcd");
    }

    #[test]
    fn test_fields_view() {
        let v = Fields(&[("a", Value::Bool(true)), ("b", Value::Text("x"))]);
        assert_eq!(v.shape().key("b"), Some(Key(1)));
        assert_eq!(v.shape().key("c"), None);
        assert!(v.get(Key(9)).is_absent());
        assert_eq!(v.get(Key(1)).as_text(), Some("x"));
        let mut got = false;
        v.call(Key(0), &[], &mut |x| got = x.is_absent());
        assert!(got);
    }
}