|
| 1 | +@_implementationOnly import _SentryPrivate |
| 2 | + |
| 3 | +/// The bucket timestamp is calculated: |
| 4 | +/// ( timeIntervalSince1970 / ROLLUP_IN_SECONDS ) * ROLLUP_IN_SECONDS |
| 5 | +typealias BucketTimestamp = UInt64 |
| 6 | +let ROLLUP_IN_SECONDS: TimeInterval = 10 |
| 7 | + |
| 8 | +extension SentryCurrentDateProvider { |
| 9 | + var bucketTimestamp: BucketTimestamp { |
| 10 | + let now = self.date() |
| 11 | + let seconds = now.timeIntervalSince1970 |
| 12 | + |
| 13 | + return (UInt64(seconds) / UInt64(ROLLUP_IN_SECONDS)) * UInt64(ROLLUP_IN_SECONDS) |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +class BucketMetricsAggregator: MetricsAggregator { |
| 18 | + |
| 19 | + private let client: SentryMetricsClient |
| 20 | + private let currentDate: SentryCurrentDateProvider |
| 21 | + private let dispatchQueue: SentryDispatchQueueWrapper |
| 22 | + private let random: SentryRandomProtocol |
| 23 | + private let totalMaxWeight: UInt |
| 24 | + private let flushShift: TimeInterval |
| 25 | + private let flushInterval: TimeInterval |
| 26 | + private let flushTolerance: TimeInterval |
| 27 | + |
| 28 | + private var timer: DispatchSourceTimer? |
| 29 | + private var totalBucketsWeight: UInt = 0 |
| 30 | + private var buckets: [BucketTimestamp: [String: Metric]] = [:] |
| 31 | + private let lock = NSLock() |
| 32 | + |
| 33 | + init( |
| 34 | + client: SentryMetricsClient, |
| 35 | + currentDate: SentryCurrentDateProvider, |
| 36 | + dispatchQueue: SentryDispatchQueueWrapper, |
| 37 | + random: SentryRandomProtocol, |
| 38 | + totalMaxWeight: UInt = METRICS_AGGREGATOR_TOTAL_MAX_WEIGHT, |
| 39 | + flushInterval: TimeInterval = METRICS_AGGREGATOR_FLUSH_INTERVAL, |
| 40 | + flushTolerance: TimeInterval = METRICS_AGGREGATOR_FLUSH_TOLERANCE |
| 41 | + ) { |
| 42 | + self.client = client |
| 43 | + self.currentDate = currentDate |
| 44 | + self.dispatchQueue = dispatchQueue |
| 45 | + self.random = random |
| 46 | + |
| 47 | + // The aggregator shifts its flushing by up to an entire rollup window to |
| 48 | + // avoid multiple clients trampling on end of a 10 second window as all the |
| 49 | + // buckets are anchored to multiples of ROLLUP seconds. We randomize this |
| 50 | + // number once per aggregator boot to achieve some level of offsetting |
| 51 | + // across a fleet of deployed SDKs. |
| 52 | + let flushShift = random.nextNumber() * ROLLUP_IN_SECONDS |
| 53 | + self.totalMaxWeight = totalMaxWeight |
| 54 | + self.flushInterval = flushInterval |
| 55 | + self.flushShift = flushShift |
| 56 | + self.flushTolerance = flushTolerance |
| 57 | + |
| 58 | + startTimer() |
| 59 | + } |
| 60 | + |
| 61 | + private func startTimer() { |
| 62 | + let timer = DispatchSource.makeTimerSource(flags: [], queue: dispatchQueue.queue) |
| 63 | + |
| 64 | + // Set leeway to reduce energy impact |
| 65 | + let leewayInMilliseconds: Int = Int(flushTolerance * 1_000) |
| 66 | + timer.schedule(deadline: .now() + flushInterval, repeating: self.flushInterval, leeway: .milliseconds(leewayInMilliseconds)) |
| 67 | + timer.setEventHandler { [weak self] in |
| 68 | + self?.flush(force: false) |
| 69 | + } |
| 70 | + timer.activate() |
| 71 | + self.timer = timer |
| 72 | + } |
| 73 | + |
| 74 | + func add(type: MetricType, key: String, value: Double, unit: MeasurementUnit, tags: [String: String]) { |
| 75 | + |
| 76 | + // It's important to sort the tags in order to |
| 77 | + // obtain the same bucket key. |
| 78 | + let tagsKey = tags.sorted(by: { $0.key < $1.key }).map({ "\($0.key)=\($0.value)" }).joined(separator: ",") |
| 79 | + let bucketKey = "\(type)_\(key)_\(unit.unit)_\(tagsKey)" |
| 80 | + |
| 81 | + let bucketTimestamp = currentDate.bucketTimestamp |
| 82 | + |
| 83 | + var isOverWeight = false |
| 84 | + |
| 85 | + lock.synchronized { |
| 86 | + var bucket = buckets[bucketTimestamp] ?? [:] |
| 87 | + |
| 88 | + let metric = bucket[bucketKey] ?? CounterMetric(key: key, unit: unit, tags: tags) |
| 89 | + let oldWeight = bucket[bucketKey]?.weight ?? 0 |
| 90 | + |
| 91 | + metric.add(value: value) |
| 92 | + let addedWeight = metric.weight - oldWeight |
| 93 | + |
| 94 | + bucket[bucketKey] = metric |
| 95 | + totalBucketsWeight += addedWeight |
| 96 | + |
| 97 | + buckets[bucketTimestamp] = bucket |
| 98 | + |
| 99 | + let totalWeight = UInt(buckets.count) + totalBucketsWeight |
| 100 | + isOverWeight = totalWeight >= totalMaxWeight |
| 101 | + } |
| 102 | + |
| 103 | + if isOverWeight { |
| 104 | + dispatchQueue.dispatchAsync({ [weak self] in |
| 105 | + self?.flush(force: true) |
| 106 | + }) |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + func flush(force: Bool) { |
| 111 | + var flushableBuckets: [BucketTimestamp: [Metric]] = [:] |
| 112 | + |
| 113 | + if force { |
| 114 | + lock.synchronized { |
| 115 | + for (timestamp, metrics) in buckets { |
| 116 | + flushableBuckets[timestamp] = Array(metrics.values) |
| 117 | + } |
| 118 | + |
| 119 | + buckets.removeAll() |
| 120 | + totalBucketsWeight = 0 |
| 121 | + } |
| 122 | + } else { |
| 123 | + let cutoff = BucketTimestamp(currentDate.date().timeIntervalSince1970 - ROLLUP_IN_SECONDS - flushShift) |
| 124 | + |
| 125 | + lock.synchronized { |
| 126 | + for (bucketTimestamp, bucket) in buckets { |
| 127 | + if bucketTimestamp <= cutoff { |
| 128 | + flushableBuckets[bucketTimestamp] = Array(bucket.values) |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + var weightToRemove: UInt = 0 |
| 133 | + for (bucketTimestamp, metrics) in flushableBuckets { |
| 134 | + for metric in metrics { |
| 135 | + weightToRemove += metric.weight |
| 136 | + } |
| 137 | + buckets.removeValue(forKey: bucketTimestamp) |
| 138 | + } |
| 139 | + |
| 140 | + totalBucketsWeight -= weightToRemove |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + if !flushableBuckets.isEmpty { |
| 145 | + client.capture(flushableBuckets: flushableBuckets) |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + func close() { |
| 150 | + self.flush(force: true) |
| 151 | + |
| 152 | + cancelTimer() |
| 153 | + } |
| 154 | + |
| 155 | + deinit { |
| 156 | + cancelTimer() |
| 157 | + } |
| 158 | + |
| 159 | + private func cancelTimer() { |
| 160 | + self.timer?.cancel() |
| 161 | + self.timer = nil |
| 162 | + } |
| 163 | +} |
0 commit comments