Skip to content

Commit

Permalink
Clean up system integration
Browse files Browse the repository at this point in the history
  • Loading branch information
udoprog committed Apr 23, 2023
1 parent d43240f commit e98bc29
Show file tree
Hide file tree
Showing 7 changed files with 279 additions and 349 deletions.
12 changes: 0 additions & 12 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion bot/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ winres = "0.1.12"
anyhow = { workspace = true }

[target.'cfg(target_os = "windows")'.dependencies]
futures-executor = "0.3.28"
winapi = { version = "0.3.9", features = ["shellapi", "impl-default"] }

[features]
Expand Down
13 changes: 4 additions & 9 deletions bot/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ fn file_version() -> Option<(String, u64)> {

fn main() -> Result<()> {
if cfg!(target_os = "windows") {
use winres::VersionInfo::*;
use winres::VersionInfo::{FILEVERSION, PRODUCTVERSION};

let mut res = winres::WindowsResource::new();
res.set_icon("res/icon.ico");
Expand Down Expand Up @@ -58,15 +58,10 @@ fn main() -> Result<()> {

if let Ok(oxidize_version) = env::var("OXIDIZE_VERSION") {
version = oxidize_version;
user_agent = format!(
"OxidizeBot/{} (git {rev}; +{url})",
version,
rev = rev,
url = URL
);
user_agent = format!("OxidizeBot/{version} (git {rev}; +{URL})",);
} else {
version = format!("git-{}", rev);
user_agent = format!("OxidizeBot/0 (git {rev}; +{url})", rev = rev, url = URL);
version = format!("git-{rev}");
user_agent = format!("OxidizeBot/0 (git {rev}; +{URL})");
}

fs::write(out_dir.join("version.txt"), &version).context("writing version.txt")?;
Expand Down
79 changes: 50 additions & 29 deletions bot/src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use std::future::Future;
use std::path::{Path, PathBuf};
use std::pin::pin;
use std::pin::{pin, Pin};
use std::time;

use anyhow::{anyhow, Context, Result};
use async_fuse::Fuse;
use async_injector::{Injector, Key};
use common::backoff;
use common::display;
Expand Down Expand Up @@ -120,18 +122,29 @@ pub fn main() -> Result<()> {
return Ok(());
}

let runtime = {
let mut runtime = tokio::runtime::Builder::new_multi_thread();
runtime.enable_all();

if let Some(size) = args.stack_size {
runtime.thread_stack_size(size);
}

runtime.build()?
};

if let Some(size) = args.stack_size {
let thread = std::thread::Builder::new()
.name(format!("main-with-stack-{}", size))
.spawn(move || inner_main(args))?;
.spawn(move || runtime.block_on(inner_main(args)))?;

thread.join().expect("thread shouldn't panic")
} else {
inner_main(args)
runtime.block_on(inner_main(args))
}
}

fn inner_main(args: Args) -> Result<()> {
async fn inner_main(args: Args) -> Result<()> {
let (old_root, root) = match args.root {
Some(root) => (None, root),
None => {
Expand All @@ -153,7 +166,8 @@ fn inner_main(args: Args) -> Result<()> {
std::fs::create_dir_all(&root)?;
}

let system = sys::setup(&root, &log_file)?;
let (system, system_future) = sys::setup(&root, &log_file)?;
let mut system_future = pin!(Fuse::new(system_future));

let mut error_backoff = backoff::Exponential::new(time::Duration::from_secs(5));

Expand Down Expand Up @@ -190,22 +204,19 @@ fn inner_main(args: Args) -> Result<()> {
let script_dirs = vec![root.join("scripts"), PathBuf::from("scripts")];

loop {
let runtime = {
let mut runtime = tokio::runtime::Builder::new_multi_thread();
runtime.enable_all();

if let Some(size) = args.stack_size {
runtime.thread_stack_size(size);
}

runtime.build()?
};

let future = try_main(&system, &root, &script_dirs, &db, &storage);

system.clear();

let backoff = match runtime.block_on(future) {
let result = try_main(
&system,
&root,
&script_dirs,
&db,
&storage,
system_future.as_mut(),
)
.await;

let backoff = match result {
Err(e) => {
let backoff = error_backoff.failed();
system.error(String::from("Bot crashed, see log for more details."));
Expand Down Expand Up @@ -237,14 +248,15 @@ fn inner_main(args: Args) -> Result<()> {

tracing::info!("Restarting in {}...", display::compact_duration(backoff));

let intent = runtime.block_on(async {
tokio::select! {
_ = system.wait_for_shutdown() => Intent::Shutdown,
_ = system.wait_for_restart() => Intent::Restart,
_ = tokio::signal::ctrl_c() => Intent::Shutdown,
_ = tokio::time::sleep(backoff) => Intent::Restart,
let intent = tokio::select! {
() = system.wait_for_shutdown() => {
Intent::Shutdown
}
});
() = system.wait_for_restart() => Intent::Restart,
() = system_future.as_mut() => Intent::Shutdown,
_ = tokio::signal::ctrl_c() => Intent::Shutdown,
_ = tokio::time::sleep(backoff) => Intent::Restart,
};

if let Intent::Shutdown = intent {
break;
Expand All @@ -264,7 +276,12 @@ fn inner_main(args: Args) -> Result<()> {
}

tracing::info!("Exiting...");
system.join()?;
system.shutdown();

if !system_future.is_empty() {
system_future.await;
}

Ok(())
}

Expand All @@ -275,6 +292,7 @@ async fn try_main(
script_dirs: &[PathBuf],
db: &db::Database,
storage: &storage::Storage,
system_future: Pin<&mut Fuse<impl Future<Output = ()>>>,
) -> Result<Intent> {
tracing::info!("Starting Oxidize Bot Version {}", crate::VERSION);

Expand Down Expand Up @@ -330,7 +348,7 @@ async fn try_main(
let command_bus = bus::Bus::new();
injector.update(command_bus.clone()).await;

let system_future = system_loop(settings.scoped("system"), system.clone());
let system_loop_future = system_loop(settings.scoped("system"), system.clone());

injector.update(storage.cache()?).await;

Expand Down Expand Up @@ -475,7 +493,7 @@ async fn try_main(
common::local_join!(
tasks =>
server_future,
system_future,
system_loop_future,
settings_future,
updater_future,
spotify_token_future,
Expand Down Expand Up @@ -511,6 +529,9 @@ async fn try_main(
tracing::info!("Shutdown triggered by signal");
Ok(Intent::Shutdown)
},
() = system_future => {
Ok(Intent::Shutdown)
}
}
}

Expand Down
22 changes: 12 additions & 10 deletions bot/src/sys/noop.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use std::future::Future;
use std::path::Path;
use std::sync::Arc;

use anyhow::Error;
use anyhow::Result;
use tokio::sync::Notify;

use crate::sys::Notification;
Expand Down Expand Up @@ -30,25 +31,26 @@ impl System {

pub(crate) fn notification(&self, _: Notification) {}

pub(crate) fn join(&self) -> Result<(), Error> {
Ok(())
}
pub(crate) fn shutdown(&self) {}

pub(crate) fn is_installed(&self) -> Result<bool, Error> {
pub(crate) fn is_installed(&self) -> Result<bool> {
Ok(true)
}

pub(crate) fn install(&self) -> Result<(), Error> {
pub(crate) fn install(&self) -> Result<()> {
Ok(())
}

pub(crate) fn uninstall(&self) -> Result<(), Error> {
pub(crate) fn uninstall(&self) -> Result<()> {
Ok(())
}
}

pub(crate) fn setup(_root: &Path, _log_file: &Path) -> Result<System, Error> {
Ok(System {
pub(crate) fn setup(_root: &Path, _log_file: &Path) -> Result<(System, impl Future<Output = ()>)> {
let system = System {
restart: Arc::new(Notify::default()),
})
};

let system_future = std::future::pending();
Ok((system, system_future))
}
Loading

0 comments on commit e98bc29

Please sign in to comment.