cache-filesystem.ts 6.8 KB

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