cache-filesystem.ts 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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 } from 'foxts/fast-string-array-join';
  8. import { performance } from 'node:perf_hooks';
  9. import fs from 'node:fs';
  10. import { simpleStringHash } from 'foxts/simple-string-hash';
  11. // import type { UndiciResponseData } from './fetch-retry';
  12. import { CACHE_DIR } from '../constants/dir';
  13. export interface CacheOptions<S = string> {
  14. /** Path to sqlite file dir */
  15. cachePath?: string,
  16. /** Time before deletion */
  17. tbd?: number,
  18. /** Cache table name */
  19. tableName?: string,
  20. type?: S extends string ? 'string' : 'buffer'
  21. }
  22. interface CacheApplyRawOption {
  23. ttl?: number | null,
  24. temporaryBypass?: boolean,
  25. incrementTtlWhenHit?: boolean
  26. }
  27. interface CacheApplyNonRawOption<T, S> extends CacheApplyRawOption {
  28. serializer: (value: T) => S,
  29. deserializer: (cached: S) => T
  30. }
  31. export type CacheApplyOption<T, S> = T extends S ? CacheApplyRawOption : CacheApplyNonRawOption<T, S>;
  32. const randomInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min;
  33. const ONE_HOUR = 60 * 60 * 1000;
  34. const ONE_DAY = 24 * ONE_HOUR;
  35. // Add some randomness to the cache ttl to avoid thundering herd
  36. export const TTL = {
  37. useHttp304: Symbol('useHttp304'),
  38. humanReadable(ttl: number) {
  39. if (ttl >= ONE_DAY) {
  40. return `${Math.round(ttl / 24 / 60 / 60 / 1000)}d`;
  41. }
  42. if (ttl >= 60 * 60 * 1000) {
  43. return `${Math.round(ttl / 60 / 60 / 1000)}h`;
  44. }
  45. return `${Math.round(ttl / 1000)}s`;
  46. },
  47. THREE_HOURS: () => randomInt(1, 3) * ONE_HOUR,
  48. TWLVE_HOURS: () => randomInt(8, 12) * ONE_HOUR,
  49. ONE_DAY: () => randomInt(23, 25) * ONE_HOUR,
  50. ONE_WEEK_STATIC: ONE_DAY * 7,
  51. THREE_DAYS: () => randomInt(1, 3) * ONE_DAY,
  52. ONE_WEEK: () => randomInt(4, 7) * ONE_DAY,
  53. TEN_DAYS: () => randomInt(7, 10) * ONE_DAY,
  54. TWO_WEEKS: () => randomInt(10, 14) * ONE_DAY
  55. };
  56. export class Cache<S = string> {
  57. private db: Database;
  58. /** Time before deletion */
  59. tbd = 60 * 1000;
  60. /** SQLite file path */
  61. cachePath: string;
  62. /** Table name */
  63. tableName: string;
  64. type: S extends string ? 'string' : 'buffer';
  65. private statement: {
  66. updateTtl: Statement<[number, string]>,
  67. del: Statement<[string]>,
  68. insert: Statement<[unknown]>,
  69. get: Statement<[string], { ttl: number, value: S }>
  70. };
  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. /** cache stmt */
  96. this.statement = {
  97. updateTtl: db.prepare(`UPDATE ${this.tableName} SET ttl = ? WHERE key = ?;`),
  98. del: db.prepare(`DELETE FROM ${this.tableName} WHERE key = ?`),
  99. insert: db.prepare(`INSERT INTO ${this.tableName} (key, value, ttl) VALUES ($key, $value, $valid) ON CONFLICT(key) DO UPDATE SET value = $value, ttl = $valid`),
  100. get: db.prepare(`SELECT ttl, value FROM ${this.tableName} WHERE key = ? LIMIT 1`)
  101. } as const;
  102. const date = new Date();
  103. // perform purge on startup
  104. // ttl + tbd < now => ttl < now - tbd
  105. const now = date.getTime() - this.tbd;
  106. db.prepare(`DELETE FROM ${this.tableName} WHERE ttl < ?`).run(now);
  107. this.db = db;
  108. const dateString = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  109. const lastVaccum = this.get('__LAST_VACUUM');
  110. if (lastVaccum === undefined || (lastVaccum !== dateString && date.getUTCDay() === 6)) {
  111. console.log(picocolors.magenta('[cache] vacuuming'));
  112. this.set('__LAST_VACUUM', dateString, 10 * 365 * 60 * 60 * 24 * 1000);
  113. this.db.exec('VACUUM;');
  114. }
  115. const end = performance.now();
  116. console.log(`${picocolors.gray(`[${((end - start)).toFixed(3)}ns]`)} cache initialized from ${this.tableName} @ ${this.cachePath}`);
  117. }
  118. set(key: string, value: string, ttl = 60 * 1000): void {
  119. const valid = Date.now() + ttl;
  120. this.statement.insert.run({
  121. $key: key,
  122. key,
  123. $value: value,
  124. value,
  125. $valid: valid,
  126. valid
  127. });
  128. }
  129. get(key: string): S | null {
  130. const rv = this.statement.get.get(key);
  131. if (!rv) return null;
  132. if (rv.ttl < Date.now()) {
  133. this.del(key);
  134. return null;
  135. }
  136. if (rv.value == null) {
  137. this.del(key);
  138. return null;
  139. }
  140. return rv.value;
  141. }
  142. updateTtl(key: string, ttl: number): void {
  143. this.statement.updateTtl.run(Date.now() + ttl, key);
  144. }
  145. del(key: string): void {
  146. this.statement.del.run(key);
  147. }
  148. destroy() {
  149. this.db.close();
  150. }
  151. deleteTable(tableName: string) {
  152. this.db.exec(`DROP TABLE IF EXISTS ${tableName};`);
  153. }
  154. }
  155. // drop deprecated cache
  156. new Cache({ cachePath: CACHE_DIR }).deleteTable('cache');
  157. // process.on('exit', () => {
  158. // fsFetchCache.destroy();
  159. // });
  160. const separator = '\u0000';
  161. export const serializeSet = (set: Set<string>) => fastStringArrayJoin(Array.from(set), separator);
  162. export const deserializeSet = (str: string) => new Set(str.split(separator));
  163. export const serializeArray = (arr: string[]) => fastStringArrayJoin(arr, separator);
  164. export const deserializeArray = (str: string) => str.split(separator);
  165. export const getFileContentHash = (filename: string) => simpleStringHash(fs.readFileSync(filename, 'utf-8'));
  166. export function createCacheKey(filename: string) {
  167. const fileHash = getFileContentHash(filename);
  168. return (key: string) => key + '$' + fileHash + '$';
  169. }