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