agent.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. 'use strict';
  2. const path = require('path');
  3. const debounce = require('debounce');
  4. const multimatch = require('multimatch');
  5. const rimraf = require('mz-modules/rimraf');
  6. const fs = require('mz/fs');
  7. module.exports = agent => {
  8. // clean all timing json
  9. agent.beforeStart(async () => {
  10. const rundir = agent.config.rundir;
  11. const files = await fs.readdir(rundir);
  12. for (const file of files) {
  13. if (!/^(agent|application)_timing/.test(file)) continue;
  14. await rimraf(path.join(agent.config.rundir, file));
  15. }
  16. });
  17. // single process mode don't watch and reload
  18. if (agent.options && agent.options.mode === 'single') return;
  19. const logger = agent.logger;
  20. const baseDir = agent.config.baseDir;
  21. const config = agent.config.development;
  22. let watchDirs = config.overrideDefault ? [] : [
  23. 'app',
  24. 'config',
  25. 'mocks',
  26. 'mocks_proxy',
  27. 'app.js',
  28. ];
  29. watchDirs = watchDirs.concat(config.watchDirs).map(dir => path.resolve(baseDir, dir));
  30. let ignoreReloadFileDirs = config.overrideIgnore ? [] : [
  31. 'app/views',
  32. 'app/view',
  33. 'app/assets',
  34. 'app/public',
  35. 'app/web',
  36. ];
  37. ignoreReloadFileDirs = ignoreReloadFileDirs.concat(config.ignoreDirs).map(dir => path.resolve(baseDir, dir));
  38. const reloadFile = debounce(function(info) {
  39. logger.warn(`[agent:development] reload worker because ${info.path} ${info.event}`);
  40. process.send({
  41. to: 'master',
  42. action: 'reload-worker',
  43. });
  44. }, 200);
  45. // watch dirs to reload worker, will debounce 200ms
  46. agent.watcher.watch(watchDirs, reloadWorker);
  47. /**
  48. * reload app worker:
  49. * [AgentWorker] - on file change
  50. * |-> emit reload-worker
  51. * [Master] - receive reload-worker event
  52. * |-> TODO: Mark worker will die
  53. * |-> Fork new worker
  54. * |-> kill old worker
  55. *
  56. * @param {Object} info - changed fileInfo
  57. */
  58. function reloadWorker(info) {
  59. if (!config.reloadOnDebug) {
  60. return;
  61. }
  62. if (isAssetsDir(info.path) || info.isDirectory) {
  63. return;
  64. }
  65. // don't reload if don't match
  66. if (config.reloadPattern && multimatch(info.path, config.reloadPattern).length === 0) {
  67. return;
  68. }
  69. reloadFile(info);
  70. }
  71. function isAssetsDir(path) {
  72. for (const ignorePath of ignoreReloadFileDirs) {
  73. if (path.startsWith(ignorePath)) {
  74. return true;
  75. }
  76. }
  77. return false;
  78. }
  79. };