Skip to main content

Control

Struct Control 

Source
pub struct Control { /* private fields */ }
Expand description

A handle for shutdown and connection counting that is not tied to an address type.

Unlike Handle, one Control can drive servers listening on different address types, for example TCP and Unix at the same time. Build a Handle for each listener with Handle::with_control, then graceful_shutdown or shutdown drains all of them and connection_count covers every listener.

use axum_server::{Control, Handle};
use std::net::SocketAddr;

let control = Control::new();

let handle = Handle::<SocketAddr>::with_control(control.clone());

Implementations§

Source§

impl Control

Source

pub fn new() -> Self

Create a new control handle.

Examples found in repository?
examples/multiple_listeners.rs (line 11)
7async fn main() -> io::Result<()> {
8    let app = Router::new().route("/", get(|| async { "Hello, world!" }));
9
10    // One control handle drains every listener below.
11    let control = Control::new();
12    let mut servers = JoinSet::new();
13
14    let tcp_handle = Handle::<SocketAddr>::with_control(control.clone());
15    let tcp =
16        axum_server::bind(SocketAddr::from(([127, 0, 0, 1], 3000))).handle(tcp_handle.clone());
17    let tcp_service = app.clone().into_make_service();
18
19    servers.spawn(async move { tcp.serve(tcp_service).await });
20
21    #[cfg(unix)]
22    let unix_handle = {
23        use std::os::unix::net::SocketAddr;
24
25        let path = std::env::temp_dir().join("axum-server-multiple-listeners.sock");
26        let _ = std::fs::remove_file(&path);
27
28        let handle = Handle::with_control(control.clone());
29        let unix = axum_server::bind(SocketAddr::from_pathname(path)?).handle(handle.clone());
30        let service = app.clone().into_make_service();
31
32        servers.spawn(async move { unix.serve(service).await });
33
34        handle
35    };
36
37    println!("tcp: http://{}/", tcp_handle.listening().await.unwrap());
38    #[cfg(unix)]
39    println!(
40        "unix: {:?}",
41        unix_handle
42            .listening()
43            .await
44            .unwrap()
45            .as_pathname()
46            .unwrap()
47    );
48
49    let shutdown = control.clone();
50    tokio::spawn(async move {
51        let _ = tokio::signal::ctrl_c().await;
52        shutdown.graceful_shutdown(Some(Duration::from_secs(10)));
53    });
54
55    // A failing listener stops the others instead of leaving them running.
56    while let Some(result) = servers.join_next().await {
57        match result {
58            Ok(Ok(())) => {}
59            Ok(Err(error)) => {
60                eprintln!("server error: {error}");
61                control.shutdown();
62            }
63            Err(error) => {
64                eprintln!("server task failed: {error}");
65                control.shutdown();
66            }
67        }
68    }
69
70    #[cfg(unix)]
71    let _ = std::fs::remove_file(std::env::temp_dir().join("axum-server-multiple-listeners.sock"));
72
73    Ok(())
74}
Source

pub fn connection_count(&self) -> usize

Get the number of live connections across all servers using this control.

Source

pub fn shutdown(&self)

Shutdown all servers using this control.

Examples found in repository?
examples/multiple_listeners.rs (line 61)
7async fn main() -> io::Result<()> {
8    let app = Router::new().route("/", get(|| async { "Hello, world!" }));
9
10    // One control handle drains every listener below.
11    let control = Control::new();
12    let mut servers = JoinSet::new();
13
14    let tcp_handle = Handle::<SocketAddr>::with_control(control.clone());
15    let tcp =
16        axum_server::bind(SocketAddr::from(([127, 0, 0, 1], 3000))).handle(tcp_handle.clone());
17    let tcp_service = app.clone().into_make_service();
18
19    servers.spawn(async move { tcp.serve(tcp_service).await });
20
21    #[cfg(unix)]
22    let unix_handle = {
23        use std::os::unix::net::SocketAddr;
24
25        let path = std::env::temp_dir().join("axum-server-multiple-listeners.sock");
26        let _ = std::fs::remove_file(&path);
27
28        let handle = Handle::with_control(control.clone());
29        let unix = axum_server::bind(SocketAddr::from_pathname(path)?).handle(handle.clone());
30        let service = app.clone().into_make_service();
31
32        servers.spawn(async move { unix.serve(service).await });
33
34        handle
35    };
36
37    println!("tcp: http://{}/", tcp_handle.listening().await.unwrap());
38    #[cfg(unix)]
39    println!(
40        "unix: {:?}",
41        unix_handle
42            .listening()
43            .await
44            .unwrap()
45            .as_pathname()
46            .unwrap()
47    );
48
49    let shutdown = control.clone();
50    tokio::spawn(async move {
51        let _ = tokio::signal::ctrl_c().await;
52        shutdown.graceful_shutdown(Some(Duration::from_secs(10)));
53    });
54
55    // A failing listener stops the others instead of leaving them running.
56    while let Some(result) = servers.join_next().await {
57        match result {
58            Ok(Ok(())) => {}
59            Ok(Err(error)) => {
60                eprintln!("server error: {error}");
61                control.shutdown();
62            }
63            Err(error) => {
64                eprintln!("server task failed: {error}");
65                control.shutdown();
66            }
67        }
68    }
69
70    #[cfg(unix)]
71    let _ = std::fs::remove_file(std::env::temp_dir().join("axum-server-multiple-listeners.sock"));
72
73    Ok(())
74}
Source

pub fn graceful_shutdown(&self, duration: Option<Duration>)

Gracefully shutdown all servers using this control.

None means indefinite grace period.

Examples found in repository?
examples/multiple_listeners.rs (line 52)
7async fn main() -> io::Result<()> {
8    let app = Router::new().route("/", get(|| async { "Hello, world!" }));
9
10    // One control handle drains every listener below.
11    let control = Control::new();
12    let mut servers = JoinSet::new();
13
14    let tcp_handle = Handle::<SocketAddr>::with_control(control.clone());
15    let tcp =
16        axum_server::bind(SocketAddr::from(([127, 0, 0, 1], 3000))).handle(tcp_handle.clone());
17    let tcp_service = app.clone().into_make_service();
18
19    servers.spawn(async move { tcp.serve(tcp_service).await });
20
21    #[cfg(unix)]
22    let unix_handle = {
23        use std::os::unix::net::SocketAddr;
24
25        let path = std::env::temp_dir().join("axum-server-multiple-listeners.sock");
26        let _ = std::fs::remove_file(&path);
27
28        let handle = Handle::with_control(control.clone());
29        let unix = axum_server::bind(SocketAddr::from_pathname(path)?).handle(handle.clone());
30        let service = app.clone().into_make_service();
31
32        servers.spawn(async move { unix.serve(service).await });
33
34        handle
35    };
36
37    println!("tcp: http://{}/", tcp_handle.listening().await.unwrap());
38    #[cfg(unix)]
39    println!(
40        "unix: {:?}",
41        unix_handle
42            .listening()
43            .await
44            .unwrap()
45            .as_pathname()
46            .unwrap()
47    );
48
49    let shutdown = control.clone();
50    tokio::spawn(async move {
51        let _ = tokio::signal::ctrl_c().await;
52        shutdown.graceful_shutdown(Some(Duration::from_secs(10)));
53    });
54
55    // A failing listener stops the others instead of leaving them running.
56    while let Some(result) = servers.join_next().await {
57        match result {
58            Ok(Ok(())) => {}
59            Ok(Err(error)) => {
60                eprintln!("server error: {error}");
61                control.shutdown();
62            }
63            Err(error) => {
64                eprintln!("server task failed: {error}");
65                control.shutdown();
66            }
67        }
68    }
69
70    #[cfg(unix)]
71    let _ = std::fs::remove_file(std::env::temp_dir().join("axum-server-multiple-listeners.sock"));
72
73    Ok(())
74}

Trait Implementations§

Source§

impl Clone for Control

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Control

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Control

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more