File size: 4,217 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use std::{
    fmt::Debug,
    future::Future,
    sync::{Arc, OnceLock},
};

use anyhow::Result;
use turbo_tasks::{TurboTasksApi, run_once, trace::TraceRawVcs};

pub struct Registration {
    execution_lock: OnceLock<()>,
    func: fn(),
    create_turbo_tasks: fn(&str, bool) -> Arc<dyn TurboTasksApi>,
}

impl Registration {
    #[doc(hidden)]
    pub const fn new(
        create_turbo_tasks: fn(&str, bool) -> Arc<dyn TurboTasksApi>,
        func: fn(),
    ) -> Self {
        Registration {
            execution_lock: OnceLock::new(),
            func,
            create_turbo_tasks,
        }
    }

    /// Called by [`run`]. You can call this manually if you're not using
    /// [`run`] (e.g. because you're using a customized `turbo_tasks`
    /// implementation or tokio runtime).
    pub fn ensure_registered(&self) {
        self.execution_lock.get_or_init(self.func);
    }

    pub fn create_turbo_tasks(&self, name: &str, initial: bool) -> Arc<dyn TurboTasksApi> {
        (self.create_turbo_tasks)(name, initial)
    }
}

#[macro_export]
macro_rules! register {
    ($($other_register_fns:expr),* $(,)?) => {{
        use turbo_tasks::TurboTasksApi;
        use std::sync::Arc;
        fn create_turbo_tasks(name: &str, initial: bool) -> Arc<dyn TurboTasksApi> {
            let inner = include!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/tests/test_config.trs"
            ));
            (inner)(name, initial)
        }
        fn register_impl() {
            $($other_register_fns();)*
            turbo_tasks::register();
            include!(concat!(
                env!("OUT_DIR"),
                "/register_test_",
                module_path!(),
                ".rs",
            ));
        }
        turbo_tasks_testing::Registration::new(create_turbo_tasks, register_impl)
    }};
}

pub async fn run_without_cache_check<T>(
    registration: &Registration,
    fut: impl Future<Output = T> + Send + 'static,
) -> T
where
    T: TraceRawVcs + Send + 'static,
{
    registration.ensure_registered();
    let name = closure_to_name(&fut);
    let tt = registration.create_turbo_tasks(&name, true);
    run_once(tt, async move { Ok(fut.await) }).await.unwrap()
}

fn closure_to_name<T>(value: &T) -> String {
    let name = std::any::type_name_of_val(value);
    name.replace("::{{closure}}", "").replace("::", "_")
}

pub async fn run<T, F>(
    registration: &Registration,
    fut: impl Fn() -> F + Send + 'static,
) -> Result<()>
where
    F: Future<Output = Result<T>> + Send + 'static,
    T: Debug + PartialEq + Eq + TraceRawVcs + Send + 'static,
{
    run_with_tt(registration, move |tt| run_once(tt, fut())).await
}

pub async fn run_with_tt<T, F>(
    registration: &Registration,
    fut: impl Fn(Arc<dyn TurboTasksApi>) -> F + Send + 'static,
) -> Result<()>
where
    F: Future<Output = Result<T>> + Send + 'static,
    T: Debug + PartialEq + Eq + TraceRawVcs + Send + 'static,
{
    registration.ensure_registered();

    let name = closure_to_name(&fut);
    let tt = registration.create_turbo_tasks(&name, true);
    println!("Run #1 (without cache)");
    let start = std::time::Instant::now();
    let first = fut(tt.clone()).await?;
    println!("Run #1 took {:?}", start.elapsed());
    for i in 2..10 {
        println!("Run #{i} (with memory cache, same TurboTasks instance)");
        let start = std::time::Instant::now();
        let second = fut(tt.clone()).await?;
        println!("Run #{i} took {:?}", start.elapsed());
        assert_eq!(first, second);
    }
    let start = std::time::Instant::now();
    tt.stop_and_wait().await;
    println!("Stopping TurboTasks took {:?}", start.elapsed());
    for i in 10..20 {
        let tt = registration.create_turbo_tasks(&name, false);
        println!("Run #{i} (with persistent cache if available, new TurboTasks instance)");
        let start = std::time::Instant::now();
        let third = fut(tt.clone()).await?;
        println!("Run #{i} took {:?}", start.elapsed());
        let start = std::time::Instant::now();
        tt.stop_and_wait().await;
        println!("Stopping TurboTasks took {:?}", start.elapsed());
        assert_eq!(first, third);
    }
    Ok(())
}