cache-filesystem.ts 13 KB

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