All files index.js

83.58% Statements 168/201
85.18% Branches 69/81
66.66% Functions 28/42
83.67% Lines 164/196

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923                              2x 2x                                                                                                             79x                           79x     79x     79x 79x     79x                                                                                   54x 1x     53x   53x 53x                                 53x           53x         53x           53x 53x     52x 52x   52x   1x 1x                               15x 14x 14x 14x                 98x 97x   1x                                                           31x 31x 31x   29x 9x 9x     20x     20x 20x     11x     2x 2x                                                   29x 29x 29x 28x   28x 28x         26x 26x   3x 3x                                         8x 8x 8x   7x 7x   1x 1x                                               3x 3x 3x   2x 1x       2x 1x   1x 1x   1x 1x                                       3x 3x 3x 2x   1x 1x                                                 4x 4x 4x   1x 1x                                       3x 3x 3x 2x   1x 1x                                             4x 4x   4x 3x   1x     1x 1x                                           3x 3x   3x 2x   1x     1x 1x                                       3x 7x 3x   2x 2x 6x 4x 4x 2x   2x 2x     2x       2x   1x 1x                                             2x 2x   2x 3x 3x 3x   3x 3x         3x     2x 1x   1x 1x                                           4x 2x     2x   2x   1x 2x 1x     1x   1x 1x                                           5x                                     2x                                                 1x                                                                                     2x 2x 2x 3x 3x 3x     2x 3x     3x 3x 1x       2x     1x   1x                                     3x 3x 1x   2x                                                                                                     2x                             2x           2x     2x                                                                                    
/**
 * @module @onlineapps/conn-base-cache
 * @description Redis cache connector with TTL, invalidation, and namespace support for OA Drive microservices.
 * This connector provides a high-level abstraction over Redis operations with automatic key prefixing,
 * statistics tracking, and namespace isolation.
 *
 * IMPORTANT: This connector uses "cache:" prefix for all keys.
 * Never accesses "obs:" namespace (reserved for monitoring).
 *
 * @see {@link https://github.com/onlineapps/oa-drive/tree/main/shared/connector/conn-base-cache|GitHub Repository}
 * @author OA Drive Team
 * @license MIT
 * @since 1.0.0
 */
 
const Redis = require('ioredis');
const crypto = require('crypto');
 
/**
 * Redis cache connector providing caching operations with automatic key management
 *
 * @class CacheConnector
 *
 * @example <caption>Basic Usage</caption>
 * const cache = new CacheConnector({
 *   host: 'localhost',
 *   port: 6379,
 *   defaultTTL: 3600
 * });
 * await cache.connect();
 * await cache.set('user:123', { name: 'John' }, 600);
 * const user = await cache.get('user:123');
 *
 * @example <caption>With Namespace</caption>
 * const cache = new CacheConnector({
 *   namespace: 'invoice-service'
 * });
 * await cache.set('inv:123', data); // Actual key: cache:invoice-service:inv:123
 */
class CacheConnector {
  /**
   * Creates a new CacheConnector instance
   *
   * @constructor
   * @param {Object} [config={}] - Configuration options
   * @param {string} [config.host='localhost'] - Redis server host
   * @param {number} [config.port=6379] - Redis server port
   * @param {string} [config.password] - Redis password for authentication
   * @param {number} [config.db=0] - Redis database number to use
   * @param {number} [config.defaultTTL=3600] - Default TTL in seconds for cached items
   * @param {string} [config.namespace=''] - Namespace prefix for all keys
   * @param {number} [config.maxRetries=3] - Maximum connection retry attempts
   * @param {number} [config.retryDelay=100] - Initial retry delay in milliseconds
   * @param {boolean} [config.enableOfflineQueue=true] - Queue commands when disconnected
   * @param {boolean} [config.lazyConnect=false] - Delay connection until first operation
   *
   * @throws {TypeError} If configuration is invalid
   *
   * @example <caption>Full Configuration</caption>
   * const cache = new CacheConnector({
   *   host: 'redis.example.com',
   *   port: 6380,
   *   password: 'secret',
   *   namespace: 'my-service',
   *   defaultTTL: 1800,
   *   maxRetries: 5,
   *   enableOfflineQueue: false
   * });
   */
  constructor(config = {}) {
    // Configuration
    this.config = {
      host: config.host || process.env.REDIS_HOST || 'localhost',
      port: config.port || process.env.REDIS_PORT || 6379,
      password: config.password || process.env.REDIS_PASSWORD,
      db: config.db || process.env.REDIS_DB || 0,
      keyPrefix: 'cache:', // ALWAYS use cache: prefix
      defaultTTL: config.defaultTTL || 3600, // 1 hour default
      maxRetries: config.maxRetries || 3,
      retryDelay: config.retryDelay || 100,
      enableOfflineQueue: config.enableOfflineQueue !== false,
      lazyConnect: config.lazyConnect || false
    };
 
    // Namespace configuration
    this.namespace = config.namespace || '';
 
    // Redis client
    this.client = null;
 
    // Connection state
    this.connected = false;
    this.connecting = false;
 
    // Statistics
    this.stats = {
      hits: 0,
      misses: 0,
      sets: 0,
      deletes: 0,
      errors: 0
    };
  }
 
  /**
   * Establishes connection to Redis server
   *
   * @async
   * @method connect
   * @returns {Promise<boolean>} Returns true when connection is established
   *
   * @throws {Error} Throws error if connection fails after all retries
   *
   * @fires CacheConnector#connect
   * @fires CacheConnector#error
   * @fires CacheConnector#close
   *
   * @example <caption>Simple Connection</caption>
   * try {
   *   await cache.connect();
   *   console.log('Connected to Redis');
   * } catch (error) {
   *   console.error('Failed to connect:', error);
   * }
   *
   * @example <caption>With Event Handlers</caption>
   * cache.client.on('connect', () => {
   *   console.log('Redis connected');
   * });
   *
   * cache.client.on('error', (err) => {
   *   console.error('Redis error:', err);
   * });
   *
   * await cache.connect();
   */
  async connect() {
    if (this.connected || this.connecting) {
      return true;
    }
 
    this.connecting = true;
 
    try {
      this.client = new Redis({
        host: this.config.host,
        port: this.config.port,
        password: this.config.password,
        db: this.config.db,
        keyPrefix: this.config.keyPrefix,
        retryStrategy: (times) => {
          if (times > this.config.maxRetries) {
            return null; // Stop retrying
          }
          return Math.min(times * this.config.retryDelay, 2000);
        },
        enableOfflineQueue: this.config.enableOfflineQueue,
        lazyConnect: this.config.lazyConnect
      });
 
      // Handle events
      this.client.on('connect', () => {
        this.connected = true;
        this.connecting = false;
        console.log('Redis cache connected');
      });
 
      this.client.on('error', (err) => {
        this.stats.errors++;
        console.error('Redis cache error:', err);
      });
 
      this.client.on('close', () => {
        this.connected = false;
        console.log('Redis cache connection closed');
      });
 
      // Wait for connection if not lazy
      Eif (!this.config.lazyConnect) {
        await this.client.connect();
      }
 
      this.connected = true;
      this.connecting = false;
 
      return true;
    } catch (error) {
      this.connecting = false;
      throw new Error(`Failed to connect to Redis: ${error.message}`);
    }
  }
 
  /**
   * Disconnect from Redis server gracefully
   *
   * @async
   * @method disconnect
   * @returns {Promise<void>}
   *
   * @example
   * await cache.disconnect();
   * console.log('Disconnected from Redis');
   */
  async disconnect() {
    if (this.client) {
      await this.client.quit();
      this.client = null;
      this.connected = false;
    }
  }
 
  /**
   * Build cache key with namespace
   * @private
   */
  buildKey(key) {
    if (this.namespace) {
      return `${this.namespace}:${key}`;
    }
    return key;
  }
 
  /**
   * Retrieves a value from cache by key
   *
   * @async
   * @method get
   * @param {string} key - Cache key to retrieve
   * @returns {Promise<*|null>} The cached value (parsed from JSON if applicable) or null if not found
   *
   * @throws {Error} Throws error if Redis operation fails
   *
   * @fires CacheConnector#hit - When cache hit occurs
   * @fires CacheConnector#miss - When cache miss occurs
   *
   * @example <caption>Get Simple Value</caption>
   * const value = await cache.get('user:123');
   * if (value) {
   *   console.log('User found:', value);
   * }
   *
   * @example <caption>Get with Fallback</caption>
   * let user = await cache.get('user:123');
   * if (!user) {
   *   user = await fetchFromDatabase(123);
   *   await cache.set('user:123', user, 600);
   * }
   */
  async get(key) {
    try {
      const fullKey = this.buildKey(key);
      const value = await this.client.get(fullKey);
 
      if (value === null) {
        this.stats.misses++;
        return null;
      }
 
      this.stats.hits++;
 
      // Try to parse JSON
      try {
        return JSON.parse(value);
      } catch {
        // Return as string if not JSON
        return value;
      }
    } catch (error) {
      this.stats.errors++;
      throw new Error(`Cache get failed: ${error.message}`);
    }
  }
 
  /**
   * Stores a value in cache with optional TTL
   *
   * @async
   * @method set
   * @param {string} key - Cache key
   * @param {*} value - Value to cache (will be JSON stringified if not a string)
   * @param {number} [ttl] - Time to live in seconds (uses defaultTTL if not specified)
   * @returns {Promise<boolean>} Returns true on successful storage
   *
   * @throws {Error} Throws error if Redis operation fails
   *
   * @example <caption>Set with Default TTL</caption>
   * await cache.set('config', { theme: 'dark' });
   *
   * @example <caption>Set with Custom TTL</caption>
   * await cache.set('session:abc', sessionData, 1800); // 30 minutes
   *
   * @example <caption>Set Permanent (no expiry)</caption>
   * await cache.set('permanent:data', data, 0);
   */
  async set(key, value, ttl) {
    try {
      const fullKey = this.buildKey(key);
      const serialized = typeof value === 'string' ? value : JSON.stringify(value);
      const expiry = ttl || this.config.defaultTTL;
 
      if (expiry > 0) {
        await this.client.setex(fullKey, expiry, serialized);
      } else E{
        await this.client.set(fullKey, serialized);
      }
 
      this.stats.sets++;
      return true;
    } catch (error) {
      this.stats.errors++;
      throw new Error(`Cache set failed: ${error.message}`);
    }
  }
 
  /**
   * Delete a single key from cache
   *
   * @async
   * @method delete
   * @param {string} key - Cache key to delete
   * @returns {Promise<boolean>} Returns true if key was deleted
   *
   * @throws {Error} Throws error if Redis operation fails
   *
   * @example
   * const deleted = await cache.delete('user:123');
   * if (deleted) {
   *   console.log('Key deleted');
   * }
   */
  async delete(key) {
    try {
      const fullKey = this.buildKey(key);
      const result = await this.client.del(fullKey);
 
      this.stats.deletes++;
      return result > 0;
    } catch (error) {
      this.stats.errors++;
      throw new Error(`Cache delete failed: ${error.message}`);
    }
  }
 
  /**
   * Deletes keys matching a pattern
   *
   * @async
   * @method deleteByPattern
   * @param {string} pattern - Redis key pattern (e.g., "user:*", "session:*")
   * @returns {Promise<number>} Number of deleted keys
   *
   * @throws {Error} Throws error if pattern deletion fails
   *
   * @warning This operation can be expensive on large datasets
   *
   * @example <caption>Delete All User Cache Entries</caption>
   * const deleted = await cache.deleteByPattern('user:*');
   * console.log(`Deleted ${deleted} user entries`);
   *
   * @example <caption>Delete Specific Session Pattern</caption>
   * await cache.deleteByPattern('session:user:123:*');
   */
  async deleteByPattern(pattern) {
    try {
      const fullPattern = this.buildKey(pattern);
      const keys = await this.client.keys(`${this.config.keyPrefix}${fullPattern}`);
 
      if (keys.length === 0) {
        return 0;
      }
 
      // Remove key prefix for del command
      const cleanKeys = keys.map(k => k.replace(this.config.keyPrefix, ''));
      const result = await this.client.del(...cleanKeys);
 
      this.stats.deletes += result;
      return result;
    } catch (error) {
      this.stats.errors++;
      throw new Error(`Pattern delete failed: ${error.message}`);
    }
  }
 
  /**
   * Check if key exists in cache
   *
   * @async
   * @method exists
   * @param {string} key - Cache key to check
   * @returns {Promise<boolean>} Returns true if key exists
   *
   * @throws {Error} Throws error if Redis operation fails
   *
   * @example
   * if (await cache.exists('user:123')) {
   *   console.log('User is cached');
   * }
   */
  async exists(key) {
    try {
      const fullKey = this.buildKey(key);
      const result = await this.client.exists(fullKey);
      return result === 1;
    } catch (error) {
      this.stats.errors++;
      throw new Error(`Cache exists check failed: ${error.message}`);
    }
  }
 
  /**
   * Get remaining TTL for key
   *
   * @async
   * @method ttl
   * @param {string} key - Cache key
   * @returns {Promise<number>} TTL in seconds, -1 if no TTL, -2 if not exists
   *
   * @throws {Error} Throws error if Redis operation fails
   *
   * @example
   * const ttl = await cache.ttl('session:abc');
   * if (ttl > 0) {
   *   console.log(`Session expires in ${ttl} seconds`);
   * } else if (ttl === -1) {
   *   console.log('Session has no expiry');
   * } else {
   *   console.log('Session does not exist');
   * }
   */
  async ttl(key) {
    try {
      const fullKey = this.buildKey(key);
      return await this.client.ttl(fullKey);
    } catch (error) {
      this.stats.errors++;
      throw new Error(`TTL check failed: ${error.message}`);
    }
  }
 
  /**
   * Update TTL for existing key
   *
   * @async
   * @method expire
   * @param {string} key - Cache key
   * @param {number} ttl - New TTL in seconds
   * @returns {Promise<boolean>} Returns true if TTL was set
   *
   * @throws {Error} Throws error if Redis operation fails
   *
   * @example
   * // Extend session by 30 minutes
   * await cache.expire('session:abc', 1800);
   */
  async expire(key, ttl) {
    try {
      const fullKey = this.buildKey(key);
      const result = await this.client.expire(fullKey, ttl);
      return result === 1;
    } catch (error) {
      this.stats.errors++;
      throw new Error(`Expire failed: ${error.message}`);
    }
  }
 
  /**
   * Increment numeric value atomically
   *
   * @async
   * @method incr
   * @param {string} key - Cache key
   * @param {number} [increment=1] - Increment value
   * @returns {Promise<number>} New value after increment
   *
   * @throws {Error} Throws error if Redis operation fails
   *
   * @example <caption>Simple Counter</caption>
   * const count = await cache.incr('page:views');
   * console.log(`Page views: ${count}`);
   *
   * @example <caption>Increment by Value</caption>
   * const score = await cache.incr('user:score', 10);
   */
  async incr(key, increment = 1) {
    try {
      const fullKey = this.buildKey(key);
 
      if (increment === 1) {
        return await this.client.incr(fullKey);
      } else {
        return await this.client.incrby(fullKey, increment);
      }
    } catch (error) {
      this.stats.errors++;
      throw new Error(`Increment failed: ${error.message}`);
    }
  }
 
  /**
   * Decrement numeric value atomically
   *
   * @async
   * @method decr
   * @param {string} key - Cache key
   * @param {number} [decrement=1] - Decrement value
   * @returns {Promise<number>} New value after decrement
   *
   * @throws {Error} Throws error if Redis operation fails
   *
   * @example
   * const remaining = await cache.decr('inventory:count', 1);
   * if (remaining < 0) {
   *   console.log('Out of stock');
   * }
   */
  async decr(key, decrement = 1) {
    try {
      const fullKey = this.buildKey(key);
 
      if (decrement === 1) {
        return await this.client.decr(fullKey);
      } else {
        return await this.client.decrby(fullKey, decrement);
      }
    } catch (error) {
      this.stats.errors++;
      throw new Error(`Decrement failed: ${error.message}`);
    }
  }
 
  /**
   * Get multiple values at once
   *
   * @async
   * @method mget
   * @param {string[]} keys - Array of cache keys
   * @returns {Promise<Object>} Key-value object with found values
   *
   * @throws {Error} Throws error if Redis operation fails
   *
   * @example
   * const result = await cache.mget(['user:1', 'user:2', 'user:3']);
   * // Returns: { 'user:1': {...}, 'user:2': {...} }
   * // Missing keys are not included in result
   */
  async mget(keys) {
    try {
      const fullKeys = keys.map(k => this.buildKey(k));
      const values = await this.client.mget(...fullKeys);
 
      const result = {};
      keys.forEach((key, index) => {
        if (values[index] !== null) {
          try {
            result[key] = JSON.parse(values[index]);
            this.stats.hits++;
          } catch {
            result[key] = values[index];
            this.stats.hits++;
          }
        } else {
          this.stats.misses++;
        }
      });
 
      return result;
    } catch (error) {
      this.stats.errors++;
      throw new Error(`Multi-get failed: ${error.message}`);
    }
  }
 
  /**
   * Set multiple values at once
   *
   * @async
   * @method mset
   * @param {Object} keyValues - Key-value pairs to set
   * @param {number} [ttl] - TTL in seconds for all keys
   * @returns {Promise<boolean>} Returns true on success
   *
   * @throws {Error} Throws error if Redis operation fails
   *
   * @example
   * await cache.mset({
   *   'user:1': { name: 'Alice' },
   *   'user:2': { name: 'Bob' },
   *   'user:3': { name: 'Charlie' }
   * }, 3600);
   */
  async mset(keyValues, ttl) {
    try {
      const pipeline = this.client.pipeline();
 
      for (const [key, value] of Object.entries(keyValues)) {
        const fullKey = this.buildKey(key);
        const serialized = typeof value === 'string' ? value : JSON.stringify(value);
        const expiry = ttl || this.config.defaultTTL;
 
        if (expiry > 0) {
          pipeline.setex(fullKey, expiry, serialized);
        } else E{
          pipeline.set(fullKey, serialized);
        }
 
        this.stats.sets++;
      }
 
      await pipeline.exec();
      return true;
    } catch (error) {
      this.stats.errors++;
      throw new Error(`Multi-set failed: ${error.message}`);
    }
  }
 
  /**
   * Flush all cache keys (dangerous!)
   *
   * @async
   * @method flush
   * @param {boolean} [confirm=false] - Must be true to execute
   * @returns {Promise<boolean>} Returns true on success
   *
   * @throws {Error} If confirmation not provided or flush fails
   *
   * @warning This will delete ALL cache keys with the configured prefix
   *
   * @example
   * // Safety check required
   * await cache.flush(true);
   * console.log('All cache cleared');
   */
  async flush(confirm = false) {
    if (!confirm) {
      throw new Error('Flush requires confirmation parameter to be true');
    }
 
    try {
      // Only flush keys with our prefix
      const keys = await this.client.keys(`${this.config.keyPrefix}*`);
 
      Eif (keys.length > 0) {
        const cleanKeys = keys.map(k => k.replace(this.config.keyPrefix, ''));
        await this.client.del(...cleanKeys);
      }
 
      return true;
    } catch (error) {
      this.stats.errors++;
      throw new Error(`Flush failed: ${error.message}`);
    }
  }
 
  /**
   * Get cache statistics
   *
   * @method getStats
   * @returns {CacheStats} Current statistics
   * @returns {number} stats.hits - Number of cache hits
   * @returns {number} stats.misses - Number of cache misses
   * @returns {number} stats.sets - Number of set operations
   * @returns {number} stats.deletes - Number of delete operations
   * @returns {number} stats.errors - Number of errors
   * @returns {string} stats.hitRate - Hit rate percentage
   *
   * @example
   * const stats = cache.getStats();
   * console.log(`Hit rate: ${stats.hitRate}`);
   * console.log(`Total operations: ${stats.hits + stats.misses}`);
   */
  getStats() {
    return {
      ...this.stats,
      hitRate: this.stats.hits + this.stats.misses > 0
        ? (this.stats.hits / (this.stats.hits + this.stats.misses) * 100).toFixed(2) + '%'
        : '0%'
    };
  }
 
  /**
   * Reset statistics counters
   *
   * @method resetStats
   * @returns {void}
   *
   * @example
   * cache.resetStats();
   * // All counters set to 0
   */
  resetStats() {
    this.stats = {
      hits: 0,
      misses: 0,
      sets: 0,
      deletes: 0,
      errors: 0
    };
  }
 
  /**
   * Creates a new CacheConnector instance with additional namespace
   *
   * @method withNamespace
   * @param {string} namespace - Additional namespace to append
   * @returns {CacheConnector} New instance with combined namespace
   *
   * @example
   * const baseCache = new CacheConnector({ namespace: 'app' });
   * const userCache = baseCache.withNamespace('users');
   * const sessionCache = baseCache.withNamespace('sessions');
   *
   * // userCache keys: cache:app:users:*
   * // sessionCache keys: cache:app:sessions:*
   */
  withNamespace(namespace) {
    return new CacheConnector({
      ...this.config,
      namespace: this.namespace ? `${this.namespace}:${namespace}` : namespace
    });
  }
 
  /**
   * Wraps a function with caching (memoization)
   *
   * @method wrap
   * @param {Function} fn - Async function to wrap
   * @param {Object} [options={}] - Wrapping options
   * @param {number} [options.ttl] - Cache TTL in seconds
   * @param {string} [options.keyPrefix] - Prefix for cache keys
   * @param {Function} [options.keyGenerator] - Custom key generation function
   * @returns {Function} Wrapped function with caching
   *
   * @example <caption>Basic Function Wrapping</caption>
   * const expensiveOperation = async (userId) => {
   *   // Complex database query
   *   return await db.query('SELECT * FROM users WHERE id = ?', [userId]);
   * };
   *
   * const cachedOperation = cache.wrap(expensiveOperation, {
   *   ttl: 600,
   *   keyPrefix: 'expensive-op'
   * });
   *
   * // First call hits database
   * const result1 = await cachedOperation(123);
   *
   * // Second call returns from cache
   * const result2 = await cachedOperation(123);
   *
   * @example <caption>Custom Key Generation</caption>
   * const searchUsers = cache.wrap(async (filters) => {
   *   return await db.searchUsers(filters);
   * }, {
   *   ttl: 300,
   *   keyGenerator: (filters) => `search:${JSON.stringify(filters)}`
   * });
   */
  wrap(fn, options = {}) {
    const ttl = options.ttl || this.config.defaultTTL;
    const keyPrefix = options.keyPrefix || fn.name || 'wrapped';
    const keyGenerator = options.keyGenerator || ((...args) => {
      const hash = crypto.createHash('sha256');
      hash.update(JSON.stringify(args));
      return `${keyPrefix}:${hash.digest('hex')}`;
    });
 
    return async (...args) => {
      const key = keyGenerator(...args);
 
      // Try to get from cache
      const cached = await this.get(key);
      if (cached !== null) {
        return cached;
      }
 
      // Execute function
      const result = await fn(...args);
 
      // Cache result
      await this.set(key, result, ttl);
 
      return result;
    };
  }
 
  /**
   * Perform health check on Redis connection
   *
   * @async
   * @method healthCheck
   * @returns {Promise<boolean>} Returns true if healthy
   *
   * @example
   * if (await cache.healthCheck()) {
   *   console.log('Redis is healthy');
   * } else {
   *   console.error('Redis is down');
   * }
   */
  async healthCheck() {
    try {
      await this.client.ping();
      return true;
    } catch {
      return false;
    }
  }
}
 
/**
 * @typedef {Object} CacheConfig
 * @property {string} [host='localhost'] - Redis host
 * @property {number} [port=6379] - Redis port
 * @property {string} [password] - Redis password
 * @property {number} [db=0] - Redis database
 * @property {number} [defaultTTL=3600] - Default TTL in seconds
 * @property {string} [namespace=''] - Key namespace
 * @property {number} [maxRetries=3] - Max connection retries
 * @property {number} [retryDelay=100] - Retry delay in ms
 * @property {boolean} [enableOfflineQueue=true] - Queue commands when disconnected
 * @property {boolean} [lazyConnect=false] - Delay connection
 */
 
/**
 * @typedef {Object} CacheStats
 * @property {number} hits - Number of cache hits
 * @property {number} misses - Number of cache misses
 * @property {number} sets - Number of set operations
 * @property {number} deletes - Number of delete operations
 * @property {number} errors - Number of errors
 * @property {string} hitRate - Hit rate percentage
 */
 
/**
 * Connection established event
 *
 * @event CacheConnector#connect
 * @type {void}
 */
 
/**
 * Error event
 *
 * @event CacheConnector#error
 * @type {Error}
 */
 
/**
 * Connection closed event
 *
 * @event CacheConnector#close
 * @type {void}
 */
 
// Export main class
module.exports = CacheConnector;
 
/**
 * Factory function to create cache instance
 *
 * @function create
 * @param {CacheConfig} config - Configuration object
 * @returns {CacheConnector} New cache connector instance
 *
 * @example
 * const cache = CacheConnector.create({
 *   host: 'localhost',
 *   namespace: 'my-service'
 * });
 */
module.exports.create = (config) => new CacheConnector(config);
 
/**
 * Current version
 * @constant {string}
 */
module.exports.VERSION = '1.0.0';
 
// Export mock for testing
module.exports.MockCacheConnector = class MockCacheConnector {
  constructor() {
    this.cache = new Map();
    this.stats = { hits: 0, misses: 0, sets: 0, deletes: 0, errors: 0 };
  }
 
  async connect() { return true; }
  async disconnect() { return true; }
 
  async get(key) {
    if (this.cache.has(key)) {
      this.stats.hits++;
      return this.cache.get(key);
    }
    this.stats.misses++;
    return null;
  }
 
  async set(key, value, ttl) {
    this.cache.set(key, value);
    this.stats.sets++;
    // Simulate TTL
    if (ttl > 0) {
      setTimeout(() => this.cache.delete(key), ttl * 1000);
    }
    return true;
  }
 
  async delete(key) {
    this.stats.deletes++;
    return this.cache.delete(key);
  }
 
  async flush() {
    this.cache.clear();
    return true;
  }
 
  getStats() { return this.stats; }
  resetStats() {
    this.stats = { hits: 0, misses: 0, sets: 0, deletes: 0, errors: 0 };
  }
};