cache-filesystem.ts 14 KB

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