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
pub mod config;

use std::sync::Arc;

use axum::{
    extract::{Json, State},
    http::StatusCode,
    routing::{get, post},
};
use tracing::{debug, info, instrument};

use crate::config::ServerConfiguration;
use pixy_core::validation::parse_configs;
use pixy_core::{Gateway, SensorGateway, SensorMessage};

fn create_app(gateway: Arc<dyn Gateway>, server_configs: &ServerConfiguration) -> axum::Router {
    let app = axum::Router::new()
        .route("/data", post(handler))
        .route("/healthz", get(|| async { StatusCode::OK }))
        .with_state(gateway);

    if server_configs.enable_echo {
        app.route("/echo", post(echo))
    } else {
        app
    }
}

pub async fn run_server_with_gateway(
    gateway: Arc<dyn Gateway>,
    server_configs: ServerConfiguration,
) {
    let app = create_app(gateway, &server_configs);

    let bind_address = format!("0.0.0.0:{}", server_configs.port);

    println!(
        r#"
     ___                     ___                 
    /  /\      ___          /__/|          ___   
   /  /::\    /  /\        |  |:|         /__/|  
  /  /:/\:\  /  /:/        |  |:|        |  |:|  
 /  /:/~/:/ /__/::\      __|__|:|        |  |:|  
/__/:/ /:/  \__\/\:\__  /__/::::\____  __|__|:|  
\  \:\/:/      \  \:\/\    ~\~~\::::/ /__/::::\  
 \  \::/        \__\::/     |~~|:|~~     ~\~~\:\ 
  \  \:\        /__/:/      |  |:|         \  \:\
   \  \:\       \__\/       |  |:|          \__\/
    \__\/                   |__|/                
    "#
    );

    info!("Starting server on {}", &bind_address);
    axum::Server::bind(&bind_address.as_str().parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

pub async fn run_server_with(server_configs: ServerConfiguration) {
    let pixy_configs = parse_configs(&server_configs.config_file).unwrap();

    let gateway: Arc<dyn Gateway> = Arc::new(SensorGateway::from(pixy_configs));

    run_server_with_gateway(gateway, server_configs).await;
}

#[instrument]
async fn handler(
    State(gateway): State<Arc<dyn Gateway>>,
    Json(reading): Json<SensorMessage>,
) -> StatusCode {
    debug!("Received reading: {:?}", &reading);

    tokio::spawn(async move {
        gateway.handle_reading(reading).await;
    });

    StatusCode::ACCEPTED
}

#[instrument]
async fn echo(data: String) -> String {
    info!("Received data: {:?}", &data);
    data
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use axum::http::{self, Request};
    use tower::ServiceExt;

    #[derive(Debug)]
    struct MockGateway {}

    #[async_trait]
    impl Gateway for MockGateway {
        async fn handle_reading(&self, _reading: SensorMessage) {}
    }

    fn default_config() -> ServerConfiguration {
        ServerConfiguration {
            config_file: String::new(),
            port: 9147,
            log_level: String::from("info"),
            enable_echo: false,
        }
    }

    #[tokio::test]
    async fn test_health_endpoint() {
        let gateway: Arc<dyn Gateway> = Arc::new(MockGateway {});

        let app = create_app(gateway, &default_config());

        let res = app
            .oneshot(Request::get("/healthz").body("".into()).unwrap())
            .await
            .unwrap();

        assert_eq!(res.status(), http::StatusCode::OK);
    }

    #[tokio::test]
    async fn test_echo_enabled() {
        let mut configs = default_config();

        configs.enable_echo = true;

        let gateway: Arc<dyn Gateway> = Arc::new(MockGateway {});

        let app = create_app(gateway, &configs);

        let res = app
            .oneshot(Request::post("/echo").body("hello".into()).unwrap())
            .await
            .unwrap();

        assert_eq!(res.status(), http::StatusCode::OK);

        let body = hyper::body::to_bytes(res.into_body()).await.unwrap();

        assert_eq!(&body[..], b"hello");
    }

    #[tokio::test]
    async fn test_echo_disable() {
        let gateway: Arc<dyn Gateway> = Arc::new(MockGateway {});

        let app = create_app(gateway, &default_config());

        let res = app
            .oneshot(Request::post("/echo").body("hello".into()).unwrap())
            .await
            .unwrap();

        assert_eq!(res.status(), http::StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_example_sensor_works() {
        let gateway: Arc<dyn Gateway> = Arc::new(MockGateway {});

        let app = create_app(gateway, &default_config());

        let example_sensor: SensorMessage =
            serde_json::from_str(include_str!("../../example-configs/test-sensor.json")).unwrap();

        let res = app
            .oneshot(
                Request::post("/data")
                    .header("Content-Type", "application/json")
                    .body(serde_json::to_string(&example_sensor).unwrap().into())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(res.status(), http::StatusCode::ACCEPTED);
    }

    #[tokio::test]
    async fn test_fails_if_wrong_content_type() {
        let gateway: Arc<dyn Gateway> = Arc::new(MockGateway {});

        let app = create_app(gateway, &default_config());

        let example_sensor: SensorMessage =
            serde_json::from_str(include_str!("../../example-configs/test-sensor.json")).unwrap();

        let res = app
            .oneshot(
                Request::post("/data")
                    .body(serde_json::to_string(&example_sensor).unwrap().into())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(res.status(), http::StatusCode::UNSUPPORTED_MEDIA_TYPE);
    }

    #[tokio::test]
    async fn test_malformed_sensor_fails() {
        let gateway: Arc<dyn Gateway> = Arc::new(MockGateway {});

        let app = create_app(gateway, &default_config());

        let example_sensor: SensorMessage =
            serde_json::from_str(include_str!("../../example-configs/test-sensor.json")).unwrap();

        let res = app
            .oneshot(
                Request::post("/data")
                    .header("Content-Type", "application/json")
                    .body(
                        serde_json::to_string(&example_sensor)
                            .unwrap()
                            .replace("temperature", "hot")
                            .into(),
                    )
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(res.status(), http::StatusCode::UNPROCESSABLE_ENTITY);
    }
}