All files / metadata/src/utilities/metadataProvider cacheData.ts

78.33% Statements 94/120
71.42% Branches 40/56
60.6% Functions 20/33
78.33% Lines 94/120

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                                          128x       128x                   140253x 140253x 645x 645x   140253x 140253x       140253x 140253x 108285x     31968x   31968x 33735x 202410x 202410x                 4224x 1536x   2688x 2688x 2688x 2688x 512x 512x   2688x         241585x               128x 128x 128x 128x       439x 439x   439x 183x   183x           183x       183x   256x 256x         256x                       177514x 177514x 177514x 62515x       114999x 114999x 6849x   108150x 108150x 108150x   108150x                                                                                     32103x               128x                 3456x 177514x     114999x             768x   768x 32103x 32103x 135x     135x     31968x 31968x       31968x 31968x       31968x 31833x 31833x     135x   135x 135x   135x     135x     135x   135x         128x       304x                                                                     3456x     3456x   3456x                 768x 768x     768x 768x   768x                 384x 384x 384x 384x     384x     384x     384x     384x        
import { getAddModuleType, MetadataModules } from '../../enums';
import {
  addAddProvider,
  addTypedProvider,
  clear,
  clearQuery,
  getMetaData,
} from '../../metaData';
import { BASE_IMAGE_ID, FRAME_IMAGE_IDS } from './imageIdsProviders';
 
interface CacheGetOptions {
  noCache?: boolean;
  reCache?: boolean;
}
 
type CacheRegistrationOptions = CacheGetOptions & {
  /** Register this cache type as secondary of one or more base cache types. */
  secondaryOf?: string | string[];
};
 
export class CacheData {
  protected static readonly mapCacheData = new Map<
    string,
    Map<string, unknown>
  >();
  protected static readonly secondaryTypesByBaseType = new Map<
    string,
    Set<string>
  >();
 
  protected static setCacheDataInternal(
    type: string,
    query: string,
    value: unknown
  ) {
    let valueMap = this.mapCacheData.get(type);
    if (!valueMap) {
      valueMap = new Map<string, unknown>();
      this.mapCacheData.set(type, valueMap);
    }
    valueMap.set(query, value);
    this.clearRelatedDerivedCache(type, query);
  }
 
  protected static clearRelatedDerivedCache(type: string, query: string) {
    const derivedTypes = this.secondaryTypesByBaseType.get(type);
    if (!derivedTypes?.size) {
      return;
    }
    const frameImageIds =
      (getMetaData(FRAME_IMAGE_IDS, query) as Set<string> | undefined) ??
      new Set<string>([query]);
    for (const frameImageId of frameImageIds) {
      for (const derivedType of derivedTypes) {
        const typeMap = this.mapCacheData.get(derivedType);
        typeMap?.delete(frameImageId);
      }
    }
  }
 
  static registerSecondaryTypes(
    secondaryType: string,
    secondaryOf?: string | string[]
  ) {
    if (!secondaryOf) {
      return;
    }
    const baseTypes = Array.isArray(secondaryOf) ? secondaryOf : [secondaryOf];
    for (const baseType of baseTypes) {
      let secondaryTypes = this.secondaryTypesByBaseType.get(baseType);
      if (!secondaryTypes) {
        secondaryTypes = new Set<string>();
        this.secondaryTypesByBaseType.set(baseType, secondaryTypes);
      }
      secondaryTypes.add(secondaryType);
    }
  }
 
  static getCacheData(type: string, query: string): unknown {
    return this.mapCacheData.get(type)?.get(query);
  }
 
  static hasCacheData(type: string, query: string): boolean {
    return this.mapCacheData.get(type)?.has(query) === true;
  }
 
  static clearCacheData() {
    this.mapCacheData.clear();
    this.secondaryTypesByBaseType.clear();
    clear(FRAME_IMAGE_IDS);
    clear(BASE_IMAGE_ID);
  }
 
  static clearTypedCacheData(type: string, query?: string) {
    const secondaryTypes = this.secondaryTypesByBaseType.get(type);
    const valueMap = this.mapCacheData.get(type);
 
    if (query) {
      valueMap?.delete(query);
 
      Iif (secondaryTypes?.size) {
        for (const secondaryType of secondaryTypes) {
          this.mapCacheData.get(secondaryType)?.delete(query);
        }
      }
 
      Iif (type === MetadataModules.NATURALIZED || secondaryTypes?.size) {
        clearQuery(FRAME_IMAGE_IDS, query);
        clearQuery(BASE_IMAGE_ID, query);
      }
      return;
    }
    valueMap?.clear();
    Iif (secondaryTypes?.size) {
      for (const secondaryType of secondaryTypes) {
        this.mapCacheData.get(secondaryType)?.clear();
      }
    }
    Iif (type === MetadataModules.NATURALIZED || secondaryTypes?.size) {
      clear(FRAME_IMAGE_IDS);
      clear(BASE_IMAGE_ID);
    }
  }
 
  static fromAsyncLookup<T>(
    type: string,
    query: string,
    lookup: () => T | Promise<T>,
    options?: CacheGetOptions
  ): T | Promise<T> | undefined {
    Eif (options?.noCache !== true && options?.reCache !== true) {
      const cachedValue = this.getCacheData(type, query);
      if (cachedValue !== undefined) {
        return cachedValue as T;
      }
    }
 
    const lookupValue = lookup();
    if (lookupValue === undefined) {
      return undefined;
    }
    Eif (!(lookupValue instanceof Promise)) {
      Eif (!options?.noCache) {
        this.setCacheDataInternal(type, query, lookupValue);
      }
      return lookupValue;
    }
 
    return lookupValue.then((resolvedValue) => {
      if (resolvedValue !== undefined && !options?.noCache) {
        this.setCacheDataInternal(type, query, resolvedValue);
      }
      return resolvedValue;
    });
  }
 
  createTypeCacheProvider(type: string) {
    return createTypeCacheProvider(type);
  }
 
  clearCacheData() {
    CacheData.clearCacheData();
  }
 
  clearTypedCacheData(type: string, query?: string) {
    CacheData.clearTypedCacheData(type, query);
  }
 
  getCacheData(type: string, query: string) {
    return CacheData.getCacheData(type, query);
  }
 
  hasCacheData(type: string, query: string) {
    return CacheData.hasCacheData(type, query);
  }
 
  fromAsyncLookup<T>(
    type: string,
    query: string,
    lookup: () => T | Promise<T>,
    options?: CacheGetOptions
  ) {
    return CacheData.fromAsyncLookup(type, query, lookup, options);
  }
}
 
export class WritableCacheData extends CacheData {
  static setCacheData(type: string, query: string, value: unknown) {
    this.setCacheDataInternal(type, query, value);
  }
 
  setCacheData(type: string, query: string, value: unknown) {
    WritableCacheData.setCacheData(type, query, value);
  }
}
 
export const cacheData: CacheData = new WritableCacheData();
 
/**
 * Creates a typed provider that caches results for the given type.
 *
 * Options can include: noCache to not cache this value or use the cached value,
 * and reCache to get a new value and add it to the cache.
 */
export function createTypeCacheProvider(type: string) {
  return (next, query: string, data, options) => {
    return CacheData.fromAsyncLookup(
      type,
      query,
      () => next(query, data, options),
      options
    );
  };
}
 
export function createTypeWritableCacheProvider(type: string) {
  const addType = getAddModuleType(type);
 
  return (next, query: string, data, options) => {
    const cachedValue = CacheData.getCacheData(type, query);
    if (cachedValue !== undefined) {
      console.warn(
        `Metadata add skipped for "${type}" at query "${query}" because cache already has a value.`
      );
      return cachedValue;
    }
 
    const addCachedValue = CacheData.getCacheData(addType, query);
    Iif (addCachedValue !== undefined) {
      return addCachedValue;
    }
 
    const nextValue = next(query, data, options);
    Iif (nextValue === undefined) {
      return undefined;
    }
 
    if (!(nextValue instanceof Promise)) {
      WritableCacheData.setCacheData(type, query, nextValue);
      return nextValue;
    }
 
    const managedPromise = nextValue
      .then((resolvedValue) => {
        Eif (resolvedValue !== undefined) {
          WritableCacheData.setCacheData(type, query, resolvedValue);
        }
        return resolvedValue;
      })
      .finally(() => {
        CacheData.clearTypedCacheData(addType, query);
      });
 
    WritableCacheData.setCacheData(addType, query, managedPromise);
 
    return managedPromise;
  };
}
 
export function clearCacheData() {
  CacheData.clearCacheData();
}
 
export function clearTypedCacheData(type: string, query?: string) {
  CacheData.clearTypedCacheData(type, query);
}
 
/**
 * Directly sets a value in the typed cache for the given type and query key.
 *
 * This is primarily an internal/advanced escape hatch for providers that need
 * explicit external writes (for example calibration-related providers). Most
 * metadata ingestion paths should use typed provider handlers instead.
 */
export function setCacheData(type: string, query: string, value: unknown) {
  WritableCacheData.setCacheData(type, query, value);
}
 
/**
 * Reads a value from the typed cache for the given type and query key.
 */
export function getCacheData(type: string, query: string): unknown {
  return CacheData.getCacheData(type, query);
}
 
export function hasCacheData(type: string, query: string): boolean {
  return CacheData.hasCacheData(type, query);
}
 
export function fromAsyncLookup<T>(
  type: string,
  query: string,
  lookup: () => T | Promise<T>,
  options?: CacheGetOptions
) {
  return CacheData.fromAsyncLookup(type, query, lookup, options);
}
 
export function addCacheForType(type: string, options?) {
  const { secondaryOf, ...providerOptions } = (options ??
    {}) as CacheRegistrationOptions;
 
  CacheData.registerSecondaryTypes(type, secondaryOf);
 
  addTypedProvider(type, createTypeCacheProvider(type), {
    priority: 50_000,
    clear: clearTypedCacheData.bind(null, type) as () => void,
    clearQuery: clearTypedCacheData.bind(null, type),
    ...providerOptions,
  });
}
 
export function addWritableCacheForType(type: string, options?) {
  const addType = getAddModuleType(type);
  const { secondaryOf, ...providerOptions } = (options ??
    {}) as CacheRegistrationOptions;
 
  addCacheForType(type, { secondaryOf, ...providerOptions });
  CacheData.registerSecondaryTypes(addType, type);
 
  addAddProvider(type, createTypeWritableCacheProvider(type), {
    priority: 50_000,
    clear: clearTypedCacheData.bind(null, addType) as () => void,
    clearQuery: clearTypedCacheData.bind(null, addType),
    ...providerOptions,
  });
}
 
export function registerCacheProviders() {
  addCacheForType(BASE_IMAGE_ID);
  addCacheForType(FRAME_IMAGE_IDS);
  addWritableCacheForType(MetadataModules.NATURALIZED);
  addCacheForType(MetadataModules.INSTANCE, {
    secondaryOf: MetadataModules.NATURALIZED,
  });
  addCacheForType(MetadataModules.URI_MODULE, {
    secondaryOf: MetadataModules.NATURALIZED,
  });
  addCacheForType(MetadataModules.IMAGE_PLANE, {
    secondaryOf: MetadataModules.NATURALIZED,
  });
  addCacheForType(MetadataModules.FRAME_MODULE, {
    secondaryOf: MetadataModules.NATURALIZED,
  });
  addCacheForType(MetadataModules.GENERAL_IMAGE, {
    secondaryOf: MetadataModules.NATURALIZED,
  });
}