use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use rand::{seq::SliceRandom, Rng};
use tor_basic_utils::retry::RetryDelay;
use tor_dircommon::{authority::AuthorityContacts, config::DirTolerance};
use tor_netdoc::doc::netstatus::ConsensusFlavor;
use tor_rtcompat::PreferredRuntime;
use crate::{
database::Timestamp,
err::IsFatal,
mirror::operation::{ConsensusBoundData, StaticEngine},
};
async fn serve<R: Rng, F: Fn() -> Timestamp>(
pool: &Pool<SqliteConnectionManager>,
flavor: ConsensusFlavor,
authorities: AuthorityContacts,
tolerance: DirTolerance,
rng: &mut R,
now_fn: F,
) {
let mut data = ConsensusBoundData::None;
let engine = StaticEngine {
flavor,
authorities,
tolerance,
rt: PreferredRuntime::current().expect("unable to get runtime"),
};
let mut downloads = engine.authorities.downloads().clone();
downloads.shuffle(rng);
let mut current = 0;
let mut retry = RetryDelay::default();
loop {
let endpoint = downloads.get(current).expect("attempted all authorities");
let res = engine
.execute(pool, &mut data, endpoint, now_fn(), rng)
.await;
match res {
Ok(()) => {
retry.reset();
downloads.swap(0, current);
}
Err(e) => {
if e.is_fatal() {
panic!("fatal error: {e}");
}
current += 1;
let delay = retry.next_delay(rng);
tokio::time::sleep(delay).await;
}
}
}
}