common.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * Creates a rate limiter that will call the disable callback when the rate limit is reached and the enable callback
  3. * when a timeout has occurred.
  4. * @param maxPerSecond Maximum number of calls per second
  5. * @param enable Callback to enable capture
  6. * @param disable Callback to disable capture
  7. * @returns A function to call to increment the rate limiter count
  8. */
  9. function createRateLimiter(
  10. maxPerSecond,
  11. enable,
  12. disable,
  13. ) {
  14. let count = 0;
  15. let retrySeconds = 5;
  16. let disabledTimeout = 0;
  17. setInterval(() => {
  18. if (disabledTimeout === 0) {
  19. if (count > maxPerSecond) {
  20. retrySeconds *= 2;
  21. disable(retrySeconds);
  22. // Cap at one day
  23. if (retrySeconds > 86400) {
  24. retrySeconds = 86400;
  25. }
  26. disabledTimeout = retrySeconds;
  27. }
  28. } else {
  29. disabledTimeout -= 1;
  30. if (disabledTimeout === 0) {
  31. enable();
  32. }
  33. }
  34. count = 0;
  35. }, 1000).unref();
  36. return () => {
  37. count += 1;
  38. };
  39. }
  40. // Add types for the exception event data
  41. /** Could this be an anonymous function? */
  42. function isAnonymous(name) {
  43. return name !== undefined && (name.length === 0 || name === '?' || name === '<anonymous>');
  44. }
  45. /** Do the function names appear to match? */
  46. function functionNamesMatch(a, b) {
  47. return a === b || (isAnonymous(a) && isAnonymous(b));
  48. }
  49. /** Creates a unique hash from stack frames */
  50. function hashFrames(frames) {
  51. if (frames === undefined) {
  52. return;
  53. }
  54. // Only hash the 10 most recent frames (ie. the last 10)
  55. return frames.slice(-10).reduce((acc, frame) => `${acc},${frame.function},${frame.lineno},${frame.colno}`, '');
  56. }
  57. /**
  58. * We use the stack parser to create a unique hash from the exception stack trace
  59. * This is used to lookup vars when the exception passes through the event processor
  60. */
  61. function hashFromStack(stackParser, stack) {
  62. if (stack === undefined) {
  63. return undefined;
  64. }
  65. return hashFrames(stackParser(stack, 1));
  66. }
  67. export { createRateLimiter, functionNamesMatch, hashFrames, hashFromStack, isAnonymous };
  68. //# sourceMappingURL=common.js.map