Skip to content

Commit

Permalink
fix: memory leak (#174)
Browse files Browse the repository at this point in the history
  • Loading branch information
evilebottnawi authored Aug 12, 2020
1 parent 025b778 commit 2a1e884
Showing 1 changed file with 28 additions and 26 deletions.
54 changes: 28 additions & 26 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,24 +71,22 @@ class CompressionPlugin {
...this.compressionOptions,
};
}

this.emittedAssets = new Set();
}

*taskGenerator(compiler, compilation, assetName) {
*taskGenerator(compiler, compilation, assetsCache, assetName) {
const assetSource = compilation.assets[assetName];

// Do not emit cached assets in watch mode
if (this.emittedAssets.has(assetSource)) {
yield false;
}

let input = assetSource.source();

if (!Buffer.isBuffer(input)) {
input = Buffer.from(input);
}

// Do not emit cached assets in watch mode
if (assetsCache.get(assetSource)) {
yield false;
}

const originalSize = input.length;

if (originalSize < this.options.threshold) {
Expand Down Expand Up @@ -128,10 +126,12 @@ class CompressionPlugin {
(p0, p1) => info[p1]
);

const compressedSource = new RawSource(output);

// eslint-disable-next-line no-param-reassign
compilation.assets[newAssetName] = new RawSource(output);
compilation.assets[newAssetName] = compressedSource;

this.emittedAssets.add(assetSource);
assetsCache.set(assetSource, compressedSource);

if (this.options.deleteOriginalAssets) {
// eslint-disable-next-line no-param-reassign
Expand Down Expand Up @@ -192,10 +192,7 @@ class CompressionPlugin {
}

if (cache.isEnabled() && !taskResult.error) {
taskResult = await cache.store(task, taskResult).then(
() => taskResult,
() => taskResult
);
await cache.store(task, taskResult);
}

task.callback(taskResult);
Expand All @@ -204,26 +201,29 @@ class CompressionPlugin {
};

scheduledTasks.push(
new Promise((resolve) => {
(async () => {
const task = getTaskForAsset(assetName).next().value;

if (!task) {
return resolve();
return Promise.resolve();
}

if (cache.isEnabled()) {
return cache.get(task).then(
(taskResult) => {
task.callback(taskResult);
let taskResult;

return resolve(taskResult);
},
() => resolve(enqueue(task))
);
try {
taskResult = await cache.get(task);
} catch (ignoreError) {
return enqueue(task);
}

task.callback(taskResult);

return Promise.resolve();
}

return resolve(enqueue(task));
})
return enqueue(task);
})()
);
}

Expand All @@ -240,6 +240,7 @@ class CompressionPlugin {
undefined,
this.options
);
const assetsCache = new WeakMap();

compiler.hooks.emit.tapPromise(
{ name: 'CompressionPlugin' },
Expand All @@ -257,7 +258,8 @@ class CompressionPlugin {
const getTaskForAsset = this.taskGenerator.bind(
this,
compiler,
compilation
compilation,
assetsCache
);
const CacheEngine = CompressionPlugin.isWebpack4()
? // eslint-disable-next-line global-require
Expand Down

0 comments on commit 2a1e884

Please sign in to comment.