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