egg_loader_trace.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict';
  2. const path = require('path');
  3. const fs = require('mz/fs');
  4. const utility = require('utility');
  5. module.exports = (_, app) => {
  6. return async (ctx, next) => {
  7. if (ctx.path !== '/__loader_trace__') return await next();
  8. const template = await fs.readFile(path.join(__dirname, '../../lib/loader_trace.html'), 'utf8');
  9. const data = await loadTimingData(app);
  10. ctx.body = template.replace('{{placeholder}}', JSON.stringify(data));
  11. };
  12. };
  13. async function loadTimingData(app) {
  14. const rundir = app.config.rundir;
  15. const files = await fs.readdir(rundir);
  16. const data = [];
  17. for (const file of files) {
  18. if (!/^(agent|application)_timing/.test(file)) continue;
  19. const json = await utility.readJSON(path.join(rundir, file));
  20. const isAgent = /^agent/.test(file);
  21. for (const item of json) {
  22. if (isAgent) {
  23. item.type = 'agent';
  24. } else {
  25. item.type = `app_${item.pid}`;
  26. }
  27. item.pid = String(item.pid);
  28. item.range = [ item.start, item.end ];
  29. item.title = `${item.type}(${item.index})`;
  30. data.push(item);
  31. }
  32. }
  33. return data;
  34. }