feat(plugin): 插件数据层 M2 —— ctx.data(原子写 + 串行队列 + 旧数据迁移)v3.25.42

- 新增 src/plugin-data.js:read/write/patch/remove/size;桌面落 plugin-data/<id>.json(tmp+rename),
  同一插件读写串行排队,maxBytes 上限(默认 2MiB/最高 16MiB)超限抛错且不破坏已有数据
- storage-file 增加 pluginData 命名空间(read/write/remove/list)
- stripLegacy:宿主 init 前同步暂存 iwb_plugins[id].data,插件首次 read 时落盘并清暂存
- 备份携带 items.pluginData 并支持恢复;存储体检显示「插件数据 N 个 / X KB」
- 非桌面环境走 IWBStorageLocal 门面 → 内存兜底(仅测试)
- 新增 tests/plugin-data-test.js(串行/上限/迁移/备份)
This commit is contained in:
qiqi committed 2026-11-20 09:27:53 +08:00
1 parent 07d1715993
commit 7b1164febb
18 files changed
+424 -15

No files matched your search

+241
View File
@@ -0,0 +1,241 @@
/* plugin-data.js —— 插件数据层(v3.25.42 / M2)
*
* 目标:给插件一块**属于自己的、容量够用的**结构化存储。
* · 桌面:<资料目录>/plugin-data/<id>.json(原子写:tmp + rename)
* · 非桌面(jsdom / playwright 测试):localStorage,再兜底为内存
* · 同一插件的写入串行排队,避免「读-改-写」互相覆盖
* · 单文件上限 maxBytes(默认 2MiB,最多 16MiB),超限抛错、不静默截断
*
* 旧数据迁移:
* 老版本把所有插件数据塞在 localStorage['iwb_plugins'][id].data 里。
* stripLegacy() 在启动时把它们搬到 iwb_plugin_data_legacy 暂存(同步、不动磁盘),
* read() 首次命中时再落到 plugin-data/<id>.json 并清掉暂存 —— 避免启动期等 IO。
*/
;(function (global) {
'use strict'
const DEFAULT_MAX = 2 * 1024 * 1024
const HARD_MAX = 16 * 1024 * 1024
const LEGACY_KEY = 'iwb_plugin_data_legacy'
const mem = new Map() // 无 localStorage / 无 Tauri 时的最后兜底
const known = new Set() // 本次会话写过的 id(用于备份枚举;持久枚举靠文件 list / localStorage 前缀)
const queues = new Map()
function stateStore () {
const S = global.IWBStorageLocal
return (S && typeof S.getStore === 'function') ? S.getStore() : null
}
// 统一走 IWBStorageLocal 门面(src 内不得直调 localStorage;存储收敛守门会拦)
function lsGetRaw (key) {
try {
const st = stateStore()
if (!st) return null
const v = st.rawGet(key, null)
if (v == null) return null
if (typeof v !== 'string') return v
try { return JSON.parse(v) } catch (e) { return v }
} catch (e) { return null }
}
function lsSetRaw (key, value) {
try {
const st = stateStore()
if (!st) return false
return !!st.rawSet(key, typeof value === 'string' ? value : JSON.stringify(value))
} catch (e) { return false }
}
function lsDelRaw (key) {
try { const st = stateStore(); return !!(st && st.remove && st.remove(key)) } catch (e) { return false }
}
function fileBackend () {
const F = global.IWBStorageFile
if (!F || typeof F.enabled !== 'function' || !F.enabled()) return null // 非桌面(测试/浏览器)没有真实 FS
const d = F.pluginData
return (d && typeof d.read === 'function') ? d : null
}
function bytesOf (text) {
try { return new global.TextEncoder().encode(String(text)).length } catch (e) { return String(text).length }
}
function base64Ids (id) { return 'iwb_plugin_data_' + id }
async function readRaw (id, backend) {
known.add(id)
const b = backend || fileBackend()
if (b) {
try { const t = await b.read(id); if (t != null) return String(t) } catch (e) { /* 落到下一层 */ }
}
const v = lsGetRaw(base64Ids(id))
if (v != null) return typeof v === 'string' ? v : JSON.stringify(v)
return mem.has(id) ? mem.get(id) : null
}
async function writeRaw (id, text, backend) {
known.add(id)
const b = backend || fileBackend()
if (b) {
try { await b.write(id, text); return true } catch (e) { if (backend) throw e /* 显式注入的后端:失败要暴露;桌面 FS 失败则退回门面 */ }
}
if (lsSetRaw(base64Ids(id), text)) return true
mem.set(id, text)
return true
}
async function removeRaw (id, backend) {
const b = backend || fileBackend()
if (b) { try { await b.remove(id) } catch (e) { /* ignore */ } }
lsDelRaw(base64Ids(id))
mem.delete(id)
return true
}
// 同一插件的写/读串行化:patch 的「读-改-写」不会被并发写覆盖
function enqueue (id, task) {
const prev = queues.get(id) || Promise.resolve()
const next = prev.then(task, task)
queues.set(id, next.then(function () {}, function () {}))
return next
}
function create (id, options) {
const opt = options || {}
const backend = opt.backend || null // 测试注入
const maxBytes = Math.min(HARD_MAX, Math.max(1024, Number(opt.maxBytes) || DEFAULT_MAX))
const schemaVersion = Number(opt.schemaVersion) || 1
async function load () {
const raw = await readRaw(id, backend)
if (!raw) {
// 懒迁移:首次读取时把暂存的旧数据落盘
const legacy = lsGetRaw(LEGACY_KEY)
if (legacy && typeof legacy === 'object' && legacy[id] && typeof legacy[id] === 'object') {
const obj = legacy[id]
await writeRaw(id, JSON.stringify(obj), backend)
try {
const left = Object.assign({}, legacy)
delete left[id]
lsSetRaw(LEGACY_KEY, left)
} catch (e) { /* ignore */ }
return { obj: obj, raw: JSON.stringify(obj) }
}
return { obj: {}, raw: '' }
}
try { return { obj: JSON.parse(raw), raw: raw } } catch (e) { return { obj: {}, raw: raw } }
}
return {
id: id,
schemaVersion: schemaVersion,
read: function () { return enqueue(id, function () { return load().then(function (r) { return r.obj }) }) },
write: function (obj) {
return enqueue(id, function () {
const text = JSON.stringify(obj == null ? {} : obj)
const n = bytesOf(text)
if (n > maxBytes) {
const err = new Error('插件数据超出上限(' + Math.round(n / 1024) + 'KB > ' + Math.round(maxBytes / 1024) + 'KB)')
err.code = 'plugin-data-too-large'
throw err
}
return writeRaw(id, text, backend).then(function () { return true })
})
},
patch: function (fnOrObj) {
return enqueue(id, function () {
return load().then(function (r) {
const next = (typeof fnOrObj === 'function') ? fnOrObj(r.obj) : Object.assign({}, r.obj, fnOrObj)
const text = JSON.stringify(next == null ? {} : next)
const n = bytesOf(text)
if (n > maxBytes) {
const err = new Error('插件数据超出上限(' + Math.round(n / 1024) + 'KB > ' + Math.round(maxBytes / 1024) + 'KB)')
err.code = 'plugin-data-too-large'
throw err
}
return writeRaw(id, text, backend).then(function () { return next })
})
})
},
remove: function () { return enqueue(id, function () { return removeRaw(id, backend) }) },
size: function () {
return enqueue(id, function () { return readRaw(id, backend).then(function (t) { return t ? bytesOf(t) : 0 }) })
},
}
}
// 启动期:把 iwb_plugins[id].data 搬到暂存(同步,不等 IO)。返回搬走的条目数。
function stripLegacy () {
let state = null
try { state = lsGetRaw('iwb_plugins') } catch (e) { state = null }
if (!state || typeof state !== 'object') return 0
let legacy = null
try { legacy = lsGetRaw(LEGACY_KEY) } catch (e) { legacy = null }
if (!legacy || typeof legacy !== 'object') legacy = {}
let moved = 0
for (const id of Object.keys(state)) {
const rec = state[id]
if (!rec || typeof rec !== 'object' || !rec.data || typeof rec.data !== 'object') continue
if (Object.keys(rec.data).length) { legacy[id] = rec.data; moved++ }
delete rec.data
rec.migratedAt = Date.now()
}
if (moved) { try { lsSetRaw(LEGACY_KEY, legacy) } catch (e) { /* ignore */ } }
try { lsSetRaw('iwb_plugins', state) } catch (e) { /* ignore */ }
return moved
}
// 备份用:列出所有插件数据({id, data})
async function collectAll () {
const b = fileBackend()
const ids = new Set()
if (b && typeof b.list === 'function') {
try { for (const it of await b.list()) ids.add(String(it && it.id)) } catch (e) { /* ignore */ }
}
for (const id of mem.keys()) ids.add(id)
for (const id of known) ids.add(id)
try {
const st = stateStore()
if (st && typeof st.keys === 'function') {
for (const k of st.keys()) if (String(k).indexOf('iwb_plugin_data_') === 0) ids.add(String(k).slice('iwb_plugin_data_'.length))
}
} catch (e) { /* ignore */ }
const legacy = lsGetRaw(LEGACY_KEY)
if (legacy && typeof legacy === 'object') for (const id of Object.keys(legacy)) ids.add(id)
const out = []
for (const id of ids) {
if (!id) continue
const raw = await readRaw(id, null)
if (raw == null) continue
try { out.push({ id: id, data: JSON.parse(raw) }) } catch (e) { /* 坏文件跳过 */ }
}
return out
}
async function restoreAll (list) {
if (!Array.isArray(list)) return 0
let n = 0
for (const it of list) {
if (!it || !it.id) continue
try {
await writeRaw(String(it.id), JSON.stringify(it.data == null ? {} : it.data), null)
n++
} catch (e) { /* 单个失败不影响其它 */ }
}
return n
}
async function totalSize () {
const all = await collectAll()
let n = 0
for (const it of all) n += bytesOf(JSON.stringify(it.data))
return { bytes: n, count: all.length }
}
global.IWBPluginData = {
create: create,
stripLegacy: stripLegacy,
collectAll: collectAll,
restoreAll: restoreAll,
totalSize: totalSize,
_bytesOf: bytesOf,
}
})(typeof window !== 'undefined' ? window : globalThis)