Intellectual Webpack cache management (#5295) * Intellectual Webpack cache management * Check if webpackRoot exists. * Wrap webpack directory reading in try-catch * Enhance cache pruning console output

645b8063e1e2c623852f8bda4c05cb546e9a870d

Cohee <18619528+Cohee1207@users.noreply.github.com>

Signed
3 files changed, +71 -19Showing whitespace changes
src/middleware/webpack-serve.js+7 -5
@@ -26,16 +26,18 @@ export default function getWebpackServeMiddleware() {
26 /**26 /**
27 * Wait until Webpack is done compiling.27 * Wait until Webpack is done compiling.
28 * @param {object} param Parameters.28 * @param {object} param Parameters.
29 * @param {boolean} [param.forceDist] Whether to force the use the /dist folder.29 * @param {boolean} [param.forceDist=false] Whether to force the use the /dist folder.
30 * @param {boolean} [param.pruneCache=false] Whether to prune old cache directories before compiling.
30 * @returns {Promise<void>}31 * @returns {Promise<void>}
31 */32 */
32 devMiddleware.runWebpackCompiler = ({ forceDist = false } = {}) => {33 devMiddleware.runWebpackCompiler = ({ forceDist = false, pruneCache = false } = {}) => {
33 const publicLibConfig = getPublicLibConfig(forceDist);34 console.log();
35 console.log('Compiling frontend libraries...');
36
37 const publicLibConfig = getPublicLibConfig({ forceDist, pruneCache });
34 const compiler = webpack(publicLibConfig);38 const compiler = webpack(publicLibConfig);
3539
36 return new Promise((resolve) => {40 return new Promise((resolve) => {
37 console.log();
38 console.log('Compiling frontend libraries...');
39 compiler.run((_error, stats) => {41 compiler.run((_error, stats) => {
40 const output = stats?.toString(publicLibConfig.stats);42 const output = stats?.toString(publicLibConfig.stats);
41 if (output) {43 if (output) {
src/server-main.js+1 -1
@@ -328,7 +328,7 @@ async function preSetupTasks() {
328 initRequestProxy({ enabled: cliArgs.requestProxyEnabled, url: cliArgs.requestProxyUrl, bypass: cliArgs.requestProxyBypass });328 initRequestProxy({ enabled: cliArgs.requestProxyEnabled, url: cliArgs.requestProxyUrl, bypass: cliArgs.requestProxyBypass });
329329
330 // Wait for frontend libs to compile330 // Wait for frontend libs to compile
331 await webpackMiddleware.runWebpackCompiler();331 await webpackMiddleware.runWebpackCompiler({ pruneCache: true });
332}332}
333333
334/**334/**
webpack.config.js+63 -13
@@ -1,45 +1,95 @@
1import process from 'node:process';1import process from 'node:process';
2import path from 'node:path';2import path from 'node:path';
3import fs from 'node:fs';
4import crypto from 'node:crypto';
3import isDocker from 'is-docker';5import isDocker from 'is-docker';
4import webpack from 'webpack';6import webpack from 'webpack';
5import { serverDirectory } from './src/server-directory.js';7import { serverDirectory } from './src/server-directory.js';
8import { getVersion, color } from './src/util.js';
9
10/**
11 * Generate a cache version string based on the application version, Git revision, and Webpack version.
12 * @returns {string} The cache version string.
13 */
14function getWebpackCacheVersion() {
15 return crypto.createHash('shake256', { outputLength: 8 })
16 .update(JSON.stringify([appVersion.pkgVersion, appVersion.gitRevision, webpack.version]))
17 .digest('hex');
18}
19
20/**
21 * Prune old Webpack cache directories that do not match the current cache version.
22 * @param {string} webpackRoot The root directory where Webpack caches are stored.
23 * @param {string} currentCacheVersion The current cache version to keep.
24 */
25function pruneWebpackCache(webpackRoot, currentCacheVersion) {
26 try {
27 if (!fs.existsSync(webpackRoot)) {
28 return;
29 }
30
31 const cacheDirectories = fs.readdirSync(webpackRoot, { withFileTypes: true })
32 .filter(dirent => dirent.isDirectory())
33 .map(dirent => dirent.name);
34
35 for (const dir of cacheDirectories) {
36 const dirPath = path.join(webpackRoot, dir);
37 if (dir !== currentCacheVersion) {
38 try {
39 fs.rmSync(dirPath, { recursive: true, force: true });
40 console.debug(`Removed outdated cache directory: ${color.yellow(dir)}`);
41 } catch (error) {
42 console.error(`Failed to remove Webpack cache directory: ${color.red(dir)}`, error);
43 }
44 }
45 }
46 } catch (error) {
47 console.error('Failed to read Webpack cache directories for pruning.', error);
48 }
49}
50
51const appVersion = await getVersion();
652
7/**53/**
8 * Get the Webpack configuration for the public/lib.js file.54 * Get the Webpack configuration for the public/lib.js file.
9 * 1. Docker has got cache and the output file pre-baked.55 * 1. Docker has got cache and the output file pre-baked.
10 * 2. Non-Docker environments use the global DATA_ROOT variable to determine the cache and output directories.56 * 2. Non-Docker environments use the global DATA_ROOT variable to determine the cache and output directories.
11 * @param {boolean} forceDist Whether to force the use the /dist folder.57 * @param {object} options Configuration options.
58 * @param {boolean} [options.forceDist=false] Whether to force the use the /dist folder.
59 * @param {boolean} [options.pruneCache=false] Whether to prune old cache directories.
12 * @returns {import('webpack').Configuration}60 * @returns {import('webpack').Configuration}
13 * @throws {Error} If the DATA_ROOT variable is not set.61 * @throws {Error} If the DATA_ROOT variable is not set.
14 * */62 * */
15export default function getPublicLibConfig(forceDist = false) {63export default function getPublicLibConfig({ forceDist = false, pruneCache = false } = {}) {
16 function getCacheDirectory() {64 function getWebpackRoot() {
17 if (forceDist || isDocker()) {65 if (forceDist || isDocker()) {
18 return path.resolve(process.cwd(), 'dist', '_webpack', webpack.version, 'cache');66 return path.resolve(process.cwd(), 'dist', '_webpack');
19 }67 }
2068
21 if (typeof globalThis.DATA_ROOT === 'string') {69 if (typeof globalThis.DATA_ROOT === 'string') {
22 return path.resolve(globalThis.DATA_ROOT, '_webpack', webpack.version, 'cache');70 return path.resolve(globalThis.DATA_ROOT, '_webpack');
23 }71 }
2472
25 throw new Error('DATA_ROOT variable is not set.');73 throw new Error('DATA_ROOT variable is not set.');
26 }74 }
2775
28 function getOutputDirectory() {76 function getCacheDirectory() {
29 if (forceDist || isDocker()) {77 return path.join(webpackRoot, cacheVersion, 'cache');
30 return path.resolve(process.cwd(), 'dist', '_webpack', webpack.version, 'output');
31 }
32
33 if (typeof globalThis.DATA_ROOT === 'string') {
34 return path.resolve(globalThis.DATA_ROOT, '_webpack', webpack.version, 'output');
35 }78 }
3679
37 throw new Error('DATA_ROOT variable is not set.');80 function getOutputDirectory() {
81 return path.join(webpackRoot, cacheVersion, 'output');
38 }82 }
3983
84 const webpackRoot = getWebpackRoot();
85 const cacheVersion = getWebpackCacheVersion();
40 const cacheDirectory = getCacheDirectory();86 const cacheDirectory = getCacheDirectory();
41 const outputDirectory = getOutputDirectory();87 const outputDirectory = getOutputDirectory();
4288
89 if (pruneCache) {
90 pruneWebpackCache(webpackRoot, cacheVersion);
91 }
92
43 return {93 return {
44 mode: 'production',94 mode: 'production',
45 entry: path.join(serverDirectory, 'public/lib.js'),95 entry: path.join(serverDirectory, 'public/lib.js'),