cache-filesystem.ts 6.3 KB

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