cache-filesystem.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. import { Custom304NotModifiedError, CustomAbortError, CustomNoETagFallbackError, fetchAssets, sleepWithAbort } from './fetch-assets';
  13. const enum CacheStatus {
  14. Hit = 'hit',
  15. Stale = 'stale',
  16. Miss = 'miss'
  17. }
  18. export interface CacheOptions<S = string> {
  19. /** Path to sqlite file dir */
  20. cachePath?: string,
  21. /** Time before deletion */
  22. tbd?: number,
  23. /** Cache table name */
  24. tableName?: string,
  25. type?: S extends string ? 'string' : 'buffer'
  26. }
  27. interface CacheApplyRawOption {
  28. ttl?: number | null,
  29. temporaryBypass?: boolean,
  30. incrementTtlWhenHit?: boolean
  31. }
  32. interface CacheApplyNonRawOption<T, S> extends CacheApplyRawOption {
  33. serializer: (value: T) => S,
  34. deserializer: (cached: S) => T
  35. }
  36. type CacheApplyOption<T, S> = T extends S ? CacheApplyRawOption : CacheApplyNonRawOption<T, S>;
  37. const randomInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min;
  38. const ONE_HOUR = 60 * 60 * 1000;
  39. const ONE_DAY = 24 * ONE_HOUR;
  40. // Add some randomness to the cache ttl to avoid thundering herd
  41. export const TTL = {
  42. useHttp304: Symbol('useHttp304'),
  43. humanReadable(ttl: number) {
  44. if (ttl >= ONE_DAY) {
  45. return `${Math.round(ttl / 24 / 60 / 60 / 1000)}d`;
  46. }
  47. if (ttl >= 60 * 60 * 1000) {
  48. return `${Math.round(ttl / 60 / 60 / 1000)}h`;
  49. }
  50. return `${Math.round(ttl / 1000)}s`;
  51. },
  52. THREE_HOURS: () => randomInt(1, 3) * ONE_HOUR,
  53. TWLVE_HOURS: () => randomInt(8, 12) * ONE_HOUR,
  54. ONE_DAY: () => randomInt(23, 25) * ONE_HOUR,
  55. ONE_WEEK_STATIC: ONE_DAY * 7,
  56. THREE_DAYS: () => randomInt(1, 3) * ONE_DAY,
  57. ONE_WEEK: () => randomInt(4, 7) * ONE_DAY,
  58. TEN_DAYS: () => randomInt(7, 10) * ONE_DAY,
  59. TWO_WEEKS: () => randomInt(10, 14) * ONE_DAY
  60. };
  61. export class Cache<S = string> {
  62. db: Database;
  63. /** Time before deletion */
  64. tbd = 60 * 1000;
  65. /** SQLite file path */
  66. cachePath: string;
  67. /** Table name */
  68. tableName: string;
  69. type: S extends string ? 'string' : 'buffer';
  70. constructor({
  71. cachePath = path.join(os.tmpdir() || '/tmp', 'hdc'),
  72. tbd,
  73. tableName = 'cache',
  74. type
  75. }: CacheOptions<S> = {}) {
  76. const start = performance.now();
  77. this.cachePath = cachePath;
  78. mkdirSync(this.cachePath, { recursive: true });
  79. if (tbd != null) this.tbd = tbd;
  80. this.tableName = tableName;
  81. if (type) {
  82. this.type = type;
  83. } else {
  84. // @ts-expect-error -- fallback type
  85. this.type = 'string';
  86. }
  87. const db = createDb(path.join(this.cachePath, 'cache.db'));
  88. db.pragma('journal_mode = WAL');
  89. db.pragma('synchronous = normal');
  90. db.pragma('temp_store = memory');
  91. db.pragma('optimize');
  92. db.prepare(`CREATE TABLE IF NOT EXISTS ${this.tableName} (key TEXT PRIMARY KEY, value ${this.type === 'string' ? 'TEXT' : 'BLOB'}, ttl REAL NOT NULL);`).run();
  93. db.prepare(`CREATE INDEX IF NOT EXISTS cache_ttl ON ${this.tableName} (ttl);`).run();
  94. const date = new Date();
  95. // perform purge on startup
  96. // ttl + tbd < now => ttl < now - tbd
  97. const now = date.getTime() - this.tbd;
  98. db.prepare(`DELETE FROM ${this.tableName} WHERE ttl < ?`).run(now);
  99. this.db = db;
  100. const dateString = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  101. const lastVaccum = this.get('__LAST_VACUUM');
  102. if (lastVaccum === undefined || (lastVaccum !== dateString && date.getUTCDay() === 6)) {
  103. console.log(picocolors.magenta('[cache] vacuuming'));
  104. this.set('__LAST_VACUUM', dateString, 10 * 365 * 60 * 60 * 24 * 1000);
  105. this.db.exec('VACUUM;');
  106. }
  107. const end = performance.now();
  108. console.log(`${picocolors.gray(`[${((end - start) / 1e6).toFixed(3)}ms]`)} cache initialized from ${this.cachePath}`);
  109. }
  110. set(key: string, value: string, ttl = 60 * 1000): void {
  111. const insert = this.db.prepare(
  112. `INSERT INTO ${this.tableName} (key, value, ttl) VALUES ($key, $value, $valid) ON CONFLICT(key) DO UPDATE SET value = $value, ttl = $valid`
  113. );
  114. const valid = Date.now() + ttl;
  115. insert.run({
  116. $key: key,
  117. key,
  118. $value: value,
  119. value,
  120. $valid: valid,
  121. valid
  122. });
  123. }
  124. get(key: string, defaultValue?: S): S | undefined {
  125. const rv = this.db.prepare<string, { value: S }>(
  126. `SELECT value FROM ${this.tableName} WHERE key = ? LIMIT 1`
  127. ).get(key);
  128. if (!rv) return defaultValue;
  129. return rv.value;
  130. }
  131. has(key: string): CacheStatus {
  132. const now = Date.now();
  133. const rv = this.db.prepare<string, { ttl: number }>(`SELECT ttl FROM ${this.tableName} WHERE key = ?`).get(key);
  134. return rv ? (rv.ttl > now ? CacheStatus.Hit : CacheStatus.Stale) : CacheStatus.Miss;
  135. }
  136. private updateTtl(key: string, ttl: number): void {
  137. this.db.prepare(`UPDATE ${this.tableName} SET ttl = ? WHERE key = ?;`).run(Date.now() + ttl, key);
  138. }
  139. del(key: string): void {
  140. this.db.prepare(`DELETE FROM ${this.tableName} WHERE key = ?`).run(key);
  141. }
  142. async apply<T>(
  143. key: string,
  144. fn: () => Promise<T>,
  145. opt: CacheApplyOption<T, S>
  146. ): Promise<T> {
  147. const { ttl, temporaryBypass, incrementTtlWhenHit } = opt;
  148. if (temporaryBypass) {
  149. return fn();
  150. }
  151. if (ttl == null) {
  152. this.del(key);
  153. return fn();
  154. }
  155. const cached = this.get(key);
  156. if (cached == null) {
  157. console.log(picocolors.yellow('[cache] miss'), picocolors.gray(key), picocolors.gray(`ttl: ${TTL.humanReadable(ttl)}`));
  158. const serializer = 'serializer' in opt ? opt.serializer : identity as any;
  159. const promise = fn();
  160. return promise.then((value) => {
  161. this.set(key, serializer(value), ttl);
  162. return value;
  163. });
  164. }
  165. console.log(picocolors.green('[cache] hit'), picocolors.gray(key));
  166. if (incrementTtlWhenHit) {
  167. this.updateTtl(key, ttl);
  168. }
  169. const deserializer = 'deserializer' in opt ? opt.deserializer : identity as any;
  170. return deserializer(cached);
  171. }
  172. async applyWithHttp304<T>(
  173. url: string,
  174. extraCacheKey: string,
  175. fn: (resp: Response) => Promise<T>,
  176. opt: Omit<CacheApplyOption<T, S>, 'incrementTtlWhenHit'>,
  177. requestInit?: RequestInit
  178. ): Promise<T> {
  179. if (opt.temporaryBypass) {
  180. return fn(await fetchWithRetry(url, requestInit ?? defaultRequestInit));
  181. }
  182. const baseKey = url + '$' + extraCacheKey;
  183. const etagKey = baseKey + '$etag';
  184. const cachedKey = baseKey + '$cached';
  185. const etag = this.get(etagKey);
  186. const onMiss = async (resp: Response) => {
  187. const serializer = 'serializer' in opt ? opt.serializer : identity as any;
  188. const value = await fn(resp);
  189. if (resp.headers.has('ETag')) {
  190. let serverETag = resp.headers.get('ETag')!;
  191. // FUCK someonewhocares.org
  192. if (url.includes('someonewhocares.org')) {
  193. serverETag = serverETag.replace('-gzip', '');
  194. }
  195. console.log(picocolors.yellow('[cache] miss'), url, { status: resp.status, cachedETag: etag, serverETag });
  196. this.set(etagKey, serverETag, TTL.ONE_WEEK_STATIC);
  197. this.set(cachedKey, serializer(value), TTL.ONE_WEEK_STATIC);
  198. return value;
  199. }
  200. this.del(etagKey);
  201. console.log(picocolors.red('[cache] no etag'), picocolors.gray(url));
  202. if (opt.ttl) {
  203. this.set(cachedKey, serializer(value), opt.ttl);
  204. }
  205. return value;
  206. };
  207. const cached = this.get(cachedKey);
  208. if (cached == null) {
  209. return onMiss(await fetchWithRetry(url, requestInit ?? defaultRequestInit));
  210. }
  211. const resp = await fetchWithRetry(
  212. url,
  213. {
  214. ...(requestInit ?? defaultRequestInit),
  215. headers: (typeof etag === 'string' && etag.length > 0)
  216. ? mergeHeaders(
  217. (requestInit ?? defaultRequestInit).headers,
  218. { 'If-None-Match': etag }
  219. )
  220. : (requestInit ?? defaultRequestInit).headers
  221. }
  222. );
  223. // Only miss if previously a ETag was present and the server responded with a 304
  224. if (resp.headers.has('ETag') && resp.status !== 304) {
  225. return onMiss(resp);
  226. }
  227. console.log(picocolors.green(`[cache] ${resp.status === 304 ? 'http 304' : 'cache hit'}`), picocolors.gray(url));
  228. this.updateTtl(cachedKey, TTL.ONE_WEEK_STATIC);
  229. const deserializer = 'deserializer' in opt ? opt.deserializer : identity as any;
  230. return deserializer(cached);
  231. }
  232. async applyWithHttp304AndMirrors<T>(
  233. primaryUrl: string,
  234. mirrorUrls: string[],
  235. extraCacheKey: string,
  236. fn: (resp: string) => Promise<T> | T,
  237. opt: Omit<CacheApplyOption<T, S>, 'incrementTtlWhenHit'>
  238. ): Promise<T> {
  239. if (opt.temporaryBypass) {
  240. return fn(await fetchAssets(primaryUrl, mirrorUrls));
  241. }
  242. if (mirrorUrls.length === 0) {
  243. return this.applyWithHttp304(primaryUrl, extraCacheKey, async (resp) => fn(await resp.text()), opt);
  244. }
  245. const baseKey = primaryUrl + '$' + extraCacheKey;
  246. const getETagKey = (url: string) => baseKey + '$' + url + '$etag';
  247. const cachedKey = baseKey + '$cached';
  248. const controller = new AbortController();
  249. const previouslyCached = this.get(cachedKey);
  250. const createFetchFallbackPromise = async (url: string, index: number) => {
  251. // Most assets can be downloaded within 250ms. To avoid wasting bandwidth, we will wait for 500ms before downloading from the fallback URL.
  252. if (index > 0) {
  253. try {
  254. await sleepWithAbort(300 + (index + 1) * 10, controller.signal);
  255. } catch {
  256. console.log(picocolors.gray('[fetch cancelled early]'), picocolors.gray(url));
  257. throw new CustomAbortError();
  258. }
  259. if (controller.signal.aborted) {
  260. console.log(picocolors.gray('[fetch cancelled]'), picocolors.gray(url));
  261. throw new CustomAbortError();
  262. }
  263. }
  264. const etag = this.get(getETagKey(url));
  265. const res = await fetchWithRetry(
  266. url,
  267. {
  268. signal: controller.signal,
  269. ...defaultRequestInit,
  270. headers: (typeof etag === 'string' && etag.length > 0)
  271. ? mergeHeaders(
  272. defaultRequestInit.headers,
  273. { 'If-None-Match': etag }
  274. )
  275. : defaultRequestInit.headers
  276. }
  277. );
  278. if (res.headers.has('etag')) {
  279. this.set(getETagKey(url), res.headers.get('etag')!, TTL.ONE_WEEK_STATIC);
  280. // If we do not have a cached value, we ignore 304
  281. if (res.status === 304 && typeof previouslyCached === 'string') {
  282. controller.abort();
  283. throw new Custom304NotModifiedError(url, previouslyCached);
  284. }
  285. } else if (!this.get(getETagKey(primaryUrl)) && typeof previouslyCached === 'string') {
  286. controller.abort();
  287. throw new CustomNoETagFallbackError(previouslyCached);
  288. }
  289. // either no etag and not cached
  290. // or has etag but not 304
  291. const text = await res.text();
  292. controller.abort();
  293. return text;
  294. };
  295. try {
  296. const text = await Promise.any([
  297. createFetchFallbackPromise(primaryUrl, -1),
  298. ...mirrorUrls.map(createFetchFallbackPromise)
  299. ]);
  300. console.log(picocolors.yellow('[cache] miss'), primaryUrl);
  301. const serializer = 'serializer' in opt ? opt.serializer : identity as any;
  302. const value = await fn(text);
  303. this.set(cachedKey, serializer(value), opt.ttl ?? TTL.ONE_WEEK_STATIC);
  304. return value;
  305. } catch (e) {
  306. if (e instanceof AggregateError) {
  307. const deserializer = 'deserializer' in opt ? opt.deserializer : identity as any;
  308. for (const error of e.errors) {
  309. if (error instanceof Custom304NotModifiedError) {
  310. console.log(picocolors.green('[cache] http 304'), picocolors.gray(primaryUrl));
  311. this.updateTtl(cachedKey, TTL.ONE_WEEK_STATIC);
  312. return deserializer(error.data);
  313. }
  314. if (error instanceof CustomNoETagFallbackError) {
  315. console.log(picocolors.green('[cache] hit'), picocolors.gray(primaryUrl));
  316. return deserializer(error.data);
  317. }
  318. }
  319. }
  320. console.log(`Download Rule for [${primaryUrl}] failed`);
  321. throw e;
  322. }
  323. }
  324. destroy() {
  325. this.db.close();
  326. }
  327. }
  328. export const fsFetchCache = new Cache({ cachePath: path.resolve(__dirname, '../../.cache') });
  329. // process.on('exit', () => {
  330. // fsFetchCache.destroy();
  331. // });
  332. // export const fsCache = traceSync('initializing filesystem cache', () => new Cache<Uint8Array>({ cachePath: path.resolve(__dirname, '../../.cache'), type: 'buffer' }));
  333. const separator = '\u0000';
  334. export const serializeSet = (set: Set<string>) => fastStringArrayJoin(Array.from(set), separator);
  335. export const deserializeSet = (str: string) => new Set(str.split(separator));
  336. export const serializeArray = (arr: string[]) => fastStringArrayJoin(arr, separator);
  337. export const deserializeArray = (str: string) => str.split(separator);
  338. export const getFileContentHash = (filename: string) => stringHash(fs.readFileSync(filename, 'utf-8'));
  339. export const createCacheKey = (filename: string) => {
  340. const fileHash = getFileContentHash(filename);
  341. return (key: string) => key + '$' + fileHash + '$';
  342. };