Skip to content
This repository has been archived by the owner on Jun 15, 2023. It is now read-only.

Commit

Permalink
Try new worker implementation. Disable workers for now.
Browse files Browse the repository at this point in the history
  • Loading branch information
paulmillr committed Dec 7, 2019
1 parent b39a05a commit 2b29ee1
Show file tree
Hide file tree
Showing 6 changed files with 167 additions and 30 deletions.
6 changes: 3 additions & 3 deletions lib/fs_utils/asset.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
const debug = require('debug')('brunch:asset');
const sysPath = require('universal-path');
const readFromCache = require('fcache').readFile;
const {processAsset} = require('./pipeline');
const {processFile} = require('./pipeline');
const BrunchError = require('../utils/error');
const isIgnored = require('./is_ignored');

Expand Down Expand Up @@ -62,13 +62,13 @@ class Asset {
asset._rawSource = data;

try {
const file = await processAsset({
const file = await processFile({
path,
get data() {
asset._wasProcessed = true;
return `${data}`;
}
});
}, true);
this._updateCache(file);
} catch (error) {
this.error = error;
Expand Down
29 changes: 18 additions & 11 deletions lib/fs_utils/pipeline.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@ const extRe = /(\.\w+)+$/;
let plugins = [];
let npmCompilers = [];
function respondTo(key) {
return plugins.filter(plugin => {
return typeof plugin[key] === 'function';
});
return plugins.filter(p => typeof p[key] === 'function');
}

function setPlugins(_plugins, _npmCompilers) {
Expand Down Expand Up @@ -70,8 +68,9 @@ async function getDependencies(file, compiler) {

debug(`Fetching dependencies ${file.path} @ ${compiler.brunchPluginName}`);
try {
const deps = compiler.getDependencies(file);
return deps.concat(deps.patterns || []).map(sysPath.normalize);
let deps = compiler.getDependencies(file);
if (!Array.isArray(deps) && deps instanceof Promise) deps = await deps;
return deps.concat(deps.patterns || []).map(d => sysPath.normalize(d));
} catch (error) {
rethrow('Dependency parsing')(error);
}
Expand Down Expand Up @@ -122,12 +121,12 @@ async function nextCompiler(file, compilers, isStatic) {
return nextCompiler(newFile, compilers, isStatic);
}

async function processAsset(file) {
const compilers = respondTo('compileStatic').filter(comp => comp.type === 'template');
return nextCompiler(file, compilers, true);
}
async function processFile(file, isStatic = false) {
if (isStatic) {
const compilers = respondTo('compileStatic').filter(comp => comp.type === 'template');
return nextCompiler(file, compilers, true);
}

async function processFile(file) {
await lint(file);

const {path} = file;
Expand All @@ -144,4 +143,12 @@ async function processFile(file) {
return processed;
}

module.exports = {processAsset, processFile, setPlugins};
// function processFileParallel(file, isStatic) {
// const WorkerPool = require('../workers/pool');
// if (WorkerPool.instance) {
// return WorkerPool.instance.schedule([file, isStatic]);
// }
// return processFile(file, isStatic);
// }

module.exports = {processFile, setPlugins};
12 changes: 10 additions & 2 deletions lib/utils/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const logger = require('loggy');
const {deepAssign, fsExists, asyncFilter, isSymlink} = require('./helpers');
const deppack = require('deppack'); // isNpm, loadInit
const wrappers = require('./modules');
const loadPlugins = require('./plugins');
const validateConfig = require('./config-validate');
const BrunchError = require('./error');
const DEFAULT_CONFIG_FILENAME = 'brunch-config';
Expand Down Expand Up @@ -413,7 +414,7 @@ async function tryToLoad(root, configPath, pkg) {
return fsExists(sysPath.join(root, file));
}).then(list => {
if (list.length) {
logger.warn('brunch-config with coffeescript is no longer supported. Compile it to JS: \n\nnpm install --global coffeescript\ncoffee --bare --compile brunch-config.coffee');
logger.error('brunch-config with coffeescript is no longer supported. Compile it to JS: \n\nnpm install --global coffeescript\ncoffee --bare --compile brunch-config.coffee');
}
});
}
Expand Down Expand Up @@ -473,11 +474,18 @@ async function loadConfig(options) {
trimTrailingSlashes(config);
normalizeConfig(config);
await checkProjectDependencies(config);
if (!fromWorker) await addPackageManagers(config);
if (true) await addPackageManagers(config);

// DOES NOT WORK right now!
// deepFreeze(config, ['static', 'overrides']);
return config;
}

async function loadConfigAndPlugins(options) {
const cfg = await loadConfig(options);
const plg = await loadPlugins(cfg, options.dependencies);
return [cfg, plg];
}

exports.loadConfig = loadConfig;
exports.loadConfigAndPlugins = loadConfigAndPlugins;
3 changes: 1 addition & 2 deletions lib/utils/plugins.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
const debug = require('debug')('brunch:plugins');
const logger = require('loggy');
const profile = require('since-app-start').profile;
const flatten = require('./helpers').flatten;
const deepFreeze = require('./helpers').deepFreeze;
const {flatten, deepFreeze} = require('./helpers');
const BrunchError = require('./error');
const adapter = require('./plugin-adapter');
const sysPath = require('universal-path');
Expand Down
30 changes: 18 additions & 12 deletions lib/watch.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,18 @@ const ignored = require('./fs_utils/is_ignored');
const FileList = require('./fs_utils/file_list');
const pipeline = require('./fs_utils/pipeline');

const application = require('./utils/config'); // loadConfig, install
const plugins = require('./utils/plugins');
const application = require('./utils/config'); // loadConfigAndPlugins, install
const helpers = require('./utils/helpers'); // asyncFilter, flatten, generateCompilationLog, getCompilationProgress

async function loadConfigAndPaths(options) {
const promises = await application.loadConfigAndPlugins(options);
const cfg = promises[0];
// if !fromWorker
promises.push(getWatchedPaths(cfg._normalized));
if (cfg.server.run) promises.push(serve(cfg.server));
return Promise.all(promises);
}

const promisifyHook = plugin => {
const hook = plugin.preCompile;
if (!hook.length) return;
Expand Down Expand Up @@ -81,20 +89,18 @@ class BrunchWatcher {
process.exit(currentCode);
});
}


try {
const cfg = await application.loadConfig(options);
this.config = cfg;
const promises = [getWatchedPaths(cfg._normalized), plugins(cfg, options.dependencies)];
if (cfg.server.run) promises.push(serve(cfg.server));
const res = await Promise.all(promises);
const [cfg, {plugins, hooks}, watchedPaths, server] = await loadConfigAndPaths(options);

const [watchedPaths, pluginArgs, server] = res;
const {hooks} = pluginArgs;
this.server = server;
pipeline.setPlugins(plugins, cfg.npm.compilers);
if (options.onCompile) hooks.onCompile.push({onCompile: options.onCompile});
this.config = cfg;
this.hooks = mergeHooks(hooks, cfg.hooks);
this.plugins = pluginArgs.plugins;
pipeline.setPlugins(pluginArgs.plugins, cfg.npm.compilers);
this.plugins = plugins;
if (server) this.server = server;

await Promise.all(this.hooks.preCompile());
this.initWatcher(watchedPaths);
this.initCompilation();
Expand Down
117 changes: 117 additions & 0 deletions lib/workers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// const sysPath = require('path');
// const {EventEmitter} = require('events');
// let threads;
// try {
// threads = require('worker_threads');
// } finally {}
// exports.enabled = true;

// // 1. no workers
// // main => processFile(file) =>
// // 2. workers
// // main => processFile(file) =>
// // pool.determineWorker(file) =>
// // worker.postMessage(file) =>
// // parentPort.postMessage(processed)
// // TODO:
// // this.workers = await WorkerPool.create(application.stripOpts(options));
// class WorkerPool extends EventEmitter {
// // static instance;
// /**
// * @returns {Promise}
// */
// static schedule(args) {
// if (!WorkerPool.instance) {
// throw new Error('No worker pool');
// }
// return WorkerPool.instance.schedule(args);
// }

// static create(options) {
// return new Promise(resolve => {
// const pool = new WorkerPool(options);
// pool.once('ready', () => {
// resolve(pool);
// });
// })
// }

// constructor(options) {
// super();

// WorkerPool.instance = this;

// if (!threads) {
// throw new Error('Workers are not supported');
// }
// const { Worker } = threads;

// const data = {workerData: {options}};

// this.counter = 0;
// this.workers = [];
// const count = 6 || require('os').cpus().length;
// this.workersToInit = count - 1;

// const file = sysPath.join(__dirname, 'listen.js');
// for (let i = 0; i < count - 1; i++) {
// this.workers.push(new Worker(file, data));
// }
// for (let worker of this.workers) {
// worker.on('message', msg => this.handleWorkerMessage(msg));
// worker.on('error', err => { throw err; });
// worker.on('exit', () => {
// this.workers.splice(this.workers.indexOf(worker), 1);
// });
// }
// }

// handleWorkerMessage(msg) {
// if (msg === 'ready') {
// this.workersToInit--;
// if (this.workersToInit === 0) {
// this.emit('ready');
// }
// return;
// }
// this.emit(msg.id, msg.result);
// }

// schedule(args) {
// const counter = this.counter++;
// const worker = this.workers[counter % this.workers.length];
// const id = counter.toString();
// worker.postMessage({type: 'compile', id, args});
// return new Promise(resolve => {
// this.once(id, resolve);
// });
// }

// async dispose() {
// await Promise.all(this.workers.map(t => t.terminate()));
// }
// }
// WorkerPool.instance = undefined;

// if (threads && !threads.isMainThread) {
// async function initWorker() {
// const {isMainThread, parentPort, workerData} = require('worker_threads');
// const application = require('../utils/config');
// const pipeline = require('../fs_utils/pipeline');
// const {options} = workerData;
// options.fromWorker = true;
// const [cfg, {plugins}] = await application.loadConfigAndPlugins(options);
// pipeline.setPlugins(plugins, cfg.npm.compilers);

// parentPort.on('message', async ({type, id, args}) => {
// if (type === 'compile') {
// const result = await pipeline.processFile(args[0], args[1]);
// parentPort.postMessage({type, id, result});
// }
// });
// parentPort.postMessage('ready');
// }
// initWorker();
// }

// module.exports = WorkerPool;

0 comments on commit 2b29ee1

Please sign in to comment.