cache-filesystem.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. import createDb from 'better-sqlite3';
  2. import type { Database } from 'better-sqlite3';
  3. import os from 'node:os';
  4. import path from 'node:path';
  5. import { mkdirSync } from 'node:fs';
  6. import picocolors from 'picocolors';
  7. import { fastStringArrayJoin } from './misc';
  8. import { performance } from 'node:perf_hooks';
  9. import fs from 'node:fs';
  10. import { stringHash } from './string-hash';
  11. const identity = (x: any) => x;
  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 = createDb(path.join(this.cachePath, 'cache.db'));
  84. db.pragma('journal_mode = WAL');
  85. db.pragma('synchronous = normal');
  86. db.pragma('temp_store = memory');
  87. db.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. const valid = Date.now() + ttl;
  111. insert.run({
  112. $key: key,
  113. key,
  114. $value: value,
  115. value,
  116. $valid: valid,
  117. valid
  118. });
  119. }
  120. get(key: string, defaultValue?: S): S | undefined {
  121. const rv = this.db.prepare<string, { value: S }>(
  122. `SELECT value FROM ${this.tableName} WHERE key = ? LIMIT 1`
  123. ).get(key);
  124. if (!rv) return defaultValue;
  125. return rv.value;
  126. }
  127. has(key: string): CacheStatus {
  128. const now = Date.now();
  129. const rv = this.db.prepare<string, { ttl: number }>(`SELECT ttl FROM ${this.tableName} WHERE key = ?`).get(key);
  130. return rv ? (rv.ttl > now ? CacheStatus.Hit : CacheStatus.Stale) : CacheStatus.Miss;
  131. }
  132. del(key: string): void {
  133. this.db.prepare(`DELETE FROM ${this.tableName} WHERE key = ?`).run(key);
  134. }
  135. async apply<T>(
  136. key: string,
  137. fn: () => Promise<T>,
  138. opt: CacheApplyOption<T, S>
  139. ): Promise<T> {
  140. const { ttl, temporaryBypass } = opt;
  141. if (temporaryBypass) {
  142. return fn();
  143. }
  144. if (ttl == null) {
  145. this.del(key);
  146. return fn();
  147. }
  148. const cached = this.get(key);
  149. if (cached == null) {
  150. console.log(picocolors.yellow('[cache] miss'), picocolors.gray(key), picocolors.gray(`ttl: ${TTL.humanReadable(ttl)}`));
  151. const serializer = 'serializer' in opt ? opt.serializer : identity;
  152. const promise = fn();
  153. return promise.then((value) => {
  154. this.set(key, serializer(value), ttl);
  155. return value;
  156. });
  157. }
  158. console.log(picocolors.green('[cache] hit'), picocolors.gray(key));
  159. const deserializer = 'deserializer' in opt ? opt.deserializer : identity;
  160. return deserializer(cached);
  161. }
  162. destroy() {
  163. this.db.close();
  164. }
  165. }
  166. export const fsFetchCache = new Cache({ cachePath: path.resolve(__dirname, '../../.cache') });
  167. // process.on('exit', () => {
  168. // fsFetchCache.destroy();
  169. // });
  170. // export const fsCache = traceSync('initializing filesystem cache', () => new Cache<Uint8Array>({ cachePath: path.resolve(__dirname, '../../.cache'), type: 'buffer' }));
  171. const separator = '\u0000';
  172. export const serializeSet = (set: Set<string>) => fastStringArrayJoin(Array.from(set), separator);
  173. export const deserializeSet = (str: string) => new Set(str.split(separator));
  174. export const serializeArray = (arr: string[]) => fastStringArrayJoin(arr, separator);
  175. export const deserializeArray = (str: string) => str.split(separator);
  176. export const createCacheKey = (filename: string) => {
  177. const fileHash = stringHash(fs.readFileSync(filename, 'utf-8'));
  178. return (key: string) => key + '$' + fileHash;
  179. };