cache-filesystem.ts 13 KB

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