/**
 * TrackingExporter base class for vendor-specific observability exporters.
 *
 * Provides common functionality for caching trace data in memory, handling
 * out-of-order span arrival via queuing, delayed cleanup, and memory management.
 */
import type { TracingEvent, AnyExportedSpan, SpanErrorInfo } from '@mastra/core/observability';
import type { BaseExporterConfig } from './base.js';
import { BaseExporter } from './base.js';
/**
 * Represents an event waiting in the early queue for its dependencies.
 */
export interface QueuedEvent {
    /** The original tracing event */
    event: TracingEvent;
    /** What this event is waiting for: 'root' or a specific parentSpanId */
    waitingFor: 'root' | string;
    /** Number of times we've attempted to process this event */
    attempts: number;
    /** When this event was queued */
    queuedAt: Date;
}
export interface TrackingExporterConfig extends BaseExporterConfig {
    /**
     * Maximum number of attempts to process a queued event before dropping it.
     * @default 5
     */
    earlyQueueMaxAttempts?: number;
    /**
     * Time-to-live in milliseconds for queued events. Events older than this are dropped.
     * @default 30000 (30 seconds)
     */
    earlyQueueTTLMs?: number;
    /**
     * Delay in milliseconds before cleaning up trace data after all spans have ended.
     * This allows late-arriving data to still be processed.
     * @default 30000 (30 seconds)
     */
    traceCleanupDelayMs?: number;
    /**
     * Soft cap on number of traces with activeSpanCount == 0 awaiting cleanup.
     * When exceeded, oldest pending traces are force-cleaned.
     * @default 100
     */
    maxPendingCleanupTraces?: number;
    /**
     * Hard cap on total number of traces (including active ones).
     * When exceeded, oldest traces are killed (active spans aborted).
     * Safety valve for memory leaks.
     * @default 500
     */
    maxTotalTraces?: number;
}
/**
 * Per-trace data container that stores vendor-specific span/event objects and
 * manages the waiting queue for out-of-order event processing.
 *
 * @typeParam TRootData - Vendor-specific root/trace object type (e.g., Langfuse trace, Braintrust logger)
 * @typeParam TSpanData - Vendor-specific span object type (e.g., LangSmith RunTree, Braintrust Span)
 * @typeParam TEventData - Vendor-specific event object type
 * @typeParam TMetadata - Vendor-specific metadata type for spans
 */
export declare class TraceData<TRootData, TSpanData, TEventData, TMetadata> {
    #private;
    /** When this trace data was created, used for cap enforcement */
    readonly createdAt: Date;
    constructor();
    /**
     * Check if this trace has a root span registered.
     * @returns True if addRoot() has been called
     */
    hasRoot(): boolean;
    /**
     * Register the root span for this trace.
     * @param args.rootId - The span ID of the root span
     * @param args.rootData - The vendor-specific root object
     */
    addRoot(args: {
        rootId: string;
        rootData: TRootData;
    }): void;
    /**
     * Get the vendor-specific root object.
     * @returns The root object, or undefined if not yet set
     */
    getRoot(): TRootData | undefined;
    /**
     * Check if a span with isRootSpan=true has been successfully processed.
     * Set via addRoot() or markRootSpanProcessed().
     * @returns True if the root span has been processed
     */
    isRootProcessed(): boolean;
    /**
     * Mark that the root span has been processed.
     * Used by exporters with skipBuildRootTask=true where root goes through _buildSpan
     * instead of _buildRoot.
     */
    markRootSpanProcessed(): void;
    /**
     * Store an arbitrary value in per-trace storage.
     * @param key - Storage key
     * @param value - Value to store
     */
    setExtraValue(key: string, value: unknown): void;
    /**
     * Check if a key exists in per-trace storage.
     * @param key - Storage key
     * @returns True if the key exists
     */
    hasExtraValue(key: string): boolean;
    /**
     * Get a value from per-trace storage.
     * @param key - Storage key
     * @returns The stored value, or undefined if not found
     */
    getExtraValue(key: string): unknown;
    /**
     * Add an event to the waiting queue.
     * @param args.event - The tracing event to queue
     * @param args.waitingFor - 'root' or a specific parentSpanId
     * @param args.attempts - Optional: preserve attempts count when re-queuing
     * @param args.queuedAt - Optional: preserve original queue time when re-queuing
     */
    addToWaitingQueue(args: {
        event: TracingEvent;
        waitingFor: 'root' | string;
        attempts?: number;
        queuedAt?: Date;
    }): void;
    /**
     * Get all events waiting for the root span.
     * Returns a copy of the internal array.
     */
    getEventsWaitingForRoot(): QueuedEvent[];
    /**
     * Get all events waiting for a specific parent span.
     * Returns a copy of the internal array.
     */
    getEventsWaitingFor(args: {
        spanId: string;
    }): QueuedEvent[];
    /**
     * Clear the waiting-for-root queue.
     */
    clearWaitingForRoot(): void;
    /**
     * Clear the waiting queue for a specific parent span.
     */
    clearWaitingFor(args: {
        spanId: string;
    }): void;
    /**
     * Get total count of events in all waiting queues.
     */
    waitingQueueSize(): number;
    /**
     * Get all queued events across all waiting queues.
     * Used for cleanup and logging orphaned events.
     * @returns Array of all queued events
     */
    getAllQueuedEvents(): QueuedEvent[];
    /**
     * Record the parent-child relationship for a span.
     * @param args.spanId - The child span ID
     * @param args.parentSpanId - The parent span ID, or undefined for root spans
     */
    addBranch(args: {
        spanId: string;
        parentSpanId: string | undefined;
    }): void;
    /**
     * Get the parent span ID for a given span.
     * @param args.spanId - The span ID to look up
     * @returns The parent span ID, or undefined if root or not found
     */
    getParentId(args: {
        spanId: string;
    }): string | undefined;
    /**
     * Register a span and mark it as active.
     * @param args.spanId - The span ID
     * @param args.spanData - The vendor-specific span object
     */
    addSpan(args: {
        spanId: string;
        spanData: TSpanData;
    }): void;
    /**
     * Check if a span exists (regardless of active state).
     * @param args.spanId - The span ID to check
     * @returns True if the span exists
     */
    hasSpan(args: {
        spanId: string;
    }): boolean;
    /**
     * Get a span by ID.
     * @param args.spanId - The span ID to look up
     * @returns The vendor-specific span object, or undefined if not found
     */
    getSpan(args: {
        spanId: string;
    }): TSpanData | undefined;
    /**
     * Mark a span as ended (no longer active).
     * @param args.spanId - The span ID to mark as ended
     */
    endSpan(args: {
        spanId: string;
    }): void;
    /**
     * Check if a span is currently active (started but not ended).
     * @param args.spanId - The span ID to check
     * @returns True if the span is active
     */
    isActiveSpan(args: {
        spanId: string;
    }): boolean;
    /**
     * Get the count of currently active spans.
     * @returns Number of active spans
     */
    activeSpanCount(): number;
    /**
     * Get all active span IDs.
     * @returns Array of active span IDs
     */
    get activeSpanIds(): string[];
    /**
     * Register an event.
     * @param args.eventId - The event ID
     * @param args.eventData - The vendor-specific event object
     */
    addEvent(args: {
        eventId: string;
        eventData: TEventData;
    }): void;
    /**
     * Store vendor-specific metadata for a span.
     * Note: This overwrites any existing metadata for the span.
     * @param args.spanId - The span ID
     * @param args.metadata - The vendor-specific metadata
     */
    addMetadata(args: {
        spanId: string;
        metadata: TMetadata;
    }): void;
    /**
     * Get vendor-specific metadata for a span.
     * @param args.spanId - The span ID
     * @returns The metadata, or undefined if not found
     */
    getMetadata(args: {
        spanId: string;
    }): TMetadata | undefined;
    /**
     * Get the parent span or event for a given span.
     * Looks up in both spans and events maps.
     * @param args.span - The span to find the parent for
     * @returns The parent span/event object, or undefined if root or not found
     */
    getParent(args: {
        span: AnyExportedSpan;
    }): TSpanData | TEventData | undefined;
    /**
     * Get the parent span/event or fall back to the root object.
     * Useful for vendors that attach child spans to either parent spans or the trace root.
     * @param args.span - The span to find the parent for
     * @returns The parent span/event, the root object, or undefined
     */
    getParentOrRoot(args: {
        span: AnyExportedSpan;
    }): TRootData | TSpanData | TEventData | undefined;
}
/**
 * Abstract base class for vendor-specific observability exporters that need to
 * track trace and span state in memory.
 *
 * This class provides:
 * - Per-trace data caching via TraceData instances
 * - Out-of-order span handling via waiting queues (for when children arrive before parents)
 * - Delayed cleanup to handle late-arriving data
 * - Memory management via configurable soft/hard caps on trace count
 * - Graceful shutdown with span abortion
 *
 * Subclasses must implement the abstract methods to handle vendor-specific
 * span/event creation and lifecycle.
 *
 * @typeParam TRootData - Vendor-specific root/trace object type
 * @typeParam TSpanData - Vendor-specific span object type
 * @typeParam TEventData - Vendor-specific event object type
 * @typeParam TMetadata - Vendor-specific metadata type
 * @typeParam TConfig - Configuration type (must extend TrackingExporterConfig)
 *
 * @example
 * ```typescript
 * class MyExporter extends TrackingExporter<MyRoot, MySpan, MyEvent, MyMeta, MyConfig> {
 *   name = 'my-exporter';
 *
 *   protected async _buildRoot(args) { ... }
 *   protected async _buildSpan(args) { ... }
 *   protected async _buildEvent(args) { ... }
 *   protected async _updateSpan(args) { ... }
 *   protected async _finishSpan(args) { ... }
 *   protected async _abortSpan(args) { ... }
 * }
 * ```
 */
export declare abstract class TrackingExporter<TRootData, TSpanData, TEventData, TMetadata, TConfig extends TrackingExporterConfig> extends BaseExporter {
    #private;
    /** Subclass configuration with resolved values */
    protected readonly config: TConfig;
    constructor(config: TConfig);
    /**
     * Hook called before processing each tracing event.
     * Override to transform or enrich the event before processing.
     *
     * Note: The customSpanFormatter is applied at the BaseExporter level before this hook.
     * Subclasses can override this to add additional pre-processing logic.
     *
     * @param event - The incoming tracing event
     * @returns The (possibly modified) event to process
     */
    protected _preExportTracingEvent(event: TracingEvent): Promise<TracingEvent>;
    /**
     * Hook called after processing each tracing event.
     * Override to perform post-processing actions like flushing.
     */
    protected _postExportTracingEvent(): Promise<void>;
    /**
     * Build the vendor-specific root/trace object for a new trace.
     * Called when the first span of a trace arrives (if skipBuildRootTask is false).
     *
     * @param args.span - The root span data
     * @param args.traceData - The trace data container
     * @returns The vendor-specific root object, or undefined if unable to create
     */
    protected abstract _buildRoot(args: {
        span: AnyExportedSpan;
        traceData: TraceData<TRootData, TSpanData, TEventData, TMetadata>;
    }): Promise<TRootData | undefined>;
    /**
     * Build a vendor-specific event object.
     * Events are zero-duration spans used for logging discrete occurrences.
     *
     * @param args.span - The event span data
     * @param args.traceData - The trace data container
     * @returns The vendor-specific event object, or undefined if parent not ready
     */
    protected abstract _buildEvent(args: {
        span: AnyExportedSpan;
        traceData: TraceData<TRootData, TSpanData, TEventData, TMetadata>;
    }): Promise<TEventData | undefined>;
    /**
     * Build a vendor-specific span object when a span starts.
     * Should create the span in the vendor system and return the SDK object.
     *
     * @param args.span - The span data
     * @param args.traceData - The trace data container
     * @returns The vendor-specific span object, or undefined if parent not ready
     */
    protected abstract _buildSpan(args: {
        span: AnyExportedSpan;
        traceData: TraceData<TRootData, TSpanData, TEventData, TMetadata>;
    }): Promise<TSpanData | undefined>;
    /**
     * Update a span with new data (called on span_updated events).
     * Should update the vendor span with any new attributes, metrics, etc.
     *
     * @param args.span - The updated span data
     * @param args.traceData - The trace data container
     */
    protected abstract _updateSpan(args: {
        span: AnyExportedSpan;
        traceData: TraceData<TRootData, TSpanData, TEventData, TMetadata>;
    }): Promise<void>;
    /**
     * Finish a span (called on span_ended events).
     * Should close/end the span in the vendor system with final data.
     *
     * @param args.span - The ended span data
     * @param args.traceData - The trace data container
     */
    protected abstract _finishSpan(args: {
        span: AnyExportedSpan;
        traceData: TraceData<TRootData, TSpanData, TEventData, TMetadata>;
    }): Promise<void>;
    /**
     * Abort a span due to shutdown or memory cap enforcement.
     * Should mark the span as failed/aborted in the vendor system.
     *
     * @param args.span - The vendor-specific span object to abort
     * @param args.traceData - The trace data container
     * @param args.reason - Error info describing why the span was aborted
     */
    protected abstract _abortSpan(args: {
        span: TSpanData;
        traceData: TraceData<TRootData, TSpanData, TEventData, TMetadata>;
        reason: SpanErrorInfo;
    }): Promise<void>;
    /**
     * If true, skip calling _buildRoot and let root spans go through _buildSpan.
     * Use when the vendor doesn't have a separate trace/root concept.
     * @default false
     */
    protected skipBuildRootTask: boolean;
    /**
     * If true, skip processing span_updated events entirely.
     * Use when the vendor doesn't support incremental span updates.
     * @default false
     */
    protected skipSpanUpdateEvents: boolean;
    /**
     * If true, don't cache event spans in TraceData.
     * Use when events can't be parents of other spans.
     * @default false
     */
    protected skipCachingEventSpans: boolean;
    private getMethod;
    protected _exportTracingEvent(event: TracingEvent): Promise<void>;
    /**
     * Get or create the TraceData container for a trace.
     * Also cancels any pending cleanup since new data has arrived.
     *
     * @param args.traceId - The trace ID
     * @param args.method - The calling method name (for logging)
     * @returns The TraceData container for this trace
     */
    protected getTraceData(args: {
        traceId: string;
        method: string;
    }): TraceData<TRootData, TSpanData, TEventData, TMetadata>;
    /**
     * Get the current number of traces being tracked.
     * @returns The trace count
     */
    protected traceMapSize(): number;
    /**
     * Hook called by flush() to perform vendor-specific flush logic.
     * Override to send buffered data to the vendor's API.
     *
     * Unlike _postShutdown(), this method should NOT release resources,
     * as the exporter will continue to be used after flushing.
     */
    protected _flush(): Promise<void>;
    /**
     * Force flush any buffered data without shutting down the exporter.
     * This is useful in serverless environments where you need to ensure spans
     * are exported before the runtime instance is terminated.
     *
     * Subclasses should override _flush() to implement vendor-specific flush logic.
     */
    flush(): Promise<void>;
    /**
     * Hook called at the start of shutdown, before cancelling timers and aborting spans.
     * Override to perform vendor-specific pre-shutdown tasks.
     */
    protected _preShutdown(): Promise<void>;
    /**
     * Hook called at the end of shutdown, after all spans are aborted.
     * Override to perform vendor-specific cleanup (e.g., flushing).
     */
    protected _postShutdown(): Promise<void>;
    /**
     * Gracefully shut down the exporter.
     * Cancels all pending cleanup timers, aborts all active spans, and clears state.
     */
    shutdown(): Promise<void>;
}
//# sourceMappingURL=tracking.d.ts.map