5 releases (3 breaking)

0.4.0 Jan 4, 2022
0.3.0 Oct 5, 2021
0.2.0 Sep 30, 2021
0.1.1 Jan 26, 2021
0.1.0 Jan 26, 2021

#722 in Asynchronous

Download history 206/week @ 2024-07-25 232/week @ 2024-08-01 82/week @ 2024-08-08 64/week @ 2024-08-15 103/week @ 2024-08-22 360/week @ 2024-08-29 512/week @ 2024-09-05 256/week @ 2024-09-12 310/week @ 2024-09-19 468/week @ 2024-09-26 482/week @ 2024-10-03 332/week @ 2024-10-10 230/week @ 2024-10-17 367/week @ 2024-10-24 307/week @ 2024-10-31 296/week @ 2024-11-07

1,249 downloads per month
Used in 2 crates

MIT license

20KB
258 lines

tourniquet

Easily round-robin between servers providing the same service, automatically reconnecting to the next server should an error happen.

This library facilitates resiliency to multiple service providers (e.g. servers) by connecting to the first available service from a list in a round-robin manner. If for some reason any provider goes down, any attempt to interact with it will reconnect to the next one, automatically.

Disclaimer: this library is not for load-balancing between a set of providers! It will connect to one provider, and only use this one provider as long as it is up. Tourniquet is meant for resiliency and not for load balancing.

Example

use async_trait::async_trait;
use std::{io::Error, net::IpAddr};
use tokio::{io::AsyncReadExt, net::TcpStream, sync::Mutex};
use tourniquet::{Connector, RoundRobin};

struct Conn(u16);

#[async_trait]
impl Connector<IpAddr, Mutex<TcpStream>, Error> for Conn {
    async fn connect(&self, src: &IpAddr) -> Result<Mutex<TcpStream>, Error> {
        let Conn(ref port) = self;
        TcpStream::connect((*src, *port)).await.map(Mutex::new)
    }
}

#[tokio::main]
async fn main() {
    let rr = RoundRobin::new(
        vec!["46.16.175.175".parse().unwrap(), "51.161.82.214".parse().unwrap()],
        Conn(6667),
    );

    let hello = rr.run(|sock| async move {
        let mut sock = sock.lock().await;
        let mut buf = [0; 50];
        sock.read_exact(&mut buf).await.map(|_| String::from_utf8(buf.to_vec()).unwrap())
    }).await.unwrap();

    assert!(hello.contains("libera.chat"));
}

License: MIT

Dependencies

~2.2–9.5MB
~65K SLoC