All files / src/utils HttpLru.ts

98.44% Statements 127/129
95.83% Branches 23/24
100% Functions 8/8
98.44% Lines 127/129

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 2411x   1x                                         1x 1x   1x                                               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x           1x 1x 13x 13x 13x 13x 13x   1x                         1x 1x 14x 1x 1x 13x 13x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x   1x               1x 1x 2x 2x   1x               1x 1x 1x 1x   1x             1x 1x 19x 13x 13x 13x 13x 6x 6x   1x                     1x 1x 16x 1x 1x 1x 15x 15x 15x 7x 7x 15x 15x 8x 8x 15x 15x 3x 3x 3x 3x 3x     3x 15x 16x 16x 16x   1x             1x 1x 14x 7x 7x 7x 5x 7x 2x 2x 7x 4x 4x 7x 7x 7x 7x 7x 7x 7x 7x 7x   1x           1x 1x 23x 23x 23x 23x 23x 23x 23x 23x 23x 1x  
import { CACHE } from '@/constants/common';
import { FetchDecoratorResponse } from '@/helpers/fetch';
import { cstorage } from '@/utils/storage';
 
/**
 * Represents a single node in the doubly-linked list used by {@link HttpLru}.
 * Each node holds a cached HTTP response keyed by its request hash, along with
 * pointers to the previous and next nodes for O(1) reordering.
 *
 * @interface LruNode
 * @source
 */
interface LruNode {
  /** The request hash used as the cache lookup key */
  key: string;
  /** The cached HTTP response data */
  value: FetchDecoratorResponse;
  /** Pointer to the previous (more recently used) node, or `null` if this is the head */
  prev: LruNode | null;
  /** Pointer to the next (less recently used) node, or `null` if this is the tail */
  next: LruNode | null;
}
 
/** Default maximum number of entries the LRU cache will hold before evicting */
const DEFAULT_CAPACITY = 100;
 
/**
 * A singleton LRU (Least Recently Used) cache for HTTP responses, backed by
 * `cstorage.local` for persistence across browser sessions.
 *
 * The cache uses a doubly-linked list combined with a `Map` for O(1) lookups,
 * insertions, and evictions. When the cache exceeds its configured capacity,
 * the least recently accessed entry is automatically evicted.
 *
 * State is persisted to `cstorage.local` on every mutation so that
 * cached responses survive extension restarts and browser closures.
 *
 * @category Utils
 * @example
 * ```typescript
 * const cache = await HttpLru.getInstance(50);
 * const cached = await cache.getByHash(requestHash);
 * if (!cached) {
 *   const response = await fetchDecorator(url, options);
 *   await cache.putByHash(requestHash, response);
 * }
 * ```
 *
 * @class HttpLru
 * @source
 */
export class HttpLru {
  /** The singleton instance, lazily initialized via {@link HttpLru.getInstance} */
  static #instance: HttpLru | null = null;
  /** Maximum number of entries before the least recently used entry is evicted */
  private capacity: number;
  /** Hash map providing O(1) access to linked-list nodes by request hash */
  private cache: Map<string, LruNode>;
  /** Pointer to the most recently used node (front of the list) */
  private head: LruNode | null;
  /** Pointer to the least recently used node (back of the list) */
  private tail: LruNode | null;
 
  /**
   * Creates a new HttpLru instance. Private to enforce the singleton pattern —
   * use {@link HttpLru.getInstance} instead.
   *
   * @param capacity - Maximum number of entries to store before evicting (default: `DEFAULT_CAPACITY`)
   * @source
   */
  private constructor(capacity: number = DEFAULT_CAPACITY) {
    this.capacity = capacity;
    this.cache = new Map();
    this.head = null;
    this.tail = null;
  }
 
  /**
   * Returns the singleton HttpLru instance, restoring persisted state from
   * `cstorage.local` on first access. Subsequent calls return the
   * same in-memory instance without hitting storage.
   *
   * @param capacity - Maximum number of entries (only applied when creating a new instance)
   * @returns The singleton HttpLru instance
   *
   * @example
   * ```typescript
   * const cache = await HttpLru.getInstance();
   * ```
   * @source
   */
  public static async getInstance(capacity: number = DEFAULT_CAPACITY): Promise<HttpLru> {
    if (HttpLru.#instance) {
      return HttpLru.#instance;
    }
    const data = await cstorage.local.get([CACHE.HTTP_LRU]);
    if (!data[CACHE.HTTP_LRU]) {
      HttpLru.#instance = new HttpLru(capacity);
      return HttpLru.#instance;
    }
    const httplru = new HttpLru(capacity);
    httplru.cache = new Map(Object.entries(data[CACHE.HTTP_LRU].cache));
    httplru.head = data[CACHE.HTTP_LRU].head;
    httplru.tail = data[CACHE.HTTP_LRU].tail;
    HttpLru.#instance = httplru;
    return httplru;
  }
 
  /**
   * Retrieves a cached response by its request hash. This is a convenience
   * wrapper around {@link HttpLru.get} that makes the hash-based lookup
   * intent explicit.
   *
   * @param hash - The request hash generated by `generateRequestHash`
   * @returns The cached response, or `null` if no entry exists for the hash
   * @source
   */
  async getByHash(hash: string): Promise<FetchDecoratorResponse | null> {
    return await this.get(hash);
  }
 
  /**
   * Stores a response in the cache keyed by its request hash. This is a
   * convenience wrapper around {@link HttpLru.put} that makes the hash-based
   * storage intent explicit.
   *
   * @param hash - The request hash generated by `generateRequestHash`
   * @param value - The HTTP response to cache
   * @source
   */
  async putByHash(hash: string, value: FetchDecoratorResponse): Promise<void> {
    return await this.put(hash, value);
  }
 
  /**
   * Retrieves a cached response by key and promotes it to the head of the
   * linked list (marking it as most recently used).
   *
   * @param key - The cache key to look up
   * @returns The cached response if found, or `null` if the key is not in the cache
   * @source
   */
  async get(key: string): Promise<FetchDecoratorResponse | null> {
    if (this.cache.has(key)) {
      const node = this.cache.get(key)!;
      this.moveToHead(node);
      return node.value;
    }
    return null;
  }
 
  /**
   * Inserts or updates a cached response. If the key already exists, its value
   * is updated and the node is promoted to the head. If the key is new, a new
   * node is created at the head. When the cache exceeds its capacity, the
   * least recently used entry (tail) is evicted.
   *
   * Persists the updated cache state to `cstorage.local` after mutation.
   *
   * @param key - The cache key (typically a request hash)
   * @param value - The HTTP response to store
   * @source
   */
  async put(key: string, value: FetchDecoratorResponse): Promise<void> {
    if (this.cache.has(key)) {
      const node = this.cache.get(key)!;
      node.value = value;
      this.moveToHead(node);
    } else {
      const newNode: LruNode = { key, value, prev: null, next: this.head };
      if (this.head) {
        this.head.prev = newNode;
      }
      this.head = newNode;
      if (!this.tail) {
        this.tail = newNode;
      }
      this.cache.set(key, newNode);
      if (this.cache.size > this.capacity) {
        this.cache.delete(this.tail.key);
        this.tail = this.tail.prev;
        if (this.tail) {
          this.tail.next = null;
        } else {
          this.head = null;
        }
      }
    }
    // Save to cstorage.local
    await this.saveToStorage();
  }
 
  /**
   * Detaches a node from its current position in the doubly-linked list and
   * reinserts it at the head, marking it as the most recently used entry.
   * Persists the reordered state to `cstorage.local`.
   *
   * @param node - The node to promote to the head of the list
   * @source
   */
  private async moveToHead(node: LruNode): Promise<void> {
    if (node === this.head) {
      return;
    }
    if (node === this.tail) {
      this.tail = node.prev;
    } else if (node.prev) {
      node.prev.next = node.next;
    }
    if (node.next) {
      node.next.prev = node.prev;
    }
    node.prev = null;
    node.next = this.head;
    if (this.head) {
      this.head.prev = node;
    }
    this.head = node;
    // Save to cstorage.local after moving node
    await this.saveToStorage();
  }
 
  /**
   * Serializes the current cache state (map entries, head, and tail pointers)
   * and writes it to `cstorage.local` under the `httplru` key.
   * Called internally after every mutation to ensure persistence.
   *
   * @source
   */
  private async saveToStorage(): Promise<void> {
    const cacheData = Object.fromEntries(this.cache);
    await cstorage.local.set({
      [CACHE.HTTP_LRU]: {
        cache: cacheData,
        head: this.head,
        tail: this.tail,
      },
    });
  }
}