cache-filesystem.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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, identity, mergeHeaders } from './misc';
  8. import { performance } from 'node:perf_hooks';
  9. import fs from 'node:fs';
  10. import { stringHash } from './string-hash';
  11. import { defaultRequestInit, fetchWithRetry } from './fetch-retry';
  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. useHttp304: Symbol('useHttp304'),
  42. humanReadable(ttl: number) {
  43. if (ttl >= ONE_DAY) {
  44. return `${Math.round(ttl / 24 / 60 / 60 / 1000)}d`;
  45. }
  46. if (ttl >= 60 * 60 * 1000) {
  47. return `${Math.round(ttl / 60 / 60 / 1000)}h`;
  48. }
  49. return `${Math.round(ttl / 1000)}s`;
  50. },
  51. THREE_HOURS: () => randomInt(1, 3) * ONE_HOUR,
  52. TWLVE_HOURS: () => randomInt(8, 12) * ONE_HOUR,
  53. ONE_DAY: () => randomInt(23, 25) * ONE_HOUR,
  54. ONE_WEEK_STATIC: ONE_DAY * 7,
  55. THREE_DAYS: () => randomInt(1, 3) * ONE_DAY,
  56. ONE_WEEK: () => randomInt(4, 7) * ONE_DAY,
  57. TEN_DAYS: () => randomInt(7, 10) * ONE_DAY,
  58. TWO_WEEKS: () => randomInt(10, 14) * ONE_DAY
  59. };
  60. export class Cache<S = string> {
  61. db: Database;
  62. /** Time before deletion */
  63. tbd = 60 * 1000;
  64. /** SQLite file path */
  65. cachePath: string;
  66. /** Table name */
  67. tableName: string;
  68. type: S extends string ? 'string' : 'buffer';
  69. constructor({
  70. cachePath = path.join(os.tmpdir() || '/tmp', 'hdc'),
  71. tbd,
  72. tableName = 'cache',
  73. type
  74. }: CacheOptions<S> = {}) {
  75. const start = performance.now();
  76. this.cachePath = cachePath;
  77. mkdirSync(this.cachePath, { recursive: true });
  78. if (tbd != null) this.tbd = tbd;
  79. this.tableName = tableName;
  80. if (type) {
  81. this.type = type;
  82. } else {
  83. // @ts-expect-error -- fallback type
  84. this.type = 'string';
  85. }
  86. const db = createDb(path.join(this.cachePath, 'cache.db'));
  87. db.pragma('journal_mode = WAL');
  88. db.pragma('synchronous = normal');
  89. db.pragma('temp_store = memory');
  90. db.pragma('optimize');
  91. db.prepare(`CREATE TABLE IF NOT EXISTS ${this.tableName} (key TEXT PRIMARY KEY, value ${this.type === 'string' ? 'TEXT' : 'BLOB'}, ttl REAL NOT NULL);`).run();
  92. db.prepare(`CREATE INDEX IF NOT EXISTS cache_ttl ON ${this.tableName} (ttl);`).run();
  93. const date = new Date();
  94. // perform purge on startup
  95. // ttl + tbd < now => ttl < now - tbd
  96. const now = date.getTime() - this.tbd;
  97. db.prepare(`DELETE FROM ${this.tableName} WHERE ttl < ?`).run(now);
  98. this.db = db;
  99. const dateString = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  100. const lastVaccum = this.get('__LAST_VACUUM');
  101. if (lastVaccum === undefined || (lastVaccum !== dateString && date.getUTCDay() === 6)) {
  102. console.log(picocolors.magenta('[cache] vacuuming'));
  103. this.set('__LAST_VACUUM', dateString, 10 * 365 * 60 * 60 * 24 * 1000);
  104. this.db.exec('VACUUM;');
  105. }
  106. const end = performance.now();
  107. console.log(`${picocolors.gray(`[${((end - start) / 1e6).toFixed(3)}ms]`)} cache initialized from ${this.cachePath}`);
  108. }
  109. set(key: string, value: string, ttl = 60 * 1000): void {
  110. const insert = this.db.prepare(
  111. `INSERT INTO ${this.tableName} (key, value, ttl) VALUES ($key, $value, $valid) ON CONFLICT(key) DO UPDATE SET value = $value, ttl = $valid`
  112. );
  113. const valid = Date.now() + ttl;
  114. insert.run({
  115. $key: key,
  116. key,
  117. $value: value,
  118. value,
  119. $valid: valid,
  120. valid
  121. });
  122. }
  123. get(key: string, defaultValue?: S): S | undefined {
  124. const rv = this.db.prepare<string, { value: S }>(
  125. `SELECT value FROM ${this.tableName} WHERE key = ? LIMIT 1`
  126. ).get(key);
  127. if (!rv) return defaultValue;
  128. return rv.value;
  129. }
  130. has(key: string): CacheStatus {
  131. const now = Date.now();
  132. const rv = this.db.prepare<string, { ttl: number }>(`SELECT ttl FROM ${this.tableName} WHERE key = ?`).get(key);
  133. return rv ? (rv.ttl > now ? CacheStatus.Hit : CacheStatus.Stale) : CacheStatus.Miss;
  134. }
  135. private updateTtl(key: string, ttl: number): void {
  136. this.db.prepare(`UPDATE ${this.tableName} SET ttl = ? WHERE key = ?;`).run(Date.now() + ttl, key);
  137. }
  138. del(key: string): void {
  139. this.db.prepare(`DELETE FROM ${this.tableName} WHERE key = ?`).run(key);
  140. }
  141. async apply<T>(
  142. key: string,
  143. fn: () => Promise<T>,
  144. opt: CacheApplyOption<T, S>
  145. ): Promise<T> {
  146. const { ttl, temporaryBypass, incrementTtlWhenHit } = opt;
  147. if (temporaryBypass) {
  148. return fn();
  149. }
  150. if (ttl == null) {
  151. this.del(key);
  152. return fn();
  153. }
  154. const cached = this.get(key);
  155. if (cached == null) {
  156. console.log(picocolors.yellow('[cache] miss'), picocolors.gray(key), picocolors.gray(`ttl: ${TTL.humanReadable(ttl)}`));
  157. const serializer = 'serializer' in opt ? opt.serializer : identity as any;
  158. const promise = fn();
  159. return promise.then((value) => {
  160. this.set(key, serializer(value), ttl);
  161. return value;
  162. });
  163. }
  164. console.log(picocolors.green('[cache] hit'), picocolors.gray(key));
  165. if (incrementTtlWhenHit) {
  166. this.updateTtl(key, ttl);
  167. }
  168. const deserializer = 'deserializer' in opt ? opt.deserializer : identity as any;
  169. return deserializer(cached);
  170. }
  171. async applyWithHttp304<T>(
  172. url: string,
  173. extraCacheKey: string,
  174. fn: (resp: Response) => Promise<T>,
  175. opt: Omit<CacheApplyOption<T, S>, 'ttl' | 'incrementTtlWhenHit'>,
  176. requestInit?: RequestInit
  177. ) {
  178. const { temporaryBypass } = opt;
  179. const ttl = TTL.ONE_WEEK_STATIC;
  180. if (temporaryBypass) {
  181. return fn(await fetchWithRetry(url, requestInit ?? defaultRequestInit));
  182. }
  183. const baseKey = url + '$' + extraCacheKey;
  184. const etagKey = baseKey + '$etag';
  185. const cachedKey = baseKey + '$cached';
  186. const onMiss = (resp: Response) => {
  187. console.log(picocolors.yellow('[cache] miss'), url, picocolors.gray(`ttl: ${TTL.humanReadable(ttl)}`));
  188. const serializer = 'serializer' in opt ? opt.serializer : identity as any;
  189. const etag = resp.headers.get('etag');
  190. if (!etag) {
  191. console.log(picocolors.red('[cache] no etag'), picocolors.gray(url));
  192. return fn(resp);
  193. }
  194. const promise = fn(resp);
  195. return promise.then((value) => {
  196. this.set(etagKey, etag, ttl);
  197. this.set(cachedKey, serializer(value), ttl);
  198. return value;
  199. });
  200. };
  201. const cached = this.get(cachedKey);
  202. if (cached == null) {
  203. return onMiss(await fetchWithRetry(url, requestInit ?? defaultRequestInit));
  204. }
  205. const etag = this.get(etagKey);
  206. const resp = await fetchWithRetry(
  207. url,
  208. {
  209. ...(requestInit ?? defaultRequestInit),
  210. headers: (typeof etag === 'string' && etag.length > 0)
  211. ? mergeHeaders(
  212. (requestInit ?? defaultRequestInit).headers,
  213. { 'If-None-Match': etag }
  214. )
  215. : (requestInit ?? defaultRequestInit).headers
  216. }
  217. );
  218. if (resp.status !== 304) {
  219. return onMiss(resp);
  220. }
  221. console.log(picocolors.green('[cache] http 304'), picocolors.gray(url));
  222. this.updateTtl(cachedKey, ttl);
  223. const deserializer = 'deserializer' in opt ? opt.deserializer : identity as any;
  224. return deserializer(cached);
  225. }
  226. destroy() {
  227. this.db.close();
  228. }
  229. }
  230. export const fsFetchCache = new Cache({ cachePath: path.resolve(__dirname, '../../.cache') });
  231. // process.on('exit', () => {
  232. // fsFetchCache.destroy();
  233. // });
  234. // export const fsCache = traceSync('initializing filesystem cache', () => new Cache<Uint8Array>({ cachePath: path.resolve(__dirname, '../../.cache'), type: 'buffer' }));
  235. const separator = '\u0000';
  236. export const serializeSet = (set: Set<string>) => fastStringArrayJoin(Array.from(set), separator);
  237. export const deserializeSet = (str: string) => new Set(str.split(separator));
  238. export const serializeArray = (arr: string[]) => fastStringArrayJoin(arr, separator);
  239. export const deserializeArray = (str: string) => str.split(separator);
  240. export const getFileContentHash = (filename: string) => stringHash(fs.readFileSync(filename, 'utf-8'));
  241. export const createCacheKey = (filename: string) => {
  242. const fileHash = getFileContentHash(filename);
  243. return (key: string) => key + '$' + fileHash + '$';
  244. };