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
//! mini-web-server
//!
//! `mini-web-server` is a simple HTTP web server that uses a thread pool to respond asynchronously.  
//! Supports 2 commandline arguments - threads(no of threads) and port(port number). Default threads is 4 and default port is 7878.
//!
//! For example to run the server with 10 worker threads listening at port 8787, run the following command -
//! ./mini-web-server 10 8787

use std::{
    error::Error,
    fs,
    io::{prelude::*, BufReader},
    net::{TcpListener, TcpStream},
    sync::{mpsc, Arc, Mutex},
    thread,
    time::Duration,
};

const THREAD_SIZE: usize = 4;
const PORT: usize = 7878;

type Job = Box<dyn FnOnce() + Send + 'static>;

pub struct Config {
    pub thread_size: usize,
    pub port: usize,
}

impl Config {
    pub fn build(mut args: impl Iterator<Item = String>) -> Result<Config, &'static str> {
        args.next();

        let thread_size = match args.next() {
            Some(arg) => {
                if let Ok(arg) = arg.parse() {
                    arg
                } else {
                    return Err("Please type a number for number of worker threads.");
                }
            }
            None => {
                println!(
                    "No thread pool size specified. Using default {THREAD_SIZE} worker threads."
                );
                THREAD_SIZE
            }
        };

        let port = match args.next() {
            Some(arg) => {
                if let Ok(arg) = arg.parse() {
                    arg
                } else {
                    return Err("Please type a number for the TCP listening port higher than 1023. Default port is 7878.");
                }
            }
            None => {
                println!("No port number specified. Using default {PORT} worker threads.");
                PORT
            }
        };

        Ok(Config { thread_size, port })
    }
}

struct Worker {
    _id: usize,
    thread: Option<thread::JoinHandle<()>>,
}

impl Worker {
    pub fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        println!("Creating Worker {id}.");

        // create a thread that continuously loops checking the channel for jobs
        let thread = thread::spawn(move || loop {
            let msg = receiver.lock().unwrap().recv();
            match msg {
                Ok(job) => {
                    println!("Worker {id} receiver job; executing...");
                    job();
                }
                Err(_e) => {
                    println!("Worker {id} received disconnection request. Shutting down");
                    break;
                }
            }

            println!("Worker {id} completed execution.");
        });

        Worker {
            _id: id,
            thread: Some(thread),
        }
    }
}
pub struct ThreadPool {
    worker_threads: Vec<Worker>,
    sender: Option<mpsc::Sender<Job>>,
}

impl ThreadPool {
    /// Create a new ThreadPool.
    ///
    /// The size is the number of threads in the pool.
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    /// Todo: return Result<ThreadPool, PoolCreationError>
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        // create a mpsc channel to send closure function implmenting work to be executed by spawned thread
        let (sender, receiver) = mpsc::channel();

        //wrap receiver in Arc<Mutex<T>> to share between threads since mpsc is multiple producer single consumer
        let receiver = Arc::new(Mutex::new(receiver));

        println!("Setting up {size} workers...");
        let mut worker_threads = Vec::with_capacity(size);
        for id in 0..size {
            worker_threads.push(Worker::new(id + 1, Arc::clone(&receiver))); //create threads
        }
        ThreadPool {
            worker_threads,
            sender: Some(sender),
        }
    }

    pub fn execute<T>(&self, f: T)
    where
        T: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);
        self.sender.as_ref().unwrap().send(job).unwrap();
    }
}

impl Drop for ThreadPool {
    fn drop(&mut self) {
        //close the channel by dropping the sender end
        //so that the receiver end receives error to exit the worker thread's loop
        drop(self.sender.take());

        //shut down worker threads by calling join.
        for worker in &mut self.worker_threads {
            if let Some(thread) = worker.thread.take() {
                thread.join().unwrap();
            }
        }
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    //listen for tcp connections with TcpListner and bind to a port
    let address = format!("127.0.0.1:{}", config.port);
    let listener = TcpListener::bind(address)?;
    let thread_pool = ThreadPool::new(config.thread_size);

    //iterate through sequence of streams
    for stream in listener.incoming() {
        let stream = stream?;

        thread_pool.execute(|| {
            handle_connection(stream);
        });
    }

    Ok(())
}

fn handle_connection(mut stream: TcpStream) {
    let buf_reader = BufReader::new(&stream);
    let mut http_request = buf_reader.lines();
    let http_request_line = http_request.next().unwrap().unwrap();

    //handle routes
    let (status_line, file_name) = match &http_request_line[..] {
        "GET / HTTP/1.1" => ("HTTP/1.1 200 OK\r\n", "welcome.html"),
        "GET /sleep HTTP/1.1" => {
            thread::sleep(Duration::from_secs(5));
            ("HTTP/1.1 200 OK\r\n", "welcome.html")
        }
        _ => ("HTTP/1.1 400 NOT FOUND\r\n", "error.html"),
    };

    //print HTTP Request to console
    let http_request: Vec<_> = http_request
        .map(|result| result.unwrap())
        .take_while(|line| !line.is_empty())
        .collect();
    println!("Connection Established. HTTP Req => {http_request_line}\n{http_request:#?}");

    let contents = fs::read_to_string(file_name).unwrap();
    let content_length = contents.len();
    let response = format!("{status_line}Content-Length: {content_length}\r\n\r\n{contents}");

    stream.write_all(response.as_bytes()).unwrap();
}