|
| 1 | +import type { |
| 2 | + Client, |
| 3 | + ClientOptions, |
| 4 | + MeasurementUnit, |
| 5 | + MetricsAggregator as MetricsAggregatorBase, |
| 6 | + Primitive, |
| 7 | +} from '@sentry/types'; |
| 8 | +import { timestampInSeconds } from '@sentry/utils'; |
| 9 | +import { DEFAULT_FLUSH_INTERVAL, MAX_WEIGHT, NAME_AND_TAG_KEY_NORMALIZATION_REGEX } from './constants'; |
| 10 | +import { METRIC_MAP } from './instance'; |
| 11 | +import type { MetricBucket, MetricType } from './types'; |
| 12 | +import { getBucketKey, sanitizeTags } from './utils'; |
| 13 | + |
| 14 | +/** |
| 15 | + * A metrics aggregator that aggregates metrics in memory and flushes them periodically. |
| 16 | + */ |
| 17 | +export class MetricsAggregator implements MetricsAggregatorBase { |
| 18 | + // TODO(@anonrig): Use FinalizationRegistry to have a proper way of flushing the buckets |
| 19 | + // when the aggregator is garbage collected. |
| 20 | + // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry |
| 21 | + private _buckets: MetricBucket; |
| 22 | + |
| 23 | + // Different metrics have different weights. We use this to limit the number of metrics |
| 24 | + // that we store in memory. |
| 25 | + private _bucketsTotalWeight; |
| 26 | + |
| 27 | + // TODO(@anonrig): Use `setTimeout` instead of `setInterval` to be more accurate |
| 28 | + // with the flush interval. |
| 29 | + private readonly _interval: ReturnType<typeof setInterval>; |
| 30 | + |
| 31 | + // SDKs are required to shift the flush interval by random() * rollup_in_seconds. |
| 32 | + // That shift is determined once per startup to create jittering. |
| 33 | + private readonly _flushShift: number; |
| 34 | + |
| 35 | + // An SDK is required to perform force flushing ahead of scheduled time if the memory |
| 36 | + // pressure is too high. There is no rule for this other than that SDKs should be tracking |
| 37 | + // abstract aggregation complexity (eg: a counter only carries a single float, whereas a |
| 38 | + // distribution is a float per emission). |
| 39 | + // |
| 40 | + // Force flush is used on either shutdown, flush() or when we exceed the max weight. |
| 41 | + private _forceFlush: boolean; |
| 42 | + |
| 43 | + public constructor(private readonly _client: Client<ClientOptions>) { |
| 44 | + this._buckets = new Map(); |
| 45 | + this._bucketsTotalWeight = 0; |
| 46 | + this._interval = setInterval(() => this._flush(), DEFAULT_FLUSH_INTERVAL); |
| 47 | + this._flushShift = Math.random() * DEFAULT_FLUSH_INTERVAL; |
| 48 | + this._forceFlush = false; |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * @inheritDoc |
| 53 | + */ |
| 54 | + public add( |
| 55 | + metricType: MetricType, |
| 56 | + unsanitizedName: string, |
| 57 | + value: number | string, |
| 58 | + unit: MeasurementUnit = 'none', |
| 59 | + unsanitizedTags: Record<string, Primitive> = {}, |
| 60 | + maybeFloatTimestamp = timestampInSeconds(), |
| 61 | + ): void { |
| 62 | + const timestamp = Math.floor(maybeFloatTimestamp); |
| 63 | + const name = unsanitizedName.replace(NAME_AND_TAG_KEY_NORMALIZATION_REGEX, '_'); |
| 64 | + const tags = sanitizeTags(unsanitizedTags); |
| 65 | + |
| 66 | + const bucketKey = getBucketKey(metricType, name, unit, tags); |
| 67 | + let bucketItem = this._buckets.get(bucketKey); |
| 68 | + if (bucketItem) { |
| 69 | + bucketItem.metric.add(value); |
| 70 | + // TODO(abhi): Do we need this check? |
| 71 | + if (bucketItem.timestamp < timestamp) { |
| 72 | + bucketItem.timestamp = timestamp; |
| 73 | + } |
| 74 | + } else { |
| 75 | + bucketItem = { |
| 76 | + // @ts-expect-error we don't need to narrow down the type of value here, saves bundle size. |
| 77 | + metric: new METRIC_MAP[metricType](value), |
| 78 | + timestamp, |
| 79 | + metricType, |
| 80 | + name, |
| 81 | + unit, |
| 82 | + tags, |
| 83 | + }; |
| 84 | + this._buckets.set(bucketKey, bucketItem); |
| 85 | + } |
| 86 | + |
| 87 | + // We need to keep track of the total weight of the buckets so that we can |
| 88 | + // flush them when we exceed the max weight. |
| 89 | + this._bucketsTotalWeight += bucketItem.metric.weight; |
| 90 | + |
| 91 | + if (this._bucketsTotalWeight >= MAX_WEIGHT) { |
| 92 | + this.flush(); |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + /** |
| 97 | + * Flushes the current metrics to the transport via the transport. |
| 98 | + */ |
| 99 | + public flush(): void { |
| 100 | + this._forceFlush = true; |
| 101 | + this._flush(); |
| 102 | + } |
| 103 | + |
| 104 | + /** |
| 105 | + * Shuts down metrics aggregator and clears all metrics. |
| 106 | + */ |
| 107 | + public close(): void { |
| 108 | + this._forceFlush = true; |
| 109 | + clearInterval(this._interval); |
| 110 | + this._flush(); |
| 111 | + } |
| 112 | + |
| 113 | + /** |
| 114 | + * Flushes the buckets according to the internal state of the aggregator. |
| 115 | + * If it is a force flush, which happens on shutdown, it will flush all buckets. |
| 116 | + * Otherwise, it will only flush buckets that are older than the flush interval, |
| 117 | + * and according to the flush shift. |
| 118 | + * |
| 119 | + * This function mutates `_forceFlush` and `_bucketsTotalWeight` properties. |
| 120 | + */ |
| 121 | + private _flush(): void { |
| 122 | + // TODO(@anonrig): Add Atomics for locking to avoid having force flush and regular flush |
| 123 | + // running at the same time. |
| 124 | + // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics |
| 125 | + |
| 126 | + // This path eliminates the need for checking for timestamps since we're forcing a flush. |
| 127 | + // Remember to reset the flag, or it will always flush all metrics. |
| 128 | + if (this._forceFlush) { |
| 129 | + this._forceFlush = false; |
| 130 | + this._bucketsTotalWeight = 0; |
| 131 | + this._captureMetrics(this._buckets); |
| 132 | + this._buckets.clear(); |
| 133 | + return; |
| 134 | + } |
| 135 | + const cutoffSeconds = timestampInSeconds() - DEFAULT_FLUSH_INTERVAL - this._flushShift; |
| 136 | + // TODO(@anonrig): Optimization opportunity. |
| 137 | + // Convert this map to an array and store key in the bucketItem. |
| 138 | + const flushedBuckets: MetricBucket = new Map(); |
| 139 | + for (const [key, bucket] of this._buckets) { |
| 140 | + if (bucket.timestamp < cutoffSeconds) { |
| 141 | + flushedBuckets.set(key, bucket); |
| 142 | + this._bucketsTotalWeight -= bucket.metric.weight; |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + for (const [key] of flushedBuckets) { |
| 147 | + this._buckets.delete(key); |
| 148 | + } |
| 149 | + |
| 150 | + this._captureMetrics(flushedBuckets); |
| 151 | + } |
| 152 | + |
| 153 | + /** |
| 154 | + * Only captures a subset of the buckets passed to this function. |
| 155 | + * @param flushedBuckets |
| 156 | + */ |
| 157 | + private _captureMetrics(flushedBuckets: MetricBucket): void { |
| 158 | + if (flushedBuckets.size > 0 && this._client.captureAggregateMetrics) { |
| 159 | + // TODO(@anonrig): Optimization opportunity. |
| 160 | + // This copy operation can be avoided if we store the key in the bucketItem. |
| 161 | + const buckets = Array.from(flushedBuckets).map(([, bucketItem]) => bucketItem); |
| 162 | + this._client.captureAggregateMetrics(buckets); |
| 163 | + } |
| 164 | + } |
| 165 | +} |
0 commit comments