Skip to content

Commit

Permalink
feat: support enabling tracing
Browse files Browse the repository at this point in the history
  • Loading branch information
hyf0 committed Nov 17, 2023
1 parent 09a5943 commit 05b89f0
Show file tree
Hide file tree
Showing 10 changed files with 86 additions and 40 deletions.
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"Finalizer",
"hasher",
"importee",
"napi",
"oxlint",
"oxlintignore",
"Renamer",
Expand Down
14 changes: 3 additions & 11 deletions crates/rolldown/examples/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,15 @@ use sugar_path::SugarPathBuf;
#[tokio::main]
async fn main() -> Result<()> {
let root = PathBuf::from(&std::env::var("CARGO_MANIFEST_DIR").unwrap());
let repo_root = root.parent().unwrap().parent().unwrap();
let cwd = root.join("./examples").into_normalize();
let mut bundler = Bundler::new(InputOptions {
input: vec![InputItem {
name: Some("basic".to_string()),
import: repo_root
.join("temp/three10x/entry.js")
.into_normalize()
.to_string_lossy()
.to_string(),
}],
input: vec![InputItem { name: Some("basic".to_string()), import: "./index.js".to_string() }],
cwd,
..Default::default()
});

let outputs = bundler.write(Default::default()).await.unwrap();
println!("{outputs:#?}");
let _outputs = bundler.write(Default::default()).await.unwrap();
// println!("{outputs:#?}");

Ok(())
}
4 changes: 3 additions & 1 deletion crates/rolldown/src/bundler/bundler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ impl Bundler<OsFileSystem> {

impl<T: FileSystem + Default + 'static> Bundler<T> {
pub fn with_plugins_and_fs(input_options: InputOptions, plugins: Vec<BoxPlugin>, fs: T) -> Self {
// rolldown_tracing::enable_tracing_on_demand();
rolldown_tracing::try_init_tracing();
Self {
resolver: Resolver::with_cwd_and_fs(input_options.cwd.clone(), false, fs.share()).into(),
plugin_driver: Arc::new(PluginDriver::new(plugins)),
Expand Down Expand Up @@ -107,6 +107,7 @@ impl<T: FileSystem + Default + 'static> Bundler<T> {
build_ret
}

#[tracing::instrument(skip_all)]
async fn try_build(&mut self) -> BatchedResult<LinkStageOutput> {
let build_info = ScanStage::new(
Arc::clone(&self.input_options),
Expand All @@ -122,6 +123,7 @@ impl<T: FileSystem + Default + 'static> Bundler<T> {
Ok(link_stage.link())
}

#[tracing::instrument(skip_all)]
async fn bundle_up(&mut self, output_options: OutputOptions) -> BuildResult<Vec<Output>> {
tracing::trace!("InputOptions {:#?}", self.input_options);
tracing::trace!("OutputOptions: {output_options:#?}",);
Expand Down
1 change: 1 addition & 0 deletions crates/rolldown/src/bundler/stages/bundle_stage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ impl<'a> BundleStage<'a> {
Self { link_output, output_options, input_options }
}

#[tracing::instrument(skip_all)]
pub fn bundle(&mut self) -> Vec<Output> {
use rayon::prelude::*;
let mut chunk_graph = self.generate_chunks();
Expand Down
1 change: 1 addition & 0 deletions crates/rolldown/src/bundler/stages/link_stage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ impl LinkStage {
}
}

#[tracing::instrument(skip_all)]
pub fn link(mut self) -> LinkStageOutput {
self.sort_modules();
Linker::new(&mut self).link();
Expand Down
1 change: 1 addition & 0 deletions crates/rolldown/src/bundler/stages/scan_stage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ impl<Fs: FileSystem + Default + 'static> ScanStage<Fs> {
Self { input_options, plugin_driver, fs, resolver }
}

#[tracing::instrument(skip_all)]
pub async fn scan(&self) -> BatchedResult<ScanStageOutput> {
assert!(!self.input_options.input.is_empty(), "You must supply options.input to rolldown");

Expand Down
4 changes: 2 additions & 2 deletions crates/rolldown_binding/src/bundler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use tracing::instrument;

use crate::{
options::InputOptions, options::OutputOptions, output::Outputs,
utils::init_custom_trace_subscriber, NAPI_ENV,
utils::try_init_custom_trace_subscriber, NAPI_ENV,
};

#[napi]
Expand All @@ -18,7 +18,7 @@ pub struct Bundler {
impl Bundler {
#[napi(constructor)]
pub fn new(env: Env, input_opts: InputOptions) -> napi::Result<Self> {
init_custom_trace_subscriber(env);
try_init_custom_trace_subscriber(env);
Self::new_impl(env, input_opts)
}

Expand Down
30 changes: 14 additions & 16 deletions crates/rolldown_binding/src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,24 @@
pub mod napi_error_ext;
use napi::Env;
use std::env;
use std::sync::atomic::AtomicBool;
mod into_js_unknown_vec;
pub use into_js_unknown_vec::*;
mod js_callback;
pub use js_callback::*;
use rolldown_tracing::enable_tracing_on_demand;
use rolldown_tracing::try_init_tracing_with_chrome_layer;

static IS_ENABLE_TRACING: AtomicBool = AtomicBool::new(false);

pub fn init_custom_trace_subscriber(mut napi_env: Env) {
let value = env::var("TRACE").unwrap_or_default();
if value == "1" && !IS_ENABLE_TRACING.swap(true, std::sync::atomic::Ordering::SeqCst) {
let guard = enable_tracing_on_demand();
if let Some(guard) = guard {
napi_env
.add_env_cleanup_hook(guard, |flush_guard| {
flush_guard.flush();
drop(flush_guard);
})
.expect("Should able to initialize cleanup for custom trace subscriber");
pub fn try_init_custom_trace_subscriber(mut napi_env: Env) {
match std::env::var("LOG_LAYER") {
Ok(val) if val == "chrome" => {
let guard = try_init_tracing_with_chrome_layer();
if let Some(guard) = guard {
napi_env
.add_env_cleanup_hook(guard, |flush_guard| {
flush_guard.flush();
drop(flush_guard);
})
.expect("Should able to initialize cleanup for custom trace subscriber");
}
}
_ => {}
}
}
7 changes: 6 additions & 1 deletion crates/rolldown_tracing/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ license.workspace = true
edition.workspace = true
repository.workspace = true

[lib]
bench = false
test = false
doctest = false

[dependencies]
tracing = { workspace = true }
tracing-chrome = "0.7.0"
tracing-chrome = "0.7.1"
tracing-subscriber = { version = "0.3.16", features = ["env-filter"] }
63 changes: 54 additions & 9 deletions crates/rolldown_tracing/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,65 @@
/// Some guidelines for tracing:
/// - By default, only allow tracing events from crates of this repo.
/// - Using `LOG_OUTPUT=chrome` to collect tracing events into a json file.
/// - This only works on using `@rolldown/node`. If you are running rolldown in rust, this doesn't works.
/// - Using `LOG=TRACE` to enable tracing or other values for more specific tracing.
/// - See https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#example-syntax for more syntax details.
use std::sync::atomic::AtomicBool;

use tracing::{metadata::LevelFilter, Level};
use tracing::{level_filters::LevelFilter, Level};
use tracing_chrome::FlushGuard;
use tracing_subscriber::EnvFilter;
use tracing_subscriber::{fmt, prelude::*};

static IS_INITIALIZE: AtomicBool = AtomicBool::new(false);
static IS_INITIALIZED: AtomicBool = AtomicBool::new(false);

pub fn enable_tracing_on_demand() -> Option<FlushGuard> {
use tracing_subscriber::{fmt, prelude::*, EnvFilter};
if !IS_INITIALIZE.swap(true, std::sync::atomic::Ordering::SeqCst) {
pub fn try_init_tracing() {
if std::env::var("LOG").is_err() {
// tracing will slow down the bundling process, so we only enable it when `LOG` is set.
return;
}
if !IS_INITIALIZED.swap(true, std::sync::atomic::Ordering::SeqCst) {
tracing_subscriber::registry()
.with(fmt::layer())
.with(
tracing_subscriber::filter::Targets::new().with_targets(vec![("rolldown", Level::TRACE)]),
tracing_subscriber::filter::Targets::new()
.with_targets(vec![("rolldown", Level::TRACE), ("rolldown_binding", Level::TRACE)]),
)
.with(
EnvFilter::builder()
.with_env_var("LOG")
.with_default_directive(LevelFilter::TRACE.into())
.from_env_lossy(),
)
.with(fmt::layer().pretty().without_time())
.init();
tracing::trace!("Tracing is initialized.");
}
}

pub fn try_init_tracing_with_chrome_layer() -> Option<FlushGuard> {
use tracing_chrome::ChromeLayerBuilder;
use tracing_subscriber::prelude::*;
if std::env::var("LOG").is_err() {
// tracing will slow down the bundling process, so we only enable it when `LOG` is set.
return None;
}
if IS_INITIALIZED.swap(true, std::sync::atomic::Ordering::SeqCst) {
None
} else {
let (chrome_layer, guard) = ChromeLayerBuilder::new().build();
tracing_subscriber::registry()
.with(
tracing_subscriber::filter::Targets::new()
.with_targets(vec![("rolldown", Level::TRACE), ("rolldown_binding", Level::TRACE)]),
)
.with(
EnvFilter::builder()
.with_env_var("LOG")
.with_default_directive(LevelFilter::TRACE.into())
.from_env_lossy(),
)
.with(EnvFilter::builder().with_default_directive(LevelFilter::TRACE.into()).from_env_lossy())
.with(chrome_layer)
.init();
Some(guard)
}
None
}

0 comments on commit 05b89f0

Please sign in to comment.