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
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::TimeoutExt;
use futures::lock::Mutex;
use futures::prelude::*;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
#[cfg(target_os = "fuchsia")]
use std::{pin::pin, task::Poll};

// Apply the timeout from config to test
// Ideally this would be a function like Config::with_timeout, but we need to handle Send and !Send
// and it's likely better not to have to duplicate this code.
macro_rules! apply_timeout {
    ($config:expr, $test:expr) => {{
        let timeout = $config.timeout;
        let test = $test;
        move |run| {
            let test = test(run);
            async move {
                if let Some(timeout) = timeout {
                    test.on_timeout(timeout, || panic!("timeout on run {}", run)).await
                } else {
                    test.await
                }
            }
        }
    }};
}

/// Defines how to compose multiple test runs for a kind of test result.
pub trait TestResult: Sized {
    /// How to repeatedly run a test with this result in a single threaded executor.
    fn run_singlethreaded(
        test: Arc<dyn Send + Sync + Fn(usize) -> Pin<Box<dyn Future<Output = Self>>>>,
        cfg: Config,
    ) -> Self;

    /// Similarly, but use run_until_stalled
    #[cfg(target_os = "fuchsia")]
    fn run_until_stalled<F: 'static + Fn(usize) -> Fut, Fut: 'static + Future<Output = Self>>(
        executor: &mut crate::TestExecutor,
        test: F,
        cfg: Config,
    ) -> Poll<Self>;

    /// Whether the result is successful.
    fn is_ok(&self) -> bool;
}

/// Defines how to compose multiple test runs for a kind of test result in a multithreaded executor.
pub trait MultithreadedTestResult: Sized {
    /// How to repeatedly run a test with this result in a multi threaded executor.
    fn run<F: 'static + Send + Fn(usize) -> Fut, Fut: 'static + Send + Future<Output = Self>>(
        test: F,
        threads: usize,
        cfg: Config,
    ) -> Self;

    /// Whether the result is successful.
    fn is_ok(&self) -> bool;
}

impl<E: 'static + std::fmt::Debug> TestResult for Result<(), E> {
    fn run_singlethreaded(
        test: Arc<dyn Send + Sync + Fn(usize) -> Pin<Box<dyn Future<Output = Self>>>>,
        cfg: Config,
    ) -> Self {
        let run_stream = Arc::new(Mutex::new(stream::iter(0..cfg.repeat_count).fuse()));
        let test = apply_timeout!(cfg, test);
        cfg.in_parallel(Arc::new(move || {
            let run_stream = run_stream.clone();
            let test = test.clone();
            crate::LocalExecutor::new().run_singlethreaded(async move {
                while let Some(run) = run_stream.lock().await.next().await {
                    if let Err(e) = test(run).await {
                        panic!("run {} failed with error {:?}", run, e)
                    }
                }
            })
        }));
        Ok(())
    }

    #[cfg(target_os = "fuchsia")]
    fn run_until_stalled<F: 'static + Fn(usize) -> Fut, Fut: 'static + Future<Output = Self>>(
        executor: &mut crate::TestExecutor,
        test: F,
        cfg: Config,
    ) -> Poll<Self> {
        executor.run_until_stalled(
            &mut stream::iter(0..cfg.repeat_count)
                .map(Ok)
                .try_for_each_concurrent(cfg.max_concurrency, apply_timeout!(cfg, test)),
        )
    }

    fn is_ok(&self) -> bool {
        Result::is_ok(self)
    }
}

impl<E: 'static + Send> MultithreadedTestResult for Result<(), E> {
    fn run<F: 'static + Send + Fn(usize) -> Fut, Fut: 'static + Send + Future<Output = Self>>(
        test: F,
        threads: usize,
        cfg: Config,
    ) -> Self {
        crate::SendExecutor::new(cfg.scale_threads(threads)).run(
            stream::iter(0..cfg.repeat_count)
                .map(Ok)
                .try_for_each_concurrent(cfg.max_concurrency, apply_timeout!(cfg, test)),
        )
    }

    fn is_ok(&self) -> bool {
        Result::is_ok(self)
    }
}

impl TestResult for () {
    fn run_singlethreaded(
        test: Arc<dyn Send + Sync + Fn(usize) -> Pin<Box<dyn Future<Output = Self>>>>,
        cfg: Config,
    ) -> Self {
        let run_stream = Arc::new(Mutex::new(stream::iter(0..cfg.repeat_count).fuse()));
        let test = apply_timeout!(cfg, Arc::new(test));
        cfg.in_parallel(Arc::new(move || {
            let run_stream = run_stream.clone();
            let test = test.clone();
            crate::LocalExecutor::new().run_singlethreaded(async move {
                while let Some(run) = run_stream.lock().await.next().await {
                    test(run).await;
                }
            })
        }));
    }

    #[cfg(target_os = "fuchsia")]
    fn run_until_stalled<F: 'static + Fn(usize) -> Fut, Fut: 'static + Future<Output = Self>>(
        executor: &mut crate::TestExecutor,
        test: F,
        cfg: Config,
    ) -> Poll<Self> {
        // TODO(ctiller): figure out why this is necessary and unify the loops
        if cfg.repeat_count == 1 {
            let mut test = pin!(test(1));
            executor.run_until_stalled(&mut test)
        } else {
            executor.run_until_stalled(
                &mut stream::iter(0..cfg.repeat_count)
                    .for_each_concurrent(cfg.max_concurrency, apply_timeout!(cfg, test)),
            )
        }
    }

    fn is_ok(&self) -> bool {
        true
    }
}

impl MultithreadedTestResult for () {
    fn run<F: 'static + Send + Fn(usize) -> Fut, Fut: 'static + Send + Future<Output = Self>>(
        test: F,
        threads: usize,
        cfg: Config,
    ) -> Self {
        crate::SendExecutor::new(cfg.scale_threads(threads)).run(
            stream::iter(0..cfg.repeat_count)
                .for_each_concurrent(cfg.max_concurrency, apply_timeout!(cfg, test)),
        )
    }

    fn is_ok(&self) -> bool {
        true
    }
}

/// Configuration variables for a single test run.
#[derive(Clone)]
pub struct Config {
    repeat_count: usize,
    max_concurrency: usize,
    max_threads: usize,
    timeout: Option<Duration>,
}

fn env_var<T: std::str::FromStr>(name: &str, default: T) -> T {
    std::env::var(name).unwrap_or_default().parse().unwrap_or(default)
}

impl Config {
    fn get() -> Self {
        let repeat_count = std::cmp::max(1, env_var("FASYNC_TEST_REPEAT_COUNT", 1));
        let max_concurrency = env_var("FASYNC_TEST_MAX_CONCURRENCY", 0);
        let timeout_seconds = env_var("FASYNC_TEST_TIMEOUT_SECONDS", 0);
        let max_threads = env_var("FASYNC_TEST_MAX_THREADS", 0);
        let timeout =
            if timeout_seconds == 0 { None } else { Some(Duration::from_secs(timeout_seconds)) };
        Self { repeat_count, max_concurrency, max_threads, timeout }
    }

    // Scale a hard-coded thread count by some factor to account for increased concurrency in the config.
    fn scale_threads(&self, test_threads: usize) -> usize {
        // We try to scale up by the maximum concurrency we'll see.
        let scale = if self.max_concurrency == 0 {
            // If concurrency is unbounded, we'll see a maximum of the test repetitions.
            self.repeat_count
        } else {
            // Otherwise the maximum concurrency will be the lower of repeat count and the concurrency cap.
            std::cmp::min(self.repeat_count, self.max_concurrency)
        };
        // Without resource constraints, we'd like to run with our test threads scaled up by the cooncurrency.
        let desired_threads = test_threads * scale;
        // Account for resource constraints
        let capped_threads = if self.max_threads == 0 {
            desired_threads
        } else {
            std::cmp::min(desired_threads, self.max_threads)
        };
        // Always run *AT LEAST* the typed in number of threads in the test definition.
        std::cmp::max(capped_threads, test_threads)
    }

    fn in_parallel(&self, f: Arc<dyn 'static + Send + Sync + Fn()>) {
        // N-1 background threads...
        let threads: Vec<_> = std::iter::repeat_with(|| {
            let f = f.clone();
            std::thread::spawn(move || f())
        })
        .take(self.scale_threads(1) - 1)
        .collect();
        // ... and we'll consume this thread to get to N.
        f();
        threads.into_iter().for_each(|t| t.join().expect("worker threads should be joinable"));
    }
}

/// Runs a test in an executor, potentially repeatedly and concurrently
pub fn run_singlethreaded_test<F, Fut, R>(test: F) -> R
where
    F: 'static + Send + Sync + Fn(usize) -> Fut,
    Fut: 'static + Future<Output = R>,
    R: TestResult,
{
    TestResult::run_singlethreaded(Arc::new(move |run| test(run).boxed_local()), Config::get())
}

/// Runs a test in an executor until it's stalled
#[cfg(target_os = "fuchsia")]
pub fn run_until_stalled_test<F, Fut, R>(executor: &mut crate::TestExecutor, test: F) -> R
where
    F: 'static + Fn(usize) -> Fut,
    Fut: 'static + Future<Output = R>,
    R: TestResult,
{
    match TestResult::run_until_stalled(executor, test, Config::get()) {
        Poll::Ready(result) => result,
        _ => panic!(
            "Stalled without completing. Consider using \"run_singlethreaded\", or check for a deadlock."
        ),
    }
}

/// Runs a test in an executor, potentially repeatedly and concurrently
pub fn run_test<F, Fut, R>(test: F, threads: usize) -> R
where
    F: 'static + Send + Fn(usize) -> Fut,
    Fut: 'static + Send + Future<Output = R>,
    R: MultithreadedTestResult,
{
    MultithreadedTestResult::run(test, threads, Config::get())
}

#[cfg(test)]
mod tests {
    use super::{Config, MultithreadedTestResult, TestResult};
    use futures::lock::Mutex;
    use futures::prelude::*;
    use std::collections::HashSet;
    use std::sync::Arc;
    use std::time::Duration;

    #[test]
    fn scale_threads() {
        let cfg = |repeat_count, max_concurrency, max_threads| Config {
            repeat_count,
            max_concurrency,
            max_threads,
            timeout: None,
        };
        // Unbounded work should look like tests_per_thread * repeat_count
        assert_eq!(cfg(1, 0, 0).scale_threads(1), 1);
        assert_eq!(cfg(1, 0, 0).scale_threads(20), 20);
        assert_eq!(cfg(30, 0, 0).scale_threads(1), 30);
        assert_eq!(cfg(30, 0, 0).scale_threads(20), 600);
        // Max concurrency should affect repetition count
        assert_eq!(cfg(30, 1, 0).scale_threads(20), 20);
        // Capping thread count should not decrease programmatic maximum
        assert_eq!(cfg(1, 0, 5).scale_threads(10), 10);
        assert_eq!(cfg(1, 0, 15).scale_threads(10), 10);
    }

    #[test]
    fn run_singlethreaded() {
        const REPEAT_COUNT: usize = 1000;
        const MAX_THREADS: usize = 10;
        let pending_runs: Arc<Mutex<HashSet<_>>> =
            Arc::new(Mutex::new((0..REPEAT_COUNT).collect()));
        let pending_runs_child = pending_runs.clone();
        TestResult::run_singlethreaded(
            Arc::new(move |i| {
                let pending_runs_child = pending_runs_child.clone();
                async move {
                    assert!(pending_runs_child.lock().await.remove(&i));
                }
                .boxed_local()
            }),
            Config {
                repeat_count: REPEAT_COUNT,
                max_concurrency: 0,
                max_threads: MAX_THREADS,
                timeout: None,
            },
        );
        assert!(pending_runs.try_lock().unwrap().is_empty());
    }

    // TODO(https://fxbug.dev/42138715): should_panic tests trigger LSAN
    #[ignore]
    #[test]
    #[should_panic]
    fn run_singlethreaded_with_timeout() {
        TestResult::run_singlethreaded(
            Arc::new(move |_| {
                async move {
                    futures::future::pending::<()>().await;
                }
                .boxed_local()
            }),
            Config {
                repeat_count: 1,
                max_concurrency: 0,
                max_threads: 0,
                timeout: Some(Duration::from_millis(1)),
            },
        );
    }

    #[test]
    #[cfg(target_os = "fuchsia")]
    fn run_until_stalled() {
        const REPEAT_COUNT: usize = 1000;
        let pending_runs: Arc<Mutex<HashSet<_>>> =
            Arc::new(Mutex::new((0..REPEAT_COUNT).collect()));
        let pending_runs_child = pending_runs.clone();
        match TestResult::run_until_stalled(
            &mut crate::TestExecutor::new(),
            move |i| {
                let pending_runs_child = pending_runs_child.clone();
                async move {
                    assert!(pending_runs_child.lock().await.remove(&i));
                }
            },
            Config {
                repeat_count: REPEAT_COUNT,
                max_concurrency: 1,
                max_threads: 1,
                timeout: None,
            },
        ) {
            std::task::Poll::Ready(()) => (),
            _ => panic!("Expected everything stalled"),
        }
        assert!(pending_runs.try_lock().unwrap().is_empty());
    }

    #[test]
    fn run() {
        const REPEAT_COUNT: usize = 1000;
        const THREADS: usize = 4;
        let pending_runs: Arc<Mutex<HashSet<_>>> =
            Arc::new(Mutex::new((0..REPEAT_COUNT).collect()));
        let pending_runs_child = pending_runs.clone();
        MultithreadedTestResult::run(
            move |i| {
                let pending_runs_child = pending_runs_child.clone();
                async move {
                    assert!(pending_runs_child.lock().await.remove(&i));
                }
            },
            THREADS,
            Config {
                repeat_count: REPEAT_COUNT,
                max_concurrency: 0,
                max_threads: THREADS,
                timeout: None,
            },
        );
        assert!(pending_runs.try_lock().unwrap().is_empty());
    }

    // TODO(https://fxbug.dev/42138715): should_panic tests trigger LSAN
    #[ignore]
    #[test]
    #[should_panic]
    fn run_with_timeout() {
        const THREADS: usize = 4;
        MultithreadedTestResult::run(
            move |_| async move {
                futures::future::pending::<()>().await;
            },
            THREADS,
            Config {
                repeat_count: 1,
                max_concurrency: 0,
                max_threads: 0,
                timeout: Some(Duration::from_millis(1)),
            },
        );
    }
}