octane 0.1.2

A web server built from the ground up.
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
use crate::constants::closures_lock;
use crate::default;
use colored::*;
use core::time::Duration;
use std::ffi::OsStr;
use std::path::PathBuf;
#[cfg(feature = "rustls")]
use tokio_rustls::rustls::{
    internal::pemfile::{certs, rsa_private_keys},
    Certificate, PrivateKey,
};

/// Ssl struct, contains the key and cert
/// required to setup SSL with the selected
/// feature (rustls or openssl)
///
/// By default, the Config struct has an ssl field so
/// you don't have to use it directly but if you want
/// to then you can and then append it to the config by
/// [`with_ssl_config()`]()
///
/// ```no_run
/// use octane::server::Octane;
/// use std::time::Duration;
/// use octane::config::{Config, Ssl};
///
/// let mut app = Octane::new();
/// let mut ssl_config = Ssl::new();
/// ssl_config.key("templates/key.pem");
/// app.with_ssl_config(ssl_config);
/// ```
/// The ssl struct has three fields
///
/// - `key`: Location of the private key file, should have the
/// extension as .pem
/// - `cert`: Location of the certificate file, should have the
/// extension as .pem
/// - `port`: The port where TLS should listen, is 443 by defaults
#[derive(Clone)]
pub struct Ssl {
    pub key: PathBuf,
    pub cert: PathBuf,
    pub port: u16,
}

impl Ssl {
    /// Returns a new Ssl struct instance with default port
    /// 443
    pub fn new() -> Self {
        Ssl {
            key: PathBuf::new(),
            cert: PathBuf::new(),
            port: 443,
        }
    }
    /// Mutates the Ssl struct and sets the private key path
    ///
    /// # Example
    ///
    /// ```no_run
    /// use octane::config::OctaneConfig;
    ///
    /// let mut config = OctaneConfig::new();
    /// config
    ///    .ssl
    ///    .key("templates/key.pem");
    /// ```
    pub fn key(&mut self, path: &str) -> &mut Self {
        self.key = PathBuf::from(path);
        self
    }
    /// Mutates the Ssl struct and sets the SSL certificate path
    ///
    /// # Example
    ///
    /// ```no_run
    /// use octane::config::OctaneConfig;
    ///
    /// let mut config = OctaneConfig::new();
    /// config
    ///    .ssl
    ///    .cert("templates/cert.pem");
    /// ```
    pub fn cert(&mut self, path: &str) -> &mut Self {
        self.cert = PathBuf::from(path);
        self
    }
    /// Validates the certs and keys by checking their extensions
    pub fn validate(&self) {
        let key_ext = self
            .key
            .as_path()
            .extension()
            .and_then(OsStr::to_str)
            .unwrap_or("");
        let cert_ext = self
            .cert
            .as_path()
            .extension()
            .and_then(OsStr::to_str)
            .unwrap_or("");
        if key_ext != "pem" && cert_ext != "pem" {
            panic!("Invalid key/cert file, {:?}", "bad extension")
        }
    }
}

/// An independent OctaneConfig struct that can be used
/// seperately from the app structure and then be appended
/// to it.
///
/// **Note**: If you won't push the independently made config
/// then the configurations won't take place, make sure
/// to push them to the main server struct like the following
///
/// ```no_run
/// use octane::server::Octane;
/// use octane::config::OctaneConfig;
///
/// let mut app = Octane::new();
/// let mut config = OctaneConfig::new();
/// app.with_config(config);
/// ```
///
/// The config holds the values for various configurable
/// item. If no config is specfied then defaults are used.
///
/// # Config parameters
///
/// - `keep_alive`: The duration for keep alive requests.
/// - `ssl`: An instance of the `Ssl` struct to store the
/// values of key and certificates.
/// - `worker_threads`: The number of worker threads to use
/// while handling requests, by default this value is equal
/// to the number of cores available to the system, this is
/// later on used for setting number for the
/// [`core_threads`](https://docs.rs/tokio/0.2.13/tokio/runtime/struct.Builder.html#method.core_threads)
/// method
pub struct OctaneConfig {
    pub keep_alive: Option<Duration>,
    pub ssl: Ssl,
    pub file_404: Option<PathBuf>,
    pub worker_threads: Option<usize>,
}

/// Shared config trait which allows us to use the config
/// methods on the Octane server struct too as it has a
/// config field by default
pub trait Config {
    /// Sets the keepalive duration for a keepalive request,
    /// by default, a 5 second keep alive is set
    /// # Example
    ///
    /// ```no_run
    /// use octane::config::{OctaneConfig, Config};
    /// use std::time::Duration;
    ///
    /// let mut config = OctaneConfig::new();
    /// config.set_keepalive(Duration::new(5, 0));
    /// ```
    ///
    /// Or with Octane struct
    ///
    /// ```no_run
    /// use octane::server::Octane;
    /// use std::time::Duration;
    /// use octane::config::Config;
    ///
    /// let mut app = Octane::new();
    /// app.set_keepalive(Duration::new(5, 0));
    /// ```
    fn set_keepalive(&mut self, duration: Duration);
    /// Sets the path of the file which is to be served
    /// when the server sends a 404 to the client
    ///
    /// # Example
    ///
    /// ```no_run
    /// use octane::config::{OctaneConfig, Config};
    /// use std::time::Duration;
    ///
    /// let mut config = OctaneConfig::new();
    /// config.set_404_file("templates/error.html");
    /// ```
    ///
    /// Or with Octane struct
    ///
    /// ```no_run
    /// use octane::server::Octane;
    /// use std::time::Duration;
    /// use octane::config::Config;
    ///
    /// let mut app = Octane::new();
    /// app.set_404_file("templates/error.html");
    /// ```
    fn set_404_file(&mut self, dir_name: &'static str);
    /// Replaces the current ssl config with the one
    /// specified in the arguments
    ///
    /// # Example
    ///
    /// ```no_run
    /// use octane::config::{OctaneConfig, Config, Ssl};
    /// use std::time::Duration;
    ///
    /// let mut config = OctaneConfig::new();
    /// let mut ssl_config = Ssl::new();
    /// ssl_config.key("templates/key.pem");
    /// config.set_404_file("templates/error.html");
    /// ```
    ///
    /// Or with Octane struct
    ///
    /// ```no_run
    /// use octane::server::Octane;
    /// use std::time::Duration;
    /// use octane::config::{Config, Ssl};
    ///
    /// let mut app = Octane::new();
    /// let mut ssl_config = Ssl::new();
    /// ssl_config.key("templates/key.pem");
    /// app.with_ssl_config(ssl_config);
    /// ```
    fn with_ssl_config(&mut self, ssl_conf: Ssl);
    /// Returns the Ssl instance of the config and
    /// sets the port number for TLS
    ///
    /// # Example
    ///
    /// ```no_run
    /// use octane::config::{OctaneConfig, Config};
    /// use std::time::Duration;
    ///
    /// let mut config = OctaneConfig::new();
    /// config
    ///     .ssl(443)
    ///     .key("key.pem")
    ///     .cert("cert.pem");
    /// ```
    ///
    /// Or with Octane struct
    ///
    /// ```no_run
    /// use octane::server::Octane;
    /// use std::time::Duration;
    /// use octane::config::Config;
    ///
    /// let mut app = Octane::new();
    /// app
    ///     .ssl(443)
    ///     .key("key.pem")
    ///     .cert("cert.pem");
    /// ```
    fn ssl(&mut self, port: u16) -> &mut Ssl;
}
/// Octane config which can be used independently to
/// configure the server settings.
///
/// To apply the settings to the main struct,
/// make sure you run `app.with_config(config);` on the
/// main struct where config is the custom config you created
impl OctaneConfig {
    /// Creates a new config instance with default values
    pub fn new() -> Self {
        OctaneConfig {
            ssl: Ssl::new(),
            keep_alive: Some(Duration::from_secs(5)),
            worker_threads: None,
            file_404: None,
        }
    }
    /// Appends a settings instance to self
    pub fn append(&mut self, settings: Self) {
        self.ssl = settings.ssl;
        self.keep_alive = settings.keep_alive;
    }

    /// Sets the number of worker threads, this is settings
    /// which will be applied to the `core_threads` method
    /// on the runtime builder struct
    /// https://docs.rs/tokio/0.2.13/tokio/runtime/struct.Builder.html#method.core_threads
    pub fn worker_threads(&mut self, threads: usize) -> &mut Self {
        self.worker_threads = Some(threads);
        self
    }

    /// Get the certs as a Vec<Certificate>, a user will not have to
    /// use this directly, this is used and done for them
    #[cfg(feature = "rustls")]
    pub fn get_cert(&self) -> std::io::Result<Vec<Certificate>> {
        self.ssl.validate();
        let mut buf = std::io::BufReader::new(std::fs::File::open(&self.ssl.cert)?);
        certs(&mut buf)
            .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "Invalid Certs"))
    }
    /// Get the private key as a Vec<PrivateKey>, a user will not have to
    /// use this directly
    #[cfg(feature = "rustls")]
    pub fn get_key(&self) -> std::io::Result<Vec<PrivateKey>> {
        self.ssl.validate();
        let mut buf = std::io::BufReader::new(std::fs::File::open(&self.ssl.key)?);
        rsa_private_keys(&mut buf)
            .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "Invalid Key"))
    }

    pub fn startup_string(&self, ssl: bool, port: u16) -> String {
        let mut final_string = String::new();
        final_string.push_str(
            format!(
                "\n\r{} {}\n\r\n{}\n\n",
                "Starting".bold().blue(),
                "Octane".green().bold(),
                "Configurations".red().bold()
            )
            .as_str(),
        );
        if let Some(x) = self.keep_alive {
            final_string.push_str(
                format!(
                    "{}: {}s\n",
                    "-> Keep-alive".blue(),
                    x.as_secs_f64().to_string().green(),
                )
                .as_str(),
            );
        } else {
            final_string.push_str(
                format!("{}: {}\n", "-> Keep-alive".blue(), "Disabled".green(),).as_str(),
            );
        }
        if let Some(x) = self.worker_threads {
            final_string.push_str(
                format!(
                    "{}: {}\n",
                    "-> Worker-threads".blue(),
                    x.to_string().green(),
                )
                .as_str(),
            );
        } else {
            final_string.push_str(
                format!(
                    "{}: {}\n",
                    "-> Worker-threads".blue(),
                    "Number of cores available in the CPU".green(),
                )
                .as_str(),
            );
        }
        if ssl {
            final_string.push_str(
                format!(
                    "{}: {} {}\n",
                    "-> TLS".blue(),
                    "enabled at".green(),
                    self.ssl.port.to_string().red().bold()
                )
                .as_str(),
            );
        } else {
            final_string.push_str(format!("{}: {} \n", "TLS".red(), "disabled".green()).as_str());
        }
        closures_lock(|map| {
            final_string.push_str(
                format!(
                    "{}: {} paths\n",
                    "-> Serving".blue(),
                    map.len().to_string().red().bold()
                )
                .as_str(),
            );
        });
        final_string.push_str(
            format!(
                "\n{} at {}:{}\n",
                "Listening".red(),
                "localhost".blue(),
                port.to_string().red().bold()
            )
            .as_str(),
        );

        final_string
    }
}

default!(OctaneConfig);
default!(Ssl);

impl Config for OctaneConfig {
    fn set_keepalive(&mut self, duration: Duration) {
        self.keep_alive = Some(duration);
    }
    fn set_404_file(&mut self, dir_name: &'static str) {
        self.file_404 = Some(PathBuf::from(dir_name));
    }
    fn with_ssl_config(&mut self, ssl_conf: Ssl) {
        self.ssl.key = ssl_conf.key;
        self.ssl.cert = ssl_conf.cert;
    }
    fn ssl(&mut self, port: u16) -> &mut Ssl {
        self.ssl.port = port;
        &mut self.ssl
    }
}