feat: 扩展 scriptResourceCache 缓存, 详见 demo.js

This commit is contained in:
xream 2025-02-28 15:54:04 +08:00
parent b1618c3803
commit dd4e0cef68
No known key found for this signature in database
GPG Key ID: 1D2C5225471789F9
3 changed files with 41 additions and 8 deletions

View File

@ -1,6 +1,6 @@
{
"name": "sub-store",
"version": "2.16.60",
"version": "2.16.61",
"description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.",
"main": "src/main.js",
"scripts": {

View File

@ -24,7 +24,7 @@ class ResourceCache {
this._cleanup();
}
_cleanup() {
_cleanup(prefix, expires) {
// clear obsolete cached resource
let clear = false;
Object.entries(this.resourceCache).forEach((entry) => {
@ -35,7 +35,11 @@ class ResourceCache {
$.delete(`#${id}`);
clear = true;
}
if (new Date().getTime() - updated.time > this.expires) {
if (
new Date().getTime() - updated.time >
(expires ?? this.expires) ||
(prefix && id.startsWith(prefix))
) {
delete this.resourceCache[id];
clear = true;
}
@ -52,10 +56,15 @@ class ResourceCache {
$.write(JSON.stringify(this.resourceCache), SCRIPT_RESOURCE_CACHE_KEY);
}
get(id) {
get(id, expires, remove) {
const updated = this.resourceCache[id] && this.resourceCache[id].time;
if (updated && new Date().getTime() - updated <= this.expires) {
return this.resourceCache[id].data;
if (updated) {
if (new Date().getTime() - updated <= (expires ?? this.expires))
return this.resourceCache[id].data;
if (remove) {
delete this.resourceCache[id];
this._persist();
}
}
return null;
}

View File

@ -52,8 +52,32 @@ function operator(proxies = [], targetPlatform, context) {
// scriptResourceCache 缓存
// 可参考 https://t.me/zhetengsha/1003
// const cache = scriptResourceCache
// cache.set(id, data)
// cache.get(id)
// 设置
// cache.set('a:1', 1)
// cache.set('a:2', 2)
// 获取
// cache.get('a:1')
// 支持第二个参数: 自定义过期时间
// 支持第三个参数: 是否删除过期项
// cache.get('a:2', 1000, true)
// 清理
// cache._cleanup()
// 支持第一个参数: 匹配前缀的项也一起删除
// 支持第二个参数: 自定义过期时间
// cache._cleanup('a:', 1000)
// 关于缓存时长
// 拉取 Sub-Store 订阅时, 会自动拉取远程订阅
// 远程订阅缓存是 1 小时, 缓存的唯一 key 为 url+ user agent. 可通过前端的刷新按钮刷新缓存. 或使用参数 noCache 来禁用缓存. 例: 内部配置订阅链接时使用 http://a.com#noCache, 外部使用 sub-store 链接时使用 https://sub.store/download/1?noCache=true
// 当使用相关脚本时, 若在对应的脚本中使用参数开启缓存, 可设置持久化缓存 sub-store-csr-expiration-time 的值来自定义默认缓存时长, 默认为 172800000 (48 * 3600 * 1000, 即 48 小时)
// 🎈Loon 可在插件中设置
// 其他平台同理, 持久化缓存数据在 JSON 里
// ProxyUtils 为节点处理工具
// 可参考 https://t.me/zhetengsha/1066