{"version":3,"file":"BatchLogRecordProcessorBase.cjs","names":["context","suppressTracing","ExportResultCode","BindOnceFuture","createNoopMeter","LogRecordProcessorMetrics","OTEL_COMPONENT_TYPE_VALUE_BATCHING_LOG_PROCESSOR"],"sources":["../../src/export/BatchLogRecordProcessorBase.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { context, createNoopMeter, diag } from '@opentelemetry/api';\nimport {\n  ExportResultCode,\n  globalErrorHandler,\n  BindOnceFuture,\n  suppressTracing,\n} from '@opentelemetry/core';\n\nimport type { BatchLogRecordProcessorOptions } from '../types';\nimport type { ReadWriteLogRecord } from './ReadWriteLogRecord';\nimport type { LogRecordExporter } from './LogRecordExporter';\nimport type { LogRecordProcessor } from '../LogRecordProcessor';\nimport { LogRecordProcessorMetrics } from './LogRecordProcessorMetrics';\nimport { OTEL_COMPONENT_TYPE_VALUE_BATCHING_LOG_PROCESSOR } from '../semconv';\n\n/**\n * Waits for all pending async resources in the log records to be resolved.\n */\nasync function waitForResources(\n  logRecords: ReadWriteLogRecord[]\n): Promise<void> {\n  // Log records from the same LoggerProvider usually share one Resource\n  // instance, so wait on each distinct pending resource only once.\n  let pendingResources: Set<ReadWriteLogRecord['resource']> | null = null;\n  for (let i = 0, len = logRecords.length; i < len; i++) {\n    const resource = logRecords[i].resource;\n    if (resource.asyncAttributesPending && resource.waitForAsyncAttributes) {\n      pendingResources ??= new Set();\n      pendingResources.add(resource);\n    }\n  }\n\n  if (pendingResources !== null) {\n    await Promise.all(\n      Array.from(pendingResources, resource =>\n        resource.waitForAsyncAttributes?.()\n      )\n    );\n  }\n}\n\n/**\n * Represents an export operation that handles the entire export workflow.\n */\nclass ExportOperation {\n  private readonly _exportCompleted: Promise<void>;\n  private readonly _exportScheduledPromise: Promise<void>;\n  private readonly _metrics: LogRecordProcessorMetrics;\n  private _exportScheduledResolve!: () => void;\n\n  constructor(\n    exporter: LogRecordExporter,\n    logRecords: ReadWriteLogRecord[],\n    exportTimeoutMillis: number,\n    metrics: LogRecordProcessorMetrics\n  ) {\n    this._exportScheduledPromise = new Promise<void>(resolve => {\n      this._exportScheduledResolve = resolve;\n    });\n    this._exportCompleted = this._executeExport(\n      exporter,\n      logRecords,\n      exportTimeoutMillis\n    );\n    this._metrics = metrics;\n  }\n\n  /** Get the promise that resolves when the export completes */\n  get exportCompleted(): Promise<void> {\n    return this._exportCompleted;\n  }\n\n  /** Get the promise that resolves when exporter.export() has been called */\n  get exportScheduled(): Promise<void> {\n    return this._exportScheduledPromise;\n  }\n\n  private async _executeExport(\n    exporter: LogRecordExporter,\n    logRecords: ReadWriteLogRecord[],\n    exportTimeoutMillis: number\n  ): Promise<void> {\n    try {\n      // Wait for all pending resources before exporting\n      await waitForResources(logRecords);\n\n      // Export with timeout, wrapped in suppressTracing context\n      await context.with(suppressTracing(context.active()), async () => {\n        return this._exportWithTimeout(\n          exporter,\n          logRecords,\n          exportTimeoutMillis\n        );\n      });\n    } catch (e) {\n      // ensure we never reject here, as we may call await after it has already resolved.\n      globalErrorHandler(e);\n      // resolve, as the error may have occurred before export was scheduled\n      this._exportScheduledResolve();\n    }\n  }\n\n  private async _exportWithTimeout(\n    exporter: LogRecordExporter,\n    logRecords: ReadWriteLogRecord[],\n    exportTimeoutMillis: number\n  ): Promise<void> {\n    return new Promise<void>((resolve, reject) => {\n      const timer = setTimeout(() => {\n        reject(new Error('Timeout'));\n      }, exportTimeoutMillis);\n\n      // Call exporter.export() and immediately resolve exportScheduled\n      exporter.export(logRecords, result => {\n        this._metrics.finishLogs(logRecords.length, result.error);\n        clearTimeout(timer);\n        if (result.code === ExportResultCode.SUCCESS) {\n          resolve();\n        } else {\n          reject(\n            result.error ??\n              new Error('BatchLogRecordProcessor: log record export failed')\n          );\n        }\n      });\n\n      // Resolve exportScheduled immediately after calling exporter.export()\n      this._exportScheduledResolve();\n    });\n  }\n}\n\nexport abstract class BatchLogRecordProcessorBase<\n  T extends BatchLogRecordProcessorOptions,\n> implements LogRecordProcessor\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: LogRecordExporter;\n  private readonly _metrics: LogRecordProcessorMetrics;\n\n  private _currentExport: ExportOperation | null = null;\n  private _finishedLogRecords: ReadWriteLogRecord[] = [];\n  private _timer: ReturnType<typeof setTimeout> | undefined;\n  private _shutdownOnce: BindOnceFuture<void>;\n  private _flushing: boolean = false;\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 ?? 1000;\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        'BatchLogRecordProcessor: 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-logs')\n      : createNoopMeter();\n\n    this._metrics = new LogRecordProcessorMetrics(\n      OTEL_COMPONENT_TYPE_VALUE_BATCHING_LOG_PROCESSOR,\n      meter,\n      {\n        capacity: this._maxQueueSize,\n        getQueueSize: () => this._finishedLogRecords.length,\n      }\n    );\n  }\n\n  public onEmit(logRecord: ReadWriteLogRecord): void {\n    if (this._shutdownOnce.isCalled) {\n      return;\n    }\n    this._addToBuffer(logRecord);\n  }\n\n  public forceFlush(): Promise<void> {\n    if (this._shutdownOnce.isCalled) {\n      return this._shutdownOnce.promise;\n    }\n    return this._flushAll();\n  }\n\n  /** Add a LogRecord in the buffer. */\n  private _addToBuffer(logRecord: ReadWriteLogRecord) {\n    if (this._finishedLogRecords.length >= this._maxQueueSize) {\n      this._metrics.dropLogs(1);\n      return;\n    }\n    this._finishedLogRecords.push(logRecord);\n    this._maybeStartTimer();\n  }\n\n  public shutdown(): Promise<void> {\n    return this._shutdownOnce.call();\n  }\n\n  private async _shutdown(): Promise<void> {\n    this.onShutdown();\n    await this._flushAll();\n    this._metrics.shutdown();\n    await this._exporter.shutdown();\n  }\n\n  /**\n   * Send all LogRecords to the exporter respecting the batch size limit\n   * This function is used only on forceFlush or shutdown,\n   * for all other cases _exportOneBatch should be used\n   * */\n  private async _flushAll(): Promise<void> {\n    // Guard against concurrent flushes. Concurrent .forceFlush() calls will\n    // return without waiting for the in-progress flush to finish.\n    if (this._flushing) {\n      return;\n    }\n    this._flushing = true;\n\n    // Grab the current set of finished log records, because the spec says:\n    // > ... for which the LogRecordProcessor had already received events prior to the call to ForceFlush ...\n    let toFlush = this._finishedLogRecords;\n    this._finishedLogRecords = [];\n\n    // Clear timer to prevent concurrent exports\n    this._clearTimer();\n\n    // Wait for any in-progress export to complete. Capture the reference\n    // into a local because `_exportOneBatch` may null out `this._currentExport`\n    // from its completion handler while we are awaiting below.\n    const inFlight = this._currentExport;\n    if (inFlight !== null) {\n      // speed up execution for current export\n      await this._exporter.forceFlush();\n      await inFlight.exportCompleted;\n      this._currentExport = null;\n    }\n\n    // Now flush all batches sequentially to avoid race conditions\n    while (toFlush.length > 0) {\n      let batch;\n      if (toFlush.length <= this._maxExportBatchSize) {\n        batch = toFlush;\n        toFlush = [];\n      } else {\n        batch = toFlush.splice(0, this._maxExportBatchSize);\n      }\n\n      const exportOp = new ExportOperation(\n        this._exporter,\n        batch,\n        this._exportTimeoutMillis,\n        this._metrics\n      );\n      this._currentExport = exportOp;\n\n      // await export scheduled, then force flush exporter to speed up export\n      try {\n        await exportOp.exportScheduled;\n        await this._exporter.forceFlush();\n        await exportOp.exportCompleted;\n      } catch (e) {\n        globalErrorHandler(e);\n      } finally {\n        this._currentExport = null;\n      }\n    }\n\n    this._flushing = false;\n    this._maybeStartTimer();\n  }\n\n  /**\n   * Extracts one batch from the buffer.\n   * Returns null if buffer is empty.\n   */\n  private _extractBatch(): ReadWriteLogRecord[] | null {\n    if (this._finishedLogRecords.length === 0) {\n      return null;\n    }\n\n    if (this._finishedLogRecords.length <= this._maxExportBatchSize) {\n      const batch = this._finishedLogRecords;\n      this._finishedLogRecords = [];\n      return batch;\n    } else {\n      return this._finishedLogRecords.splice(0, this._maxExportBatchSize);\n    }\n  }\n\n  private _exportOneBatch(): void {\n    this._clearTimer();\n\n    const logRecords = this._extractBatch();\n    if (logRecords === null) {\n      return;\n    }\n\n    const exportOp = new ExportOperation(\n      this._exporter,\n      logRecords,\n      this._exportTimeoutMillis,\n      this._metrics\n    );\n    this._currentExport = exportOp;\n\n    // Handle completion asynchronously\n    exportOp.exportCompleted\n      .then(() => {\n        this._currentExport = null;\n        this._maybeStartTimer();\n      })\n      .catch(error => {\n        this._currentExport = null;\n        globalErrorHandler(error);\n        this._maybeStartTimer();\n      });\n  }\n\n  private _maybeStartTimer() {\n    if (this._shutdownOnce.isCalled) {\n      return;\n    }\n\n    if (this._flushing) {\n      return;\n    }\n\n    if (this._finishedLogRecords.length === 0) {\n      return;\n    }\n\n    if (this._currentExport !== null) {\n      return;\n    }\n\n    // If batch is full, export immediately\n    if (this._finishedLogRecords.length >= this._maxExportBatchSize) {\n      this._exportOneBatch();\n      return;\n    }\n\n    // If timer is already set, don't set another one\n    if (this._timer !== undefined) {\n      return;\n    }\n\n    // Set timer for scheduled export\n    this._timer = setTimeout(() => {\n      this._timer = undefined;\n      this._exportOneBatch();\n    }, this._scheduledDelayMillis);\n\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 = tim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