Files
image-workbench-desktop/tests/plugin-data-test.js
T
qiqi 7b1164febb 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(串行/上限/迁移/备份)
2026-11-20 09:27:53 +08:00

95 lines
4.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict'
// 插件数据层行为测试(src/plugin-data.js,v3.25.42 / M2)
//
// 为什么要有:ctx.data 是"插件唯一能放心存业务数据"的地方,
// 一旦串行队列写错(并发 patch 互相覆盖)或上限判定失效(静默截断),用户数据会悄悄丢。
// 这里用注入 backend(内存 Map)跑纯逻辑,不依赖 Tauri / 浏览器。
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const vm = require('vm')
const root = path.resolve(__dirname, '..')
const lsMap = new Map()
// 存储走 IWBStorageLocal 门面(src 内禁止直调 localStorage)
const store = {
rawGet: (k, fb) => (lsMap.has(k) ? lsMap.get(k) : fb),
rawSet: (k, v) => { lsMap.set(k, String(v)); return true },
remove: (k) => { lsMap.delete(k); return true },
keys: () => Array.from(lsMap.keys()),
}
const sandbox = { TextEncoder, IWBStorageLocal: { getStore: () => store } }
vm.runInNewContext(fs.readFileSync(path.join(root, 'src', 'plugin-data.js'), 'utf8'), sandbox)
const PD = sandbox.IWBPluginData
assert.ok(PD, 'IWBPluginData 未导出')
// vm 里造出来的对象原型不同,deepStrictEqual 会误报 ⇒ 统一用 JSON 比较
const eq = (actual, expected, msg) => assert.strictEqual(JSON.stringify(actual), JSON.stringify(expected), msg)
function memBackend () {
const store = new Map()
return {
store,
read: async (id) => (store.has(id) ? store.get(id) : null),
write: async (id, text) => { store.set(id, text); return true },
remove: async (id) => { store.delete(id); return true },
list: async () => Array.from(store.keys()).map((id) => ({ id })),
}
}
;(async () => {
const be = memBackend()
const d = PD.create('test-a', { backend: be, maxBytes: 2048, schemaVersion: 3 }) // 下限 1KB,这里取 2KB 方便测上限
eq(await d.read(), {}, '空数据应返回 {}')
assert.strictEqual(d.schemaVersion, 3)
await d.write({ x: 1 })
eq(await d.read(), { x: 1 })
await d.patch({ y: 2 })
eq(await d.read(), { x: 1, y: 2 })
await d.patch((o) => Object.assign({}, o, { x: 9 }))
eq(await d.read(), { x: 9, y: 2 })
// 并发 20 次 patch:串行队列必须一个都不丢
await Promise.all(Array.from({ length: 20 }, (_, i) => d.patch((o) => Object.assign({}, o, { ['k' + i]: i }))))
const all = await d.read()
for (let i = 0; i < 20; i++) assert.strictEqual(all['k' + i], i, '并发 patch 丢了 k' + i)
assert.strictEqual(all.x, 9)
// 超上限:抛错、且不破坏上一次成功写入
let err = null
try { await d.write({ big: 'x'.repeat(4000) }) } catch (e) { err = e }
assert.ok(err && err.code === 'plugin-data-too-large', '超上限应抛 plugin-data-too-large')
eq(await d.read(), all, '写失败不得改动已有数据')
assert.ok((await d.size()) > 0, 'size 应大于 0')
await d.remove()
eq(await d.read(), {}, 'remove 后应回到空')
// stripLegacy:旧 iwb_plugins[id].data 搬到暂存,首次 read 再落盘
lsMap.set('iwb_plugins', JSON.stringify({ legacy1: { enabled: true, data: { a: 1, b: 'x' } }, plain: { enabled: false } }))
const moved = PD.stripLegacy()
assert.strictEqual(moved, 1, '应搬走 1 个插件的旧数据')
const stateAfter = JSON.parse(lsMap.get('iwb_plugins'))
assert.strictEqual(stateAfter.legacy1.data, undefined, '旧 data 必须从宿主状态移除(避免双份)')
assert.ok(stateAfter.legacy1.migratedAt > 0, '应记录 migratedAt')
assert.strictEqual(stateAfter.plain.enabled, false, '其它字段不得被改动')
const legacyBackend = memBackend()
const dLegacy = PD.create('legacy1', { backend: legacyBackend })
eq(await dLegacy.read(), { a: 1, b: 'x' }, '首次读取应拿到迁移过来的旧数据')
assert.ok(legacyBackend.store.has('legacy1'), '迁移应落到新后端')
const legacyLeft = JSON.parse(lsMap.get('iwb_plugin_data_legacy') || '{}')
assert.strictEqual(legacyLeft.legacy1, undefined, '迁移完成后应清掉暂存')
// 备份:collectAll / restoreAll(无注入 backend ⇒ 走内存兜底)
const dMem = PD.create('backup-a')
await dMem.write({ keep: [1, 2, 3] })
const collected = await PD.collectAll()
const hit = collected.find((x) => x.id === 'backup-a')
assert.ok(hit && Array.isArray(hit.data.keep), 'collectAll 应包含插件数据')
await PD.restoreAll([{ id: 'restored-x', data: { ok: true } }])
eq(await PD.create('restored-x').read(), { ok: true }, 'restoreAll 应写回数据')
console.log('plugin-data checks passed(串行队列 / 上限 / 迁移 / 备份)')
})().catch((e) => { console.error(e); process.exit(1) })