cache-filesystem.ts 6.8 KB

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