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