cache-filesystem.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. import createDb from 'better-sqlite3';
  2. import type { Database } from 'better-sqlite3';
  3. import os from 'os';
  4. import path from 'path';
  5. import { mkdirSync } from 'fs';
  6. import picocolors from 'picocolors';
  7. import { fastStringArrayJoin } from './misc';
  8. import { performance } from 'perf_hooks';
  9. const identity = (x: any) => x;
  10. // eslint-disable-next-line sukka-ts/no-const-enum -- bun is smart, right?
  11. const enum CacheStatus {
  12. Hit = 'hit',
  13. Stale = 'stale',
  14. Miss = 'miss'
  15. }
  16. export interface CacheOptions<S = string> {
  17. /** Path to sqlite file dir */
  18. cachePath?: string,
  19. /** Time before deletion */
  20. tbd?: number,
  21. /** Cache table name */
  22. tableName?: string,
  23. type?: S extends string ? 'string' : 'buffer'
  24. }
  25. interface CacheApplyRawOption {
  26. ttl?: number | null,
  27. temporaryBypass?: boolean
  28. }
  29. interface CacheApplyNonRawOption<T, S> extends CacheApplyRawOption {
  30. serializer: (value: T) => S,
  31. deserializer: (cached: S) => T
  32. }
  33. type CacheApplyOption<T, S> = T extends S ? CacheApplyRawOption : CacheApplyNonRawOption<T, S>;
  34. const randomInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min;
  35. const ONE_HOUR = 60 * 60 * 1000;
  36. const ONE_DAY = 24 * ONE_HOUR;
  37. // Add some randomness to the cache ttl to avoid thundering herd
  38. export const TTL = {
  39. humanReadable(ttl: number) {
  40. if (ttl >= ONE_DAY) {
  41. return `${Math.round(ttl / 24 / 60 / 60 / 1000)}d`;
  42. }
  43. if (ttl >= 60 * 60 * 1000) {
  44. return `${Math.round(ttl / 60 / 60 / 1000)}h`;
  45. }
  46. return `${Math.round(ttl / 1000)}s`;
  47. },
  48. THREE_HOURS: () => randomInt(1, 3) * ONE_HOUR,
  49. TWLVE_HOURS: () => randomInt(8, 12) * ONE_HOUR,
  50. ONE_DAY: () => randomInt(23, 25) * ONE_HOUR,
  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. 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. constructor({
  66. cachePath = path.join(os.tmpdir() || '/tmp', 'hdc'),
  67. tbd,
  68. tableName = 'cache',
  69. type
  70. }: CacheOptions<S> = {}) {
  71. const start = performance.now();
  72. this.cachePath = cachePath;
  73. mkdirSync(this.cachePath, { recursive: true });
  74. if (tbd != null) this.tbd = tbd;
  75. this.tableName = tableName;
  76. if (type) {
  77. this.type = type;
  78. } else {
  79. // @ts-expect-error -- fallback type
  80. this.type = 'string';
  81. }
  82. const db = createDb(path.join(this.cachePath, 'cache.db'));
  83. db.pragma('journal_mode = WAL');
  84. db.pragma('synchronous = normal');
  85. db.pragma('temp_store = memory');
  86. db.pragma('optimize');
  87. db.prepare(`CREATE TABLE IF NOT EXISTS ${this.tableName} (key TEXT PRIMARY KEY, value ${this.type === 'string' ? 'TEXT' : 'BLOB'}, ttl REAL NOT NULL);`).run();
  88. db.prepare(`CREATE INDEX IF NOT EXISTS cache_ttl ON ${this.tableName} (ttl);`).run();
  89. const date = new Date();
  90. // perform purge on startup
  91. // ttl + tbd < now => ttl < now - tbd
  92. const now = date.getTime() - this.tbd;
  93. db.prepare(`DELETE FROM ${this.tableName} WHERE ttl < ?`).run(now);
  94. this.db = db;
  95. const dateString = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  96. const lastVaccum = this.get('__LAST_VACUUM');
  97. if (lastVaccum === undefined || (lastVaccum !== dateString && date.getUTCDay() === 6)) {
  98. console.log(picocolors.magenta('[cache] vacuuming'));
  99. this.set('__LAST_VACUUM', dateString, 10 * 365 * 60 * 60 * 24 * 1000);
  100. this.db.exec('VACUUM;');
  101. }
  102. const end = performance.now();
  103. console.log(`${picocolors.gray(`[${((end - start) / 1e6).toFixed(3)}ms]`)} cache initialized from ${this.cachePath}`);
  104. }
  105. set(key: string, value: string, ttl = 60 * 1000): void {
  106. const insert = this.db.prepare(
  107. `INSERT INTO ${this.tableName} (key, value, ttl) VALUES ($key, $value, $valid) ON CONFLICT(key) DO UPDATE SET value = $value, ttl = $valid`
  108. );
  109. const valid = Date.now() + ttl;
  110. insert.run({
  111. $key: key,
  112. key,
  113. $value: value,
  114. value,
  115. $valid: valid,
  116. valid
  117. });
  118. }
  119. get(key: string, defaultValue?: S): S | undefined {
  120. const rv = this.db.prepare<string, { value: S }>(
  121. `SELECT value FROM ${this.tableName} WHERE key = ? LIMIT 1`
  122. ).get(key);
  123. if (!rv) return defaultValue;
  124. return rv.value;
  125. }
  126. has(key: string): CacheStatus {
  127. const now = Date.now();
  128. const rv = this.db.prepare<string, { ttl: number }>(`SELECT ttl FROM ${this.tableName} WHERE key = ?`).get(key);
  129. return !rv ? CacheStatus.Miss : (rv.ttl > now ? CacheStatus.Hit : CacheStatus.Stale);
  130. }
  131. del(key: string): void {
  132. this.db.prepare(`DELETE FROM ${this.tableName} WHERE key = ?`).run(key);
  133. }
  134. async apply<T>(
  135. key: string,
  136. fn: () => Promise<T>,
  137. opt: CacheApplyOption<T, S>
  138. ): Promise<T> {
  139. const { ttl, temporaryBypass } = opt;
  140. if (temporaryBypass) {
  141. return fn();
  142. }
  143. if (ttl == null) {
  144. this.del(key);
  145. return fn();
  146. }
  147. const cached = this.get(key);
  148. if (cached == null) {
  149. console.log(picocolors.yellow('[cache] miss'), picocolors.gray(key), picocolors.gray(`ttl: ${TTL.humanReadable(ttl)}`));
  150. const serializer = 'serializer' in opt ? opt.serializer : identity;
  151. const promise = fn();
  152. return promise.then((value) => {
  153. this.set(key, serializer(value), ttl);
  154. return value;
  155. });
  156. }
  157. console.log(picocolors.green('[cache] hit'), picocolors.gray(key));
  158. const deserializer = 'deserializer' in opt ? opt.deserializer : identity;
  159. return deserializer(cached);
  160. }
  161. destroy() {
  162. this.db.close();
  163. }
  164. }
  165. export const fsFetchCache = new Cache({ cachePath: path.resolve(__dirname, '../../.cache') });
  166. // process.on('exit', () => {
  167. // fsFetchCache.destroy();
  168. // });
  169. // export const fsCache = traceSync('initializing filesystem cache', () => new Cache<Uint8Array>({ cachePath: path.resolve(__dirname, '../../.cache'), type: 'buffer' }));
  170. const separator = '\u0000';
  171. export const serializeSet = (set: Set<string>) => fastStringArrayJoin(Array.from(set), separator);
  172. export const deserializeSet = (str: string) => new Set(str.split(separator));
  173. export const serializeArray = (arr: string[]) => fastStringArrayJoin(arr, separator);
  174. export const deserializeArray = (str: string) => str.split(separator);