UNPKG

xypriss-security

Version:

Advanced High-Performance Security Framework. Military-grade encryption, post-quantum resilience, and fortified data structures.

305 lines 9.32 kB
/** * XyPrissJS Secure Cache Adapter * Ultra-fast hybrid cache system combining security cache with Redis clustering * * Features: * - Memory-first hybrid architecture for maximum speed * - Redis Cluster support with automatic failover * - Connection pooling and health monitoring * - Advanced tagging and invalidation * - Real-time performance metrics * - Military-grade security from XyPrissJS security cache */ import { EventEmitter } from "events"; import * as CacheTypes from "./type"; /** * UF secure cache adapter */ export declare class SecureCacheAdapter extends EventEmitter { private static sharedMemoryCache; private static sharedMasterEncryptionKey; private config; private memoryCache; private redisClient?; private connectionPool; private metadata; private stats; private healthMonitor?; private metricsCollector?; private masterEncryptionKey; private logger; constructor(config?: CacheTypes.SecureCacheConfig); /** * Initialize statistics */ private initializeStats; /** * Initialize master encryption key for consistent encryption * Uses singleton pattern to ensure all instances use the same key */ private initializeMasterKey; /** * Initialize memory cache with security features * Uses singleton pattern to ensure all instances share the same memory cache */ private initializeMemoryCache; /** * Connect to cache backends */ connect(): Promise<void>; /** * Initialize Redis with clustering and failover support */ private initializeRedis; /** * Setup Redis event handlers for monitoring and failover */ private setupRedisEventHandlers; /** * Start monitoring and health checks */ private startMonitoring; /** * Perform health check on all cache backends */ private performHealthCheck; /** * Collect performance metrics */ private collectMetrics; /** * Update performance metrics */ private updatePerformanceMetrics; /** * Generate cache key with namespace and security */ private generateKey; /** * Determine if data should be considered "hot" (frequently accessed) */ private isHotData; /** * Update access metadata for performance optimization */ private updateAccessMetadata; /** * Convert any data to CachedData format for SecurityCache compatibility */ private toCachedData; /** * Extract raw data from CachedData format */ private fromCachedData; /** * Serialize data for Redis storage with proper encryption */ private serializeForRedis; /** * Deserialize data from Redis storage with proper decryption */ private deserializeFromRedis; /** * Get value from cache with ultra-fast hybrid strategy * * @param key - The cache key to retrieve * @returns Promise resolving to the cached value with proper typing, or null if not found * * @example * ```typescript * interface User { id: number; name: string; } * const user = await cache.get<User>("user:123"); * if (user) { * console.log(user.name); // TypeScript knows this is a string * } * ``` */ get<T = any>(key: string): Promise<T | null>; /** * Set value in cache with intelligent placement * * @param key - The cache key to store the value under * @param value - The value to cache with proper typing * @param options - Optional caching options * @param options.ttl - Time to live in milliseconds * @param options.tags - Array of tags for bulk invalidation * @returns Promise resolving to true if successful, false otherwise * * @example * ```typescript * interface User { id: number; name: string; email: string; } * * const user: User = { id: 123, name: "John", email: "john@example.com" }; * const success = await cache.set<User>("user:123", user, { * ttl: 3600000, // 1 hour * tags: ["users", "active"] * }); * ``` */ set<T = any>(key: string, value: T, options?: { ttl?: number; tags?: string[]; }): Promise<boolean>; /** * Delete value from cache */ delete(key: string): Promise<boolean>; /** * Check if key exists in cache */ exists(key: string): Promise<boolean>; /** * Clear all cache entries */ clear(): Promise<void>; /** * Get value from Redis with encryption support */ private getFromRedis; /** * Set value in Redis with encryption and TTL support */ private setInRedis; /** * Set tags for cache invalidation */ private setTags; /** * Record response time for performance monitoring */ private recordResponseTime; /** * Invalidate cache entries by tags */ invalidateByTags(tags: string[]): Promise<number>; /** * Get multiple values at once (batch operation) * * @param keys - Array of cache keys to retrieve * @returns Promise resolving to an object with key-value pairs (missing keys are omitted) * * @example * ```typescript * interface User { id: number; name: string; } * * const users = await cache.mget<User>(["user:1", "user:2", "user:3"]); * // users is Record<string, User> * * for (const [key, user] of Object.entries(users)) { * console.log(`${key}: ${user.name}`); // TypeScript knows user.name is string * } * ``` */ mget<T = any>(keys: string[]): Promise<Record<string, T>>; /** * Set multiple values at once (batch operation) * * @param entries - Object with key-value pairs or array of [key, value] tuples * @param options - Optional caching options applied to all entries * @param options.ttl - Time to live in milliseconds for all entries * @param options.tags - Array of tags applied to all entries * @returns Promise resolving to true if all operations successful, false otherwise * * @example * ```typescript * interface User { id: number; name: string; } * * // Using object notation * const success1 = await cache.mset<User>({ * "user:1": { id: 1, name: "Alice" }, * "user:2": { id: 2, name: "Bob" } * }, { ttl: 3600000, tags: ["users"] }); * * // Using array notation * const success2 = await cache.mset<User>([ * ["user:3", { id: 3, name: "Charlie" }], * ["user:4", { id: 4, name: "Diana" }] * ], { ttl: 3600000 }); * ``` */ mset<T = any>(entries: Record<string, T> | Array<[string, T]>, options?: { ttl?: number; tags?: string[]; }): Promise<boolean>; /** * Read value from cache (alias for get method) * * @param key - The cache key to retrieve * @returns Promise resolving to the cached value with proper typing, or null if not found * * @example * ```typescript * interface User { id: number; name: string; } * const user = await cache.read<User>("user:123"); * if (user) { * console.log(user.name); // TypeScript knows this is a string * } * ``` */ read<T = any>(key: string): Promise<T | null>; /** * Write value to cache (alias for set method) * * @param key - The cache key to store the value under * @param value - The value to cache with proper typing * @param options - Optional caching options * @param options.ttl - Time to live in milliseconds * @param options.tags - Array of tags for bulk invalidation * @returns Promise resolving to true if successful, false otherwise * * @example * ```typescript * interface User { id: number; name: string; email: string; } * * const user: User = { id: 123, name: "John", email: "john@example.com" }; * const success = await cache.write<User>("user:123", user, { * ttl: 3600000, // 1 hour * tags: ["users", "active"] * }); * ``` */ write<T = any>(key: string, value: T, options?: { ttl?: number; tags?: string[]; }): Promise<boolean>; /** * Get TTL for a specific key */ getTTL(key: string): Promise<number>; /** * Set expiration time for a key */ expire(key: string, ttl: number): Promise<boolean>; /** * Get all keys matching a pattern */ keys(pattern?: string): Promise<string[]>; /** * Extract original key from cache key */ private extractOriginalKey; /** * Get comprehensive cache statistics */ getStats(): Promise<CacheTypes.EnhancedCacheStats>; /** * Update Redis statistics using Redis INFO command */ private updateRedisStats; /** * Calculate Redis memory usage percentage */ private calculateRedisMemoryPercentage; /** * Get cache health status */ getHealth(): { status: "healthy" | "degraded" | "unhealthy"; details: any; }; /** * Disconnect from all cache backends */ disconnect(): Promise<void>; } //# sourceMappingURL=SecureCacheAdapter.d.ts.map