cache-filesystem.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. // eslint-disable-next-line import-x/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 { fastStringArrayJoin } from './misc';
  8. import { peek } from 'bun';
  9. import { performance } from 'perf_hooks';
  10. const identity = (x: any) => x;
  11. // eslint-disable-next-line sukka-ts/no-const-enum -- bun is smart, right?
  12. const enum CacheStatus {
  13. Hit = 'hit',
  14. Stale = 'stale',
  15. Miss = 'miss'
  16. }
  17. export interface CacheOptions<S = string> {
  18. /** Path to sqlite file dir */
  19. cachePath?: string,
  20. /** Time before deletion */
  21. tbd?: number,
  22. /** Cache table name */
  23. tableName?: string,
  24. type?: S extends string ? 'string' : 'buffer'
  25. }
  26. interface CacheApplyRawOption {
  27. ttl?: number | null,
  28. temporaryBypass?: boolean
  29. }
  30. interface CacheApplyNonRawOption<T, S> extends CacheApplyRawOption {
  31. serializer: (value: T) => S,
  32. deserializer: (cached: S) => T
  33. }
  34. type CacheApplyOption<T, S> = T extends S ? CacheApplyRawOption : CacheApplyNonRawOption<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'),
  68. tbd,
  69. tableName = 'cache',
  70. type
  71. }: CacheOptions<S> = {}) {
  72. const start = performance.now();
  73. this.cachePath = cachePath;
  74. mkdirSync(this.cachePath, { recursive: true });
  75. if (tbd != null) this.tbd = tbd;
  76. this.tableName = tableName;
  77. if (type) {
  78. this.type = type;
  79. } else {
  80. // @ts-expect-error -- fallback type
  81. this.type = 'string';
  82. }
  83. const db = new Database(path.join(this.cachePath, 'cache.db'));
  84. db.exec('PRAGMA journal_mode = WAL;');
  85. db.exec('PRAGMA synchronous = normal;');
  86. db.exec('PRAGMA temp_store = memory;');
  87. db.exec('PRAGMA optimize;');
  88. db.prepare(`CREATE TABLE IF NOT EXISTS ${this.tableName} (key TEXT PRIMARY KEY, value ${this.type === 'string' ? 'TEXT' : 'BLOB'}, ttl REAL NOT NULL);`).run();
  89. db.prepare(`CREATE INDEX IF NOT EXISTS cache_ttl ON ${this.tableName} (ttl);`).run();
  90. const date = new Date();
  91. // perform purge on startup
  92. // ttl + tbd < now => ttl < now - tbd
  93. const now = date.getTime() - this.tbd;
  94. db.prepare(`DELETE FROM ${this.tableName} WHERE ttl < ?`).run(now);
  95. this.db = db;
  96. const dateString = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  97. const lastVaccum = this.get('__LAST_VACUUM');
  98. if (lastVaccum === undefined || (lastVaccum !== dateString && date.getUTCDay() === 6)) {
  99. console.log(picocolors.magenta('[cache] vacuuming'));
  100. this.set('__LAST_VACUUM', dateString, 10 * 365 * 60 * 60 * 24 * 1000);
  101. this.db.exec('VACUUM;');
  102. }
  103. const end = performance.now();
  104. console.log(`${picocolors.gray(`[${((end - start) / 1e6).toFixed(3)}ms]`)} cache initialized from ${this.cachePath}`);
  105. }
  106. set(key: string, value: string, ttl = 60 * 1000): void {
  107. const insert = this.db.prepare(
  108. `INSERT INTO ${this.tableName} (key, value, ttl) VALUES ($key, $value, $valid) ON CONFLICT(key) DO UPDATE SET value = $value, ttl = $valid`
  109. );
  110. insert.run({
  111. $key: key,
  112. $value: value,
  113. $valid: Date.now() + ttl
  114. });
  115. }
  116. get(key: string, defaultValue?: S): S | undefined {
  117. const rv = this.db.prepare<{ value: S }, string>(
  118. `SELECT value FROM ${this.tableName} WHERE key = ? LIMIT 1`
  119. ).get(key);
  120. if (!rv) return defaultValue;
  121. return rv.value;
  122. }
  123. has(key: string): CacheStatus {
  124. const now = Date.now();
  125. const rv = this.db.prepare<{ ttl: number }, string>(`SELECT ttl FROM ${this.tableName} WHERE key = ?`).get(key);
  126. return !rv ? CacheStatus.Miss : (rv.ttl > now ? CacheStatus.Hit : CacheStatus.Stale);
  127. }
  128. del(key: string): void {
  129. this.db.prepare(`DELETE FROM ${this.tableName} WHERE key = ?`).run(key);
  130. }
  131. async apply<T>(
  132. key: string,
  133. fn: () => Promise<T>,
  134. opt: CacheApplyOption<T, S>
  135. ): Promise<T> {
  136. const { ttl, temporaryBypass } = opt;
  137. if (temporaryBypass) {
  138. return fn();
  139. }
  140. if (ttl == null) {
  141. this.del(key);
  142. return fn();
  143. }
  144. const cached = this.get(key);
  145. let value: T;
  146. if (cached == null) {
  147. console.log(picocolors.yellow('[cache] miss'), picocolors.gray(key), picocolors.gray(`ttl: ${TTL.humanReadable(ttl)}`));
  148. const serializer = 'serializer' in opt ? opt.serializer : identity;
  149. const promise = fn();
  150. const peeked = peek(promise);
  151. if (peeked === promise) {
  152. return promise.then((value) => {
  153. this.set(key, serializer(value), ttl);
  154. return value;
  155. });
  156. }
  157. value = peeked as T;
  158. this.set(key, serializer(value), ttl);
  159. } else {
  160. console.log(picocolors.green('[cache] hit'), picocolors.gray(key));
  161. const deserializer = 'deserializer' in opt ? opt.deserializer : identity;
  162. value = deserializer(cached);
  163. }
  164. return value;
  165. }
  166. destroy() {
  167. this.db.close();
  168. }
  169. }
  170. export const fsFetchCache = new Cache({ cachePath: path.resolve(import.meta.dir, '../../.cache') });
  171. // process.on('exit', () => {
  172. // fsFetchCache.destroy();
  173. // });
  174. // export const fsCache = traceSync('initializing filesystem cache', () => new Cache<Uint8Array>({ cachePath: path.resolve(import.meta.dir, '../../.cache'), type: 'buffer' }));
  175. const separator = '\u0000';
  176. // const textEncoder = new TextEncoder();
  177. // const textDecoder = new TextDecoder();
  178. // export const serializeString = (str: string) => textEncoder.encode(str);
  179. // export const deserializeString = (str: string) => textDecoder.decode(new Uint8Array(str.split(separator).map(Number)));
  180. export const serializeSet = (set: Set<string>) => fastStringArrayJoin(Array.from(set), separator);
  181. export const deserializeSet = (str: string) => new Set(str.split(separator));
  182. export const serializeArray = (arr: string[]) => fastStringArrayJoin(arr, separator);
  183. export const deserializeArray = (str: string) => str.split(separator);