/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import type { Context } from '@opentelemetry/api'; import { context, createNoopMeter, diag, TraceFlags } from '@opentelemetry/api'; import { BindOnceFuture, ExportResultCode, globalErrorHandler, suppressTracing, } from '@opentelemetry/core'; import type { Span } from '../Span'; import type { SpanProcessor } from '../SpanProcessor'; import type { BatchSpanProcessorOptions } from '../types'; import type { ReadableSpan } from './ReadableSpan'; import type { SpanExporter } from './SpanExporter'; import { SpanProcessorMetrics } from './SpanProcessorMetrics'; import { OTEL_COMPONENT_TYPE_VALUE_BATCHING_SPAN_PROCESSOR } from '../semconv'; /** * Implementation of the {@link SpanProcessor} that batches spans exported by * the SDK then pushes them to the exporter pipeline. */ export abstract class BatchSpanProcessorBase< T extends BatchSpanProcessorOptions, > implements SpanProcessor { private readonly _maxExportBatchSize: number; private readonly _maxQueueSize: number; private readonly _scheduledDelayMillis: number; private readonly _exportTimeoutMillis: number; private readonly _exporter: SpanExporter; private readonly _metrics: SpanProcessorMetrics; private _isExporting = false; private _finishedSpans: ReadableSpan[] = []; private _timer: ReturnType | undefined; private _shutdownOnce: BindOnceFuture; private _droppedSpansCount: number = 0; constructor(options: T) { this._exporter = options.exporter; this._maxExportBatchSize = options.maxExportBatchSize ?? 512; this._maxQueueSize = options.maxQueueSize ?? 2048; this._scheduledDelayMillis = options.scheduledDelayMillis ?? 5000; this._exportTimeoutMillis = options.exportTimeoutMillis ?? 30000; this._shutdownOnce = new BindOnceFuture(this._shutdown, this); if (this._maxExportBatchSize > this._maxQueueSize) { diag.warn( 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize' ); this._maxExportBatchSize = this._maxQueueSize; } const meter = options.selfObsMeterProvider ? options.selfObsMeterProvider.getMeter('@opentelemetry/sdk-trace') : createNoopMeter(); this._metrics = new SpanProcessorMetrics( OTEL_COMPONENT_TYPE_VALUE_BATCHING_SPAN_PROCESSOR, meter, { capacity: this._maxQueueSize, getQueueSize: () => this._finishedSpans.length, } ); } forceFlush(): Promise { if (this._shutdownOnce.isCalled) { return this._shutdownOnce.promise; } return this._flushAll(); } // does nothing. onStart(_span: Span, _parentContext: Context): void {} onEnd(span: ReadableSpan): void { if (this._shutdownOnce.isCalled) { return; } if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) { return; } this._addToBuffer(span); } shutdown(): Promise { return this._shutdownOnce.call(); } private _shutdown() { return Promise.resolve() .then(() => { return this.onShutdown(); }) .then(() => { return this._flushAll(); }) .then(() => { this._metrics.shutdown(); return this._exporter.shutdown(); }); } /** Add a span in the buffer. */ private _addToBuffer(span: ReadableSpan) { if (this._finishedSpans.length >= this._maxQueueSize) { // limit reached, drop span if (this._droppedSpansCount === 0) { diag.debug('maxQueueSize reached, dropping spans'); } this._droppedSpansCount++; this._metrics.dropSpans(1); return; } if (this._droppedSpansCount > 0) { // some spans were dropped, log once with count of spans dropped diag.warn( `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached` ); this._droppedSpansCount = 0; } this._finishedSpans.push(span); this._maybeStartTimer(); } /** * Send all spans to the exporter respecting the batch size limit * This function is used only on forceFlush or shutdown, * for all other cases _flush should be used * */ private _flushAll(): Promise { return new Promise((resolve, reject) => { const promises = []; // calculate number of batches const count = Math.ceil( this._finishedSpans.length / this._maxExportBatchSize ); for (let i = 0, j = count; i < j; i++) { promises.push(this._flushOneBatch()); } Promise.all(promises) .then(() => { resolve(); }) .catch(reject); }); } private _flushOneBatch(): Promise { this._clearTimer(); if (this._finishedSpans.length === 0) { return Promise.resolve(); } return new Promise((resolve, reject) => { const timer = setTimeout(() => { // don't wait anymore for export, this way the next batch can start reject(new Error('Timeout')); }, this._exportTimeoutMillis); // prevent downstream exporter calls from generating spans context.with(suppressTracing(context.active()), () => { // Reset the finished spans buffer here because the next invocations of the _flush method // could pass the same finished spans to the exporter if the buffer is cleared // outside the execution of this callback. let spans: ReadableSpan[]; if (this._finishedSpans.length <= this._maxExportBatchSize) { spans = this._finishedSpans; this._finishedSpans = []; } else { spans = this._finishedSpans.splice(0, this._maxExportBatchSize); } const doExport = () => this._exporter.export(spans, result => { clearTimeout(timer); this._metrics.finishSpans(spans.length, result.error); if (result.code === ExportResultCode.SUCCESS) { resolve(); } else { reject( result.error ?? new Error('BatchSpanProcessor: span export failed') ); } }); // Spans from the same TracerProvider usually share one Resource // instance, so wait on each distinct pending resource only once. let pendingResources: Set<(typeof spans)[number]['resource']> | null = null; for (let i = 0, len = spans.length; i < len; i++) { const resource = spans[i].resource; if ( resource.asyncAttributesPending && resource.waitForAsyncAttributes ) { pendingResources ??= new Set(); pendingResources.add(resource); } } // Avoid scheduling a promise to make the behavior more predictable and easier to test if (pendingResources === null) { doExport(); } else { Promise.all( Array.from(pendingResources, resource => resource.waitForAsyncAttributes?.() ) ).then(doExport, err => { globalErrorHandler(err); reject(err); }); } }); }); } private _maybeStartTimer() { if (this._isExporting) return; const flush = () => { this._isExporting = true; this._flushOneBatch() .finally(() => { this._isExporting = false; if (this._finishedSpans.length > 0) { this._clearTimer(); this._maybeStartTimer(); } }) .catch(e => { this._isExporting = false; globalErrorHandler(e); }); }; // we only wait if the queue doesn't have enough elements yet if (this._finishedSpans.length >= this._maxExportBatchSize) { return flush(); } if (this._timer !== undefined) return; this._timer = setTimeout(() => flush(), this._scheduledDelayMillis); unrefTimer(this._timer); } private _clearTimer() { if (this._timer !== undefined) { clearTimeout(this._timer); this._timer = undefined; } } protected abstract onShutdown(): void; } // Node.js timers keep the process alive unless unref'd; browsers return a number. function unrefTimer(timer: ReturnType): void { const handle = timer as number | { unref?: () => void }; if (typeof handle !== 'number') handle.unref?.(); }