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

package log

import (
	
	
	

	
	
	
	
	
	
	
)

const (
	// attributesInlineCount is the number of attributes that are efficiently
	// stored in an array within a Record. This value is borrowed from slog, which
	// performed a quantitative survey of log library use and found that this
	// value covers 95% of all use cases (https://go.dev/blog/slog#performance).
	attributesInlineCount = 5
	// maxUniqueSize helps reduce peak allocation.
	maxUniqueSize = 1028
)

var logAttrDropped = sync.OnceFunc(func() {
	global.Warn("limit reached: dropping log Record attributes")
})

var logKeyValuePairDropped = sync.OnceFunc(func() {
	global.Warn("key duplication: dropping key-value pair")
})

var logInvalidAttribute = sync.OnceFunc(func() {
	global.Warn("invalid attribute: dropping attribute with empty key")
})

// uniquePool is a pool of unique attributes used for attribute deduplication.
var uniquePool = sync.Pool{
	New: func() any { return new([]attribute.KeyValue) },
}

func getUnique() *[]attribute.KeyValue {
	return uniquePool.Get().(*[]attribute.KeyValue)
}

func putUnique( *[]attribute.KeyValue) {
	if cap(*) <= maxUniqueSize {
		clear(*)
		* = (*)[:0]
		uniquePool.Put()
	}
}

// indexPool is a pool of index maps used for attribute deduplication.
var indexPool = sync.Pool{
	New: func() any { return make(map[attribute.Key]int) },
}

func getIndex() map[attribute.Key]int {
	return indexPool.Get().(map[attribute.Key]int)
}

func putIndex( map[attribute.Key]int) {
	clear()
	indexPool.Put()
}

// Record is a log record emitted by the Logger.
// A log record with a non-empty event name is interpreted as an event record.
//
// Do not create instances of Record on your own in production code.
// You can use [go.opentelemetry.io/otel/sdk/log/logtest.RecordFactory]
// for testing purposes.
type Record struct {
	// Do not embed the log.Record. Attributes need to be overwritable, and
	// deep-copying needs to be possible.

	eventName         string
	timestamp         time.Time
	observedTimestamp time.Time
	severity          log.Severity
	severityText      string
	body              attribute.Value

	// The fields below are for optimizing the implementation of Attributes and
	// AddAttributes. This design is borrowed from the slog Record type:
	// https://cs.opensource.google/go/go/+/refs/tags/go1.22.0:src/log/slog/record.go;l=20

	// Allocation optimization: an inline array sized to hold
	// the majority of log calls (based on examination of open-source
	// code). It holds the start of the list of attributes.
	front [attributesInlineCount]attribute.KeyValue

	// The number of attributes in front.
	nFront int

	// The list of attributes except for those in front.
	// Invariants:
	//   - len(back) > 0 if nFront == len(front)
	//   - Unused array elements are zeroed to detect mistakes.
	back []attribute.KeyValue

	// dropped is the count of attributes that have been dropped when limits
	// were reached.
	dropped int

	traceID    trace.TraceID
	spanID     trace.SpanID
	traceFlags trace.TraceFlags

	// resource represents the entity that collected the log.
	resource *resource.Resource

	// scope is the Scope that the Logger was created with.
	scope *instrumentation.Scope

	attributeValueLengthLimit int
	attributeValueDepthLimit  int
	attributeCountLimit       int

	// allowDupKeys specifies whether duplicate keys are allowed in key-value
	// collections.
	allowDupKeys bool

	noCmp [0]func() //nolint: unused  // This is indeed used.
}

func ( *Record) ( int) {
	.dropped += 
	if  > 0 {
		logAttrDropped()
	}
}

// EventName returns the event name.
// A log record with a non-empty event name is interpreted as an event record.
func ( *Record) () string {
	return .eventName
}

// SetEventName sets the event name.
// A log record with a non-empty event name is interpreted as an event record.
func ( *Record) ( string) {
	.eventName = 
}

// Timestamp returns the time when the log record occurred.
func ( *Record) () time.Time {
	return .timestamp
}

// SetTimestamp sets the time when the log record occurred.
func ( *Record) ( time.Time) {
	.timestamp = 
}

// ObservedTimestamp returns the time when the log record was observed.
func ( *Record) () time.Time {
	return .observedTimestamp
}

// SetObservedTimestamp sets the time when the log record was observed.
func ( *Record) ( time.Time) {
	.observedTimestamp = 
}

// Severity returns the severity of the log record.
func ( *Record) () log.Severity {
	return .severity
}

// SetSeverity sets the severity level of the log record.
func ( *Record) ( log.Severity) {
	.severity = 
}

// SeverityText returns the text of the severity (also known as the log level).
// This is the original string representation of the severity as it is known at
// the source.
func ( *Record) () string {
	return .severityText
}

// SetSeverityText sets the text of the severity (also known as the log level).
// This is the original string representation of the severity as it is known at
// the source.
func ( *Record) ( string) {
	.severityText = 
}

// Body returns the body of the log record.
func ( *Record) () attribute.Value {
	return .body
}

// SetBody sets the body of the log record.
func ( *Record) ( attribute.Value) {
	if !.allowDupKeys {
		.body, _ = attrnorm.ValueDedup()
	} else {
		.body = 
	}
}

// WalkAttributes walks through all attributes held by the log record, calling
// f for each [attribute.KeyValue] in the [Record]. Iteration stops if f returns
// false.
func ( *Record) ( func(attribute.KeyValue) bool) {
	for  := 0;  < .nFront; ++ {
		if !(.front[]) {
			return
		}
	}
	for ,  := range .back {
		if !() {
			return
		}
	}
}

// AddAttributes adds attributes to the log record.
// Unless key duplication is enabled with [WithAllowKeyDuplication], an
// attribute in attrs overwrites any attribute already added to r with the same
// key. Attributes with invalid keys are ignored.
func ( *Record) ( ...attribute.KeyValue) {
	 = filterInvalid()
	 := .AttributesLen()
	if  == 0 {
		// Avoid the more complex duplicate map lookups below.
		var  int
		if !.allowDupKeys {
			,  = dedup()
			if  > 0 {
				logKeyValuePairDropped()
			}
		}

		,  := .head()
		.addDropped()

		.addAttrs()
		return
	}

	if !.allowDupKeys {
		// Use a slice from the pool to avoid modifying the original.
		// Note, do not iterate attrs twice by just calling dedup(attrs) here.
		 := getUnique()
		defer putUnique()

		// Used to find duplicates between attrs and existing attributes in r.
		 := .attrIndex()
		defer putIndex()

		// Used to find duplicates within attrs itself.
		// The index value is the index of the element in unique.
		 := getIndex()
		defer putIndex()

		 := 0

		// Deduplicate attrs within the scope of all existing attributes.
		for ,  := range  {
			// Last-value-wins for any duplicates in attrs.
			,  := [.Key]
			if  {
				++
				logKeyValuePairDropped()
				(*)[] = 
				continue
			}

			,  = [.Key]
			if  {
				// New attrs overwrite any existing with the same key.
				++
				logKeyValuePairDropped()
				 = .applyAttrLimitsAndDedup()
				if  < 0 {
					.front[-( + 1)] = 
				} else {
					.back[] = 
				}
			} else {
				// Unique attribute.
				(*) = append(*, )
				[.Key] = len(*) - 1
			}
		}

		if  > 0 {
			 = make([]attribute.KeyValue, len(*))
			copy(, *)
		}
	}

	if .hasAttributeCountLimit() && +len() > .attributeCountLimit {
		// Truncate the now unique attributes to comply with limit.
		//
		// Do not use head(attrs, r.attributeCountLimit - n) here. If
		// (r.attributeCountLimit - n) <= 0 attrs needs to be emptied.
		 := max(0, .attributeCountLimit-)
		.addDropped(len() - )
		 = [:]
	}

	.addAttrs()
}

// attrIndex returns an index map for all attributes in the Record r. The index
// maps the attribute key to the location where the attribute is stored. If the
// value is < 0, then -(value + 1) (e.g., -1 -> 0, -2 -> 1, -3 -> 2) represents
// the index in r.front. Otherwise, the value is the exact index in r.back.
//
// The returned index is taken from the indexPool. It is the caller's
// responsibility to return the index to that pool (putIndex) when done.
func ( *Record) () map[attribute.Key]int {
	 := getIndex()
	for  := 0;  < .nFront; ++ {
		 := .front[].Key
		[] = - - 1 // stored in front: negative index.
	}
	for  := 0;  < len(.back); ++ {
		 := .back[].Key
		[] =  // stored in back: positive index.
	}
	return 
}

// addAttrs adds attrs to the Record r. This does not validate any limits or
// attribute duplication; these tasks are left to the caller to handle before
// calling addAttrs.
func ( *Record) ( []attribute.KeyValue) {
	var  int
	for  = 0;  < len() && .nFront < len(.front); ++ {
		 := []
		.front[.nFront] = .applyAttrLimitsAndDedup()
		.nFront++
	}

	// Make a copy to avoid modifying the original.
	 := len(.back)
	.back = slices.Grow(.back, len([:]))
	.back = append(.back, [:]...)
	for ,  := range .back[:] {
		.back[+] = .applyAttrLimitsAndDedup()
	}
}

// SetAttributes sets (and overrides) attributes on the log record.
// Attributes with invalid keys are ignored.
func ( *Record) ( ...attribute.KeyValue) {
	 = filterInvalid()
	var  int
	.dropped = 0
	if !.allowDupKeys {
		,  = dedup()
		if  > 0 {
			logKeyValuePairDropped()
		}
	}

	,  = .head()
	.addDropped()

	.nFront = 0
	var  int
	for  = 0;  < len() && .nFront < len(.front); ++ {
		 := []
		.front[.nFront] = .applyAttrLimitsAndDedup()
		.nFront++
	}

	.back = slices.Clone([:])
	for ,  := range .back {
		.back[] = .applyAttrLimitsAndDedup()
	}
}

// filterInvalid returns attrs without invalid attributes. The original slice is
// returned when all attributes are valid.
func filterInvalid( []attribute.KeyValue) []attribute.KeyValue {
	 := 0
	for ,  := range  {
		if .Valid() {
			++
		}
	}
	if  == len() {
		return 
	}
	logInvalidAttribute()
	if  == 0 {
		return nil
	}

	 := make([]attribute.KeyValue, 0, )
	for ,  := range  {
		if .Valid() {
			 = append(, )
		}
	}
	return 
}

// head returns the attributes r can retain along with the number dropped.
func ( *Record) ( []attribute.KeyValue) ( []attribute.KeyValue,  int) {
	if .attributeCountLimit < 0 || len() <= .attributeCountLimit {
		return , 0
	}
	if .attributeCountLimit == 0 {
		return nil, len()
	}
	return [:.attributeCountLimit], len() - .attributeCountLimit
}

func ( *Record) () bool {
	return .attributeCountLimit >= 0
}

// dedup deduplicates kvs front-to-back with the last value saved.
func dedup( []attribute.KeyValue) ( []attribute.KeyValue,  int) {
	if len() <= 1 {
		return , 0 // No deduplication needed.
	}

	 := getIndex()
	defer putIndex()
	 := getUnique()
	defer putUnique()
	for ,  := range  {
		,  := [.Key]
		if  {
			++
			(*)[] = 
		} else {
			* = append(*, )
			[.Key] = len(*) - 1
		}
	}

	if  == 0 {
		return , 0
	}

	 = make([]attribute.KeyValue, len(*))
	copy(, *)
	return , 
}

// AttributesLen returns the number of attributes in the log record.
func ( *Record) () int {
	return .nFront + len(.back)
}

// DroppedAttributes returns the number of attributes dropped due to limits
// being reached. Invalid attributes are ignored and not counted.
func ( *Record) () int {
	return .dropped
}

// TraceID returns the trace ID or an empty array.
func ( *Record) () trace.TraceID {
	return .traceID
}

// SetTraceID sets the trace ID.
func ( *Record) ( trace.TraceID) {
	.traceID = 
}

// SpanID returns the span ID or an empty array.
func ( *Record) () trace.SpanID {
	return .spanID
}

// SetSpanID sets the span ID.
func ( *Record) ( trace.SpanID) {
	.spanID = 
}

// TraceFlags returns the trace flags.
func ( *Record) () trace.TraceFlags {
	return .traceFlags
}

// SetTraceFlags sets the trace flags.
func ( *Record) ( trace.TraceFlags) {
	.traceFlags = 
}

// Resource returns the entity that collected the log.
func ( *Record) () *resource.Resource {
	return .resource
}

// InstrumentationScope returns the scope that the Logger was created with.
func ( *Record) () instrumentation.Scope {
	if .scope == nil {
		return instrumentation.Scope{}
	}
	return *.scope
}

// Clone returns a copy of the record with no shared state. The original record
// and the clone can both be modified without interfering with each other.
func ( *Record) () Record {
	 := *
	.back = slices.Clone(.back)
	return 
}

func ( *Record) ( attribute.KeyValue) attribute.KeyValue {
	switch .Value.Type() {
	case attribute.SLICE, attribute.MAP:
		 = .applyCompositeAttrDepthLimitAndDedup()
	}
	.Value = attrnorm.TruncateValue(.attributeValueLengthLimit, .Value)
	return 
}

func ( *Record) ( attribute.KeyValue) attribute.KeyValue {
	 := .attrValueDepthLimit()
	if !.allowDupKeys {
		var  bool
		if  < 0 {
			,  = attrnorm.KeyValueDedup()
		} else {
			, _,  = attrnorm.KeyValueDedupLimitDepth(, )
		}
		if  {
			logKeyValuePairDropped()
		}
	} else if  >= 0 {
		, _ = attrnorm.KeyValueLimitDepth(, )
	}
	return 
}

func ( *Record) () int {
	if .attributeValueDepthLimit == 0 {
		return defaultAttrValDepthLim
	}
	return .attributeValueDepthLimit
}