// Copyright 2014 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package prometheus

import (
	
	
	
	
	
	
	
	
	
	
	

	

	
	dto 
	
	
)

const (
	// Capacity for the channel to collect metrics and descriptors.
	capMetricChan = 1000
	capDescChan   = 10
)

// DefaultRegisterer and DefaultGatherer are the implementations of the
// Registerer and Gatherer interface a number of convenience functions in this
// package act on. Initially, both variables point to the same Registry, which
// has a process collector (currently on Linux only, see NewProcessCollector)
// and a Go collector (see NewGoCollector, in particular the note about
// stop-the-world implication with Go versions older than 1.9) already
// registered. This approach to keep default instances as global state mirrors
// the approach of other packages in the Go standard library. Note that there
// are caveats. Change the variables with caution and only if you understand the
// consequences. Users who want to avoid global state altogether should not use
// the convenience functions and act on custom instances instead.
var (
	defaultRegistry              = NewRegistry()
	DefaultRegisterer Registerer = defaultRegistry
	DefaultGatherer   Gatherer   = defaultRegistry
)

func init() {
	MustRegister(NewProcessCollector(ProcessCollectorOpts{}))
	MustRegister(NewGoCollector())
}

// NewRegistry creates a new vanilla Registry without any Collectors
// pre-registered.
func () *Registry {
	return &Registry{
		collectorsByID:  map[uint64]Collector{},
		descIDs:         map[uint64]struct{}{},
		dimHashesByName: map[string]uint64{},
	}
}

// NewPedanticRegistry returns a registry that checks during collection if each
// collected Metric is consistent with its reported Desc, and if the Desc has
// actually been registered with the registry. Unchecked Collectors (those whose
// Describe method does not yield any descriptors) are excluded from the check.
//
// Usually, a Registry will be happy as long as the union of all collected
// Metrics is consistent and valid even if some metrics are not consistent with
// their own Desc or a Desc provided by their registered Collector. Well-behaved
// Collectors and Metrics will only provide consistent Descs. This Registry is
// useful to test the implementation of Collectors and Metrics.
func () *Registry {
	 := NewRegistry()
	.pedanticChecksEnabled = true
	return 
}

// Registerer is the interface for the part of a registry in charge of
// registering and unregistering. Users of custom registries should use
// Registerer as type for registration purposes (rather than the Registry type
// directly). In that way, they are free to use custom Registerer implementation
// (e.g. for testing purposes).
type Registerer interface {
	// Register registers a new Collector to be included in metrics
	// collection. It returns an error if the descriptors provided by the
	// Collector are invalid or if they — in combination with descriptors of
	// already registered Collectors — do not fulfill the consistency and
	// uniqueness criteria described in the documentation of metric.Desc.
	//
	// If the provided Collector is equal to a Collector already registered
	// (which includes the case of re-registering the same Collector), the
	// returned error is an instance of AlreadyRegisteredError, which
	// contains the previously registered Collector.
	//
	// A Collector whose Describe method does not yield any Desc is treated
	// as unchecked. Registration will always succeed. No check for
	// re-registering (see previous paragraph) is performed. Thus, the
	// caller is responsible for not double-registering the same unchecked
	// Collector, and for providing a Collector that will not cause
	// inconsistent metrics on collection. (This would lead to scrape
	// errors.)
	Register(Collector) error
	// MustRegister works like Register but registers any number of
	// Collectors and panics upon the first registration that causes an
	// error.
	MustRegister(...Collector)
	// Unregister unregisters the Collector that equals the Collector passed
	// in as an argument.  (Two Collectors are considered equal if their
	// Describe method yields the same set of descriptors.) The function
	// returns whether a Collector was unregistered. Note that an unchecked
	// Collector cannot be unregistered (as its Describe method does not
	// yield any descriptor).
	//
	// Note that even after unregistering, it will not be possible to
	// register a new Collector that is inconsistent with the unregistered
	// Collector, e.g. a Collector collecting metrics with the same name but
	// a different help string. The rationale here is that the same registry
	// instance must only collect consistent metrics throughout its
	// lifetime.
	Unregister(Collector) bool
}

// Gatherer is the interface for the part of a registry in charge of gathering
// the collected metrics into a number of MetricFamilies. The Gatherer interface
// comes with the same general implication as described for the Registerer
// interface.
type Gatherer interface {
	// Gather calls the Collect method of the registered Collectors and then
	// gathers the collected metrics into a lexicographically sorted slice
	// of uniquely named MetricFamily protobufs. Gather ensures that the
	// returned slice is valid and self-consistent so that it can be used
	// for valid exposition. As an exception to the strict consistency
	// requirements described for metric.Desc, Gather will tolerate
	// different sets of label names for metrics of the same metric family.
	//
	// Even if an error occurs, Gather attempts to gather as many metrics as
	// possible. Hence, if a non-nil error is returned, the returned
	// MetricFamily slice could be nil (in case of a fatal error that
	// prevented any meaningful metric collection) or contain a number of
	// MetricFamily protobufs, some of which might be incomplete, and some
	// might be missing altogether. The returned error (which might be a
	// MultiError) explains the details. Note that this is mostly useful for
	// debugging purposes. If the gathered protobufs are to be used for
	// exposition in actual monitoring, it is almost always better to not
	// expose an incomplete result and instead disregard the returned
	// MetricFamily protobufs in case the returned error is non-nil.
	Gather() ([]*dto.MetricFamily, error)
}

// Register registers the provided Collector with the DefaultRegisterer.
//
// Register is a shortcut for DefaultRegisterer.Register(c). See there for more
// details.
func ( Collector) error {
	return DefaultRegisterer.Register()
}

// MustRegister registers the provided Collectors with the DefaultRegisterer and
// panics if any error occurs.
//
// MustRegister is a shortcut for DefaultRegisterer.MustRegister(cs...). See
// there for more details.
func ( ...Collector) {
	DefaultRegisterer.MustRegister(...)
}

// Unregister removes the registration of the provided Collector from the
// DefaultRegisterer.
//
// Unregister is a shortcut for DefaultRegisterer.Unregister(c). See there for
// more details.
func ( Collector) bool {
	return DefaultRegisterer.Unregister()
}

// GathererFunc turns a function into a Gatherer.
type GathererFunc func() ([]*dto.MetricFamily, error)

// Gather implements Gatherer.
func ( GathererFunc) () ([]*dto.MetricFamily, error) {
	return ()
}

// AlreadyRegisteredError is returned by the Register method if the Collector to
// be registered has already been registered before, or a different Collector
// that collects the same metrics has been registered before. Registration fails
// in that case, but you can detect from the kind of error what has
// happened. The error contains fields for the existing Collector and the
// (rejected) new Collector that equals the existing one. This can be used to
// find out if an equal Collector has been registered before and switch over to
// using the old one, as demonstrated in the example.
type AlreadyRegisteredError struct {
	ExistingCollector, NewCollector Collector
}

func ( AlreadyRegisteredError) () string {
	return "duplicate metrics collector registration attempted"
}

// MultiError is a slice of errors implementing the error interface. It is used
// by a Gatherer to report multiple errors during MetricFamily gathering.
type MultiError []error

// Error formats the contained errors as a bullet point list, preceded by the
// total number of errors. Note that this results in a multi-line string.
func ( MultiError) () string {
	if len() == 0 {
		return ""
	}
	 := &bytes.Buffer{}
	fmt.Fprintf(, "%d error(s) occurred:", len())
	for ,  := range  {
		fmt.Fprintf(, "\n* %s", )
	}
	return .String()
}

// Append appends the provided error if it is not nil.
func ( *MultiError) ( error) {
	if  != nil {
		* = append(*, )
	}
}

// MaybeUnwrap returns nil if len(errs) is 0. It returns the first and only
// contained error as error if len(errs is 1). In all other cases, it returns
// the MultiError directly. This is helpful for returning a MultiError in a way
// that only uses the MultiError if needed.
func ( MultiError) () error {
	switch len() {
	case 0:
		return nil
	case 1:
		return [0]
	default:
		return 
	}
}

// Registry registers Prometheus collectors, collects their metrics, and gathers
// them into MetricFamilies for exposition. It implements Registerer, Gatherer,
// and Collector. The zero value is not usable. Create instances with
// NewRegistry or NewPedanticRegistry.
//
// Registry implements Collector to allow it to be used for creating groups of
// metrics. See the Grouping example for how this can be done.
type Registry struct {
	mtx                   sync.RWMutex
	collectorsByID        map[uint64]Collector // ID is a hash of the descIDs.
	descIDs               map[uint64]struct{}
	dimHashesByName       map[string]uint64
	uncheckedCollectors   []Collector
	pedanticChecksEnabled bool
}

// Register implements Registerer.
func ( *Registry) ( Collector) error {
	var (
		           = make(chan *Desc, capDescChan)
		         = map[uint64]struct{}{}
		 = map[string]uint64{}
		        uint64 // All desc IDs XOR'd together.
		   error
	)
	go func() {
		.Describe()
		close()
	}()
	.mtx.Lock()
	defer func() {
		// Drain channel in case of premature return to not leak a goroutine.
		for range  {
		}
		.mtx.Unlock()
	}()
	// Conduct various tests...
	for  := range  {

		// Is the descriptor valid at all?
		if .err != nil {
			return fmt.Errorf("descriptor %s is invalid: %w", , .err)
		}

		// Is the descID unique?
		// (In other words: Is the fqName + constLabel combination unique?)
		if ,  := .descIDs[.id];  {
			 = fmt.Errorf("descriptor %s already exists with the same fully-qualified name and const label values", )
		}
		// If it is not a duplicate desc in this collector, XOR it to
		// the collectorID.  (We allow duplicate descs within the same
		// collector, but their existence must be a no-op.)
		if ,  := [.id]; ! {
			[.id] = struct{}{}
			 ^= .id
		}

		// Are all the label names and the help string consistent with
		// previous descriptors of the same name?
		// First check existing descriptors...
		if ,  := .dimHashesByName[.fqName];  {
			if  != .dimHash {
				return fmt.Errorf("a previously registered descriptor with the same fully-qualified name as %s has different label names or a different help string", )
			}
			continue
		}

		// ...then check the new descriptors already seen.
		if ,  := [.fqName];  {
			if  != .dimHash {
				return fmt.Errorf("descriptors reported by collector have inconsistent label names or help strings for the same fully-qualified name, offender is %s", )
			}
			continue
		}
		[.fqName] = .dimHash
	}
	// A Collector yielding no Desc at all is considered unchecked.
	if len() == 0 {
		.uncheckedCollectors = append(.uncheckedCollectors, )
		return nil
	}
	if ,  := .collectorsByID[];  {
		switch e := .(type) {
		case *wrappingCollector:
			return AlreadyRegisteredError{
				ExistingCollector: .unwrapRecursively(),
				NewCollector:      ,
			}
		default:
			return AlreadyRegisteredError{
				ExistingCollector: ,
				NewCollector:      ,
			}
		}
	}
	// If the collectorID is new, but at least one of the descs existed
	// before, we are in trouble.
	if  != nil {
		return 
	}

	// Only after all tests have passed, actually register.
	.collectorsByID[] = 
	for  := range  {
		.descIDs[] = struct{}{}
	}
	for ,  := range  {
		.dimHashesByName[] = 
	}
	return nil
}

// Unregister implements Registerer.
func ( *Registry) ( Collector) bool {
	var (
		    = make(chan *Desc, capDescChan)
		     = map[uint64]struct{}{}
		 uint64 // All desc IDs XOR'd together.
	)
	go func() {
		.Describe()
		close()
	}()
	for  := range  {
		if ,  := [.id]; ! {
			 ^= .id
			[.id] = struct{}{}
		}
	}

	.mtx.RLock()
	if ,  := .collectorsByID[]; ! {
		.mtx.RUnlock()
		return false
	}
	.mtx.RUnlock()

	.mtx.Lock()
	defer .mtx.Unlock()

	delete(.collectorsByID, )
	for  := range  {
		delete(.descIDs, )
	}
	// dimHashesByName is left untouched as those must be consistent
	// throughout the lifetime of a program.
	return true
}

// MustRegister implements Registerer.
func ( *Registry) ( ...Collector) {
	for ,  := range  {
		if  := .Register();  != nil {
			panic()
		}
	}
}

// Gather implements Gatherer.
func ( *Registry) () ([]*dto.MetricFamily, error) {
	.mtx.RLock()

	if len(.collectorsByID) == 0 && len(.uncheckedCollectors) == 0 {
		// Fast path.
		.mtx.RUnlock()
		return nil, nil
	}

	var (
		   = make(chan Metric, capMetricChan)
		 = make(chan Metric, capMetricChan)
		        = map[uint64]struct{}{}
		                  sync.WaitGroup
		                MultiError          // The collected errors to return in the end.
		   map[uint64]struct{} // Only used for pedantic checks
	)

	 := len(.collectorsByID) + len(.uncheckedCollectors)
	 := make(map[string]*dto.MetricFamily, len(.dimHashesByName))
	 := make(chan Collector, len(.collectorsByID))
	 := make(chan Collector, len(.uncheckedCollectors))
	for ,  := range .collectorsByID {
		 <- 
	}
	for ,  := range .uncheckedCollectors {
		 <- 
	}
	// In case pedantic checks are enabled, we have to copy the map before
	// giving up the RLock.
	if .pedanticChecksEnabled {
		 = make(map[uint64]struct{}, len(.descIDs))
		for  := range .descIDs {
			[] = struct{}{}
		}
	}
	.mtx.RUnlock()

	.Add()

	 := func() {
		for {
			select {
			case  := <-:
				.Collect()
			case  := <-:
				.Collect()
			default:
				return
			}
			.Done()
		}
	}

	// Start the first worker now to make sure at least one is running.
	go ()
	--

	// Close checkedMetricChan and uncheckedMetricChan once all collectors
	// are collected.
	go func() {
		.Wait()
		close()
		close()
	}()

	// Drain checkedMetricChan and uncheckedMetricChan in case of premature return.
	defer func() {
		if  != nil {
			for range  {
			}
		}
		if  != nil {
			for range  {
			}
		}
	}()

	// Copy the channel references so we can nil them out later to remove
	// them from the select statements below.
	 := 
	 := 

	for {
		select {
		case ,  := <-:
			if ! {
				 = nil
				break
			}
			.Append(processMetric(
				, ,
				,
				,
			))
		case ,  := <-:
			if ! {
				 = nil
				break
			}
			.Append(processMetric(
				, ,
				,
				nil,
			))
		default:
			if  <= 0 || len()+len() == 0 {
				// All collectors are already being worked on or
				// we have already as many goroutines started as
				// there are collectors. Do the same as above,
				// just without the default.
				select {
				case ,  := <-:
					if ! {
						 = nil
						break
					}
					.Append(processMetric(
						, ,
						,
						,
					))
				case ,  := <-:
					if ! {
						 = nil
						break
					}
					.Append(processMetric(
						, ,
						,
						nil,
					))
				}
				break
			}
			// Start more workers.
			go ()
			--
			runtime.Gosched()
		}
		// Once both checkedMetricChan and uncheckedMetricChan are closed
		// and drained, the contraption above will nil out cmc and umc,
		// and then we can leave the collect loop here.
		if  == nil &&  == nil {
			break
		}
	}
	return internal.NormalizeMetricFamilies(), .MaybeUnwrap()
}

// Describe implements Collector.
func ( *Registry) ( chan<- *Desc) {
	.mtx.RLock()
	defer .mtx.RUnlock()

	// Only report the checked Collectors; unchecked collectors don't report any
	// Desc.
	for ,  := range .collectorsByID {
		.Describe()
	}
}

// Collect implements Collector.
func ( *Registry) ( chan<- Metric) {
	.mtx.RLock()
	defer .mtx.RUnlock()

	for ,  := range .collectorsByID {
		.Collect()
	}
	for ,  := range .uncheckedCollectors {
		.Collect()
	}
}

// WriteToTextfile calls Gather on the provided Gatherer, encodes the result in the
// Prometheus text format, and writes it to a temporary file. Upon success, the
// temporary file is renamed to the provided filename.
//
// This is intended for use with the textfile collector of the node exporter.
// Note that the node exporter expects the filename to be suffixed with ".prom".
func ( string,  Gatherer) error {
	,  := os.CreateTemp(filepath.Dir(), filepath.Base())
	if  != nil {
		return 
	}
	defer os.Remove(.Name())

	,  := .Gather()
	if  != nil {
		return 
	}
	for ,  := range  {
		if ,  := expfmt.MetricFamilyToText(, );  != nil {
			return 
		}
	}
	if  := .Close();  != nil {
		return 
	}

	if  := os.Chmod(.Name(), 0o644);  != nil {
		return 
	}
	return os.Rename(.Name(), )
}

// processMetric is an internal helper method only used by the Gather method.
func processMetric(
	 Metric,
	 map[string]*dto.MetricFamily,
	 map[uint64]struct{},
	 map[uint64]struct{},
) error {
	 := .Desc()
	// Wrapped metrics collected by an unchecked Collector can have an
	// invalid Desc.
	if .err != nil {
		return .err
	}
	 := &dto.Metric{}
	if  := .Write();  != nil {
		return fmt.Errorf("error collecting metric %v: %w", , )
	}
	,  := [.fqName]
	if  { // Existing name.
		if .GetHelp() != .help {
			return fmt.Errorf(
				"collected metric %s %s has help %q but should have %q",
				.fqName, , .help, .GetHelp(),
			)
		}
		// TODO(beorn7): Simplify switch once Desc has type.
		switch .GetType() {
		case dto.MetricType_COUNTER:
			if .Counter == nil {
				return fmt.Errorf(
					"collected metric %s %s should be a Counter",
					.fqName, ,
				)
			}
		case dto.MetricType_GAUGE:
			if .Gauge == nil {
				return fmt.Errorf(
					"collected metric %s %s should be a Gauge",
					.fqName, ,
				)
			}
		case dto.MetricType_SUMMARY:
			if .Summary == nil {
				return fmt.Errorf(
					"collected metric %s %s should be a Summary",
					.fqName, ,
				)
			}
		case dto.MetricType_UNTYPED:
			if .Untyped == nil {
				return fmt.Errorf(
					"collected metric %s %s should be Untyped",
					.fqName, ,
				)
			}
		case dto.MetricType_HISTOGRAM:
			if .Histogram == nil {
				return fmt.Errorf(
					"collected metric %s %s should be a Histogram",
					.fqName, ,
				)
			}
		default:
			panic("encountered MetricFamily with invalid type")
		}
	} else { // New name.
		 = &dto.MetricFamily{}
		.Name = proto.String(.fqName)
		.Help = proto.String(.help)
		// TODO(beorn7): Simplify switch once Desc has type.
		switch {
		case .Gauge != nil:
			.Type = dto.MetricType_GAUGE.Enum()
		case .Counter != nil:
			.Type = dto.MetricType_COUNTER.Enum()
		case .Summary != nil:
			.Type = dto.MetricType_SUMMARY.Enum()
		case .Untyped != nil:
			.Type = dto.MetricType_UNTYPED.Enum()
		case .Histogram != nil:
			.Type = dto.MetricType_HISTOGRAM.Enum()
		default:
			return fmt.Errorf("empty metric collected: %s", )
		}
		if  := checkSuffixCollisions(, );  != nil {
			return 
		}
		[.fqName] = 
	}
	if  := checkMetricConsistency(, , );  != nil {
		return 
	}
	if  != nil {
		// Is the desc registered at all?
		if ,  := [.id]; ! {
			return fmt.Errorf(
				"collected metric %s %s with unregistered descriptor %s",
				.GetName(), , ,
			)
		}
		if  := checkDescConsistency(, , );  != nil {
			return 
		}
	}
	.Metric = append(.Metric, )
	return nil
}

// Gatherers is a slice of Gatherer instances that implements the Gatherer
// interface itself. Its Gather method calls Gather on all Gatherers in the
// slice in order and returns the merged results. Errors returned from the
// Gather calls are all returned in a flattened MultiError. Duplicate and
// inconsistent Metrics are skipped (first occurrence in slice order wins) and
// reported in the returned error.
//
// Gatherers can be used to merge the Gather results from multiple
// Registries. It also provides a way to directly inject existing MetricFamily
// protobufs into the gathering by creating a custom Gatherer with a Gather
// method that simply returns the existing MetricFamily protobufs. Note that no
// registration is involved (in contrast to Collector registration), so
// obviously registration-time checks cannot happen. Any inconsistencies between
// the gathered MetricFamilies are reported as errors by the Gather method, and
// inconsistent Metrics are dropped. Invalid parts of the MetricFamilies
// (e.g. syntactically invalid metric or label names) will go undetected.
type Gatherers []Gatherer

// Gather implements Gatherer.
func ( Gatherers) () ([]*dto.MetricFamily, error) {
	var (
		 = map[string]*dto.MetricFamily{}
		         = map[uint64]struct{}{}
		                 MultiError // The collected errors to return in the end.
	)

	for ,  := range  {
		,  := .Gather()
		if  != nil {
			 := MultiError{}
			if errors.As(, &) {
				for ,  := range  {
					 = append(, fmt.Errorf("[from Gatherer #%d] %w", +1, ))
				}
			} else {
				 = append(, fmt.Errorf("[from Gatherer #%d] %w", +1, ))
			}
		}
		for ,  := range  {
			,  := [.GetName()]
			if  {
				if .GetHelp() != .GetHelp() {
					 = append(, fmt.Errorf(
						"gathered metric family %s has help %q but should have %q",
						.GetName(), .GetHelp(), .GetHelp(),
					))
					continue
				}
				if .GetType() != .GetType() {
					 = append(, fmt.Errorf(
						"gathered metric family %s has type %s but should have %s",
						.GetName(), .GetType(), .GetType(),
					))
					continue
				}
			} else {
				 = &dto.MetricFamily{}
				.Name = .Name
				.Help = .Help
				.Type = .Type
				if  := checkSuffixCollisions(, );  != nil {
					 = append(, )
					continue
				}
				[.GetName()] = 
			}
			for ,  := range .Metric {
				if  := checkMetricConsistency(, , );  != nil {
					 = append(, )
					continue
				}
				.Metric = append(.Metric, )
			}
		}
	}
	return internal.NormalizeMetricFamilies(), .MaybeUnwrap()
}

// checkSuffixCollisions checks for collisions with the “magic” suffixes the
// Prometheus text format and the internal metric representation of the
// Prometheus server add while flattening Summaries and Histograms.
func checkSuffixCollisions( *dto.MetricFamily,  map[string]*dto.MetricFamily) error {
	var (
		              = .GetName()
		              = .GetType()
		 = ""
	)
	switch {
	case strings.HasSuffix(, "_count"):
		 = [:len()-6]
	case strings.HasSuffix(, "_sum"):
		 = [:len()-4]
	case strings.HasSuffix(, "_bucket"):
		 = [:len()-7]
	}
	if  != "" {
		if ,  := [];  {
			switch .GetType() {
			case dto.MetricType_SUMMARY:
				if !strings.HasSuffix(, "_bucket") {
					return fmt.Errorf(
						"collected metric named %q collides with previously collected summary named %q",
						, ,
					)
				}
			case dto.MetricType_HISTOGRAM:
				return fmt.Errorf(
					"collected metric named %q collides with previously collected histogram named %q",
					, ,
				)
			}
		}
	}
	if  == dto.MetricType_SUMMARY ||  == dto.MetricType_HISTOGRAM {
		if ,  := [+"_count"];  {
			return fmt.Errorf(
				"collected histogram or summary named %q collides with previously collected metric named %q",
				, +"_count",
			)
		}
		if ,  := [+"_sum"];  {
			return fmt.Errorf(
				"collected histogram or summary named %q collides with previously collected metric named %q",
				, +"_sum",
			)
		}
	}
	if  == dto.MetricType_HISTOGRAM {
		if ,  := [+"_bucket"];  {
			return fmt.Errorf(
				"collected histogram named %q collides with previously collected metric named %q",
				, +"_bucket",
			)
		}
	}
	return nil
}

// checkMetricConsistency checks if the provided Metric is consistent with the
// provided MetricFamily. It also hashes the Metric labels and the MetricFamily
// name. If the resulting hash is already in the provided metricHashes, an error
// is returned. If not, it is added to metricHashes.
func checkMetricConsistency(
	 *dto.MetricFamily,
	 *dto.Metric,
	 map[uint64]struct{},
) error {
	 := .GetName()

	// Type consistency with metric family.
	if .GetType() == dto.MetricType_GAUGE && .Gauge == nil ||
		.GetType() == dto.MetricType_COUNTER && .Counter == nil ||
		.GetType() == dto.MetricType_SUMMARY && .Summary == nil ||
		.GetType() == dto.MetricType_HISTOGRAM && .Histogram == nil ||
		.GetType() == dto.MetricType_UNTYPED && .Untyped == nil {
		return fmt.Errorf(
			"collected metric %q { %s} is not a %s",
			, , .GetType(),
		)
	}

	 := ""
	for ,  := range .GetLabel() {
		 := .GetName()
		if  ==  {
			return fmt.Errorf(
				"collected metric %q { %s} has two or more labels with the same name: %s",
				, , ,
			)
		}
		if !checkLabelName() {
			return fmt.Errorf(
				"collected metric %q { %s} has a label with an invalid name: %s",
				, , ,
			)
		}
		if .Summary != nil &&  == quantileLabel {
			return fmt.Errorf(
				"collected metric %q { %s} must not have an explicit %q label",
				, , quantileLabel,
			)
		}
		if !utf8.ValidString(.GetValue()) {
			return fmt.Errorf(
				"collected metric %q { %s} has a label named %q whose value is not utf8: %#v",
				, , , .GetValue())
		}
		 = 
	}

	// Is the metric unique (i.e. no other metric with the same name and the same labels)?
	 := xxhash.New()
	.WriteString()
	.Write(separatorByteSlice)
	// Make sure label pairs are sorted. We depend on it for the consistency
	// check.
	if !sort.IsSorted(internal.LabelPairSorter(.Label)) {
		// We cannot sort dtoMetric.Label in place as it is immutable by contract.
		 := make([]*dto.LabelPair, len(.Label))
		copy(, .Label)
		sort.Sort(internal.LabelPairSorter())
		.Label = 
	}
	for ,  := range .Label {
		.WriteString(.GetName())
		.Write(separatorByteSlice)
		.WriteString(.GetValue())
		.Write(separatorByteSlice)
	}
	if .TimestampMs != nil {
		.WriteString(strconv.FormatInt(*(.TimestampMs), 10))
		.Write(separatorByteSlice)
	}
	 := .Sum64()
	if ,  := [];  {
		return fmt.Errorf(
			"collected metric %q { %s} was collected before with the same name and label values",
			, ,
		)
	}
	[] = struct{}{}
	return nil
}

func checkDescConsistency(
	 *dto.MetricFamily,
	 *dto.Metric,
	 *Desc,
) error {
	// Desc help consistency with metric family help.
	if .GetHelp() != .help {
		return fmt.Errorf(
			"collected metric %s %s has help %q but should have %q",
			.GetName(), , .GetHelp(), .help,
		)
	}

	// Is the desc consistent with the content of the metric?
	 := make([]*dto.LabelPair, len(.constLabelPairs), len(.Label))
	copy(, .constLabelPairs)
	for ,  := range .variableLabels.names {
		 = append(, &dto.LabelPair{
			Name: proto.String(),
		})
	}
	if len() != len(.Label) {
		return fmt.Errorf(
			"labels in collected metric %s %s are inconsistent with descriptor %s",
			.GetName(), , ,
		)
	}
	sort.Sort(internal.LabelPairSorter())
	for ,  := range  {
		 := .Label[]
		if .GetName() != .GetName() ||
			.Value != nil && .GetValue() != .GetValue() {
			return fmt.Errorf(
				"labels in collected metric %s %s are inconsistent with descriptor %s",
				.GetName(), , ,
			)
		}
	}
	return nil
}

var _ TransactionalGatherer = &MultiTRegistry{}

// MultiTRegistry is a TransactionalGatherer that joins gathered metrics from multiple
// transactional gatherers.
//
// It is caller responsibility to ensure two registries have mutually exclusive metric families,
// no deduplication will happen.
type MultiTRegistry struct {
	tGatherers []TransactionalGatherer
}

// NewMultiTRegistry creates MultiTRegistry.
func ( ...TransactionalGatherer) *MultiTRegistry {
	return &MultiTRegistry{
		tGatherers: ,
	}
}

// Gather implements TransactionalGatherer interface.
func ( *MultiTRegistry) () ( []*dto.MetricFamily,  func(),  error) {
	 := MultiError{}

	 := make([]func(), 0, len(.tGatherers))
	// TODO(bwplotka): Implement concurrency for those?
	for ,  := range .tGatherers {
		// TODO(bwplotka): Check for duplicates?
		, ,  := .Gather()
		.Append()

		 = append(, ...)
		 = append(, )
	}

	// TODO(bwplotka): Consider sort in place, given metric family in gather is sorted already.
	sort.Slice(, func(,  int) bool {
		return *[].Name < *[].Name
	})
	return , func() {
		for ,  := range  {
			()
		}
	}, .MaybeUnwrap()
}

// TransactionalGatherer represents transactional gatherer that can be triggered to notify gatherer that memory
// used by metric family is no longer used by a caller. This allows implementations with cache.
type TransactionalGatherer interface {
	// Gather returns metrics in a lexicographically sorted slice
	// of uniquely named MetricFamily protobufs. Gather ensures that the
	// returned slice is valid and self-consistent so that it can be used
	// for valid exposition. As an exception to the strict consistency
	// requirements described for metric.Desc, Gather will tolerate
	// different sets of label names for metrics of the same metric family.
	//
	// Even if an error occurs, Gather attempts to gather as many metrics as
	// possible. Hence, if a non-nil error is returned, the returned
	// MetricFamily slice could be nil (in case of a fatal error that
	// prevented any meaningful metric collection) or contain a number of
	// MetricFamily protobufs, some of which might be incomplete, and some
	// might be missing altogether. The returned error (which might be a
	// MultiError) explains the details. Note that this is mostly useful for
	// debugging purposes. If the gathered protobufs are to be used for
	// exposition in actual monitoring, it is almost always better to not
	// expose an incomplete result and instead disregard the returned
	// MetricFamily protobufs in case the returned error is non-nil.
	//
	// Important: done is expected to be triggered (even if the error occurs!)
	// once caller does not need returned slice of dto.MetricFamily.
	Gather() (_ []*dto.MetricFamily, done func(), err error)
}

// ToTransactionalGatherer transforms Gatherer to transactional one with noop as done function.
func ( Gatherer) TransactionalGatherer {
	return &noTransactionGatherer{g: }
}

type noTransactionGatherer struct {
	g Gatherer
}

// Gather implements TransactionalGatherer interface.
func ( *noTransactionGatherer) () ( []*dto.MetricFamily,  func(),  error) {
	,  := .g.Gather()
	return , func() {}, 
}