1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-10-16 14:37:27 +00:00

Allow running multiple tasks at once, and bail as soon as the first one crashes

This commit is contained in:
Steffo 2024-07-10 21:49:05 +02:00
parent ade4973fc4
commit 4d7e196d13
Signed by: steffo
GPG key ID: 5ADA3868646C3FC0
3 changed files with 33 additions and 13 deletions

View file

@ -1,4 +1,5 @@
use anyhow::{Result};
use crate::telegram::DispatchWithResult;
pub(crate) mod database;
mod telegram;
@ -6,16 +7,21 @@ mod telegram;
#[tokio::main]
async fn main() -> Result<()> {
// Logging setup
{
pretty_env_logger::init();
log::info!("Logging initialized successfully!");
}
// Telegram setup
{
log::trace!("Setting up Telegram bot...");
let mut dispatcher = telegram::dispatcher();
dispatcher.dispatch().await
}
pretty_env_logger::init();
log::debug!("Logging initialized successfully!");
Ok(())
// Telegram setup
log::trace!("Setting up Telegram bot dispatcher...");
let mut telegram_dispatcher = telegram::dispatcher();
let telegram_awaitable = telegram_dispatcher.dispatch_with_result();
// Run all services concurrently
log::info!("Starting services...");
tokio::try_join![
telegram_awaitable,
];
// This should never happen, but just in case...
log::error!("A service has exited, bailing out...");
anyhow::bail!("A service has exited.")
}

View file

@ -105,7 +105,6 @@ pub fn dispatcher(bot: Bot) -> Dispatcher<Bot, Error, DefaultKey> {
.dependencies(
dptree::deps![] // No deps needed at the moment.
)
.enable_ctrlc_handler()
.build()
}

View file

@ -1,4 +1,5 @@
use anyhow::Error;
use std::convert::Infallible;
use anyhow::{Error, Result};
use teloxide::Bot;
use teloxide::dispatching::{DefaultKey, Dispatcher};
@ -12,3 +13,17 @@ pub fn dispatcher() -> Dispatcher<Bot, Error, DefaultKey> {
)
)
}
pub trait DispatchWithResult {
async fn dispatch_with_result(&mut self) -> Result<Infallible>;
}
impl DispatchWithResult for Dispatcher<Bot, Error, DefaultKey> {
async fn dispatch_with_result(&mut self) -> Result<Infallible> {
log::info!("Starting Telegram dispatcher...");
self.dispatch().await;
log::error!("Telegram dispatcher has exited, bailing out...");
anyhow::bail!("Telegram dispatcher has exited.")
}
}