diff --git a/crates/rspack_core/src/cache/persistent/occasion/make/module_graph.rs b/crates/rspack_core/src/cache/persistent/occasion/make/module_graph.rs index fd3ac2186fe..4601324a450 100644 --- a/crates/rspack_core/src/cache/persistent/occasion/make/module_graph.rs +++ b/crates/rspack_core/src/cache/persistent/occasion/make/module_graph.rs @@ -132,9 +132,16 @@ pub async fn recovery_module_graph( let mut need_check_dep = vec![]; let mut partial = ModuleGraphPartial::default(); let mut mg = ModuleGraph::new(vec![], Some(&mut partial)); - for (_, v) in storage.load(SCOPE).await? { - let mut node: Node = - from_bytes(&v, context).expect("unexpected module graph deserialize failed"); + let nodes: Vec<_> = storage + .load(SCOPE) + .await? + .into_par_iter() + .map(|(_, v)| { + from_bytes::(&v, context) + .expect("unexpected module graph deserialize failed") + }) + .collect(); + for mut node in nodes { for (index_in_block, (dep, parent_block)) in node.dependencies.into_iter().enumerate() { mg.set_parents( *dep.id(), diff --git a/crates/rspack_core/src/cache/persistent/snapshot/mod.rs b/crates/rspack_core/src/cache/persistent/snapshot/mod.rs index 92dc56d1bce..7ee5fc3a43e 100644 --- a/crates/rspack_core/src/cache/persistent/snapshot/mod.rs +++ b/crates/rspack_core/src/cache/persistent/snapshot/mod.rs @@ -6,6 +6,7 @@ use std::{path::Path, sync::Arc}; use rspack_cacheable::{from_bytes, to_bytes}; use rspack_error::Result; use rspack_fs::ReadableFileSystem; +use rspack_futures::FuturesResults; use rspack_paths::{ArcPath, AssertUtf8}; use rustc_hash::FxHashSet as HashSet; @@ -42,37 +43,38 @@ impl Snapshot { #[tracing::instrument("Cache::Snapshot::add", skip_all)] pub async fn add(&self, paths: impl Iterator) { let default_strategy = StrategyHelper::compile_time(); - let mut helper = StrategyHelper::new(self.fs.clone()); - // TODO use multi thread + let helper = StrategyHelper::new(self.fs.clone()); // TODO merge package version file - for path in paths { - let utf8_path = path.assert_utf8(); - // check path exists - if self.fs.metadata(utf8_path).is_err() { - continue; - } - // TODO directory path should check all sub file - let path_str = utf8_path.as_str(); - if self.options.is_immutable_path(path_str) { - continue; - } - if self.options.is_managed_path(path_str) { - if let Some(v) = helper.package_version(path).await { - self.storage.set( - SCOPE, - path.as_os_str().as_encoded_bytes().to_vec(), - to_bytes::<_, ()>(&v, &()).expect("should to bytes success"), - ); - continue; + let _ = paths + .map(|path| async { + let utf8_path = path.assert_utf8(); + // check path exists + if self.fs.metadata(utf8_path).is_err() { + return; } - } - // compiler time - self.storage.set( - SCOPE, - path.as_os_str().as_encoded_bytes().to_vec(), - to_bytes::<_, ()>(&default_strategy, &()).expect("should to bytes success"), - ); - } + // TODO directory path should check all sub file + let path_str = utf8_path.as_str(); + if self.options.is_immutable_path(path_str) { + return; + } + if self.options.is_managed_path(path_str) { + if let Some(v) = helper.package_version(path).await { + self.storage.set( + SCOPE, + path.as_os_str().as_encoded_bytes().to_vec(), + to_bytes::<_, ()>(&v, &()).expect("should to bytes success"), + ); + return; + } + } + // compiler time + self.storage.set( + SCOPE, + path.as_os_str().as_encoded_bytes().to_vec(), + to_bytes::<_, ()>(&default_strategy, &()).expect("should to bytes success"), + ); + }) + .collect::>(); } pub fn remove(&self, paths: impl Iterator) { @@ -85,16 +87,26 @@ impl Snapshot { #[tracing::instrument("Cache::Snapshot::calc_modified_path", skip_all)] pub async fn calc_modified_paths(&self) -> Result<(HashSet, HashSet)> { - let mut helper = StrategyHelper::new(self.fs.clone()); + let helper = StrategyHelper::new(self.fs.clone()); + + let results = self + .storage + .load(SCOPE) + .await? + .iter() + .map(|(key, value)| async { + let path: ArcPath = Path::new(&*String::from_utf8_lossy(key)).into(); + let strategy: Strategy = + from_bytes::(value, &()).expect("should from bytes success"); + let validate = helper.validate(&path, &strategy).await; + (path, validate) + }) + .collect::>(); + let mut modified_path = HashSet::default(); let mut deleted_path = HashSet::default(); - - // TODO use multi thread - for (key, value) in self.storage.load(SCOPE).await? { - let path: ArcPath = Path::new(&*String::from_utf8_lossy(&key)).into(); - let strategy: Strategy = - from_bytes::(&value, &()).expect("should from bytes success"); - match helper.validate(&path, &strategy).await { + for (path, validate) in results.into_inner() { + match validate { ValidateResult::Modified => { modified_path.insert(path); } @@ -123,7 +135,7 @@ mod tests { }; } - #[tokio::test] + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn should_snapshot_work() { let fs = Arc::new(MemoryFileSystem::default()); let storage = Arc::new(MemoryStorage::default()); diff --git a/crates/rspack_core/src/cache/persistent/snapshot/strategy.rs b/crates/rspack_core/src/cache/persistent/snapshot/strategy.rs index b3f5a76e7b1..e56e0daf3c2 100644 --- a/crates/rspack_core/src/cache/persistent/snapshot/strategy.rs +++ b/crates/rspack_core/src/cache/persistent/snapshot/strategy.rs @@ -4,10 +4,10 @@ use std::{ time::{SystemTime, UNIX_EPOCH}, }; +use dashmap::DashMap; use rspack_cacheable::cacheable; use rspack_fs::ReadableFileSystem; use rspack_paths::{ArcPath, AssertUtf8}; -use rustc_hash::FxHashMap as HashMap; /// Snapshot check strategy #[cacheable] @@ -38,7 +38,7 @@ pub enum ValidateResult { pub struct StrategyHelper { fs: Arc, - package_version_cache: HashMap>, + package_version_cache: DashMap>, } impl StrategyHelper { @@ -60,7 +60,7 @@ impl StrategyHelper { /// get path file version in package.json #[async_recursion::async_recursion] - async fn package_version_with_cache(&mut self, path: &Path) -> Option { + async fn package_version_with_cache(&self, path: &Path) -> Option { if let Some(version) = self.package_version_cache.get(path) { return version.clone(); } @@ -99,7 +99,7 @@ impl StrategyHelper { Strategy::CompileTime(now) } /// get path file package version strategy - pub async fn package_version(&mut self, path: &Path) -> Option { + pub async fn package_version(&self, path: &Path) -> Option { self .package_version_with_cache(path) .await @@ -107,7 +107,7 @@ impl StrategyHelper { } /// validate path file by target strategy - pub async fn validate(&mut self, path: &Path, strategy: &Strategy) -> ValidateResult { + pub async fn validate(&self, path: &Path, strategy: &Strategy) -> ValidateResult { match strategy { Strategy::PackageVersion(version) => { if let Some(ref cur_version) = self.package_version_with_cache(path).await { @@ -172,7 +172,7 @@ mod tests { }; assert!(time1 < time2); - let mut helper = StrategyHelper::new(fs.clone()); + let helper = StrategyHelper::new(fs.clone()); // modified_time assert_eq!( helper.modified_time(Path::new("/file1")).await, diff --git a/packages/rspack-cli/package.json b/packages/rspack-cli/package.json index 7caf77350ba..38e992d0b27 100644 --- a/packages/rspack-cli/package.json +++ b/packages/rspack-cli/package.json @@ -35,7 +35,6 @@ "dependencies": { "@discoveryjs/json-ext": "^0.5.7", "@rspack/dev-server": "1.0.10", - "@rspack/tracing": "workspace:*", "colorette": "2.0.19", "exit-hook": "^4.0.0", "interpret": "^3.1.1", @@ -46,6 +45,7 @@ "devDependencies": { "@rslib/core": "0.2.2", "@rspack/core": "workspace:*", + "@rspack/tracing": "workspace:*", "@types/interpret": "^1.1.3", "@types/rechoir": "^0.6.1", "@types/webpack-bundle-analyzer": "^4.6.0", @@ -57,7 +57,13 @@ "typescript": "^5.7.2" }, "peerDependencies": { - "@rspack/core": "^1.0.0-alpha || ^1.x" + "@rspack/core": "^1.0.0-alpha || ^1.x", + "@rspack/tracing": "^1.x" + }, + "peerDependenciesMeta": { + "@rspack/tracing": { + "optional": true + } }, "publishConfig": { "access": "public", diff --git a/packages/rspack-tracing/package.json b/packages/rspack-tracing/package.json index fd9774b70aa..b7e83ce1a5e 100644 --- a/packages/rspack-tracing/package.json +++ b/packages/rspack-tracing/package.json @@ -1,7 +1,6 @@ { "name": "@rspack/tracing", - "version": "1.0.12", - "private": true, + "version": "1.2.0-beta.0", "type": "module", "description": "Internal tracing package for rspack", "homepage": "https://rspack.dev", @@ -11,6 +10,10 @@ "url": "https://github.com/web-infra-dev/rspack", "directory": "packages/rspack-tracing" }, + "publishConfig": { + "access": "public", + "provenance": true + }, "license": "MIT", "main": "./index.js", "types": "./index.d.ts", diff --git a/packages/rspack/etc/core.api.md b/packages/rspack/etc/core.api.md index 85666c85b65..ec7866722a8 100644 --- a/packages/rspack/etc/core.api.md +++ b/packages/rspack/etc/core.api.md @@ -23,6 +23,7 @@ import { ExternalObject } from '@rspack/binding'; import fs from 'graceful-fs'; import { fs as fs_2 } from 'fs'; import { HookMap } from '@rspack/lite-tapable'; +import type { IncomingMessage } from 'node:http'; import { inspect } from 'node:util'; import type { JsAddingRuntimeModule } from '@rspack/binding'; import { JsAfterEmitData } from '@rspack/binding'; @@ -54,6 +55,7 @@ import type { JsStats } from '@rspack/binding'; import type { JsStatsCompilation } from '@rspack/binding'; import type { JsStatsError } from '@rspack/binding'; import type { JsStatsWarning } from '@rspack/binding'; +import type { ListenOptions } from 'node:net'; import * as liteTapable from '@rspack/lite-tapable'; import { Logger as Logger_2 } from './logging/Logger'; import { RawCopyPattern } from '@rspack/binding'; @@ -65,11 +67,16 @@ import { RawProgressPluginOptions } from '@rspack/binding'; import { RawProvideOptions } from '@rspack/binding'; import { RawRuntimeChunkOptions } from '@rspack/binding'; import { RspackOptionsNormalized as RspackOptionsNormalized_2 } from '.'; +import type { SecureContextOptions } from 'node:tls'; +import type { Server } from 'node:net'; +import type { ServerOptions } from 'node:http'; +import type { ServerResponse } from 'node:http'; import { RawSourceMapDevToolPluginOptions as SourceMapDevToolPluginOptions } from '@rspack/binding'; import sources = require('../compiled/webpack-sources'); import { SyncBailHook } from '@rspack/lite-tapable'; import { SyncHook } from '@rspack/lite-tapable'; import { SyncWaterfallHook } from '@rspack/lite-tapable'; +import type { TlsOptions } from 'node:tls'; import type * as webpackDevServer from 'webpack-dev-server'; // @public (undocumented) @@ -3152,13 +3159,17 @@ type KnownStatsProfile = { // @public export type Layer = string | null; +// @public (undocumented) +interface LazyCompilationDefaultBackendOptions { + client?: string; + listen?: number | ListenOptions | ((server: Server) => void); + protocol?: "http" | "https"; + server?: ServerOptions | ServerOptionsHttps | (() => Server); +} + // @public export type LazyCompilationOptions = { - backend?: { - client?: string; - listen?: number | ListenOptions; - protocol?: "http" | "https"; - }; + backend?: LazyCompilationDefaultBackendOptions; imports?: boolean; entries?: boolean; test?: RegExp | ((module: any) => boolean); @@ -3304,18 +3315,6 @@ const LimitChunkCountPlugin: { }; }; -// @public -type ListenOptions = { - port?: number; - host?: string; - backlog?: number; - path?: string; - exclusive?: boolean; - readableAll?: boolean; - writableAll?: boolean; - ipv6Only?: boolean; -}; - // @public (undocumented) export type Loader = Record; @@ -6098,6 +6097,7 @@ export const rspackOptions: z.ZodObject<{ compareBeforeEmit: z.ZodOptional; }, "strict", z.ZodTypeAny, { module?: boolean | undefined; + path?: string | undefined; chunkLoading?: string | false | undefined; asyncChunks?: boolean | undefined; publicPath?: string | ((args_0: PathData, args_1: JsAssetInfo | undefined, ...args: unknown[]) => string) | undefined; @@ -6132,7 +6132,6 @@ export const rspackOptions: z.ZodObject<{ root?: string | undefined; } | undefined; umdNamedDefine?: boolean | undefined; - path?: string | undefined; pathinfo?: boolean | "verbose" | undefined; clean?: boolean | { keep?: string | undefined; @@ -6197,6 +6196,7 @@ export const rspackOptions: z.ZodObject<{ strictModuleExceptionHandling?: boolean | undefined; }, { module?: boolean | undefined; + path?: string | undefined; chunkLoading?: string | false | undefined; asyncChunks?: boolean | undefined; publicPath?: string | ((args_0: PathData, args_1: JsAssetInfo | undefined, ...args: unknown[]) => string) | undefined; @@ -6231,7 +6231,6 @@ export const rspackOptions: z.ZodObject<{ root?: string | undefined; } | undefined; umdNamedDefine?: boolean | undefined; - path?: string | undefined; pathinfo?: boolean | "verbose" | undefined; clean?: boolean | { keep?: string | undefined; @@ -6371,19 +6370,19 @@ export const rspackOptions: z.ZodObject<{ writableAll: z.ZodOptional; ipv6Only: z.ZodOptional; }, "strip", z.ZodTypeAny, { - path?: string | undefined; port?: number | undefined; host?: string | undefined; backlog?: number | undefined; + path?: string | undefined; exclusive?: boolean | undefined; readableAll?: boolean | undefined; writableAll?: boolean | undefined; ipv6Only?: boolean | undefined; }, { - path?: string | undefined; port?: number | undefined; host?: string | undefined; backlog?: number | undefined; + path?: string | undefined; exclusive?: boolean | undefined; readableAll?: boolean | undefined; writableAll?: boolean | undefined; @@ -6393,10 +6392,10 @@ export const rspackOptions: z.ZodObject<{ }, "strip", z.ZodTypeAny, { client?: string | undefined; listen?: number | { - path?: string | undefined; port?: number | undefined; host?: string | undefined; backlog?: number | undefined; + path?: string | undefined; exclusive?: boolean | undefined; readableAll?: boolean | undefined; writableAll?: boolean | undefined; @@ -6406,10 +6405,10 @@ export const rspackOptions: z.ZodObject<{ }, { client?: string | undefined; listen?: number | { - path?: string | undefined; port?: number | undefined; host?: string | undefined; backlog?: number | undefined; + path?: string | undefined; exclusive?: boolean | undefined; readableAll?: boolean | undefined; writableAll?: boolean | undefined; @@ -6427,10 +6426,10 @@ export const rspackOptions: z.ZodObject<{ backend?: { client?: string | undefined; listen?: number | { - path?: string | undefined; port?: number | undefined; host?: string | undefined; backlog?: number | undefined; + path?: string | undefined; exclusive?: boolean | undefined; readableAll?: boolean | undefined; writableAll?: boolean | undefined; @@ -6445,10 +6444,10 @@ export const rspackOptions: z.ZodObject<{ backend?: { client?: string | undefined; listen?: number | { - path?: string | undefined; port?: number | undefined; host?: string | undefined; backlog?: number | undefined; + path?: string | undefined; exclusive?: boolean | undefined; readableAll?: boolean | undefined; writableAll?: boolean | undefined; @@ -6564,10 +6563,10 @@ export const rspackOptions: z.ZodObject<{ backend?: { client?: string | undefined; listen?: number | { - path?: string | undefined; port?: number | undefined; host?: string | undefined; backlog?: number | undefined; + path?: string | undefined; exclusive?: boolean | undefined; readableAll?: boolean | undefined; writableAll?: boolean | undefined; @@ -6630,10 +6629,10 @@ export const rspackOptions: z.ZodObject<{ backend?: { client?: string | undefined; listen?: number | { - path?: string | undefined; port?: number | undefined; host?: string | undefined; backlog?: number | undefined; + path?: string | undefined; exclusive?: boolean | undefined; readableAll?: boolean | undefined; writableAll?: boolean | undefined; @@ -8575,10 +8574,10 @@ export const rspackOptions: z.ZodObject<{ backend?: { client?: string | undefined; listen?: number | { - path?: string | undefined; port?: number | undefined; host?: string | undefined; backlog?: number | undefined; + path?: string | undefined; exclusive?: boolean | undefined; readableAll?: boolean | undefined; writableAll?: boolean | undefined; @@ -8787,6 +8786,7 @@ export const rspackOptions: z.ZodObject<{ }>>) | undefined; output?: { module?: boolean | undefined; + path?: string | undefined; chunkLoading?: string | false | undefined; asyncChunks?: boolean | undefined; publicPath?: string | ((args_0: PathData, args_1: JsAssetInfo | undefined, ...args: unknown[]) => string) | undefined; @@ -8821,7 +8821,6 @@ export const rspackOptions: z.ZodObject<{ root?: string | undefined; } | undefined; umdNamedDefine?: boolean | undefined; - path?: string | undefined; pathinfo?: boolean | "verbose" | undefined; clean?: boolean | { keep?: string | undefined; @@ -9179,10 +9178,10 @@ export const rspackOptions: z.ZodObject<{ backend?: { client?: string | undefined; listen?: number | { - path?: string | undefined; port?: number | undefined; host?: string | undefined; backlog?: number | undefined; + path?: string | undefined; exclusive?: boolean | undefined; readableAll?: boolean | undefined; writableAll?: boolean | undefined; @@ -9391,6 +9390,7 @@ export const rspackOptions: z.ZodObject<{ }>>) | undefined; output?: { module?: boolean | undefined; + path?: string | undefined; chunkLoading?: string | false | undefined; asyncChunks?: boolean | undefined; publicPath?: string | ((args_0: PathData, args_1: JsAssetInfo | undefined, ...args: unknown[]) => string) | undefined; @@ -9425,7 +9425,6 @@ export const rspackOptions: z.ZodObject<{ root?: string | undefined; } | undefined; umdNamedDefine?: boolean | undefined; - path?: string | undefined; pathinfo?: boolean | "verbose" | undefined; clean?: boolean | { keep?: string | undefined; @@ -9920,6 +9919,9 @@ type SafeParseSuccess = { // @public (undocumented) export type ScriptType = false | "text/javascript" | "module"; +// @public (undocumented) +type ServerOptionsHttps = SecureContextOptions & TlsOptions & ServerOptions; + // @public (undocumented) export type Shared = (SharedItem | SharedObject)[] | SharedObject; diff --git a/packages/rspack/package.json b/packages/rspack/package.json index 681d794ff1a..7730bd56be7 100644 --- a/packages/rspack/package.json +++ b/packages/rspack/package.json @@ -68,21 +68,25 @@ "webpack-dev-server": "5.0.4", "webpack-sources": "3.2.3", "zod": "^3.23.8", - "zod-validation-error": "3.4.0" + "zod-validation-error": "3.4.0", + "@rspack/tracing": "workspace:*" }, "dependencies": { "@module-federation/runtime-tools": "0.8.4", "@rspack/binding": "workspace:*", - "@rspack/tracing": "workspace:*", "@rspack/lite-tapable": "1.0.1", "caniuse-lite": "^1.0.30001616" }, "peerDependencies": { - "@swc/helpers": ">=0.5.1" + "@swc/helpers": ">=0.5.1", + "@rspack/tracing": "^1.x" }, "peerDependenciesMeta": { "@swc/helpers": { "optional": true + }, + "@rspack/tracing": { + "optional": true } } } \ No newline at end of file diff --git a/packages/rspack/src/builtin-plugin/lazy-compilation/backend.ts b/packages/rspack/src/builtin-plugin/lazy-compilation/backend.ts index 9171136a3a7..1d2ac7545cb 100644 --- a/packages/rspack/src/builtin-plugin/lazy-compilation/backend.ts +++ b/packages/rspack/src/builtin-plugin/lazy-compilation/backend.ts @@ -15,7 +15,7 @@ import type { Compiler } from "../.."; export interface LazyCompilationDefaultBackendOptions { /** - * A custom client. + * A custom client script path. */ client?: string; diff --git a/packages/rspack/src/config/types.ts b/packages/rspack/src/config/types.ts index 3c928c65e00..750db3118c8 100644 --- a/packages/rspack/src/config/types.ts +++ b/packages/rspack/src/config/types.ts @@ -3,6 +3,7 @@ import type * as webpackDevServer from "webpack-dev-server"; import type { Compilation, PathData } from "../Compilation"; import type { Compiler } from "../Compiler"; import type { Module } from "../Module"; +import type { LazyCompilationDefaultBackendOptions } from "../builtin-plugin/lazy-compilation/backend"; import type { Chunk } from "../exports"; export type FilenameTemplate = string; @@ -2414,44 +2415,6 @@ export type RspackFutureOptions = { }; }; -/** - * Options for server listening. - */ -type ListenOptions = { - /** - * The port to listen on. - */ - port?: number; - /** - * The host to listen on. - */ - host?: string; - /** - * The backlog of connections. - */ - backlog?: number; - /** - * The path for Unix socket. - */ - path?: string; - /** - * Whether the server is exclusive. - */ - exclusive?: boolean; - /** - * Whether the socket is readable by all users. - */ - readableAll?: boolean; - /** - * Whether the socket is writable by all users. - */ - writableAll?: boolean; - /** - * Whether to use IPv6 only. - */ - ipv6Only?: boolean; -}; - /** * Options for lazy compilation. */ @@ -2459,20 +2422,7 @@ export type LazyCompilationOptions = { /** * Backend configuration for lazy compilation. */ - backend?: { - /** - * Client script path. - */ - client?: string; - /** - * Listening options. - */ - listen?: number | ListenOptions; - /** - * Protocol to use. - */ - protocol?: "http" | "https"; - }; + backend?: LazyCompilationDefaultBackendOptions; /** * Enable lazy compilation for imports. */ @@ -2577,19 +2527,23 @@ export type Experiments = { cache?: ExperimentCacheOptions; /** * Enable lazy compilation. + * @default false */ lazyCompilation?: boolean | LazyCompilationOptions; /** * Enable async WebAssembly. * Support the new WebAssembly according to the [updated specification](https://github.com/WebAssembly/esm-integration), it makes a WebAssembly module an async module. + * @default false */ asyncWebAssembly?: boolean; /** * Enable output as ES module. + * @default false */ outputModule?: boolean; /** * Enable top-level await. + * @default true */ topLevelAwait?: boolean; /** @@ -2616,6 +2570,7 @@ export type Experiments = { incremental?: boolean | Incremental; /** * Enable future default options. + * @default false */ futureDefaults?: boolean; /** diff --git a/packages/rspack/src/exports.ts b/packages/rspack/src/exports.ts index 4bb28e71af0..9ca4bbacab4 100644 --- a/packages/rspack/src/exports.ts +++ b/packages/rspack/src/exports.ts @@ -308,14 +308,25 @@ export const experiments: Experiments = { async register(filter, layer, output) { registerGlobalTrace(filter, layer, output); if (layer === "otel") { - const { initOpenTelemetry } = await import("@rspack/tracing"); - await initOpenTelemetry(); + try { + const { initOpenTelemetry } = await import("@rspack/tracing"); + await initOpenTelemetry(); + } catch (error) { + console.error( + "Failed to import `@rspack/tracing` package. Please install `@rspack/tracing` to enable OpenTelemetry tracing.", + error + ); + } } }, async cleanup() { cleanupGlobalTrace(); - const { shutdownOpenTelemetry } = await import("@rspack/tracing"); - await shutdownOpenTelemetry(); + try { + const { shutdownOpenTelemetry } = await import("@rspack/tracing"); + await shutdownOpenTelemetry(); + } catch (error) { + // ignore cleanup tracing error + } } }, RemoveDuplicateModulesPlugin diff --git a/packages/rspack/src/loader-runner/index.ts b/packages/rspack/src/loader-runner/index.ts index fb2d5e56915..2eadbeb93c7 100644 --- a/packages/rspack/src/loader-runner/index.ts +++ b/packages/rspack/src/loader-runner/index.ts @@ -328,20 +328,29 @@ function getCurrentLoader( return null; } +async function tryTrace(context: JsLoaderContext) { + try { + const { + trace, + propagation, + context: tracingContext + } = await import("@rspack/tracing"); + const tracer = trace.getTracer("rspack-loader-runner"); + const activeContext = propagation.extract( + tracingContext.active(), + context.__internal__tracingCarrier + ); + return { tracer, activeContext }; + } catch (error) { + return { tracer: null, activeContext: null }; + } +} + export async function runLoaders( compiler: Compiler, context: JsLoaderContext ): Promise { - const { - trace, - propagation, - context: tracingContext - } = await import("@rspack/tracing"); - const tracer = trace.getTracer("rspack-loader-runner"); - const activeContext = propagation.extract( - tracingContext.active(), - context.__internal__tracingCarrier - ); + const { tracer, activeContext } = await tryTrace(context); const loaderState = context.loaderState; @@ -810,7 +819,7 @@ export async function runLoaders( currentLoaderObject.pitchExecuted = true; if (!fn) continue; - const span = tracer.startSpan( + const span = tracer?.startSpan( "LoaderRunner:pitch", { attributes: { @@ -825,7 +834,7 @@ export async function runLoaders( loaderContext.previousRequest, currentLoaderObject.data ])) || []; - span.end(); + span?.end(); const hasArg = args.some(value => value !== undefined); @@ -862,7 +871,7 @@ export async function runLoaders( const args = [content, sourceMap, additionalData]; convertArgs(args, !!currentLoaderObject.raw); - const span = tracer.startSpan( + const span = tracer?.startSpan( "LoaderRunner:normal", { attributes: { @@ -873,7 +882,7 @@ export async function runLoaders( ); [content, sourceMap, additionalData] = (await runSyncOrAsync(fn, loaderContext, args)) || []; - span.end(); + span?.end(); } context.content = isNil(content) ? null : toBuffer(content); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 29776c529c1..df53b78d408 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -300,9 +300,6 @@ importers: '@rspack/lite-tapable': specifier: 1.0.1 version: 1.0.1 - '@rspack/tracing': - specifier: workspace:* - version: link:../rspack-tracing '@swc/helpers': specifier: '>=0.5.1' version: 0.5.13 @@ -310,6 +307,9 @@ importers: specifier: ^1.0.30001616 version: 1.0.30001676 devDependencies: + '@rspack/tracing': + specifier: workspace:* + version: link:../rspack-tracing '@swc/core': specifier: 1.10.1 version: 1.10.1(@swc/helpers@0.5.13) @@ -379,9 +379,6 @@ importers: '@rspack/dev-server': specifier: 1.0.10 version: 1.0.10(@rspack/core@packages+rspack)(@types/express@4.17.21)(webpack-cli@5.1.4(webpack@5.95.0))(webpack@5.95.0(@swc/core@1.10.1(@swc/helpers@0.5.15))(webpack-cli@5.1.4(webpack@5.95.0))) - '@rspack/tracing': - specifier: workspace:* - version: link:../rspack-tracing colorette: specifier: 2.0.19 version: 2.0.19 @@ -407,6 +404,9 @@ importers: '@rspack/core': specifier: workspace:* version: link:../rspack + '@rspack/tracing': + specifier: workspace:* + version: link:../rspack-tracing '@types/interpret': specifier: ^1.1.3 version: 1.1.3 diff --git a/website/docs/en/config/experiments.mdx b/website/docs/en/config/experiments.mdx index 68fbae077ba..966cf3a2631 100644 --- a/website/docs/en/config/experiments.mdx +++ b/website/docs/en/config/experiments.mdx @@ -72,6 +72,9 @@ module.exports = { ## experiments.futureDefaults +- **Type:** `boolean` +- **Default:** `false` + Use defaults of the next major Rspack and show warnings in any problematic places. ```js title="rspack.config.js" @@ -84,6 +87,9 @@ module.exports = { ## experiments.topLevelAwait +- **Type:** `boolean` +- **Default:** `true` + Enable support for [Top-level await](https://github.com/tc39/proposal-top-level-await), `Top-level await` can only be used in modules with [ModuleType](/config/module#ruletype) is `javascript/esm`. Enabled by default and can be disabled with this configuration: @@ -107,17 +113,24 @@ type LazyCompilationOptions = | { backend?: { /** - * A custom client. + * A custom client script path. */ client?: string; /** - * Specify where to listen to from the server. + * Specifies where to listen to from the server. */ - listen?: number | ListenOptions; + listen?: number | ListenOptions | ((server: Server) => void); /** - * Specify the protocol the client should use to connect to the server. + * Specifies the protocol the client should use to connect to the server. */ protocol?: 'http' | 'https'; + /** + * Specifies how to create the server handling the EventSource requests. + */ + server?: + | ServerOptionsImport + | ServerOptionsHttps + | (() => Server); }; /** * Enable lazy compilation for entries. diff --git a/website/docs/zh/config/experiments.mdx b/website/docs/zh/config/experiments.mdx index 12243d8725a..ab692fed3f5 100644 --- a/website/docs/zh/config/experiments.mdx +++ b/website/docs/zh/config/experiments.mdx @@ -72,6 +72,9 @@ module.exports = { ## experiments.futureDefaults +- **类型:** `boolean` +- **默认值:** `false` + 使用下一个主版本 Rspack 的默认值,并在任何有问题的地方显示警告。 ```js title="rspack.config.js" @@ -84,6 +87,9 @@ module.exports = { ## experiments.topLevelAwait +- **类型:** `boolean` +- **默认值:** `true` + 开启打包 [Top-level await](https://github.com/tc39/proposal-top-level-await) 的支持,`Top-level await` 仅能在 [ModuleType](/config/module#ruletype) 为 `javascript/esm` 的模块中使用。 默认开启,可通过该配置关闭: @@ -107,17 +113,24 @@ type LazyCompilationOptions = | { backend?: { /** - * A custom client. + * 自定义客户端脚本路径。 */ client?: string; /** - * Specify where to listen to from the server. + * 指定从服务器监听的端口或选项。 */ - listen?: number | ListenOptions; + listen?: number | ListenOptions | ((server: Server) => void); /** - * Specify the protocol the client should use to connect to the server. + * 指定客户端使用的协议。 */ protocol?: 'http' | 'https'; + /** + * 指定如何创建处理 EventSource 请求的服务器。 + */ + server?: + | ServerOptionsImport + | ServerOptionsHttps + | (() => Server); }; /** * 为 entries 启用 lazy compilation