From 48b94c099526eb262287e101a75cb4571b8972b0 Mon Sep 17 00:00:00 2001 From: David Sherret Date: Fri, 15 Nov 2024 23:22:50 -0500 Subject: [PATCH] refactor: use boxed_error in some places (#26887) --- Cargo.lock | 129 +++++++++++++++++++++----------------- Cargo.toml | 1 + ext/fs/Cargo.toml | 1 + ext/fs/lib.rs | 1 + ext/fs/ops.rs | 65 ++++++++++--------- ext/kv/Cargo.toml | 1 + ext/kv/lib.rs | 100 +++++++++++++++++------------ ext/node/Cargo.toml | 1 + ext/node/ops/require.rs | 16 +++-- resolvers/deno/Cargo.toml | 1 + resolvers/deno/lib.rs | 55 +++++----------- resolvers/deno/npm/mod.rs | 52 ++++++++++----- resolvers/node/Cargo.toml | 1 + resolvers/node/errors.rs | 70 ++++++++------------- runtime/errors.rs | 114 ++++++++++++++++----------------- 15 files changed, 323 insertions(+), 285 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fc5834da53..eccd52fffe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -267,7 +267,7 @@ dependencies = [ "proc-macro2", "quote", "swc_macros_common", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -303,7 +303,7 @@ checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -314,7 +314,7 @@ checksum = "c6fa2087f2753a7da8cc1c0dbfcf89579dd57458e36769de5ac750b4671737ca" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -338,7 +338,7 @@ checksum = "3c87f3f15e7794432337fc718554eaa4dc8f04c9677a950ffe366f20a162ae42" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -499,7 +499,7 @@ dependencies = [ "regex", "rustc-hash 1.1.0", "shlex", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -577,6 +577,16 @@ dependencies = [ "generic-array", ] +[[package]] +name = "boxed_error" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69aae56aaf59d1994b902ed5c0c79024012bdc2426741def75a635999a030e7e" +dependencies = [ + "quote", + "syn 2.0.87", +] + [[package]] name = "brotli" version = "6.0.0" @@ -1086,7 +1096,7 @@ checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -1121,7 +1131,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -1132,7 +1142,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -1298,7 +1308,7 @@ checksum = "05d59a1cfd445fd86f63616127a434aabca000e03d963b01b03ce813520565b9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -1613,6 +1623,7 @@ version = "0.87.0" dependencies = [ "async-trait", "base32", + "boxed_error", "deno_core", "deno_io", "deno_path_util", @@ -1725,6 +1736,7 @@ dependencies = [ "anyhow", "async-trait", "base64 0.21.7", + "boxed_error", "bytes", "chrono", "deno_core", @@ -1844,6 +1856,7 @@ dependencies = [ "async-trait", "base64 0.21.7", "blake2", + "boxed_error", "brotli", "bytes", "cbc", @@ -1955,7 +1968,7 @@ dependencies = [ "quote", "strum", "strum_macros", - "syn 2.0.72", + "syn 2.0.87", "thiserror", ] @@ -2008,6 +2021,7 @@ version = "0.9.0" dependencies = [ "anyhow", "base32", + "boxed_error", "dashmap", "deno_config", "deno_media_type", @@ -2391,7 +2405,7 @@ checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -2411,7 +2425,7 @@ checksum = "67e77553c4162a157adbf834ebae5b415acbecbeafc7a74b0e886657506a7611" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -2432,7 +2446,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -2442,7 +2456,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "206868b8242f27cecce124c19fd88157fbd0dd334df2587f36417bafbc85097b" dependencies = [ "derive_builder_core", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -2527,7 +2541,7 @@ checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -2556,7 +2570,7 @@ checksum = "f2b99bf03862d7f545ebc28ddd33a665b50865f4dfd84031a393823879bd4c54" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -2855,7 +2869,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -3139,7 +3153,7 @@ checksum = "1a5c6c585bc94aaf2c7b51dd4c2ba22680844aba4c687be581871a6f518c5742" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -3171,7 +3185,7 @@ checksum = "fdc9cc75639b041067353b9bce2450d6847e547276c6fbe4487d7407980e07db" dependencies = [ "proc-macro2", "swc_macros_common", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -3266,7 +3280,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -4066,7 +4080,7 @@ dependencies = [ "Inflector", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -4256,7 +4270,7 @@ dependencies = [ "proc-macro2", "quote", "regex", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -4642,7 +4656,7 @@ dependencies = [ "quote", "serde", "serde_json", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -4696,6 +4710,7 @@ version = "0.16.0" dependencies = [ "anyhow", "async-trait", + "boxed_error", "deno_media_type", "deno_package_json", "deno_path_util", @@ -5204,7 +5219,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -5258,7 +5273,7 @@ dependencies = [ "phf_shared", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -5287,7 +5302,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -5411,7 +5426,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8d3928fb5db768cb86f891ff014f0144589297e3c6a1aba6ed7cecfdace270c7" dependencies = [ "proc-macro2", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -5455,7 +5470,7 @@ checksum = "07c277e4e643ef00c1233393c673f655e3672cf7eb3ba08a00bdd0ea59139b5f" dependencies = [ "proc-macro-rules-macros", "proc-macro2", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -5467,7 +5482,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -5512,7 +5527,7 @@ dependencies = [ "prost", "prost-types", "regex", - "syn 2.0.72", + "syn 2.0.87", "tempfile", ] @@ -5526,7 +5541,7 @@ dependencies = [ "itertools 0.13.0", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -5656,9 +5671,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.36" +version = "1.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" +checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" dependencies = [ "proc-macro2", ] @@ -5703,7 +5718,7 @@ checksum = "4fdb50eb5bf734fa5a770680a61876a6ec77b99c1e0e52d1f18ad6ebfa85759f" dependencies = [ "heck 0.5.0", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -5805,7 +5820,7 @@ checksum = "5fddb4f8d99b0a2ebafc65a87a69a7b9875e4b1ae1f00db265d300ef7f28bccc" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -6350,7 +6365,7 @@ checksum = "692d6f5ac90220161d6774db30c662202721e64aed9058d2c394f451261420c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -6374,7 +6389,7 @@ checksum = "8725e1dfadb3a50f7e5ce0b1a540466f6ed3fe7a0fca2ac2b8b831d31316bd00" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -6703,7 +6718,7 @@ dependencies = [ "proc-macro2", "quote", "swc_macros_common", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -6740,7 +6755,7 @@ dependencies = [ "proc-macro2", "quote", "rustversion", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -6868,7 +6883,7 @@ dependencies = [ "proc-macro2", "quote", "swc_macros_common", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -6917,7 +6932,7 @@ dependencies = [ "proc-macro2", "quote", "swc_macros_common", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -7002,7 +7017,7 @@ dependencies = [ "proc-macro2", "quote", "swc_macros_common", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -7133,7 +7148,7 @@ checksum = "63db0adcff29d220c3d151c5b25c0eabe7e32dd936212b84cdaa1392e3130497" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -7169,7 +7184,7 @@ checksum = "f486687bfb7b5c560868f69ed2d458b880cebc9babebcb67e49f31b55c5bf847" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -7192,7 +7207,7 @@ dependencies = [ "proc-macro2", "quote", "swc_macros_common", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -7208,9 +7223,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.72" +version = "2.0.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc4b9b9bf2add8093d3f2c0204471e951b2285580335de42f9d2534f3ae7a8af" +checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" dependencies = [ "proc-macro2", "quote", @@ -7243,7 +7258,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -7414,7 +7429,7 @@ checksum = "08904e7672f5eb876eaaf87e0ce17857500934f4981c4a0ab2b4aa98baac7fc3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -7515,7 +7530,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -7693,7 +7708,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -8062,7 +8077,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", "wasm-bindgen-shared", ] @@ -8096,7 +8111,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -8605,7 +8620,7 @@ checksum = "28cc31741b18cb6f1d5ff12f5b7523e3d6eb0852bbbad19d73905511d9849b95" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", "synstructure 0.13.1", ] @@ -8627,7 +8642,7 @@ checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] @@ -8647,7 +8662,7 @@ checksum = "0ea7b4a3637ea8669cedf0f1fd5c286a17f3de97b8dd5a70a6c167a1730e63a5" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", "synstructure 0.13.1", ] @@ -8668,7 +8683,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.87", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 36e59eab2c..ad63355d21 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -100,6 +100,7 @@ async-trait = "0.1.73" base32 = "=0.5.1" base64 = "0.21.7" bencher = "0.1" +boxed_error = "0.2.2" brotli = "6.0.0" bytes = "1.4.0" cache_control = "=0.2.0" diff --git a/ext/fs/Cargo.toml b/ext/fs/Cargo.toml index e85f349b15..ace1b89f3a 100644 --- a/ext/fs/Cargo.toml +++ b/ext/fs/Cargo.toml @@ -19,6 +19,7 @@ sync_fs = [] [dependencies] async-trait.workspace = true base32.workspace = true +boxed_error.workspace = true deno_core.workspace = true deno_io.workspace = true deno_path_util.workspace = true diff --git a/ext/fs/lib.rs b/ext/fs/lib.rs index dd852e6be8..aed9a7085f 100644 --- a/ext/fs/lib.rs +++ b/ext/fs/lib.rs @@ -15,6 +15,7 @@ pub use crate::interface::FsDirEntry; pub use crate::interface::FsFileType; pub use crate::interface::OpenOptions; pub use crate::ops::FsOpsError; +pub use crate::ops::FsOpsErrorKind; pub use crate::ops::OperationError; pub use crate::std_fs::RealFs; pub use crate::sync::MaybeSend; diff --git a/ext/fs/ops.rs b/ext/fs/ops.rs index 3d0d96ce66..e3a511f8e7 100644 --- a/ext/fs/ops.rs +++ b/ext/fs/ops.rs @@ -16,6 +16,7 @@ use crate::interface::FsDirEntry; use crate::interface::FsFileType; use crate::FsPermissions; use crate::OpenOptions; +use boxed_error::Boxed; use deno_core::op2; use deno_core::CancelFuture; use deno_core::CancelHandle; @@ -32,8 +33,11 @@ use rand::thread_rng; use rand::Rng; use serde::Serialize; +#[derive(Debug, Boxed)] +pub struct FsOpsError(pub Box); + #[derive(Debug, thiserror::Error)] -pub enum FsOpsError { +pub enum FsOpsErrorKind { #[error("{0}")] Io(#[source] std::io::Error), #[error("{0}")] @@ -73,15 +77,16 @@ pub enum FsOpsError { impl From for FsOpsError { fn from(err: FsError) -> Self { match err { - FsError::Io(err) => FsOpsError::Io(err), + FsError::Io(err) => FsOpsErrorKind::Io(err), FsError::FileBusy => { - FsOpsError::Other(deno_core::error::resource_unavailable()) + FsOpsErrorKind::Other(deno_core::error::resource_unavailable()) } FsError::NotSupported => { - FsOpsError::Other(deno_core::error::not_supported()) + FsOpsErrorKind::Other(deno_core::error::not_supported()) } - FsError::NotCapable(err) => FsOpsError::NotCapable(err), + FsError::NotCapable(err) => FsOpsErrorKind::NotCapable(err), } + .into_box() } } @@ -127,11 +132,12 @@ fn map_permission_error( (path.as_str(), "") }; - FsOpsError::NotCapableAccess { + FsOpsErrorKind::NotCapableAccess { standalone: deno_permissions::is_standalone(), err, path: format!("{path}{truncated}"), } + .into_box() } err => Err::<(), _>(err) .context_path(operation, path) @@ -1176,7 +1182,9 @@ fn validate_temporary_filename_component( ) -> Result<(), FsOpsError> { // Ban ASCII and Unicode control characters: these will often fail if let Some(c) = component.matches(|c: char| c.is_control()).next() { - return Err(FsOpsError::InvalidControlCharacter(c.to_string())); + return Err( + FsOpsErrorKind::InvalidControlCharacter(c.to_string()).into_box(), + ); } // Windows has the most restrictive filenames. As temp files aren't normal files, we just // use this set of banned characters for all platforms because wildcard-like files can also @@ -1192,13 +1200,13 @@ fn validate_temporary_filename_component( .matches(|c: char| "<>:\"/\\|?*".contains(c)) .next() { - return Err(FsOpsError::InvalidCharacter(c.to_string())); + return Err(FsOpsErrorKind::InvalidCharacter(c.to_string()).into_box()); } // This check is only for Windows #[cfg(windows)] if suffix && component.ends_with(|c: char| ". ".contains(c)) { - return Err(FsOpsError::InvalidTrailingCharacter); + return Err(FsOpsErrorKind::InvalidTrailingCharacter.into_box()); } Ok(()) @@ -1440,7 +1448,7 @@ fn to_seek_from(offset: i64, whence: i32) -> Result { 1 => SeekFrom::Current(offset), 2 => SeekFrom::End(offset), _ => { - return Err(FsOpsError::InvalidSeekMode(whence)); + return Err(FsOpsErrorKind::InvalidSeekMode(whence).into_box()); } }; Ok(seek_from) @@ -1456,7 +1464,7 @@ pub fn op_fs_seek_sync( ) -> Result { let pos = to_seek_from(offset, whence)?; let file = - FileResource::get_file(state, rid).map_err(FsOpsError::Resource)?; + FileResource::get_file(state, rid).map_err(FsOpsErrorKind::Resource)?; let cursor = file.seek_sync(pos)?; Ok(cursor) } @@ -1471,7 +1479,7 @@ pub async fn op_fs_seek_async( ) -> Result { let pos = to_seek_from(offset, whence)?; let file = FileResource::get_file(&state.borrow(), rid) - .map_err(FsOpsError::Resource)?; + .map_err(FsOpsErrorKind::Resource)?; let cursor = file.seek_async(pos).await?; Ok(cursor) } @@ -1482,7 +1490,7 @@ pub fn op_fs_file_sync_data_sync( #[smi] rid: ResourceId, ) -> Result<(), FsOpsError> { let file = - FileResource::get_file(state, rid).map_err(FsOpsError::Resource)?; + FileResource::get_file(state, rid).map_err(FsOpsErrorKind::Resource)?; file.datasync_sync()?; Ok(()) } @@ -1493,7 +1501,7 @@ pub async fn op_fs_file_sync_data_async( #[smi] rid: ResourceId, ) -> Result<(), FsOpsError> { let file = FileResource::get_file(&state.borrow(), rid) - .map_err(FsOpsError::Resource)?; + .map_err(FsOpsErrorKind::Resource)?; file.datasync_async().await?; Ok(()) } @@ -1504,7 +1512,7 @@ pub fn op_fs_file_sync_sync( #[smi] rid: ResourceId, ) -> Result<(), FsOpsError> { let file = - FileResource::get_file(state, rid).map_err(FsOpsError::Resource)?; + FileResource::get_file(state, rid).map_err(FsOpsErrorKind::Resource)?; file.sync_sync()?; Ok(()) } @@ -1515,7 +1523,7 @@ pub async fn op_fs_file_sync_async( #[smi] rid: ResourceId, ) -> Result<(), FsOpsError> { let file = FileResource::get_file(&state.borrow(), rid) - .map_err(FsOpsError::Resource)?; + .map_err(FsOpsErrorKind::Resource)?; file.sync_async().await?; Ok(()) } @@ -1527,7 +1535,7 @@ pub fn op_fs_file_stat_sync( #[buffer] stat_out_buf: &mut [u32], ) -> Result<(), FsOpsError> { let file = - FileResource::get_file(state, rid).map_err(FsOpsError::Resource)?; + FileResource::get_file(state, rid).map_err(FsOpsErrorKind::Resource)?; let stat = file.stat_sync()?; let serializable_stat = SerializableStat::from(stat); serializable_stat.write(stat_out_buf); @@ -1541,7 +1549,7 @@ pub async fn op_fs_file_stat_async( #[smi] rid: ResourceId, ) -> Result { let file = FileResource::get_file(&state.borrow(), rid) - .map_err(FsOpsError::Resource)?; + .map_err(FsOpsErrorKind::Resource)?; let stat = file.stat_async().await?; Ok(stat.into()) } @@ -1553,7 +1561,7 @@ pub fn op_fs_flock_sync( exclusive: bool, ) -> Result<(), FsOpsError> { let file = - FileResource::get_file(state, rid).map_err(FsOpsError::Resource)?; + FileResource::get_file(state, rid).map_err(FsOpsErrorKind::Resource)?; file.lock_sync(exclusive)?; Ok(()) } @@ -1565,7 +1573,7 @@ pub async fn op_fs_flock_async( exclusive: bool, ) -> Result<(), FsOpsError> { let file = FileResource::get_file(&state.borrow(), rid) - .map_err(FsOpsError::Resource)?; + .map_err(FsOpsErrorKind::Resource)?; file.lock_async(exclusive).await?; Ok(()) } @@ -1576,7 +1584,7 @@ pub fn op_fs_funlock_sync( #[smi] rid: ResourceId, ) -> Result<(), FsOpsError> { let file = - FileResource::get_file(state, rid).map_err(FsOpsError::Resource)?; + FileResource::get_file(state, rid).map_err(FsOpsErrorKind::Resource)?; file.unlock_sync()?; Ok(()) } @@ -1587,7 +1595,7 @@ pub async fn op_fs_funlock_async( #[smi] rid: ResourceId, ) -> Result<(), FsOpsError> { let file = FileResource::get_file(&state.borrow(), rid) - .map_err(FsOpsError::Resource)?; + .map_err(FsOpsErrorKind::Resource)?; file.unlock_async().await?; Ok(()) } @@ -1599,7 +1607,7 @@ pub fn op_fs_ftruncate_sync( #[number] len: u64, ) -> Result<(), FsOpsError> { let file = - FileResource::get_file(state, rid).map_err(FsOpsError::Resource)?; + FileResource::get_file(state, rid).map_err(FsOpsErrorKind::Resource)?; file.truncate_sync(len)?; Ok(()) } @@ -1611,7 +1619,7 @@ pub async fn op_fs_file_truncate_async( #[number] len: u64, ) -> Result<(), FsOpsError> { let file = FileResource::get_file(&state.borrow(), rid) - .map_err(FsOpsError::Resource)?; + .map_err(FsOpsErrorKind::Resource)?; file.truncate_async(len).await?; Ok(()) } @@ -1626,7 +1634,7 @@ pub fn op_fs_futime_sync( #[smi] mtime_nanos: u32, ) -> Result<(), FsOpsError> { let file = - FileResource::get_file(state, rid).map_err(FsOpsError::Resource)?; + FileResource::get_file(state, rid).map_err(FsOpsErrorKind::Resource)?; file.utime_sync(atime_secs, atime_nanos, mtime_secs, mtime_nanos)?; Ok(()) } @@ -1641,7 +1649,7 @@ pub async fn op_fs_futime_async( #[smi] mtime_nanos: u32, ) -> Result<(), FsOpsError> { let file = FileResource::get_file(&state.borrow(), rid) - .map_err(FsOpsError::Resource)?; + .map_err(FsOpsErrorKind::Resource)?; file .utime_async(atime_secs, atime_nanos, mtime_secs, mtime_nanos) .await?; @@ -1717,7 +1725,7 @@ impl MapErrContext for Result { where F: FnOnce(FsError) -> OperationError, { - self.map_err(|err| FsOpsError::OperationError(f(err))) + self.map_err(|err| FsOpsErrorKind::OperationError(f(err)).into_box()) } fn context(self, operation: &'static str) -> Self::R { @@ -1754,7 +1762,8 @@ impl MapErrContext for Result { } fn path_into_string(s: std::ffi::OsString) -> Result { - s.into_string().map_err(FsOpsError::InvalidUtf8) + s.into_string() + .map_err(|e| FsOpsErrorKind::InvalidUtf8(e).into_box()) } macro_rules! create_struct_writer { diff --git a/ext/kv/Cargo.toml b/ext/kv/Cargo.toml index 1d7b91770f..aa73817667 100644 --- a/ext/kv/Cargo.toml +++ b/ext/kv/Cargo.toml @@ -17,6 +17,7 @@ path = "lib.rs" anyhow.workspace = true async-trait.workspace = true base64.workspace = true +boxed_error.workspace = true bytes.workspace = true chrono = { workspace = true, features = ["now"] } deno_core.workspace = true diff --git a/ext/kv/lib.rs b/ext/kv/lib.rs index a4ccfe3d63..5392b97210 100644 --- a/ext/kv/lib.rs +++ b/ext/kv/lib.rs @@ -14,6 +14,7 @@ use std::time::Duration; use base64::prelude::BASE64_URL_SAFE; use base64::Engine; +use boxed_error::Boxed; use chrono::DateTime; use chrono::Utc; use deno_core::error::get_custom_error_class; @@ -114,8 +115,11 @@ impl Resource for DatabaseWatcherResource { } } +#[derive(Debug, Boxed)] +pub struct KvError(pub Box); + #[derive(Debug, thiserror::Error)] -pub enum KvError { +pub enum KvErrorKind { #[error(transparent)] DatabaseHandler(deno_core::error::AnyError), #[error(transparent)] @@ -193,7 +197,7 @@ where let db = handler .open(state.clone(), path) .await - .map_err(KvError::DatabaseHandler)?; + .map_err(KvErrorKind::DatabaseHandler)?; let rid = state.borrow_mut().resource_table.add(DatabaseResource { db, cancel_handle: CancelHandle::new_rc(), @@ -329,7 +333,7 @@ where let resource = state .resource_table .get::>(rid) - .map_err(KvError::Resource)?; + .map_err(KvErrorKind::Resource)?; resource.db.clone() }; @@ -339,7 +343,7 @@ where }; if ranges.len() > config.max_read_ranges { - return Err(KvError::TooManyRanges(config.max_read_ranges)); + return Err(KvErrorKind::TooManyRanges(config.max_read_ranges).into_box()); } let mut total_entries = 0usize; @@ -358,14 +362,16 @@ where Ok(ReadRange { start, end, - limit: NonZeroU32::new(limit).ok_or(KvError::InvalidLimit)?, + limit: NonZeroU32::new(limit).ok_or(KvErrorKind::InvalidLimit)?, reverse, }) }) .collect::, KvError>>()?; if total_entries > config.max_read_entries { - return Err(KvError::TooManyEntries(config.max_read_entries)); + return Err( + KvErrorKind::TooManyEntries(config.max_read_entries).into_box(), + ); } let opts = SnapshotReadOptions { @@ -374,7 +380,7 @@ where let output_ranges = db .snapshot_read(read_ranges, opts) .await - .map_err(KvError::Kv)?; + .map_err(KvErrorKind::Kv)?; let output_ranges = output_ranges .into_iter() .map(|x| { @@ -415,7 +421,7 @@ where if get_custom_error_class(&err) == Some("BadResource") { return Ok(None); } else { - return Err(KvError::Resource(err)); + return Err(KvErrorKind::Resource(err).into_box()); } } }; @@ -423,11 +429,11 @@ where }; let Some(mut handle) = - db.dequeue_next_message().await.map_err(KvError::Kv)? + db.dequeue_next_message().await.map_err(KvErrorKind::Kv)? else { return Ok(None); }; - let payload = handle.take_payload().await.map_err(KvError::Kv)?.into(); + let payload = handle.take_payload().await.map_err(KvErrorKind::Kv)?.into(); let handle_rid = { let mut state = state.borrow_mut(); state.resource_table.add(QueueMessageResource { handle }) @@ -448,11 +454,11 @@ where let resource = state .resource_table .get::>(rid) - .map_err(KvError::Resource)?; + .map_err(KvErrorKind::Resource)?; let config = state.borrow::>().clone(); if keys.len() > config.max_watched_keys { - return Err(KvError::TooManyKeys(config.max_watched_keys)); + return Err(KvErrorKind::TooManyKeys(config.max_watched_keys).into_box()); } let keys: Vec> = keys @@ -493,7 +499,7 @@ async fn op_kv_watch_next( let resource = state .resource_table .get::(rid) - .map_err(KvError::Resource)?; + .map_err(KvErrorKind::Resource)?; resource.clone() }; @@ -519,7 +525,7 @@ async fn op_kv_watch_next( return Ok(None); }; - let entries = res.map_err(KvError::Kv)?; + let entries = res.map_err(KvErrorKind::Kv)?; let entries = entries .into_iter() .map(|entry| { @@ -549,9 +555,9 @@ where let handle = state .resource_table .take::::DB as Database>::QMH>>(handle_rid) - .map_err(|_| KvError::QueueMessageNotFound)?; + .map_err(|_| KvErrorKind::QueueMessageNotFound)?; Rc::try_unwrap(handle) - .map_err(|_| KvError::QueueMessageNotFound)? + .map_err(|_| KvErrorKind::QueueMessageNotFound)? .handle }; // if we fail to finish the message, there is not much we can do and the @@ -692,7 +698,7 @@ impl RawSelector { }), (Some(prefix), Some(start), None) => { if !start.starts_with(&prefix) || start.len() == prefix.len() { - return Err(KvError::StartKeyNotInKeyspace); + return Err(KvErrorKind::StartKeyNotInKeyspace.into_box()); } Ok(Self::Prefixed { prefix, @@ -702,7 +708,7 @@ impl RawSelector { } (Some(prefix), None, Some(end)) => { if !end.starts_with(&prefix) || end.len() == prefix.len() { - return Err(KvError::EndKeyNotInKeyspace); + return Err(KvErrorKind::EndKeyNotInKeyspace.into_box()); } Ok(Self::Prefixed { prefix, @@ -712,7 +718,7 @@ impl RawSelector { } (None, Some(start), Some(end)) => { if start > end { - return Err(KvError::StartKeyGreaterThanEndKey); + return Err(KvErrorKind::StartKeyGreaterThanEndKey.into_box()); } Ok(Self::Range { start, end }) } @@ -720,7 +726,7 @@ impl RawSelector { let end = start.iter().copied().chain(Some(0)).collect(); Ok(Self::Range { start, end }) } - _ => Err(KvError::InvalidRange), + _ => Err(KvErrorKind::InvalidRange.into_box()), } } @@ -782,7 +788,7 @@ fn encode_cursor( ) -> Result { let common_prefix = selector.common_prefix(); if !boundary_key.starts_with(common_prefix) { - return Err(KvError::InvalidBoundaryKey); + return Err(KvErrorKind::InvalidBoundaryKey.into_box()); } Ok(BASE64_URL_SAFE.encode(&boundary_key[common_prefix.len()..])) } @@ -799,7 +805,7 @@ fn decode_selector_and_cursor( let common_prefix = selector.common_prefix(); let cursor = BASE64_URL_SAFE .decode(cursor) - .map_err(|_| KvError::InvalidCursor)?; + .map_err(|_| KvErrorKind::InvalidCursor)?; let first_key: Vec; let last_key: Vec; @@ -824,13 +830,13 @@ fn decode_selector_and_cursor( // Defend against out-of-bounds reading if let Some(start) = selector.start() { if &first_key[..] < start { - return Err(KvError::CursorOutOfBounds); + return Err(KvErrorKind::CursorOutOfBounds.into_box()); } } if let Some(end) = selector.end() { if &last_key[..] > end { - return Err(KvError::CursorOutOfBounds); + return Err(KvErrorKind::CursorOutOfBounds.into_box()); } } @@ -855,7 +861,7 @@ where let resource = state .resource_table .get::>(rid) - .map_err(KvError::Resource)?; + .map_err(KvErrorKind::Resource)?; resource.db.clone() }; @@ -865,28 +871,28 @@ where }; if checks.len() > config.max_checks { - return Err(KvError::TooManyChecks(config.max_checks)); + return Err(KvErrorKind::TooManyChecks(config.max_checks).into_box()); } if mutations.len() + enqueues.len() > config.max_mutations { - return Err(KvError::TooManyMutations(config.max_mutations)); + return Err(KvErrorKind::TooManyMutations(config.max_mutations).into_box()); } let checks = checks .into_iter() .map(check_from_v8) .collect::, KvCheckError>>() - .map_err(KvError::InvalidCheck)?; + .map_err(KvErrorKind::InvalidCheck)?; let mutations = mutations .into_iter() .map(|mutation| mutation_from_v8((mutation, current_timestamp))) .collect::, KvMutationError>>() - .map_err(KvError::InvalidMutation)?; + .map_err(KvErrorKind::InvalidMutation)?; let enqueues = enqueues .into_iter() .map(|e| enqueue_from_v8(e, current_timestamp)) .collect::, std::io::Error>>() - .map_err(KvError::InvalidEnqueue)?; + .map_err(KvErrorKind::InvalidEnqueue)?; let mut total_payload_size = 0usize; let mut total_key_size = 0usize; @@ -897,7 +903,7 @@ where .chain(mutations.iter().map(|m| &m.key)) { if key.is_empty() { - return Err(KvError::EmptyKey); + return Err(KvErrorKind::EmptyKey.into_box()); } total_payload_size += check_write_key_size(key, &config)?; @@ -921,13 +927,16 @@ where } if total_payload_size > config.max_total_mutation_size_bytes { - return Err(KvError::TotalMutationTooLarge( - config.max_total_mutation_size_bytes, - )); + return Err( + KvErrorKind::TotalMutationTooLarge(config.max_total_mutation_size_bytes) + .into_box(), + ); } if total_key_size > config.max_total_key_size_bytes { - return Err(KvError::TotalKeyTooLarge(config.max_total_key_size_bytes)); + return Err( + KvErrorKind::TotalKeyTooLarge(config.max_total_key_size_bytes).into_box(), + ); } let atomic_write = AtomicWrite { @@ -936,7 +945,10 @@ where enqueues, }; - let result = db.atomic_write(atomic_write).await.map_err(KvError::Kv)?; + let result = db + .atomic_write(atomic_write) + .await + .map_err(KvErrorKind::Kv)?; Ok(result.map(|res| faster_hex::hex_string(&res.versionstamp))) } @@ -958,7 +970,9 @@ fn op_kv_encode_cursor( fn check_read_key_size(key: &[u8], config: &KvConfig) -> Result<(), KvError> { if key.len() > config.max_read_key_size_bytes { - Err(KvError::KeyTooLargeToRead(config.max_read_key_size_bytes)) + Err( + KvErrorKind::KeyTooLargeToRead(config.max_read_key_size_bytes).into_box(), + ) } else { Ok(()) } @@ -969,7 +983,10 @@ fn check_write_key_size( config: &KvConfig, ) -> Result { if key.len() > config.max_write_key_size_bytes { - Err(KvError::KeyTooLargeToWrite(config.max_write_key_size_bytes)) + Err( + KvErrorKind::KeyTooLargeToWrite(config.max_write_key_size_bytes) + .into_box(), + ) } else { Ok(key.len()) } @@ -986,7 +1003,7 @@ fn check_value_size( }; if payload.len() > config.max_value_size_bytes { - Err(KvError::ValueTooLarge(config.max_value_size_bytes)) + Err(KvErrorKind::ValueTooLarge(config.max_value_size_bytes).into_box()) } else { Ok(payload.len()) } @@ -997,7 +1014,10 @@ fn check_enqueue_payload_size( config: &KvConfig, ) -> Result { if payload.len() > config.max_value_size_bytes { - Err(KvError::EnqueuePayloadTooLarge(config.max_value_size_bytes)) + Err( + KvErrorKind::EnqueuePayloadTooLarge(config.max_value_size_bytes) + .into_box(), + ) } else { Ok(payload.len()) } diff --git a/ext/node/Cargo.toml b/ext/node/Cargo.toml index 9e1a3495b5..c4ee86a957 100644 --- a/ext/node/Cargo.toml +++ b/ext/node/Cargo.toml @@ -22,6 +22,7 @@ aes.workspace = true async-trait.workspace = true base64.workspace = true blake2 = "0.10.6" +boxed_error.workspace = true brotli.workspace = true bytes.workspace = true cbc.workspace = true diff --git a/ext/node/ops/require.rs b/ext/node/ops/require.rs index e381ee91d4..06c034fd50 100644 --- a/ext/node/ops/require.rs +++ b/ext/node/ops/require.rs @@ -1,5 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. +use boxed_error::Boxed; use deno_core::error::AnyError; use deno_core::op2; use deno_core::url::Url; @@ -40,8 +41,11 @@ where loader.ensure_read_permission(permissions, file_path) } +#[derive(Debug, Boxed)] +pub struct RequireError(pub Box); + #[derive(Debug, thiserror::Error)] -pub enum RequireError { +pub enum RequireErrorKind { #[error(transparent)] UrlParse(#[from] url::ParseError), #[error(transparent)] @@ -135,7 +139,7 @@ where let from = if from.starts_with("file:///") { url_to_file_path(&Url::parse(&from)?)? } else { - let current_dir = &fs.cwd().map_err(RequireError::UnableToGetCwd)?; + let current_dir = &fs.cwd().map_err(RequireErrorKind::UnableToGetCwd)?; normalize_path(current_dir.join(from)) }; @@ -324,7 +328,7 @@ where { let path = PathBuf::from(request); let path = ensure_read_permission::

(state, &path) - .map_err(RequireError::Permission)?; + .map_err(RequireErrorKind::Permission)?; let fs = state.borrow::(); let canonicalized_path = deno_path_util::strip_unc_prefix(fs.realpath_sync(&path)?); @@ -484,11 +488,11 @@ where let file_path = PathBuf::from(file_path); // todo(dsherret): there's multiple borrows to NodeRequireLoaderRc here let file_path = ensure_read_permission::

(state, &file_path) - .map_err(RequireError::Permission)?; + .map_err(RequireErrorKind::Permission)?; let loader = state.borrow::(); loader .load_text_file_lossy(&file_path) - .map_err(RequireError::ReadModule) + .map_err(|e| RequireErrorKind::ReadModule(e).into_box()) } #[op2] @@ -612,7 +616,7 @@ where { let referrer_path = PathBuf::from(&referrer_filename); let referrer_path = ensure_read_permission::

(state, &referrer_path) - .map_err(RequireError::Permission)?; + .map_err(RequireErrorKind::Permission)?; let pkg_json_resolver = state.borrow::(); let Some(pkg) = pkg_json_resolver.get_closest_package_json_from_path(&referrer_path)? diff --git a/resolvers/deno/Cargo.toml b/resolvers/deno/Cargo.toml index 89c0232dc9..c2d4a3bc29 100644 --- a/resolvers/deno/Cargo.toml +++ b/resolvers/deno/Cargo.toml @@ -16,6 +16,7 @@ path = "lib.rs" [dependencies] anyhow.workspace = true base32.workspace = true +boxed_error.workspace = true dashmap.workspace = true deno_config.workspace = true deno_media_type.workspace = true diff --git a/resolvers/deno/lib.rs b/resolvers/deno/lib.rs index a2b6b642fc..303a827102 100644 --- a/resolvers/deno/lib.rs +++ b/resolvers/deno/lib.rs @@ -6,6 +6,7 @@ use std::path::PathBuf; use std::sync::Arc; +use boxed_error::Boxed; use deno_config::workspace::MappedResolution; use deno_config::workspace::MappedResolutionDiagnostic; use deno_config::workspace::MappedResolutionError; @@ -26,9 +27,9 @@ use node_resolver::NodeResolver; use npm::MissingPackageNodeModulesFolderError; use npm::NodeModulesOutOfDateError; use npm::NpmReqResolver; -use npm::ResolveIfForNpmPackageError; +use npm::ResolveIfForNpmPackageErrorKind; use npm::ResolvePkgFolderFromDenoReqError; -use npm::ResolveReqWithSubPathError; +use npm::ResolveReqWithSubPathErrorKind; use sloppy_imports::SloppyImportResolverFs; use sloppy_imports::SloppyImportsResolutionMode; use sloppy_imports::SloppyImportsResolver; @@ -47,6 +48,9 @@ pub struct DenoResolution { pub found_package_json_dep: bool, } +#[derive(Debug, Boxed)] +pub struct DenoResolveError(pub Box); + #[derive(Debug, Error)] pub enum DenoResolveErrorKind { #[error("Importing from the vendor directory is not permitted. Use a remote specifier instead or disable vendoring.")] @@ -71,35 +75,6 @@ pub enum DenoResolveErrorKind { WorkspaceResolvePkgJsonFolder(#[from] WorkspaceResolvePkgJsonFolderError), } -impl DenoResolveErrorKind { - pub fn into_box(self) -> DenoResolveError { - DenoResolveError(Box::new(self)) - } -} - -#[derive(Error, Debug)] -#[error(transparent)] -pub struct DenoResolveError(pub Box); - -impl DenoResolveError { - pub fn as_kind(&self) -> &DenoResolveErrorKind { - &self.0 - } - - pub fn into_kind(self) -> DenoResolveErrorKind { - *self.0 - } -} - -impl From for DenoResolveError -where - DenoResolveErrorKind: From, -{ - fn from(err: E) -> Self { - DenoResolveError(Box::new(DenoResolveErrorKind::from(err))) - } -} - #[derive(Debug)] pub struct NodeAndNpmReqResolver< Fs: DenoResolverFs, @@ -378,16 +353,18 @@ impl< maybe_diagnostic, found_package_json_dep, }) - .map_err(|err| match err { - ResolveReqWithSubPathError::MissingPackageNodeModulesFolder( + .map_err(|err| { + match err.into_kind() { + ResolveReqWithSubPathErrorKind::MissingPackageNodeModulesFolder( err, ) => err.into(), - ResolveReqWithSubPathError::ResolvePkgFolderFromDenoReq( + ResolveReqWithSubPathErrorKind::ResolvePkgFolderFromDenoReq( err, ) => err.into(), - ResolveReqWithSubPathError::PackageSubpathResolve(err) => { + ResolveReqWithSubPathErrorKind::PackageSubpathResolve(err) => { err.into() } + } }); } } @@ -410,11 +387,13 @@ impl< referrer_kind, mode, ) - .map_err(|e| match e { - ResolveIfForNpmPackageError::NodeResolve(e) => { + .map_err(|e| match e.into_kind() { + ResolveIfForNpmPackageErrorKind::NodeResolve(e) => { DenoResolveErrorKind::Node(e).into_box() } - ResolveIfForNpmPackageError::NodeModulesOutOfDate(e) => e.into(), + ResolveIfForNpmPackageErrorKind::NodeModulesOutOfDate(e) => { + e.into() + } })?; if let Some(res) = maybe_resolution { match res { diff --git a/resolvers/deno/npm/mod.rs b/resolvers/deno/npm/mod.rs index b0aec71b08..09e35b15c3 100644 --- a/resolvers/deno/npm/mod.rs +++ b/resolvers/deno/npm/mod.rs @@ -4,6 +4,7 @@ use std::fmt::Debug; use std::path::PathBuf; use std::sync::Arc; +use boxed_error::Boxed; use deno_semver::npm::NpmPackageReqReference; use deno_semver::package::PackageReq; use node_resolver::env::NodeResolverEnv; @@ -45,16 +46,24 @@ pub struct MissingPackageNodeModulesFolderError { pub package_json_path: PathBuf, } +#[derive(Debug, Boxed)] +pub struct ResolveIfForNpmPackageError( + pub Box, +); + #[derive(Debug, Error)] -pub enum ResolveIfForNpmPackageError { +pub enum ResolveIfForNpmPackageErrorKind { #[error(transparent)] NodeResolve(#[from] NodeResolveError), #[error(transparent)] NodeModulesOutOfDate(#[from] NodeModulesOutOfDateError), } +#[derive(Debug, Boxed)] +pub struct ResolveReqWithSubPathError(pub Box); + #[derive(Debug, Error)] -pub enum ResolveReqWithSubPathError { +pub enum ResolveReqWithSubPathErrorKind { #[error(transparent)] MissingPackageNodeModulesFolder(#[from] MissingPackageNodeModulesFolderError), #[error(transparent)] @@ -191,20 +200,21 @@ impl | NodeResolveErrorKind::UnsupportedEsmUrlScheme(_) | NodeResolveErrorKind::DataUrlReferrer(_) | NodeResolveErrorKind::TypesNotFound(_) - | NodeResolveErrorKind::FinalizeResolution(_) => { - Err(ResolveIfForNpmPackageError::NodeResolve(err.into())) - } + | NodeResolveErrorKind::FinalizeResolution(_) => Err( + ResolveIfForNpmPackageErrorKind::NodeResolve(err.into()).into_box(), + ), NodeResolveErrorKind::PackageResolve(err) => { let err = err.into_kind(); match err { PackageResolveErrorKind::ClosestPkgJson(_) | PackageResolveErrorKind::InvalidModuleSpecifier(_) | PackageResolveErrorKind::ExportsResolve(_) - | PackageResolveErrorKind::SubpathResolve(_) => { - Err(ResolveIfForNpmPackageError::NodeResolve( + | PackageResolveErrorKind::SubpathResolve(_) => Err( + ResolveIfForNpmPackageErrorKind::NodeResolve( NodeResolveErrorKind::PackageResolve(err.into()).into(), - )) - } + ) + .into_box(), + ), PackageResolveErrorKind::PackageFolderResolve(err) => { match err.as_kind() { PackageFolderResolveErrorKind::Io( @@ -214,9 +224,13 @@ impl PackageNotFoundError { package_name, .. }, ) => { if self.in_npm_pkg_checker.in_npm_package(referrer) { - return Err(ResolveIfForNpmPackageError::NodeResolve( - NodeResolveErrorKind::PackageResolve(err.into()).into(), - )); + return Err( + ResolveIfForNpmPackageErrorKind::NodeResolve( + NodeResolveErrorKind::PackageResolve(err.into()) + .into(), + ) + .into_box(), + ); } if let Some(byonm_npm_resolver) = &self.byonm_resolver { if byonm_npm_resolver @@ -227,11 +241,11 @@ impl .is_some() { return Err( - ResolveIfForNpmPackageError::NodeModulesOutOfDate( + ResolveIfForNpmPackageErrorKind::NodeModulesOutOfDate( NodeModulesOutOfDateError { specifier: specifier.to_string(), }, - ), + ).into_box(), ); } } @@ -239,9 +253,13 @@ impl } PackageFolderResolveErrorKind::ReferrerNotFound(_) => { if self.in_npm_pkg_checker.in_npm_package(referrer) { - return Err(ResolveIfForNpmPackageError::NodeResolve( - NodeResolveErrorKind::PackageResolve(err.into()).into(), - )); + return Err( + ResolveIfForNpmPackageErrorKind::NodeResolve( + NodeResolveErrorKind::PackageResolve(err.into()) + .into(), + ) + .into_box(), + ); } Ok(None) } diff --git a/resolvers/node/Cargo.toml b/resolvers/node/Cargo.toml index 6c2407ad9f..eeac79c256 100644 --- a/resolvers/node/Cargo.toml +++ b/resolvers/node/Cargo.toml @@ -19,6 +19,7 @@ sync = ["deno_package_json/sync"] [dependencies] anyhow.workspace = true async-trait.workspace = true +boxed_error.workspace = true deno_media_type.workspace = true deno_package_json.workspace = true deno_path_util.workspace = true diff --git a/resolvers/node/errors.rs b/resolvers/node/errors.rs index aacbecefb4..0f332d2c93 100644 --- a/resolvers/node/errors.rs +++ b/resolvers/node/errors.rs @@ -4,39 +4,13 @@ use std::borrow::Cow; use std::fmt::Write; use std::path::PathBuf; +use boxed_error::Boxed; use thiserror::Error; use url::Url; use crate::NodeModuleKind; use crate::NodeResolutionMode; -macro_rules! kinded_err { - ($name:ident, $kind_name:ident) => { - #[derive(Error, Debug)] - #[error(transparent)] - pub struct $name(pub Box<$kind_name>); - - impl $name { - pub fn as_kind(&self) -> &$kind_name { - &self.0 - } - - pub fn into_kind(self) -> $kind_name { - *self.0 - } - } - - impl From for $name - where - $kind_name: From, - { - fn from(err: E) -> Self { - $name(Box::new($kind_name::from(err))) - } - } - }; -} - #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[allow(non_camel_case_types)] pub enum NodeJsErrorCode { @@ -102,7 +76,8 @@ impl NodeJsErrorCoded for InvalidModuleSpecifierError { } } -kinded_err!(LegacyResolveError, LegacyResolveErrorKind); +#[derive(Debug, Boxed)] +pub struct LegacyResolveError(pub Box); #[derive(Debug, Error)] pub enum LegacyResolveErrorKind { @@ -121,8 +96,6 @@ impl NodeJsErrorCoded for LegacyResolveError { } } -kinded_err!(PackageFolderResolveError, PackageFolderResolveErrorKind); - #[derive(Debug, Error)] #[error( "Could not find package '{}' from referrer '{}'{}.", @@ -186,6 +159,9 @@ impl NodeJsErrorCoded for PackageFolderResolveError { } } +#[derive(Debug, Boxed)] +pub struct PackageFolderResolveError(pub Box); + #[derive(Debug, Error)] pub enum PackageFolderResolveErrorKind { #[error(transparent)] @@ -196,8 +172,6 @@ pub enum PackageFolderResolveErrorKind { Io(#[from] PackageFolderResolveIoError), } -kinded_err!(PackageSubpathResolveError, PackageSubpathResolveErrorKind); - impl NodeJsErrorCoded for PackageSubpathResolveError { fn code(&self) -> NodeJsErrorCode { match self.as_kind() { @@ -208,6 +182,9 @@ impl NodeJsErrorCoded for PackageSubpathResolveError { } } +#[derive(Debug, Boxed)] +pub struct PackageSubpathResolveError(pub Box); + #[derive(Debug, Error)] pub enum PackageSubpathResolveErrorKind { #[error(transparent)] @@ -252,8 +229,6 @@ impl NodeJsErrorCoded for PackageTargetNotFoundError { } } -kinded_err!(PackageTargetResolveError, PackageTargetResolveErrorKind); - impl NodeJsErrorCoded for PackageTargetResolveError { fn code(&self) -> NodeJsErrorCode { match self.as_kind() { @@ -266,6 +241,9 @@ impl NodeJsErrorCoded for PackageTargetResolveError { } } +#[derive(Debug, Boxed)] +pub struct PackageTargetResolveError(pub Box); + #[derive(Debug, Error)] pub enum PackageTargetResolveErrorKind { #[error(transparent)] @@ -280,8 +258,6 @@ pub enum PackageTargetResolveErrorKind { TypesNotFound(#[from] TypesNotFoundError), } -kinded_err!(PackageExportsResolveError, PackageExportsResolveErrorKind); - impl NodeJsErrorCoded for PackageExportsResolveError { fn code(&self) -> NodeJsErrorCode { match self.as_kind() { @@ -291,6 +267,9 @@ impl NodeJsErrorCoded for PackageExportsResolveError { } } +#[derive(Debug, Boxed)] +pub struct PackageExportsResolveError(pub Box); + #[derive(Debug, Error)] pub enum PackageExportsResolveErrorKind { #[error(transparent)] @@ -338,8 +317,6 @@ impl NodeJsErrorCoded for PackageJsonLoadError { } } -kinded_err!(ClosestPkgJsonError, ClosestPkgJsonErrorKind); - impl NodeJsErrorCoded for ClosestPkgJsonError { fn code(&self) -> NodeJsErrorCode { match self.as_kind() { @@ -349,6 +326,9 @@ impl NodeJsErrorCoded for ClosestPkgJsonError { } } +#[derive(Debug, Boxed)] +pub struct ClosestPkgJsonError(pub Box); + #[derive(Debug, Error)] pub enum ClosestPkgJsonErrorKind { #[error(transparent)] @@ -392,7 +372,8 @@ impl NodeJsErrorCoded for PackageImportNotDefinedError { } } -kinded_err!(PackageImportsResolveError, PackageImportsResolveErrorKind); +#[derive(Debug, Boxed)] +pub struct PackageImportsResolveError(pub Box); #[derive(Debug, Error)] pub enum PackageImportsResolveErrorKind { @@ -417,8 +398,6 @@ impl NodeJsErrorCoded for PackageImportsResolveErrorKind { } } -kinded_err!(PackageResolveError, PackageResolveErrorKind); - impl NodeJsErrorCoded for PackageResolveError { fn code(&self) -> NodeJsErrorCode { match self.as_kind() { @@ -431,6 +410,9 @@ impl NodeJsErrorCoded for PackageResolveError { } } +#[derive(Debug, Boxed)] +pub struct PackageResolveError(pub Box); + #[derive(Debug, Error)] pub enum PackageResolveErrorKind { #[error(transparent)] @@ -461,7 +443,8 @@ pub struct DataUrlReferrerError { pub source: url::ParseError, } -kinded_err!(NodeResolveError, NodeResolveErrorKind); +#[derive(Debug, Boxed)] +pub struct NodeResolveError(pub Box); #[derive(Debug, Error)] pub enum NodeResolveErrorKind { @@ -481,7 +464,8 @@ pub enum NodeResolveErrorKind { FinalizeResolution(#[from] FinalizeResolutionError), } -kinded_err!(FinalizeResolutionError, FinalizeResolutionErrorKind); +#[derive(Debug, Boxed)] +pub struct FinalizeResolutionError(pub Box); #[derive(Debug, Error)] pub enum FinalizeResolutionErrorKind { diff --git a/runtime/errors.rs b/runtime/errors.rs index 0c26e0e47a..4268fbd502 100644 --- a/runtime/errors.rs +++ b/runtime/errors.rs @@ -41,12 +41,14 @@ use deno_ffi::IRError; use deno_ffi::ReprError; use deno_ffi::StaticError; use deno_fs::FsOpsError; +use deno_fs::FsOpsErrorKind; use deno_http::HttpError; use deno_http::HttpNextError; use deno_http::WebSocketUpgradeError; use deno_io::fs::FsError; use deno_kv::KvCheckError; use deno_kv::KvError; +use deno_kv::KvErrorKind; use deno_kv::KvMutationError; use deno_napi::NApiError; use deno_net::ops::NetError; @@ -760,67 +762,67 @@ fn get_websocket_handshake_error(error: &HandshakeError) -> &'static str { } fn get_fs_ops_error(error: &FsOpsError) -> &'static str { - match error { - FsOpsError::Io(e) => get_io_error_class(e), - FsOpsError::OperationError(e) => get_fs_error(&e.err), - FsOpsError::Permission(e) => get_permission_check_error_class(e), - FsOpsError::Resource(e) | FsOpsError::Other(e) => { - get_error_class_name(e).unwrap_or("Error") - } - FsOpsError::InvalidUtf8(_) => "InvalidData", - FsOpsError::StripPrefix(_) => "Error", - FsOpsError::Canceled(e) => { + use FsOpsErrorKind::*; + match error.as_kind() { + Io(e) => get_io_error_class(e), + OperationError(e) => get_fs_error(&e.err), + Permission(e) => get_permission_check_error_class(e), + Resource(e) | Other(e) => get_error_class_name(e).unwrap_or("Error"), + InvalidUtf8(_) => "InvalidData", + StripPrefix(_) => "Error", + Canceled(e) => { let io_err: io::Error = e.to_owned().into(); get_io_error_class(&io_err) } - FsOpsError::InvalidSeekMode(_) => "TypeError", - FsOpsError::InvalidControlCharacter(_) => "Error", - FsOpsError::InvalidCharacter(_) => "Error", + InvalidSeekMode(_) => "TypeError", + InvalidControlCharacter(_) => "Error", + InvalidCharacter(_) => "Error", #[cfg(windows)] - FsOpsError::InvalidTrailingCharacter => "Error", - FsOpsError::NotCapableAccess { .. } => "NotCapable", - FsOpsError::NotCapable(_) => "NotCapable", + InvalidTrailingCharacter => "Error", + NotCapableAccess { .. } => "NotCapable", + NotCapable(_) => "NotCapable", } } fn get_kv_error(error: &KvError) -> &'static str { - match error { - KvError::DatabaseHandler(e) | KvError::Resource(e) | KvError::Kv(e) => { + use KvErrorKind::*; + match error.as_kind() { + DatabaseHandler(e) | Resource(e) | Kv(e) => { get_error_class_name(e).unwrap_or("Error") } - KvError::TooManyRanges(_) => "TypeError", - KvError::TooManyEntries(_) => "TypeError", - KvError::TooManyChecks(_) => "TypeError", - KvError::TooManyMutations(_) => "TypeError", - KvError::TooManyKeys(_) => "TypeError", - KvError::InvalidLimit => "TypeError", - KvError::InvalidBoundaryKey => "TypeError", - KvError::KeyTooLargeToRead(_) => "TypeError", - KvError::KeyTooLargeToWrite(_) => "TypeError", - KvError::TotalMutationTooLarge(_) => "TypeError", - KvError::TotalKeyTooLarge(_) => "TypeError", - KvError::Io(e) => get_io_error_class(e), - KvError::QueueMessageNotFound => "TypeError", - KvError::StartKeyNotInKeyspace => "TypeError", - KvError::EndKeyNotInKeyspace => "TypeError", - KvError::StartKeyGreaterThanEndKey => "TypeError", - KvError::InvalidCheck(e) => match e { + TooManyRanges(_) => "TypeError", + TooManyEntries(_) => "TypeError", + TooManyChecks(_) => "TypeError", + TooManyMutations(_) => "TypeError", + TooManyKeys(_) => "TypeError", + InvalidLimit => "TypeError", + InvalidBoundaryKey => "TypeError", + KeyTooLargeToRead(_) => "TypeError", + KeyTooLargeToWrite(_) => "TypeError", + TotalMutationTooLarge(_) => "TypeError", + TotalKeyTooLarge(_) => "TypeError", + Io(e) => get_io_error_class(e), + QueueMessageNotFound => "TypeError", + StartKeyNotInKeyspace => "TypeError", + EndKeyNotInKeyspace => "TypeError", + StartKeyGreaterThanEndKey => "TypeError", + InvalidCheck(e) => match e { KvCheckError::InvalidVersionstamp => "TypeError", KvCheckError::Io(e) => get_io_error_class(e), }, - KvError::InvalidMutation(e) => match e { + InvalidMutation(e) => match e { KvMutationError::BigInt(_) => "Error", KvMutationError::Io(e) => get_io_error_class(e), KvMutationError::InvalidMutationWithValue(_) => "TypeError", KvMutationError::InvalidMutationWithoutValue(_) => "TypeError", }, - KvError::InvalidEnqueue(e) => get_io_error_class(e), - KvError::EmptyKey => "TypeError", - KvError::ValueTooLarge(_) => "TypeError", - KvError::EnqueuePayloadTooLarge(_) => "TypeError", - KvError::InvalidCursor => "TypeError", - KvError::CursorOutOfBounds => "TypeError", - KvError::InvalidRange => "TypeError", + InvalidEnqueue(e) => get_io_error_class(e), + EmptyKey => "TypeError", + ValueTooLarge(_) => "TypeError", + EnqueuePayloadTooLarge(_) => "TypeError", + InvalidCursor => "TypeError", + CursorOutOfBounds => "TypeError", + InvalidRange => "TypeError", } } @@ -1087,6 +1089,7 @@ mod node { use deno_node::ops::os::priority::PriorityError; pub use deno_node::ops::os::OsError; pub use deno_node::ops::require::RequireError; + use deno_node::ops::require::RequireErrorKind; pub use deno_node::ops::worker_threads::WorkerThreadsFilenameError; pub use deno_node::ops::zlib::brotli::BrotliError; pub use deno_node::ops::zlib::mode::ModeError; @@ -1158,19 +1161,18 @@ mod node { } pub fn get_require_error(error: &RequireError) -> &'static str { - match error { - RequireError::UrlParse(e) => get_url_parse_error_class(e), - RequireError::Permission(e) => get_error_class_name(e).unwrap_or("Error"), - RequireError::PackageExportsResolve(_) - | RequireError::PackageJsonLoad(_) - | RequireError::ClosestPkgJson(_) - | RequireError::FilePathConversion(_) - | RequireError::UrlConversion(_) - | RequireError::ReadModule(_) - | RequireError::PackageImportsResolve(_) => "Error", - RequireError::Fs(e) | RequireError::UnableToGetCwd(e) => { - super::get_fs_error(e) - } + use RequireErrorKind::*; + match error.as_kind() { + UrlParse(e) => get_url_parse_error_class(e), + Permission(e) => get_error_class_name(e).unwrap_or("Error"), + PackageExportsResolve(_) + | PackageJsonLoad(_) + | ClosestPkgJson(_) + | FilePathConversion(_) + | UrlConversion(_) + | ReadModule(_) + | PackageImportsResolve(_) => "Error", + Fs(e) | UnableToGetCwd(e) => super::get_fs_error(e), } }