Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nward/commands error handling #11184

Open
wants to merge 18 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,8 @@ bytemuck = "1.7"
futures-lite = "2.0.1"
crossbeam-channel = "0.5.0"
argh = "0.1.12"
# Needed for command handler example
tracing-subscriber = "0.3.18"

[[example]]
name = "hello_world"
Expand Down Expand Up @@ -1352,6 +1354,16 @@ description = "Groups commonly used compound queries and query filters into a si
category = "ECS (Entity Component System)"
wasm = false

[[example]]
name = "command_error_handling"
path = "examples/ecs/command_error_handling.rs"

[package.metadata.example.command_error_handling]
name = "Command Error Handling"
description = "Command error handling"
category = "ECS (Entity Component System)"
wasm = false

[[example]]
name = "dynamic"
path = "examples/ecs/dynamic.rs"
Expand Down
45 changes: 44 additions & 1 deletion benches/benches/bevy_ecs/world/commands.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use bevy_ecs::{
component::Component,
entity::Entity,
system::{Command, CommandQueue, Commands},
system::{Command, CommandQueue, Commands, CommandErrorHandler},
world::World,
};
use criterion::{black_box, Criterion};
Expand Down Expand Up @@ -69,6 +69,49 @@ pub fn spawn_commands(criterion: &mut Criterion) {
group.finish();
}

pub fn spawn_commands_error_handler(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("spawn_commands_error_handler");
group.warm_up_time(std::time::Duration::from_millis(500));
group.measurement_time(std::time::Duration::from_secs(4));

for entity_count in (1..5).map(|i| i * 2 * 1000) {
group.bench_function(format!("{}_entities", entity_count), |bencher| {
let mut world = World::default();
let mut command_queue = CommandQueue::default();

bencher.iter(|| {
let mut commands = Commands::new(&mut command_queue, &world);
for i in 0..entity_count {
let mut entity = commands.spawn_empty();

if black_box(i % 2 == 0) {
entity.insert(A).on_err(CommandErrorHandler::log);
}

if black_box(i % 3 == 0) {
entity.insert(B).on_err(CommandErrorHandler::ignore);
}

if black_box(i % 4 == 0) {
entity.insert(C).on_err(|err, _ctx| {
println!("Error: {:?}", err);
});
}

if black_box(i % 5 == 0) {
entity.despawn().on_err(CommandErrorHandler::log);
}
}
command_queue.apply(&mut world);
});
});
}

group.finish();
}



#[derive(Default, Component)]
struct Matrix([[f32; 4]; 4]);

Expand Down
1 change: 1 addition & 0 deletions benches/benches/bevy_ecs/world/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ criterion_group!(
world_benches,
empty_commands,
spawn_commands,
spawn_commands_error_handler,
insert_commands,
fake_commands,
zero_sized_commands,
Expand Down
5 changes: 3 additions & 2 deletions crates/bevy_ecs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,9 @@ pub mod prelude {
OnTransition, Schedule, Schedules, State, StateTransitionEvent, States, SystemSet,
},
system::{
Commands, Deferred, In, IntoSystem, Local, NonSend, NonSendMut, ParallelCommands,
ParamSet, Query, ReadOnlySystem, Res, ResMut, Resource, System, SystemParamFunction,
CommandErrorHandler, Commands, Deferred, FallibleCommand, In, IntoSystem, Local,
NonSend, NonSendMut, ParallelCommands, ParamSet, Query, ReadOnlySystem, Res, ResMut,
Resource, System, SystemParamFunction,
},
world::{EntityMut, EntityRef, EntityWorldMut, FromWorld, World},
};
Expand Down
204 changes: 204 additions & 0 deletions crates/bevy_ecs/src/system/commands/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
use crate::{
prelude::{FallibleCommand, World},
system::Command,
};
use bevy_utils::tracing::error;
use std::{
fmt::Debug,
ops::{Deref, DerefMut},
};

#[doc(hidden)]
pub trait AddCommand {
fn add_command(&mut self, command: impl Command);
}

/// Provides configuration mechanisms in case a command errors.
/// You can specify a custom handler via [`CommandErrorHandler`] or
/// use one of the provided implementations.
///
/// ## Note
/// The default error handler logs the error (via [`error!`]), but does not panic.
pub struct FallibleCommandConfig<'a, C, T>
where
C: FallibleCommand,
T: AddCommand,
{
command: Option<C>,
inner: &'a mut T,
}

impl<'a, C, T> Deref for FallibleCommandConfig<'a, C, T>
where
C: FallibleCommand,
T: AddCommand,
{
type Target = T;

#[inline]
fn deref(&self) -> &Self::Target {
self.inner
}
}

impl<'a, C, T> DerefMut for FallibleCommandConfig<'a, C, T>
where
C: FallibleCommand,
T: AddCommand,
{
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
self.inner
}
}

/// Builtin command error handlers.
pub struct CommandErrorHandler;

impl CommandErrorHandler {
/// If the command failed, log the error.
///
/// ## Note
/// This is the default behavior if no error handler is specified.
pub fn log<E: Debug>(error: E, _ctx: CommandContext) {
error!("Commands failed with error: {:?}", error);
}

/// If the command failed, [`panic!`] with the error.
pub fn panic<E: Debug>(error: E, _ctx: CommandContext) {
panic!("Commands failed with error: {:?}", error)
}

/// If the command failed, ignore the error and silently succeed.
pub fn ignore<E>(_error: E, _ctx: CommandContext) {}
}

pub(crate) struct HandledErrorCommand<C, F>
where
C: FallibleCommand,
F: FnOnce(C::Error, CommandContext) + Send + Sync + 'static,
{
pub(crate) command: C,
pub(crate) error_handler: F,
}

impl<C, F> Command for HandledErrorCommand<C, F>
where
C: FallibleCommand,
F: FnOnce(C::Error, CommandContext) + Send + Sync + 'static,
{
fn apply(self, world: &mut World) {
let HandledErrorCommand {
command,
error_handler,
} = self;

if let Err(error) = command.try_apply(world) {
error_handler(error, CommandContext { world });
}
}
}

#[non_exhaustive]
/// Context passed to [`CommandErrorHandler`].
pub struct CommandContext<'a> {
/// The [`World`] the command was applied to.
pub world: &'a mut World,
}

/// Similar to [`FallibleCommandConfig`] however does not
/// implement [`DerefMut`] nor return `&mut T` of the underlying
/// Commands type.
pub struct FinalFallibleCommandConfig<'a, C, T>
where
C: FallibleCommand,
T: AddCommand,
{
command: Option<C>,
inner: &'a mut T,
}

macro_rules! impl_fallible_commands {
($name:ident, $returnty:ty, $returnfunc:ident) => {
impl<'a, C, T> $name<'a, C, T>
where
C: FallibleCommand,
C::Error: Debug,
T: AddCommand,
{
#[inline]
pub(crate) fn new(command: C, inner: &'a mut T) -> Self {
Self {
command: Some(command),
inner,
}
}

#[inline]
#[allow(dead_code)]
fn return_inner(&mut self) -> &mut T {
self.inner
}

#[inline]
#[allow(dead_code)]
fn return_unit(&self) {}

/// If the command failed, run the provided `error_handler`.
///
/// ## Note
/// This is normally used in conjunction with [`CommandErrorHandler`].
/// However, this can also be used with custom error handlers (e.g. closures).
///
/// # Examples
/// ```
/// use bevy_ecs::prelude::*;
///
/// #[derive(Component, Resource)]
/// struct TestComponent(pub u32);
///
/// fn system(mut commands: Commands) {
/// // built-in error handler
/// commands.spawn_empty().insert(TestComponent(42)).on_err(CommandErrorHandler::ignore);
///
/// // custom error handler
/// commands.spawn_empty().insert(TestComponent(42)).on_err(|error, ctx| {});
/// }
/// ```
#[inline]
pub fn on_err(
&mut self,
error_handler: impl FnOnce(C::Error, CommandContext) + Send + Sync + 'static,
) -> $returnty {
let command = self
.command
.take()
.expect("Cannot call `on_err` multiple times for a command error handler.");
self.inner.add_command(HandledErrorCommand {
command,
error_handler,
});
self.$returnfunc()
}
}

impl<'a, C, T> Drop for $name<'a, C, T>
where
C: FallibleCommand,
T: AddCommand,
{
#[inline]
fn drop(&mut self) {
if let Some(command) = self.command.take() {
self.inner.add_command(HandledErrorCommand {
command,
error_handler: CommandErrorHandler::log,
});
}
}
}
};
}

impl_fallible_commands!(FinalFallibleCommandConfig, (), return_unit);
impl_fallible_commands!(FallibleCommandConfig, &mut T, return_inner);
Loading