fs-memo.ts 2.1 KB

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