Skip to content

Commit

Permalink
feat: align module error
Browse files Browse the repository at this point in the history
  • Loading branch information
h-a-n-a committed Dec 6, 2023
1 parent 2155d7d commit 0143b8b
Show file tree
Hide file tree
Showing 65 changed files with 1,151 additions and 1,239 deletions.
11 changes: 0 additions & 11 deletions Cargo.lock

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

4 changes: 2 additions & 2 deletions crates/node_binding/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use rspack_binding_options::BuiltinPlugin;
use rspack_binding_values::SingleThreadedHashMap;
use rspack_core::PluginExt;
use rspack_fs_node::{AsyncNodeWritableFileSystem, ThreadsafeNodeFS};
use rspack_napi_shared::NAPI_ENV;

mod hook;
mod loader;
Expand All @@ -29,6 +28,7 @@ use loader::run_builtin_loader;
use plugins::*;
use rspack_binding_options::*;
use rspack_binding_values::*;
use rspack_napi_shared::set_napi_env;
use rspack_tracing::chrome::FlushGuard;

#[cfg(not(target_os = "linux"))]
Expand Down Expand Up @@ -223,7 +223,7 @@ impl ObjectFinalize for Rspack {

impl Rspack {
fn prepare_environment(env: &Env) {
NAPI_ENV.with(|napi_env| *napi_env.borrow_mut() = Some(env.raw()));
set_napi_env(env.raw());
}
}

Expand Down
1 change: 1 addition & 0 deletions crates/rspack_binding_options/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
#![feature(try_blocks)]
mod options;
pub use options::*;
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ use derivative::Derivative;
use napi::{Either, Env, JsFunction};
use napi_derive::napi;
use rspack_binding_values::JsChunk;
use rspack_error::{internal_error, Result};
use rspack_error::{internal_error, miette::IntoDiagnostic, Result};
use rspack_napi_shared::{
get_napi_env,
threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode},
JsRegExp, JsRegExpExt, NapiResultExt, NAPI_ENV,
JsRegExp, JsRegExpExt, NapiResultExt,
};
use rspack_plugin_banner::{
BannerContent, BannerContentFnCtx, BannerPluginOptions, BannerRule, BannerRules,
Expand Down Expand Up @@ -39,13 +40,11 @@ impl TryFrom<RawBannerContentWrapper> for BannerContent {
match value.0 {
Either::A(s) => Ok(Self::String(s)),
Either::B(f) => {
let func: ThreadsafeFunction<RawBannerContentFnCtx, String> =
NAPI_ENV.with(|env| -> anyhow::Result<_> {
let env = env.borrow().expect("Failed to get env with external");
let func_use = rspack_binding_macros::js_fn_into_threadsafe_fn!(f, &Env::from(env));
Ok(func_use)
})?;
let func = Arc::new(func);
let func: napi::Result<ThreadsafeFunction<RawBannerContentFnCtx, String>> = try {
let env = unsafe { get_napi_env() };
rspack_binding_macros::js_fn_into_threadsafe_fn!(f, &Env::from(env))
};
let func = Arc::new(func.expect("convert to threadsafe function failed"));
Ok(BannerContent::Fn(Box::new(
move |ctx: BannerContentFnCtx| {
let func = func.clone();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use napi::{bindgen_prelude::Either3, Either};
use napi_derive::napi;
use rspack_error::Result;
use rspack_error::{miette::IntoDiagnostic, Result};
use rspack_napi_shared::{JsRegExp, JsRegExpExt};
use rspack_plugin_swc_js_minimizer::{
SwcJsMinimizerRspackPluginOptions, SwcJsMinimizerRule, SwcJsMinimizerRules,
Expand Down Expand Up @@ -34,7 +34,7 @@ fn try_deserialize_into<'de, T: 'de + Deserialize<'de>>(
) -> Result<BoolOrDataConfig<T>> {
Ok(match value {
Either::A(b) => BoolOrDataConfig::from_bool(*b),
Either::B(s) => BoolOrDataConfig::from_obj(serde_json::from_str(s)?),
Either::B(s) => BoolOrDataConfig::from_obj(serde_json::from_str(s).into_diagnostic()?),
})
}

Expand All @@ -50,7 +50,7 @@ impl TryFrom<RawSwcJsMinimizerRspackPluginOptions> for SwcJsMinimizerRspackPlugi
extract_comments: value.extract_comments,
compress: try_deserialize_into(&value.compress)?,
mangle: try_deserialize_into(&value.mangle)?,
format: serde_json::from_str(&value.format)?,
format: serde_json::from_str(&value.format).into_diagnostic()?,
module: value.module,
test: into_condition(value.test),
include: into_condition(value.include),
Expand Down
19 changes: 10 additions & 9 deletions crates/rspack_binding_options/src/options/raw_external.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ use napi::{Env, JsFunction};
use napi_derive::napi;
use rspack_core::ExternalItemFnCtx;
use rspack_core::{ExternalItem, ExternalItemFnResult, ExternalItemValue};
use rspack_error::internal_error;
use rspack_error::miette::IntoDiagnostic;
use rspack_error::{internal_error, AnyhowError};
use rspack_napi_shared::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode};
use rspack_napi_shared::{JsRegExp, JsRegExpExt, NapiResultExt, NAPI_ENV};
use rspack_napi_shared::{get_napi_env, JsRegExp, JsRegExpExt, NapiResultExt};

#[napi(object)]
pub struct RawHttpExternalsRspackPluginOptions {
Expand Down Expand Up @@ -92,13 +93,13 @@ impl TryFrom<RawExternalItemWrapper> for ExternalItem {
.collect(),
)),
Either4::D(v) => {
let fn_payload: ThreadsafeFunction<RawExternalItemFnCtx, RawExternalItemFnResult> =
NAPI_ENV.with(|env| -> anyhow::Result<_> {
let env = env.borrow().expect("Failed to get env with external");
let fn_payload = rspack_binding_macros::js_fn_into_threadsafe_fn!(v, &Env::from(env));
Ok(fn_payload)
})?;
let fn_payload = Arc::new(fn_payload);
let fn_payload: napi::Result<
ThreadsafeFunction<RawExternalItemFnCtx, RawExternalItemFnResult>,
> = try {
let env = unsafe { get_napi_env() };
rspack_binding_macros::js_fn_into_threadsafe_fn!(v, &Env::from(env))
};
let fn_payload = Arc::new(fn_payload.expect("convert to threadsafe function failed"));
Ok(Self::Fn(Box::new(move |ctx: ExternalItemFnCtx| {
let fn_payload = fn_payload.clone();
Box::pin(async move {
Expand Down
107 changes: 50 additions & 57 deletions crates/rspack_binding_options/src/options/raw_module/js_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use napi_derive::napi;
use rspack_core::{rspack_sources::SourceMap, Content, ResourceData};
use rspack_error::Diagnostic;
use rspack_loader_runner::AdditionalData;
use rspack_napi_shared::get_napi_env;
use rustc_hash::FxHashSet as HashSet;
use tracing::{span_enabled, Level};
use {
Expand All @@ -17,7 +18,7 @@ use {
rspack_error::internal_error,
rspack_identifier::{Identifiable, Identifier},
rspack_napi_shared::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode},
rspack_napi_shared::{NapiResultExt, NAPI_ENV},
rspack_napi_shared::NapiResultExt,
};

use crate::get_builtin_loader;
Expand Down Expand Up @@ -53,56 +54,48 @@ impl TryFrom<JsFunction> for JsLoaderRunner {

fn try_from(value: JsFunction) -> std::result::Result<Self, Self::Error> {
let loader_runner = unsafe { value.raw() };

let func = NAPI_ENV.with(|env| -> anyhow::Result<_> {
let env = env
.borrow()
.expect("Failed to get env, did you forget to call it from node?");

let mut func = ThreadsafeFunction::<JsLoaderContext, LoaderThreadsafeLoaderResult>::create(
env,
loader_runner,
0,
|ctx| {
let (ctx, resolver) = ctx.split_into_parts();

let env = ctx.env;
let cb = ctx.callback;
let resource = ctx.value.resource.clone();

let loader_name = if span_enabled!(Level::TRACE) {
let loader_path = &ctx.value.current_loader;
// try to remove the previous node_modules parts from path for better display

let parts = loader_path.split("node_modules/");
let loader_name: &str = parts.last().unwrap_or(loader_path.as_str());
String::from(loader_name)
} else {
String::from("unknown")
};
let result = tracing::span!(
tracing::Level::INFO,
"loader_sync_call",
resource = &resource,
loader_name = &loader_name
)
.in_scope(|| unsafe { call_js_function_with_napi_objects!(env, cb, ctx.value) });

let resolve_start = std::time::Instant::now();
resolver.resolve::<Option<JsLoaderResult>>(result, move |_, r| {
tracing::trace!(
"Finish resolving loader result for {}, took {}ms",
resource,
resolve_start.elapsed().as_millis()
);
Ok(r)
})
},
)?;
func.unref(&Env::from(env))?;
Ok(func)
})?;

let env = unsafe { get_napi_env() };
let mut func = ThreadsafeFunction::<JsLoaderContext, LoaderThreadsafeLoaderResult>::create(
env,
loader_runner,
0,
|ctx| {
let (ctx, resolver) = ctx.split_into_parts();

let env = ctx.env;
let cb = ctx.callback;
let resource = ctx.value.resource.clone();

let loader_name = if span_enabled!(Level::TRACE) {
let loader_path = &ctx.value.current_loader;
// try to remove the previous node_modules parts from path for better display

let parts = loader_path.split("node_modules/");
let loader_name: &str = parts.last().unwrap_or(loader_path.as_str());
String::from(loader_name)
} else {
String::from("unknown")
};
let result = tracing::span!(
tracing::Level::INFO,
"loader_sync_call",
resource = &resource,
loader_name = &loader_name
)
.in_scope(|| unsafe { call_js_function_with_napi_objects!(env, cb, ctx.value) });

let resolve_start = std::time::Instant::now();
resolver.resolve::<Option<JsLoaderResult>>(result, move |_, r| {
tracing::trace!(
"Finish resolving loader result for {}, took {}ms",
resource,
resolve_start.elapsed().as_millis()
);
Ok(r)
})
},
)?;
func.unref(&Env::from(env))?;
Ok(Self::ThreadsafeFunction(func))
}
}
Expand Down Expand Up @@ -132,7 +125,7 @@ impl Loader<LoaderRunnerContext> for JsLoaderAdapter {
&self,
loader_context: &mut LoaderContext<'_, LoaderRunnerContext>,
) -> rspack_error::Result<()> {
let mut js_loader_context: JsLoaderContext = (&*loader_context).try_into()?;
let mut js_loader_context: JsLoaderContext = loader_context.try_into()?;
js_loader_context.is_pitching = true;

let loader_result = self
Expand Down Expand Up @@ -161,7 +154,7 @@ impl Loader<LoaderRunnerContext> for JsLoaderAdapter {
&self,
loader_context: &mut LoaderContext<'_, LoaderRunnerContext>,
) -> rspack_error::Result<()> {
let mut js_loader_context: JsLoaderContext = (&*loader_context).try_into()?;
let mut js_loader_context: JsLoaderContext = loader_context.try_into()?;
// Instruct the JS loader-runner to execute loaders in backwards.
js_loader_context.is_pitching = false;

Expand Down Expand Up @@ -265,13 +258,13 @@ pub struct JsLoaderContext {
pub diagnostics_external: External<Vec<Diagnostic>>,
}

impl TryFrom<&rspack_core::LoaderContext<'_, rspack_core::LoaderRunnerContext>>
impl TryFrom<&mut rspack_core::LoaderContext<'_, rspack_core::LoaderRunnerContext>>
for JsLoaderContext
{
type Error = rspack_error::Error;

fn try_from(
cx: &rspack_core::LoaderContext<'_, rspack_core::LoaderRunnerContext>,
cx: &mut rspack_core::LoaderContext<'_, rspack_core::LoaderRunnerContext>,
) -> std::result::Result<Self, Self::Error> {
Ok(JsLoaderContext {
content: cx
Expand Down Expand Up @@ -322,7 +315,7 @@ impl TryFrom<&rspack_core::LoaderContext<'_, rspack_core::LoaderRunnerContext>>

additional_data_external: External::new(cx.additional_data.clone()),
context_external: External::new(cx.context.clone()),
diagnostics_external: External::new(cx.__diagnostics.clone()),
diagnostics_external: External::new(cx.__diagnostics.drain(..).collect()),
})
}
}
Expand Down Expand Up @@ -410,7 +403,7 @@ pub async fn run_builtin_loader(
cx.__loader_index = 0;
}

JsLoaderContext::try_from(&cx).map_err(|e| Error::from_reason(e.to_string()))
JsLoaderContext::try_from(&mut cx).map_err(|e| Error::from_reason(e.to_string()))
}

// #[napi(object)]
Expand Down
35 changes: 15 additions & 20 deletions crates/rspack_binding_options/src/options/raw_module/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,15 @@ use rspack_core::{
ModuleRule, ModuleRuleEnforce, ModuleRuleUse, ModuleRuleUseLoader, ModuleType, ParserOptions,
ParserOptionsByModuleType,
};
use rspack_error::internal_error;
use rspack_error::{internal_error, miette::IntoDiagnostic};
use rspack_loader_react_refresh::REACT_REFRESH_LOADER_IDENTIFIER;
use rspack_loader_sass::SASS_LOADER_IDENTIFIER;
use rspack_loader_swc::SWC_LOADER_IDENTIFIER;
use rspack_napi_shared::get_napi_env;
use serde::Deserialize;
use {
rspack_napi_shared::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode},
rspack_napi_shared::{NapiResultExt, NAPI_ENV},
rspack_napi_shared::NapiResultExt,
};

use crate::{RawOptionsApply, RawResolveOptions};
Expand Down Expand Up @@ -222,16 +223,13 @@ impl TryFrom<RawRuleSetCondition> for rspack_core::RuleSetCondition {
"should have a func_matcher when RawRuleSetCondition.type is \"function\""
)
})?;
let func_matcher: ThreadsafeFunction<String, bool> =
NAPI_ENV.with(|env| -> anyhow::Result<_> {
let env = env
.borrow()
.expect("Failed to get env, did you forget to call it from node?");
let func_matcher =
rspack_binding_macros::js_fn_into_threadsafe_fn!(func_matcher, &Env::from(env));
Ok(func_matcher)
})?;
let func_matcher = Arc::new(func_matcher);

let env =unsafe { get_napi_env()};

let func_matcher: napi::Result<ThreadsafeFunction<String, bool>> = try {
rspack_binding_macros::js_fn_into_threadsafe_fn!(func_matcher, &Env::from(env))
};
let func_matcher = Arc::new(func_matcher.expect("convert to threadsafe function failed"));

Self::Func(Box::new(move |data: &str| {
let func_matcher = func_matcher.clone();
Expand Down Expand Up @@ -598,14 +596,11 @@ impl RawOptionsApply for RawModuleRule {
"should have a func_matcher when RawRuleSetCondition.type is \"function\""
)
})?;
let func_use: ThreadsafeFunction<RawFuncUseCtx, Vec<RawModuleRuleUse>> =
NAPI_ENV.with(|env| -> anyhow::Result<_> {
let env = env.borrow().expect("Failed to get env with external");
let func_use =
rspack_binding_macros::js_fn_into_threadsafe_fn!(func_use, &Env::from(env));
Ok(func_use)
})?;
let func_use = Arc::new(func_use);
let func_use: Result<ThreadsafeFunction<RawFuncUseCtx, Vec<RawModuleRuleUse>>> = try {
let env = unsafe { get_napi_env() };
rspack_binding_macros::js_fn_into_threadsafe_fn!(func_use, &Env::from(env))
};
let func_use = Arc::new(func_use.into_diagnostic()?);
Ok::<ModuleRuleUse, rspack_error::Error>(ModuleRuleUse::Func(Box::new(
move |ctx: FuncUseCtx| {
let func_use = func_use.clone();
Expand Down
Loading

0 comments on commit 0143b8b

Please sign in to comment.