summaryrefslogtreecommitdiff
path: root/rust/src/web.rs
blob: f676b3cdcec509b722645cc2e83f5da7f379e5e1 (plain)
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
use actix_web::{middleware::Logger, post, web, App, HttpResponse, HttpServer, Responder};
use clap::Parser;
use futures::lock::Mutex;
use log::info;
use proptest::test_runner::{Config, RngAlgorithm, TestRng, TestRunner};
use rand::Rng;
use serde::{Deserialize, Serialize};
use std::time::Duration;
use std::{collections::HashMap, sync::Arc};
use tokio::task;
use uuid::Uuid;

use lambda::lambda::{eval_all, eval_whnf, generate_expr, Environment};
use lambda::parser::parse;

#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
struct Registration {
    url: String,
}

trait AppState: Send + Sync {
    fn register(&mut self, registration: &Registration) -> RegistrationResult;
}

#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
enum RegistrationResult {
    RegistrationSuccess { id: String, url: String },
    UrlAlreadyRegistered { url: String },
}

#[derive(Debug, Clone)]
struct Client {
    id: Uuid,
    url: String,
    grade: u8,
    runner: TestRunner,
    results: Vec<TestResult>,
    delay: std::time::Duration,
}

#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
enum TestResult {
    TestFailed(String),
    ErrorSendingTest(String),
    TestSucceeded,
}

impl Client {
    fn new(url: String) -> Self {
        let id = Uuid::new_v4();
        let runner = TestRunner::new_with_rng(
            Config::default(),
            TestRng::from_seed(RngAlgorithm::XorShift, &id.to_bytes_le()),
        );
        Self {
            id,
            url,
            grade: 1,
            runner,
            results: Vec::new(),
            delay: Duration::from_secs(10),
        }
    }

    fn time_to_next_test(&self) -> Duration {
        self.delay
    }

    fn generate_expr(&mut self) -> (String, String) {
        let input = generate_expr(self.grade.into(), &mut self.runner);
        let expected = eval_whnf(&input, &mut Environment::new());
        (input.to_string(), expected.to_string())
    }

    fn check_result(
        &mut self,
        expected: &String,
        response: &Result<String, TestResult>,
    ) -> TestResult {
        let result = match response {
            Ok(expr) => {
                let vals = parse(expr);
                let actual = eval_all(&vals)
                    .iter()
                    .map(|v| format!("{}", v))
                    .collect::<Vec<_>>()
                    .join("\n");
                if actual == *expected {
                    self.grade += 1;
                    self.delay = Duration::from_secs_f64(self.delay.as_secs_f64() * 0.8);
                    TestResult::TestSucceeded
                } else {
                    self.delay = Duration::from_secs_f64(self.delay.as_secs_f64() * 1.2);
                    if self.delay.as_secs() > 30 {
                        self.delay = Duration::from_secs(30);
                    }
                    TestResult::TestFailed(actual)
                }
            }
            Err(res) => res.clone(),
        };
        self.results.push(result.clone());
        result
    }
}

#[derive(Debug)]
struct State {
    clients: HashMap<String, Arc<Mutex<Client>>>,
}

impl State {
    fn new() -> Self {
        Self {
            clients: HashMap::new(),
        }
    }
}

impl AppState for State {
    fn register(&mut self, registration: &Registration) -> RegistrationResult {
        if self.clients.contains_key(&registration.url) {
            RegistrationResult::UrlAlreadyRegistered {
                url: registration.url.clone(),
            }
        } else {
            let client = Client::new(registration.url.clone());
            let id = client.id.to_string();
            let client_ref = Arc::new(Mutex::new(client));
            let client_s = client_ref.clone();
            self.clients.insert(registration.url.clone(), client_ref);
            // let it run in the background
            // FIXME: should find a way to handle graceful termination
            task::spawn(async move { send_tests(client_s).await });

            RegistrationResult::RegistrationSuccess {
                id,
                url: registration.url.clone(),
            }
        }
    }
}

#[post("/register")]
async fn register(
    app_state: web::Data<Arc<Mutex<dyn AppState>>>,
    registration: web::Json<Registration>,
) -> impl Responder {
    let result = app_state.lock().await.register(&registration);
    match result {
        RegistrationResult::RegistrationSuccess { .. } => HttpResponse::Ok().json(result),
        RegistrationResult::UrlAlreadyRegistered { .. } => HttpResponse::BadRequest().json(result),
    }
}

#[post("/eval")]
async fn eval(input: String) -> impl Responder {
    let mut env = Environment::new();
    match parse(&input).first() {
        Some(expr) => {
            let output = eval_whnf(expr, &mut env);
            HttpResponse::Ok().body(format!("{}", output))
        }
        None => HttpResponse::BadRequest().finish(),
    }
}

#[derive(Parser, Debug)]
struct Options {
    /// The port to listen on
    /// Defaults to 8080
    #[arg(short, long, default_value_t = 8080)]
    port: u16,
    /// The host to bind the server to
    /// Defaults to 127.0.0.1
    #[arg(long, default_value = "127.0.0.1")]
    host: String,
}

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let options = Options::parse();
    let app_state = Arc::new(Mutex::new(State::new()));
    let http_state: Arc<Mutex<dyn AppState>> = app_state;
    env_logger::init();
    HttpServer::new(move || {
        App::new()
            .wrap(Logger::default())
            .app_data(web::Data::new(http_state.clone()))
            .service(register)
            .service(eval)
    })
    .bind((options.host, options.port))?
    .run()
    .await
}

async fn send_tests(client_m: Arc<Mutex<Client>>) {
    loop {
        let mut client = client_m.lock().await;
        tokio::time::sleep(client.time_to_next_test()).await;

        let (input, expected) = client.generate_expr();
        let response = send_test(&input, &client.url).await;

        client.check_result(&expected, &response);
    }
}

async fn send_test(input: &String, url: &String) -> Result<String, TestResult> {
    info!("Sending {} to {}", input, url);
    let body = input.clone();
    let response = reqwest::Client::new()
        .post(url)
        .header("content-type", "text/plain")
        .body(body)
        .send()
        .await;
    match response {
        Ok(response) => {
            let body = response.text().await.unwrap();
            Ok(body)
        }
        Err(e) => {
            info!("Error sending test: {}", e);
            Err(TestResult::ErrorSendingTest(e.to_string()))
        }
    }
}

#[cfg(test)]
mod app_tests {
    use std::sync::Arc;

    use actix_web::http::header::TryIntoHeaderValue;
    use actix_web::{body, http::header::ContentType, middleware::Logger, test, App};
    use lambda::ast::Value;

    use super::*;

    struct DummyAppState {
        id: String,
    }

    impl DummyAppState {
        fn new(id: String) -> Self {
            Self { id }
        }
    }

    impl AppState for DummyAppState {
        fn register(&mut self, registration: &Registration) -> RegistrationResult {
            if self.id.is_empty() {
                RegistrationResult::UrlAlreadyRegistered {
                    url: registration.url.clone(),
                }
            } else {
                RegistrationResult::RegistrationSuccess {
                    id: self.id.clone(),
                    url: registration.url.clone(),
                }
            }
        }
    }

    #[actix_web::test]
    async fn post_registration_returns_success_with_unique_id() {
        let id = "0123456789abcdef0123456789abcdef".to_string();
        let dummy_state: Arc<Mutex<dyn AppState>> =
            Arc::new(Mutex::new(DummyAppState::new(id.clone())));
        // FIXME should only be called once, move to setup
        env_logger::init();

        let app = test::init_service(
            App::new()
                .wrap(Logger::default())
                .app_data(web::Data::new(dummy_state))
                .service(register),
        )
        .await;
        let url = "http://192.168.1.1".to_string();
        let req = test::TestRequest::post()
            .uri("/register")
            .set_json(Registration { url: url.clone() })
            .insert_header(ContentType::json())
            .to_request();

        let resp = test::call_service(&app, req).await;

        assert!(resp.status().is_success());

        let body = resp.into_body();
        let bytes = body::to_bytes(body).await;
        assert_eq!(
            RegistrationResult::RegistrationSuccess { id, url },
            serde_json::from_slice(&bytes.unwrap()).unwrap()
        );
    }

    #[actix_web::test]
    async fn post_registration_returns_400_when_register_fails() {
        let dummy_state: Arc<Mutex<dyn AppState>> =
            Arc::new(Mutex::new(DummyAppState::new("".to_string())));

        let app = test::init_service(
            App::new()
                .wrap(Logger::default())
                .app_data(web::Data::new(dummy_state))
                .service(register),
        )
        .await;
        let url = "http://192.168.1.1".to_string();

        let req = test::TestRequest::post()
            .uri("/register")
            .set_json(Registration { url: url.clone() })
            .insert_header(ContentType::json())
            .to_request();

        let resp = test::call_service(&app, req).await;

        assert!(resp.status().is_client_error());
        assert_eq!(
            ContentType::json().try_into_value().unwrap(),
            resp.headers().get("content-type").unwrap()
        );
    }

    #[actix_web::test]
    async fn post_expression_returns_evaluation() {
        let app = test::init_service(App::new().wrap(Logger::default()).service(eval)).await;

        let req = test::TestRequest::post()
            .uri("/eval")
            .set_payload("((lam (x y) x) 1 2)")
            .insert_header(ContentType::plaintext())
            .to_request();

        let resp = test::call_service(&app, req).await;

        assert!(resp.status().is_success());

        let body = resp.into_body();
        let bytes = body::to_bytes(body).await.unwrap();
        assert_eq!(bytes, "1".to_string().into_bytes());
    }

    #[test]
    async fn app_does_not_register_same_url_twice() {
        let mut app_state = State::new();
        let registration = Registration {
            url: "http://1.2.3.4".to_string(),
        };

        app_state.register(&registration);
        let result = app_state.register(&registration);

        assert_eq!(
            RegistrationResult::UrlAlreadyRegistered {
                url: "http://1.2.3.4".to_string()
            },
            result
        );
    }

    fn client() -> Client {
        Client::new("http://1.2.3.4".to_string())
    }

    #[test]
    async fn client_generates_constant_at_level_1() {
        let mut client = client();

        let (input, _) = client.generate_expr();

        match parse(&input)[..] {
            [Value::Num(_)] => (),
            _ => panic!("Expected constant 3"),
        }
    }

    #[test]
    async fn client_generates_different_inputs_on_each_call() {
        let mut client = client();

        let (input1, _) = client.generate_expr();
        let (input2, _) = client.generate_expr();

        assert_ne!(input1, input2);
    }

    #[test]
    async fn client_generates_ascii_variables_at_level_2() {
        let mut client = client();
        client.grade = 2;

        let (input, _) = client.generate_expr();

        let parsed = parse(&input);
        match &parsed[..] {
            [Value::Sym(name)] => {
                println!("{}", name);
                assert!(name.chars().all(|c| c.is_ascii_alphanumeric()));
            }
            _ => panic!("Expected symbol, got {:?}", parsed),
        }
    }

    #[test]
    async fn client_generates_unicode_variables_at_level_3() {
        let mut client = client();
        client.grade = 3;

        let (input, _) = client.generate_expr();

        let parsed = parse(&input);
        match &parsed[..] {
            [Value::Sym(_)] => (),
            _ => panic!("Expected symbol, got {:?}", parsed),
        }
    }

    #[test]
    async fn client_generates_binary_application_at_level_4() {
        let mut client = client();
        client.grade = 4;

        let (input, _) = client.generate_expr();

        let parsed = parse(&input);
        match &parsed[..] {
            [Value::App(_, _)] => (),
            _ => panic!("Expected symbol, got {:?}", parsed),
        }
    }

    #[test]
    async fn client_generates_nested_applications_and_constants_at_level_5() {
        let mut client = client();
        client.grade = 5;

        let (input, _) = client.generate_expr();

        let parsed = parse(&input);
        match &parsed[..] {
            [Value::App(_, _)] => (),
            [Value::Sym(_)] => (),
            [Value::Num(_)] => (),
            _ => panic!("Expected symbol, got {:?}", parsed),
        }
    }

    #[test]
    async fn client_generates_lambda_terms_at_level_6() {
        let mut client = client();
        client.grade = 6;

        let (input, _) = client.generate_expr();

        let parsed = parse(&input);
        match &parsed[..] {
            [Value::Lam(_, _)] => (),
            _ => panic!("Expected symbol, got {:?}", parsed),
        }
    }

    #[test]
    async fn client_generates_application_with_lambda_terms_at_level_7() {
        let mut client = client();
        client.grade = 7;

        let (input, _) = client.generate_expr();

        let parsed = parse(&input);
        match &parsed[..] {
            [Value::App(t1, _)] if matches!(**t1, Value::Lam(_, _)) => (),
            _ => panic!("Expected symbol, got {:?}", parsed),
        }
    }

    #[test]
    async fn client_generates_applications_with_more_than_2_terms_at_level_8() {
        let mut client = client();
        client.grade = 8;

        let (input, _) = client.generate_expr();

        assert!(input.split(' ').count() > 2);
    }

    #[test]
    async fn client_generates_more_complex_terms_at_level_9() {
        let mut client = client();
        client.grade = 9;

        let (input, _) = client.generate_expr();

        let parsed = parse(&input);
        match &parsed[..] {
            _ => panic!("Expected term, got {:?}", parsed),
        }
    }

    #[test]
    async fn client_increases_grade_on_successful_test() {
        let mut client = client();
        let expected = "1".to_string();
        let response = Ok("1".to_string());

        let result = client.check_result(&expected, &response);

        assert_eq!(TestResult::TestSucceeded, result);
        assert_eq!(2, client.grade);
    }

    #[test]
    async fn client_does_not_increase_grade_on_failed_test() {
        let mut client = client();
        let expected = "1".to_string();
        let response = Ok("2".to_string());

        let result = client.check_result(&expected, &response);

        assert_eq!(TestResult::TestFailed("2".to_string()), result);
        assert_eq!(1, client.grade);
    }

    #[test]
    async fn client_starts_delay_to_next_test_at_10s() {
        let client = client();

        let delay = client.time_to_next_test();

        assert_eq!(std::time::Duration::from_secs(10), delay);
    }

    #[test]
    async fn client_increases_delay_to_next_upon_failed_test() {
        let mut client = client();
        let expected = "1".to_string();
        let response = Ok("2".to_string());
        let delay_before = client.time_to_next_test();

        client.check_result(&expected, &response);

        assert!(delay_before < client.time_to_next_test());
    }

    #[test]
    async fn client_increases_delay_to_maximum_of_30s() {
        let mut client = client();
        let expected = "1".to_string();
        let response = Ok("2".to_string());

        for _ in 0..100 {
            client.check_result(&expected, &response);
        }

        assert_eq!(Duration::from_secs(30), client.time_to_next_test());
    }

    #[test]
    async fn client_decreases_delay_to_next_upon_successful_test() {
        let mut client = client();
        let expected = "1".to_string();
        let response = Ok("1".to_string());
        let delay_before = client.time_to_next_test();

        client.check_result(&expected, &response);

        assert!(delay_before > client.time_to_next_test());
    }
}