-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy path1.rs
77 lines (69 loc) · 1.99 KB
/
1.rs
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
use axum::routing::post;
use rand::prelude::*;
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc::{self, Sender};
static HOST: &str = "127.0.0.1";
lazy_static::lazy_static! {
static ref HTTP_CLIENT: reqwest::Client = reqwest::Client::new();
}
fn main() -> anyhow::Result<()> {
let n = std::env::args_os()
.nth(1)
.and_then(|s| s.into_string().ok())
.and_then(|s| s.parse().ok())
.unwrap_or(10);
let mut rng = thread_rng();
let port = rng.gen_range(30000..40000);
tokio_main(n, port)?;
std::process::exit(0);
}
#[tokio::main]
async fn tokio_main(n: usize, port: usize) -> anyhow::Result<()> {
tokio::spawn(run_server(port));
let (sender, mut receiver) = mpsc::channel::<usize>(n);
let mut sum = 0;
let api = format!("http://{}:{}/api", HOST, port);
for i in 1..=n {
tokio::spawn(send_with_retry(api.clone(), i, sender.clone()));
}
for _i in 0..n {
if let Some(v) = receiver.recv().await {
sum += v;
}
}
println!("{}", sum);
Ok(())
}
async fn run_server(port: usize) -> anyhow::Result<()> {
let app = axum::Router::new().route("/api", post(handler));
axum::Server::bind(&format!("{}:{}", HOST, port).parse()?)
.serve(app.into_make_service())
.await?;
Ok(())
}
async fn send_with_retry(
api: String,
value: usize,
sender: Sender<usize>,
) -> anyhow::Result<()> {
loop {
if let Ok(r) = send_once(&api, value).await {
sender.send(r).await?;
break;
}
}
Ok(())
}
async fn send_once(api: &str, value: usize) -> anyhow::Result<usize> {
let payload = Payload { value };
let resp = HTTP_CLIENT.post(api).json(&payload).send().await?;
let resp_text = resp.text().await?;
Ok(resp_text.parse::<usize>()?)
}
async fn handler(payload: axum::Json<Payload>) -> String {
format!("{}", payload.value)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Payload {
pub value: usize,
}