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

package log

import (
	
	
	
	
	
	

	
	
	
	
)

const (
	dfltMaxQSize        = 2048
	dfltExpInterval     = time.Second
	dfltExpTimeout      = 30 * time.Second
	dfltExpMaxBatchSize = 512

	envarMaxQSize        = "OTEL_BLRP_MAX_QUEUE_SIZE"
	envarExpInterval     = "OTEL_BLRP_SCHEDULE_DELAY"
	envarExpTimeout      = "OTEL_BLRP_EXPORT_TIMEOUT"
	envarExpMaxBatchSize = "OTEL_BLRP_MAX_EXPORT_BATCH_SIZE"
)

// This is a compile-time check that BatchProcessor implements Processor.
var _ Processor = (*BatchProcessor)(nil)

// BatchProcessor is a processor that exports batches of log records.
//
// Use [NewBatchProcessor] to create a BatchProcessor. An empty BatchProcessor
// is shut down by default, so no records will be batched or exported.
type BatchProcessor struct {
	// A single goroutine owns dequeueing and all exporter calls. OnEmit only
	// writes to the bounded queue and signals that goroutine. Consequently,
	// exporter backpressure blocks the exporter goroutine instead of causing
	// another goroutine to retry without making progress.
	exporter Exporter

	// q is the active queue of records that have not yet been exported.
	q *queue
	// batchSize is the maximum number of records in a scheduled export.
	batchSize int

	// exportTrigger is a coalesced signal that records are ready to export.
	exportTrigger chan struct{}
	// flush serializes ForceFlush requests through the worker.
	flush chan batchProcessorRequest
	// shutdown accepts the single Shutdown request. It is separate from flush
	// so shutdown cannot be blocked behind concurrent ForceFlush callers.
	shutdown chan batchProcessorRequest
	// done is closed by the exporter goroutine after exporter shutdown.
	done chan struct{}

	// stopped holds the stopped state of the BatchProcessor.
	stopped atomic.Bool

	// inst is the instrumentation for observability (nil when disabled).
	inst *observ.BLP

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

type batchProcessorRequest struct {
	ctx  context.Context
	resp chan<- error
}

func ( batchProcessorRequest) ( error) {
	.resp <- 
}

// NewBatchProcessor decorates the provided exporter
// so that the log records are batched before they are exported.
//
// Calls to the exporter's Export, ForceFlush, and Shutdown methods are
// synchronized and never invoked concurrently.
func ( Exporter,  ...BatchProcessorOption) *BatchProcessor {
	 := newBatchConfig()
	if  == nil {
		// Do not panic on nil export.
		 = defaultNoopExporter
	}

	 := &BatchProcessor{
		q:             newQueue(.maxQSize.Value),
		batchSize:     .expMaxBatchSize.Value,
		exportTrigger: make(chan struct{}, 1),
		flush:         make(chan batchProcessorRequest),
		shutdown:      make(chan batchProcessorRequest, 1),
		done:          make(chan struct{}),
	}

	var  error
	.inst,  = observ.NewBLP(
		counter.NextExporterID(),
		func() int64 { return int64(.q.Len()) },
		int64(.maxQSize.Value),
	)
	if  != nil {
		otel.Handle()
	}

	// Wrap exporter with metrics recording if observability is enabled.
	// This must be the innermost wrapper (closest to user exporter) to record
	// metrics just before calling the actual exporter.
	if .inst != nil {
		 = newMetricsExporter(, .inst)
	}

	// Order is important here. Wrap the timeoutExporter with the chunkExporter
	// to ensure each export completes in timeout (instead of all chunked
	// exports).
	 = newTimeoutExporter(, .expTimeout.Value)
	// Use a chunkExporter to ensure ForceFlush and Shutdown calls are batched
	// appropriately on export.
	 = newChunkExporter(, .expMaxBatchSize.Value)

	.exporter = 
	.process(.expInterval.Value)
	return 
}

// process starts the goroutine that owns dequeueing and all exporter calls.
func ( *BatchProcessor) ( time.Duration) {
	go func() {
		 := time.NewTimer()
		defer .Stop()
		// The worker owns and reuses buf. Exporters must not retain the slice
		// passed to them, so it is safe to refill after Export returns.
		 := make([]Record, .batchSize)

		for {
			// Probe shutdown by itself first. This makes an already queued terminal
			// request win over every other ready case. Closing done before replying
			// also means a successful Shutdown response observes a stopped worker.
			select {
			case  := <-.shutdown:
				 := .shutdownExporter(.ctx)
				close(.done)
				.respond()
				return
			default:
			}

			// With no queued shutdown, service a waiting ForceFlush before ordinary
			// export wakes. The default keeps this priority check non-blocking.
			// Shutdown remains selectable in case it arrived after the first probe.
			select {
			case  := <-.shutdown:
				 := .shutdownExporter(.ctx)
				close(.done)
				.respond()
				return
			case  := <-.flush:
				 := .flushExporter(.ctx)
				.respond()
				continue
			default:
			}

			// No lifecycle request was waiting, so block on the complete event set.
			// Both timer and size-triggered exports start a new interval window.
			select {
			case  := <-.shutdown:
				 := .shutdownExporter(.ctx)
				close(.done)
				.respond()
				return
			case  := <-.flush:
				 := .flushExporter(.ctx)
				.respond()
			case <-.C:
				resetTimer(, )
				.exportBatch()
			case <-.exportTrigger:
				resetTimer(, )
				.exportBatch()
			}
		}
	}()
}

func resetTimer( *time.Timer,  time.Duration) {
	// Handle both GODEBUG=asynctimerchan=[0|1] properly.
	if !.Stop() {
		select {
		case <-.C:
		default:
		}
	}
	.Reset()
}

func ( *BatchProcessor) ( []Record) {
	.logDroppedRecords()
	,  := .q.Dequeue()
	if  == 0 {
		return
	}

	 := .exporter.Export(context.Background(), [:])
	clear([:])
	if  != nil {
		otel.Handle()
	}
	if  >= .batchSize {
		.triggerExport()
	}
}

func ( *BatchProcessor) ( context.Context) error {
	if  := .Err();  != nil {
		return 
	}
	.logDroppedRecords()
	 := .q.Flush()
	 := .exporter.Export(, )
	clear()
	if  := .Err();  != nil {
		return errors.Join(, )
	}
	return errors.Join(, .exporter.ForceFlush())
}

func ( *BatchProcessor) ( context.Context) error {
	.logDroppedRecords()
	 := .q.Flush()
	 := .exporter.Export(, )
	clear()
	if  := .Err();  != nil {
		 = errors.Join(, )
	} else {
		 = errors.Join(, .exporter.ForceFlush())
	}
	 = errors.Join(, .exporter.Shutdown())
	if .inst != nil {
		 = errors.Join(, .inst.Shutdown())
	}
	return 
}

func ( *BatchProcessor) () {
	if  := .q.Dropped();  > 0 {
		if .inst != nil {
			.inst.ProcessedQueueFull(context.Background(), int64(min(math.MaxInt64, ))) // nolint:gosec
		}
		global.Warn("dropped log records", "dropped", )
	}
}

func ( *BatchProcessor) () {
	select {
	case .exportTrigger <- struct{}{}:
	default:
	}
}

// Enabled returns true, indicating this Processor will process all records.
func (*BatchProcessor) (context.Context, EnabledParameters) bool {
	return true
}

// OnEmit batches the provided log record.
func ( *BatchProcessor) ( context.Context,  *Record) error {
	if .stopped.Load() || .q == nil {
		return nil
	}
	// The record is cloned so that changes done by subsequent processors
	// are not going to lead to a data race.
	if ,  := .q.Enqueue(.Clone());  &&  >= .batchSize {
		.triggerExport()
	}
	return nil
}

// Shutdown flushes queued log records and the decorated exporter before
// shutting it down.
func ( *BatchProcessor) ( context.Context) error {
	if .stopped.Swap(true) || .q == nil {
		return nil
	}

	.q.Close()
	 := make(chan error, 1)
	.shutdown <- batchProcessorRequest{ctx: , resp: }
	if  := .Err();  != nil {
		return 
	}
	select {
	case  := <-:
		return 
	case <-.Done():
		return .Err()
	}
}

// ForceFlush flushes queued log records and flushes the decorated exporter.
func ( *BatchProcessor) ( context.Context) error {
	if .stopped.Load() || .q == nil {
		return nil
	}
	if  := .Err();  != nil {
		return 
	}

	 := make(chan error, 1)
	 := batchProcessorRequest{ctx: , resp: }
	select {
	case .flush <- :
	case <-.done:
		return nil
	case <-.Done():
		return .Err()
	}

	select {
	case  := <-:
		return 
	case <-.Done():
		return .Err()
	}
}

// queue holds a queue of logging records.
//
// When the queue becomes full, the oldest records in the queue are
// overwritten.
type queue struct {
	sync.Mutex

	dropped     atomic.Uint64
	cap, len    int
	read, write *ring
	closed      bool
}

func newQueue( int) *queue {
	 := newRing()
	return &queue{
		cap:   ,
		read:  ,
		write: ,
	}
}

func ( *queue) () int {
	.Lock()
	defer .Unlock()

	return .len
}

// Dropped returns the number of Records dropped during enqueueing since the
// last time Dropped was called.
func ( *queue) () uint64 {
	return .dropped.Swap(0)
}

// Enqueue adds r to the queue. The queue size, including the addition of r, is
// returned.
//
// If enqueueing r would exceed the capacity of q, the oldest Record held in q
// will be dropped and r will be retained.
func ( *queue) ( Record) (int, bool) {
	.Lock()
	defer .Unlock()

	if .closed {
		return .len, false
	}

	.write.Value = 
	.write = .write.Next()

	.len++
	if .len > .cap {
		// Overflow. Advance read to be the new "oldest".
		.len = .cap
		.read = .read.Next()
		.dropped.Add(1)
	}
	return .len, true
}

// Dequeue removes up to len(buf) records from the queue and copies them into
// buf. The number copied and the number remaining are returned.
func ( *queue) ( []Record) (int, int) {
	.Lock()
	defer .Unlock()

	 := min(len(), .len)
	for  := range  {
		[] = .read.Value // nolint:gosec // n is bounded by len(buf)
		.read.Value = Record{}
		.read = .read.Next()
	}
	.len -= 
	return , .len
}

// Flush returns all the Records held in the queue and resets it to empty.
func ( *queue) () []Record {
	.Lock()
	defer .Unlock()

	return .flush()
}

// Close stops the queue from accepting records.
func ( *queue) () {
	.Lock()
	defer .Unlock()

	.closed = true
}

func ( *queue) () []Record {
	 := make([]Record, .len)
	for  := range  {
		[] = .read.Value
		.read.Value = Record{}
		.read = .read.Next()
	}
	.len = 0

	return 
}

type batchConfig struct {
	maxQSize        setting[int]
	expInterval     setting[time.Duration]
	expTimeout      setting[time.Duration]
	expMaxBatchSize setting[int]
}

func newBatchConfig( []BatchProcessorOption) batchConfig {
	var  batchConfig
	for ,  := range  {
		 = .apply()
	}

	.maxQSize = .maxQSize.Resolve(
		clearLessThanOne[int](),
		getenv[int](envarMaxQSize),
		clearLessThanOne[int](), // nolint:gocritic // the function argument is duplicated on purpose
		fallback[int](dfltMaxQSize),
	)
	.expInterval = .expInterval.Resolve(
		clearLessThanOne[time.Duration](),
		getenv[time.Duration](envarExpInterval),
		clearLessThanOne[time.Duration](), // nolint:gocritic // the function argument is duplicated on purpose
		fallback[time.Duration](dfltExpInterval),
	)
	.expTimeout = .expTimeout.Resolve(
		clearLessThanOne[time.Duration](),
		getenv[time.Duration](envarExpTimeout),
		clearLessThanOne[time.Duration](), // nolint:gocritic // the function argument is duplicated on purpose
		fallback[time.Duration](dfltExpTimeout),
	)
	.expMaxBatchSize = .expMaxBatchSize.Resolve(
		clearLessThanOne[int](),
		getenv[int](envarExpMaxBatchSize),
		clearLessThanOne[int](), // nolint:gocritic // the function argument is duplicated on purpose
		fallback[int](dfltExpMaxBatchSize),
		clampMax[int](.maxQSize.Value),
	)
	return 
}

// BatchProcessorOption applies a configuration to a [BatchProcessor].
type BatchProcessorOption interface {
	apply(batchConfig) batchConfig
}

type batchOptionFunc func(batchConfig) batchConfig

func ( batchOptionFunc) ( batchConfig) batchConfig {
	return ()
}

// WithMaxQueueSize sets the maximum queue size used by the Batcher.
// After the size is reached, log records are dropped.
//
// If the OTEL_BLRP_MAX_QUEUE_SIZE environment variable is set and this option
// is not passed, the value of that variable will be used.
//
// By default, if the environment variable is not set and this option is not
// passed, 2048 will be used.
// The default value is also used when the provided value is less than one.
func ( int) BatchProcessorOption {
	return batchOptionFunc(func( batchConfig) batchConfig {
		.maxQSize = newSetting()
		return 
	})
}

// WithExportInterval sets the maximum duration between batched exports.
//
// If the OTEL_BLRP_SCHEDULE_DELAY environment variable is set and this option
// is not passed, the value of that variable will be used.
//
// By default, if the environment variable is not set and this option is not
// passed, 1s will be used.
// The default value is also used when the provided value is less than one.
func ( time.Duration) BatchProcessorOption {
	return batchOptionFunc(func( batchConfig) batchConfig {
		.expInterval = newSetting()
		return 
	})
}

// WithExportTimeout sets the duration after which a batched export is canceled.
//
// If the OTEL_BLRP_EXPORT_TIMEOUT environment variable is set and this option
// is not passed, the value of that variable will be used.
//
// By default, if the environment variable is not set and this option is not
// passed, 30s will be used.
// The default value is also used when the provided value is less than one.
func ( time.Duration) BatchProcessorOption {
	return batchOptionFunc(func( batchConfig) batchConfig {
		.expTimeout = newSetting()
		return 
	})
}

// WithExportMaxBatchSize sets the maximum batch size of every export.
// A batch will be split into multiple exports so that none exceed this size.
//
// If the OTEL_BLRP_MAX_EXPORT_BATCH_SIZE environment variable is set and this
// option is not passed, the value of that variable will be used.
//
// By default, if the environment variable is not set and this option is not
// passed, 512 or the maximum queue size, if smaller, will be used.
// The default value is also used when the provided value is less than one.
// The effective batch size will not exceed the configured maximum queue size.
func ( int) BatchProcessorOption {
	return batchOptionFunc(func( batchConfig) batchConfig {
		.expMaxBatchSize = newSetting()
		return 
	})
}

// WithExportBufferSize is retained for source compatibility and has no effect.
// The processor no longer maintains a separately configurable export-request
// buffer. [WithMaxQueueSize] bounds the pending-record queue.
//
// Deprecated: This option is no longer used.
func ( int) BatchProcessorOption {
	return batchOptionFunc(func( batchConfig) batchConfig {
		return 
	})
}