Skip to content

Commit

Permalink
Added AssetLoadFailedEvent, UntypedAssetLoadFailedEvent (#11369)
Browse files Browse the repository at this point in the history
# Objective

This adds events for assets that fail to load along with minor utility
methods to make them useful. This paves the way for users writing their
own error handling and retry systems, plus Bevy including robust retry
handling: #11349.

* Addresses #11288
* Needed for #11349

# Solution

```rust
/// An event emitted when a specific [`Asset`] fails to load.
#[derive(Event, Clone, Debug)]
pub struct AssetLoadFailedEvent<A: Asset> {
    pub id: AssetId<A>,
    /// The original handle returned when the asset load was requested.
    pub handle: Option<Handle<A>>,
    /// The asset path that was attempted.
    pub path: AssetPath<'static>,
    /// Why the asset failed to load.
    pub error: AssetLoadError,
}
```

I started implementing `AssetEvent::Failed` like suggested in #11288,
but decided it was better as its own type because:

* I think it makes sense for `AssetEvent` to only refer to assets that
actually exist.
* In order to return `AssetLoadError` in the event (which is useful
information for error handlers that might attempt a retry) we would have
to remove `Copy` from `AssetEvent`.
* There are numerous places in the render app that match against
`AssetEvent`, and I don't think it's worth introducing extra noise about
assets that don't exist.

I also introduced `UntypedAssetLoadErrorEvent`, which is very useful in
places that need to support type flexibility, like an Asset-agnostic
retry plugin.

# Changelog

* **Added:** `AssetLoadFailedEvent<A>`
* **Added**: `UntypedAssetLoadFailedEvent`
* **Added:** `AssetReaderError::Http` for status code information on
HTTP errors. Before this, status codes were only available by parsing
the error message of generic `Io` errors.
* **Added:** `asset_server.get_path_id(path)`. This method simply gets
the asset id for the path. Without this, one was left using
`get_path_handle(path)`, which has the overhead of returning a strong
handle.
* **Fixed**: Made `AssetServer` loads return the same handle for assets
that already exist in a failed state. Now, when you attempt a `load`
that's in a `LoadState::Failed` state, it'll re-use the original asset
id. The advantage of this is that any dependent assets created using the
original handle will "unbreak" if a retry succeeds.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
  • Loading branch information
brianreavis and alice-i-cecile authored Jan 17, 2024
1 parent 9abf565 commit c9e1fcd
Show file tree
Hide file tree
Showing 9 changed files with 411 additions and 54 deletions.
43 changes: 41 additions & 2 deletions crates/bevy_asset/src/event.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,47 @@
use crate::{Asset, AssetId};
use crate::{Asset, AssetId, AssetLoadError, AssetPath, UntypedAssetId};
use bevy_ecs::event::Event;
use std::fmt::Debug;

/// Events that occur for a specific [`Asset`], such as "value changed" events and "dependency" events.
/// An event emitted when a specific [`Asset`] fails to load.
///
/// For an untyped equivalent, see [`UntypedAssetLoadFailedEvent`].
#[derive(Event, Clone, Debug)]
pub struct AssetLoadFailedEvent<A: Asset> {
pub id: AssetId<A>,
/// The asset path that was attempted.
pub path: AssetPath<'static>,
/// Why the asset failed to load.
pub error: AssetLoadError,
}

impl<A: Asset> AssetLoadFailedEvent<A> {
/// Converts this to an "untyped" / "generic-less" asset error event that stores the type information.
pub fn untyped(&self) -> UntypedAssetLoadFailedEvent {
self.into()
}
}

/// An untyped version of [`AssetLoadFailedEvent`].
#[derive(Event, Clone, Debug)]
pub struct UntypedAssetLoadFailedEvent {
pub id: UntypedAssetId,
/// The asset path that was attempted.
pub path: AssetPath<'static>,
/// Why the asset failed to load.
pub error: AssetLoadError,
}

impl<A: Asset> From<&AssetLoadFailedEvent<A>> for UntypedAssetLoadFailedEvent {
fn from(value: &AssetLoadFailedEvent<A>) -> Self {
UntypedAssetLoadFailedEvent {
id: value.id.untyped(),
path: value.path.clone(),
error: value.error.clone(),
}
}
}

/// Events that occur for a specific loaded [`Asset`], such as "value changed" events and "dependency" events.
#[derive(Event)]
pub enum AssetEvent<A: Asset> {
/// Emitted whenever an [`Asset`] is added.
Expand Down
20 changes: 16 additions & 4 deletions crates/bevy_asset/src/io/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,32 @@ use futures_lite::{ready, Stream};
use std::{
path::{Path, PathBuf},
pin::Pin,
sync::Arc,
task::Poll,
};
use thiserror::Error;

/// Errors that occur while loading assets.
#[derive(Error, Debug)]
#[derive(Error, Debug, Clone)]
pub enum AssetReaderError {
/// Path not found.
#[error("path not found: {0}")]
#[error("Path not found: {0}")]
NotFound(PathBuf),

/// Encountered an I/O error while loading an asset.
#[error("encountered an io error while loading asset: {0}")]
Io(#[from] std::io::Error),
#[error("Encountered an I/O error while loading asset: {0}")]
Io(Arc<std::io::Error>),

/// The HTTP request completed but returned an unhandled [HTTP response status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status).
/// If the request fails before getting a status code (e.g. request timeout, interrupted connection, etc), expect [`AssetReaderError::Io`].
#[error("Encountered HTTP status {0:?} when loading asset")]
HttpError(u16),
}

impl From<std::io::Error> for AssetReaderError {
fn from(value: std::io::Error) -> Self {
Self::Io(Arc::new(value))
}
}

pub type Reader<'a> = dyn AsyncRead + Unpin + Send + Sync + 'a;
Expand Down
8 changes: 4 additions & 4 deletions crates/bevy_asset/src/io/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -569,22 +569,22 @@ impl AssetSources {
}

/// An error returned when an [`AssetSource`] does not exist for a given id.
#[derive(Error, Debug)]
#[derive(Error, Debug, Clone)]
#[error("Asset Source '{0}' does not exist")]
pub struct MissingAssetSourceError(AssetSourceId<'static>);

/// An error returned when an [`AssetWriter`] does not exist for a given id.
#[derive(Error, Debug)]
#[derive(Error, Debug, Clone)]
#[error("Asset Source '{0}' does not have an AssetWriter.")]
pub struct MissingAssetWriterError(AssetSourceId<'static>);

/// An error returned when a processed [`AssetReader`] does not exist for a given id.
#[derive(Error, Debug)]
#[derive(Error, Debug, Clone)]
#[error("Asset Source '{0}' does not have a processed AssetReader.")]
pub struct MissingProcessedAssetReaderError(AssetSourceId<'static>);

/// An error returned when a processed [`AssetWriter`] does not exist for a given id.
#[derive(Error, Debug)]
#[derive(Error, Debug, Clone)]
#[error("Asset Source '{0}' does not have a processed AssetWriter.")]
pub struct MissingProcessedAssetWriterError(AssetSourceId<'static>);

Expand Down
5 changes: 1 addition & 4 deletions crates/bevy_asset/src/io/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,7 @@ impl HttpWasmAssetReader {
Ok(reader)
}
404 => Err(AssetReaderError::NotFound(path)),
status => Err(AssetReaderError::Io(std::io::Error::new(
std::io::ErrorKind::Other,
format!("Encountered unexpected HTTP status {status}"),
))),
status => Err(AssetReaderError::HttpError(status as u16)),
}
}
}
Expand Down
Loading

0 comments on commit c9e1fcd

Please sign in to comment.