cache-filesystem.ts 6.8 KB

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