cache-filesystem.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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 { 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. private 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. private statement: {
  82. updateTtl: Statement<[number, string]>,
  83. del: Statement<[string]>,
  84. insert: Statement<[unknown]>,
  85. get: Statement<[string], { ttl: number, value: S }>
  86. };
  87. constructor({
  88. cachePath = path.join(os.tmpdir() || '/tmp', 'hdc'),
  89. tbd,
  90. tableName = 'cache',
  91. type
  92. }: CacheOptions<S> = {}) {
  93. const start = performance.now();
  94. this.cachePath = cachePath;
  95. mkdirSync(this.cachePath, { recursive: true });
  96. if (tbd != null) this.tbd = tbd;
  97. this.tableName = tableName;
  98. if (type) {
  99. this.type = type;
  100. } else {
  101. // @ts-expect-error -- fallback type
  102. this.type = 'string';
  103. }
  104. const db = createDb(path.join(this.cachePath, 'cache.db'));
  105. db.pragma('journal_mode = WAL');
  106. db.pragma('synchronous = normal');
  107. db.pragma('temp_store = memory');
  108. db.pragma('optimize');
  109. db.prepare(`CREATE TABLE IF NOT EXISTS ${this.tableName} (key TEXT PRIMARY KEY, value ${this.type === 'string' ? 'TEXT' : 'BLOB'}, ttl REAL NOT NULL);`).run();
  110. db.prepare(`CREATE INDEX IF NOT EXISTS cache_ttl ON ${this.tableName} (ttl);`).run();
  111. /** cache stmt */
  112. this.statement = {
  113. updateTtl: db.prepare(`UPDATE ${this.tableName} SET ttl = ? WHERE key = ?;`),
  114. del: db.prepare(`DELETE FROM ${this.tableName} WHERE key = ?`),
  115. insert: db.prepare(`INSERT INTO ${this.tableName} (key, value, ttl) VALUES ($key, $value, $valid) ON CONFLICT(key) DO UPDATE SET value = $value, ttl = $valid`),
  116. get: db.prepare(`SELECT ttl, value FROM ${this.tableName} WHERE key = ? LIMIT 1`)
  117. } as const;
  118. const date = new Date();
  119. // perform purge on startup
  120. // ttl + tbd < now => ttl < now - tbd
  121. const now = date.getTime() - this.tbd;
  122. db.prepare(`DELETE FROM ${this.tableName} WHERE ttl < ?`).run(now);
  123. this.db = db;
  124. const dateString = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  125. const lastVaccum = this.get('__LAST_VACUUM');
  126. if (lastVaccum === undefined || (lastVaccum !== dateString && date.getUTCDay() === 6)) {
  127. console.log(picocolors.magenta('[cache] vacuuming'));
  128. this.set('__LAST_VACUUM', dateString, 10 * 365 * 60 * 60 * 24 * 1000);
  129. this.db.exec('VACUUM;');
  130. }
  131. const end = performance.now();
  132. console.log(`${picocolors.gray(`[${((end - start) / 1e6).toFixed(3)}ms]`)} cache initialized from ${this.cachePath}`);
  133. }
  134. set(key: string, value: string, ttl = 60 * 1000): void {
  135. const valid = Date.now() + ttl;
  136. this.statement.insert.run({
  137. $key: key,
  138. key,
  139. $value: value,
  140. value,
  141. $valid: valid,
  142. valid
  143. });
  144. }
  145. get(key: string): S | null {
  146. const rv = this.statement.get.get(key);
  147. if (!rv) return null;
  148. if (rv.ttl < Date.now()) {
  149. this.del(key);
  150. return null;
  151. }
  152. if (rv.value == null) {
  153. this.del(key);
  154. return null;
  155. }
  156. return rv.value;
  157. }
  158. updateTtl(key: string, ttl: number): void {
  159. this.statement.updateTtl.run(Date.now() + ttl, key);
  160. }
  161. del(key: string): void {
  162. this.statement.del.run(key);
  163. }
  164. async applyWithHttp304<T>(
  165. url: string,
  166. extraCacheKey: string,
  167. fn: (resp: UndiciResponseData) => Promise<T>,
  168. opt: Omit<CacheApplyOption<T, S>, 'incrementTtlWhenHit'>
  169. // requestInit?: RequestInit
  170. ): Promise<T> {
  171. if (opt.temporaryBypass) {
  172. return fn(await requestWithLog(url));
  173. }
  174. const baseKey = url + '$' + extraCacheKey;
  175. const etagKey = baseKey + '$etag';
  176. const cachedKey = baseKey + '$cached';
  177. const etag = this.get(etagKey);
  178. const onMiss = async (resp: UndiciResponseData) => {
  179. const serializer = 'serializer' in opt ? opt.serializer : identity as any;
  180. const value = await fn(resp);
  181. let serverETag = ensureETag(resp.headers);
  182. if (serverETag) {
  183. // FUCK someonewhocares.org
  184. if (url.includes('someonewhocares.org')) {
  185. serverETag = serverETag.replace('-gzip', '');
  186. }
  187. console.log(picocolors.yellow('[cache] miss'), url, { status: resp.statusCode, cachedETag: etag, serverETag });
  188. this.set(etagKey, serverETag, TTL.ONE_WEEK_STATIC);
  189. this.set(cachedKey, serializer(value), TTL.ONE_WEEK_STATIC);
  190. return value;
  191. }
  192. this.del(etagKey);
  193. console.log(picocolors.red('[cache] no etag'), picocolors.gray(url));
  194. if (opt.ttl) {
  195. this.set(cachedKey, serializer(value), opt.ttl);
  196. }
  197. return value;
  198. };
  199. const cached = this.get(cachedKey);
  200. if (cached == null) {
  201. return onMiss(await requestWithLog(url));
  202. }
  203. const resp = await requestWithLog(
  204. url,
  205. {
  206. ...defaultRequestInit,
  207. headers: (typeof etag === 'string' && etag.length > 0)
  208. ? mergeHeaders<Record<string, string>>(defaultRequestInit.headers, { 'If-None-Match': etag })
  209. : defaultRequestInit.headers
  210. }
  211. );
  212. // Only miss if previously a ETag was present and the server responded with a 304
  213. if (!ensureETag(resp.headers) && resp.statusCode !== 304) {
  214. return onMiss(resp);
  215. }
  216. console.log(picocolors.green(`[cache] ${resp.statusCode === 304 ? 'http 304' : 'cache hit'}`), picocolors.gray(url));
  217. this.updateTtl(cachedKey, TTL.ONE_WEEK_STATIC);
  218. const deserializer = 'deserializer' in opt ? opt.deserializer : identity as any;
  219. return deserializer(cached);
  220. }
  221. async applyWithHttp304AndMirrors<T>(
  222. primaryUrl: string,
  223. mirrorUrls: string[],
  224. extraCacheKey: string,
  225. fn: (resp: string) => Promise<T> | T,
  226. opt: Omit<CacheApplyOption<T, S>, 'incrementTtlWhenHit'>
  227. ): Promise<T> {
  228. if (opt.temporaryBypass) {
  229. return fn(await fetchAssetsWithout304(primaryUrl, mirrorUrls));
  230. }
  231. if (mirrorUrls.length === 0) {
  232. return this.applyWithHttp304(primaryUrl, extraCacheKey, async (resp) => fn(await resp.body.text()), opt);
  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(300 + (index + 1) * 10, 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. ? mergeHeaders<Record<string, string>>(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 = await Promise.any([
  290. createFetchFallbackPromise(primaryUrl, -1),
  291. ...mirrorUrls.map(createFetchFallbackPromise)
  292. ]);
  293. console.log(picocolors.yellow('[cache] miss'), primaryUrl);
  294. const serializer = 'serializer' in opt ? opt.serializer : identity as any;
  295. const value = await fn(text);
  296. this.set(cachedKey, serializer(value), opt.ttl ?? TTL.ONE_WEEK_STATIC);
  297. return value;
  298. } catch (e) {
  299. if (e && typeof e === 'object' && 'errors' in e && Array.isArray(e.errors)) {
  300. const deserializer = 'deserializer' in opt ? opt.deserializer : identity as any;
  301. for (let i = 0, len = e.errors.length; i < len; i++) {
  302. const error = e.errors[i];
  303. if ('name' in error && (error.name === 'CustomAbortError' || error.name === 'AbortError')) {
  304. continue;
  305. }
  306. if ('digest' in error) {
  307. if (error.digest === 'Custom304NotModifiedError') {
  308. console.log(picocolors.green('[cache] http 304'), picocolors.gray(primaryUrl));
  309. this.updateTtl(cachedKey, TTL.ONE_WEEK_STATIC);
  310. return deserializer(error.data);
  311. }
  312. if (error.digest === 'CustomNoETagFallbackError') {
  313. console.log(picocolors.green('[cache] hit'), picocolors.gray(primaryUrl));
  314. return deserializer(error.data);
  315. }
  316. }
  317. console.log(picocolors.red('[fetch error]'), picocolors.gray(error.url), error);
  318. }
  319. }
  320. console.log({ e });
  321. console.log(`Download Rule for [${primaryUrl}] failed`);
  322. throw e;
  323. }
  324. }
  325. destroy() {
  326. this.db.close();
  327. }
  328. }
  329. export const fsFetchCache = new Cache({ cachePath: path.resolve(__dirname, '../../.cache') });
  330. // process.on('exit', () => {
  331. // fsFetchCache.destroy();
  332. // });
  333. // export const fsCache = traceSync('initializing filesystem cache', () => new Cache<Uint8Array>({ cachePath: path.resolve(__dirname, '../../.cache'), type: 'buffer' }));
  334. const separator = '\u0000';
  335. export const serializeSet = (set: Set<string>) => fastStringArrayJoin(Array.from(set), separator);
  336. export const deserializeSet = (str: string) => new Set(str.split(separator));
  337. export const serializeArray = (arr: string[]) => fastStringArrayJoin(arr, separator);
  338. export const deserializeArray = (str: string) => str.split(separator);
  339. export const getFileContentHash = (filename: string) => stringHash(fs.readFileSync(filename, 'utf-8'));
  340. export function createCacheKey(filename: string) {
  341. const fileHash = getFileContentHash(filename);
  342. return (key: string) => key + '$' + fileHash + '$';
  343. }