utils.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. Object.defineProperty(exports, '__esModule', { value: true });
  2. const utils = require('@sentry/utils');
  3. const constants = require('./constants.js');
  4. /**
  5. * Generate bucket key from metric properties.
  6. */
  7. function getBucketKey(
  8. metricType,
  9. name,
  10. unit,
  11. tags,
  12. ) {
  13. const stringifiedTags = Object.entries(utils.dropUndefinedKeys(tags)).sort((a, b) => a[0].localeCompare(b[0]));
  14. return `${metricType}${name}${unit}${stringifiedTags}`;
  15. }
  16. /* eslint-disable no-bitwise */
  17. /**
  18. * Simple hash function for strings.
  19. */
  20. function simpleHash(s) {
  21. let rv = 0;
  22. for (let i = 0; i < s.length; i++) {
  23. const c = s.charCodeAt(i);
  24. rv = (rv << 5) - rv + c;
  25. rv &= rv;
  26. }
  27. return rv >>> 0;
  28. }
  29. /* eslint-enable no-bitwise */
  30. /**
  31. * Serialize metrics buckets into a string based on statsd format.
  32. *
  33. * Example of format:
  34. * metric.name@second:1:1.2|d|#a:value,b:anothervalue|T12345677
  35. * Segments:
  36. * name: metric.name
  37. * unit: second
  38. * value: [1, 1.2]
  39. * type of metric: d (distribution)
  40. * tags: { a: value, b: anothervalue }
  41. * timestamp: 12345677
  42. */
  43. function serializeMetricBuckets(metricBucketItems) {
  44. let out = '';
  45. for (const item of metricBucketItems) {
  46. const tagEntries = Object.entries(item.tags);
  47. const maybeTags = tagEntries.length > 0 ? `|#${tagEntries.map(([key, value]) => `${key}:${value}`).join(',')}` : '';
  48. out += `${item.name}@${item.unit}:${item.metric}|${item.metricType}${maybeTags}|T${item.timestamp}\n`;
  49. }
  50. return out;
  51. }
  52. /**
  53. * Sanitizes tags.
  54. */
  55. function sanitizeTags(unsanitizedTags) {
  56. const tags = {};
  57. for (const key in unsanitizedTags) {
  58. if (Object.prototype.hasOwnProperty.call(unsanitizedTags, key)) {
  59. const sanitizedKey = key.replace(constants.NAME_AND_TAG_KEY_NORMALIZATION_REGEX, '_');
  60. tags[sanitizedKey] = String(unsanitizedTags[key]).replace(constants.TAG_VALUE_NORMALIZATION_REGEX, '');
  61. }
  62. }
  63. return tags;
  64. }
  65. exports.getBucketKey = getBucketKey;
  66. exports.sanitizeTags = sanitizeTags;
  67. exports.serializeMetricBuckets = serializeMetricBuckets;
  68. exports.simpleHash = simpleHash;
  69. //# sourceMappingURL=utils.js.map