1
//! `ConsoleEval` over a real `Mux` and a real session.
2

            
3
use super::super::*;
4

            
5
use rpc::{ScriptLimits, Session};
6
use sqlx::types::Uuid;
7
use std::time::{Duration, Instant};
8
use tokio::time::sleep;
9

            
10
/// Runs for seconds, longer than `ABORT_WAIT`.
11
const FOREVER: &str = "(do ((i 0 (+ i 1))) ((>= i 1073741823) i))";
12
const WAIT: Duration = Duration::from_secs(60);
13
const ABORT_WAIT: Duration = Duration::from_secs(2);
14

            
15
6
fn connect() -> ConsoleEval {
16
6
    let ctx = ScriptCtx::new(Uuid::nil()).with_limits(ScriptLimits {
17
6
        fuel: u64::MAX,
18
6
        ..ScriptLimits::default()
19
6
    });
20
6
    ConsoleEval::connect(&Handle::current(), ctx, Session::new).expect("open the console")
21
6
}
22

            
23
11
fn wire_of(item: &DrainItem) -> &str {
24
11
    match item {
25
11
        DrainItem::Routed { wire, .. } | DrainItem::Unroutable(wire) => wire,
26
    }
27
11
}
28

            
29
/// Drains until `count` items arrived or the deadline passed.
30
4
async fn drain_count(eval: &mut ConsoleEval, count: usize) -> Vec<DrainItem> {
31
4
    let deadline = Instant::now() + WAIT;
32
4
    let mut items = Vec::new();
33
51
    while items.len() < count && Instant::now() < deadline {
34
47
        items.extend(eval.drain());
35
47
        sleep(Duration::from_millis(5)).await;
36
    }
37
4
    items
38
4
}
39

            
40
11
fn alive_tasks() -> usize {
41
11
    Handle::current().metrics().num_alive_tasks()
42
11
}
43

            
44
/// Waits until the runtime holds `count` tasks or the aborts had `ABORT_WAIT`.
45
1
async fn settle_tasks(count: usize) -> bool {
46
1
    let deadline = Instant::now() + ABORT_WAIT;
47
8
    while alive_tasks() != count && Instant::now() < deadline {
48
7
        sleep(Duration::from_millis(5)).await;
49
    }
50
1
    alive_tasks() == count
51
1
}
52

            
53
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
54
1
async fn a_reply_is_routed_by_its_id() {
55
1
    let mut eval = connect();
56
1
    assert_eq!(eval.submit(MAIN_STREAM, "(+ 1 2)".to_string()), Some(1));
57
1
    let items = drain_count(&mut eval, 1).await;
58
1
    assert!(
59
1
        matches!(items.as_slice(), [DrainItem::Routed { id: 1, wire }] if wire.contains(":value 3")),
60
1
        "{items:?}"
61
1
    );
62
1
}
63

            
64
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
65
1
async fn two_forms_submitted_back_to_back_answer_in_order() {
66
1
    let mut eval = connect();
67
1
    eval.submit(MAIN_STREAM, "(+ 1 2)".to_string());
68
1
    eval.submit(MAIN_STREAM, "(+ 2 2)".to_string());
69
1
    let items = drain_count(&mut eval, 2).await;
70
1
    let ids: Vec<i64> = items
71
1
        .iter()
72
2
        .filter_map(|item| match item {
73
2
            DrainItem::Routed { id, .. } => Some(*id),
74
            _ => None,
75
2
        })
76
        .collect();
77
1
    assert_eq!(ids, [1, 2], "{items:?}");
78
1
    assert!(wire_of(&items[0]).contains(":value 3"), "{items:?}");
79
1
    assert!(wire_of(&items[1]).contains(":value 4"), "{items:?}");
80
1
}
81

            
82
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
83
1
async fn a_reader_error_answers_its_own_request_and_the_next_command_works() {
84
1
    let mut eval = connect();
85
1
    eval.submit(MAIN_STREAM, "(+ 1".to_string());
86
1
    let items = eval.drain();
87
1
    assert!(
88
1
        matches!(items.as_slice(), [DrainItem::Routed { id: 1, .. }]),
89
        "{items:?}"
90
    );
91
1
    eval.submit(MAIN_STREAM, "(+ 2 2)".to_string());
92
1
    let items = drain_count(&mut eval, 1).await;
93
1
    assert!(wire_of(&items[0]).contains(":value 4"), "{items:?}");
94
1
}
95

            
96
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
97
1
async fn a_full_queue_shows_the_refusal_at_once() {
98
1
    let mut eval = connect();
99
1
    for _ in 0..40 {
100
40
        eval.submit(MAIN_STREAM, FOREVER.to_string());
101
    }
102
1
    let refused = eval
103
1
        .drain()
104
1
        .iter()
105
8
        .filter(|item| wire_of(item).contains(":code busy"))
106
        .count();
107
1
    assert!((7..=8).contains(&refused), "{refused} refused");
108
1
}
109

            
110
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
111
1
async fn interrupt_cancels_an_inflight_eval() {
112
1
    let mut eval = connect();
113
1
    eval.submit(MAIN_STREAM, FOREVER.to_string());
114
    // Path-agnostic: the epoch trap or the pre-start latch, whichever wins the race.
115
1
    sleep(Duration::from_millis(40)).await;
116
1
    eval.interrupt(MAIN_STREAM);
117
1
    let items = drain_count(&mut eval, 1).await;
118
1
    assert!(
119
1
        matches!(items.as_slice(), [DrainItem::Routed { wire, .. }] if wire.contains(":code interrupted")),
120
1
        "{items:?}"
121
1
    );
122
1
}
123

            
124
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
125
1
async fn dropping_the_console_leaves_no_worker_running() {
126
1
    let idle = alive_tasks();
127
1
    let mut eval = connect();
128
1
    eval.submit(MAIN_STREAM, FOREVER.to_string());
129
1
    sleep(Duration::from_millis(40)).await;
130
1
    assert!(alive_tasks() > idle, "the worker never started");
131
1
    drop(eval);
132
1
    assert!(settle_tasks(idle).await, "{} tasks", alive_tasks());
133
1
}