cache-filesystem.ts 15 KB

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