Skip to content
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
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,15 @@
"node": ">= 18.12.0"
},
"scripts": {
"start": "npm run build -- -w",
"start": "npm-run-all -p \"watch:**\"",
"clean": "del-cli dist types",
"prebuild": "npm run clean",
"build:types": "tsc --declaration --emitDeclarationOnly && prettier \"types/**/*.ts\" --write",
"build:types": "tsc --declaration --emitDeclarationOnly",
"postbuild:types": "prettier \"types/**/*.ts\" --write",
"build:code": "cross-env NODE_ENV=production babel src -d dist --copy-files",
"build": "npm-run-all -p \"build:**\"",
"watch:types": "npm run build:types -- -w",
"watch:code": "npm run build:code -- -w",
"commitlint": "commitlint --from=master",
"security": "npm audit --production",
"lint:prettier": "prettier --cache --list-different .",
Expand Down
34 changes: 25 additions & 9 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -281,8 +281,18 @@ class ImageMinimizerPlugin {
* @returns {Promise<Task<Z>>}
*/
const getFromCache = async (transformer) => {
const cacheName = getSerializeJavascript()({ name, transformer });
const eTag = cache.getLazyHashedEtag(source);
const cacheName = getSerializeJavascript()({
eTag: eTag.toString(),
transformer: (Array.isArray(transformer)
? transformer
: [transformer]
).map(({ implementation, options }) => ({
implementation,
options,
})),
});

const cacheItem = cache.getItemCache(cacheName, eTag);
const output = await cacheItem.getPromise();

Expand Down Expand Up @@ -338,6 +348,9 @@ class ImageMinimizerPlugin {

const sourceFromInputSource = inputSource.source();

const pluginName = this.constructor.name;
const logger = compilation.getLogger(pluginName);

if (!output) {
input = sourceFromInputSource;

Expand All @@ -356,16 +369,19 @@ class ImageMinimizerPlugin {
generateFilename: compilation.getAssetPath.bind(compilation),
});

output = await worker(minifyOptions);
output = await cacheItem.providePromise(async () => {
logger.debug(`optimize cache miss: ${name}`);

output.source = new RawSource(output.data);
const result = await worker(minifyOptions);

await cacheItem.storePromise({
source: output.source,
info: output.info,
filename: output.filename,
warnings: output.warnings,
errors: output.errors,
return {
data: result.data,
source: new RawSource(result.data),
info: result.info,
filename: result.filename,
warnings: result.warnings,
errors: result.errors,
};
});
}

Expand Down
50 changes: 38 additions & 12 deletions src/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
IMAGE_MINIMIZER_PLUGIN_INFO_MAPPINGS,
ABSOLUTE_URL_REGEX,
WINDOWS_PATH_REGEX,
memoize,
} = require("./utils.js");
const getSerializeJavascript = memoize(() => require("serialize-javascript"));

/** @typedef {import("schema-utils/declarations/validate").Schema} Schema */
/** @typedef {import("webpack").Compilation} Compilation */
Expand Down Expand Up @@ -210,18 +212,42 @@
? this.resourcePath
: path.relative(this.rootContext, this.resourcePath);

const minifyOptions =
/** @type {import("./index").InternalWorkerOptions<T>} */ ({
input: content,
filename,
severityError,
transformer,
generateFilename:
/** @type {Compilation} */
(this._compilation).getAssetPath.bind(this._compilation),
});

const output = await worker(minifyOptions);
if (!this._compilation || !this._compiler) {
callback(new Error("_compilation and/or _compiler unavailable"));
return;

Check warning on line 217 in src/loader.js

View check run for this annotation

Codecov / codecov/patch

src/loader.js#L216-L217

Added lines #L216 - L217 were not covered by tests
}

const logger = this._compilation.getLogger("ImageMinimizerPlugin");
const cache = this._compilation.getCache("ImageMinimizerWebpackPlugin");

const { RawSource } = this._compiler.webpack.sources;
const eTag = cache.getLazyHashedEtag(new RawSource(content));
const cacheName = getSerializeJavascript()({
eTag: eTag.toString(),
transformer: (Array.isArray(transformer) ? transformer : [transformer]).map(
(each) => ({
implementation: each.implementation,
options: each.options,
}),
),
});
const cacheItem = cache.getItemCache(cacheName, eTag);
const output = await cacheItem.providePromise(() => {
const minifyOptions =
/** @type {import("./index").InternalWorkerOptions<T>} */ ({
input: content,
filename,
severityError,
transformer,
generateFilename:
/** @type {Compilation} */
(this._compilation).getAssetPath.bind(this._compilation),
});

logger.debug(`loader cache miss: ${filename}`);

return worker(minifyOptions);
});
Copy link
Member

Choose a reason for hiding this comment

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

We can't do it in loader:

  1. this._compilation.getCache is unavaliable in multi threading mode (thread-loader)
  2. Also this plugin is using by rspack too and such api is not working there

This PR eliminates the race condition where the loader or optimizer may do the same processing (same transformation on the same image) redundantly if the same file transformation's loader is triggered more than once before the first transformation has finished.

Can you provide reproducible example?

Also I think we can use WeakMap in the loader to prevent such situations


if (output.errors && output.errors.length > 0) {
for (const error of output.errors) {
Expand Down
Loading