-
Notifications
You must be signed in to change notification settings - Fork 0
/
smol.rs
65 lines (51 loc) · 1.73 KB
/
smol.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
use anyhow::Result;
use smol::io::AsyncReadExt;
use smol::{future, Async};
use std::net::{TcpListener, TcpStream};
use std::time::Duration;
async fn serve(mut stream: Async<TcpStream>) -> Result<()> {
println!("Serving http://{}", stream.get_ref().local_addr()?);
let mut buffer = [0u8; 13];
stream.read_exact(&mut buffer).await?;
if &buffer == b"GET /shutdown" {
println!("Initiating shutdown!");
drop(elegant_departure::shutdown());
}
Ok(())
}
async fn listen(listener: Async<TcpListener>) -> Result<()> {
println!("Listening on http://{}", listener.get_ref().local_addr()?);
loop {
// We could also race on a shutdown guard here to stop accepting connections
// and implement graceful shutdown behaviour for the http server.
let (stream, _) = listener.accept().await?;
smol::spawn(async move {
if let Err(err) = serve(stream).await {
println!("Connection error: {:#?}", err);
}
})
.detach();
}
}
async fn worker(name: &'static str) {
let guard = elegant_departure::get_shutdown_guard();
println!("[{}] working", name);
guard.wait().await;
println!("[{}] shutting down", name);
smol::Timer::after(Duration::from_secs(1)).await;
println!("[{}] done", name);
}
fn main() -> Result<()> {
smol::block_on(async_main())
}
async fn async_main() -> Result<()> {
smol::spawn(worker("worker 1")).detach();
smol::spawn(worker("worker 2")).detach();
let http = listen(Async::<TcpListener>::bind(([127, 0, 0, 1], 8000))?);
let shutdown = async {
elegant_departure::wait_for_shutdown_complete().await;
Ok(())
};
future::race(shutdown, http).await?;
Ok(())
}