import type { TrustRecord } from '../trust-engine/index.js';
import { Counter } from 'prom-client';
/**
 * XFetch cache entry with timing metadata for probabilistic early refresh.
 *
 * The XFetch algorithm uses:
 * - fetchTime: when the value was computed/fetched
 * - ttl: time-to-live in milliseconds
 * - delta: computation time in milliseconds (used to scale refresh probability)
 *
 * @template T - The type of the cached value
 */
export interface XFetchCacheEntry<T> {
    /** The cached value */
    value: T;
    /** Unix timestamp when the value was fetched (milliseconds) */
    fetchTime: number;
    /** Time-to-live in milliseconds */
    ttl: number;
    /** Computation time in milliseconds (how long the fetch took) */
    delta: number;
}
/**
 * Options for XFetch cache operations
 */
export interface XFetchOptions {
    /**
     * Beta parameter for XFetch algorithm (default: 1.0)
     * Higher values = more aggressive early refresh
     */
    beta?: number;
    /**
     * Jitter fraction to apply to TTL (default: 0.1 for ±10%)
     * This helps prevent synchronized expiration across keys
     */
    jitter?: number;
}
/**
 * Trust cache operations counter
 */
export declare const trustCacheOperations: Counter<"operation" | "result">;
/**
 * XFetch early refresh counter - tracks proactive cache refreshes
 * triggered by the XFetch algorithm before TTL expiration
 */
export declare const cacheXFetchEarlyRefreshTotal: Counter<"cache_type">;
/**
 * XFetch stale serve counter - tracks when stale data was served
 * while a background refresh was triggered
 */
export declare const cacheXFetchStaleServeTotal: Counter<"cache_type">;
/**
 * Record a cache hit
 */
export declare function recordCacheHit(): void;
/**
 * Record a cache miss
 */
export declare function recordCacheMiss(): void;
/**
 * Record a cache set operation
 */
export declare function recordCacheSet(): void;
/**
 * Record a cache invalidation
 */
export declare function recordCacheInvalidation(): void;
/**
 * Record a cache error
 */
export declare function recordCacheError(operation: string): void;
/**
 * Record an early refresh triggered by PER (legacy)
 */
export declare function recordEarlyRefresh(): void;
/**
 * Record an XFetch early refresh for a specific cache type
 */
export declare function recordXFetchEarlyRefresh(cacheType?: string): void;
/**
 * Record serving stale data during XFetch background refresh
 */
export declare function recordXFetchStaleServe(cacheType?: string): void;
/**
 * Add jitter to TTL to prevent synchronized expiration
 *
 * Adds 0-10% random jitter to the base TTL to stagger cache expiration
 * across multiple entries, reducing the chance of thundering herd.
 *
 * @param baseTTL - Base TTL in seconds
 * @returns TTL with jitter added
 */
export declare function getTTLWithJitter(baseTTL: number): number;
/**
 * Apply jitter to TTL in milliseconds with configurable range
 *
 * Applies random jitter within ±jitterFraction of the base TTL.
 * This staggers cache expiration across entries to prevent thundering herd.
 *
 * @param baseTtlMs - Base TTL in milliseconds
 * @param jitterFraction - Jitter range as fraction of TTL (default: 0.1 for ±10%)
 * @returns TTL with jitter applied (always positive)
 */
export declare function applyTTLJitter(baseTtlMs: number, jitterFraction?: number): number;
/**
 * Determine if we should refresh early using the XFetch algorithm.
 *
 * The XFetch algorithm formula:
 *   shouldRefresh = currentTime - fetchTime > ttl - delta * beta * log(random())
 *
 * Where:
 * - currentTime: current timestamp
 * - fetchTime: when the cache entry was created
 * - ttl: time-to-live of the entry
 * - delta: computation time of the fetch operation
 * - beta: tuning parameter (typically 1.0)
 * - random(): uniform random value in (0, 1)
 *
 * Since log(random()) is negative (random is in (0,1)), the term
 * `-delta * beta * log(random())` is positive, effectively reducing the
 * TTL threshold. The longer the computation time (delta), the earlier
 * we start probabilistically refreshing.
 *
 * @param entry - The XFetch cache entry with timing metadata
 * @param beta - Tuning parameter (default: 1.0). Higher = more aggressive refresh
 * @returns true if the entry should be refreshed
 */
export declare function shouldRefresh<T>(entry: XFetchCacheEntry<T>, beta?: number): boolean;
/**
 * Determine if we should refresh early using XFetch algorithm (legacy signature)
 *
 * The probability of refresh increases as the cache entry approaches expiration.
 * This spreads out refresh requests over time instead of all hitting at once
 * when the entry expires.
 *
 * @param cachedAt - Unix timestamp when entry was cached (seconds)
 * @param expiresAt - Unix timestamp when entry expires (seconds)
 * @param delta - Computation time in milliseconds (optional, defaults to using window-based calculation)
 * @returns true if early refresh should be triggered
 */
export declare function shouldRefreshEarly(cachedAt: number, expiresAt: number, delta?: number): boolean;
/**
 * Get a value from cache with XFetch stampede prevention.
 *
 * This implements the cache-aside pattern with the XFetch algorithm for
 * probabilistic early refresh. When a cache entry is approaching expiration,
 * XFetch probabilistically triggers a background refresh while returning the
 * stale value, preventing cache stampede.
 *
 * @template T - The type of the cached value
 * @param key - Cache key (will be prefixed with 'xfetch:')
 * @param fetchFn - Function to fetch fresh data on cache miss or refresh
 * @param ttlMs - Time-to-live in milliseconds
 * @param options - XFetch options (beta, jitter)
 * @returns The cached or fresh value
 *
 * @example
 * ```typescript
 * const user = await getWithXFetch(
 *   `user:${userId}`,
 *   () => fetchUserFromDatabase(userId),
 *   60_000, // 1 minute TTL
 *   { beta: 1.0, jitter: 0.1 }
 * );
 * ```
 */
export declare function getWithXFetch<T>(key: string, fetchFn: () => Promise<T>, ttlMs: number, options?: XFetchOptions): Promise<T>;
/**
 * Invalidate an XFetch cache entry
 *
 * @param key - Cache key (will be prefixed with 'xfetch:')
 */
export declare function invalidateXFetchCache(key: string): Promise<void>;
/**
 * Get the number of in-flight background refreshes
 * Useful for monitoring and testing
 */
export declare function getInFlightRefreshCount(): number;
/**
 * Clear all in-flight refresh tracking
 * Primarily for testing purposes
 */
export declare function clearInFlightRefreshes(): void;
/**
 * Get a cached trust score with probabilistic early refresh using XFetch
 *
 * Uses the XFetch algorithm to probabilistically refresh cache entries
 * before they expire, preventing cache stampede. This implementation
 * tracks computation time (delta) to scale the early refresh probability.
 *
 * @param entityId - The entity ID to look up
 * @param tenantId - The tenant ID for namespace isolation
 * @param fetchFn - Function to fetch fresh data on cache miss or early refresh
 * @returns The TrustRecord (cached or fresh)
 */
export declare function getCachedTrustScoreWithRefresh(entityId: string, tenantId: string, fetchFn: () => Promise<TrustRecord>): Promise<TrustRecord>;
/**
 * Get the number of in-flight trust score refreshes
 * Useful for monitoring and testing
 */
export declare function getInFlightTrustRefreshCount(): number;
/**
 * Clear all in-flight trust refresh tracking
 * Primarily for testing purposes
 */
export declare function clearInFlightTrustRefreshes(): void;
/**
 * Get a cached trust score for an entity (legacy API)
 *
 * @param entityId - The entity ID to look up
 * @param tenantId - The tenant ID for namespace isolation
 * @returns The cached TrustRecord or null if not found
 */
export declare function getCachedTrustScore(entityId: string, tenantId: string): Promise<TrustRecord | null>;
/**
 * Cache a trust score for an entity (legacy API)
 *
 * @param entityId - The entity ID
 * @param tenantId - The tenant ID for namespace isolation
 * @param score - The TrustRecord to cache
 */
export declare function cacheTrustScore(entityId: string, tenantId: string, score: TrustRecord): Promise<void>;
/**
 * Invalidate a cached trust score for an entity
 *
 * Use this when a trust score needs to be refreshed (e.g., after
 * recording new trust signals).
 *
 * @param entityId - The entity ID
 * @param tenantId - The tenant ID for namespace isolation
 */
export declare function invalidateTrustScore(entityId: string, tenantId: string): Promise<void>;
/**
 * Invalidate all trust scores for a tenant
 *
 * Use this when tenant-wide trust recalculation is needed.
 *
 * @param tenantId - The tenant ID
 */
export declare function invalidateTenantTrustScores(tenantId: string): Promise<void>;
//# sourceMappingURL=trust-cache.d.ts.map