mz_testdrive/action/
sleep.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::thread;
11use std::time::Duration;
12
13use anyhow::Context;
14use rand::Rng;
15
16use crate::action::ControlFlow;
17use crate::parser::BuiltinCommand;
18
19pub fn run_sleep(cmd: BuiltinCommand) -> Result<ControlFlow, anyhow::Error> {
20    run_sleep_inner(cmd, false)
21}
22
23pub fn run_random_sleep(cmd: BuiltinCommand) -> Result<ControlFlow, anyhow::Error> {
24    run_sleep_inner(cmd, true)
25}
26
27fn run_sleep_inner(mut cmd: BuiltinCommand, random: bool) -> Result<ControlFlow, anyhow::Error> {
28    let arg = cmd.args.string("duration")?;
29    cmd.args.done()?;
30    let duration = humantime::parse_duration(&arg).context("parsing duration")?;
31    let sleep = if random {
32        let mut rng = rand::thread_rng();
33        rng.gen_range(Duration::from_secs(0)..duration)
34    } else {
35        duration
36    };
37    println!("Sleeping for {:?}", sleep);
38    thread::sleep(sleep);
39    Ok(ControlFlow::Continue)
40}