cache-filesystem.ts 15 KB

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