Surge_by_SukkaW/Dist/Build/lib/cache-filesystem.cjs
SukkaW d354c5e988
Some checks are pending
Build / Build (push) Waiting to run
Build / Diff output (push) Blocked by required conditions
Build / Deploy to Cloudflare Pages (push) Blocked by required conditions
Build / Deploy to GitHub and GitLab (push) Blocked by required conditions
Chore: maintainance
2025-02-07 17:52:36 +08:00

134 lines
5.5 KiB
JavaScript

'use strict';Object.defineProperty(exports,Symbol.toStringTag,{value:'Module'});const cacheFilesystem=require('../../_virtual/cache-filesystem.cjs'),require$$0=require('better-sqlite3'),require$$1$1=require('node:os'),require$$0$2=require('node:path'),require$$1=require('node:fs'),require$$0$1=require('picocolors'),require$$3=require('foxts/fast-string-array-join'),require$$6=require('node:perf_hooks');var hasRequiredCacheFilesystem;
function requireCacheFilesystem () {
if (hasRequiredCacheFilesystem) return cacheFilesystem.__exports;
hasRequiredCacheFilesystem = 1;
(function (exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
Cache: function() {
return Cache;
},
deserializeArray: function() {
return deserializeArray;
},
serializeArray: function() {
return serializeArray;
}
});
const _bettersqlite3 = /*#__PURE__*/ _interop_require_default(require$$0);
const _nodeos = /*#__PURE__*/ _interop_require_default(require$$1$1);
const _nodepath = /*#__PURE__*/ _interop_require_default(require$$0$2);
const _nodefs = require$$1;
const _picocolors = /*#__PURE__*/ _interop_require_default(require$$0$1);
const _faststringarrayjoin = require$$3;
const _nodeperf_hooks = require$$6;
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
class Cache {
db;
/** Time before deletion */ tbd = 60 * 1000;
/** SQLite file path */ cachePath;
/** Table name */ tableName;
type;
statement;
constructor({ cachePath = _nodepath.default.join(_nodeos.default.tmpdir() || '/tmp', 'hdc'), tbd, tableName = 'cache', type } = {}){
const start = _nodeperf_hooks.performance.now();
this.cachePath = cachePath;
(0, _nodefs.mkdirSync)(this.cachePath, {
recursive: true
});
if (tbd != null) this.tbd = tbd;
this.tableName = tableName;
if (type) {
this.type = type;
} else {
// @ts-expect-error -- fallback type
this.type = 'string';
}
const db = (0, _bettersqlite3.default)(_nodepath.default.join(this.cachePath, 'cache.db'));
db.pragma('journal_mode = WAL');
db.pragma('synchronous = normal');
db.pragma('temp_store = memory');
db.pragma('optimize');
db.prepare(`CREATE TABLE IF NOT EXISTS ${this.tableName} (key TEXT PRIMARY KEY, value ${this.type === 'string' ? 'TEXT' : 'BLOB'}, ttl REAL NOT NULL);`).run();
db.prepare(`CREATE INDEX IF NOT EXISTS cache_ttl ON ${this.tableName} (ttl);`).run();
/** cache stmt */ this.statement = {
updateTtl: db.prepare(`UPDATE ${this.tableName} SET ttl = ? WHERE key = ?;`),
del: db.prepare(`DELETE FROM ${this.tableName} WHERE key = ?`),
insert: db.prepare(`INSERT INTO ${this.tableName} (key, value, ttl) VALUES ($key, $value, $valid) ON CONFLICT(key) DO UPDATE SET value = $value, ttl = $valid`),
get: db.prepare(`SELECT ttl, value FROM ${this.tableName} WHERE key = ? LIMIT 1`)
};
const date = new Date();
// perform purge on startup
// ttl + tbd < now => ttl < now - tbd
const now = date.getTime() - this.tbd;
db.prepare(`DELETE FROM ${this.tableName} WHERE ttl < ?`).run(now);
this.db = db;
const dateString = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
const lastVaccum = this.get('__LAST_VACUUM');
if (lastVaccum === undefined || lastVaccum !== dateString && date.getUTCDay() === 6) {
console.log(_picocolors.default.magenta('[cache] vacuuming'));
this.set('__LAST_VACUUM', dateString, 10 * 365 * 60 * 60 * 24 * 1000);
this.db.exec('VACUUM;');
}
const end = _nodeperf_hooks.performance.now();
console.log(`${_picocolors.default.gray(`[${(end - start).toFixed(3)}ns]`)} cache initialized from ${this.tableName} @ ${this.cachePath}`);
}
set(key, value, ttl = 60 * 1000) {
const valid = Date.now() + ttl;
this.statement.insert.run({
$key: key,
key,
$value: value,
value,
$valid: valid,
valid
});
}
get(key) {
const rv = this.statement.get.get(key);
if (!rv) return null;
if (rv.ttl < Date.now()) {
this.del(key);
return null;
}
if (rv.value == null) {
this.del(key);
return null;
}
return rv.value;
}
updateTtl(key, ttl) {
this.statement.updateTtl.run(Date.now() + ttl, key);
}
del(key) {
this.statement.del.run(key);
}
destroy() {
this.db.close();
}
deleteTable(tableName) {
this.db.exec(`DROP TABLE IF EXISTS ${tableName};`);
}
}
// process.on('exit', () => {
// fsFetchCache.destroy();
// });
const separator = '\u0000';
const serializeArray = (arr)=>(0, _faststringarrayjoin.fastStringArrayJoin)(arr, separator);
const deserializeArray = (str)=>str.split(separator);
} (cacheFilesystem.__exports));
return cacheFilesystem.__exports;
}exports.__require=requireCacheFilesystem;