cache-filesystem.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. // @ts-expect-error -- fallback type
  78. this.type = 'string';
  79. }
  80. const db = new Database(path.join(this.cachePath, 'cache.db'));
  81. db.exec('PRAGMA journal_mode = WAL;');
  82. db.exec('PRAGMA synchronous = normal;');
  83. db.exec('PRAGMA temp_store = memory;');
  84. db.exec('PRAGMA optimize;');
  85. db.prepare(`CREATE TABLE IF NOT EXISTS ${this.tableName} (key TEXT PRIMARY KEY, value ${this.type === 'string' ? 'TEXT' : 'BLOB'}, ttl REAL NOT NULL);`).run();
  86. db.prepare(`CREATE INDEX IF NOT EXISTS cache_ttl ON ${this.tableName} (ttl);`).run();
  87. const date = new Date();
  88. // perform purge on startup
  89. // ttl + tbd < now => ttl < now - tbd
  90. const now = date.getTime() - this.tbd;
  91. db.prepare(`DELETE FROM ${this.tableName} WHERE ttl < ?`).run(now);
  92. this.db = db;
  93. const dateString = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  94. const lastVaccum = this.get('__LAST_VACUUM');
  95. if (lastVaccum === undefined || (lastVaccum !== dateString && date.getUTCDay() === 6)) {
  96. console.log(picocolors.magenta('[cache] vacuuming'));
  97. this.set('__LAST_VACUUM', dateString, 10 * 365 * 60 * 60 * 24 * 1000);
  98. this.db.exec('VACUUM;');
  99. }
  100. const end = Bun.nanoseconds();
  101. console.log(`${picocolors.gray(`[${((end - start) / 1e6).toFixed(3)}ms]`)} cache initialized from ${this.cachePath}`);
  102. }
  103. set(key: string, value: string, ttl = 60 * 1000): void {
  104. const insert = this.db.prepare(
  105. `INSERT INTO ${this.tableName} (key, value, ttl) VALUES ($key, $value, $valid) ON CONFLICT(key) DO UPDATE SET value = $value, ttl = $valid`
  106. );
  107. insert.run({
  108. $key: key,
  109. $value: value,
  110. $valid: Date.now() + ttl
  111. });
  112. }
  113. get(key: string, defaultValue?: S): S | undefined {
  114. const rv = this.db.prepare<{ value: S }, string>(
  115. `SELECT value FROM ${this.tableName} WHERE key = ? LIMIT 1`
  116. ).get(key);
  117. if (!rv) return defaultValue;
  118. return rv.value;
  119. }
  120. has(key: string): CacheStatus {
  121. const now = Date.now();
  122. const rv = this.db.prepare<{ ttl: number }, string>(`SELECT ttl FROM ${this.tableName} WHERE key = ?`).get(key);
  123. return !rv ? CacheStatus.Miss : (rv.ttl > now ? CacheStatus.Hit : CacheStatus.Stale);
  124. }
  125. del(key: string): void {
  126. this.db.prepare(`DELETE FROM ${this.tableName} WHERE key = ?`).run(key);
  127. }
  128. async apply<T>(
  129. key: string,
  130. fn: () => Promise<T>,
  131. opt: CacheApplyOption<T, S>
  132. ): Promise<T> {
  133. const { ttl, temporaryBypass } = opt;
  134. if (temporaryBypass) {
  135. return fn();
  136. }
  137. if (ttl == null) {
  138. this.del(key);
  139. return fn();
  140. }
  141. const cached = this.get(key);
  142. let value: T;
  143. if (cached == null) {
  144. console.log(picocolors.yellow('[cache] miss'), picocolors.gray(key), picocolors.gray(`ttl: ${TTL.humanReadable(ttl)}`));
  145. const serializer = 'serializer' in opt ? opt.serializer : identity;
  146. const promise = fn();
  147. const peeked = Bun.peek(promise);
  148. if (peeked === promise) {
  149. return promise.then((value) => {
  150. this.set(key, serializer(value), ttl);
  151. return value;
  152. });
  153. }
  154. value = peeked as T;
  155. this.set(key, serializer(value), ttl);
  156. } else {
  157. console.log(picocolors.green('[cache] hit'), picocolors.gray(key));
  158. const deserializer = 'deserializer' in opt ? opt.deserializer : identity;
  159. value = deserializer(cached);
  160. }
  161. return value;
  162. }
  163. destroy() {
  164. this.db.close();
  165. }
  166. }
  167. export const fsFetchCache = new Cache({ cachePath: path.resolve(import.meta.dir, '../../.cache') });
  168. // process.on('exit', () => {
  169. // fsFetchCache.destroy();
  170. // });
  171. // export const fsCache = traceSync('initializing filesystem cache', () => new Cache<Uint8Array>({ cachePath: path.resolve(import.meta.dir, '../../.cache'), type: 'buffer' }));
  172. const separator = '\u0000';
  173. // const textEncoder = new TextEncoder();
  174. // const textDecoder = new TextDecoder();
  175. // export const serializeString = (str: string) => textEncoder.encode(str);
  176. // export const deserializeString = (str: string) => textDecoder.decode(new Uint8Array(str.split(separator).map(Number)));
  177. export const serializeSet = (set: Set<string>) => Array.from(set).join(separator);
  178. export const deserializeSet = (str: string) => new Set(str.split(separator));
  179. export const serializeArray = (arr: string[]) => arr.join(separator);
  180. export const deserializeArray = (str: string) => str.split(separator);