3 releases (breaking)

0.3.0 Jul 4, 2024
0.2.0 Nov 15, 2022
0.1.0 Feb 8, 2021

#324 in Asynchronous

Download history 3533/week @ 2024-07-22 2895/week @ 2024-07-29 3985/week @ 2024-08-05 4439/week @ 2024-08-12 2010/week @ 2024-08-19 1302/week @ 2024-08-26 2271/week @ 2024-09-02 1441/week @ 2024-09-09 411/week @ 2024-09-16 228/week @ 2024-09-23 859/week @ 2024-09-30 893/week @ 2024-10-07 502/week @ 2024-10-14 932/week @ 2024-10-21 594/week @ 2024-10-28 188/week @ 2024-11-04

2,221 downloads per month

Apache-2.0

21KB
291 lines

A library to make it easier to handle graceful shutdowns in async code.

This provides tools to wait for pending tasks to complete before finalizing shutdown.

Examples

use graceful_shutdown::Shutdown;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
use tokio::signal;
use tokio::{select, spawn};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let shutdown = Shutdown::new();
    let listener = TcpListener::bind("127.0.0.1:8000").await?;
    spawn(shutdown.shutdown_after(signal::ctrl_c()));
    loop {
       match shutdown.cancel_on_shutdown(listener.accept()).await {
           Some(Ok((mut conn, _))) => {
               spawn(shutdown.graceful(async move {
                   let mut buf = [0; 1024];
                   loop {
                       let n = match conn.read(&mut buf).await {
                           Ok(n) if n == 0 => return,
                           Ok(n) => n,
                           Err(e) => {
                               eprintln!("failed to read from socket; err = {:?}", e);
                               return;
                           }
                       };
                       if let Err(e) = conn.write_all(&buf[0..n]).await {
                           eprintln!("failed to write to socket; err = {:?}", e);
                           return;
                       }
                   }
               }));
           }
           Some(Err(e)) => {
               eprintln!("Error accepting connection; err = {:?}", e);
               shutdown.shutdown();
           }
           None => {
               eprintln!("Starting shutdown");
               break;
           }
       }
    }
    shutdown.await;
    Ok(())
}

Dependencies

~0–9.5MB
~102K SLoC