cache-filesystem.ts 6.7 KB

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