metric-summary.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import { dropUndefinedKeys } from '@sentry/utils';
  2. import '../debug-build.js';
  3. import '../tracing/errors.js';
  4. import '../tracing/spanstatus.js';
  5. import { getActiveSpan } from '../tracing/trace.js';
  6. /**
  7. * key: bucketKey
  8. * value: [exportKey, MetricSummary]
  9. */
  10. let SPAN_METRIC_SUMMARY;
  11. function getMetricStorageForSpan(span) {
  12. return SPAN_METRIC_SUMMARY ? SPAN_METRIC_SUMMARY.get(span) : undefined;
  13. }
  14. /**
  15. * Fetches the metric summary if it exists for the passed span
  16. */
  17. function getMetricSummaryJsonForSpan(span) {
  18. const storage = getMetricStorageForSpan(span);
  19. if (!storage) {
  20. return undefined;
  21. }
  22. const output = {};
  23. for (const [, [exportKey, summary]] of storage) {
  24. if (!output[exportKey]) {
  25. output[exportKey] = [];
  26. }
  27. output[exportKey].push(dropUndefinedKeys(summary));
  28. }
  29. return output;
  30. }
  31. /**
  32. * Updates the metric summary on the currently active span
  33. */
  34. function updateMetricSummaryOnActiveSpan(
  35. metricType,
  36. sanitizedName,
  37. value,
  38. unit,
  39. tags,
  40. bucketKey,
  41. ) {
  42. const span = getActiveSpan();
  43. if (span) {
  44. const storage = getMetricStorageForSpan(span) || new Map();
  45. const exportKey = `${metricType}:${sanitizedName}@${unit}`;
  46. const bucketItem = storage.get(bucketKey);
  47. if (bucketItem) {
  48. const [, summary] = bucketItem;
  49. storage.set(bucketKey, [
  50. exportKey,
  51. {
  52. min: Math.min(summary.min, value),
  53. max: Math.max(summary.max, value),
  54. count: (summary.count += 1),
  55. sum: (summary.sum += value),
  56. tags: summary.tags,
  57. },
  58. ]);
  59. } else {
  60. storage.set(bucketKey, [
  61. exportKey,
  62. {
  63. min: value,
  64. max: value,
  65. count: 1,
  66. sum: value,
  67. tags,
  68. },
  69. ]);
  70. }
  71. if (!SPAN_METRIC_SUMMARY) {
  72. SPAN_METRIC_SUMMARY = new WeakMap();
  73. }
  74. SPAN_METRIC_SUMMARY.set(span, storage);
  75. }
  76. }
  77. export { getMetricSummaryJsonForSpan, updateMetricSummaryOnActiveSpan };
  78. //# sourceMappingURL=metric-summary.js.map