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
//! Helpers for integration-testing Kvarn.
//!
//! Here, you can easily spin up a new server on a random non-used port
//! and send a request to it in under 5 lines.

#![deny(clippy::all, clippy::perf, clippy::pedantic)]
#![allow(clippy::missing_panics_doc)]

use kvarn::prelude::*;
use rustls::{
    pki_types::{CertificateDer, PrivateKeyDer},
    sign::CertifiedKey,
};

macro_rules! impl_methods {
    ($($method: ident $name: ident),*) => {
        $(
            /// Make a request to `path` with the selected method.
            pub fn $method(&self, path: impl AsRef<str>) -> reqwest::RequestBuilder {
                let client = self.client().build().unwrap();
                client.request(reqwest::Method::$name, self.url(path))
            }
        )*
    };
}

/// A port returned by [`ServerBuilder::run`] to connect to.
pub struct Server {
    server: Arc<shutdown::Manager>,
    certificate: Option<CertifiedKey>,
    port: u16,
    handover: Option<PathBuf>,
    // also update Debug implementation when adding fields
}
impl Server {
    impl_methods!(get GET, post POST, put PUT, delete DELETE, head HEAD, options OPTIONS, connect CONNECT, patch PATCH, trace TRACE);

    /// Get a [`reqwest::ClientBuilder`] with the [`Self::cert`] accepted.
    pub fn client(&self) -> reqwest::ClientBuilder {
        let mut client = reqwest::Client::builder();
        if let Some(cert) = self.cert() {
            let cert = reqwest::Certificate::from_der(cert).unwrap();
            client = client.add_root_certificate(cert);
        };
        client
    }
    /// Builds a URL to the server with `path`.
    pub fn url(&self, path: impl AsRef<str>) -> reqwest::Url {
        let added_root = if path.as_ref().starts_with('/') {
            ""
        } else {
            "/"
        };
        let string = format!(
            "http{}://localhost:{}{}{}",
            self.cert().map_or("", |_| "s"),
            self.port(),
            added_root,
            path.as_ref()
        );
        reqwest::Url::parse(&string).unwrap()
    }
    /// Gets the port of the TCP server.
    #[must_use]
    pub fn port(&self) -> u16 {
        self.port
    }
    /// Gets the certificate, if any.
    /// This dictates whether or not HTTPS should be on.
    #[must_use]
    pub fn cert(&self) -> Option<&CertificateDer<'static>> {
        self.certificate.as_ref().map(|key| &key.cert[0])
    }

    /// Gets a [`shutdown::Manager`] which is [`Send`].
    ///
    /// You can shut down Kvarn from another thread using this.
    #[must_use]
    pub fn get_shutdown_manager(&self) -> Arc<shutdown::Manager> {
        Arc::clone(&self.server)
    }
}
impl Debug for Server {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut s = f.debug_struct(utils::ident_str!(Server));
        utils::fmt_fields!(
            s,
            (self.server),
            (self.certificate, &"[internal certificate]".as_clean()),
            (self.port),
            (self.handover)
        );
        s.finish()
    }
}
impl Drop for Server {
    fn drop(&mut self) {
        self.server.shutdown();
    }
}

/// A builder struct for starting a test [`Server`].
#[must_use = "run the server"]
pub struct ServerBuilder {
    https: bool,
    extensions: Extensions,
    options: host::Options,
    path: Option<CompactString>,
    handover: Option<(PathBuf, Option<u16>)>,
    cert: Option<CertifiedKey>,
}
impl ServerBuilder {
    /// Creates a new builder with `extensions` and `options`,
    /// with HTTPS enabled. To disable this, call [`Self::http`].
    /// Use `Self::default()` for a default configuration.
    ///
    /// Also see the [`From`] implementations for this struct.
    ///
    /// The inner [`Extensions`] can be modified with [`Self::with_extensions`]
    /// and the [`host::Options`] with [`Self::with_options`]
    pub fn new(extensions: Extensions, options: host::Options) -> Self {
        let _ = env_logger::Builder::new()
            .parse_filters("rustls=warn,debug")
            .is_test(true)
            .parse_default_env()
            .try_init();
        Self {
            https: true,
            extensions,
            options,
            path: None,
            handover: None,
            cert: None,
        }
    }
    /// Disables HTTPS.
    pub fn http(mut self) -> Self {
        self.https = false;
        self
    }
    /// Modifies the internal [`Extensions`] with `mutation`.
    /// If you already have a [`Extensions`], use [`From`].
    pub fn with_extensions(mut self, mutation: impl Fn(&mut Extensions)) -> Self {
        mutation(&mut self.extensions);
        self
    }
    /// Modifies the internal [`host::Options`] with `mutation`.
    /// If you already have a [`host::Options`], use [`From`].
    pub fn with_options(mut self, mutation: impl Fn(&mut host::Options)) -> Self {
        mutation(&mut self.options);
        self
    }
    /// Sets the [`Host::path`] of this server.
    pub fn path(mut self, path: impl AsRef<str>) -> Self {
        self.path = Some(path.as_ref().to_compact_string());
        self
    }

    /// Enables [handover](https://kvarn.org/shutdown-handover.) for this server.
    /// If you are starting the server which will take over the requests, use [`Self::handover_from`] instead.
    /// The communication socket is at `path`.
    pub fn enable_handover(mut self, path: impl AsRef<Path>) -> Self {
        self.handover = Some((path.as_ref().to_path_buf(), None));
        self
    }
    /// "Steals" the requests from `previous`.
    ///
    /// # Panics
    ///
    /// Will panic if [`Self::enable_handover`] wasn't called on `previous`'s [`ServerBuilder`].
    pub fn handover_from(mut self, previous: &Server) -> Self {
        self.handover = Some((
            previous
                .handover
                .clone()
                .expect("Previous server didn't have handover configured!"),
            Some(previous.port()),
        ));
        println!("Previous port {}", previous.port());
        self.cert = previous.certificate.clone();
        self
    }

    async fn test_port_availability(port: u16) -> io::Result<()> {
        match tokio::net::TcpStream::connect(SocketAddr::new(
            IpAddr::V4(net::Ipv4Addr::LOCALHOST),
            port,
        ))
        .await
        {
            Err(e) => match e.kind() {
                io::ErrorKind::ConnectionRefused => Ok(()),
                _ => panic!(
                    "Spurious IO error while checking port availability: {:?}",
                    e
                ),
            },
            Ok(_) => Err(io::Error::new(
                io::ErrorKind::AddrInUse,
                "Something is listening on the port!",
            )),
        }
    }
    async fn get_port() -> u16 {
        use rand::prelude::*;
        let mut rng = rand::thread_rng();
        let port_range = rand::distributions::Uniform::new(4096, 61440);

        loop {
            let port = port_range.sample(&mut rng);

            if Self::test_port_availability(port).await.is_err() {
                continue;
            }
            return port;
        }
    }

    /// Starts a Kvarn server with the current configuraion.
    ///
    /// The returned [`Server`] can make requests to the server, streamlining
    /// the process of testing Kvarn.
    pub async fn run(self) -> Server {
        let Self {
            https,
            extensions,
            options,
            path,
            handover,
            cert,
        } = self;

        let path = path.as_deref().unwrap_or("tests");

        let (mut host, certified_key) = if https {
            let key = cert.unwrap_or_else(|| {
                let self_signed_cert =
                    rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
                let cert = CertificateDer::from(self_signed_cert.serialize_der().unwrap());

                let pk = PrivateKeyDer::Pkcs8(self_signed_cert.serialize_private_key_der().into());
                let pk = rustls::crypto::ring::sign::any_supported_type(&pk).unwrap();
                CertifiedKey::new(vec![cert], pk)
            });

            (
                Host::new("localhost", key.clone(), path, extensions, options),
                Some(key),
            )
        } else {
            (Host::unsecure("localhost", path, extensions, options), None)
        };

        host.limiter.disable();
        let data = HostCollection::builder().insert(host).build();

        loop {
            let mut custom_port = false;
            let port = if let Some((_, Some(port))) = &handover {
                custom_port = true;
                println!("Custom port!");
                *port
            } else {
                Self::get_port().await
            };
            println!("Running on {}", port);
            let port_descriptor = if https {
                PortDescriptor::new(port, data.clone())
            } else {
                PortDescriptor::unsecure(port, data.clone())
            };
            let mut config = RunConfig::new().bind(port_descriptor);
            if let Some((handover_path, _)) = &handover {
                config = config.set_ctl_path(handover_path);
            } else {
                config = config.disable_ctl();
            }

            // Last check for collisions
            if !custom_port && Self::test_port_availability(port).await.is_err() {
                continue;
            }
            let shutdown = config.execute().await;
            return Server {
                port,
                certificate: certified_key,
                server: shutdown,
                handover: handover.map(|(path, _)| path),
            };
        }
    }
}
impl Default for ServerBuilder {
    fn default() -> Self {
        Self::new(Extensions::default(), host::Options::default())
    }
}
impl From<Extensions> for ServerBuilder {
    fn from(extensions: Extensions) -> Self {
        Self::new(extensions, host::Options::default())
    }
}
impl From<host::Options> for ServerBuilder {
    fn from(options: host::Options) -> Self {
        Self::new(Extensions::default(), options)
    }
}
impl From<(Extensions, host::Options)> for ServerBuilder {
    fn from(data: (Extensions, host::Options)) -> Self {
        Self::new(data.0, data.1)
    }
}

/// The testing prelude.
/// Also imports `kvarn::prelude::*`.
pub mod prelude {
    pub use super::{Server, ServerBuilder};
    #[doc(hidden)]
    pub use kvarn::prelude::*;
    pub use reqwest;
}

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

    async fn simple_request(server: &super::Server) {
        let response = server
            .get("")
            .timeout(Duration::from_millis(100))
            .send()
            .await
            .unwrap();

        assert_eq!(
            response.status(),
            reqwest::StatusCode::NOT_FOUND,
            "Got response {:#?}",
            response
        );
        assert!(response.text().await.unwrap().contains("404 Not Found"));
    }

    #[tokio::test]
    async fn https() {
        let server = ServerBuilder::default().run().await;
        simple_request(&server).await;
    }
    #[tokio::test]
    async fn http() {
        let server = ServerBuilder::default().http().run().await;
        simple_request(&server).await;
    }
}