Skip to content

Commit

Permalink
start to convert ad-hoc errors to explicit types
Browse files Browse the repository at this point in the history
  • Loading branch information
ashkitten authored and technobaboo committed Dec 31, 2024
1 parent 0adde69 commit 8708f24
Show file tree
Hide file tree
Showing 23 changed files with 166 additions and 78 deletions.
13 changes: 7 additions & 6 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ xkbcommon-rs = "0.1.0"
# wayland
wayland-backend = { version = "0.3.7", optional = true, default-features = false }
wayland-scanner = { version = "0.31.4", optional = true }
thiserror = "2.0.9"

[dependencies.smithay]
# git = "https://github.com/technobaboo/smithay.git"
Expand Down
22 changes: 11 additions & 11 deletions codegen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ fn codegen_protocol(protocol: &'static str) -> proc_macro::TokenStream {
impl crate::nodes::Aspect for Interface {
impl_aspect_for_interface_aspect!{}
}
pub fn create_interface(client: &std::sync::Arc<crate::core::client::Client>) -> color_eyre::eyre::Result<()>{
pub fn create_interface(client: &std::sync::Arc<crate::core::client::Client>) -> crate::core::error::Result<()>{
let node = crate::nodes::Node::from_id(client,INTERFACE_NODE_ID,false);
node.add_aspect(Interface);
node.add_to_scenegraph()?;
Expand Down Expand Up @@ -403,7 +403,7 @@ fn generate_member(aspect_id: u64, member: &Member) -> TokenStream {
(Side::Client, MemberType::Signal) => {
quote! {
#[doc = #description]
pub fn #name(#argument_decls) -> color_eyre::eyre::Result<()> {
pub fn #name(#argument_decls) -> crate::core::error::Result<()> {
let serialized = stardust_xr::schemas::flex::serialize((#argument_uses))?;
_node.send_remote_signal(#aspect_id, #opcode, serialized)
}
Expand All @@ -412,21 +412,21 @@ fn generate_member(aspect_id: u64, member: &Member) -> TokenStream {
(Side::Client, MemberType::Method) => {
quote! {
#[doc = #description]
pub async fn #name(#argument_decls) -> color_eyre::eyre::Result<(#return_type, Vec<std::os::fd::OwnedFd>)> {
pub async fn #name(#argument_decls) -> crate::core::error::Result<(#return_type, Vec<std::os::fd::OwnedFd>)> {
_node.execute_remote_method_typed(#aspect_id, #opcode, &(#argument_uses), vec![]).await
}
}
}
(Side::Server, MemberType::Signal) => {
quote! {
#[doc = #description]
fn #name(#argument_decls) -> color_eyre::eyre::Result<()>;
fn #name(#argument_decls) -> crate::core::error::Result<()>;
}
}
(Side::Server, MemberType::Method) => {
quote! {
#[doc = #description]
fn #name(#argument_decls) -> impl std::future::Future<Output = color_eyre::eyre::Result<#return_type>> + Send + Sync + 'static;
fn #name(#argument_decls) -> impl std::future::Future<Output = crate::core::error::Result<#return_type>> + Send + Sync + 'static;
}
}
}
Expand Down Expand Up @@ -475,7 +475,7 @@ fn generate_run_member(aspect_name: &Ident, _type: MemberType, member: &Member)
#opcode => (move || {
#deserialize
<Self as #aspect_name>::#member_name_ident(_node, _calling_client.clone(), #argument_uses)
})().map_err(|e: color_eyre::Report| stardust_xr::scenegraph::ScenegraphError::MemberError { error: e.to_string() }),
})().map_err(|e: crate::core::error::ServerError| stardust_xr::scenegraph::ScenegraphError::MemberError { error: e.to_string() }),
},
MemberType::Method => quote! {
#opcode => _method_response.wrap_async(async move {
Expand Down Expand Up @@ -516,18 +516,18 @@ fn generate_argument_deserialize(
}
if optional {
let mapping = generate_argument_deserialize("o", argument_type, false);
return quote!(#name.map(|o| Ok::<_, color_eyre::eyre::Report>(#mapping)).transpose()?);
return quote!(#name.map(|o| Ok::<_, crate::core::error::ServerError>(#mapping)).transpose()?);
}

match argument_type {
ArgumentType::Color => quote!(color::rgba_linear!(#name[0], #name[1], #name[2], #name[3])),
ArgumentType::Vec(v) => {
let mapping = generate_argument_deserialize("a", v, false);
quote!(#name.into_iter().map(|a| Ok(#mapping)).collect::<color_eyre::eyre::Result<Vec<_>>>()?)
quote!(#name.into_iter().map(|a| Ok(#mapping)).collect::<crate::core::error::Result<Vec<_>>>()?)
}
ArgumentType::Map(v) => {
let mapping = generate_argument_deserialize("a", v, false);
quote!(#name.into_iter().map(|(k, a)| Ok((k, #mapping))).collect::<color_eyre::eyre::Result<rustc_hash::FxHashMap<String, _>>>()?)
quote!(#name.into_iter().map(|(k, a)| Ok((k, #mapping))).collect::<crate::core::error::Result<rustc_hash::FxHashMap<String, _>>>()?)
}
_ => quote!(#name),
}
Expand All @@ -549,11 +549,11 @@ fn generate_argument_serialize(
ArgumentType::Color => quote!([#name.c.r, #name.c.g, #name.c.b, #name.a]),
ArgumentType::Vec(v) => {
let mapping = generate_argument_serialize("a", v, false);
quote!(#name.into_iter().map(|a| Ok(#mapping)).collect::<color_eyre::eyre::Result<Vec<_>>>()?)
quote!(#name.into_iter().map(|a| Ok(#mapping)).collect::<crate::core::error::Result<Vec<_>>>()?)
}
ArgumentType::Map(v) => {
let mapping = generate_argument_serialize("a", v, false);
quote!(#name.into_iter().map(|(k, a)| Ok((k, #mapping))).collect::<color_eyre::eyre::Result<rustc_hash::FxHashMap<String, _>>>()?)
quote!(#name.into_iter().map(|(k, a)| Ok((k, #mapping))).collect::<crate::core::error::Result<rustc_hash::FxHashMap<String, _>>>()?)
}
_ => quote!(#name),
}
Expand Down
75 changes: 75 additions & 0 deletions src/core/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
use std::any::TypeId;

use color_eyre::eyre::Report;
use stardust_xr::{
messenger::MessengerError,
schemas::flex::{
flexbuffers::{DeserializationError, ReaderError},
FlexSerializeError,
},
};
use stereokit_rust::StereoKitError;
use thiserror::Error;

pub type Result<T, E = ServerError> = std::result::Result<T, E>;

#[derive(Error, Debug)]
pub enum ServerError {
#[error("Internal: Unable to get client")]
NoClient,
#[error("Messenger does not exist for this node")]
NoMessenger,
#[error("Messenger error: {0}")]
MessengerError(#[from] MessengerError),
#[error("Remote method error: {0}")]
RemoteMethodError(String),
#[error("Serialization error: {0}")]
SerializationError(#[from] FlexSerializeError),
#[error("Deserialization error: {0}")]
DeserializationError(#[from] DeserializationError),
#[error("Reader error: {0}")]
ReaderError(#[from] ReaderError),
#[error("StereoKit error: {0}")]
StereoKitError(#[from] StereoKitError),
#[error("Aspect {} does not exist for node", 0.to_string())]
NoAspect(TypeId),
#[error("{0}")]
Report(#[from] Report),
}

#[macro_export]
macro_rules! bail {
($msg:literal $(,)?) => {
return Err($crate::core::error::ServerError::from(color_eyre::eyre::eyre!($msg)));
};
($err:expr $(,)?) => {
return Err($crate::core::error::ServerError::from(color_eyre::eyre::eyre!($err)));
};
($fmt:expr, $($arg:tt)*) => {
return Err($crate::core::error::ServerError::from(color_eyre::eyre::eyre!($fmt, $($arg)*)));
};
}

#[macro_export]
macro_rules! ensure {
($cond:expr $(,)?) => {
if !$cond {
$crate::ensure!($cond, concat!("Condition failed: `", stringify!($cond), "`"))
}
};
($cond:expr, $msg:literal $(,)?) => {
if !$cond {
return Err($crate::core::error::ServerError::from(color_eyre::eyre::eyre!($msg)));
}
};
($cond:expr, $err:expr $(,)?) => {
if !$cond {
return Err($crate::core::error::ServerError::from(color_eyre::eyre::eyre!($err)));
}
};
($cond:expr, $fmt:expr, $($arg:tt)*) => {
if !$cond {
return Err($crate::core::error::ServerError::from(color_eyre::eyre::eyre!($fmt, $($arg)*)));
}
};
}
1 change: 1 addition & 0 deletions src/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ pub mod client;
pub mod client_state;
pub mod delta;
pub mod destroy_queue;
pub mod error;
pub mod registry;
pub mod resource;
pub mod scenegraph;
Expand Down
8 changes: 4 additions & 4 deletions src/core/scenegraph.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::core::error::Result;
use crate::nodes::alias::get_original;
use crate::nodes::Node;
use crate::{core::client::Client, nodes::Message};
use color_eyre::eyre::Result;
use once_cell::sync::OnceCell;
use parking_lot::Mutex;
use rustc_hash::FxHashMap;
Expand Down Expand Up @@ -59,20 +59,20 @@ impl MethodResponseSender {
// ) {
// let _ = self.0.send(map_method_return(result));
// }
pub fn wrap_sync<F: FnOnce() -> color_eyre::eyre::Result<Message>>(self, f: F) {
pub fn wrap_sync<F: FnOnce() -> crate::core::error::Result<Message>>(self, f: F) {
self.send(f().map_err(|e| ScenegraphError::MemberError {
error: e.to_string(),
}))
}
pub fn wrap_async<T: Serialize>(
self,
f: impl Future<Output = color_eyre::eyre::Result<(T, Vec<OwnedFd>)>> + Send + 'static,
f: impl Future<Output = Result<(T, Vec<OwnedFd>)>> + Send + 'static,
) {
tokio::task::spawn(async move { self.0.send(map_method_return(f.await)) });
}
}
fn map_method_return<T: Serialize>(
result: color_eyre::eyre::Result<(T, Vec<OwnedFd>)>,
result: Result<(T, Vec<OwnedFd>)>,
) -> Result<(Vec<u8>, Vec<OwnedFd>), ScenegraphError> {
let (value, fds) = result.map_err(|e| ScenegraphError::MemberError {
error: e.to_string(),
Expand Down
3 changes: 1 addition & 2 deletions src/nodes/alias.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use super::{Aspect, AspectIdentifier, Node};
use crate::core::{client::Client, registry::Registry};
use color_eyre::eyre::Result;
use crate::core::{client::Client, error::Result, registry::Registry};
use std::{
ops::Add,
sync::{Arc, Weak},
Expand Down
3 changes: 2 additions & 1 deletion src/nodes/audio.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use super::{Aspect, AspectIdentifier, Node};
use crate::core::client::Client;
use crate::core::destroy_queue;
use crate::core::error::Result;
use crate::core::registry::Registry;
use crate::core::resource::get_resource_file;
use crate::nodes::spatial::{Spatial, Transform, SPATIAL_ASPECT_ALIAS_INFO};
use color_eyre::eyre::{eyre, Result};
use color_eyre::eyre::eyre;
use glam::{vec3, Vec4Swizzles};
use once_cell::sync::OnceCell;
use parking_lot::Mutex;
Expand Down
3 changes: 1 addition & 2 deletions src/nodes/drawable/lines.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use super::{Line, LinesAspect};
use crate::{
core::{client::Client, registry::Registry},
core::{client::Client, error::Result, registry::Registry},
nodes::{spatial::Spatial, Node},
};
use color_eyre::eyre::Result;
use glam::Vec3;
use parking_lot::Mutex;
use prisma::Lerp;
Expand Down
8 changes: 4 additions & 4 deletions src/nodes/drawable/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ use super::{
spatial::{Spatial, Transform},
Aspect, AspectIdentifier, Node,
};
use crate::core::{client::Client, resource::get_resource_file};
use crate::core::{client::Client, error::Result, resource::get_resource_file};
use crate::nodes::spatial::SPATIAL_ASPECT_ALIAS_INFO;
use color_eyre::eyre::{self, Result};
use color_eyre::eyre::eyre;
use model::ModelPart;
use parking_lot::Mutex;
use stardust_xr::values::ResourceID;
Expand Down Expand Up @@ -70,7 +70,7 @@ impl Aspect for Text {
impl InterfaceAspect for Interface {
fn set_sky_tex(_node: Arc<Node>, calling_client: Arc<Client>, tex: ResourceID) -> Result<()> {
let resource_path = get_resource_file(&tex, &calling_client, &[OsStr::new("hdr")])
.ok_or(eyre::eyre!("Could not find resource"))?;
.ok_or(eyre!("Could not find resource"))?;
QUEUED_SKYTEX.lock().replace(resource_path);
Ok(())
}
Expand All @@ -81,7 +81,7 @@ impl InterfaceAspect for Interface {
light: ResourceID,
) -> Result<()> {
let resource_path = get_resource_file(&light, &calling_client, &[OsStr::new("hdr")])
.ok_or(eyre::eyre!("Could not find resource"))?;
.ok_or(eyre!("Could not find resource"))?;
QUEUED_SKYLIGHT.lock().replace(resource_path);
Ok(())
}
Expand Down
8 changes: 5 additions & 3 deletions src/nodes/drawable/model.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use super::{MaterialParameter, ModelAspect, ModelPartAspect, MODEL_PART_ASPECT_ALIAS_INFO};
use crate::bail;
use crate::core::client::Client;
use crate::core::error::Result;
use crate::core::registry::Registry;
use crate::core::resource::get_resource_file;
use crate::nodes::alias::{Alias, AliasList};
use crate::nodes::spatial::Spatial;
use crate::nodes::Node;
use color_eyre::eyre::{bail, eyre, Result};
use color_eyre::eyre::eyre;
use glam::{Mat4, Vec2, Vec3};
use once_cell::sync::{Lazy, OnceCell};
use parking_lot::Mutex;
Expand Down Expand Up @@ -363,12 +365,12 @@ impl ModelAspect for Model {
calling_client: Arc<Client>,
id: u64,
part_path: String,
) -> color_eyre::eyre::Result<()> {
) -> Result<()> {
let model = node.get_aspect::<Model>()?;
let parts = model.parts.lock();
let Some(part) = parts.iter().find(|p| p.path == part_path) else {
let paths = parts.iter().map(|p| &p.path).collect::<Vec<_>>();
bail!("Couldn't find model part at path {part_path}, all available paths: {paths:?}",)
bail!("Couldn't find model part at path {part_path}, all available paths: {paths:?}",);
};
Alias::create_with_id(
&part.space.node().unwrap(),
Expand Down
25 changes: 13 additions & 12 deletions src/nodes/drawable/text.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
use crate::{
core::{client::Client, destroy_queue, registry::Registry, resource::get_resource_file},
core::{
client::Client, destroy_queue, error::Result, registry::Registry,
resource::get_resource_file,
},
nodes::{spatial::Spatial, Node},
};
use color_eyre::eyre::{eyre, Result};
use color_eyre::eyre::eyre;
use glam::{vec3, Mat4, Vec2};
use once_cell::sync::OnceCell;
use parking_lot::Mutex;
Expand Down Expand Up @@ -59,16 +62,14 @@ impl Text {
}

fn draw(&self, token: &MainThreadToken) {
let style =
self.style
.get_or_try_init(|| -> Result<SkTextStyle, color_eyre::eyre::Error> {
let font = self
.font_path
.as_deref()
.and_then(|path| Font::from_file(path).ok())
.unwrap_or_default();
Ok(SkTextStyle::from_font(font, 1.0, Color32::WHITE))
});
let style = self.style.get_or_try_init(|| -> Result<SkTextStyle> {
let font = self
.font_path
.as_deref()
.and_then(|path| Font::from_file(path).ok())
.unwrap_or_default();
Ok(SkTextStyle::from_font(font, 1.0, Color32::WHITE))
});

if let Ok(style) = style {
let text = self.text.lock();
Expand Down
Loading

0 comments on commit 8708f24

Please sign in to comment.