fs-memo.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import path from 'node:path';
  2. import { isCI } from 'ci-info';
  3. import picocolors from 'picocolors';
  4. import { Cache } from './cache-filesystem';
  5. import { createMemoize } from 'foxts/serialized-memo';
  6. import type { MemoizeStorageProvider } from 'foxts/serialized-memo';
  7. const fsMemoCache = new Cache({ cachePath: path.resolve(__dirname, '../../.cache'), tableName: 'fs_memo_cache' });
  8. const fsMemoCacheProvider: MemoizeStorageProvider = {
  9. has(key) {
  10. return fsMemoCache.get(key) !== null;
  11. },
  12. delete() {
  13. // noop
  14. },
  15. get(key) {
  16. return fsMemoCache.get(key) ?? undefined;
  17. },
  18. set(key, value, ttl) {
  19. fsMemoCache.set(key, value, ttl);
  20. },
  21. updateTtl(key, ttl) {
  22. fsMemoCache.updateTtl(key, ttl);
  23. }
  24. };
  25. const TTL = isCI
  26. // We run CI daily, so 1.5 days TTL is enough to persist the cache across runs
  27. ? 1.5 * 86400 * 1000
  28. // We run locally less frequently, so we need to persist the cache for longer, 7 days
  29. : 7 * 86400 * 1000;
  30. export const cache = createMemoize(fsMemoCacheProvider, {
  31. defaultTtl: TTL,
  32. onCacheMiss(key, { humanReadableName, isUseCachedIfFail }) {
  33. const cacheName = picocolors.gray(humanReadableName);
  34. if (isUseCachedIfFail) {
  35. console.log(picocolors.red('[fail] and no cache, throwing'), cacheName);
  36. } else {
  37. console.log(picocolors.yellow('[cache] miss'), cacheName);
  38. }
  39. },
  40. onCacheUpdate(key, { humanReadableName, isUseCachedIfFail }) {
  41. const cacheName = picocolors.gray(humanReadableName);
  42. if (isUseCachedIfFail) {
  43. console.log(picocolors.gray('[cache] update'), cacheName);
  44. }
  45. },
  46. onCacheHit(key, { humanReadableName, isUseCachedIfFail }) {
  47. const cacheName = picocolors.gray(humanReadableName);
  48. if (isUseCachedIfFail) {
  49. console.log(picocolors.yellow('[fail] try cache'), cacheName);
  50. } else {
  51. console.log(picocolors.green('[cache] hit'), cacheName);
  52. }
  53. }
  54. });
  55. export const cachedOnlyFail = createMemoize(fsMemoCacheProvider, {
  56. defaultTtl: TTL,
  57. onlyUseCachedIfFail: true
  58. });
  59. // export const cache = createCache(false);
  60. // export const cachedOnlyFail = createCache(true);