cache-filesystem.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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.prepare('CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY, value TEXT, ttl REAL NOT NULL);').run();
  63. db.prepare('CREATE INDEX IF NOT EXISTS cache_ttl ON cache (ttl);').run();
  64. // perform purge on startup
  65. // ttl + tbd < now => ttl < now - tbd
  66. const now = Date.now() - this.tbd;
  67. db.prepare('DELETE FROM cache WHERE ttl < ?').run(now);
  68. this.db = db;
  69. }
  70. set(key: string, value: string, ttl = 60 * 1000): void {
  71. const insert = this.db.prepare(
  72. 'INSERT INTO cache (key, value, ttl) VALUES ($key, $value, $valid) ON CONFLICT(key) DO UPDATE SET value = $value, ttl = $valid'
  73. );
  74. insert.run({
  75. $key: key,
  76. $value: value,
  77. $valid: Date.now() + ttl
  78. });
  79. }
  80. get(key: string, defaultValue?: string): string | undefined {
  81. const rv = this.db.prepare<{ value: string }, string>(
  82. 'SELECT value FROM cache WHERE key = ?'
  83. ).get(key);
  84. if (!rv) return defaultValue;
  85. return rv.value;
  86. }
  87. has(key: string): CacheStatus {
  88. const now = Date.now();
  89. const rv = this.db.prepare<{ ttl: number }, string>('SELECT ttl FROM cache WHERE key = ?').get(key);
  90. return !rv ? CacheStatus.Miss : (rv.ttl > now ? CacheStatus.Hit : CacheStatus.Stale);
  91. }
  92. del(key: string): void {
  93. this.db.prepare('DELETE FROM cache WHERE key = ?').run(key);
  94. }
  95. async apply<T>(
  96. key: string,
  97. fn: () => Promise<T>,
  98. opt: CacheApplyOption<T>
  99. ): Promise<T> {
  100. const { ttl, temporaryBypass } = opt;
  101. if (temporaryBypass) {
  102. return fn();
  103. }
  104. if (ttl == null) {
  105. this.del(key);
  106. return fn();
  107. }
  108. const cached = this.get(key);
  109. let value: T;
  110. if (cached == null) {
  111. console.log(picocolors.yellow('[cache] miss'), picocolors.gray(key), picocolors.gray(`ttl: ${TTL.humanReadable(ttl)}`));
  112. value = await fn();
  113. const serializer = 'serializer' in opt ? opt.serializer : identity;
  114. this.set(key, serializer(value), ttl);
  115. } else {
  116. console.log(picocolors.green('[cache] hit'), picocolors.gray(key));
  117. const deserializer = 'deserializer' in opt ? opt.deserializer : identity;
  118. value = deserializer(cached);
  119. }
  120. return value;
  121. }
  122. destroy() {
  123. this.db.close();
  124. }
  125. }
  126. export const fsCache = traceSync('initializing filesystem cache', () => new Cache({ cachePath: path.resolve(import.meta.dir, '../../.cache') }));
  127. // process.on('exit', () => {
  128. // fsCache.destroy();
  129. // });
  130. const separator = '\u0000';
  131. // const textEncoder = new TextEncoder();
  132. // const textDecoder = new TextDecoder();
  133. // export const serializeString = (str: string) => textEncoder.encode(str);
  134. // export const deserializeString = (str: string) => textDecoder.decode(new Uint8Array(str.split(separator).map(Number)));
  135. export const serializeSet = (set: Set<string>) => Array.from(set).join(separator);
  136. export const deserializeSet = (str: string) => new Set(str.split(separator));
  137. export const serializeArray = (arr: string[]) => arr.join(separator);
  138. export const deserializeArray = (str: string) => str.split(separator);