utils.js 1.9 KB

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