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
#![doc = include_str!("../README.md")]

pub mod bytes;
pub mod error;
pub mod http;
pub mod threadpool;

use crate::{
    bytes::{Sink, Source},
    error::Error,
    http::{Request, Response},
    threadpool::{Executable, Threadpool},
};
use std::{
    convert::Infallible,
    io::BufReader,
    net::{TcpListener, ToSocketAddrs},
    sync::Arc,
};

/// A connection to pass to the thread pool
struct Connection<T, const STACK_SIZE: usize> {
    /// The connection handler
    pub handler: T,
    /// The receiving half of the stream
    pub rx: Source,
    /// The writing half of the stream
    pub tx: Sink,
    /// The connection queue for keep-alice TCP connections
    pub threadpool: Arc<Threadpool<Self, STACK_SIZE>>,
}
impl<T, const STACK_SIZE: usize> Connection<T, STACK_SIZE>
where
    T: Fn(&mut Source, &mut Sink) -> bool + Send + Sync + 'static,
{
    /// Handles the connection
    fn handle(mut self) -> Result<(), Error> {
        // Call the connection handler
        if (self.handler)(&mut self.rx, &mut self.tx) {
            // Reschedule the connection
            let threadpool = self.threadpool.clone();
            threadpool.dispatch(self)?;
        }
        Ok(())
    }
}
impl<T, const STACK_SIZE: usize> Executable for Connection<T, STACK_SIZE>
where
    T: Fn(&mut Source, &mut Sink) -> bool + Send + Sync + 'static,
{
    fn exec(self) {
        let _ = self.handle();
    }
}

/// A HTTP server
pub struct Server<T, const STACK_SIZE: usize = 65_536> {
    /// The thread pool to handle the incoming connections
    threadpool: Arc<Threadpool<Connection<T, STACK_SIZE>, STACK_SIZE>>,
    /// The connection handler
    handler: T,
}
impl<T, const STACK_SIZE: usize> Server<T, STACK_SIZE>
where
    T: Fn(&mut Source, &mut Sink) -> bool + Clone + Send + Sync + 'static,
{
    /// Creates a new server bound on the given address
    pub fn new(worker_max: usize, handler: T) -> Self {
        // Create threadpool and init self
        let threadpool: Threadpool<_, STACK_SIZE> = Threadpool::new(worker_max);
        Self { threadpool: Arc::new(threadpool), handler }
    }

    /// Dispatches a connection
    pub fn dispatch(&self, rx: Source, tx: Sink) -> Result<(), Error> {
        // Create and dispatch the job
        let job = Connection { handler: self.handler.clone(), rx, tx, threadpool: self.threadpool.clone() };
        self.threadpool.dispatch(job)
    }

    /// Listens on the given address and accepts forever
    pub fn accept<A>(self, address: A) -> Result<Infallible, Error>
    where
        A: ToSocketAddrs,
    {
        // Bind and listen
        let socket = TcpListener::bind(address)?;
        loop {
            // Accept and prepare connection
            let (stream, _) = socket.accept()?;
            let tx = stream.try_clone()?;
            let rx = BufReader::new(stream);

            // Dispatch connection
            let rx = Source::from_other(rx);
            self.dispatch(rx, tx.into())?;
        }
    }
}

/// An adapter to bridge a `source,sink`-handler to a `request->response`-handler
#[must_use]
pub fn reqresp<F>(source: &mut Source, sink: &mut Sink, handler: F) -> bool
where
    F: Fn(Request) -> Response + Send + Sync + 'static,
{
    // Read request
    let Ok(Some(request)) = Request::from_stream(source) else {
        return false;
    };

    // Handle request and write response
    let mut response = handler(request);
    let Ok(_) = response.to_stream(sink) else {
        return false;
    };

    // Mark connection as to-be-rescheduled
    !response.has_connection_close()
}