Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] feat: native plugin init #1691

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
244 changes: 218 additions & 26 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ resolver = "2"
anyhow = "1.0.71"
cached = "0.46.1"
clap = "4.3.11"
mimalloc-rust = { version = "=0.2.1" }
oneshot = "0.1.8"
regex = "1.9.3"
serde = "1.0.211"
serde_json = "1.0.132"
swc_core = { version = "0.101.4", default-features = false }
swc_malloc = "1.0.0"
tikv-jemallocator = { version = "=0.5.4", features = ["disable_initial_exec_tls"] }
Comment on lines +14 to 15
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

发现潜在的内存分配器冲突问题

根据代码分析,发现以下问题:

  • crates/mako/src/main.rscrates/binding/src/lib.rs 都使用了 extern crate swc_malloc
  • 但是没有找到全局分配器的配置(#[global_allocator]
  • 同时引入 swc_malloctikv-jemallocator 可能会导致内存分配冲突

建议:

  • 选择其中一个内存分配器作为全局分配器
  • 如果需要使用 tikv-jemallocator,应该移除 swc_malloc 的依赖
  • 在主入口文件中正确配置全局分配器
🔗 Analysis chain

请验证内存分配器的兼容性

当前工作区同时包含了 swc_malloctikv-jemallocator 两个内存分配器。请确认:

  1. 这两个分配器的共存是否会产生冲突
  2. 是否正确配置了全局分配器
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 搜索全局分配器的配置
rg -l "#\[global_allocator\]" 

# 检查是否有其他内存分配器相关的配置
ast-grep --pattern 'use $_malloc'

Length of output: 67


Script:

#!/bin/bash
# 搜索全局分配器的配置,包括可能的变体形式
rg -l "global_allocator|GlobalAlloc" 

# 搜索 jemalloc 相关的导入和使用
rg -l "jemalloc|tikv_jemallocator"

# 搜索 swc_malloc 相关的导入和使用
rg -l "swc_malloc"

# 检查 lib.rs 或 main.rs 中的内存分配器配置
fd -e rs "(lib|main).rs$" -x cat {}

Length of output: 17159


[profile.release]
Expand Down
7 changes: 1 addition & 6 deletions crates/binding/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,7 @@ napi-derive = "2.16.12"
oneshot = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }

[target.'cfg(not(target_os = "linux"))'.dependencies]
mimalloc-rust = { workspace = true }

[target.'cfg(all(target_os = "linux", target_env = "gnu", any(target_arch = "x86_64", target_arch = "aarch64")))'.dependencies]
tikv-jemallocator = { workspace = true }
swc_malloc = { workspace = true }

[build-dependencies]
napi-build = "2.0.1"
15 changes: 3 additions & 12 deletions crates/binding/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#![deny(clippy::all)]

extern crate swc_malloc;

use std::sync::{Arc, Once};

use js_hook::{JsHooks, TsFnHooks};
Expand All @@ -18,18 +20,6 @@ mod js_hook;
mod js_plugin;
mod threadsafe_function;

#[cfg(not(target_os = "linux"))]
#[global_allocator]
static GLOBAL: mimalloc_rust::GlobalMiMalloc = mimalloc_rust::GlobalMiMalloc;

#[cfg(all(
target_os = "linux",
target_env = "gnu",
any(target_arch = "x86_64", target_arch = "aarch64")
))]
#[global_allocator]
static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;

static LOG_INIT: Once = Once::new();

#[napi(object)]
Expand Down Expand Up @@ -165,6 +155,7 @@ pub struct BuildParams {
};
experimental?: {
webpackSyntaxValidate?: string[];
rustPlugins?: Array<[string, any]>;
};
watch?: {
ignoredPaths?: string[];
Expand Down
15 changes: 8 additions & 7 deletions crates/mako/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ oxc_resolver = { version = "=1.7.0", features = ["package_json_raw_json_api"
percent-encoding = { version = "2.3.1" }
serde = { workspace = true }
serde_json = { workspace = true }
swc_malloc = { workspace = true }
url = { version = "2.5.0" }

swc_core = { workspace = true, features = [
Expand All @@ -47,6 +48,7 @@ swc_core = { workspace = true, features = [
"ecma_minifier",
"ecma_minifier_concurrent",
"ecma_parser",
"ecma_plugin_transform",
"ecma_preset_env",
"ecma_quote",
"ecma_transforms_compat",
Expand All @@ -57,10 +59,11 @@ swc_core = { workspace = true, features = [
"ecma_transforms_typescript",
"ecma_utils",
"ecma_visit_path",
"swc_common",
"swc_ecma_quote_macros",
] }

swc_emotion = "0.72.19"
swc_emotion = "=0.72.22"
swc_error_reporters = "0.21.0"
swc_node_comments = "0.24.0"

Expand All @@ -81,6 +84,7 @@ hyper-staticfile = "0.9.6"
hyper-tungstenite = "0.10.0"
indexmap = "2.0.0"
indicatif = "0.17.8"
libloading = "0.8"
md5 = "0.7.0"
mdxjs = "0.2.6"
mime_guess = "2.0.4"
Expand All @@ -90,15 +94,18 @@ parking_lot = { version = "0.12", features = ["nightly"] }
path-clean = "1.0.1"
pathdiff = "0.2.1"
petgraph = "0.6.3"
proc-macro2 = "1"
puffin = { version = "0.16.0", optional = true }
puffin_egui = { version = "0.22.0", optional = true }
quote = "1"
rayon = "1.7.0"
regex = { workspace = true }
sailfish = "0.8.3"
semver = "1.0.23"
serde-xml-rs = "0.6.0"
serde_yaml = "0.9.22"
svgr-rs = { path = "../svgr-rs" }
syn = { version = "2", features = ["full"] }
thiserror = "1.0.43"
tokio = { version = "1", features = ["rt-multi-thread", "sync"] }
tokio-tungstenite = "0.19.0"
Expand All @@ -108,12 +115,6 @@ tracing-subscriber = { version = "0.3.17", features = ["env-filter"] }
tungstenite = "0.19.0"
twox-hash = "1.6.3"

[target.'cfg(not(target_os = "linux"))'.dependencies]
mimalloc-rust = { workspace = true }

[target.'cfg(all(target_os = "linux", target_env = "gnu", any(target_arch = "x86_64", target_arch = "aarch64")))'.dependencies]
tikv-jemallocator = { workspace = true }

[dev-dependencies]
insta = { version = "1.30.0", features = ["yaml"] }
maplit = "1.0.2"
Expand Down
2 changes: 1 addition & 1 deletion crates/mako/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ pub(crate) mod js_ast;
pub(crate) mod sourcemap;
#[cfg(test)]
pub mod tests;
pub(crate) mod utils;
pub mod utils;

pub const DUMMY_CTXT: SyntaxContext = SyntaxContext::empty();
20 changes: 16 additions & 4 deletions crates/mako/src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use anyhow::{anyhow, Error, Result};
use colored::Colorize;
use libloading::Library;
use regex::Regex;
use swc_core::common::sync::Lrc;
use swc_core::common::{Globals, SourceMap, DUMMY_SP};
Expand Down Expand Up @@ -220,7 +221,7 @@

impl Compiler {
pub fn new(
config: Config,
mut config: Config,
root: PathBuf,
args: Args,
extra_plugins: Option<Vec<Arc<dyn Plugin>>>,
Expand All @@ -238,6 +239,19 @@
if let Some(extra_plugins) = extra_plugins {
plugins.extend(extra_plugins);
}

let mut external_plugins: Vec<Arc<dyn Plugin>> = vec![];
unsafe {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using unsafe blocks can lead to undefined behavior if not handled correctly. Ensure that the Rust plugins being loaded are trusted and that the _plugin_create function is safe to call with the provided options. Consider adding checks or constraints to mitigate potential risks.

for rust_plugin in config.experimental.rust_plugins.clone() {
let lib = Arc::new(Library::new(rust_plugin.path)?);

Check warning on line 246 in crates/mako/src/compiler.rs

View check run for this annotation

Codecov / codecov/patch

crates/mako/src/compiler.rs#L246

Added line #L246 was not covered by tests
let plugin_create_fn: libloading::Symbol<
unsafe extern "C" fn(option: String) -> Arc<dyn Plugin>,
> = lib.get(b"_plugin_create").unwrap();
let plugin = plugin_create_fn(rust_plugin.options);
external_plugins.push(plugin);

Check warning on line 251 in crates/mako/src/compiler.rs

View check run for this annotation

Codecov / codecov/patch

crates/mako/src/compiler.rs#L249-L251

Added lines #L249 - L251 were not covered by tests
}
}

let builtin_plugins: Vec<Arc<dyn Plugin>> = vec![
// features
Arc::new(plugins::manifest::ManifestPlugin {}),
Expand All @@ -254,10 +268,9 @@
Arc::new(plugins::tree_shaking::FarmTreeShake {}),
Arc::new(plugins::detect_circular_dependence::LoopDetector {}),
];
plugins.extend(external_plugins);
plugins.extend(builtin_plugins);

let mut config = config;

if let Some(progress) = &config.progress {
plugins.push(Arc::new(plugins::progress::ProgressPlugin::new(
plugins::progress::ProgressPluginOptions {
Expand Down Expand Up @@ -480,7 +493,6 @@
let mg = self.context.module_graph.read().unwrap();
cg.full_hash(&mg)
}

fn clean_dist(&self) -> Result<()> {
// compiler 前清除 dist,如果后续 dev 环境不在 output_path 里,需要再补上 dev 的逻辑
let output_path = &self.context.config.output.path;
Expand Down
24 changes: 23 additions & 1 deletion crates/mako/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@
pub use rsc_client::{deserialize_rsc_client, LogServerComponent, RscClientConfig};
pub use rsc_server::{deserialize_rsc_server, RscServerConfig};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_json::{json, Value};
pub use stats::{deserialize_stats, StatsConfig};
use thiserror::Error;
pub use transform_import::{TransformImportConfig, TransformImportStyle};
Expand Down Expand Up @@ -232,14 +232,27 @@
) -> Result<Self> {
let abs_config_file = root.join(CONFIG_FILE);
let abs_config_file = abs_config_file.to_str().unwrap();
let mut overrides_json: Option<String> = None;
let c = config::Config::builder();
// default config
let c = c.add_source(config::File::from_str(
DEFAULT_CONFIG,
config::FileFormat::Json5,
));

// default config from args
let c = if let Some(default_config) = default_config {
let result: Result<Value, serde_json::Error> = serde_json::from_str(default_config);
if let Ok(config) = result {
if let Some(experimental) = config.get("experimental") {
overrides_json = Some(
serde_json::to_string(&json!({

Check warning on line 249 in crates/mako/src/config.rs

View check run for this annotation

Codecov / codecov/patch

crates/mako/src/config.rs#L248-L249

Added lines #L248 - L249 were not covered by tests
"experimental": experimental
}))
.unwrap(),
);

Check warning on line 253 in crates/mako/src/config.rs

View check run for this annotation

Codecov / codecov/patch

crates/mako/src/config.rs#L253

Added line #L253 was not covered by tests
}
};
c.add_source(config::File::from_str(
default_config,
config::FileFormat::Json5,
Expand All @@ -260,6 +273,15 @@
} else {
c
};
// overrides config
let c = if let Some(overrides) = overrides_json {
c.add_source(config::File::from_str(
overrides.as_str(),
config::FileFormat::Json5,

Check warning on line 280 in crates/mako/src/config.rs

View check run for this annotation

Codecov / codecov/patch

crates/mako/src/config.rs#L278-L280

Added lines #L278 - L280 were not covered by tests
))
} else {

Check warning on line 282 in crates/mako/src/config.rs

View check run for this annotation

Codecov / codecov/patch

crates/mako/src/config.rs#L282

Added line #L282 was not covered by tests
c
};

let c = c.build()?;
let mut ret = c.try_deserialize::<Config>();
Expand Down
7 changes: 7 additions & 0 deletions crates/mako/src/config/experimental.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

use crate::create_deserialize_fn;

#[derive(Deserialize, Serialize, Debug, Clone)]

Check warning on line 5 in crates/mako/src/config/experimental.rs

View check run for this annotation

Codecov / codecov/patch

crates/mako/src/config/experimental.rs#L5

Added line #L5 was not covered by tests
pub struct RustPlugin {
pub path: String,
pub options: String,

Check warning on line 8 in crates/mako/src/config/experimental.rs

View check run for this annotation

Codecov / codecov/patch

crates/mako/src/config/experimental.rs#L7-L8

Added lines #L7 - L8 were not covered by tests
}
Comment on lines +5 to +9
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

建议改进 RustPlugin 结构体的设计

当前实现存在以下需要改进的地方:

  1. 缺少结构体和字段的文档注释,建议添加以说明用途和预期值
  2. options 字段使用 String 类型可能过于简单,建议考虑使用更结构化的类型(如 serde_json::Value)来支持更复杂的配置

建议按如下方式修改:

 #[derive(Deserialize, Serialize, Debug, Clone)]
+/// 用于配置 Rust 原生插件的结构体
 pub struct RustPlugin {
+    /// 插件的文件路径
     pub path: String,
+    /// 插件的配置选项,支持 JSON 格式
-    pub options: String,
+    pub options: serde_json::Value,
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct RustPlugin {
pub path: String,
pub options: String,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
/// 用于配置 Rust 原生插件的结构体
pub struct RustPlugin {
/// 插件的文件路径
pub path: String,
/// 插件的配置选项,支持 JSON 格式
pub options: serde_json::Value,
}


#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ExperimentalConfig {
Expand All @@ -12,6 +18,7 @@
pub magic_comment: bool,
#[serde(deserialize_with = "deserialize_detect_loop")]
pub detect_circular_dependence: Option<DetectCircularDependence>,
pub rust_plugins: Vec<RustPlugin>,
pub central_ensure: bool,
}

Expand Down
1 change: 1 addition & 0 deletions crates/mako/src/config/mako.config.default.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
"rscClient": false,
"experimental": {
"webpackSyntaxValidate": [],
"rustPlugins": [],
"requireContext": true,
"ignoreNonLiteralRequire": false,
"magicComment": true,
Expand Down
4 changes: 3 additions & 1 deletion crates/mako/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub mod config;
pub mod dev;
mod features;
mod generate;
mod module;
pub mod module;
mod module_graph;
pub mod plugin;
mod plugins;
Expand All @@ -20,6 +20,8 @@ pub mod stats;
pub mod utils;
mod visitors;

pub use {swc_core, swc_malloc};

#[macro_export]
macro_rules! mako_profile_scope {
($id:expr) => {
Expand Down
14 changes: 2 additions & 12 deletions crates/mako/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#![feature(box_patterns)]
#![feature(let_chains)]

extern crate swc_malloc;

use std::sync::Arc;

use anyhow::{anyhow, Result};
Expand All @@ -15,18 +17,6 @@ use mako::utils::tokio_runtime;
use mako::{cli, config};
use tracing::debug;

#[cfg(not(target_os = "linux"))]
#[global_allocator]
static GLOBAL: mimalloc_rust::GlobalMiMalloc = mimalloc_rust::GlobalMiMalloc;

#[cfg(all(
target_os = "linux",
target_env = "gnu",
any(target_arch = "x86_64", target_arch = "aarch64")
))]
#[global_allocator]
static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;

fn main() -> Result<()> {
let fut = async { run().await };

Expand Down
13 changes: 13 additions & 0 deletions crates/mako_plugin_macro/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "mako_plugin_macro"
version = "0.0.1"
edition = "2021"
license = "MIT"

[dependencies]
proc-macro2 = "1"
quote = "1"
syn = { version = "2", features = ["full"] }

[lib]
proc-macro = true
Loading
Loading