joist 1.0.0

A backend framework for Rust: routing, middleware, JSON, config and plugins, with no third-party dependencies.
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
use std::cell::Cell;
use std::io::{self, BufReader, BufWriter, Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

use crate::config::Config;
use crate::error::{Error, Result};
use crate::method::Method;
use crate::middleware::Middleware;
use crate::plugin::Plugin;
use crate::pool::ThreadPool;
use crate::request::Request;
use crate::response::Response;
use crate::router::Router;
use crate::status::Status;

const DEFAULT_MAX_BODY: usize = 2 * 1024 * 1024;
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(30);
const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);

/// Everything a worker thread needs, shared behind an `Arc`.
struct App {
    router: Router,
    middleware: Vec<Box<dyn Middleware>>,
    max_body: usize,
}

/// The two clocks a connection answers to.
#[derive(Clone, Copy)]
struct Timeouts {
    /// Bounds one read or write, so a connection that has gone silent is
    /// eventually dropped.
    idle: Option<Duration>,
    /// Bounds a whole exchange once it has started, which is the only thing that
    /// stops a client resetting the idle timeout forever.
    request: Option<Duration>,
}

/// An HTTP server, configured then bound.
pub struct Server {
    router: Router,
    middleware: Vec<Box<dyn Middleware>>,
    config: Config,
    workers: usize,
    max_body: usize,
    read_timeout: Option<Duration>,
    request_timeout: Option<Duration>,
}

impl Server {
    pub fn new(router: Router) -> Server {
        Server {
            router,
            middleware: Vec::new(),
            config: Config::new(),
            workers: default_workers(),
            max_body: DEFAULT_MAX_BODY,
            read_timeout: Some(DEFAULT_READ_TIMEOUT),
            request_timeout: Some(DEFAULT_REQUEST_TIMEOUT),
        }
    }

    /// Configuration handed to plugins as they install.
    pub fn config(mut self, config: Config) -> Server {
        self.config = config;
        self
    }

    pub fn with<M: Middleware>(mut self, middleware: M) -> Server {
        self.middleware.push(Box::new(middleware));
        self
    }

    /// Install a plugin now, before the listener exists.
    pub fn plugin<P: Plugin + 'static>(mut self, plugin: P) -> Server {
        let config = self.config.clone();
        Box::new(plugin).install(&mut self.router, &config);
        self
    }

    /// Worker threads. Defaults to four per core, since HTTP work is mostly
    /// waiting on sockets rather than burning CPU.
    pub fn workers(mut self, workers: usize) -> Server {
        self.workers = workers.max(1);
        self
    }

    pub fn max_body_bytes(mut self, bytes: usize) -> Server {
        self.max_body = bytes;
        self
    }

    /// How long a single read or write may wait for the peer. This is what
    /// drops a connection that has gone silent between keep-alive requests, and
    /// it is all it does: a client that sends one byte before every expiry
    /// resets it indefinitely, so [`Server::request_timeout`] is what bounds a
    /// request. `None` waits forever.
    pub fn read_timeout(mut self, timeout: Option<Duration>) -> Server {
        self.read_timeout = timeout;
        self
    }

    /// How long one request and its response may take in total, measured from
    /// the first byte of the request. It covers the request line, the header
    /// block, the body and the response write, so no amount of dribbling extends
    /// it. `None` removes the deadline and leaves only the per-read timeout,
    /// which a slow client can reset forever.
    ///
    /// The clock runs while a handler does, and spends what the handler spends.
    /// It cannot interrupt one: a handler that never returns holds its worker
    /// whatever this is set to.
    pub fn request_timeout(mut self, timeout: Option<Duration>) -> Server {
        self.request_timeout = timeout;
        self
    }

    /// Bind and start accepting. Returns immediately; the server runs on its
    /// own thread. Bind to port 0 to let the OS choose, then read `addr()`.
    pub fn bind<A: ToSocketAddrs>(self, addr: A) -> Result<Running> {
        let listener = TcpListener::bind(addr)?;
        let local_addr = listener.local_addr()?;

        // Non-blocking accept is what makes shutdown possible: a blocking
        // accept would sit there until the next connection arrived, however
        // long after the stop flag was set.
        listener.set_nonblocking(true)?;

        let app = Arc::new(App {
            router: self.router,
            middleware: self.middleware,
            max_body: self.max_body,
        });
        let shutdown = Arc::new(AtomicBool::new(false));
        let stop = Arc::clone(&shutdown);
        let workers = self.workers;
        let timeouts = Timeouts {
            idle: self.read_timeout,
            request: self.request_timeout,
        };

        let thread = thread::spawn(move || {
            let pool = ThreadPool::new(workers);
            while !stop.load(Ordering::Relaxed) {
                match listener.accept() {
                    Ok((stream, peer)) => {
                        let app = Arc::clone(&app);
                        pool.execute(move || serve(stream, peer, app, timeouts));
                    }
                    Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                        thread::sleep(Duration::from_millis(2));
                    }
                    Err(_) => {
                        // A single failed accept (fd limit, reset) is not worth
                        // taking the listener down for.
                        thread::sleep(Duration::from_millis(2));
                    }
                }
            }
            // Dropping the pool drains connections already being served.
        });

        Ok(Running {
            addr: local_addr,
            shutdown,
            thread: Some(thread),
        })
    }
}

/// A bound, running server.
pub struct Running {
    addr: SocketAddr,
    shutdown: Arc<AtomicBool>,
    thread: Option<JoinHandle<()>>,
}

impl Running {
    pub fn addr(&self) -> SocketAddr {
        self.addr
    }

    pub fn port(&self) -> u16 {
        self.addr.port()
    }

    /// A stop switch that can be moved elsewhere, for a signal handler.
    pub fn shutdown_handle(&self) -> Shutdown {
        Shutdown {
            flag: Arc::clone(&self.shutdown),
        }
    }

    /// Block until the server stops. Without a [`Shutdown`] held somewhere
    /// else, this blocks for the life of the process, which is what a plain
    /// server wants.
    pub fn wait(mut self) {
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }

    /// Stop accepting and wait for in-flight requests to finish.
    pub fn shutdown(mut self) {
        self.shutdown.store(true, Ordering::Relaxed);
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}

impl Drop for Running {
    fn drop(&mut self) {
        self.shutdown.store(true, Ordering::Relaxed);
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}

/// A cloneable stop switch for a [`Running`] server.
#[derive(Clone)]
pub struct Shutdown {
    flag: Arc<AtomicBool>,
}

impl Shutdown {
    pub fn stop(&self) {
        self.flag.store(true, Ordering::Relaxed);
    }
}

fn default_workers() -> usize {
    let cores = thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(2);
    (cores * 4).clamp(4, 256)
}

/// The deadline for one request and its response, shared by both halves of the
/// connection.
///
/// A socket timeout is per operation, so on its own it bounds nothing: a client
/// that sends a byte before every expiry resets it forever and keeps the worker.
/// A deadline is absolute, so the same client runs out of time. Both halves live
/// on the same worker thread, which is why a `Cell` is enough to share it.
#[derive(Clone)]
struct Deadline {
    limit: Option<Duration>,
    expires: Rc<Cell<Option<Instant>>>,
}

impl Deadline {
    fn new(limit: Option<Duration>) -> Deadline {
        Deadline {
            limit,
            expires: Rc::new(Cell::new(None)),
        }
    }

    /// Start the clock, unless it is already running.
    fn arm(&self) {
        if self.expires.get().is_some() {
            return;
        }
        // A limit the clock cannot represent is no practical deadline at all,
        // which is the same as not having asked for one.
        if let Some(at) = self
            .limit
            .and_then(|limit| Instant::now().checked_add(limit))
        {
            self.expires.set(Some(at));
        }
    }

    /// Stop the clock. The connection is between requests, not late.
    fn clear(&self) {
        self.expires.set(None);
    }

    /// Time left, `None` when no deadline is running, and `TimedOut` once there
    /// is none left.
    fn remaining(&self) -> io::Result<Option<Duration>> {
        match self.expires.get() {
            None => Ok(None),
            Some(at) => match at.checked_duration_since(Instant::now()) {
                Some(left) if !left.is_zero() => Ok(Some(left)),
                _ => Err(io::Error::new(
                    io::ErrorKind::TimedOut,
                    "request deadline exceeded",
                )),
            },
        }
    }
}

/// One half of a connection, bounded by the idle timeout on each operation and
/// by the request deadline across all of them.
struct Timed {
    stream: TcpStream,
    idle: Option<Duration>,
    deadline: Deadline,
}

impl Timed {
    fn new(stream: TcpStream, idle: Option<Duration>, deadline: Deadline) -> Timed {
        Timed {
            stream,
            idle,
            deadline,
        }
    }

    /// How long the next operation may block: whichever of the idle timeout and
    /// the time left on the deadline runs out first.
    fn window(&self) -> io::Result<Option<Duration>> {
        let window = match (self.idle, self.deadline.remaining()?) {
            (Some(idle), Some(left)) => Some(idle.min(left)),
            (Some(idle), None) => Some(idle),
            (None, left) => left,
        };
        // A zero timeout means "block forever" to the socket API and "out of
        // time" here, so ask for the smallest window instead of the largest.
        Ok(window.map(|d| {
            if d.is_zero() {
                Duration::from_millis(1)
            } else {
                d
            }
        }))
    }
}

impl Read for Timed {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let window = self.window()?;
        self.stream.set_read_timeout(window)?;
        let read = self.stream.read(buf)?;
        // The deadline runs from the first byte of a request, not from whenever
        // the connection happened to go idle waiting for one.
        if read > 0 {
            self.deadline.arm();
        }
        Ok(read)
    }
}

impl Write for Timed {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        // Normally the request already armed this. A pipelined request served
        // out of the buffer without a read did not, and a client that stops
        // reading its response holds a worker just as effectively.
        self.deadline.arm();
        let window = self.window()?;
        self.stream.set_write_timeout(window)?;
        self.stream.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.stream.flush()
    }
}

fn serve(stream: TcpStream, peer: SocketAddr, app: Arc<App>, timeouts: Timeouts) {
    // The socket inherits non-blocking from the listener on some platforms,
    // which would turn every read into a WouldBlock error.
    let _ = stream.set_nonblocking(false);
    let _ = stream.set_nodelay(true);

    let write_half = match stream.try_clone() {
        Ok(half) => half,
        Err(_) => return,
    };
    // One deadline across both halves: an exchange is bounded from the first
    // byte of the request to the last byte of the response, whichever end of it
    // the client chooses to stall.
    let deadline = Deadline::new(timeouts.request);
    let mut reader = BufReader::new(Timed::new(stream, timeouts.idle, deadline.clone()));
    let mut writer = BufWriter::new(Timed::new(write_half, timeouts.idle, deadline.clone()));

    loop {
        // Between requests the connection is idle rather than late, so only the
        // idle timeout applies until the next request's first byte lands.
        deadline.clear();

        match Request::read_from(&mut reader, app.max_body) {
            // Clean close between requests on a kept-alive connection.
            Ok(None) => break,
            Ok(Some(mut request)) => {
                request.peer = Some(peer);
                let keep_alive = request.keep_alive();
                let head_only = request.method == Method::Head;

                let response = handle(&app, &mut request);
                if response
                    .write_to(&mut writer, head_only, keep_alive)
                    .is_err()
                {
                    break;
                }
                if !keep_alive {
                    break;
                }
            }
            Err(err) => {
                // A connection that ran out of time, whether idle or past its
                // deadline, and one the peer reset, are not client errors worth
                // answering. Writing a 400 into one is worse than useless: if the
                // peer is still reading, it cannot tell that reply apart from the
                // response to a request it is about to send.
                if !is_disconnect(&err) {
                    let response = error_response(&err);
                    let _ = response.write_to(&mut writer, false, false);
                }
                break;
            }
        }
    }
}

fn handle(app: &App, request: &mut Request) -> Response {
    let mut short_circuit = None;
    for middleware in &app.middleware {
        if let Some(response) = middleware.before(request) {
            short_circuit = Some(response);
            break;
        }
    }

    let mut response = match short_circuit {
        Some(response) => response,
        None => {
            // A panicking handler should cost one request, not one worker, and
            // the client should not learn what panicked.
            match catch_unwind(AssertUnwindSafe(|| app.router.dispatch(request))) {
                Ok(response) => response,
                Err(_) => Response::error(Status::INTERNAL_SERVER_ERROR, "internal server error"),
            }
        }
    };

    // Reverse order, and always: a logger registered first still sees a request
    // that authentication rejected.
    for middleware in app.middleware.iter().rev() {
        response = middleware.after(request, response);
    }
    response
}

/// Whether the failure means the connection is gone rather than the request
/// being bad.
fn is_disconnect(err: &Error) -> bool {
    match err {
        Error::Io(e) => matches!(
            e.kind(),
            io::ErrorKind::TimedOut
                | io::ErrorKind::WouldBlock
                | io::ErrorKind::UnexpectedEof
                | io::ErrorKind::ConnectionReset
                | io::ErrorKind::ConnectionAborted
                | io::ErrorKind::BrokenPipe
        ),
        _ => false,
    }
}

/// Map a parse failure onto a response. The detail stays server-side, since it
/// is derived from attacker-controlled bytes.
fn error_response(err: &Error) -> Response {
    match err {
        Error::BodyTooLarge { .. } => {
            Response::error(Status::PAYLOAD_TOO_LARGE, "request body too large")
        }
        Error::Unsupported(what) => Response::error(Status::NOT_IMPLEMENTED, what),
        _ => Response::error(Status::BAD_REQUEST, "malformed request"),
    }
}

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

    #[test]
    fn default_worker_count_is_sane() {
        let n = default_workers();
        assert!((4..=256).contains(&n), "got {n}");
    }

    #[test]
    fn errors_map_to_the_right_status() {
        assert_eq!(
            error_response(&Error::BodyTooLarge { limit: 1 }).status,
            Status::PAYLOAD_TOO_LARGE
        );
        assert_eq!(
            error_response(&Error::Unsupported("chunked")).status,
            Status::NOT_IMPLEMENTED
        );
        assert_eq!(
            error_response(&Error::BadRequest("x".into())).status,
            Status::BAD_REQUEST
        );
    }

    #[test]
    fn parse_failures_do_not_leak_detail_to_the_client() {
        let res = error_response(&Error::BadRequest("secret internal detail".into()));
        let body = String::from_utf8(res.into_body().into_bytes().unwrap()).unwrap();
        assert!(!body.contains("secret internal detail"));
    }
}