cache-filesystem.ts 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. // eslint-disable-next-line import/no-unresolved -- bun built-in module
  2. import { Database } from 'bun:sqlite';
  3. import os from 'os';
  4. import path from 'path';
  5. import fs from 'fs';
  6. import picocolors from 'picocolors';
  7. const identity = (x: any) => x;
  8. // eslint-disable-next-line sukka-ts/no-const-enum -- bun is smart, right?
  9. const enum CacheStatus {
  10. Hit = 'hit',
  11. Stale = 'stale',
  12. Miss = 'miss'
  13. }
  14. export interface CacheOptions {
  15. cachePath?: string,
  16. tbd?: number
  17. }
  18. interface CacheApplyNonStringOption<T> {
  19. ttl?: number | null,
  20. serializer: (value: T) => string,
  21. deserializer: (cached: string) => T,
  22. temporaryBypass?: boolean
  23. }
  24. interface CacheApplyStringOption {
  25. ttl?: number | null,
  26. temporaryBypass?: boolean
  27. }
  28. type CacheApplyOption<T> = T extends string ? CacheApplyStringOption : CacheApplyNonStringOption<T>;
  29. const randomInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min;
  30. // Add some randomness to the cache ttl to avoid thundering herd
  31. export const TTL = {
  32. humanReadable(ttl: number) {
  33. if (ttl >= 24 * 60 * 60 * 1000) {
  34. return `${Math.round(ttl / 24 / 60 / 60 / 1000)}d`;
  35. }
  36. if (ttl >= 60 * 60 * 1000) {
  37. return `${Math.round(ttl / 60 / 60 / 1000)}h`;
  38. }
  39. return `${Math.round(ttl / 1000)}s`;
  40. },
  41. THREE_HOURS: () => randomInt(1, 3) * 60 * 60 * 1000,
  42. TWLVE_HOURS: () => randomInt(8, 12) * 60 * 60 * 1000,
  43. ONE_DAY: () => randomInt(23, 25) * 60 * 60 * 1000,
  44. THREE_DAYS: () => randomInt(1, 3) * 24 * 60 * 60 * 1000,
  45. ONE_WEEK: () => randomInt(5, 7) * 24 * 60 * 60 * 1000,
  46. TWO_WEEKS: () => randomInt(10, 14) * 24 * 60 * 60 * 1000,
  47. TEN_DAYS: () => randomInt(7, 10) * 24 * 60 * 60 * 1000
  48. };
  49. export class Cache {
  50. db: Database;
  51. tbd = 60 * 1000; // time before deletion
  52. cachePath: string;
  53. constructor({ cachePath = path.join(os.tmpdir() || '/tmp', 'hdc'), tbd }: CacheOptions = {}) {
  54. this.cachePath = cachePath;
  55. fs.mkdirSync(this.cachePath, { recursive: true });
  56. if (tbd != null) this.tbd = tbd;
  57. const db = new Database(path.join(this.cachePath, 'cache.db'));
  58. db.exec('PRAGMA journal_mode = WAL');
  59. db.prepare('CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY, value TEXT, ttl REAL NOT NULL);').run();
  60. db.prepare('CREATE INDEX IF NOT EXISTS cache_ttl ON cache (ttl);').run();
  61. // perform purge on startup
  62. // ttl + tbd < now => ttl < now - tbd
  63. const now = Date.now() - this.tbd;
  64. db.prepare('DELETE FROM cache WHERE ttl < ?').run(now);
  65. this.db = db;
  66. }
  67. set(key: string, value: string, ttl = 60 * 1000): void {
  68. const insert = this.db.prepare(
  69. 'INSERT INTO cache (key, value, ttl) VALUES ($key, $value, $valid) ON CONFLICT(key) DO UPDATE SET value = $value, ttl = $valid'
  70. );
  71. insert.run({
  72. $key: key,
  73. $value: value,
  74. $valid: Date.now() + ttl
  75. });
  76. }
  77. get(key: string, defaultValue?: string): string | undefined {
  78. const rv = this.db.prepare<{ value: string }, string>(
  79. 'SELECT value FROM cache WHERE key = ?'
  80. ).get(key);
  81. if (!rv) return defaultValue;
  82. return rv.value;
  83. }
  84. has(key: string): CacheStatus {
  85. const now = Date.now();
  86. const rv = this.db.prepare<{ ttl: number }, string>('SELECT ttl FROM cache WHERE key = ?').get(key);
  87. return !rv ? CacheStatus.Miss : (rv.ttl > now ? CacheStatus.Hit : CacheStatus.Stale);
  88. }
  89. del(key: string): void {
  90. this.db.prepare('DELETE FROM cache WHERE key = ?').run(key);
  91. }
  92. async apply<T>(
  93. key: string,
  94. fn: () => Promise<T>,
  95. opt: CacheApplyOption<T>
  96. ): Promise<T> {
  97. const { ttl, temporaryBypass } = opt;
  98. if (temporaryBypass) {
  99. return fn();
  100. }
  101. if (ttl == null) {
  102. this.del(key);
  103. return fn();
  104. }
  105. const cached = this.get(key);
  106. let value: T;
  107. if (cached == null) {
  108. console.log(picocolors.yellow('[cache] miss'), picocolors.gray(key), picocolors.gray(`ttl: ${TTL.humanReadable(ttl)}`));
  109. value = await fn();
  110. const serializer = 'serializer' in opt ? opt.serializer : identity;
  111. this.set(key, serializer(value), ttl);
  112. } else {
  113. console.log(picocolors.green('[cache] hit'), picocolors.gray(key));
  114. const deserializer = 'deserializer' in opt ? opt.deserializer : identity;
  115. value = deserializer(cached);
  116. }
  117. return value;
  118. }
  119. destroy() {
  120. this.db.close();
  121. }
  122. }
  123. export const fsCache = new Cache({ cachePath: path.resolve(import.meta.dir, '../../.cache') });
  124. // process.on('exit', () => {
  125. // fsCache.destroy();
  126. // });
  127. const separator = '\u0000';
  128. // const textEncoder = new TextEncoder();
  129. // const textDecoder = new TextDecoder();
  130. // export const serializeString = (str: string) => textEncoder.encode(str);
  131. // export const deserializeString = (str: string) => textDecoder.decode(new Uint8Array(str.split(separator).map(Number)));
  132. export const serializeSet = (set: Set<string>) => Array.from(set).join(separator);
  133. export const deserializeSet = (str: string) => new Set(str.split(separator));
  134. export const serializeArray = (arr: string[]) => arr.join(separator);
  135. export const deserializeArray = (str: string) => str.split(separator);