rate_limiter_test/
rate_limiter_test.rs

1use amazon_spapi::client::RateLimiter;
2use anyhow::Result;
3use std::time::Duration;
4
5async fn call_api_with_error(
6    i: usize,
7    rate_limiter: &RateLimiter,
8    should_fail: bool,
9) -> Result<()> {
10    let guard = rate_limiter.wait("func1", 0.1, 1).await?;
11
12    println!("API call {} start at: {}", i, chrono::Local::now());
13
14    if should_fail {
15        return Err(anyhow::anyhow!("API call failed"));
16    }
17
18    tokio::time::sleep(Duration::from_secs(1)).await;
19    println!("API call {} end at  : {}", i, chrono::Local::now());
20
21    guard.mark_response().await;
22    Ok(())
23}
24
25#[tokio::main]
26async fn main() -> Result<()> {
27    env_logger::init();
28
29    let rate_limiter = RateLimiter::new();
30
31    if let Err(e) = call_api_with_error(1, &rate_limiter, false).await {
32        println!("Call 1 failed: {}", e);
33    }
34
35    if let Err(e) = call_api_with_error(2, &rate_limiter, true).await {
36        println!("Call 2 failed: {}", e);
37    }
38
39    if let Err(e) = call_api_with_error(3, &rate_limiter, false).await {
40        println!("Call 3 failed: {}", e);
41    }
42
43    Ok(())
44}