aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: be2fc906023622f08b2550de5855399ce471e620 (plain) (blame)
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
78
79
80
81
82
83
84
85
86
87
88
89
#![feature(try_trait_v2)]
#![feature(pattern)]
#![feature(concat_idents)]
#![feature(associated_type_defaults)]
#![feature(box_patterns)]
#![allow(deprecated)]

use std::time::{
    Duration,
    Instant,
};

use log::{
    error,
    info,
};

pub use self::{
    config::*,
    util::*,
};

#[cfg(feature = "db")]
mod db;

#[cfg(feature = "games")]
mod game;

#[cfg(not(feature = "games"))]
mod game {
    use serenity::framework::StandardFramework;

    #[inline]
    fn register(f: StandardFramework) -> StandardFramework {
        return f;
    }
}

mod bot;
mod commands;
mod config;
mod log_setup;
mod util;

pub type Error = anyhow::Error;
pub type Result<T> = anyhow::Result<T>;

const BACKOFF_FACTOR: f64 = 2.0;
const MAX_BACKOFFS: usize = 3;
const BACKOFF_INIT: f64 = 100.0;

const MIN_RUN_DURATION: Duration = Duration::from_secs(120);

#[tokio::main]
async fn main() {
    log_setup::init(false).expect("initializing logging");

    let mut backoff_count: usize = 0;

    loop {
        let start = Instant::now();

        info!("starting bot");
        match bot::run().await {
            Err(e) => {
                error!("error encountered running client: {:?}", e);
            },
            _ => {
                // NOTE: we MUST have gotten here through SIGINT/SIGTERM handlers
                std::process::exit(0);
            },
        }

        if Instant::now() - start >= MIN_RUN_DURATION {
            backoff_count = 0;
            continue;
        }

        backoff_count += 1;
        if backoff_count >= MAX_BACKOFFS {
            panic!("restarted bot too many times");
        }

        let backoff_millis = (BACKOFF_INIT * BACKOFF_FACTOR.powi(backoff_count as i32)) as u64;
        info!("bot died too quickly. backing off, retrying in {}ms.", backoff_millis);

        tokio::time::sleep(Duration::from_millis(backoff_millis)).await;
    }
}