cache-filesystem.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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, requestWithLog, ResponseError } from './fetch-retry';
  12. import type { UndiciResponseData } from './fetch-retry';
  13. // import type { UndiciResponseData } from './fetch-retry';
  14. import { Custom304NotModifiedError, CustomAbortError, CustomNoETagFallbackError, fetchAssetsWithout304, sleepWithAbort } from './fetch-assets';
  15. import type { IncomingHttpHeaders } from 'undici/types/header';
  16. import { Headers } from 'undici';
  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. cacheName?: string,
  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. export 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. function ensureETag(headers: IncomingHttpHeaders | Headers) {
  62. if (headers instanceof Headers && headers.has('etag')) {
  63. return headers.get('etag');
  64. }
  65. if ('etag' in headers && typeof headers.etag === 'string' && headers.etag.length > 0) {
  66. return headers.etag;
  67. }
  68. if ('ETag' in headers && typeof headers.ETag === 'string' && headers.ETag.length > 0) {
  69. return headers.ETag;
  70. }
  71. return null;
  72. }
  73. export class Cache<S = string> {
  74. db: Database;
  75. /** Time before deletion */
  76. tbd = 60 * 1000;
  77. /** SQLite file path */
  78. cachePath: string;
  79. /** Table name */
  80. tableName: string;
  81. type: S extends string ? 'string' : 'buffer';
  82. constructor({
  83. cachePath = path.join(os.tmpdir() || '/tmp', 'hdc'),
  84. tbd,
  85. tableName = 'cache',
  86. type
  87. }: CacheOptions<S> = {}) {
  88. const start = performance.now();
  89. this.cachePath = cachePath;
  90. mkdirSync(this.cachePath, { recursive: true });
  91. if (tbd != null) this.tbd = tbd;
  92. this.tableName = tableName;
  93. if (type) {
  94. this.type = type;
  95. } else {
  96. // @ts-expect-error -- fallback type
  97. this.type = 'string';
  98. }
  99. const db = createDb(path.join(this.cachePath, 'cache.db'));
  100. db.pragma('journal_mode = WAL');
  101. db.pragma('synchronous = normal');
  102. db.pragma('temp_store = memory');
  103. db.pragma('optimize');
  104. db.prepare(`CREATE TABLE IF NOT EXISTS ${this.tableName} (key TEXT PRIMARY KEY, value ${this.type === 'string' ? 'TEXT' : 'BLOB'}, ttl REAL NOT NULL);`).run();
  105. db.prepare(`CREATE INDEX IF NOT EXISTS cache_ttl ON ${this.tableName} (ttl);`).run();
  106. const date = new Date();
  107. // perform purge on startup
  108. // ttl + tbd < now => ttl < now - tbd
  109. const now = date.getTime() - this.tbd;
  110. db.prepare(`DELETE FROM ${this.tableName} WHERE ttl < ?`).run(now);
  111. this.db = db;
  112. const dateString = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  113. const lastVaccum = this.get('__LAST_VACUUM');
  114. if (lastVaccum === undefined || (lastVaccum !== dateString && date.getUTCDay() === 6)) {
  115. console.log(picocolors.magenta('[cache] vacuuming'));
  116. this.set('__LAST_VACUUM', dateString, 10 * 365 * 60 * 60 * 24 * 1000);
  117. this.db.exec('VACUUM;');
  118. }
  119. const end = performance.now();
  120. console.log(`${picocolors.gray(`[${((end - start) / 1e6).toFixed(3)}ms]`)} cache initialized from ${this.cachePath}`);
  121. }
  122. set(key: string, value: string, ttl = 60 * 1000): void {
  123. const insert = this.db.prepare(
  124. `INSERT INTO ${this.tableName} (key, value, ttl) VALUES ($key, $value, $valid) ON CONFLICT(key) DO UPDATE SET value = $value, ttl = $valid`
  125. );
  126. const valid = Date.now() + ttl;
  127. insert.run({
  128. $key: key,
  129. key,
  130. $value: value,
  131. value,
  132. $valid: valid,
  133. valid
  134. });
  135. }
  136. get(key: string): S | null {
  137. const rv = this.db.prepare<string, { value: S, ttl: number }>(
  138. `SELECT ttl, value FROM ${this.tableName} WHERE key = ? LIMIT 1`
  139. ).get(key);
  140. if (!rv) return null;
  141. if (rv.ttl < Date.now()) {
  142. this.del(key);
  143. return null;
  144. }
  145. if (rv.value == null) {
  146. this.del(key);
  147. return null;
  148. }
  149. return rv.value;
  150. }
  151. updateTtl(key: string, ttl: number): void {
  152. this.db.prepare(`UPDATE ${this.tableName} SET ttl = ? WHERE key = ?;`).run(Date.now() + ttl, key);
  153. }
  154. del(key: string): void {
  155. this.db.prepare(`DELETE FROM ${this.tableName} WHERE key = ?`).run(key);
  156. }
  157. async apply<T>(
  158. key: string,
  159. fn: () => Promise<T>,
  160. opt: CacheApplyOption<T, S>
  161. ): Promise<T> {
  162. const { ttl, temporaryBypass, incrementTtlWhenHit, cacheName } = opt;
  163. if (temporaryBypass) {
  164. return fn();
  165. }
  166. if (ttl == null) {
  167. this.del(key);
  168. return fn();
  169. }
  170. const cached = this.get(key);
  171. if (cached == null) {
  172. console.log(picocolors.yellow('[cache] miss'), picocolors.gray(cacheName || key), picocolors.gray(`ttl: ${TTL.humanReadable(ttl)}`));
  173. const serializer = 'serializer' in opt ? opt.serializer : identity as any;
  174. const promise = fn();
  175. return promise.then((value) => {
  176. this.set(key, serializer(value), ttl);
  177. return value;
  178. });
  179. }
  180. console.log(picocolors.green('[cache] hit'), picocolors.gray(cacheName || key));
  181. if (incrementTtlWhenHit) {
  182. this.updateTtl(key, ttl);
  183. }
  184. const deserializer = 'deserializer' in opt ? opt.deserializer : identity as any;
  185. return deserializer(cached);
  186. }
  187. async applyWithHttp304<T>(
  188. url: string,
  189. extraCacheKey: string,
  190. fn: (resp: UndiciResponseData) => Promise<T>,
  191. opt: Omit<CacheApplyOption<T, S>, 'incrementTtlWhenHit'>
  192. // requestInit?: RequestInit
  193. ): Promise<T> {
  194. if (opt.temporaryBypass) {
  195. return fn(await requestWithLog(url));
  196. }
  197. const baseKey = url + '$' + extraCacheKey;
  198. const etagKey = baseKey + '$etag';
  199. const cachedKey = baseKey + '$cached';
  200. const etag = this.get(etagKey);
  201. const onMiss = async (resp: UndiciResponseData) => {
  202. const serializer = 'serializer' in opt ? opt.serializer : identity as any;
  203. const value = await fn(resp);
  204. let serverETag = ensureETag(resp.headers);
  205. if (serverETag) {
  206. // FUCK someonewhocares.org
  207. if (url.includes('someonewhocares.org')) {
  208. serverETag = serverETag.replace('-gzip', '');
  209. }
  210. console.log(picocolors.yellow('[cache] miss'), url, { status: resp.statusCode, cachedETag: etag, serverETag });
  211. this.set(etagKey, serverETag, TTL.ONE_WEEK_STATIC);
  212. this.set(cachedKey, serializer(value), TTL.ONE_WEEK_STATIC);
  213. return value;
  214. }
  215. this.del(etagKey);
  216. console.log(picocolors.red('[cache] no etag'), picocolors.gray(url));
  217. if (opt.ttl) {
  218. this.set(cachedKey, serializer(value), opt.ttl);
  219. }
  220. return value;
  221. };
  222. const cached = this.get(cachedKey);
  223. if (cached == null) {
  224. return onMiss(await requestWithLog(url));
  225. }
  226. const resp = await requestWithLog(
  227. url,
  228. {
  229. ...defaultRequestInit,
  230. headers: (typeof etag === 'string' && etag.length > 0)
  231. ? mergeHeaders<Record<string, string>>(defaultRequestInit.headers, { 'If-None-Match': etag })
  232. : defaultRequestInit.headers
  233. }
  234. );
  235. // Only miss if previously a ETag was present and the server responded with a 304
  236. if (!ensureETag(resp.headers) && resp.statusCode !== 304) {
  237. return onMiss(resp);
  238. }
  239. console.log(picocolors.green(`[cache] ${resp.statusCode === 304 ? 'http 304' : 'cache hit'}`), picocolors.gray(url));
  240. this.updateTtl(cachedKey, TTL.ONE_WEEK_STATIC);
  241. const deserializer = 'deserializer' in opt ? opt.deserializer : identity as any;
  242. return deserializer(cached);
  243. }
  244. async applyWithHttp304AndMirrors<T>(
  245. primaryUrl: string,
  246. mirrorUrls: string[],
  247. extraCacheKey: string,
  248. fn: (resp: string) => Promise<T> | T,
  249. opt: Omit<CacheApplyOption<T, S>, 'incrementTtlWhenHit'>
  250. ): Promise<T> {
  251. if (opt.temporaryBypass) {
  252. return fn(await fetchAssetsWithout304(primaryUrl, mirrorUrls));
  253. }
  254. if (mirrorUrls.length === 0) {
  255. return this.applyWithHttp304(primaryUrl, extraCacheKey, async (resp) => fn(await resp.body.text()), opt);
  256. }
  257. const baseKey = primaryUrl + '$' + extraCacheKey;
  258. const getETagKey = (url: string) => baseKey + '$' + url + '$etag';
  259. const cachedKey = baseKey + '$cached';
  260. const controller = new AbortController();
  261. const previouslyCached = this.get(cachedKey);
  262. const createFetchFallbackPromise = async (url: string, index: number) => {
  263. // Most assets can be downloaded within 250ms. To avoid wasting bandwidth, we will wait for 500ms before downloading from the fallback URL.
  264. if (index > 0) {
  265. try {
  266. await sleepWithAbort(300 + (index + 1) * 10, controller.signal);
  267. } catch {
  268. console.log(picocolors.gray('[fetch cancelled early]'), picocolors.gray(url));
  269. throw new CustomAbortError();
  270. }
  271. if (controller.signal.aborted) {
  272. console.log(picocolors.gray('[fetch cancelled]'), picocolors.gray(url));
  273. throw new CustomAbortError();
  274. }
  275. }
  276. const etag = this.get(getETagKey(url));
  277. const res = await requestWithLog(
  278. url,
  279. {
  280. signal: controller.signal,
  281. ...defaultRequestInit,
  282. headers: (typeof etag === 'string' && etag.length > 0 && typeof previouslyCached === 'string' && previouslyCached.length > 1)
  283. ? mergeHeaders<Record<string, string>>(defaultRequestInit.headers, { 'If-None-Match': etag })
  284. : defaultRequestInit.headers
  285. }
  286. );
  287. const serverETag = ensureETag(res.headers);
  288. if (serverETag) {
  289. this.set(getETagKey(url), serverETag, TTL.ONE_WEEK_STATIC);
  290. }
  291. // If we do not have a cached value, we ignore 304
  292. if (res.statusCode === 304 && typeof previouslyCached === 'string' && previouslyCached.length > 1) {
  293. const err = new Custom304NotModifiedError(url, previouslyCached);
  294. controller.abort(err);
  295. throw err;
  296. }
  297. if (!serverETag && !this.get(getETagKey(primaryUrl)) && typeof previouslyCached === 'string') {
  298. const err = new CustomNoETagFallbackError(previouslyCached);
  299. controller.abort(err);
  300. throw err;
  301. }
  302. // either no etag and not cached
  303. // or has etag but not 304
  304. const text = await res.body.text();
  305. if (text.length < 2) {
  306. throw new ResponseError(res, url, 'empty response');
  307. }
  308. controller.abort();
  309. return text;
  310. };
  311. try {
  312. const text = await Promise.any([
  313. createFetchFallbackPromise(primaryUrl, -1),
  314. ...mirrorUrls.map(createFetchFallbackPromise)
  315. ]);
  316. console.log(picocolors.yellow('[cache] miss'), primaryUrl);
  317. const serializer = 'serializer' in opt ? opt.serializer : identity as any;
  318. const value = await fn(text);
  319. this.set(cachedKey, serializer(value), opt.ttl ?? TTL.ONE_WEEK_STATIC);
  320. return value;
  321. } catch (e) {
  322. if (e && typeof e === 'object' && 'errors' in e && Array.isArray(e.errors)) {
  323. const deserializer = 'deserializer' in opt ? opt.deserializer : identity as any;
  324. for (let i = 0, len = e.errors.length; i < len; i++) {
  325. const error = e.errors[i];
  326. if ('name' in error && (error.name === 'CustomAbortError' || error.name === 'AbortError')) {
  327. continue;
  328. }
  329. if ('digest' in error) {
  330. if (error.digest === 'Custom304NotModifiedError') {
  331. console.log(picocolors.green('[cache] http 304'), picocolors.gray(primaryUrl));
  332. this.updateTtl(cachedKey, TTL.ONE_WEEK_STATIC);
  333. return deserializer(error.data);
  334. }
  335. if (error.digest === 'CustomNoETagFallbackError') {
  336. console.log(picocolors.green('[cache] hit'), picocolors.gray(primaryUrl));
  337. return deserializer(error.data);
  338. }
  339. }
  340. console.log(picocolors.red('[fetch error]'), picocolors.gray(error.url), error);
  341. }
  342. }
  343. console.log({ e });
  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. }