All files / router/src cache.ts

100% Statements 80/80
100% Branches 36/36
100% Functions 8/8
100% Lines 80/80

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 2321x 1x                                                   1x           1x 213x 213x                                               1x 74x 74x 74x 74x 74x 74x   49x 23x 23x   46x   46x 46x 46x   74x 8x 8x   38x 74x 33x 33x 33x   37x 74x                             1x 5x 5x 5x 5x   5x 3x 3x 3x 5x                             1x 3x 3x 3x                       1x 6x 6x 1x                             1x 84x               84x 84x 84x 84x                                       84x 3392x     3392x 3392x   3302x 3302x 3302x 3302x     90x 90x   90x   3392x 85x 85x 85x     85x 1x 1x 1x 1x 1x     85x 85x   90x 3392x 84x  
import { anchor, mutable } from '@anchorlib/core';
import { parseQuery } from './query.js';
import type { RouteRegistry } from './registry.js';
import type {
  MatchResult,
  ProviderCache,
  ProviderContext,
  ProviderOptions,
  TRec,
  UnknownProvider,
  UnknownRoute,
} from './types.js';
 
/**
 * A cache for route provider data with time-based expiration.
 *
 * Extends WeakMap to store provider results keyed by provider instances.
 * Each provider has its own Map of cached entries keyed by params and query.
 *
 * @template T - The type of data returned by providers
 *
 * @example
 * ```ts
 * const cache = new RouteCache(route);
 * const data = await cache.resolve(provider, context, { maxAge: 60000 });
 * ```
 */
export class RouteCache extends WeakMap<UnknownProvider, ProviderCache> {
  /**
   * Creates a new RouteCache instance.
   *
   * @param route - The route this cache is associated with, used for default options
   */
  constructor(private route: UnknownRoute) {
    super();
  }
 
  /**
   * Resolves a provider with caching support.
   *
   * If caching is enabled (maxAge > 0), checks for cached data first.
   * Returns cached data if it exists and hasn't expired.
   * Otherwise, calls the provider and caches the result.
   *
   * @template T - The type of data returned by the provider
   * @param provider - The provider function to resolve
   * @param context - The provider context containing params, query, and data
   * @param options - Optional provider options including maxAge for caching
   * @returns A promise that resolves to the provider's data
   *
   * @example
   * ```ts
   * const data = await cache.resolve(
   *   async (ctx) => await fetchUser(ctx.params.id),
   *   { params: { id: '123' }, query: {}, data: {} },
   *   { maxAge: 60000 }
   * );
   * ```
   */
  public async resolve<T>(
    provider: UnknownProvider,
    context: ProviderContext<TRec, TRec, TRec>,
    options?: ProviderOptions
  ): Promise<T> {
    const maxAge = options?.maxAge ?? this.route.options?.maxAge;
    if (!maxAge) return (await provider(context)) as T;
 
    if (!this.has(provider)) {
      this.set(provider, new Map());
    }
 
    const { params, query } = (anchor.get as (ctx: typeof context, silent: boolean) => typeof context)(context, true);
 
    const key = JSON.stringify({ params, query });
    const cache = this.get(provider)!;
    const cached = cache.get(key);
 
    if (cached && Date.now() - cached.timestamp <= maxAge) {
      return cached.data as T;
    }
 
    const data = await provider(context);
    if (data !== null && typeof data !== 'undefined') {
      const scheduler = setTimeout(() => cache.delete(key), maxAge) as never as number;
      cache.set(key, { data, timestamp: Date.now(), scheduler });
    }
 
    return data as T;
  }
 
  /**
   * Invalidates a cached entry for a specific provider and context.
   *
   * Removes the cached data and clears any pending expiration timeout.
   *
   * @param provider - The provider whose cache should be invalidated
   * @param context - The context identifying which cache entry to invalidate
   *
   * @example
   * ```ts
   * cache.invalidate(provider, { params: { id: '123' }, query: {}, data: {} });
   * ```
   */
  public invalidate(provider: UnknownProvider, context: ProviderContext<TRec, TRec, TRec>): void {
    const { params, query } = (anchor.get as (ctx: typeof context, silent: boolean) => typeof context)(context, true);
    const key = JSON.stringify({ params, query });
    const cache = this.get(provider);
    const cached = cache?.get(key);
 
    if (cache && cached) {
      cache.delete(key);
      clearTimeout(cached.scheduler);
    }
  }
 
  /**
   * Deletes all cached entries for a provider.
   *
   * Clears all cached data and removes the provider from the cache.
   *
   * @param provider - The provider to delete from the cache
   * @returns true if the provider was in the cache, false otherwise
   *
   * @example
   * ```ts
   * cache.delete(provider);
   * ```
   */
  public delete(provider: UnknownProvider): boolean {
    this.clear(provider);
    return super.delete(provider);
  }
 
  /**
   * Clears all cached entries for a provider without removing the provider itself.
   *
   * @param provider - The provider whose cache should be cleared
   *
   * @example
   * ```ts
   * cache.clear(provider);
   * ```
   */
  public clear(provider: UnknownProvider): void {
    this.get(provider)?.clear();
  }
}
 
/**
 * A cache for URL matching results with LRU (Least Recently Used) eviction.
 *
 * Caches parsed and matched route results to avoid repeated parsing and matching.
 * Uses a Map with LRU behavior - accessed entries are moved to the end,
 * and the oldest entry is evicted when the cache reaches maxSize.
 *
 * @example
 * ```ts
 * const cache = new URLCache(registry, 100);
 * const match = cache.get(new URL('/users/123', baseUrl));
 * ```
 */
export class URLCache {
  private cache = new Map<string, MatchResult>();
 
  /**
   * Creates a new URLCache instance.
   *
   * @param registry - The route registry used for matching URLs
   * @param maxSize - Maximum number of entries to cache (default: 100)
   */
  constructor(
    private registry: RouteRegistry,
    private maxSize = 100
  ) {}
 
  /**
   * Gets a cached match result for a URL, or creates one if not cached.
   *
   * If the URL is cached, returns the cached result and updates its LRU position.
   * Otherwise, parses the URL, matches it against the registry, and caches the result.
   * Evicts the oldest entry if the cache is at capacity.
   *
   * @param url - The URL to match
   * @returns The match result, or undefined if no match is found
   *
   * @example
   * ```ts
   * const match = cache.get(new URL('/users/123', baseUrl));
   * if (match) {
   *   console.log(match.route, match.params);
   * }
   * ```
   */
  public get(url: URL): MatchResult | undefined {
    const cacheKey = url.href;
 
    // Check cache first - return cached match if exists
    const cached = this.cache.get(cacheKey);
    if (cached) {
      // LRU: Move to end by deleting and re-inserting
      this.cache.delete(cacheKey);
      this.cache.set(cacheKey, cached);
      return cached;
    }
 
    // Not cached - parse, match, and create context
    const query = parseQuery(url.search);
    const pathname = url.pathname;
 
    const match = this.registry.match(pathname) as MatchResult;
 
    if (match) {
      match.url = url;
      match.query = query;
      match.context = mutable({ params: match.params, query, data: {} });
 
      // Evict oldest entry if at capacity
      if (this.cache.size >= this.maxSize) {
        const firstKey = this.cache.keys().next().value;
        if (firstKey !== undefined) {
          this.cache.delete(firstKey);
        }
      }
 
      // Cache the complete match result
      this.cache.set(cacheKey, match);
    }
 
    return match;
  }
}