diff --git a/Cargo.lock b/Cargo.lock index 26ac36ff11..11c0ae9f76 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1827,6 +1827,7 @@ dependencies = [ name = "dal" version = "0.1.0" dependencies = [ + "anyhow", "async-recursion", "async-trait", "audit-database", diff --git a/Cargo.toml b/Cargo.toml index 89edb76c2f..1172f28521 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -88,6 +88,7 @@ rust-version = "1.82" publish = false [workspace.dependencies] +anyhow = { version = "1.0.94" } async-nats = { version = "0.38.0", features = ["service"] } async-openai = "0.26.0" async-recursion = "1.1.1" @@ -105,7 +106,12 @@ bollard = "0.18.1" bytes = "1.9.0" chrono = { version = "0.4.39", features = ["serde"] } ciborium = "0.2.2" -clap = { version = "4.5.23", features = ["derive", "color", "env", "wrap_help"] } +clap = { version = "4.5.23", features = [ + "derive", + "color", + "env", + "wrap_help", +] } color-eyre = "0.6.3" config = { version = "0.14.1", default-features = false, features = ["toml"] } convert_case = "0.6.0" diff --git a/lib/dal/Cargo.toml b/lib/dal/Cargo.toml index ab975feb1e..59a37bc0b1 100644 --- a/lib/dal/Cargo.toml +++ b/lib/dal/Cargo.toml @@ -37,6 +37,7 @@ telemetry-nats = { path = "../../lib/telemetry-nats-rs" } telemetry-utils = { path = "../../lib/telemetry-utils-rs" } veritech-client = { path = "../../lib/veritech-client" } +anyhow = { workspace = true } async-recursion = { workspace = true } async-trait = { workspace = true } base64 = { workspace = true } diff --git a/lib/dal/src/action.rs b/lib/dal/src/action.rs index 5caaba1f12..ab4ac54765 100644 --- a/lib/dal/src/action.rs +++ b/lib/dal/src/action.rs @@ -1,5 +1,6 @@ use std::collections::{HashSet, VecDeque}; +use anyhow::Result; use petgraph::prelude::*; use postgres_types::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; @@ -63,7 +64,7 @@ pub enum ActionError { WsEvent(#[from] WsEventError), } -pub type ActionResult = Result; +pub type ActionResult = Result; pub use si_id::ActionId; pub use si_id::ActionPrototypeId; @@ -448,7 +449,7 @@ impl Action { } } - Err(ActionError::PrototypeNotFoundForAction(action_id)) + Err(ActionError::PrototypeNotFoundForAction(action_id).into()) } pub async fn component_id( diff --git a/lib/dal/src/action/prototype.rs b/lib/dal/src/action/prototype.rs index 2b4278c796..bcda98fc52 100644 --- a/lib/dal/src/action/prototype.rs +++ b/lib/dal/src/action/prototype.rs @@ -1,5 +1,6 @@ use std::sync::Arc; +use anyhow::Result; use petgraph::{Direction::Incoming, Outgoing}; use serde::{Deserialize, Serialize}; use si_events::{ActionResultState, FuncRunId}; @@ -66,7 +67,7 @@ pub enum ActionPrototypeError { WsEvent(#[from] WsEventError), } -pub type ActionPrototypeResult = Result; +pub type ActionPrototypeResult = Result; #[remain::sorted] #[derive(Debug, Copy, Clone, Deserialize, Serialize, PartialEq, Eq, Display, Hash)] diff --git a/lib/dal/src/actor_view.rs b/lib/dal/src/actor_view.rs index 1f63beaa53..9c57dacb98 100644 --- a/lib/dal/src/actor_view.rs +++ b/lib/dal/src/actor_view.rs @@ -5,6 +5,7 @@ #![warn(missing_docs, clippy::missing_errors_doc, clippy::missing_panics_doc)] +use anyhow::Result; use serde::{Deserialize, Serialize}; use crate::{DalContext, HistoryActor, StandardModelError, User, UserPk}; @@ -42,15 +43,12 @@ impl ActorView { /// /// Returns [`Err`] if a user cannot be determined given a user pk or if there is a aconnection /// issue with the database. - pub async fn from_history_actor( - ctx: &DalContext, - history_actor: HistoryActor, - ) -> Result { + pub async fn from_history_actor(ctx: &DalContext, history_actor: HistoryActor) -> Result { match history_actor { HistoryActor::User(user_pk) => { let user = User::get_by_pk(ctx, user_pk) .await? - .ok_or(StandardModelError::UserNotFound(user_pk))?; + .ok_or_else(|| StandardModelError::UserNotFound(user_pk))?; Ok(Self::User { pk: user.pk(), label: user.name().to_string(), @@ -69,7 +67,7 @@ impl postgres_types::ToSql for ActorView { &self, ty: &postgres_types::Type, out: &mut postgres_types::private::BytesMut, - ) -> Result> + ) -> std::result::Result> where Self: Sized, { @@ -88,7 +86,7 @@ impl postgres_types::ToSql for ActorView { &self, ty: &postgres_types::Type, out: &mut postgres_types::private::BytesMut, - ) -> Result> { + ) -> std::result::Result> { let json = serde_json::to_value(self)?; postgres_types::ToSql::to_sql(&json, ty, out) } diff --git a/lib/dal/src/attribute/prototype.rs b/lib/dal/src/attribute/prototype.rs index 8cd5be75c0..0ac21a6a39 100644 --- a/lib/dal/src/attribute/prototype.rs +++ b/lib/dal/src/attribute/prototype.rs @@ -11,6 +11,7 @@ use std::sync::Arc; +use anyhow::Result; use content_node_weight::ContentNodeWeight; use petgraph::Direction; use serde::{Deserialize, Serialize}; @@ -84,7 +85,7 @@ pub enum AttributePrototypeError { WorkspaceSnapshot(#[from] WorkspaceSnapshotError), } -pub type AttributePrototypeResult = Result; +pub type AttributePrototypeResult = Result; /// Indicates the _one and only one_ eventual parent of a corresponding [`AttributePrototype`]. /// diff --git a/lib/dal/src/attribute/value.rs b/lib/dal/src/attribute/value.rs index 3f008a05d6..06f26f4936 100644 --- a/lib/dal/src/attribute/value.rs +++ b/lib/dal/src/attribute/value.rs @@ -41,6 +41,7 @@ use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::Arc; +use anyhow::Result; use async_recursion::async_recursion; use indexmap::IndexMap; use petgraph::prelude::*; @@ -230,7 +231,7 @@ impl From for AttributeValueError { } } -pub type AttributeValueResult = Result; +pub type AttributeValueResult = Result; pub use si_id::AttributeValueId; diff --git a/lib/dal/src/audit_logging.rs b/lib/dal/src/audit_logging.rs index 9ef5e38a5a..57ab5e9341 100644 --- a/lib/dal/src/audit_logging.rs +++ b/lib/dal/src/audit_logging.rs @@ -1,5 +1,6 @@ //! This module provides audit logging functionality to the rest of the crate. +use anyhow::Result; use audit_database::AuditDatabaseContext; use audit_database::AuditDatabaseError; use audit_database::AuditLogRow; @@ -44,7 +45,7 @@ pub enum AuditLoggingError { Transactions(#[from] Box), } -type Result = std::result::Result; +// type Result = std::result::Result; /// Publishes all pending [`AuditLogs`](AuditLog) to the audit logs stream for the event session. /// @@ -66,8 +67,10 @@ pub(crate) async fn publish_pending( // TODO(nick): nuke this from intergalactic orbit. Then do it again. let workspace_id = match ctx.workspace_pk() { Ok(workspace_id) => workspace_id, - Err(TransactionsError::Tenancy(TenancyError::NoWorkspace)) => return Ok(()), - Err(err) => return Err(AuditLoggingError::Transactions(Box::new(err))), + Err(error) => match error.downcast_ref::() { + Some(TenancyError::NoWorkspace) => return Ok(()), + _ => return Err(error), + }, }; let (tracker, provided_tracker) = match tracker { @@ -203,8 +206,10 @@ pub(crate) async fn write( // TODO(nick): nuke this from intergalactic orbit. Then do it again. let workspace_id = match ctx.workspace_pk() { Ok(workspace_id) => workspace_id, - Err(TransactionsError::Tenancy(TenancyError::NoWorkspace)) => return Ok(()), - Err(err) => return Err(AuditLoggingError::Transactions(Box::new(err))), + Err(error) => match error.downcast_ref::() { + Some(TenancyError::NoWorkspace) => return Ok(()), + _ => return Err(error), + }, }; let destination_change_set_id = @@ -233,8 +238,10 @@ pub(crate) async fn write_final_message(ctx: &DalContext) -> Result<()> { // TODO(nick): nuke this from intergalactic orbit. Then do it again. let workspace_id = match ctx.workspace_pk() { Ok(workspace_id) => workspace_id, - Err(TransactionsError::Tenancy(TenancyError::NoWorkspace)) => return Ok(()), - Err(err) => return Err(AuditLoggingError::Transactions(Box::new(err))), + Err(error) => match error.downcast_ref::() { + Some(TenancyError::NoWorkspace) => return Ok(()), + _ => return Err(error), + }, }; let pending_events_stream = PendingEventsStream::get_or_create(ctx.jetstream_context()).await?; @@ -251,25 +258,17 @@ pub async fn list( size: usize, sort_ascending: bool, ) -> Result<(Vec, bool)> { - let workspace_id = ctx.workspace_pk().map_err(Box::new)?; + let workspace_id = ctx.workspace_pk()?; let change_set_id = ctx.change_set_id(); let change_set_ids = { let mut change_set_ids = vec![change_set_id]; - if ctx - .get_workspace_default_change_set_id() - .await - .map_err(Box::new)? - == change_set_id - { + if ctx.get_workspace_default_change_set_id().await? == change_set_id { // NOTE(nick,fletcher,brit,paul): we need to decide what this entails on HEAD in the long term. For now, // it is all non-open, non-abandoned change sets... which are just the applied ones. In the future, we may // or will need to ability to tell a story about abandoned change sets. This is for future us or future // victims to solve. Good luck! - for applied_change_set in ChangeSet::list_all_applied(ctx, workspace_id) - .await - .map_err(Box::new)? - { + for applied_change_set in ChangeSet::list_all_applied(ctx, workspace_id).await? { change_set_ids.push(applied_change_set.id); } } diff --git a/lib/dal/src/billing_publish.rs b/lib/dal/src/billing_publish.rs index bc7b4a5030..01ce01090e 100644 --- a/lib/dal/src/billing_publish.rs +++ b/lib/dal/src/billing_publish.rs @@ -25,6 +25,7 @@ while_true )] +use anyhow::Result; use billing_events::{BillingEvent, BillingEventKind, BillingEventsError}; use chrono::Utc; use si_events::FuncRunId; @@ -55,7 +56,7 @@ pub enum BillingPublishError { Transactions(#[from] TransactionsError), } -type BillingPublishResult = Result; +type BillingPublishResult = Result; #[instrument( name = "billing_publish.for_head_change_set_pointer_update", diff --git a/lib/dal/src/cached_module.rs b/lib/dal/src/cached_module.rs index 28af3719ce..452e346716 100644 --- a/lib/dal/src/cached_module.rs +++ b/lib/dal/src/cached_module.rs @@ -1,5 +1,6 @@ use std::{collections::HashMap, str::FromStr, sync::Arc}; +use anyhow::Result; use chrono::{DateTime, Utc}; use itertools::Itertools; use postgres_types::ToSql; @@ -44,7 +45,7 @@ pub enum CachedModuleError { UrlParse(#[from] url::ParseError), } -pub type CachedModuleResult = Result; +pub type CachedModuleResult = Result; #[derive(Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] @@ -119,7 +120,7 @@ impl CachedModule { } let Some(package_data) = &self.package_data else { - return Err(CachedModuleError::NoPackageData); + return Err(CachedModuleError::NoPackageData.into()); }; Ok(package_data.as_slice()) diff --git a/lib/dal/src/change_set.rs b/lib/dal/src/change_set.rs index bc27dda0e4..76ac215799 100644 --- a/lib/dal/src/change_set.rs +++ b/lib/dal/src/change_set.rs @@ -3,6 +3,7 @@ use std::str::FromStr; use std::sync::Arc; use std::time::Duration; +use anyhow::Result; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use si_data_pg::{PgError, PgRow}; @@ -116,7 +117,7 @@ impl From for ChangeSetError { } /// The primary result type for this module. -pub type ChangeSetResult = Result; +pub type ChangeSetResult = Result; /// A superset of [`ChangeSetError`] used when performing apply logic. #[remain::sorted] @@ -145,7 +146,7 @@ pub enum ChangeSetApplyError { } /// A superset of [`ChangeSetResult`] used when performing apply logic. -pub type ChangeSetApplyResult = Result; +pub type ChangeSetApplyResult = Result; pub use si_id::ChangeSetId; @@ -199,15 +200,13 @@ impl ChangeSet { let id: Ulid = Ulid::new(); let change_set_id: ChangeSetId = id.into(); - let workspace_snapshot = WorkspaceSnapshot::find(ctx, workspace_snapshot_address) - .await - .map_err(Box::new)?; + let workspace_snapshot = WorkspaceSnapshot::find(ctx, workspace_snapshot_address).await?; // The workspace snapshot needs to be marked as seen by this new // changeset, so that edit sessions are able to know what is net new in // the edit session vs what the changeset already contained. The "onto" // changeset needs to have seen the "to_rebase" or we will treat them as // completely disjoint changesets. - let workspace_snapshot_address = workspace_snapshot.write(ctx).await.map_err(Box::new)?; + let workspace_snapshot_address = workspace_snapshot.write(ctx).await?; let workspace_id = ctx.tenancy().workspace_pk_opt(); let name = name.as_ref(); @@ -326,7 +325,7 @@ impl ChangeSet { } pub fn workspace_id(&self) -> ChangeSetResult { - self.workspace_id.ok_or(ChangeSetError::NoTenancySet) + self.workspace_id.ok_or(ChangeSetError::NoTenancySet.into()) } async fn workspace(&self, ctx: &DalContext) -> ChangeSetResult { @@ -353,9 +352,7 @@ impl ChangeSet { self.workspace_snapshot_address = workspace_snapshot_address; - billing_publish::for_head_change_set_pointer_update(ctx, self) - .await - .map_err(Box::new)?; + billing_publish::for_head_change_set_pointer_update(ctx, self).await?; Ok(()) } @@ -375,9 +372,7 @@ impl ChangeSet { .await?; self.status = status; - billing_publish::for_change_set_status_update(ctx, self) - .await - .map_err(Box::new)?; + billing_publish::for_change_set_status_update(ctx, self).await?; Ok(()) } @@ -447,11 +442,9 @@ impl ChangeSet { // Ensure that DVU roots are empty before continuing. if !ctx - .workspace_snapshot() - .map_err(Box::new)? + .workspace_snapshot()? .get_dependent_value_roots() - .await - .map_err(Box::new)? + .await? .is_empty() { // TODO(nick): we should consider requiring this check in integration tests too. Why did I @@ -459,44 +452,32 @@ impl ChangeSet { // its via helpers or through the change set methods directly. In addition, they test // for success and failure, not solely for success. We should still do this, but not within // the PR corresponding to when this message was written. - return Err(ChangeSetError::DvuRootsNotEmpty(ctx.change_set_id())); + return Err(ChangeSetError::DvuRootsNotEmpty(ctx.change_set_id()).into()); } // if the change set status isn't approved, we shouldn't go // locking stuff if change_set.status != ChangeSetStatus::Approved { - return Err(ChangeSetError::ChangeSetNotApprovedForApply( - change_set.status, - )); + return Err(ChangeSetError::ChangeSetNotApprovedForApply(change_set.status).into()); } // Lock all unlocked variants - for schema_id in Schema::list_ids(ctx).await.map_err(Box::new)? { - let schema = Schema::get_by_id_or_error(ctx, schema_id) - .await - .map_err(Box::new)?; - let Some(variant) = SchemaVariant::get_unlocked_for_schema(ctx, schema_id) - .await - .map_err(Box::new)? + for schema_id in Schema::list_ids(ctx).await? { + let schema = Schema::get_by_id_or_error(ctx, schema_id).await?; + let Some(variant) = SchemaVariant::get_unlocked_for_schema(ctx, schema_id).await? else { continue; }; let variant_id = variant.id(); - variant.lock(ctx).await.map_err(Box::new)?; - schema - .set_default_schema_variant(ctx, variant_id) - .await - .map_err(Box::new)?; + variant.lock(ctx).await?; + schema.set_default_schema_variant(ctx, variant_id).await?; } // Lock all unlocked functions too - for func in Func::list_for_default_and_editing(ctx) - .await - .map_err(Box::new)? - { + for func in Func::list_for_default_and_editing(ctx).await? { if !func.is_locked { - func.lock(ctx).await.map_err(Box::new)?; + func.lock(ctx).await?; } } Ok(()) @@ -720,18 +701,13 @@ impl ChangeSet { .base_change_set_id .ok_or(ChangeSetError::NoBaseChangeSet(self.id))?; - let base_snapshot = Arc::new( - WorkspaceSnapshot::find_for_change_set(ctx, base_change_set_id) - .await - .map_err(Box::new)?, - ); + let base_snapshot = + Arc::new(WorkspaceSnapshot::find_for_change_set(ctx, base_change_set_id).await?); - Ok(WorkspaceSnapshot::calculate_rebase_batch( - base_snapshot, - ctx.workspace_snapshot().map_err(Box::new)?, + Ok( + WorkspaceSnapshot::calculate_rebase_batch(base_snapshot, ctx.workspace_snapshot()?) + .await?, ) - .await - .map_err(Box::new)?) } /// Applies the current [`ChangeSet`] in the provided [`DalContext`] to its base @@ -916,14 +892,8 @@ impl ChangeSet { } pub async fn extract_userid_from_context_or_error(ctx: &DalContext) -> ChangeSetResult { let user_id = match ctx.history_actor() { - HistoryActor::User(user_pk) => { - let maybe_user = User::get_by_pk_or_error(ctx, *user_pk).await; - match maybe_user { - Ok(user) => user.pk(), - Err(err) => return Err(ChangeSetError::User(err)), - } - } - HistoryActor::SystemInit => return Err(ChangeSetError::InvalidUserSystemInit), + HistoryActor::User(user_pk) => User::get_by_pk_or_error(ctx, *user_pk).await?.pk(), + HistoryActor::SystemInit => return Err(ChangeSetError::InvalidUserSystemInit.into()), }; Ok(user_id) } diff --git a/lib/dal/src/code_view.rs b/lib/dal/src/code_view.rs index f46f8014dd..5be50d98d4 100644 --- a/lib/dal/src/code_view.rs +++ b/lib/dal/src/code_view.rs @@ -1,5 +1,6 @@ use crate::attribute::value::AttributeValueError; use crate::{AttributeValue, AttributeValueId, DalContext}; +use anyhow::Result; use serde::{Deserialize, Serialize}; use strum::{AsRefStr, Display}; use thiserror::Error; @@ -15,7 +16,7 @@ pub enum CodeViewError { Serde(#[from] serde_json::Error), } -pub type CodeViewResult = Result; +pub type CodeViewResult = Result; #[remain::sorted] #[derive(Deserialize, Serialize, Debug, Clone, Display, AsRefStr, PartialEq, Eq, Copy)] @@ -32,7 +33,7 @@ pub enum CodeLanguage { impl TryFrom for CodeLanguage { type Error = CodeViewError; - fn try_from(value: String) -> CodeViewResult { + fn try_from(value: String) -> std::result::Result { match value.to_lowercase().as_str() { "diff" => Ok(Self::Diff), "json" => Ok(Self::Json), @@ -75,7 +76,7 @@ impl CodeView { pub async fn new( ctx: &DalContext, attribute_value_id: AttributeValueId, - ) -> Result, CodeViewError> { + ) -> CodeViewResult> { let attribute_value = AttributeValue::get_by_id(ctx, attribute_value_id).await?; let code_view_name = match attribute_value.key(ctx).await? { Some(key) => key, diff --git a/lib/dal/src/component.rs b/lib/dal/src/component.rs index a232bf698c..1e60ffdc5f 100644 --- a/lib/dal/src/component.rs +++ b/lib/dal/src/component.rs @@ -1,6 +1,7 @@ //! This module contains [`Component`], which is an instance of a //! [`SchemaVariant`](SchemaVariant) and a _model_ of a "real world resource". +use anyhow::Result; use itertools::Itertools; use petgraph::Direction::Outgoing; use serde::{Deserialize, Serialize}; @@ -227,7 +228,7 @@ pub enum ComponentError { WsEvent(#[from] WsEventError), } -pub type ComponentResult = Result; +pub type ComponentResult = Result; pub use si_id::ComponentId; @@ -423,9 +424,7 @@ impl Component { .await?; // Create geometry node - Geometry::new_for_component(ctx, component.id, view_id) - .await - .map_err(|e| ComponentError::Diagram(Box::new(e)))?; + Geometry::new_for_component(ctx, component.id, view_id).await?; Ok(component) } @@ -582,9 +581,7 @@ impl Component { ) .await? { - Action::new(ctx, prototype_id, Some(component.id)) - .await - .map_err(|err| ComponentError::Action(Box::new(err)))?; + Action::new(ctx, prototype_id, Some(component.id)).await?; } Ok(component) @@ -983,7 +980,7 @@ impl Component { let dest_sv_id = Component::schema_variant_id(ctx, self.id).await?; if from_sv_id != dest_sv_id { - return Err(ComponentError::CannotCloneFromDifferentVariants); + return Err(ComponentError::CannotCloneFromDifferentVariants.into()); } // Paste attribute value "values" from original component (or create them for maps/arrays) @@ -1251,7 +1248,7 @@ impl Component { let maybe_parent = if let Some(raw_parent) = raw_sources.pop() { if !raw_sources.is_empty() { - return Err(ComponentError::MultipleParentsForComponent(component_id)); + return Err(ComponentError::MultipleParentsForComponent(component_id).into()); } Some( workspace_snapshot @@ -1298,7 +1295,7 @@ impl Component { ) -> ComponentResult<(ComponentNodeWeight, ComponentContentV2)> { Self::try_get_node_weight_and_content(ctx, component_id) .await? - .ok_or(ComponentError::NotFound(component_id)) + .ok_or(ComponentError::NotFound(component_id).into()) } async fn try_get_node_weight_and_content_hash( @@ -1456,9 +1453,7 @@ impl Component { } pub async fn geometry(&self, ctx: &DalContext, view_id: ViewId) -> ComponentResult { - Geometry::get_by_component_and_view(ctx, self.id, view_id) - .await - .map_err(|e| ComponentError::Diagram(Box::new(e))) + Ok(Geometry::get_by_component_and_view(ctx, self.id, view_id).await?) } pub async fn set_geometry( @@ -1488,10 +1483,7 @@ impl Component { ) -> ComponentResult { let mut geometry_pre = self.geometry(ctx, view_id).await?; if geometry_pre.clone().into_raw() != raw_geometry { - geometry_pre - .update(ctx, raw_geometry) - .await - .map_err(|e| ComponentError::Diagram(Box::new(e)))?; + geometry_pre.update(ctx, raw_geometry).await?; } Ok(geometry_pre) @@ -1717,7 +1709,7 @@ impl Component { // if the current component has children, and the new type is a component, return an error if new_type == ComponentType::Component && !children.is_empty() { - return Err(ComponentError::ComponentHasChildren); + return Err(ComponentError::ComponentHasChildren.into()); } // no-op if we're not actually changing the type @@ -1735,10 +1727,11 @@ impl Component { | (ComponentType::ConfigurationFrameUp, ComponentType::Component) | (ComponentType::ConfigurationFrameUp, ComponentType::ConfigurationFrameDown) => { Frame::update_type_from_or_to_frame(ctx, component_id, reference_id, new_type) - .await - .map_err(Box::new)?; + .await?; + } + (new, old) => { + return Err(ComponentError::InvalidComponentTypeUpdate(old, new).into()) } - (new, old) => return Err(ComponentError::InvalidComponentTypeUpdate(old, new)), } } else { // this component stands alone, just set the type! @@ -1779,14 +1772,15 @@ impl Component { target_node_weight.id().into(), already_found_root_attribute_value_id, component_id, - )); + ) + .into()); } None => Some(target_node_weight.id().into()), }; } } maybe_root_attribute_value_id - .ok_or(ComponentError::RootAttributeValueNotFound(component_id)) + .ok_or_else(|| ComponentError::RootAttributeValueNotFound(component_id).into()) } pub async fn output_socket_attribute_values( &self, @@ -1851,14 +1845,11 @@ impl Component { ) -> ComponentResult { let values = Self::attribute_values_for_prop_id(ctx, component_id, prop_id).await?; if values.len() > 1 { - return Err(ComponentError::ComponentHasTooManyValues( - component_id, - prop_id, - )); + return Err(ComponentError::ComponentHasTooManyValues(component_id, prop_id).into()); } match values.first() { Some(value) => Ok(*value), - None => Err(ComponentError::ComponentMissingValue(component_id, prop_id)), + None => Err(ComponentError::ComponentMissingValue(component_id, prop_id).into()), } } @@ -2204,7 +2195,8 @@ impl Component { return Err( ComponentError::WrongNumberOfPrototypesForAttributePrototypeArgument( base_change_set_connection.attribute_prototype_argument_id, - ), + ) + .into(), ); }; @@ -2524,14 +2516,10 @@ impl Component { } // Remove all geometries for the component - Geometry::remove_all_for_component_id(ctx, id) - .await - .map_err(|e| ComponentError::Diagram(Box::new(e)))?; + Geometry::remove_all_for_component_id(ctx, id).await?; // Remove all actions for this component from queue - Action::remove_all_for_component_id(ctx, id) - .await - .map_err(|err| ComponentError::Action(Box::new(err)))?; + Action::remove_all_for_component_id(ctx, id).await?; WsEvent::action_list_updated(ctx) .await? .publish_on_commit(ctx) @@ -2667,15 +2655,11 @@ impl Component { ) .await? { - Action::new(ctx, prototype_id, Some(component_id)) - .await - .map_err(|err| ComponentError::Action(Box::new(err)))?; + Action::new(ctx, prototype_id, Some(component_id)).await?; } } else if !to_delete { // Remove delete actions for component - Action::remove_all_for_component_id(ctx, component_id) - .await - .map_err(|err| ComponentError::Action(Box::new(err)))?; + Action::remove_all_for_component_id(ctx, component_id).await?; WsEvent::action_list_updated(ctx) .await? .publish_on_commit(ctx) @@ -2768,24 +2752,15 @@ impl Component { raw_geometry: RawGeometry, ) -> ComponentResult<()> { if Geometry::try_get_by_component_and_view(ctx, component_id, view_id) - .await - .map_err(|e| ComponentError::Diagram(Box::new(e)))? + .await? .is_some() { - return Err(ComponentError::ComponentAlreadyInView( - component_id, - view_id, - )); + return Err(ComponentError::ComponentAlreadyInView(component_id, view_id).into()); } - let mut geometry = Geometry::new_for_component(ctx, component_id, view_id) - .await - .map_err(|e| ComponentError::Diagram(Box::new(e)))?; + let mut geometry = Geometry::new_for_component(ctx, component_id, view_id).await?; - geometry - .update(ctx, raw_geometry) - .await - .map_err(|e| ComponentError::Diagram(Box::new(e)))?; + geometry.update(ctx, raw_geometry).await?; Ok(()) } @@ -2990,9 +2965,7 @@ impl Component { let original_parent = original_component.parent(ctx).await?; let original_children = Component::get_children_for_id(ctx, original_component_id).await?; - let geometry_ids = Geometry::list_ids_by_component(ctx, self.id) - .await - .map_err(|e| ComponentError::Diagram(Box::new(e)))?; + let geometry_ids = Geometry::list_ids_by_component(ctx, self.id).await?; // ================================================================================ // Create new component and run changes that depend on the old one still existing @@ -3025,7 +2998,8 @@ impl Component { if new_schema_variant_id != schema_variant_id { return Err(ComponentError::ComponentIncorrectSchemaVariant( new_component_with_temp_id.id(), - )); + ) + .into()); } new_component_with_temp_id @@ -3041,7 +3015,8 @@ impl Component { { return Err(ComponentError::ComponentIncorrectSchemaVariant( new_component_with_temp_id.id(), - )); + ) + .into()); } // Remove old component connections @@ -3237,38 +3212,25 @@ impl Component { ) -> ComponentResult<()> { // Remove any actions created for the new component as a side effect of the upgrade // Then loop through the existing queued actions for the old component and re-add them piecemeal. - Action::remove_all_for_component_id(ctx, new_component_id) - .await - .map_err(|err| ComponentError::Action(Box::new(err)))?; + Action::remove_all_for_component_id(ctx, new_component_id).await?; - let queued_for_old_component = Action::find_for_component_id(ctx, old_component_id) - .await - .map_err(|err| ComponentError::Action(Box::new(err)))?; - let available_for_new_component = ActionPrototype::for_variant(ctx, new_schema_variant_id) - .await - .map_err(|err| ComponentError::ActionPrototype(Box::new(err)))?; + let queued_for_old_component = Action::find_for_component_id(ctx, old_component_id).await?; + let available_for_new_component = + ActionPrototype::for_variant(ctx, new_schema_variant_id).await?; for existing_queued in queued_for_old_component { - let action = Action::get_by_id(ctx, existing_queued) - .await - .map_err(|err| ComponentError::Action(Box::new(err)))?; - let action_prototype_id = Action::prototype_id(ctx, existing_queued) - .await - .map_err(|err| ComponentError::Action(Box::new(err)))?; + let action = Action::get_by_id(ctx, existing_queued).await?; + let action_prototype_id = Action::prototype_id(ctx, existing_queued).await?; // what do we do about the various states? // maybe you shouldn't upgrade a component if an action // is dispatched or running for the current? match action.state() { ActionState::Failed | ActionState::OnHold | ActionState::Queued => { - let func_id = ActionPrototype::func_id(ctx, action_prototype_id) - .await - .map_err(|err| ComponentError::ActionPrototype(Box::new(err)))?; + let func_id = ActionPrototype::func_id(ctx, action_prototype_id).await?; let queued_func = Func::get_by_id_or_error(ctx, func_id).await?; for available_action_prototype in available_for_new_component.clone() { let available_func_id = - ActionPrototype::func_id(ctx, available_action_prototype.id()) - .await - .map_err(|err| ComponentError::ActionPrototype(Box::new(err)))?; + ActionPrototype::func_id(ctx, available_action_prototype.id()).await?; let available_func = Func::get_by_id_or_error(ctx, available_func_id).await?; @@ -3280,8 +3242,7 @@ impl Component { available_action_prototype.id(), Some(new_component_id), ) - .await - .map_err(|err| ComponentError::Action(Box::new(err)))?; + .await?; } } } @@ -3332,9 +3293,7 @@ impl Component { ctx.add_dependent_values_and_enqueue(component.input_socket_attribute_values(ctx).await?) .await?; - Geometry::restore_all_for_component_id(ctx, component_id) - .await - .map_err(|e| ComponentError::Diagram(Box::new(e)))?; + Geometry::restore_all_for_component_id(ctx, component_id).await?; Ok(()) } @@ -3431,7 +3390,8 @@ impl Component { managed_component_id, managed_component_schema_id, manager_component_id, - )); + ) + .into()); } let guard = ctx.workspace_snapshot()?.enable_cycle_check().await; @@ -3588,9 +3548,7 @@ impl Component { let maybe_parent = self.parent(ctx).await?; let geometry = if let Some(geometry) = maybe_geometry { - let view_id = Geometry::get_view_id_by_id(ctx, geometry.id()) - .await - .map_err(|e| ComponentError::Diagram(Box::new(e)))?; + let view_id = Geometry::get_view_id_by_id(ctx, geometry.id()).await?; Some(GeometryAndView { view_id, @@ -3632,9 +3590,7 @@ impl Component { change_status: ChangeStatus, diagram_sockets: &mut HashMap>, ) -> ComponentResult { - let default_view_id = View::get_id_for_default(ctx) - .await - .map_err(|e| ComponentError::Diagram(Box::new(e)))?; + let default_view_id = View::get_id_for_default(ctx).await?; let geometry = self.geometry(ctx, default_view_id).await?; self.into_frontend_type(ctx, Some(&geometry), change_status, diagram_sockets) diff --git a/lib/dal/src/component/inferred_connection_graph.rs b/lib/dal/src/component/inferred_connection_graph.rs index f5ad5d2732..0556b86a93 100644 --- a/lib/dal/src/component/inferred_connection_graph.rs +++ b/lib/dal/src/component/inferred_connection_graph.rs @@ -14,6 +14,7 @@ use std::collections::{BTreeSet, HashMap, HashSet}; +use anyhow::Result; use petgraph::{ prelude::*, visit::{Control, DfsEvent}, @@ -52,7 +53,7 @@ pub enum InferredConnectionGraphError { WorkspaceSnapshot(#[from] WorkspaceSnapshotError), } -pub type InferredConnectionGraphResult = Result; +pub type InferredConnectionGraphResult = Result; #[derive(Debug, Clone, Deserialize, Serialize)] pub struct InferredConnectionGraph { diff --git a/lib/dal/src/context.rs b/lib/dal/src/context.rs index 96f0cf3df2..afc1f3faf8 100644 --- a/lib/dal/src/context.rs +++ b/lib/dal/src/context.rs @@ -2,6 +2,7 @@ use std::collections::HashSet; use std::time::Duration; use std::{fmt, mem, path::PathBuf, sync::Arc}; +use anyhow::Result; use futures::future::BoxFuture; use futures::Future; use rebaser_client::api_types::enqueue_updates_response::v1::RebaseStatus; @@ -234,9 +235,9 @@ impl ConnectionState { async fn start_txns(self) -> TransactionsResult { match self { - Self::Invalid => Err(TransactionsError::TxnStart("invalid")), + Self::Invalid => Err(TransactionsError::TxnStart("invalid").into()), Self::Connections(conns) => Ok(Self::Transactions(conns.start_txns().await?)), - Self::Transactions(_) => Err(TransactionsError::TxnStart("transactions")), + Self::Transactions(_) => Err(TransactionsError::TxnStart("transactions").into()), } } @@ -310,7 +311,7 @@ impl ConnectionState { let conns = txns.blocking_commit_into_conns(maybe_rebase).await?; Ok(Self::Connections(conns)) } - Self::Invalid => Err(TransactionsError::TxnCommit), + Self::Invalid => Err(TransactionsError::TxnCommit.into()), } } @@ -324,7 +325,7 @@ impl ConnectionState { let conns = txns.rollback_into_conns().await?; Ok(Self::Connections(conns)) } - Self::Invalid => Err(TransactionsError::TxnRollback), + Self::Invalid => Err(TransactionsError::TxnRollback.into()), } } } @@ -381,7 +382,7 @@ impl DalContext { Ok(workspace.default_change_set_id()) } - pub async fn get_workspace_token(&self) -> Result, TransactionsError> { + pub async fn get_workspace_token(&self) -> Result> { let workspace_pk = self .tenancy() .workspace_pk_opt() @@ -392,7 +393,7 @@ impl DalContext { Ok(workspace.token()) } - pub async fn get_workspace(&self) -> Result { + pub async fn get_workspace(&self) -> Result { let workspace_pk = self.tenancy().workspace_pk().unwrap_or(WorkspacePk::NONE); let workspace = Workspace::get_by_pk(self, &workspace_pk) .await? @@ -408,22 +409,17 @@ impl DalContext { .map_err(|err| TransactionsError::ChangeSet(err.to_string()))? .ok_or(TransactionsError::ChangeSetNotFound(self.change_set_id()))?; - let workspace_snapshot = WorkspaceSnapshot::find_for_change_set(self, change_set.id) - .await - .map_err(|err| TransactionsError::WorkspaceSnapshot(Box::new(err)))?; + let workspace_snapshot = + WorkspaceSnapshot::find_for_change_set(self, change_set.id).await?; self.set_change_set(change_set)?; self.set_workspace_snapshot(workspace_snapshot); Ok(()) } - pub async fn write_snapshot( - &self, - ) -> Result, TransactionsError> { + pub async fn write_snapshot(&self) -> Result> { if let Some(snapshot) = &self.workspace_snapshot { - Ok(Some(snapshot.write(self).await.map_err(|err| { - TransactionsError::WorkspaceSnapshot(Box::new(err)) - })?)) + Ok(Some(snapshot.write(self).await?)) } else { Ok(None) } @@ -472,9 +468,10 @@ impl DalContext { from_change_set_id: ChangeSetId, ) -> TransactionsResult<( RequestId, - BoxFuture<'static, Result>, + BoxFuture<'static, Result>, )> { - self.rebaser() + Ok(self + .rebaser() .enqueue_updates_from_change_set_with_reply( workspace_pk, change_set_id, @@ -482,8 +479,7 @@ impl DalContext { from_change_set_id, self.event_session_id, ) - .await - .map_err(Into::into) + .await?) } async fn commit_internal( @@ -541,9 +537,7 @@ impl DalContext { Ok(rebase_batch_address) } - async fn write_current_rebase_batch( - &self, - ) -> Result, TransactionsError> { + async fn write_current_rebase_batch(&self) -> Result> { Ok(if let Some(snapshot) = &self.workspace_snapshot { if let Some(rebase_batch) = snapshot.current_rebase_batch().await.map_err(Box::new)? { Some(self.write_rebase_batch(rebase_batch).await?) @@ -641,7 +635,7 @@ impl DalContext { } /// Fetch the workspace snapshot for the current visibility - pub fn workspace_snapshot(&self) -> Result, WorkspaceSnapshotError> { + pub fn workspace_snapshot(&self) -> Result> { match &self.workspace_snapshot { Some(workspace_snapshot) => Ok(workspace_snapshot.clone()), None => Err(WorkspaceSnapshotError::WorkspaceSnapshotNotFetched), @@ -818,7 +812,7 @@ impl DalContext { pub async fn add_dependent_values_and_enqueue( &self, ids: Vec>, - ) -> Result<(), WorkspaceSnapshotError> { + ) -> Result<()> { for id in ids { self.workspace_snapshot()? .add_dependent_value_root(DependentValueRoot::Unfinished(id.into())) @@ -896,7 +890,7 @@ impl DalContext { } /// Gets the dal context's txns. - pub async fn txns(&self) -> Result, TransactionsError> { + pub async fn txns(&self) -> Result> { let mut guard = self.conns_state.lock().await; let conns_state = guard.take(); @@ -1246,7 +1240,7 @@ impl DalContextBuilder { // access to, *AND* that the Change Set requested is one of the Change Sets for _that_ // workspace. if !(user_workspaces.contains(&workspace_pk) && workspace_has_change_set) { - return Err(TransactionsError::BadWorkspaceAndChangeSet); + return Err(TransactionsError::BadWorkspaceAndChangeSet.into()); } } } @@ -1358,7 +1352,7 @@ pub enum TransactionsError { WorkspaceSnapshot(#[from] Box), } -pub type TransactionsResult = Result; +pub type TransactionsResult = Result; impl From for TransactionsError { fn from(err: WorkspaceError) -> Self { diff --git a/lib/dal/src/diagram.rs b/lib/dal/src/diagram.rs index f469a0cf87..94acc983f1 100644 --- a/lib/dal/src/diagram.rs +++ b/lib/dal/src/diagram.rs @@ -2,6 +2,7 @@ mod diagram_object; pub mod geometry; pub mod view; +use anyhow::Result; use petgraph::prelude::*; use serde::{Deserialize, Serialize}; use si_data_pg::PgError; @@ -138,7 +139,7 @@ pub enum DiagramError { WorkspaceSnapshot(#[from] WorkspaceSnapshotError), } -pub type DiagramResult = Result; +pub type DiagramResult = Result; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] #[serde(rename_all(serialize = "camelCase"))] @@ -641,21 +642,23 @@ impl Diagram { for geometry in Geometry::list_by_view_id(ctx, view_id).await? { let geo_represents = match Geometry::represented_id(ctx, geometry.id()).await { Ok(r) => r, - Err(DiagramError::RepresentedNotFoundForGeometry(geo_id)) => { - let changeset_id = ctx.change_set_id(); - // NOTE(victor): The first version of views didn't delete geometries with components, - // so we have dangling geometries in some workspaces. We should clean this up at some point, - // but we just skip orphan geometries here to make assemble work. - - debug!( - si.change_set.id = %changeset_id, - si.geometry.id = %geo_id, - "Could not find represented node for geometry - skipping" - ); - - continue; - } - Err(e) => return Err(e), + Err(error) => match error.downcast_ref() { + Some(DiagramError::RepresentedNotFoundForGeometry(geo_id)) => { + let changeset_id = ctx.change_set_id(); + // NOTE(victor): The first version of views didn't delete geometries with components, + // so we have dangling geometries in some workspaces. We should clean this up at some point, + // but we just skip orphan geometries here to make assemble work. + + debug!( + si.change_set.id = %changeset_id, + si.geometry.id = %geo_id, + "Could not find represented node for geometry - skipping" + ); + + continue; + } + _ => return Err(error), + }, }; match geo_represents { GeometryRepresents::Component(component_id) => { diff --git a/lib/dal/src/func.rs b/lib/dal/src/func.rs index b5f0fee803..635e8bf8d0 100644 --- a/lib/dal/src/func.rs +++ b/lib/dal/src/func.rs @@ -1,3 +1,4 @@ +use anyhow::Result; use argument::{FuncArgument, FuncArgumentError}; use authoring::{FuncAuthoringClient, FuncAuthoringError}; use base64::{engine::general_purpose, Engine}; @@ -92,7 +93,7 @@ pub enum FuncError { WorkspaceSnapshot(#[from] WorkspaceSnapshotError), } -pub type FuncResult = Result; +pub type FuncResult = Result; impl From for FuncContent { fn from(value: Func) -> Self { @@ -319,7 +320,7 @@ impl Func { Self::get_intrinsic_kind_by_id(ctx, id) .await? - .ok_or(FuncError::IntrinsicFuncNotFound(func.name)) + .ok_or(FuncError::IntrinsicFuncNotFound(func.name).into()) } pub async fn get_intrinsic_kind_by_id( @@ -420,7 +421,7 @@ impl Func { pub fn error_if_locked(&self) -> FuncResult<()> { if self.is_locked { - return Err(FuncError::FuncLocked(self.id)); + return Err(FuncError::FuncLocked(self.id).into()); } Ok(()) } @@ -433,10 +434,10 @@ impl Func { let id: Ulid = func_id.into(); let node_index = match workspace_snapshot.get_node_index_by_id(id).await { Ok(node_index) => node_index, - Err(WorkspaceSnapshotError::WorkspaceSnapshotGraph( - WorkspaceSnapshotGraphError::NodeWithIdNotFound(_), - )) => return Ok(None), - Err(err) => return Err(err.into()), + Err(error) => match error.downcast_ref() { + Some(WorkspaceSnapshotGraphError::NodeWithIdNotFound(_)) => return Ok(None), + _ => return Err(error), + }, }; let node_weight = workspace_snapshot.get_node_weight(node_index).await?; @@ -530,12 +531,8 @@ impl Func { pub async fn delete_by_id(ctx: &DalContext, id: FuncId) -> FuncResult { let func = Self::get_by_id_or_error(ctx, id).await?; // Check that we can remove the func. - if !FuncBinding::for_func_id(ctx, id) - .await - .map_err(Box::new)? - .is_empty() - { - return Err(FuncError::FuncToBeDeletedHasBindings(id)); + if !FuncBinding::for_func_id(ctx, id).await?.is_empty() { + return Err(FuncError::FuncToBeDeletedHasBindings(id).into()); } // Now, we can remove the func. @@ -549,7 +546,7 @@ impl Func { let name = intrinsic.name(); Self::find_id_by_name(ctx, name) .await? - .ok_or(FuncError::IntrinsicFuncNotFound(name.to_owned())) + .ok_or(FuncError::IntrinsicFuncNotFound(name.to_owned()).into()) } /// List all [`Funcs`](Func) in the workspace @@ -676,18 +673,11 @@ impl Func { ) .await?; - for arg in FuncArgument::list_for_func(ctx, self.id) - .await - .map_err(Box::new)? - { + for arg in FuncArgument::list_for_func(ctx, self.id).await? { // create new func args for the new func - FuncArgument::new(ctx, arg.name, arg.kind, arg.element_kind, new_func.id) - .await - .map_err(Box::new)?; + FuncArgument::new(ctx, arg.name, arg.kind, arg.element_kind, new_func.id).await?; } - FuncArgument::list_for_func(ctx, new_func.id) - .await - .map_err(Box::new)?; + FuncArgument::list_for_func(ctx, new_func.id).await?; Ok(new_func) } @@ -697,7 +687,7 @@ impl Func { new_name: String, ) -> FuncResult { if new_name == self.name.clone() { - return Err(FuncError::FuncNameInUse(new_name)); + return Err(FuncError::FuncNameInUse(new_name).into()); } let duplicated_func = Self::new( @@ -735,9 +725,7 @@ impl Func { let bindings: Vec = bindings.into_iter().map(Into::into).collect_vec(); - let args = FuncArgument::list_for_func(ctx, self.id) - .await - .map_err(Box::new)?; + let args = FuncArgument::list_for_func(ctx, self.id).await?; let mut arguments = vec![]; for arg in args { arguments.push(si_frontend_types::FuncArgument { diff --git a/lib/dal/src/func/argument.rs b/lib/dal/src/func/argument.rs index f9e787bc53..649f70aa8f 100644 --- a/lib/dal/src/func/argument.rs +++ b/lib/dal/src/func/argument.rs @@ -1,3 +1,4 @@ +use anyhow::Result; use postgres_types::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; use si_events::ContentHash; @@ -61,7 +62,7 @@ pub enum FuncArgumentError { WorkspaceSnapshot(#[from] WorkspaceSnapshotError), } -type FuncArgumentResult = Result; +type FuncArgumentResult = Result; #[remain::sorted] #[derive( diff --git a/lib/dal/src/func/runner.rs b/lib/dal/src/func/runner.rs index 8c4d2ad828..b59a6e9097 100644 --- a/lib/dal/src/func/runner.rs +++ b/lib/dal/src/func/runner.rs @@ -1,3 +1,4 @@ +use anyhow::Result; use serde_json; use std::collections::VecDeque; use std::sync::Arc; @@ -146,7 +147,7 @@ pub enum FuncRunnerError { WsEvent(#[from] WsEventError), } -pub type FuncRunnerResult = Result; +pub type FuncRunnerResult = Result; pub type FuncRunnerValueChannel = oneshot::Receiver>; @@ -1024,16 +1025,12 @@ impl FuncRunner { span: &Span, ) -> FuncRunnerResult { let func = Func::get_by_id_or_error(ctx, func_id).await?; - let prototype = ActionPrototype::get_by_id(ctx, action_prototype_id) - .await - .map_err(Box::new)?; + let prototype = ActionPrototype::get_by_id(ctx, action_prototype_id).await?; let maybe_action_id = - Action::find_equivalent(ctx, action_prototype_id, Some(component_id)) - .await - .map_err(Box::new)?; + Action::find_equivalent(ctx, action_prototype_id, Some(component_id)).await?; let maybe_action_originating_change_set_id = match maybe_action_id { Some(action_id) => { - let action = Action::get_by_id(ctx, action_id).await.map_err(Box::new)?; + let action = Action::get_by_id(ctx, action_id).await?; Some(action.originating_changeset_id()) } None => None, @@ -1196,7 +1193,7 @@ impl FuncRunner { } if !ctx.history_actor().email_is_systeminit(ctx).await? { - return Err(FuncRunnerError::DoNotHavePermissionToKillExecution); + return Err(FuncRunnerError::DoNotHavePermissionToKillExecution.into()); } let result = ctx @@ -1226,7 +1223,7 @@ impl FuncRunner { // suffice... oh words, do not haunt me. Ok(()) } - FunctionResult::Failure(err) => Err(FuncRunnerError::KillExecutionFailure(err)), + FunctionResult::Failure(err) => Err(FuncRunnerError::KillExecutionFailure(err).into()), } } @@ -1291,10 +1288,11 @@ impl FuncRunner { // Skip secret if unauthorized // Skip secret if we can't find keypair let decrypted_secret = match encrypted_secret.decrypt(ctx).await { - Err(SecretError::KeyPair(KeyPairError::UnauthorizedKeyAccess)) - | Err(SecretError::KeyPair(KeyPairError::KeyPairNotFound(_))) => { - continue; - } + Err(error) => match error.downcast_ref() { + Some(KeyPairError::UnauthorizedKeyAccess) + | Some(KeyPairError::KeyPairNotFound(_)) => continue, + _ => Err(error), + }, other_result => other_result, }?; @@ -1362,7 +1360,8 @@ impl FuncRunner { return Err(FuncRunnerError::TooManyAttributeValues( component_id, secret_child_prop_id, - )); + ) + .into()); } let attribute_value_id = *attribute_value_ids @@ -1384,7 +1383,8 @@ impl FuncRunner { component_id, secret_child_prop_id, attribute_prototype_argument_ids.clone(), - )); + ) + .into()); } // If there's not attribute prototype argument yet, the prototype is either using "si:unset" or nothing @@ -1441,7 +1441,8 @@ impl FuncRunner { secret_child_prop_id, attribute_prototype_argument_id, component_id, - )) + ) + .into()) } } } @@ -1716,18 +1717,19 @@ impl FuncRunnerExecutionTask { .await } FuncBackendKind::JsReconciliation => { - return Err(FuncRunnerError::ReconciliationFuncsNoLongerSupported( - self.func.id, - )) + return Err( + FuncRunnerError::ReconciliationFuncsNoLongerSupported(self.func.id).into(), + ) } FuncBackendKind::JsValidation => { - return Err(FuncRunnerError::DirectValidationFuncsNoLongerSupported( - self.func.id, - )) + return Err( + FuncRunnerError::DirectValidationFuncsNoLongerSupported(self.func.id).into(), + ) } FuncBackendKind::JsAuthentication => { return Err( - FuncRunnerError::DirectAuthenticationFuncExecutionUnsupported(self.func.id), + FuncRunnerError::DirectAuthenticationFuncExecutionUnsupported(self.func.id) + .into(), ) } FuncBackendKind::Management => { @@ -1815,7 +1817,8 @@ impl FuncRunnerExecutionTask { kind, message, backend, - })); + } + .into())); } Err(err) => { let mut next_state_inner = Arc::unwrap_or_clone(running_state_func_run.clone()); diff --git a/lib/dal/src/history_event.rs b/lib/dal/src/history_event.rs index 1427d466d8..4cb215425c 100644 --- a/lib/dal/src/history_event.rs +++ b/lib/dal/src/history_event.rs @@ -1,3 +1,4 @@ +use anyhow::Result; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use si_data_nats::NatsError; @@ -30,7 +31,7 @@ pub enum HistoryEventError { User(String), } -pub type HistoryEventResult = Result; +pub type HistoryEventResult = Result; #[remain::sorted] #[derive(Deserialize, Serialize, Debug, PartialEq, Eq, StrumDisplay, Clone, Copy, Hash)] diff --git a/lib/dal/src/input_sources.rs b/lib/dal/src/input_sources.rs index 2ec3472307..6617364648 100644 --- a/lib/dal/src/input_sources.rs +++ b/lib/dal/src/input_sources.rs @@ -1,3 +1,4 @@ +use anyhow::Result; use serde::{Deserialize, Serialize}; use std::collections::VecDeque; use thiserror::Error; @@ -25,7 +26,7 @@ pub enum InputSourcesError { WorkspaceSnapshot(#[from] WorkspaceSnapshotError), } -type InputSourcesResult = Result; +type InputSourcesResult = Result; #[derive(Deserialize, Serialize, Debug)] #[serde(rename_all = "camelCase")] diff --git a/lib/dal/src/key_pair.rs b/lib/dal/src/key_pair.rs index 7dedf78459..da367cfbb2 100644 --- a/lib/dal/src/key_pair.rs +++ b/lib/dal/src/key_pair.rs @@ -1,3 +1,4 @@ +use anyhow::Result; use base64::{engine::general_purpose, Engine}; use serde::{Deserialize, Serialize}; use si_crypto::{SymmetricCryptoError, SymmetricCryptoService, SymmetricNonce}; @@ -50,7 +51,7 @@ pub enum KeyPairError { Workspace(#[from] Box), } -pub type KeyPairResult = Result; +pub type KeyPairResult = Result; pub use si_id::KeyPairPk; @@ -113,13 +114,13 @@ impl KeyPair { pub async fn get_by_pk(ctx: &DalContext, pk: KeyPairPk) -> KeyPairResult { let Some(row) = ctx.txns().await?.pg().query_opt(GET_BY_PK, &[&pk]).await? else { - return Err(KeyPairError::KeyPairNotFound(pk)); + return Err(KeyPairError::KeyPairNotFound(pk).into()); }; let json: serde_json::Value = row.try_get("object")?; let key_pair_row: KeyPairRow = serde_json::from_value(json)?; if key_pair_row.workspace_pk != ctx.tenancy().workspace_pk()? { - return Err(KeyPairError::UnauthorizedKeyAccess); + return Err(KeyPairError::UnauthorizedKeyAccess.into()); } let key_pair = key_pair_row.decrypt_into(ctx.symmetric_crypto_service())?; @@ -134,9 +135,8 @@ impl KeyPair { pub async fn workspace(&self, ctx: &DalContext) -> KeyPairResult { Workspace::get_by_pk(ctx, &self.workspace_pk) - .await - .map_err(Box::new)? - .ok_or(KeyPairError::InvalidWorkspace(self.workspace_pk)) + .await? + .ok_or(KeyPairError::InvalidWorkspace(self.workspace_pk).into()) } fn gen_keys( diff --git a/lib/dal/src/module.rs b/lib/dal/src/module.rs index 917f673637..326ae5ea0b 100644 --- a/lib/dal/src/module.rs +++ b/lib/dal/src/module.rs @@ -2,6 +2,7 @@ use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; use std::sync::Arc; +use anyhow::Result; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use si_events::ulid::Ulid; @@ -63,7 +64,7 @@ pub enum ModuleError { WorkspaceSnapshot(#[from] WorkspaceSnapshotError), } -pub type ModuleResult = Result; +pub type ModuleResult = Result; pub use si_id::ModuleId; @@ -501,7 +502,8 @@ impl Module { schema_id, existing.latest_hash, latest_module.latest_hash, - )); + ) + .into()); } Entry::Vacant(entry) => { entry.insert(latest_module.to_owned()); @@ -601,10 +603,7 @@ impl Module { let name = name.as_ref().trim(); let version = version.as_ref().trim(); if name.is_empty() || version.is_empty() { - return Err(ModuleError::EmptyMetadata( - name.to_string(), - version.to_string(), - )); + return Err(ModuleError::EmptyMetadata(name.to_string(), version.to_string()).into()); } // The frontend will send us the schema variant as this is what we care about from diff --git a/lib/dal/src/prompt_override.rs b/lib/dal/src/prompt_override.rs index 73829f7c0c..caa4ecd090 100644 --- a/lib/dal/src/prompt_override.rs +++ b/lib/dal/src/prompt_override.rs @@ -1,4 +1,5 @@ use crate::{DalContext, WsEvent, WsEventResult, WsPayload}; +use anyhow::Result; use serde::{Deserialize, Serialize}; use std::collections::HashSet; use telemetry::prelude::*; @@ -15,7 +16,7 @@ pub enum PromptOverrideError { WsEvent(#[from] crate::WsEventError), } -pub type Result = std::result::Result; +// pub type Result = std::result::Result; #[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Eq)] #[serde(rename_all = "camelCase")] diff --git a/lib/dal/src/prop.rs b/lib/dal/src/prop.rs index d96af9e289..8b273efb71 100644 --- a/lib/dal/src/prop.rs +++ b/lib/dal/src/prop.rs @@ -1,3 +1,4 @@ +use anyhow::Result; use async_recursion::async_recursion; use petgraph::prelude::*; use serde::{Deserialize, Serialize}; @@ -85,7 +86,7 @@ pub enum PropError { WorkspaceSnapshot(#[from] WorkspaceSnapshotError), } -pub type PropResult = Result; +pub type PropResult = Result; pub const SECRET_KIND_WIDGET_OPTION_LABEL: &str = "secretKind"; @@ -470,8 +471,7 @@ impl Prop { root_prop.id, EdgeWeightKind::new_use(), ) - .await - .map_err(Box::new)?; + .await?; Ok(root_prop) } @@ -577,14 +577,14 @@ impl Prop { content_inner.content_address().into(); match content_addr_discrim { ContentAddressDiscriminants::SchemaVariant => None, - _ => return Err(PropError::PropParentInvalid(prop_id)), + _ => return Err(PropError::PropParentInvalid(prop_id).into()), } } NodeWeight::SchemaVariant(_) => None, - _ => return Err(PropError::PropParentInvalid(prop_id)), + _ => return Err(PropError::PropParentInvalid(prop_id).into()), }, ), - None => Err(PropError::PropIsOrphan(prop_id)), + None => Err(PropError::PropIsOrphan(prop_id).into()), } } @@ -633,7 +633,8 @@ impl Prop { prop_id, single_child_prop_id, direct_child_prop_ids_should_only_be_one, - )); + ) + .into()); } Ok(single_child_prop_id) @@ -731,7 +732,7 @@ impl Prop { .await? .first() .copied() - .ok_or(PropError::MapOrArrayMissingElementProp(prop_id)) + .ok_or(PropError::MapOrArrayMissingElementProp(prop_id).into()) } pub async fn find_child_prop_index_by_name( @@ -757,10 +758,7 @@ impl Prop { } } - Err(PropError::ChildPropNotFoundByName( - node_index, - child_name.as_ref().to_string(), - )) + Err(PropError::ChildPropNotFoundByName(node_index, child_name.as_ref().to_string()).into()) } /// Find the `SchemaVariantId`` for a given prop. If the prop tree is @@ -790,7 +788,7 @@ impl Prop { NodeWeight::SchemaVariant(schema_variant) => { Ok(Some(schema_variant.id().into())) } - _ => Err(PropError::PropParentInvalid(root_prop_id)), + _ => Err(PropError::PropParentInvalid(root_prop_id).into()), } } None => Ok(None), @@ -815,9 +813,10 @@ impl Prop { ) -> PropResult> { match Self::find_prop_id_by_path(ctx, schema_variant_id, path).await { Ok(prop_id) => Ok(Some(prop_id)), - Err(err) => match err { - PropError::ChildPropNotFoundByName(_, _) => Ok(None), - err => Err(err), + Err(error) => match error.downcast_ref::() { + Some(PropError::ChildPropNotFoundByName(_, _)) => Ok(None), + Some(_prop_err) => Err(error), + None => Err(error), }, } } @@ -976,7 +975,7 @@ impl Prop { let prop = Self::get_by_id(ctx, prop_id).await?; if !prop.kind.is_scalar() { - return Err(PropError::SetDefaultForNonScalar(prop_id, prop.kind)); + return Err(PropError::SetDefaultForNonScalar(prop_id, prop.kind).into()); } let prototype_id = Self::prototype_id(ctx, prop_id).await?; diff --git a/lib/dal/src/qualification.rs b/lib/dal/src/qualification.rs index 7c4e43c673..8f818d8dbc 100644 --- a/lib/dal/src/qualification.rs +++ b/lib/dal/src/qualification.rs @@ -1,3 +1,4 @@ +use anyhow::Result; use serde::{Deserialize, Serialize}; use si_data_pg::PgError; use si_layer_cache::LayerDbError; @@ -47,7 +48,7 @@ pub enum QualificationSummaryError { StandardModel(#[from] StandardModelError), } -pub type QualificationSummaryResult = Result; +pub type QualificationSummaryResult = Result; impl QualificationSummary { #[instrument(level = "debug", skip_all)] @@ -175,7 +176,7 @@ impl QualificationView { pub async fn new( ctx: &DalContext, attribute_value: AttributeValue, - ) -> Result, QualificationError> { + ) -> QualificationSummaryResult> { let maybe_qual_run = ctx .layer_db() .func_run() @@ -252,7 +253,7 @@ impl QualificationView { pub async fn new_for_validations( ctx: &DalContext, component_id: ComponentId, - ) -> Result, QualificationError> { + ) -> QualificationSummaryResult> { let mut output = Vec::new(); let mut status = QualificationSubCheckStatus::Success; diff --git a/lib/dal/src/resource_metadata.rs b/lib/dal/src/resource_metadata.rs index 4fba84269b..1ff739d3cc 100644 --- a/lib/dal/src/resource_metadata.rs +++ b/lib/dal/src/resource_metadata.rs @@ -25,6 +25,7 @@ while_true )] +use anyhow::Result; use telemetry::prelude::*; use thiserror::Error; use veritech_client::ResourceStatus; @@ -41,7 +42,7 @@ pub enum ResourceMetadataError { Component(#[from] ComponentError), } -type ResourceMetadataResult = Result; +type ResourceMetadataResult = Result; /// Collect [`ResourceMetadata`] for every [`Component`] in the workspace. #[instrument(name = "resource_metadata.list", level = "debug", skip(ctx))] diff --git a/lib/dal/src/schema.rs b/lib/dal/src/schema.rs index 536a3e4a71..8f0ebb0a6f 100644 --- a/lib/dal/src/schema.rs +++ b/lib/dal/src/schema.rs @@ -1,3 +1,4 @@ +use anyhow::Result; use petgraph::Outgoing; use serde::{Deserialize, Serialize}; use si_events::ContentHash; @@ -65,7 +66,7 @@ pub enum SchemaError { WorkspaceSnapshot(#[from] WorkspaceSnapshotError), } -pub type SchemaResult = Result; +pub type SchemaResult = Result; pub use si_id::SchemaId; @@ -214,7 +215,7 @@ impl Schema { ) -> SchemaResult { Self::get_default_schema_variant_by_id(ctx, schema_id) .await? - .ok_or(SchemaError::DefaultSchemaVariantNotFound(schema_id)) + .ok_or(SchemaError::DefaultSchemaVariantNotFound(schema_id).into()) } /// This method returns all [`SchemaVariantIds`](SchemaVariant) that are used by the [`Schema`] @@ -508,11 +509,7 @@ impl Schema { pub async fn all_func_ids(ctx: &DalContext, id: SchemaId) -> SchemaResult> { let mut func_ids = HashSet::new(); for schema_variant_id in Self::list_schema_variant_ids(ctx, id).await? { - func_ids.extend( - SchemaVariant::all_func_ids(ctx, schema_variant_id) - .await - .map_err(Box::new)?, - ); + func_ids.extend(SchemaVariant::all_func_ids(ctx, schema_variant_id).await?); } Ok(func_ids) } diff --git a/lib/dal/src/schema/variant.rs b/lib/dal/src/schema/variant.rs index 2af9a3192a..8471a2189e 100644 --- a/lib/dal/src/schema/variant.rs +++ b/lib/dal/src/schema/variant.rs @@ -3,6 +3,7 @@ use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::Arc; +use anyhow::Result; use chrono::Utc; use petgraph::{Direction, Outgoing}; use serde::{Deserialize, Serialize}; @@ -179,7 +180,7 @@ pub enum SchemaVariantError { WorkspaceSnapshot(#[from] WorkspaceSnapshotError), } -pub type SchemaVariantResult = Result; +pub type SchemaVariantResult = Result; pub use si_id::SchemaVariantId; @@ -706,13 +707,10 @@ impl SchemaVariant { let node_index = match maybe_node_result { Ok(node_index) => node_index, - Err(e) => { - return if e.is_node_with_id_not_found() { - Ok(None) - } else { - Err(SchemaVariantError::from(e)) - } - } + Err(error) => match error.downcast_ref::() { + Some(e) if e.is_node_with_id_not_found() => return Ok(None), + _ => return Err(error), + }, }; let node_weight = workspace_snapshot.get_node_weight(node_index).await?; @@ -895,7 +893,7 @@ impl SchemaVariant { pub async fn error_if_locked(ctx: &DalContext, id: SchemaVariantId) -> SchemaVariantResult<()> { match Self::is_locked_by_id(ctx, id).await? { - true => Err(SchemaVariantError::SchemaVariantLocked(id)), + true => Err(SchemaVariantError::SchemaVariantLocked(id).into()), false => Ok(()), } } @@ -1037,7 +1035,7 @@ impl SchemaVariant { pub fn asset_func_id_or_error(&self) -> SchemaVariantResult { self.asset_func_id - .ok_or(SchemaVariantError::MissingAssetFuncId(self.id)) + .ok_or(SchemaVariantError::MissingAssetFuncId(self.id).into()) } pub fn is_builtin(&self) -> bool { @@ -1113,7 +1111,7 @@ impl SchemaVariant { } } - Err(SchemaVariantError::RootNodeMissing(schema_variant_id)) + Err(SchemaVariantError::RootNodeMissing(schema_variant_id).into()) } pub async fn create_default_prototypes( @@ -1537,8 +1535,7 @@ impl SchemaVariant { component_id, leaf_kind, ) - .await - .map_err(Box::new)?; + .await?; let new_attribute_value = AttributeValue::new( ctx, @@ -1547,8 +1544,7 @@ impl SchemaVariant { Some(parent_attribute_value_id), key.clone(), ) - .await - .map_err(Box::new)?; + .await?; new_attribute_value_ids.push(new_attribute_value.id); } if !new_attribute_value_ids.is_empty() { @@ -2060,7 +2056,7 @@ impl SchemaVariant { } // This should be impossible to hit. - Err(SchemaVariantError::NotFoundForProp(prop_id)) + Err(SchemaVariantError::NotFoundForProp(prop_id).into()) } async fn find_for_root_prop_id( @@ -2084,7 +2080,7 @@ impl SchemaVariant { } } - Err(SchemaVariantError::NotFoundForRootProp(root_prop_id)) + Err(SchemaVariantError::NotFoundForRootProp(root_prop_id).into()) } /// Find the [`SchemaVariantId`](SchemaVariant) for the given [`InputSocketId`](InputSocket). @@ -2112,7 +2108,7 @@ impl SchemaVariant { } } - Err(SchemaVariantError::NotFoundForInputSocket(input_socket_id)) + Err(SchemaVariantError::NotFoundForInputSocket(input_socket_id).into()) } /// Find the [`SchemaVariantId`](SchemaVariant) for the given [`OutputSocketId`](OutputSocket). @@ -2140,9 +2136,7 @@ impl SchemaVariant { } } - Err(SchemaVariantError::NotFoundForOutputSocket( - output_socket_id, - )) + Err(SchemaVariantError::NotFoundForOutputSocket(output_socket_id).into()) } /// List all [`SchemaVariantIds`](SchemaVariant) for the provided @@ -2317,7 +2311,8 @@ impl SchemaVariant { SchemaVariantError::SecretDefiningSchemaVariantTooManyOutputSockets( output_socket_ids, secret_defining_id, - ), + ) + .into(), ); } let secret_output_socket = output_sockets.first().ok_or( diff --git a/lib/dal/src/secret.rs b/lib/dal/src/secret.rs index b0d2112b80..88914a9e9d 100644 --- a/lib/dal/src/secret.rs +++ b/lib/dal/src/secret.rs @@ -25,6 +25,7 @@ while_true )] +use anyhow::Result; use chrono::Utc; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -148,7 +149,7 @@ pub enum SecretError { } #[allow(missing_docs)] -pub type SecretResult = Result; +pub type SecretResult = Result; pub use si_id::SecretId; @@ -327,9 +328,11 @@ impl Secret { match encrypted_secret.key_pair(ctx).await { Ok(_) => Ok(true), - Err(SecretError::KeyPair(KeyPairError::KeyPairNotFound(_))) - | Err(SecretError::KeyPair(KeyPairError::UnauthorizedKeyAccess)) => Ok(false), - Err(err) => Err(err), + Err(error) => match error.downcast_ref::() { + Some(KeyPairError::KeyPairNotFound(_)) + | Some(KeyPairError::UnauthorizedKeyAccess) => Ok(false), + _ => Err(error), + }, } } @@ -551,7 +554,7 @@ impl Secret { } } - Err(SecretError::NotFoundForKey) + Err(SecretError::NotFoundForKey.into()) } /// Lists all [`Secrets`](Secret) in the current [`snapshot`](crate::WorkspaceSnapshot). diff --git a/lib/dal/src/secret/view.rs b/lib/dal/src/secret/view.rs index c01bfbf514..68fc16705a 100644 --- a/lib/dal/src/secret/view.rs +++ b/lib/dal/src/secret/view.rs @@ -1,3 +1,4 @@ +use anyhow::Result; use serde::{Deserialize, Serialize}; use thiserror::Error; @@ -17,7 +18,7 @@ pub enum SecretViewError { #[allow(missing_docs)] -pub type SecretViewResult = Result; +pub type SecretViewResult = Result; /// A [`view`](SecretView) of a corresponding [`Secret`]. #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] diff --git a/lib/dal/src/socket/debug.rs b/lib/dal/src/socket/debug.rs index caacf8dc27..a6954279b2 100644 --- a/lib/dal/src/socket/debug.rs +++ b/lib/dal/src/socket/debug.rs @@ -1,3 +1,4 @@ +use anyhow::Result; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use telemetry::prelude::*; @@ -37,7 +38,7 @@ pub struct SocketDebugView { pub name: String, pub inferred_connections: Vec, } -type SocketDebugViewResult = Result; +type SocketDebugViewResult = Result; #[remain::sorted] #[derive(Error, Debug)] diff --git a/lib/dal/src/socket/input.rs b/lib/dal/src/socket/input.rs index 8ee94fa3e7..7a5f37d243 100644 --- a/lib/dal/src/socket/input.rs +++ b/lib/dal/src/socket/input.rs @@ -1,3 +1,4 @@ +use anyhow::Result; use serde::{Deserialize, Serialize}; use si_frontend_types as frontend_types; use si_layer_cache::LayerDbError; @@ -71,7 +72,7 @@ pub enum InputSocketError { WorkspaceSnapshot(#[from] WorkspaceSnapshotError), } -pub type InputSocketResult = Result; +pub type InputSocketResult = Result; pub use si_id::InputSocketId; @@ -158,7 +159,6 @@ impl InputSocket { ctx.workspace_snapshot()? .get_input_socket_by_name_opt(ctx, name, schema_variant_id) .await - .map_err(Into::into) } pub async fn find_with_name_or_error( @@ -169,7 +169,9 @@ impl InputSocket { let name = name.as_ref(); Self::find_with_name(ctx, name, schema_variant_id) .await? - .ok_or_else(|| InputSocketError::NotFoundByName(name.to_string(), schema_variant_id)) + .ok_or_else(|| { + InputSocketError::NotFoundByName(name.to_string(), schema_variant_id).into() + }) } #[allow(clippy::too_many_arguments)] diff --git a/lib/dal/src/socket/output.rs b/lib/dal/src/socket/output.rs index ed85057268..409b20c329 100644 --- a/lib/dal/src/socket/output.rs +++ b/lib/dal/src/socket/output.rs @@ -1,3 +1,4 @@ +use anyhow::Result; use serde::{Deserialize, Serialize}; use si_events::ContentHash; use si_frontend_types as frontend_types; @@ -70,7 +71,7 @@ pub enum OutputSocketError { WorkspaceSnapshot(#[from] WorkspaceSnapshotError), } -pub type OutputSocketResult = Result; +pub type OutputSocketResult = Result; pub use si_id::OutputSocketId; @@ -191,8 +192,7 @@ impl OutputSocket { id.into(), EdgeWeightKind::Socket, ) - .await - .map_err(Box::new)?; + .await?; let attribute_prototype = AttributePrototype::new(ctx, func_id).await?; @@ -280,16 +280,13 @@ impl OutputSocket { Self::all_attribute_values_everywhere_for_output_socket_id(ctx, output_socket_id) .await? { - if AttributeValue::component_id(ctx, attribute_value_id) - .await - .map_err(Box::new)? - == component_id - { + if AttributeValue::component_id(ctx, attribute_value_id).await? == component_id { if result.is_some() { return Err(OutputSocketError::FoundTooManyForOutputSocketId( output_socket_id, component_id, - )); + ) + .into()); } result = Some(attribute_value_id); } @@ -299,7 +296,8 @@ impl OutputSocket { None => Err(OutputSocketError::MissingAttributeValueForComponent( output_socket_id, component_id, - )), + ) + .into()), } } @@ -400,7 +398,8 @@ impl OutputSocket { already_found.id(), output_socket.id(), schema_variant_id, - )); + ) + .into()); } None => maybe_output_socket = Some(output_socket), } @@ -417,7 +416,9 @@ impl OutputSocket { let name = name.as_ref(); Self::find_with_name(ctx, name, schema_variant_id) .await? - .ok_or_else(|| OutputSocketError::NotFoundByName(name.to_string(), schema_variant_id)) + .ok_or_else(|| { + OutputSocketError::NotFoundByName(name.to_string(), schema_variant_id).into() + }) } #[instrument(level="debug" skip(ctx))] @@ -460,7 +461,8 @@ impl OutputSocket { if !raw_sources.is_empty() { return Err(OutputSocketError::MultipleSocketsForAttributeValue( attribute_value_id, - )); + ) + .into()); } Some( workspace_snapshot diff --git a/lib/dal/src/standard_connection.rs b/lib/dal/src/standard_connection.rs index cd9e43018c..68a591ffa4 100644 --- a/lib/dal/src/standard_connection.rs +++ b/lib/dal/src/standard_connection.rs @@ -1,7 +1,9 @@ +use anyhow::Result; +use thiserror::Error; + use crate::{ EdgeWeightKind, EdgeWeightKindDiscriminants, TransactionsError, WorkspaceSnapshotError, }; -use thiserror::Error; #[derive(Debug, Error)] pub enum HelperError { @@ -13,7 +15,7 @@ pub enum HelperError { WorkspaceSnapshot(#[from] WorkspaceSnapshotError), } -pub type HelperResult = Result; +pub type HelperResult = Result; #[macro_export] macro_rules! implement_add_edge_to { @@ -26,7 +28,7 @@ macro_rules! implement_add_edge_to { ) => { paste::paste! { /// Inserts edge from source to destination with specified weight to the graph - pub async fn $add_fn(ctx: &$crate::DalContext, source_id: $source_id, destination_id: $destination_id, weight: $crate::EdgeWeightKind) -> $result<()> { + pub async fn $add_fn(ctx: &$crate::DalContext, source_id: $source_id, destination_id: $destination_id, weight: $crate::EdgeWeightKind) -> ::anyhow::Result<()> { if $crate::EdgeWeightKindDiscriminants::from(&weight) != $discriminant { return Err($crate::HelperError::InvalidEdgeWeight(weight, $discriminant))?; } @@ -43,7 +45,7 @@ macro_rules! implement_add_edge_to { /// Inserts ordered edge from source to destination with specified weight to the graph #[allow(dead_code)] - pub async fn [<$add_fn _ordered>](ctx: &DalContext, source_id: $source_id, destination_id: $destination_id, weight: $crate::EdgeWeightKind) -> $result<()> { + pub async fn [<$add_fn _ordered>](ctx: &DalContext, source_id: $source_id, destination_id: $destination_id, weight: $crate::EdgeWeightKind) -> ::anyhow::Result<()> { if $crate::EdgeWeightKindDiscriminants::from(&weight) != $discriminant { return Err($crate::HelperError::InvalidEdgeWeight(weight, $discriminant))?; } diff --git a/lib/dal/src/standard_model.rs b/lib/dal/src/standard_model.rs index 2cb4599d1e..06d3d17375 100644 --- a/lib/dal/src/standard_model.rs +++ b/lib/dal/src/standard_model.rs @@ -1,4 +1,5 @@ use crate::{Tenancy, TransactionsError, UserError, UserPk}; +use anyhow::Result; use chrono::{DateTime, Utc}; use postgres_types::ToSql; use serde::{de::DeserializeOwned, Serialize}; @@ -32,7 +33,7 @@ pub enum StandardModelError { UserNotFound(UserPk), } -pub type StandardModelResult = Result; +pub type StandardModelResult = Result; #[remain::sorted] #[derive(AsRefStr, Debug, Eq, PartialEq)] @@ -505,7 +506,7 @@ where ) .await?; row.try_get("updated_at") - .map_err(|_| StandardModelError::ModelMissing(table.to_string(), id.to_string())) + .map_err(|_| StandardModelError::ModelMissing(table.to_string(), id.to_string()).into()) } #[instrument(level = "trace", skip(ctx))] @@ -541,7 +542,7 @@ pub async fn delete_by_id( ) .await?; row.try_get("deleted_at") - .map_err(|_| StandardModelError::ModelMissing(table.to_string(), id.to_string())) + .map_err(|_| StandardModelError::ModelMissing(table.to_string(), id.to_string()).into()) } #[instrument(level = "trace", skip(ctx))] @@ -560,7 +561,7 @@ pub async fn delete_by_pk( ) .await?; row.try_get("updated_at") - .map_err(|_| StandardModelError::ModelMissing(table.to_string(), pk.to_string())) + .map_err(|_| StandardModelError::ModelMissing(table.to_string(), pk.to_string()).into()) } #[instrument(level = "trace", skip(ctx))] @@ -579,7 +580,7 @@ pub async fn undelete( ) .await?; row.try_get("updated_at") - .map_err(|_| StandardModelError::ModelMissing(table.to_string(), pk.to_string())) + .map_err(|_| StandardModelError::ModelMissing(table.to_string(), pk.to_string()).into()) } #[instrument(level = "trace", skip(ctx))] diff --git a/lib/dal/src/user.rs b/lib/dal/src/user.rs index da2c99c689..fd56099802 100644 --- a/lib/dal/src/user.rs +++ b/lib/dal/src/user.rs @@ -1,3 +1,4 @@ +use anyhow::Result; use serde::{Deserialize, Serialize}; use si_data_nats::NatsError; use si_data_pg::PgError; @@ -41,7 +42,7 @@ pub enum UserError { Transactions(#[from] TransactionsError), } -pub type UserResult = Result; +pub type UserResult = Result; pub use si_id::UserPk; @@ -123,7 +124,7 @@ impl User { pub async fn get_by_pk_or_error(ctx: &DalContext, pk: UserPk) -> UserResult { Self::get_by_pk(ctx, pk) .await? - .ok_or_else(|| UserError::NotFoundInTenancy(pk, *ctx.tenancy())) + .ok_or_else(|| UserError::NotFoundInTenancy(pk, *ctx.tenancy()).into()) } pub async fn authorize( diff --git a/lib/dal/src/validation.rs b/lib/dal/src/validation.rs index a1333b4b5a..dd941aac33 100644 --- a/lib/dal/src/validation.rs +++ b/lib/dal/src/validation.rs @@ -1,3 +1,4 @@ +use anyhow::Result; use serde::{Deserialize, Serialize}; use si_data_nats::NatsError; use si_data_pg::PgError; @@ -70,7 +71,7 @@ pub enum ValidationError { WorkspaceSnapshot(#[from] WorkspaceSnapshotError), } -pub type ValidationResult = Result; +pub type ValidationResult = Result; pub use si_id::ValidationOutputId; @@ -250,8 +251,7 @@ impl ValidationOutput { attribute_value_id: AttributeValueId, ) -> ValidationResult> { Ok(AttributeValue::prop_opt(ctx, attribute_value_id) - .await - .map_err(Box::new)? + .await? .and_then(|prop| prop.validation_format)) } @@ -326,13 +326,8 @@ impl ValidationOutput { ctx: &DalContext, component_id: ComponentId, ) -> ValidationResult> { - let component = Component::get_by_id(ctx, component_id) - .await - .map_err(Box::new)?; - let domain_av = component - .domain_prop_attribute_value(ctx) - .await - .map_err(Box::new)?; + let component = Component::get_by_id(ctx, component_id).await?; + let domain_av = component.domain_prop_attribute_value(ctx).await?; let mut outputs = vec![]; let mut queue = VecDeque::from(vec![domain_av]); @@ -343,9 +338,7 @@ impl ValidationOutput { .map(|node| node.validation); let children_av_ids = - AttributeValue::get_child_av_ids_in_order(ctx, attribute_value_id) - .await - .map_err(Box::new)?; + AttributeValue::get_child_av_ids_in_order(ctx, attribute_value_id).await?; queue.extend(children_av_ids); diff --git a/lib/dal/src/workspace.rs b/lib/dal/src/workspace.rs index 2e5af3451a..7c81be6ea6 100644 --- a/lib/dal/src/workspace.rs +++ b/lib/dal/src/workspace.rs @@ -1,3 +1,4 @@ +use anyhow::Result; use chrono::{DateTime, Utc}; use petgraph::Direction; use serde::{Deserialize, Serialize}; @@ -93,7 +94,7 @@ pub enum WorkspaceError { WorkspaceSnapshot(#[from] WorkspaceSnapshotError), } -pub type WorkspaceResult = Result; +pub type WorkspaceResult = Result; #[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)] pub struct Workspace { diff --git a/lib/dal/src/workspace_snapshot.rs b/lib/dal/src/workspace_snapshot.rs index f1f5376cc4..bc088e2e28 100644 --- a/lib/dal/src/workspace_snapshot.rs +++ b/lib/dal/src/workspace_snapshot.rs @@ -44,6 +44,7 @@ use std::collections::{HashMap, HashSet}; use std::sync::atomic::AtomicBool; use std::sync::Arc; +use anyhow::Result; use petgraph::prelude::*; pub use petgraph::Direction; use serde::{Deserialize, Serialize}; @@ -188,7 +189,7 @@ impl WorkspaceSnapshotError { } } -pub type WorkspaceSnapshotResult = Result; +pub type WorkspaceSnapshotResult = Result; /// The workspace graph. The public interface for this is provided through the the various `Ext` /// traits that are implemented for [`WorkspaceSnapshot`]. @@ -982,7 +983,7 @@ impl WorkspaceSnapshot { ) -> WorkspaceSnapshotResult { self.get_category_node(source, kind) .await? - .ok_or(WorkspaceSnapshotError::CategoryNodeNotFound(kind)) + .ok_or(WorkspaceSnapshotError::CategoryNodeNotFound(kind).into()) } pub async fn get_category_node( @@ -1690,8 +1691,7 @@ impl WorkspaceSnapshot { ) -> WorkspaceSnapshotResult> { let mut inferred_connection_write_guard = self.inferred_connection_graph.write().await; if inferred_connection_write_guard.is_none() { - *inferred_connection_write_guard = - Some(InferredConnectionGraph::new(ctx).await.map_err(Box::new)?); + *inferred_connection_write_guard = Some(InferredConnectionGraph::new(ctx).await?); } Ok(InferredConnectionsWriteGuard { diff --git a/lib/dal/src/workspace_snapshot/graph.rs b/lib/dal/src/workspace_snapshot/graph.rs index 59050b9047..c1045c05e4 100644 --- a/lib/dal/src/workspace_snapshot/graph.rs +++ b/lib/dal/src/workspace_snapshot/graph.rs @@ -1,3 +1,4 @@ +use anyhow::Result; use std::{fs::File, io::Write}; use deprecated::DeprecatedWorkspaceSnapshotGraphV1; @@ -100,7 +101,7 @@ pub enum WorkspaceSnapshotGraphError { WorkspacesConflict, } -pub type WorkspaceSnapshotGraphResult = Result; +pub type WorkspaceSnapshotGraphResult = Result; #[derive(Debug, Deserialize, Serialize, Clone, EnumDiscriminants)] #[strum_discriminants(derive(strum::Display, Serialize, Deserialize, EnumString, EnumIter))] diff --git a/lib/dal/src/workspace_snapshot/migrator.rs b/lib/dal/src/workspace_snapshot/migrator.rs index 2c69d2d1ea..bf5c9a32fb 100644 --- a/lib/dal/src/workspace_snapshot/migrator.rs +++ b/lib/dal/src/workspace_snapshot/migrator.rs @@ -14,6 +14,7 @@ use crate::{ ChangeSet, ChangeSetError, ChangeSetStatus, DalContext, TransactionsError, Visibility, Workspace, WorkspaceError, WorkspaceSnapshot, WorkspaceSnapshotError, }; +use anyhow::Result; use si_events::WorkspaceSnapshotAddress; use si_layer_cache::LayerDbError; use std::sync::Arc; @@ -55,7 +56,7 @@ pub enum SnapshotGraphMigratorError { WorkspaceSnapshotGraph(#[from] WorkspaceSnapshotGraphError), } -pub type SnapshotGraphMigratorResult = Result; +pub type SnapshotGraphMigratorResult = Result; pub struct SnapshotGraphMigrator; @@ -126,7 +127,7 @@ impl SnapshotGraphMigrator { .await?; continue; } else { - return Err(err)?; + return Err(err); } } }; @@ -194,7 +195,8 @@ impl SnapshotGraphMigrator { return Err(SnapshotGraphMigratorError::UnexpectedGraphVersion( workspace_snapshot_address, working_graph.into(), - )); + ) + .into()); } WorkspaceSnapshotGraph::V1(inner_graph) => { working_graph = WorkspaceSnapshotGraph::V2(migrate_v1_to_v2(inner_graph)?); diff --git a/lib/dal/src/workspace_snapshot/node_weight.rs b/lib/dal/src/workspace_snapshot/node_weight.rs index 2589d5d395..0e2aee1500 100644 --- a/lib/dal/src/workspace_snapshot/node_weight.rs +++ b/lib/dal/src/workspace_snapshot/node_weight.rs @@ -1,5 +1,6 @@ use std::num::TryFromIntError; +use anyhow::Result; use finished_dependent_value_root_node_weight::FinishedDependentValueRootNodeWeight; use serde::{Deserialize, Serialize}; use si_events::{merkle_tree_hash::MerkleTreeHash, ulid::Ulid, ContentHash, EncryptedSecretKey}; @@ -119,7 +120,7 @@ pub enum NodeWeightError { WorkspaceSnapshotGraph(#[from] Box), } -pub type NodeWeightResult = Result; +pub type NodeWeightResult = Result; /// **WARNING**: the order of this enum is important! Do not re-order elements. /// New variants must go at the end, even if it's not in lexical order! @@ -412,7 +413,9 @@ impl NodeWeight { | NodeWeight::DependentValueRoot(_) | NodeWeight::FinishedDependentValueRoot(_) | NodeWeight::Ordering(_) - | NodeWeight::DiagramObject(_) => Err(NodeWeightError::CannotSetContentHashOnKind), + | NodeWeight::DiagramObject(_) => { + Err(NodeWeightError::CannotSetContentHashOnKind.into()) + } NodeWeight::Geometry(w) => { traits::SiVersionedNodeWeight::inner_mut(w).new_content_hash(content_hash); Ok(()) @@ -501,7 +504,7 @@ impl NodeWeight { | NodeWeight::InputSocket(_) | NodeWeight::ManagementPrototype(_) | NodeWeight::DiagramObject(_) - | NodeWeight::SchemaVariant(_) => Err(NodeWeightError::CannotSetOrderOnKind), + | NodeWeight::SchemaVariant(_) => Err(NodeWeightError::CannotSetOrderOnKind.into()), } } @@ -550,7 +553,8 @@ impl NodeWeight { other => Err(NodeWeightError::UnexpectedNodeWeightVariant( NodeWeightDiscriminants::Action, other.into(), - )), + ) + .into()), } } @@ -560,7 +564,8 @@ impl NodeWeight { other => Err(NodeWeightError::UnexpectedNodeWeightVariant( NodeWeightDiscriminants::ActionPrototype, other.into(), - )), + ) + .into()), } } @@ -572,7 +577,8 @@ impl NodeWeight { other => Err(NodeWeightError::UnexpectedNodeWeightVariant( NodeWeightDiscriminants::AttributePrototypeArgument, other.into(), - )), + ) + .into()), } } @@ -582,7 +588,8 @@ impl NodeWeight { other => Err(NodeWeightError::UnexpectedNodeWeightVariant( NodeWeightDiscriminants::AttributeValue, other.into(), - )), + ) + .into()), } } @@ -594,7 +601,8 @@ impl NodeWeight { other => Err(NodeWeightError::UnexpectedNodeWeightVariant( NodeWeightDiscriminants::DependentValueRoot, other.into(), - )), + ) + .into()), } } @@ -604,7 +612,8 @@ impl NodeWeight { other => Err(NodeWeightError::UnexpectedNodeWeightVariant( NodeWeightDiscriminants::Component, other.into(), - )), + ) + .into()), } } @@ -614,7 +623,8 @@ impl NodeWeight { other => Err(NodeWeightError::UnexpectedNodeWeightVariant( NodeWeightDiscriminants::Geometry, other.into(), - )), + ) + .into()), } } @@ -624,7 +634,8 @@ impl NodeWeight { other => Err(NodeWeightError::UnexpectedNodeWeightVariant( NodeWeightDiscriminants::View, other.into(), - )), + ) + .into()), } } @@ -634,7 +645,8 @@ impl NodeWeight { other => Err(NodeWeightError::UnexpectedNodeWeightVariant( NodeWeightDiscriminants::DiagramObject, other.into(), - )), + ) + .into()), } } @@ -644,7 +656,8 @@ impl NodeWeight { other => Err(NodeWeightError::UnexpectedNodeWeightVariant( NodeWeightDiscriminants::Prop, other.into(), - )), + ) + .into()), } } @@ -654,7 +667,8 @@ impl NodeWeight { other => Err(NodeWeightError::UnexpectedNodeWeightVariant( NodeWeightDiscriminants::Func, other.into(), - )), + ) + .into()), } } @@ -664,7 +678,8 @@ impl NodeWeight { other => Err(NodeWeightError::UnexpectedNodeWeightVariant( NodeWeightDiscriminants::FuncArgument, other.into(), - )), + ) + .into()), } } @@ -674,7 +689,8 @@ impl NodeWeight { other => Err(NodeWeightError::UnexpectedNodeWeightVariant( NodeWeightDiscriminants::Secret, other.into(), - )), + ) + .into()), } } @@ -684,7 +700,8 @@ impl NodeWeight { other => Err(NodeWeightError::UnexpectedNodeWeightVariant( NodeWeightDiscriminants::Ordering, other.into(), - )), + ) + .into()), } } @@ -700,7 +717,8 @@ impl NodeWeight { return Err(NodeWeightError::UnexpectedContentAddressVariant( content_addr_discrim, inner_addr_discrim, - )); + ) + .into()); } Ok(inner.to_owned()) @@ -708,7 +726,8 @@ impl NodeWeight { other => Err(NodeWeightError::UnexpectedNodeWeightVariant( NodeWeightDiscriminants::Content, other.into(), - )), + ) + .into()), } } @@ -735,7 +754,8 @@ impl NodeWeight { other => Err(NodeWeightError::UnexpectedNodeWeightVariant( NodeWeightDiscriminants::InputSocket, other.into(), - )), + ) + .into()), } } @@ -745,7 +765,8 @@ impl NodeWeight { other => Err(NodeWeightError::UnexpectedNodeWeightVariant( NodeWeightDiscriminants::SchemaVariant, other.into(), - )), + ) + .into()), } } @@ -758,7 +779,8 @@ impl NodeWeight { NodeWeightDiscriminants::SchemaVariant, // &*other is to convert the `&mut` to `&`. NodeWeightDiscriminants::from(&*other), - )), + ) + .into()), } } diff --git a/lib/dal/src/workspace_snapshot/node_weight/component_node_weight.rs b/lib/dal/src/workspace_snapshot/node_weight/component_node_weight.rs index af0742c9a8..9bcbd6a697 100644 --- a/lib/dal/src/workspace_snapshot/node_weight/component_node_weight.rs +++ b/lib/dal/src/workspace_snapshot/node_weight/component_node_weight.rs @@ -89,7 +89,8 @@ impl ComponentNodeWeight { return Err(NodeWeightError::InvalidContentAddressForWeightKind( Into::::into(other).to_string(), ContentAddressDiscriminants::Component.to_string(), - )); + ) + .into()); } }; @@ -131,9 +132,7 @@ impl ComponentNodeWeight { default_view_idx: NodeIndex, component_node_weight: &ComponentNodeWeight, ) -> NodeWeightResult<()> { - let component_idx = v4_graph - .get_node_index_by_id(component_node_weight.id) - .map_err(|e| NodeWeightError::WorkspaceSnapshotGraph(Box::new(e)))?; + let component_idx = v4_graph.get_node_index_by_id(component_node_weight.id)?; let layer_db = ctx.layer_db(); let cas = layer_db.cas(); @@ -149,7 +148,8 @@ impl ComponentNodeWeight { return Err(NodeWeightError::UnexpectedComponentContentVersion( actual, ComponentContentDiscriminants::V1, - )); + ) + .into()); }; // Create geometry node @@ -168,39 +168,26 @@ impl ComponentNodeWeight { ctx.events_actor(), )?; - let geometry_id = v4_graph - .generate_ulid() - .map_err(|e| NodeWeightError::WorkspaceSnapshotGraph(Box::new(e)))?; + let geometry_id = v4_graph.generate_ulid()?; - let geometry_node_weight = NodeWeight::new_geometry( - geometry_id, - v4_graph - .generate_ulid() - .map_err(|e| NodeWeightError::WorkspaceSnapshotGraph(Box::new(e)))?, - content_address, - ); + let geometry_node_weight = + NodeWeight::new_geometry(geometry_id, v4_graph.generate_ulid()?, content_address); - let geometry_idx = v4_graph - .add_or_replace_node(geometry_node_weight) - .map_err(|e| NodeWeightError::WorkspaceSnapshotGraph(Box::new(e)))?; + let geometry_idx = v4_graph.add_or_replace_node(geometry_node_weight)?; // Connect geometry to component - v4_graph - .add_edge( - geometry_idx, - EdgeWeight::new(EdgeWeightKind::Represents), - component_idx, - ) - .map_err(|e| NodeWeightError::WorkspaceSnapshotGraph(Box::new(e)))?; + v4_graph.add_edge( + geometry_idx, + EdgeWeight::new(EdgeWeightKind::Represents), + component_idx, + )?; // Connect geometry to default view - v4_graph - .add_edge( - default_view_idx, - EdgeWeight::new(EdgeWeightKind::new_use()), - geometry_idx, - ) - .map_err(|e| NodeWeightError::WorkspaceSnapshotGraph(Box::new(e)))?; + v4_graph.add_edge( + default_view_idx, + EdgeWeight::new(EdgeWeightKind::new_use()), + geometry_idx, + )?; // Upgrade component content let updated_content = ComponentContent::V2(ComponentContentV2 { @@ -220,9 +207,7 @@ impl ComponentNodeWeight { updated_content_address, ); - v4_graph - .add_or_replace_node(upgraded_node_weight) - .map_err(|e| NodeWeightError::WorkspaceSnapshotGraph(Box::new(e)))?; + v4_graph.add_or_replace_node(upgraded_node_weight)?; Ok(()) } diff --git a/lib/dal/src/workspace_snapshot/node_weight/content_node_weight.rs b/lib/dal/src/workspace_snapshot/node_weight/content_node_weight.rs index 95268b1b69..f205c38e55 100644 --- a/lib/dal/src/workspace_snapshot/node_weight/content_node_weight.rs +++ b/lib/dal/src/workspace_snapshot/node_weight/content_node_weight.rs @@ -107,13 +107,15 @@ impl ContentNodeWeight { return Err(NodeWeightError::InvalidContentAddressForWeightKind( "Geometry".to_string(), "Content".to_string(), - )); + ) + .into()); } ContentAddress::InputSocket(_) => { return Err(NodeWeightError::InvalidContentAddressForWeightKind( "InputSocket".to_string(), "Content".to_string(), - )); + ) + .into()); } ContentAddress::JsonValue(_) => ContentAddress::JsonValue(content_hash), ContentAddress::Module(_) => ContentAddress::Module(content_hash), @@ -121,21 +123,26 @@ impl ContentNodeWeight { return Err(NodeWeightError::InvalidContentAddressForWeightKind( "Prop".to_string(), "Content".to_string(), - )); + ) + .into()); + } + ContentAddress::Root => { + return Err(NodeWeightError::CannotUpdateRootNodeContentHash.into()) } - ContentAddress::Root => return Err(NodeWeightError::CannotUpdateRootNodeContentHash), ContentAddress::Schema(_) => ContentAddress::Schema(content_hash), ContentAddress::SchemaVariant(_) => { return Err(NodeWeightError::InvalidContentAddressForWeightKind( "SchemaVariant".to_string(), "Content".to_string(), - )); + ) + .into()); } ContentAddress::Secret(_) => { return Err(NodeWeightError::InvalidContentAddressForWeightKind( "Secret".to_string(), "Content".to_string(), - )); + ) + .into()); } ContentAddress::StaticArgumentValue(_) => { ContentAddress::StaticArgumentValue(content_hash) @@ -151,7 +158,8 @@ impl ContentNodeWeight { return Err(NodeWeightError::InvalidContentAddressForWeightKind( "Geometry".to_string(), "Content".to_string(), - )); + ) + .into()); } }; diff --git a/lib/dal/src/workspace_snapshot/node_weight/func_argument_node_weight.rs b/lib/dal/src/workspace_snapshot/node_weight/func_argument_node_weight.rs index 2c33081749..f5f4c5436c 100644 --- a/lib/dal/src/workspace_snapshot/node_weight/func_argument_node_weight.rs +++ b/lib/dal/src/workspace_snapshot/node_weight/func_argument_node_weight.rs @@ -72,7 +72,8 @@ impl FuncArgumentNodeWeight { return Err(NodeWeightError::InvalidContentAddressForWeightKind( Into::::into(other).to_string(), ContentAddressDiscriminants::FuncArg.to_string(), - )); + ) + .into()); } }; diff --git a/lib/dal/src/workspace_snapshot/node_weight/func_node_weight.rs b/lib/dal/src/workspace_snapshot/node_weight/func_node_weight.rs index 59604c3023..bb7cf067c9 100644 --- a/lib/dal/src/workspace_snapshot/node_weight/func_node_weight.rs +++ b/lib/dal/src/workspace_snapshot/node_weight/func_node_weight.rs @@ -89,7 +89,8 @@ impl FuncNodeWeight { return Err(NodeWeightError::InvalidContentAddressForWeightKind( Into::::into(other).to_string(), ContentAddressDiscriminants::Func.to_string(), - )); + ) + .into()); } }; diff --git a/lib/dal/src/workspace_snapshot/node_weight/geometry_node_weight/v1.rs b/lib/dal/src/workspace_snapshot/node_weight/geometry_node_weight/v1.rs index f9c7b85d02..8c621574bd 100644 --- a/lib/dal/src/workspace_snapshot/node_weight/geometry_node_weight/v1.rs +++ b/lib/dal/src/workspace_snapshot/node_weight/geometry_node_weight/v1.rs @@ -128,7 +128,8 @@ impl CorrectTransforms for GeometryNodeWeightV1 { let Some(container_view_for_self) = maybe_container_view_for_self else { return Err(CorrectTransformsError::InvalidUpdates( "Trying to create a geometry without a container view".to_string(), - )); + ) + .into()); }; // If geometry is not for diagram object, there's no need to run this check @@ -145,7 +146,8 @@ impl CorrectTransforms for GeometryNodeWeightV1 { else { return Err(CorrectTransformsError::InvalidUpdates( "Diagram object should exist on graph".to_string(), - )); + ) + .into()); }; let diagram_object_node = workspace_snapshot_graph @@ -226,7 +228,7 @@ impl CorrectTransforms for GeometryNodeWeightV1 { // Update::NewNode, then something has gone horribly wrong, as we got the // idx by iterating over the updates, and looking at what kind of thing was // there. - _ => return Err(CorrectTransformsError::InvalidUpdates("Updates list is no longer what is expected. Expected Update::NewNode at index, but element is either missing, or not the expected variant".to_string())), + _ => return Err(CorrectTransformsError::InvalidUpdates("Updates list is no longer what is expected. Expected Update::NewNode at index, but element is either missing, or not the expected variant".to_string()).into()), } self_updates.sort(); diff --git a/lib/dal/src/workspace_snapshot/node_weight/input_socket_node_weight.rs b/lib/dal/src/workspace_snapshot/node_weight/input_socket_node_weight.rs index 23521eb04a..428953e2da 100644 --- a/lib/dal/src/workspace_snapshot/node_weight/input_socket_node_weight.rs +++ b/lib/dal/src/workspace_snapshot/node_weight/input_socket_node_weight.rs @@ -1,3 +1,4 @@ +use anyhow::Result; use serde::{Deserialize, Serialize}; use si_events::{ulid::Ulid, ContentHash}; use si_layer_cache::LayerDbError; @@ -29,7 +30,7 @@ pub enum InputSocketNodeWeightError { WorkspaceSnapshotGraph(#[from] Box), } -pub type InputSocketNodeWeightResult = Result; +pub type InputSocketNodeWeightResult = Result; #[derive( Debug, Clone, Serialize, Deserialize, PartialEq, Eq, dal_macros::SiVersionedNodeWeight, diff --git a/lib/dal/src/workspace_snapshot/node_weight/input_socket_node_weight/v1.rs b/lib/dal/src/workspace_snapshot/node_weight/input_socket_node_weight/v1.rs index d73714ce50..bd8b2b6211 100644 --- a/lib/dal/src/workspace_snapshot/node_weight/input_socket_node_weight/v1.rs +++ b/lib/dal/src/workspace_snapshot/node_weight/input_socket_node_weight/v1.rs @@ -100,7 +100,8 @@ impl InputSocketNodeWeightV1 { InputSocketContent::V2(_) => { return Err(InputSocketNodeWeightError::InvalidContentForNodeWeight( content_node_weight.id(), - )); + ) + .into()); } }; @@ -121,9 +122,7 @@ impl InputSocketNodeWeightV1 { let new_node_weight = NodeWeight::InputSocket(InputSocketNodeWeight::V1(new_node_weight_inner)); - v3_graph - .add_or_replace_node(new_node_weight) - .map_err(Box::new)?; + v3_graph.add_or_replace_node(new_node_weight)?; Ok(()) } diff --git a/lib/dal/src/workspace_snapshot/node_weight/ordering_node_weight.rs b/lib/dal/src/workspace_snapshot/node_weight/ordering_node_weight.rs index 76bf2928a7..d393325c33 100644 --- a/lib/dal/src/workspace_snapshot/node_weight/ordering_node_weight.rs +++ b/lib/dal/src/workspace_snapshot/node_weight/ordering_node_weight.rs @@ -256,7 +256,8 @@ impl CorrectTransforms for OrderingNodeWeight { _ => { return Err(CorrectTransformsError::UnexpectedNodeWeight( NodeWeightDiscriminants::Ordering, - )) + ) + .into()); } }; } diff --git a/lib/dal/src/workspace_snapshot/node_weight/prop_node_weight.rs b/lib/dal/src/workspace_snapshot/node_weight/prop_node_weight.rs index 02c7f81949..ccaa3a8675 100644 --- a/lib/dal/src/workspace_snapshot/node_weight/prop_node_weight.rs +++ b/lib/dal/src/workspace_snapshot/node_weight/prop_node_weight.rs @@ -95,7 +95,8 @@ impl PropNodeWeight { return Err(NodeWeightError::InvalidContentAddressForWeightKind( Into::::into(other).to_string(), ContentAddressDiscriminants::Prop.to_string(), - )); + ) + .into()); } }; diff --git a/lib/dal/src/workspace_snapshot/node_weight/schema_variant_node_weight.rs b/lib/dal/src/workspace_snapshot/node_weight/schema_variant_node_weight.rs index 69eab86774..623fda45a4 100644 --- a/lib/dal/src/workspace_snapshot/node_weight/schema_variant_node_weight.rs +++ b/lib/dal/src/workspace_snapshot/node_weight/schema_variant_node_weight.rs @@ -1,3 +1,4 @@ +use anyhow::Result; use serde::{Deserialize, Serialize}; use si_events::{ulid::Ulid, ContentHash}; use si_layer_cache::LayerDbError; @@ -28,7 +29,7 @@ pub enum SchemaVariantNodeWeightError { WorkspaceSnapshotGraph(#[from] Box), } -pub type SchemaVariantNodeWeightResult = Result; +pub type SchemaVariantNodeWeightResult = Result; #[derive( Debug, Clone, Serialize, Deserialize, PartialEq, Eq, dal_macros::SiVersionedNodeWeight, diff --git a/lib/dal/src/workspace_snapshot/node_weight/schema_variant_node_weight/v1.rs b/lib/dal/src/workspace_snapshot/node_weight/schema_variant_node_weight/v1.rs index ba3647dfd7..8f91fabcae 100644 --- a/lib/dal/src/workspace_snapshot/node_weight/schema_variant_node_weight/v1.rs +++ b/lib/dal/src/workspace_snapshot/node_weight/schema_variant_node_weight/v1.rs @@ -131,7 +131,8 @@ impl SchemaVariantNodeWeightV1 { SchemaVariantContent::V3(_) => { return Err(SchemaVariantNodeWeightError::InvalidContentForNodeWeight( content_node_weight.id(), - )); + ) + .into()); } }; @@ -151,9 +152,7 @@ impl SchemaVariantNodeWeightV1 { let new_node_weight = NodeWeight::SchemaVariant(SchemaVariantNodeWeight::V1(new_node_weight_inner)); - v3_graph - .add_or_replace_node(new_node_weight) - .map_err(Box::new)?; + v3_graph.add_or_replace_node(new_node_weight)?; Ok(()) } @@ -201,26 +200,15 @@ impl CorrectTransforms for SchemaVariantNodeWeightV1 { let mut maybe_my_schema_id = match workspace_snapshot_graph.schema_id_for_schema_variant_id(self.id.into()) { - Err(WorkspaceSnapshotGraphError::SchemaVariant(schema_variant_error)) => { - match *schema_variant_error { - SchemaVariantError::NotFound(_) => { - // This is a brand-new SchemaVariant. The Schema may also be brand-new, - // which means we won't find it until we go through the updates, and find - // an Update::NewNode for it, and a corresponding Update::NewEdge that - // links us to the new node. - None - } - err => { - return Err( - WorkspaceSnapshotGraphError::SchemaVariant(Box::new(err)).into() - ); - } - } - } Ok(schema_id) => Some(schema_id), - Err(err) => { - return Err(err.into()); - } + Err(error) => match error.downcast_ref::() { + // This is a brand-new SchemaVariant. The Schema may also be brand-new, + // which means we won't find it until we go through the updates, and find + // an Update::NewNode for it, and a corresponding Update::NewEdge that + // links us to the new node. + Some(SchemaVariantError::NotFound(_)) => None, + _ => return Err(error), + }, }; let mut variants_for_schema: HashMap> = HashMap::new(); let mut new_schemas = HashSet::new(); @@ -304,23 +292,13 @@ impl CorrectTransforms for SchemaVariantNodeWeightV1 { .schema_id_for_schema_variant_id(node_weight.id().into()) { Ok(schema_id) => schema_id, - Err(WorkspaceSnapshotGraphError::SchemaVariant(sv_error)) => { - match *sv_error { - // Couldn't find the Schema/SchemaVariant; ignore it and keep - // checking for relevant updates. - SchemaVariantError::NotFound(_) - | SchemaVariantError::SchemaNotFound(_) => continue, - _ => { - return Err(WorkspaceSnapshotGraphError::SchemaVariant( - sv_error, - ) - .into()) - } - } - } - Err(err) => { - return Err(err.into()); - } + Err(error) => match error.downcast_ref::() { + // Couldn't find the Schema/SchemaVariant; ignore it and keep + // checking for relevant updates. + Some(SchemaVariantError::NotFound(_)) + | Some(SchemaVariantError::SchemaNotFound(_)) => continue, + _ => return Err(error), + }, }; variants_for_schema .entry(schema_id) diff --git a/lib/dal/src/workspace_snapshot/node_weight/secret_node_weight.rs b/lib/dal/src/workspace_snapshot/node_weight/secret_node_weight.rs index 2f5a580434..bd679a8ee0 100644 --- a/lib/dal/src/workspace_snapshot/node_weight/secret_node_weight.rs +++ b/lib/dal/src/workspace_snapshot/node_weight/secret_node_weight.rs @@ -88,7 +88,8 @@ impl SecretNodeWeight { return Err(NodeWeightError::InvalidContentAddressForWeightKind( Into::::into(other).to_string(), ContentAddressDiscriminants::Secret.to_string(), - )); + ) + .into()); } }; diff --git a/lib/dal/src/workspace_snapshot/node_weight/traits.rs b/lib/dal/src/workspace_snapshot/node_weight/traits.rs index 5c1c46f56b..81860a88e1 100644 --- a/lib/dal/src/workspace_snapshot/node_weight/traits.rs +++ b/lib/dal/src/workspace_snapshot/node_weight/traits.rs @@ -5,6 +5,7 @@ use crate::{ }, EdgeWeightKindDiscriminants, WorkspaceSnapshotGraphVCurrent, }; +use anyhow::Result; use si_events::{merkle_tree_hash::MerkleTreeHash, ulid::Ulid, ContentHash}; use thiserror::Error; @@ -27,7 +28,7 @@ pub enum CorrectTransformsError { WorkspaceSnapshotGraph(#[from] WorkspaceSnapshotGraphError), } -pub type CorrectTransformsResult = Result; +pub type CorrectTransformsResult = Result; pub trait CorrectTransforms { fn correct_transforms( diff --git a/lib/dal/src/workspace_snapshot/traits/socket/input.rs b/lib/dal/src/workspace_snapshot/traits/socket/input.rs index 8961988902..0856c93a5e 100644 --- a/lib/dal/src/workspace_snapshot/traits/socket/input.rs +++ b/lib/dal/src/workspace_snapshot/traits/socket/input.rs @@ -129,9 +129,7 @@ impl InputSocketExt for WorkspaceSnapshot { hash, )?; - let attribute_prototype = AttributePrototype::new(ctx, func_id) - .await - .map_err(Box::new)?; + let attribute_prototype = AttributePrototype::new(ctx, func_id).await?; self.working_copy_mut().await.add_edge_between_ids( input_socket_id.into(), diff --git a/lib/dal/src/ws_event.rs b/lib/dal/src/ws_event.rs index c12cb54321..c93857c147 100644 --- a/lib/dal/src/ws_event.rs +++ b/lib/dal/src/ws_event.rs @@ -1,5 +1,6 @@ use std::num::ParseIntError; +use anyhow::Result; use serde::{Deserialize, Serialize}; use si_data_nats::NatsError; use si_data_pg::PgError; @@ -69,7 +70,7 @@ pub enum WsEventError { Transactions(#[from] TransactionsError), } -pub type WsEventResult = Result; +pub type WsEventResult = Result; #[remain::sorted] #[derive(Deserialize, Serialize, Debug, Clone, Eq, PartialEq)] @@ -174,7 +175,7 @@ impl WsEvent { let workspace_pk = match ctx.tenancy().workspace_pk_opt() { Some(pk) => pk, None => { - return Err(WsEventError::NoWorkspaceInTenancy); + return Err(WsEventError::NoWorkspaceInTenancy.into()); } }; let change_set_pk = ctx.change_set_id();