google.golang.org/grpc@v1.72.2/stats/metrics.go (about) 1 /* 2 * Copyright 2024 gRPC authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package stats 18 19 import "maps" 20 21 // MetricSet is a set of metrics to record. Once created, MetricSet is immutable, 22 // however Add and Remove can make copies with specific metrics added or 23 // removed, respectively. 24 // 25 // Do not construct directly; use NewMetricSet instead. 26 type MetricSet struct { 27 // metrics are the set of metrics to initialize. 28 metrics map[string]bool 29 } 30 31 // NewMetricSet returns a MetricSet containing metricNames. 32 func NewMetricSet(metricNames ...string) *MetricSet { 33 newMetrics := make(map[string]bool) 34 for _, metric := range metricNames { 35 newMetrics[metric] = true 36 } 37 return &MetricSet{metrics: newMetrics} 38 } 39 40 // Metrics returns the metrics set. The returned map is read-only and must not 41 // be modified. 42 func (m *MetricSet) Metrics() map[string]bool { 43 return m.metrics 44 } 45 46 // Add adds the metricNames to the metrics set and returns a new copy with the 47 // additional metrics. 48 func (m *MetricSet) Add(metricNames ...string) *MetricSet { 49 newMetrics := make(map[string]bool) 50 for metric := range m.metrics { 51 newMetrics[metric] = true 52 } 53 54 for _, metric := range metricNames { 55 newMetrics[metric] = true 56 } 57 return &MetricSet{metrics: newMetrics} 58 } 59 60 // Join joins the metrics passed in with the metrics set, and returns a new copy 61 // with the merged metrics. 62 func (m *MetricSet) Join(metrics *MetricSet) *MetricSet { 63 newMetrics := make(map[string]bool) 64 maps.Copy(newMetrics, m.metrics) 65 maps.Copy(newMetrics, metrics.metrics) 66 return &MetricSet{metrics: newMetrics} 67 } 68 69 // Remove removes the metricNames from the metrics set and returns a new copy 70 // with the metrics removed. 71 func (m *MetricSet) Remove(metricNames ...string) *MetricSet { 72 newMetrics := make(map[string]bool) 73 for metric := range m.metrics { 74 newMetrics[metric] = true 75 } 76 77 for _, metric := range metricNames { 78 delete(newMetrics, metric) 79 } 80 return &MetricSet{metrics: newMetrics} 81 }