cache-filesystem.ts 6.7 KB

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