Skip to content

Commit

Permalink
fix: Spawn executes on background tasks. (#76)
Browse files Browse the repository at this point in the history
* Add impls.

* Fix tests.

* Move test crates.
  • Loading branch information
milesj authored Jun 6, 2024
1 parent 0402d2a commit e865acc
Show file tree
Hide file tree
Showing 9 changed files with 74 additions and 128 deletions.
114 changes: 24 additions & 90 deletions Cargo.lock

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

3 changes: 1 addition & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
[workspace]
resolver = "2"
members = ["crates/*"]
members = ["crates/*", "examples/*"]

[workspace.dependencies]
async-trait = "0.1.80"
dirs = "5.0.1"
futures = "0.3.30"
miette = "7.2.0"
once_cell = "1.19.0"
regex = { version = "1.10.4", default-features = false }
Expand Down
5 changes: 1 addition & 4 deletions crates/app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ chrono = { version = "0.4.38", default-features = false, features = [
"clock",
"std",
] }
futures = { workspace = true }
miette = { workspace = true, features = ["fancy"] }
tokio = { workspace = true }
tracing = { workspace = true, optional = true }
tracing-chrome = { version = "0.7.2", optional = true }
tracing-log = { version = "0.2.0", optional = true, default-features = false, features = [
Expand All @@ -32,9 +32,6 @@ tracing-subscriber = { version = "0.3.18", optional = true, default-features = f
"fmt",
] }

[dev-dependencies]
tokio = { workspace = true }

[features]
default = ["tracing"]
tracing = [
Expand Down
27 changes: 19 additions & 8 deletions crates/app/src/app.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use crate::session::{AppResult, AppSession};
use crate::tracing::TracingOptions;
use futures::try_join;
use miette::IntoDiagnostic;
use std::future::Future;
use tokio::spawn;
use tokio::task::JoinHandle;
use tracing::{instrument, trace};

pub type MainResult = miette::Result<()>;
Expand Down Expand Up @@ -43,9 +45,9 @@ impl App {
#[instrument(skip_all)]
pub async fn run<S, F, Fut>(mut self, session: &mut S, op: F) -> miette::Result<()>
where
S: AppSession,
F: FnOnce(S) -> Fut,
Fut: Future<Output = AppResult>,
S: AppSession + 'static,
F: FnOnce(S) -> Fut + Send + 'static,
Fut: Future<Output = AppResult> + Send + 'static,
{
// Startup
if let Err(error) = self.run_startup(session).await {
Expand Down Expand Up @@ -107,15 +109,24 @@ impl App {
#[instrument(skip_all)]
async fn run_execute<S, F, Fut>(&mut self, session: &mut S, op: F) -> AppResult
where
S: AppSession,
F: FnOnce(S) -> Fut,
Fut: Future<Output = AppResult>,
S: AppSession + 'static,
F: FnOnce(S) -> Fut + Send + 'static,
Fut: Future<Output = AppResult> + Send + 'static,
{
trace!("Running execute phase");

self.phase = AppPhase::Execute;

try_join!(op(session.clone()), session.execute(),)?;
let fg_session = session.clone();
let mut bg_session = session.clone();
let mut futures: Vec<JoinHandle<AppResult>> = vec![];

futures.push(spawn(async move { op(fg_session).await }));
futures.push(spawn(async move { bg_session.execute().await }));

for future in futures {
future.await.into_diagnostic()??;
}

Ok(())
}
Expand Down
25 changes: 15 additions & 10 deletions crates/app/tests/app_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use tokio::task;
#[derive(Clone, Debug, Default)]
struct TestSession {
pub contexts: Arc<RwLock<Vec<String>>>,
pub order: Vec<String>,
pub order: Arc<RwLock<Vec<String>>>,
pub error_in_phase: Option<AppPhase>,
}

Expand All @@ -19,12 +19,17 @@ impl TestSession {
let lock = Arc::into_inner(self.contexts).unwrap();
lock.into_inner()
}

pub fn get_order(self) -> Vec<String> {
let lock = Arc::into_inner(self.order).unwrap();
lock.into_inner()
}
}

#[async_trait]
impl AppSession for TestSession {
async fn startup(&mut self) -> AppResult {
self.order.push("startup".into());
self.order.write().await.push("startup".into());

if self.error_in_phase == Some(AppPhase::Startup) {
bail!("error in startup");
Expand All @@ -34,7 +39,7 @@ impl AppSession for TestSession {
}

async fn analyze(&mut self) -> AppResult {
self.order.push("analyze".into());
self.order.write().await.push("analyze".into());

if self.error_in_phase == Some(AppPhase::Analyze) {
bail!("error in analyze");
Expand All @@ -44,7 +49,7 @@ impl AppSession for TestSession {
}

async fn execute(&mut self) -> AppResult {
self.order.push("execute".into());
self.order.write().await.push("execute".into());

if self.error_in_phase == Some(AppPhase::Execute) {
bail!("error in execute");
Expand All @@ -64,7 +69,7 @@ impl AppSession for TestSession {
}

async fn shutdown(&mut self) -> AppResult {
self.order.push("shutdown".into());
self.order.write().await.push("shutdown".into());

if self.error_in_phase == Some(AppPhase::Shutdown) {
bail!("error in shutdown");
Expand All @@ -87,7 +92,7 @@ async fn runs_in_order() {
App::default().run(&mut session, noop).await.unwrap();

assert_eq!(
session.order,
session.get_order(),
vec!["startup", "analyze", "execute", "shutdown"]
);
}
Expand Down Expand Up @@ -118,7 +123,7 @@ mod startup {

assert!(error.is_err());
assert_eq!(error.unwrap_err().to_string(), "error in startup");
assert_eq!(session.order, vec!["startup", "shutdown"]);
assert_eq!(session.get_order(), vec!["startup", "shutdown"]);
}
}

Expand All @@ -136,7 +141,7 @@ mod analyze {

assert!(error.is_err());
assert_eq!(error.unwrap_err().to_string(), "error in analyze");
assert_eq!(session.order, vec!["startup", "analyze", "shutdown"]);
assert_eq!(session.get_order(), vec!["startup", "analyze", "shutdown"]);
}
}

Expand All @@ -155,7 +160,7 @@ mod execute {
assert!(error.is_err());
assert_eq!(error.unwrap_err().to_string(), "error in execute");
assert_eq!(
session.order,
session.get_order(),
vec!["startup", "analyze", "execute", "shutdown"]
);
}
Expand All @@ -176,7 +181,7 @@ mod shutdown {
assert!(error.is_err());
assert_eq!(error.unwrap_err().to_string(), "error in shutdown");
assert_eq!(
session.order,
session.get_order(),
vec!["startup", "analyze", "execute", "shutdown"]
);
}
Expand Down
8 changes: 4 additions & 4 deletions crates/test-app/Cargo.toml → examples/app/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
[package]
name = "test_app"
name = "example_app"
version = "0.5.0"
edition = "2021"
publish = false

[dependencies]
test_lib = { path = "../test-lib" }
starbase = { path = "../app" }
starbase_utils = { path = "../utils", features = ["glob", "fs-lock"] }
example_lib = { path = "../lib" }
starbase = { path = "../../crates/app" }
starbase_utils = { path = "../../crates/utils", features = ["glob", "fs-lock"] }
log = "0.4.21"
async-trait = { workspace = true }
miette = { workspace = true, features = ["fancy"] }
Expand Down
Loading

0 comments on commit e865acc

Please sign in to comment.