timeAsyncMethod.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * decaffeinate suggestions:
  3. * DS101: Remove unnecessary use of Array.from
  4. * DS102: Remove unnecessary code created because of implicit returns
  5. * DS201: Simplify complex destructure assignments
  6. * DS207: Consider shorter variations of null checks
  7. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  8. */
  9. module.exports = function(obj, methodName, prefix, logger) {
  10. let modifedMethodName;
  11. const metrics = require('./metrics');
  12. if (typeof obj[methodName] !== 'function') {
  13. throw new Error(`[Metrics] expected object property '${methodName}' to be a function`);
  14. }
  15. const key = `${prefix}.${methodName}`;
  16. const realMethod = obj[methodName];
  17. const splitPrefix = prefix.split(".");
  18. const startPrefix = splitPrefix[0];
  19. if (splitPrefix[1] != null) {
  20. modifedMethodName = `${splitPrefix[1]}_${methodName}`;
  21. } else {
  22. modifedMethodName = methodName;
  23. }
  24. return obj[methodName] = function(...originalArgs) {
  25. const adjustedLength = Math.max(originalArgs.length, 1), firstArgs = originalArgs.slice(0, adjustedLength - 1), callback = originalArgs[adjustedLength - 1];
  26. if ((callback == null) || (typeof callback !== 'function')) {
  27. if (logger != null) {
  28. logger.log(`[Metrics] expected wrapped method '${methodName}' to be invoked with a callback`);
  29. }
  30. return realMethod.apply(this, originalArgs);
  31. }
  32. const timer = new metrics.Timer(startPrefix, 1, {method: modifedMethodName});
  33. return realMethod.call(this, ...Array.from(firstArgs), function(...callbackArgs) {
  34. const elapsedTime = timer.done();
  35. const possibleError = callbackArgs[0];
  36. if (possibleError != null) {
  37. metrics.inc(`${startPrefix}_result`, 1, {status:"failed", method: modifedMethodName});
  38. } else {
  39. metrics.inc(`${startPrefix}_result`, 1, {status:"success", method: modifedMethodName});
  40. }
  41. if (logger != null) {
  42. const loggableArgs = {};
  43. try {
  44. for (let idx = 0; idx < firstArgs.length; idx++) {
  45. const arg = firstArgs[idx];
  46. if (arg.toString().match(/^[0-9a-f]{24}$/)) {
  47. loggableArgs[`${idx}`] = arg;
  48. }
  49. }
  50. } catch (error) {}
  51. logger.log({key, args: loggableArgs, elapsedTime}, "[Metrics] timed async method call");
  52. }
  53. return callback.apply(this, callbackArgs);
  54. });
  55. };
  56. };