cache-filesystem.ts 6.8 KB

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