cache-filesystem.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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, UndiciResponseError } from './fetch-retry';
  12. import type { UndiciResponseData } from './fetch-retry';
  13. import { Custom304NotModifiedError, CustomAbortError, CustomNoETagFallbackError, fetchAssetsWith304, sleepWithAbort } from './fetch-assets';
  14. import type { HeadersInit } from 'undici';
  15. import type { IncomingHttpHeaders } from 'undici/types/header';
  16. const enum CacheStatus {
  17. Hit = 'hit',
  18. Stale = 'stale',
  19. Miss = 'miss'
  20. }
  21. export interface CacheOptions<S = string> {
  22. /** Path to sqlite file dir */
  23. cachePath?: string,
  24. /** Time before deletion */
  25. tbd?: number,
  26. /** Cache table name */
  27. tableName?: string,
  28. type?: S extends string ? 'string' : 'buffer'
  29. }
  30. interface CacheApplyRawOption {
  31. ttl?: number | null,
  32. temporaryBypass?: boolean,
  33. incrementTtlWhenHit?: boolean
  34. }
  35. interface CacheApplyNonRawOption<T, S> extends CacheApplyRawOption {
  36. serializer: (value: T) => S,
  37. deserializer: (cached: S) => T
  38. }
  39. type CacheApplyOption<T, S> = T extends S ? CacheApplyRawOption : CacheApplyNonRawOption<T, S>;
  40. const randomInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min;
  41. const ONE_HOUR = 60 * 60 * 1000;
  42. const ONE_DAY = 24 * ONE_HOUR;
  43. // Add some randomness to the cache ttl to avoid thundering herd
  44. export const TTL = {
  45. useHttp304: Symbol('useHttp304'),
  46. humanReadable(ttl: number) {
  47. if (ttl >= ONE_DAY) {
  48. return `${Math.round(ttl / 24 / 60 / 60 / 1000)}d`;
  49. }
  50. if (ttl >= 60 * 60 * 1000) {
  51. return `${Math.round(ttl / 60 / 60 / 1000)}h`;
  52. }
  53. return `${Math.round(ttl / 1000)}s`;
  54. },
  55. THREE_HOURS: () => randomInt(1, 3) * ONE_HOUR,
  56. TWLVE_HOURS: () => randomInt(8, 12) * ONE_HOUR,
  57. ONE_DAY: () => randomInt(23, 25) * ONE_HOUR,
  58. ONE_WEEK_STATIC: ONE_DAY * 7,
  59. THREE_DAYS: () => randomInt(1, 3) * ONE_DAY,
  60. ONE_WEEK: () => randomInt(4, 7) * ONE_DAY,
  61. TEN_DAYS: () => randomInt(7, 10) * ONE_DAY,
  62. TWO_WEEKS: () => randomInt(10, 14) * ONE_DAY
  63. };
  64. function ensureETag(headers: IncomingHttpHeaders) {
  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 '';
  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, defaultValue?: S): S | undefined {
  137. const rv = this.db.prepare<string, { value: S }>(
  138. `SELECT value FROM ${this.tableName} WHERE key = ? LIMIT 1`
  139. ).get(key);
  140. if (!rv) return defaultValue;
  141. return rv.value;
  142. }
  143. has(key: string): CacheStatus {
  144. const now = Date.now();
  145. const rv = this.db.prepare<string, { ttl: number }>(`SELECT ttl FROM ${this.tableName} WHERE key = ?`).get(key);
  146. return rv ? (rv.ttl > now ? CacheStatus.Hit : CacheStatus.Stale) : CacheStatus.Miss;
  147. }
  148. private updateTtl(key: string, ttl: number): void {
  149. this.db.prepare(`UPDATE ${this.tableName} SET ttl = ? WHERE key = ?;`).run(Date.now() + ttl, key);
  150. }
  151. del(key: string): void {
  152. this.db.prepare(`DELETE FROM ${this.tableName} WHERE key = ?`).run(key);
  153. }
  154. async apply<T>(
  155. key: string,
  156. fn: () => Promise<T>,
  157. opt: CacheApplyOption<T, S>
  158. ): Promise<T> {
  159. const { ttl, temporaryBypass, incrementTtlWhenHit } = opt;
  160. if (temporaryBypass) {
  161. return fn();
  162. }
  163. if (ttl == null) {
  164. this.del(key);
  165. return fn();
  166. }
  167. const cached = this.get(key);
  168. if (cached == null) {
  169. console.log(picocolors.yellow('[cache] miss'), picocolors.gray(key), picocolors.gray(`ttl: ${TTL.humanReadable(ttl)}`));
  170. const serializer = 'serializer' in opt ? opt.serializer : identity as any;
  171. const promise = fn();
  172. return promise.then((value) => {
  173. this.set(key, serializer(value), ttl);
  174. return value;
  175. });
  176. }
  177. console.log(picocolors.green('[cache] hit'), picocolors.gray(key));
  178. if (incrementTtlWhenHit) {
  179. this.updateTtl(key, ttl);
  180. }
  181. const deserializer = 'deserializer' in opt ? opt.deserializer : identity as any;
  182. return deserializer(cached);
  183. }
  184. async applyWithHttp304<T>(
  185. url: string,
  186. extraCacheKey: string,
  187. fn: (resp: UndiciResponseData) => Promise<T>,
  188. opt: Omit<CacheApplyOption<T, S>, 'incrementTtlWhenHit'>
  189. // requestInit?: RequestInit
  190. ): Promise<T> {
  191. if (opt.temporaryBypass) {
  192. return fn(await requestWithLog(url));
  193. }
  194. const baseKey = url + '$' + extraCacheKey;
  195. const etagKey = baseKey + '$etag';
  196. const cachedKey = baseKey + '$cached';
  197. const etag = this.get(etagKey);
  198. const onMiss = async (resp: UndiciResponseData) => {
  199. const serializer = 'serializer' in opt ? opt.serializer : identity as any;
  200. const value = await fn(resp);
  201. let serverETag = ensureETag(resp.headers);
  202. if (serverETag) {
  203. // FUCK someonewhocares.org
  204. if (url.includes('someonewhocares.org')) {
  205. serverETag = serverETag.replace('-gzip', '');
  206. }
  207. console.log(picocolors.yellow('[cache] miss'), url, { status: resp.statusCode, cachedETag: etag, serverETag });
  208. this.set(etagKey, serverETag, TTL.ONE_WEEK_STATIC);
  209. this.set(cachedKey, serializer(value), TTL.ONE_WEEK_STATIC);
  210. return value;
  211. }
  212. this.del(etagKey);
  213. console.log(picocolors.red('[cache] no etag'), picocolors.gray(url));
  214. if (opt.ttl) {
  215. this.set(cachedKey, serializer(value), opt.ttl);
  216. }
  217. return value;
  218. };
  219. const cached = this.get(cachedKey);
  220. if (cached == null) {
  221. return onMiss(await requestWithLog(url));
  222. }
  223. const resp = await requestWithLog(
  224. url,
  225. {
  226. headers: (typeof etag === 'string' && etag.length > 0)
  227. ? { 'If-None-Match': etag }
  228. : {}
  229. }
  230. );
  231. // Only miss if previously a ETag was present and the server responded with a 304
  232. if (!ensureETag(resp.headers) && resp.statusCode !== 304) {
  233. return onMiss(resp);
  234. }
  235. console.log(picocolors.green(`[cache] ${resp.statusCode === 304 ? 'http 304' : 'cache hit'}`), picocolors.gray(url));
  236. this.updateTtl(cachedKey, TTL.ONE_WEEK_STATIC);
  237. const deserializer = 'deserializer' in opt ? opt.deserializer : identity as any;
  238. return deserializer(cached);
  239. }
  240. async applyWithHttp304AndMirrors<T>(
  241. primaryUrl: string,
  242. mirrorUrls: string[],
  243. extraCacheKey: string,
  244. fn: (resp: string) => Promise<T> | T,
  245. opt: Omit<CacheApplyOption<T, S>, 'incrementTtlWhenHit'>
  246. ): Promise<T> {
  247. if (opt.temporaryBypass) {
  248. return fn(await fetchAssetsWith304(primaryUrl, mirrorUrls));
  249. }
  250. if (mirrorUrls.length === 0) {
  251. return this.applyWithHttp304(primaryUrl, extraCacheKey, async (resp) => fn(await resp.body.text()), opt);
  252. }
  253. const baseKey = primaryUrl + '$' + extraCacheKey;
  254. const getETagKey = (url: string) => baseKey + '$' + url + '$etag';
  255. const cachedKey = baseKey + '$cached';
  256. const controller = new AbortController();
  257. const previouslyCached = this.get(cachedKey);
  258. const createFetchFallbackPromise = async (url: string, index: number) => {
  259. // Most assets can be downloaded within 250ms. To avoid wasting bandwidth, we will wait for 500ms before downloading from the fallback URL.
  260. if (index > 0) {
  261. try {
  262. await sleepWithAbort(300 + (index + 1) * 10, controller.signal);
  263. } catch {
  264. console.log(picocolors.gray('[fetch cancelled early]'), picocolors.gray(url));
  265. throw new CustomAbortError();
  266. }
  267. if (controller.signal.aborted) {
  268. console.log(picocolors.gray('[fetch cancelled]'), picocolors.gray(url));
  269. throw new CustomAbortError();
  270. }
  271. }
  272. const etag = this.get(getETagKey(url));
  273. const res = await requestWithLog(
  274. url,
  275. {
  276. signal: controller.signal,
  277. ...defaultRequestInit,
  278. headers: (typeof etag === 'string' && etag.length > 0)
  279. ? mergeHeaders<HeadersInit>(
  280. { 'If-None-Match': etag },
  281. defaultRequestInit.headers
  282. )
  283. : defaultRequestInit.headers
  284. }
  285. );
  286. const serverETag = ensureETag(res.headers);
  287. if (serverETag) {
  288. this.set(getETagKey(url), serverETag, TTL.ONE_WEEK_STATIC);
  289. }
  290. // If we do not have a cached value, we ignore 304
  291. if (res.statusCode === 304 && typeof previouslyCached === 'string') {
  292. controller.abort();
  293. throw new Custom304NotModifiedError(url, previouslyCached);
  294. }
  295. if (!serverETag && !this.get(getETagKey(primaryUrl)) && typeof previouslyCached === 'string') {
  296. controller.abort();
  297. throw new CustomNoETagFallbackError(previouslyCached);
  298. }
  299. // either no etag and not cached
  300. // or has etag but not 304
  301. const text = await res.body.text();
  302. if (text.length < 2) {
  303. throw new UndiciResponseError(res, url);
  304. }
  305. controller.abort();
  306. return text;
  307. };
  308. try {
  309. const text = await Promise.any([
  310. createFetchFallbackPromise(primaryUrl, -1),
  311. ...mirrorUrls.map(createFetchFallbackPromise)
  312. ]);
  313. console.log(picocolors.yellow('[cache] miss'), primaryUrl);
  314. const serializer = 'serializer' in opt ? opt.serializer : identity as any;
  315. const value = await fn(text);
  316. this.set(cachedKey, serializer(value), opt.ttl ?? TTL.ONE_WEEK_STATIC);
  317. return value;
  318. } catch (e) {
  319. if (e instanceof AggregateError) {
  320. const deserializer = 'deserializer' in opt ? opt.deserializer : identity as any;
  321. for (const error of e.errors) {
  322. if (error instanceof Custom304NotModifiedError) {
  323. console.log(picocolors.green('[cache] http 304'), picocolors.gray(primaryUrl));
  324. this.updateTtl(cachedKey, TTL.ONE_WEEK_STATIC);
  325. return deserializer(error.data);
  326. }
  327. if (error instanceof CustomNoETagFallbackError) {
  328. console.log(picocolors.green('[cache] hit'), picocolors.gray(primaryUrl));
  329. return deserializer(error.data);
  330. }
  331. }
  332. }
  333. console.log(`Download Rule for [${primaryUrl}] failed`);
  334. throw e;
  335. }
  336. }
  337. destroy() {
  338. this.db.close();
  339. }
  340. }
  341. export const fsFetchCache = new Cache({ cachePath: path.resolve(__dirname, '../../.cache') });
  342. // process.on('exit', () => {
  343. // fsFetchCache.destroy();
  344. // });
  345. // export const fsCache = traceSync('initializing filesystem cache', () => new Cache<Uint8Array>({ cachePath: path.resolve(__dirname, '../../.cache'), type: 'buffer' }));
  346. const separator = '\u0000';
  347. export const serializeSet = (set: Set<string>) => fastStringArrayJoin(Array.from(set), separator);
  348. export const deserializeSet = (str: string) => new Set(str.split(separator));
  349. export const serializeArray = (arr: string[]) => fastStringArrayJoin(arr, separator);
  350. export const deserializeArray = (str: string) => str.split(separator);
  351. export const getFileContentHash = (filename: string) => stringHash(fs.readFileSync(filename, 'utf-8'));
  352. export function createCacheKey(filename: string) {
  353. const fileHash = getFileContentHash(filename);
  354. return (key: string) => key + '$' + fileHash + '$';
  355. }