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
//! HSR runtime helpers and types

#[macro_use]
#[allow(unused_imports)]
extern crate serde_derive;
pub use serde_derive::{Deserialize, Serialize};

// We have a tonne of public imports. We places them here and make them public
// so that the user doesn't have to faff around adding them all and making sure
// the versions are all compatible
pub use actix_http;
pub use actix_rt;
pub use actix_web;
pub use async_trait;
pub use awc;
pub use futures;
pub use serde_json;
pub use serde_urlencoded;
pub use url;

pub use openssl;

pub use url::Url;

// We re-export this type as it is used in all the trait functions
use actix_http::StatusCode;
use actix_web::{Error as ActixError, HttpResponse};

/// Associate an http status code with a type. Defaults to 501 Internal Server Error
pub trait HasStatusCode {
    /// The http status code associated with the type
    fn status_code(&self) -> StatusCode;
}

/// Errors that may be returned by the client, apart from those explicitly
/// specified in the spec.
///
/// This will handle bad connections, path errors, unreconginized statuses
/// and any other 'unexpected errors'
#[derive(Debug, thiserror::Error)]
pub enum ClientError {
    #[error("Unknown status code: {:?}", _0)]
    BadStatus(StatusCode),
    #[error("Actix error: {}", _0)]
    Actix(#[from] ActixError),
}

pub fn configure_spec(
    cfg: &mut actix_web::web::ServiceConfig,
    spec: &'static str,
    ui: &'static str,
) {
    use actix_web::http::header::ContentType;
    async fn serve_spec(spec: &'static str) -> HttpResponse {
        HttpResponse::Ok()
            .insert_header(ContentType::json())
            .body(spec.to_owned())
    }
    async fn serve_ui(ui: &'static str) -> HttpResponse {
        HttpResponse::Ok()
            .insert_header(ContentType::json())
            .body(ui.to_owned())
    }
    // Add route serving up the json spec
    cfg.route(
        "/spec.json",
        actix_web::web::get().to(
            move || serve_spec(spec), // spec.clone()
        ),
    )
    // Add route serving up the rendered ui
    .route("/ui.html", actix_web::web::get().to(move || serve_ui(ui)));
}

pub struct Config {
    pub host: Url,
    pub ssl: Option<openssl::ssl::SslAcceptorBuilder>,
}

impl Config {
    pub fn with_host(host: Url) -> Self {
        Self { host, ssl: None }
    }
}