// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package propagation

import (
	
	
	
	

	
	
)

const (
	baggageHeader = "baggage"

	maxParseErrors = 5

	// W3C Baggage specification limits.
	// https://www.w3.org/TR/baggage/#limits
	maxMembers               = 64
	maxBytesPerBaggageString = 8192
)

// handleExtractErrOnce limits error reporting for attacker-controlled baggage headers
// to one process-wide emission, preventing repeated extraction from flooding logs.
var handleExtractErrOnce sync.Once

// Baggage is a propagator that supports the W3C Baggage format.
//
// This propagates user-defined baggage associated with a trace. The complete
// specification is defined at https://www.w3.org/TR/baggage/.
type Baggage struct{}

var _ TextMapPropagator = Baggage{}

// Inject sets baggage key-values from ctx into the carrier.
func (Baggage) ( context.Context,  TextMapCarrier) {
	 := baggage.FromContext().String()
	if  != "" {
		.Set(baggageHeader, )
	}
}

// Extract returns a copy of parent with the baggage from the carrier added.
// If carrier implements [ValuesGetter] (e.g. [HeaderCarrier]), Values is invoked
// for multiple values extraction. Otherwise, Get is called.
func (Baggage) ( context.Context,  TextMapCarrier) context.Context {
	if ,  := .(ValuesGetter);  {
		return extractMultiBaggage(, )
	}
	return extractSingleBaggage(, )
}

// Fields returns the keys who's values are set with Inject.
func (Baggage) () []string {
	return []string{baggageHeader}
}

func extractSingleBaggage( context.Context,  TextMapCarrier) context.Context {
	 := .Get(baggageHeader)
	if  == "" {
		return 
	}

	,  := baggage.Parse()
	if  != nil {
		handleExtractErrOnce.Do(func() {
			errorhandler.GetErrorHandler().Handle()
		})
	}
	if .Len() == 0 {
		return 
	}
	return baggage.ContextWithBaggage(, )
}

func extractMultiBaggage( context.Context,  ValuesGetter) context.Context {
	 := .Values(baggageHeader)
	if len() == 0 {
		return 
	}

	var  []baggage.Member
	var  int
	var  int
	var  error
	for ,  := range  {
		if  > 0 {
			++ // comma separator between combined header values
		}
		 += len()
		if  > maxBytesPerBaggageString {
			// Per the W3C Baggage spec, the byte limit applies to the
			// combination of all baggage headers, not each header
			// individually. Mirror the single-header behavior of
			// reporting the error and returning the parent context
			// with no baggage attached.
			handleExtractErrOnce.Do(func() {
				errorhandler.GetErrorHandler().Handle(fmt.Errorf(
					"baggage: aggregate header size %d exceeds %d byte limit",
					,
					maxBytesPerBaggageString,
				))
			})
			return 
		}

		// If members exceed the limit, stop parsing baggage.
		if len() <= maxMembers {
			,  := baggage.Parse()
			if  != nil {
				++
				if  <= maxParseErrors {
					 = errors.Join(, )
				}
			}
			if .Len() == 0 {
				continue
			}
			 = append(, .Members()...)
		}
	}

	if  :=  - maxParseErrors;  > 0 {
		 = errors.Join(, fmt.Errorf("and %d more error(s)", ))
	}

	,  := baggage.New(...)
	if  != nil {
		 = errors.Join(, )
	}
	if  != nil {
		handleExtractErrOnce.Do(func() {
			errorhandler.GetErrorHandler().Handle()
		})
	}

	if .Len() == 0 {
		return 
	}
	return baggage.ContextWithBaggage(, )
}