cache-filesystem.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. // eslint-disable-next-line import/no-unresolved -- bun built-in module
  2. import { Database } from 'bun:sqlite';
  3. import os from 'os';
  4. import path from 'path';
  5. import { mkdirSync } from 'fs';
  6. import picocolors from 'picocolors';
  7. import { traceSync } from './trace-runner';
  8. const identity = (x: any) => x;
  9. // eslint-disable-next-line sukka-ts/no-const-enum -- bun is smart, right?
  10. const enum CacheStatus {
  11. Hit = 'hit',
  12. Stale = 'stale',
  13. Miss = 'miss'
  14. }
  15. export interface CacheOptions {
  16. cachePath?: string,
  17. tbd?: number
  18. }
  19. interface CacheApplyNonStringOption<T> {
  20. ttl?: number | null,
  21. serializer: (value: T) => string,
  22. deserializer: (cached: string) => T,
  23. temporaryBypass?: boolean
  24. }
  25. interface CacheApplyStringOption {
  26. ttl?: number | null,
  27. temporaryBypass?: boolean
  28. }
  29. type CacheApplyOption<T> = T extends string ? CacheApplyStringOption : CacheApplyNonStringOption<T>;
  30. const randomInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min;
  31. const ONE_HOUR = 60 * 60 * 1000;
  32. const ONE_DAY = 24 * ONE_HOUR;
  33. // Add some randomness to the cache ttl to avoid thundering herd
  34. export const TTL = {
  35. humanReadable(ttl: number) {
  36. if (ttl >= ONE_DAY) {
  37. return `${Math.round(ttl / 24 / 60 / 60 / 1000)}d`;
  38. }
  39. if (ttl >= 60 * 60 * 1000) {
  40. return `${Math.round(ttl / 60 / 60 / 1000)}h`;
  41. }
  42. return `${Math.round(ttl / 1000)}s`;
  43. },
  44. THREE_HOURS: () => randomInt(1, 3) * ONE_HOUR,
  45. TWLVE_HOURS: () => randomInt(8, 12) * ONE_HOUR,
  46. ONE_DAY: () => randomInt(23, 25) * ONE_HOUR,
  47. THREE_DAYS: () => randomInt(1, 3) * ONE_DAY,
  48. ONE_WEEK: () => randomInt(4, 7) * ONE_DAY,
  49. TEN_DAYS: () => randomInt(7, 10) * ONE_DAY,
  50. TWO_WEEKS: () => randomInt(10, 14) * ONE_DAY
  51. };
  52. export class Cache {
  53. db: Database;
  54. tbd = 60 * 1000; // time before deletion
  55. cachePath: string;
  56. constructor({ cachePath = path.join(os.tmpdir() || '/tmp', 'hdc'), tbd }: CacheOptions = {}) {
  57. this.cachePath = cachePath;
  58. mkdirSync(this.cachePath, { recursive: true });
  59. if (tbd != null) this.tbd = tbd;
  60. const db = new Database(path.join(this.cachePath, 'cache.db'));
  61. db.exec('PRAGMA journal_mode = WAL;');
  62. db.exec('PRAGMA synchronous = normal;');
  63. db.exec('PRAGMA temp_store = memory;');
  64. db.exec('PRAGMA optimize;');
  65. db.prepare('CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY, value TEXT, ttl REAL NOT NULL);').run();
  66. db.prepare('CREATE INDEX IF NOT EXISTS cache_ttl ON cache (ttl);').run();
  67. const date = new Date();
  68. // perform purge on startup
  69. // ttl + tbd < now => ttl < now - tbd
  70. const now = date.getTime() - this.tbd;
  71. db.prepare('DELETE FROM cache WHERE ttl < ?').run(now);
  72. this.db = db;
  73. const dateString = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  74. const lastVaccum = this.get('__LAST_VACUUM');
  75. if (lastVaccum === undefined || (lastVaccum !== dateString && date.getUTCDay() === 6)) {
  76. console.log(picocolors.magenta('[cache] vacuuming'));
  77. this.set('__LAST_VACUUM', dateString, 10 * 365 * 60 * 60 * 24 * 1000);
  78. this.db.exec('VACUUM;');
  79. }
  80. }
  81. set(key: string, value: string, ttl = 60 * 1000): void {
  82. const insert = this.db.prepare(
  83. 'INSERT INTO cache (key, value, ttl) VALUES ($key, $value, $valid) ON CONFLICT(key) DO UPDATE SET value = $value, ttl = $valid'
  84. );
  85. insert.run({
  86. $key: key,
  87. $value: value,
  88. $valid: Date.now() + ttl
  89. });
  90. }
  91. get(key: string, defaultValue?: string): string | undefined {
  92. const rv = this.db.prepare<{ value: string }, string>(
  93. 'SELECT value FROM cache WHERE key = ?'
  94. ).get(key);
  95. if (!rv) return defaultValue;
  96. return rv.value;
  97. }
  98. has(key: string): CacheStatus {
  99. const now = Date.now();
  100. const rv = this.db.prepare<{ ttl: number }, string>('SELECT ttl FROM cache WHERE key = ?').get(key);
  101. return !rv ? CacheStatus.Miss : (rv.ttl > now ? CacheStatus.Hit : CacheStatus.Stale);
  102. }
  103. del(key: string): void {
  104. this.db.prepare('DELETE FROM cache WHERE key = ?').run(key);
  105. }
  106. async apply<T>(
  107. key: string,
  108. fn: () => Promise<T>,
  109. opt: CacheApplyOption<T>
  110. ): Promise<T> {
  111. const { ttl, temporaryBypass } = opt;
  112. if (temporaryBypass) {
  113. return fn();
  114. }
  115. if (ttl == null) {
  116. this.del(key);
  117. return fn();
  118. }
  119. const cached = this.get(key);
  120. let value: T;
  121. if (cached == null) {
  122. console.log(picocolors.yellow('[cache] miss'), picocolors.gray(key), picocolors.gray(`ttl: ${TTL.humanReadable(ttl)}`));
  123. value = await fn();
  124. const serializer = 'serializer' in opt ? opt.serializer : identity;
  125. this.set(key, serializer(value), ttl);
  126. } else {
  127. console.log(picocolors.green('[cache] hit'), picocolors.gray(key));
  128. const deserializer = 'deserializer' in opt ? opt.deserializer : identity;
  129. value = deserializer(cached);
  130. }
  131. return value;
  132. }
  133. destroy() {
  134. this.db.close();
  135. }
  136. }
  137. export const fsCache = traceSync('initializing filesystem cache', () => new Cache({ cachePath: path.resolve(import.meta.dir, '../../.cache') }));
  138. // process.on('exit', () => {
  139. // fsCache.destroy();
  140. // });
  141. const separator = '\u0000';
  142. // const textEncoder = new TextEncoder();
  143. // const textDecoder = new TextDecoder();
  144. // export const serializeString = (str: string) => textEncoder.encode(str);
  145. // export const deserializeString = (str: string) => textDecoder.decode(new Uint8Array(str.split(separator).map(Number)));
  146. export const serializeSet = (set: Set<string>) => Array.from(set).join(separator);
  147. export const deserializeSet = (str: string) => new Set(str.split(separator));
  148. export const serializeArray = (arr: string[]) => arr.join(separator);
  149. export const deserializeArray = (str: string) => str.split(separator);